File: | clang/lib/Sema/SemaDecl.cpp |
Warning: | line 9928, column 19 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___ibm128: | ||||
145 | case tok::kw_wchar_t: | ||||
146 | case tok::kw_bool: | ||||
147 | case tok::kw___underlying_type: | ||||
148 | case tok::kw___auto_type: | ||||
149 | return true; | ||||
150 | |||||
151 | case tok::annot_typename: | ||||
152 | case tok::kw_char16_t: | ||||
153 | case tok::kw_char32_t: | ||||
154 | case tok::kw_typeof: | ||||
155 | case tok::annot_decltype: | ||||
156 | case tok::kw_decltype: | ||||
157 | return getLangOpts().CPlusPlus; | ||||
158 | |||||
159 | case tok::kw_char8_t: | ||||
160 | return getLangOpts().Char8; | ||||
161 | |||||
162 | default: | ||||
163 | break; | ||||
164 | } | ||||
165 | |||||
166 | return false; | ||||
167 | } | ||||
168 | |||||
169 | namespace { | ||||
170 | enum class UnqualifiedTypeNameLookupResult { | ||||
171 | NotFound, | ||||
172 | FoundNonType, | ||||
173 | FoundType | ||||
174 | }; | ||||
175 | } // end anonymous namespace | ||||
176 | |||||
177 | /// Tries to perform unqualified lookup of the type decls in bases for | ||||
178 | /// dependent class. | ||||
179 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a | ||||
180 | /// type decl, \a FoundType if only type decls are found. | ||||
181 | static UnqualifiedTypeNameLookupResult | ||||
182 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, | ||||
183 | SourceLocation NameLoc, | ||||
184 | const CXXRecordDecl *RD) { | ||||
185 | if (!RD->hasDefinition()) | ||||
186 | return UnqualifiedTypeNameLookupResult::NotFound; | ||||
187 | // Look for type decls in base classes. | ||||
188 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | ||||
189 | UnqualifiedTypeNameLookupResult::NotFound; | ||||
190 | for (const auto &Base : RD->bases()) { | ||||
191 | const CXXRecordDecl *BaseRD = nullptr; | ||||
192 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) | ||||
193 | BaseRD = BaseTT->getAsCXXRecordDecl(); | ||||
194 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { | ||||
195 | // Look for type decls in dependent base classes that have known primary | ||||
196 | // templates. | ||||
197 | if (!TST || !TST->isDependentType()) | ||||
198 | continue; | ||||
199 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); | ||||
200 | if (!TD) | ||||
201 | continue; | ||||
202 | if (auto *BasePrimaryTemplate = | ||||
203 | dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { | ||||
204 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) | ||||
205 | BaseRD = BasePrimaryTemplate; | ||||
206 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { | ||||
207 | if (const ClassTemplatePartialSpecializationDecl *PS = | ||||
208 | CTD->findPartialSpecialization(Base.getType())) | ||||
209 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) | ||||
210 | BaseRD = PS; | ||||
211 | } | ||||
212 | } | ||||
213 | } | ||||
214 | if (BaseRD) { | ||||
215 | for (NamedDecl *ND : BaseRD->lookup(&II)) { | ||||
216 | if (!isa<TypeDecl>(ND)) | ||||
217 | return UnqualifiedTypeNameLookupResult::FoundNonType; | ||||
218 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | ||||
219 | } | ||||
220 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { | ||||
221 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { | ||||
222 | case UnqualifiedTypeNameLookupResult::FoundNonType: | ||||
223 | return UnqualifiedTypeNameLookupResult::FoundNonType; | ||||
224 | case UnqualifiedTypeNameLookupResult::FoundType: | ||||
225 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | ||||
226 | break; | ||||
227 | case UnqualifiedTypeNameLookupResult::NotFound: | ||||
228 | break; | ||||
229 | } | ||||
230 | } | ||||
231 | } | ||||
232 | } | ||||
233 | |||||
234 | return FoundTypeDecl; | ||||
235 | } | ||||
236 | |||||
237 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, | ||||
238 | const IdentifierInfo &II, | ||||
239 | SourceLocation NameLoc) { | ||||
240 | // Lookup in the parent class template context, if any. | ||||
241 | const CXXRecordDecl *RD = nullptr; | ||||
242 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | ||||
243 | UnqualifiedTypeNameLookupResult::NotFound; | ||||
244 | for (DeclContext *DC = S.CurContext; | ||||
245 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; | ||||
246 | DC = DC->getParent()) { | ||||
247 | // Look for type decls in dependent base classes that have known primary | ||||
248 | // templates. | ||||
249 | RD = dyn_cast<CXXRecordDecl>(DC); | ||||
250 | if (RD && RD->getDescribedClassTemplate()) | ||||
251 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); | ||||
252 | } | ||||
253 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) | ||||
254 | return nullptr; | ||||
255 | |||||
256 | // We found some types in dependent base classes. Recover as if the user | ||||
257 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the | ||||
258 | // lookup during template instantiation. | ||||
259 | S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; | ||||
260 | |||||
261 | ASTContext &Context = S.Context; | ||||
262 | auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, | ||||
263 | cast<Type>(Context.getRecordType(RD))); | ||||
264 | QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); | ||||
265 | |||||
266 | CXXScopeSpec SS; | ||||
267 | SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||
268 | |||||
269 | TypeLocBuilder Builder; | ||||
270 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | ||||
271 | DepTL.setNameLoc(NameLoc); | ||||
272 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
273 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
274 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||
275 | } | ||||
276 | |||||
277 | /// If the identifier refers to a type name within this scope, | ||||
278 | /// return the declaration of that type. | ||||
279 | /// | ||||
280 | /// This routine performs ordinary name lookup of the identifier II | ||||
281 | /// within the given scope, with optional C++ scope specifier SS, to | ||||
282 | /// determine whether the name refers to a type. If so, returns an | ||||
283 | /// opaque pointer (actually a QualType) corresponding to that | ||||
284 | /// type. Otherwise, returns NULL. | ||||
285 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, | ||||
286 | Scope *S, CXXScopeSpec *SS, | ||||
287 | bool isClassName, bool HasTrailingDot, | ||||
288 | ParsedType ObjectTypePtr, | ||||
289 | bool IsCtorOrDtorName, | ||||
290 | bool WantNontrivialTypeSourceInfo, | ||||
291 | bool IsClassTemplateDeductionContext, | ||||
292 | IdentifierInfo **CorrectedII) { | ||||
293 | // FIXME: Consider allowing this outside C++1z mode as an extension. | ||||
294 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && | ||||
295 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && | ||||
296 | !isClassName && !HasTrailingDot; | ||||
297 | |||||
298 | // Determine where we will perform name lookup. | ||||
299 | DeclContext *LookupCtx = nullptr; | ||||
300 | if (ObjectTypePtr) { | ||||
301 | QualType ObjectType = ObjectTypePtr.get(); | ||||
302 | if (ObjectType->isRecordType()) | ||||
303 | LookupCtx = computeDeclContext(ObjectType); | ||||
304 | } else if (SS && SS->isNotEmpty()) { | ||||
305 | LookupCtx = computeDeclContext(*SS, false); | ||||
306 | |||||
307 | if (!LookupCtx) { | ||||
308 | if (isDependentScopeSpecifier(*SS)) { | ||||
309 | // C++ [temp.res]p3: | ||||
310 | // A qualified-id that refers to a type and in which the | ||||
311 | // nested-name-specifier depends on a template-parameter (14.6.2) | ||||
312 | // shall be prefixed by the keyword typename to indicate that the | ||||
313 | // qualified-id denotes a type, forming an | ||||
314 | // elaborated-type-specifier (7.1.5.3). | ||||
315 | // | ||||
316 | // We therefore do not perform any name lookup if the result would | ||||
317 | // refer to a member of an unknown specialization. | ||||
318 | if (!isClassName && !IsCtorOrDtorName) | ||||
319 | return nullptr; | ||||
320 | |||||
321 | // We know from the grammar that this name refers to a type, | ||||
322 | // so build a dependent node to describe the type. | ||||
323 | if (WantNontrivialTypeSourceInfo) | ||||
324 | return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); | ||||
325 | |||||
326 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); | ||||
327 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, | ||||
328 | II, NameLoc); | ||||
329 | return ParsedType::make(T); | ||||
330 | } | ||||
331 | |||||
332 | return nullptr; | ||||
333 | } | ||||
334 | |||||
335 | if (!LookupCtx->isDependentContext() && | ||||
336 | RequireCompleteDeclContext(*SS, LookupCtx)) | ||||
337 | return nullptr; | ||||
338 | } | ||||
339 | |||||
340 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of | ||||
341 | // lookup for class-names. | ||||
342 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : | ||||
343 | LookupOrdinaryName; | ||||
344 | LookupResult Result(*this, &II, NameLoc, Kind); | ||||
345 | if (LookupCtx) { | ||||
346 | // Perform "qualified" name lookup into the declaration context we | ||||
347 | // computed, which is either the type of the base of a member access | ||||
348 | // expression or the declaration context associated with a prior | ||||
349 | // nested-name-specifier. | ||||
350 | LookupQualifiedName(Result, LookupCtx); | ||||
351 | |||||
352 | if (ObjectTypePtr && Result.empty()) { | ||||
353 | // C++ [basic.lookup.classref]p3: | ||||
354 | // If the unqualified-id is ~type-name, the type-name is looked up | ||||
355 | // in the context of the entire postfix-expression. If the type T of | ||||
356 | // the object expression is of a class type C, the type-name is also | ||||
357 | // looked up in the scope of class C. At least one of the lookups shall | ||||
358 | // find a name that refers to (possibly cv-qualified) T. | ||||
359 | LookupName(Result, S); | ||||
360 | } | ||||
361 | } else { | ||||
362 | // Perform unqualified name lookup. | ||||
363 | LookupName(Result, S); | ||||
364 | |||||
365 | // For unqualified lookup in a class template in MSVC mode, look into | ||||
366 | // dependent base classes where the primary class template is known. | ||||
367 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { | ||||
368 | if (ParsedType TypeInBase = | ||||
369 | recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) | ||||
370 | return TypeInBase; | ||||
371 | } | ||||
372 | } | ||||
373 | |||||
374 | NamedDecl *IIDecl = nullptr; | ||||
375 | UsingShadowDecl *FoundUsingShadow = nullptr; | ||||
376 | switch (Result.getResultKind()) { | ||||
377 | case LookupResult::NotFound: | ||||
378 | case LookupResult::NotFoundInCurrentInstantiation: | ||||
379 | if (CorrectedII) { | ||||
380 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, | ||||
381 | AllowDeducedTemplate); | ||||
382 | TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, | ||||
383 | S, SS, CCC, CTK_ErrorRecovery); | ||||
384 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); | ||||
385 | TemplateTy Template; | ||||
386 | bool MemberOfUnknownSpecialization; | ||||
387 | UnqualifiedId TemplateName; | ||||
388 | TemplateName.setIdentifier(NewII, NameLoc); | ||||
389 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); | ||||
390 | CXXScopeSpec NewSS, *NewSSPtr = SS; | ||||
391 | if (SS && NNS) { | ||||
392 | NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||
393 | NewSSPtr = &NewSS; | ||||
394 | } | ||||
395 | if (Correction && (NNS || NewII != &II) && | ||||
396 | // Ignore a correction to a template type as the to-be-corrected | ||||
397 | // identifier is not a template (typo correction for template names | ||||
398 | // is handled elsewhere). | ||||
399 | !(getLangOpts().CPlusPlus && NewSSPtr && | ||||
400 | isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, | ||||
401 | Template, MemberOfUnknownSpecialization))) { | ||||
402 | ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, | ||||
403 | isClassName, HasTrailingDot, ObjectTypePtr, | ||||
404 | IsCtorOrDtorName, | ||||
405 | WantNontrivialTypeSourceInfo, | ||||
406 | IsClassTemplateDeductionContext); | ||||
407 | if (Ty) { | ||||
408 | diagnoseTypo(Correction, | ||||
409 | PDiag(diag::err_unknown_type_or_class_name_suggest) | ||||
410 | << Result.getLookupName() << isClassName); | ||||
411 | if (SS && NNS) | ||||
412 | SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||
413 | *CorrectedII = NewII; | ||||
414 | return Ty; | ||||
415 | } | ||||
416 | } | ||||
417 | } | ||||
418 | // If typo correction failed or was not performed, fall through | ||||
419 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
420 | case LookupResult::FoundOverloaded: | ||||
421 | case LookupResult::FoundUnresolvedValue: | ||||
422 | Result.suppressDiagnostics(); | ||||
423 | return nullptr; | ||||
424 | |||||
425 | case LookupResult::Ambiguous: | ||||
426 | // Recover from type-hiding ambiguities by hiding the type. We'll | ||||
427 | // do the lookup again when looking for an object, and we can | ||||
428 | // diagnose the error then. If we don't do this, then the error | ||||
429 | // about hiding the type will be immediately followed by an error | ||||
430 | // that only makes sense if the identifier was treated like a type. | ||||
431 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { | ||||
432 | Result.suppressDiagnostics(); | ||||
433 | return nullptr; | ||||
434 | } | ||||
435 | |||||
436 | // Look to see if we have a type anywhere in the list of results. | ||||
437 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); | ||||
438 | Res != ResEnd; ++Res) { | ||||
439 | NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); | ||||
440 | if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( | ||||
441 | RealRes) || | ||||
442 | (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { | ||||
443 | if (!IIDecl || | ||||
444 | // Make the selection of the recovery decl deterministic. | ||||
445 | RealRes->getLocation() < IIDecl->getLocation()) { | ||||
446 | IIDecl = RealRes; | ||||
447 | FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res); | ||||
448 | } | ||||
449 | } | ||||
450 | } | ||||
451 | |||||
452 | if (!IIDecl) { | ||||
453 | // None of the entities we found is a type, so there is no way | ||||
454 | // to even assume that the result is a type. In this case, don't | ||||
455 | // complain about the ambiguity. The parser will either try to | ||||
456 | // perform this lookup again (e.g., as an object name), which | ||||
457 | // will produce the ambiguity, or will complain that it expected | ||||
458 | // a type name. | ||||
459 | Result.suppressDiagnostics(); | ||||
460 | return nullptr; | ||||
461 | } | ||||
462 | |||||
463 | // We found a type within the ambiguous lookup; diagnose the | ||||
464 | // ambiguity and then return that type. This might be the right | ||||
465 | // answer, or it might not be, but it suppresses any attempt to | ||||
466 | // perform the name lookup again. | ||||
467 | break; | ||||
468 | |||||
469 | case LookupResult::Found: | ||||
470 | IIDecl = Result.getFoundDecl(); | ||||
471 | FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin()); | ||||
472 | break; | ||||
473 | } | ||||
474 | |||||
475 | assert(IIDecl && "Didn't find decl")(static_cast <bool> (IIDecl && "Didn't find decl" ) ? void (0) : __assert_fail ("IIDecl && \"Didn't find decl\"" , "clang/lib/Sema/SemaDecl.cpp", 475, __extension__ __PRETTY_FUNCTION__ )); | ||||
476 | |||||
477 | QualType T; | ||||
478 | if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { | ||||
479 | // C++ [class.qual]p2: A lookup that would find the injected-class-name | ||||
480 | // instead names the constructors of the class, except when naming a class. | ||||
481 | // This is ill-formed when we're not actually forming a ctor or dtor name. | ||||
482 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); | ||||
483 | auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); | ||||
484 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && | ||||
485 | FoundRD->isInjectedClassName() && | ||||
486 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) | ||||
487 | Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) | ||||
488 | << &II << /*Type*/1; | ||||
489 | |||||
490 | DiagnoseUseOfDecl(IIDecl, NameLoc); | ||||
491 | |||||
492 | T = Context.getTypeDeclType(TD); | ||||
493 | MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); | ||||
494 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { | ||||
495 | (void)DiagnoseUseOfDecl(IDecl, NameLoc); | ||||
496 | if (!HasTrailingDot) | ||||
497 | T = Context.getObjCInterfaceType(IDecl); | ||||
498 | FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. | ||||
499 | } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { | ||||
500 | (void)DiagnoseUseOfDecl(UD, NameLoc); | ||||
501 | // Recover with 'int' | ||||
502 | T = Context.IntTy; | ||||
503 | FoundUsingShadow = nullptr; | ||||
504 | } else if (AllowDeducedTemplate) { | ||||
505 | if (auto *TD = getAsTypeTemplateDecl(IIDecl)) { | ||||
506 | // FIXME: TemplateName should include FoundUsingShadow sugar. | ||||
507 | T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), | ||||
508 | QualType(), false); | ||||
509 | // Don't wrap in a further UsingType. | ||||
510 | FoundUsingShadow = nullptr; | ||||
511 | } | ||||
512 | } | ||||
513 | |||||
514 | if (T.isNull()) { | ||||
515 | // If it's not plausibly a type, suppress diagnostics. | ||||
516 | Result.suppressDiagnostics(); | ||||
517 | return nullptr; | ||||
518 | } | ||||
519 | |||||
520 | if (FoundUsingShadow) | ||||
521 | T = Context.getUsingType(FoundUsingShadow, T); | ||||
522 | |||||
523 | // NOTE: avoid constructing an ElaboratedType(Loc) if this is a | ||||
524 | // constructor or destructor name (in such a case, the scope specifier | ||||
525 | // will be attached to the enclosing Expr or Decl node). | ||||
526 | if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && | ||||
527 | !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { | ||||
528 | if (WantNontrivialTypeSourceInfo) { | ||||
529 | // Construct a type with type-source information. | ||||
530 | TypeLocBuilder Builder; | ||||
531 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | ||||
532 | |||||
533 | T = getElaboratedType(ETK_None, *SS, T); | ||||
534 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | ||||
535 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
536 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); | ||||
537 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||
538 | } else { | ||||
539 | T = getElaboratedType(ETK_None, *SS, T); | ||||
540 | } | ||||
541 | } | ||||
542 | |||||
543 | return ParsedType::make(T); | ||||
544 | } | ||||
545 | |||||
546 | // Builds a fake NNS for the given decl context. | ||||
547 | static NestedNameSpecifier * | ||||
548 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { | ||||
549 | for (;; DC = DC->getLookupParent()) { | ||||
550 | DC = DC->getPrimaryContext(); | ||||
551 | auto *ND = dyn_cast<NamespaceDecl>(DC); | ||||
552 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) | ||||
553 | return NestedNameSpecifier::Create(Context, nullptr, ND); | ||||
554 | else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||
555 | return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | ||||
556 | RD->getTypeForDecl()); | ||||
557 | else if (isa<TranslationUnitDecl>(DC)) | ||||
558 | return NestedNameSpecifier::GlobalSpecifier(Context); | ||||
559 | } | ||||
560 | llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?" , "clang/lib/Sema/SemaDecl.cpp", 560); | ||||
561 | } | ||||
562 | |||||
563 | /// Find the parent class with dependent bases of the innermost enclosing method | ||||
564 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end | ||||
565 | /// up allowing unqualified dependent type names at class-level, which MSVC | ||||
566 | /// correctly rejects. | ||||
567 | static const CXXRecordDecl * | ||||
568 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { | ||||
569 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { | ||||
570 | DC = DC->getPrimaryContext(); | ||||
571 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||
572 | if (MD->getParent()->hasAnyDependentBases()) | ||||
573 | return MD->getParent(); | ||||
574 | } | ||||
575 | return nullptr; | ||||
576 | } | ||||
577 | |||||
578 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, | ||||
579 | SourceLocation NameLoc, | ||||
580 | bool IsTemplateTypeArg) { | ||||
581 | assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")(static_cast <bool> (getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode") ? void (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\"" , "clang/lib/Sema/SemaDecl.cpp", 581, __extension__ __PRETTY_FUNCTION__ )); | ||||
582 | |||||
583 | NestedNameSpecifier *NNS = nullptr; | ||||
584 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { | ||||
585 | // If we weren't able to parse a default template argument, delay lookup | ||||
586 | // until instantiation time by making a non-dependent DependentTypeName. We | ||||
587 | // pretend we saw a NestedNameSpecifier referring to the current scope, and | ||||
588 | // lookup is retried. | ||||
589 | // FIXME: This hurts our diagnostic quality, since we get errors like "no | ||||
590 | // type named 'Foo' in 'current_namespace'" when the user didn't write any | ||||
591 | // name specifiers. | ||||
592 | NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); | ||||
593 | Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; | ||||
594 | } else if (const CXXRecordDecl *RD = | ||||
595 | findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { | ||||
596 | // Build a DependentNameType that will perform lookup into RD at | ||||
597 | // instantiation time. | ||||
598 | NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | ||||
599 | RD->getTypeForDecl()); | ||||
600 | |||||
601 | // Diagnose that this identifier was undeclared, and retry the lookup during | ||||
602 | // template instantiation. | ||||
603 | Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II | ||||
604 | << RD; | ||||
605 | } else { | ||||
606 | // This is not a situation that we should recover from. | ||||
607 | return ParsedType(); | ||||
608 | } | ||||
609 | |||||
610 | QualType T = Context.getDependentNameType(ETK_None, NNS, &II); | ||||
611 | |||||
612 | // Build type location information. We synthesized the qualifier, so we have | ||||
613 | // to build a fake NestedNameSpecifierLoc. | ||||
614 | NestedNameSpecifierLocBuilder NNSLocBuilder; | ||||
615 | NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||
616 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); | ||||
617 | |||||
618 | TypeLocBuilder Builder; | ||||
619 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | ||||
620 | DepTL.setNameLoc(NameLoc); | ||||
621 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
622 | DepTL.setQualifierLoc(QualifierLoc); | ||||
623 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||
624 | } | ||||
625 | |||||
626 | /// isTagName() - This method is called *for error recovery purposes only* | ||||
627 | /// to determine if the specified name is a valid tag name ("struct foo"). If | ||||
628 | /// so, this returns the TST for the tag corresponding to it (TST_enum, | ||||
629 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose | ||||
630 | /// cases in C where the user forgot to specify the tag. | ||||
631 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { | ||||
632 | // Do a tag name lookup in this scope. | ||||
633 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); | ||||
634 | LookupName(R, S, false); | ||||
635 | R.suppressDiagnostics(); | ||||
636 | if (R.getResultKind() == LookupResult::Found) | ||||
637 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { | ||||
638 | switch (TD->getTagKind()) { | ||||
639 | case TTK_Struct: return DeclSpec::TST_struct; | ||||
640 | case TTK_Interface: return DeclSpec::TST_interface; | ||||
641 | case TTK_Union: return DeclSpec::TST_union; | ||||
642 | case TTK_Class: return DeclSpec::TST_class; | ||||
643 | case TTK_Enum: return DeclSpec::TST_enum; | ||||
644 | } | ||||
645 | } | ||||
646 | |||||
647 | return DeclSpec::TST_unspecified; | ||||
648 | } | ||||
649 | |||||
650 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, | ||||
651 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes | ||||
652 | /// then downgrade the missing typename error to a warning. | ||||
653 | /// This is needed for MSVC compatibility; Example: | ||||
654 | /// @code | ||||
655 | /// template<class T> class A { | ||||
656 | /// public: | ||||
657 | /// typedef int TYPE; | ||||
658 | /// }; | ||||
659 | /// template<class T> class B : public A<T> { | ||||
660 | /// public: | ||||
661 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. | ||||
662 | /// }; | ||||
663 | /// @endcode | ||||
664 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { | ||||
665 | if (CurContext->isRecord()) { | ||||
666 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) | ||||
667 | return true; | ||||
668 | |||||
669 | const Type *Ty = SS->getScopeRep()->getAsType(); | ||||
670 | |||||
671 | CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); | ||||
672 | for (const auto &Base : RD->bases()) | ||||
673 | if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) | ||||
674 | return true; | ||||
675 | return S->isFunctionPrototypeScope(); | ||||
676 | } | ||||
677 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); | ||||
678 | } | ||||
679 | |||||
680 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, | ||||
681 | SourceLocation IILoc, | ||||
682 | Scope *S, | ||||
683 | CXXScopeSpec *SS, | ||||
684 | ParsedType &SuggestedType, | ||||
685 | bool IsTemplateName) { | ||||
686 | // Don't report typename errors for editor placeholders. | ||||
687 | if (II->isEditorPlaceholder()) | ||||
688 | return; | ||||
689 | // We don't have anything to suggest (yet). | ||||
690 | SuggestedType = nullptr; | ||||
691 | |||||
692 | // There may have been a typo in the name of the type. Look up typo | ||||
693 | // results, in case we have something that we can suggest. | ||||
694 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, | ||||
695 | /*AllowTemplates=*/IsTemplateName, | ||||
696 | /*AllowNonTemplates=*/!IsTemplateName); | ||||
697 | if (TypoCorrection Corrected = | ||||
698 | CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, | ||||
699 | CCC, CTK_ErrorRecovery)) { | ||||
700 | // FIXME: Support error recovery for the template-name case. | ||||
701 | bool CanRecover = !IsTemplateName; | ||||
702 | if (Corrected.isKeyword()) { | ||||
703 | // We corrected to a keyword. | ||||
704 | diagnoseTypo(Corrected, | ||||
705 | PDiag(IsTemplateName ? diag::err_no_template_suggest | ||||
706 | : diag::err_unknown_typename_suggest) | ||||
707 | << II); | ||||
708 | II = Corrected.getCorrectionAsIdentifierInfo(); | ||||
709 | } else { | ||||
710 | // We found a similarly-named type or interface; suggest that. | ||||
711 | if (!SS || !SS->isSet()) { | ||||
712 | diagnoseTypo(Corrected, | ||||
713 | PDiag(IsTemplateName ? diag::err_no_template_suggest | ||||
714 | : diag::err_unknown_typename_suggest) | ||||
715 | << II, CanRecover); | ||||
716 | } else if (DeclContext *DC = computeDeclContext(*SS, false)) { | ||||
717 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||
718 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||
719 | II->getName().equals(CorrectedStr); | ||||
720 | diagnoseTypo(Corrected, | ||||
721 | PDiag(IsTemplateName | ||||
722 | ? diag::err_no_member_template_suggest | ||||
723 | : diag::err_unknown_nested_typename_suggest) | ||||
724 | << II << DC << DroppedSpecifier << SS->getRange(), | ||||
725 | CanRecover); | ||||
726 | } else { | ||||
727 | llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here" , "clang/lib/Sema/SemaDecl.cpp", 727); | ||||
728 | } | ||||
729 | |||||
730 | if (!CanRecover) | ||||
731 | return; | ||||
732 | |||||
733 | CXXScopeSpec tmpSS; | ||||
734 | if (Corrected.getCorrectionSpecifier()) | ||||
735 | tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | ||||
736 | SourceRange(IILoc)); | ||||
737 | // FIXME: Support class template argument deduction here. | ||||
738 | SuggestedType = | ||||
739 | getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, | ||||
740 | tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, | ||||
741 | /*IsCtorOrDtorName=*/false, | ||||
742 | /*WantNontrivialTypeSourceInfo=*/true); | ||||
743 | } | ||||
744 | return; | ||||
745 | } | ||||
746 | |||||
747 | if (getLangOpts().CPlusPlus && !IsTemplateName) { | ||||
748 | // See if II is a class template that the user forgot to pass arguments to. | ||||
749 | UnqualifiedId Name; | ||||
750 | Name.setIdentifier(II, IILoc); | ||||
751 | CXXScopeSpec EmptySS; | ||||
752 | TemplateTy TemplateResult; | ||||
753 | bool MemberOfUnknownSpecialization; | ||||
754 | if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, | ||||
755 | Name, nullptr, true, TemplateResult, | ||||
756 | MemberOfUnknownSpecialization) == TNK_Type_template) { | ||||
757 | diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); | ||||
758 | return; | ||||
759 | } | ||||
760 | } | ||||
761 | |||||
762 | // FIXME: Should we move the logic that tries to recover from a missing tag | ||||
763 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? | ||||
764 | |||||
765 | if (!SS || (!SS->isSet() && !SS->isInvalid())) | ||||
766 | Diag(IILoc, IsTemplateName ? diag::err_no_template | ||||
767 | : diag::err_unknown_typename) | ||||
768 | << II; | ||||
769 | else if (DeclContext *DC = computeDeclContext(*SS, false)) | ||||
770 | Diag(IILoc, IsTemplateName ? diag::err_no_member_template | ||||
771 | : diag::err_typename_nested_not_found) | ||||
772 | << II << DC << SS->getRange(); | ||||
773 | else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { | ||||
774 | SuggestedType = | ||||
775 | ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); | ||||
776 | } else if (isDependentScopeSpecifier(*SS)) { | ||||
777 | unsigned DiagID = diag::err_typename_missing; | ||||
778 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) | ||||
779 | DiagID = diag::ext_typename_missing; | ||||
780 | |||||
781 | Diag(SS->getRange().getBegin(), DiagID) | ||||
782 | << SS->getScopeRep() << II->getName() | ||||
783 | << SourceRange(SS->getRange().getBegin(), IILoc) | ||||
784 | << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); | ||||
785 | SuggestedType = ActOnTypenameType(S, SourceLocation(), | ||||
786 | *SS, *II, IILoc).get(); | ||||
787 | } else { | ||||
788 | assert(SS && SS->isInvalid() &&(static_cast <bool> (SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed") ? void (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "clang/lib/Sema/SemaDecl.cpp", 789, __extension__ __PRETTY_FUNCTION__ )) | ||||
789 | "Invalid scope specifier has already been diagnosed")(static_cast <bool> (SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed") ? void (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "clang/lib/Sema/SemaDecl.cpp", 789, __extension__ __PRETTY_FUNCTION__ )); | ||||
790 | } | ||||
791 | } | ||||
792 | |||||
793 | /// Determine whether the given result set contains either a type name | ||||
794 | /// or | ||||
795 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { | ||||
796 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && | ||||
797 | NextToken.is(tok::less); | ||||
798 | |||||
799 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { | ||||
800 | if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) | ||||
801 | return true; | ||||
802 | |||||
803 | if (CheckTemplate && isa<TemplateDecl>(*I)) | ||||
804 | return true; | ||||
805 | } | ||||
806 | |||||
807 | return false; | ||||
808 | } | ||||
809 | |||||
810 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, | ||||
811 | Scope *S, CXXScopeSpec &SS, | ||||
812 | IdentifierInfo *&Name, | ||||
813 | SourceLocation NameLoc) { | ||||
814 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); | ||||
815 | SemaRef.LookupParsedName(R, S, &SS); | ||||
816 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { | ||||
817 | StringRef FixItTagName; | ||||
818 | switch (Tag->getTagKind()) { | ||||
819 | case TTK_Class: | ||||
820 | FixItTagName = "class "; | ||||
821 | break; | ||||
822 | |||||
823 | case TTK_Enum: | ||||
824 | FixItTagName = "enum "; | ||||
825 | break; | ||||
826 | |||||
827 | case TTK_Struct: | ||||
828 | FixItTagName = "struct "; | ||||
829 | break; | ||||
830 | |||||
831 | case TTK_Interface: | ||||
832 | FixItTagName = "__interface "; | ||||
833 | break; | ||||
834 | |||||
835 | case TTK_Union: | ||||
836 | FixItTagName = "union "; | ||||
837 | break; | ||||
838 | } | ||||
839 | |||||
840 | StringRef TagName = FixItTagName.drop_back(); | ||||
841 | SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) | ||||
842 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus | ||||
843 | << FixItHint::CreateInsertion(NameLoc, FixItTagName); | ||||
844 | |||||
845 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); | ||||
846 | I != IEnd; ++I) | ||||
847 | SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) | ||||
848 | << Name << TagName; | ||||
849 | |||||
850 | // Replace lookup results with just the tag decl. | ||||
851 | Result.clear(Sema::LookupTagName); | ||||
852 | SemaRef.LookupParsedName(Result, S, &SS); | ||||
853 | return true; | ||||
854 | } | ||||
855 | |||||
856 | return false; | ||||
857 | } | ||||
858 | |||||
859 | Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, | ||||
860 | IdentifierInfo *&Name, | ||||
861 | SourceLocation NameLoc, | ||||
862 | const Token &NextToken, | ||||
863 | CorrectionCandidateCallback *CCC) { | ||||
864 | DeclarationNameInfo NameInfo(Name, NameLoc); | ||||
865 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
866 | |||||
867 | assert(NextToken.isNot(tok::coloncolon) &&(static_cast <bool> (NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName") ? void (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\"" , "clang/lib/Sema/SemaDecl.cpp", 868, __extension__ __PRETTY_FUNCTION__ )) | ||||
868 | "parse nested name specifiers before calling ClassifyName")(static_cast <bool> (NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName") ? void (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\"" , "clang/lib/Sema/SemaDecl.cpp", 868, __extension__ __PRETTY_FUNCTION__ )); | ||||
869 | if (getLangOpts().CPlusPlus && SS.isSet() && | ||||
870 | isCurrentClassName(*Name, S, &SS)) { | ||||
871 | // Per [class.qual]p2, this names the constructors of SS, not the | ||||
872 | // injected-class-name. We don't have a classification for that. | ||||
873 | // There's not much point caching this result, since the parser | ||||
874 | // will reject it later. | ||||
875 | return NameClassification::Unknown(); | ||||
876 | } | ||||
877 | |||||
878 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | ||||
879 | LookupParsedName(Result, S, &SS, !CurMethod); | ||||
880 | |||||
881 | if (SS.isInvalid()) | ||||
882 | return NameClassification::Error(); | ||||
883 | |||||
884 | // For unqualified lookup in a class template in MSVC mode, look into | ||||
885 | // dependent base classes where the primary class template is known. | ||||
886 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||
887 | if (ParsedType TypeInBase = | ||||
888 | recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) | ||||
889 | return TypeInBase; | ||||
890 | } | ||||
891 | |||||
892 | // Perform lookup for Objective-C instance variables (including automatically | ||||
893 | // synthesized instance variables), if we're in an Objective-C method. | ||||
894 | // FIXME: This lookup really, really needs to be folded in to the normal | ||||
895 | // unqualified lookup mechanism. | ||||
896 | if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { | ||||
897 | DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); | ||||
898 | if (Ivar.isInvalid()) | ||||
899 | return NameClassification::Error(); | ||||
900 | if (Ivar.isUsable()) | ||||
901 | return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); | ||||
902 | |||||
903 | // We defer builtin creation until after ivar lookup inside ObjC methods. | ||||
904 | if (Result.empty()) | ||||
905 | LookupBuiltin(Result); | ||||
906 | } | ||||
907 | |||||
908 | bool SecondTry = false; | ||||
909 | bool IsFilteredTemplateName = false; | ||||
910 | |||||
911 | Corrected: | ||||
912 | switch (Result.getResultKind()) { | ||||
913 | case LookupResult::NotFound: | ||||
914 | // If an unqualified-id is followed by a '(', then we have a function | ||||
915 | // call. | ||||
916 | if (SS.isEmpty() && NextToken.is(tok::l_paren)) { | ||||
917 | // In C++, this is an ADL-only call. | ||||
918 | // FIXME: Reference? | ||||
919 | if (getLangOpts().CPlusPlus) | ||||
920 | return NameClassification::UndeclaredNonType(); | ||||
921 | |||||
922 | // C90 6.3.2.2: | ||||
923 | // If the expression that precedes the parenthesized argument list in a | ||||
924 | // function call consists solely of an identifier, and if no | ||||
925 | // declaration is visible for this identifier, the identifier is | ||||
926 | // implicitly declared exactly as if, in the innermost block containing | ||||
927 | // the function call, the declaration | ||||
928 | // | ||||
929 | // extern int identifier (); | ||||
930 | // | ||||
931 | // appeared. | ||||
932 | // | ||||
933 | // We also allow this in C99 as an extension. | ||||
934 | if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) | ||||
935 | return NameClassification::NonType(D); | ||||
936 | } | ||||
937 | |||||
938 | if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { | ||||
939 | // In C++20 onwards, this could be an ADL-only call to a function | ||||
940 | // template, and we're required to assume that this is a template name. | ||||
941 | // | ||||
942 | // FIXME: Find a way to still do typo correction in this case. | ||||
943 | TemplateName Template = | ||||
944 | Context.getAssumedTemplateName(NameInfo.getName()); | ||||
945 | return NameClassification::UndeclaredTemplate(Template); | ||||
946 | } | ||||
947 | |||||
948 | // In C, we first see whether there is a tag type by the same name, in | ||||
949 | // which case it's likely that the user just forgot to write "enum", | ||||
950 | // "struct", or "union". | ||||
951 | if (!getLangOpts().CPlusPlus && !SecondTry && | ||||
952 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | ||||
953 | break; | ||||
954 | } | ||||
955 | |||||
956 | // Perform typo correction to determine if there is another name that is | ||||
957 | // close to this name. | ||||
958 | if (!SecondTry && CCC) { | ||||
959 | SecondTry = true; | ||||
960 | if (TypoCorrection Corrected = | ||||
961 | CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, | ||||
962 | &SS, *CCC, CTK_ErrorRecovery)) { | ||||
963 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; | ||||
964 | unsigned QualifiedDiag = diag::err_no_member_suggest; | ||||
965 | |||||
966 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); | ||||
967 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); | ||||
968 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||
969 | UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { | ||||
970 | UnqualifiedDiag = diag::err_no_template_suggest; | ||||
971 | QualifiedDiag = diag::err_no_member_template_suggest; | ||||
972 | } else if (UnderlyingFirstDecl && | ||||
973 | (isa<TypeDecl>(UnderlyingFirstDecl) || | ||||
974 | isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || | ||||
975 | isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { | ||||
976 | UnqualifiedDiag = diag::err_unknown_typename_suggest; | ||||
977 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; | ||||
978 | } | ||||
979 | |||||
980 | if (SS.isEmpty()) { | ||||
981 | diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); | ||||
982 | } else {// FIXME: is this even reachable? Test it. | ||||
983 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||
984 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||
985 | Name->getName().equals(CorrectedStr); | ||||
986 | diagnoseTypo(Corrected, PDiag(QualifiedDiag) | ||||
987 | << Name << computeDeclContext(SS, false) | ||||
988 | << DroppedSpecifier << SS.getRange()); | ||||
989 | } | ||||
990 | |||||
991 | // Update the name, so that the caller has the new name. | ||||
992 | Name = Corrected.getCorrectionAsIdentifierInfo(); | ||||
993 | |||||
994 | // Typo correction corrected to a keyword. | ||||
995 | if (Corrected.isKeyword()) | ||||
996 | return Name; | ||||
997 | |||||
998 | // Also update the LookupResult... | ||||
999 | // FIXME: This should probably go away at some point | ||||
1000 | Result.clear(); | ||||
1001 | Result.setLookupName(Corrected.getCorrection()); | ||||
1002 | if (FirstDecl) | ||||
1003 | Result.addDecl(FirstDecl); | ||||
1004 | |||||
1005 | // If we found an Objective-C instance variable, let | ||||
1006 | // LookupInObjCMethod build the appropriate expression to | ||||
1007 | // reference the ivar. | ||||
1008 | // FIXME: This is a gross hack. | ||||
1009 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { | ||||
1010 | DeclResult R = | ||||
1011 | LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); | ||||
1012 | if (R.isInvalid()) | ||||
1013 | return NameClassification::Error(); | ||||
1014 | if (R.isUsable()) | ||||
1015 | return NameClassification::NonType(Ivar); | ||||
1016 | } | ||||
1017 | |||||
1018 | goto Corrected; | ||||
1019 | } | ||||
1020 | } | ||||
1021 | |||||
1022 | // We failed to correct; just fall through and let the parser deal with it. | ||||
1023 | Result.suppressDiagnostics(); | ||||
1024 | return NameClassification::Unknown(); | ||||
1025 | |||||
1026 | case LookupResult::NotFoundInCurrentInstantiation: { | ||||
1027 | // We performed name lookup into the current instantiation, and there were | ||||
1028 | // dependent bases, so we treat this result the same way as any other | ||||
1029 | // dependent nested-name-specifier. | ||||
1030 | |||||
1031 | // C++ [temp.res]p2: | ||||
1032 | // A name used in a template declaration or definition and that is | ||||
1033 | // dependent on a template-parameter is assumed not to name a type | ||||
1034 | // unless the applicable name lookup finds a type name or the name is | ||||
1035 | // qualified by the keyword typename. | ||||
1036 | // | ||||
1037 | // FIXME: If the next token is '<', we might want to ask the parser to | ||||
1038 | // perform some heroics to see if we actually have a | ||||
1039 | // template-argument-list, which would indicate a missing 'template' | ||||
1040 | // keyword here. | ||||
1041 | return NameClassification::DependentNonType(); | ||||
1042 | } | ||||
1043 | |||||
1044 | case LookupResult::Found: | ||||
1045 | case LookupResult::FoundOverloaded: | ||||
1046 | case LookupResult::FoundUnresolvedValue: | ||||
1047 | break; | ||||
1048 | |||||
1049 | case LookupResult::Ambiguous: | ||||
1050 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||
1051 | hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, | ||||
1052 | /*AllowDependent=*/false)) { | ||||
1053 | // C++ [temp.local]p3: | ||||
1054 | // A lookup that finds an injected-class-name (10.2) can result in an | ||||
1055 | // ambiguity in certain cases (for example, if it is found in more than | ||||
1056 | // one base class). If all of the injected-class-names that are found | ||||
1057 | // refer to specializations of the same class template, and if the name | ||||
1058 | // is followed by a template-argument-list, the reference refers to the | ||||
1059 | // class template itself and not a specialization thereof, and is not | ||||
1060 | // ambiguous. | ||||
1061 | // | ||||
1062 | // This filtering can make an ambiguous result into an unambiguous one, | ||||
1063 | // so try again after filtering out template names. | ||||
1064 | FilterAcceptableTemplateNames(Result); | ||||
1065 | if (!Result.isAmbiguous()) { | ||||
1066 | IsFilteredTemplateName = true; | ||||
1067 | break; | ||||
1068 | } | ||||
1069 | } | ||||
1070 | |||||
1071 | // Diagnose the ambiguity and return an error. | ||||
1072 | return NameClassification::Error(); | ||||
1073 | } | ||||
1074 | |||||
1075 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||
1076 | (IsFilteredTemplateName || | ||||
1077 | hasAnyAcceptableTemplateNames( | ||||
1078 | Result, /*AllowFunctionTemplates=*/true, | ||||
1079 | /*AllowDependent=*/false, | ||||
1080 | /*AllowNonTemplateFunctions*/ SS.isEmpty() && | ||||
1081 | getLangOpts().CPlusPlus20))) { | ||||
1082 | // C++ [temp.names]p3: | ||||
1083 | // After name lookup (3.4) finds that a name is a template-name or that | ||||
1084 | // an operator-function-id or a literal- operator-id refers to a set of | ||||
1085 | // overloaded functions any member of which is a function template if | ||||
1086 | // this is followed by a <, the < is always taken as the delimiter of a | ||||
1087 | // template-argument-list and never as the less-than operator. | ||||
1088 | // C++2a [temp.names]p2: | ||||
1089 | // A name is also considered to refer to a template if it is an | ||||
1090 | // unqualified-id followed by a < and name lookup finds either one | ||||
1091 | // or more functions or finds nothing. | ||||
1092 | if (!IsFilteredTemplateName) | ||||
1093 | FilterAcceptableTemplateNames(Result); | ||||
1094 | |||||
1095 | bool IsFunctionTemplate; | ||||
1096 | bool IsVarTemplate; | ||||
1097 | TemplateName Template; | ||||
1098 | if (Result.end() - Result.begin() > 1) { | ||||
1099 | IsFunctionTemplate = true; | ||||
1100 | Template = Context.getOverloadedTemplateName(Result.begin(), | ||||
1101 | Result.end()); | ||||
1102 | } else if (!Result.empty()) { | ||||
1103 | auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( | ||||
1104 | *Result.begin(), /*AllowFunctionTemplates=*/true, | ||||
1105 | /*AllowDependent=*/false)); | ||||
1106 | IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); | ||||
1107 | IsVarTemplate = isa<VarTemplateDecl>(TD); | ||||
1108 | |||||
1109 | if (SS.isNotEmpty()) | ||||
1110 | Template = | ||||
1111 | Context.getQualifiedTemplateName(SS.getScopeRep(), | ||||
1112 | /*TemplateKeyword=*/false, TD); | ||||
1113 | else | ||||
1114 | Template = TemplateName(TD); | ||||
1115 | } else { | ||||
1116 | // All results were non-template functions. This is a function template | ||||
1117 | // name. | ||||
1118 | IsFunctionTemplate = true; | ||||
1119 | Template = Context.getAssumedTemplateName(NameInfo.getName()); | ||||
1120 | } | ||||
1121 | |||||
1122 | if (IsFunctionTemplate) { | ||||
1123 | // Function templates always go through overload resolution, at which | ||||
1124 | // point we'll perform the various checks (e.g., accessibility) we need | ||||
1125 | // to based on which function we selected. | ||||
1126 | Result.suppressDiagnostics(); | ||||
1127 | |||||
1128 | return NameClassification::FunctionTemplate(Template); | ||||
1129 | } | ||||
1130 | |||||
1131 | return IsVarTemplate ? NameClassification::VarTemplate(Template) | ||||
1132 | : NameClassification::TypeTemplate(Template); | ||||
1133 | } | ||||
1134 | |||||
1135 | auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { | ||||
1136 | QualType T = Context.getTypeDeclType(Type); | ||||
1137 | if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) | ||||
1138 | T = Context.getUsingType(USD, T); | ||||
1139 | |||||
1140 | if (SS.isEmpty()) // No elaborated type, trivial location info | ||||
1141 | return ParsedType::make(T); | ||||
1142 | |||||
1143 | TypeLocBuilder Builder; | ||||
1144 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | ||||
1145 | T = getElaboratedType(ETK_None, SS, T); | ||||
1146 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | ||||
1147 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
1148 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
1149 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||
1150 | }; | ||||
1151 | |||||
1152 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); | ||||
1153 | if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { | ||||
1154 | DiagnoseUseOfDecl(Type, NameLoc); | ||||
1155 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | ||||
1156 | return BuildTypeFor(Type, *Result.begin()); | ||||
1157 | } | ||||
1158 | |||||
1159 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); | ||||
1160 | if (!Class) { | ||||
1161 | // FIXME: It's unfortunate that we don't have a Type node for handling this. | ||||
1162 | if (ObjCCompatibleAliasDecl *Alias = | ||||
1163 | dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) | ||||
1164 | Class = Alias->getClassInterface(); | ||||
1165 | } | ||||
1166 | |||||
1167 | if (Class) { | ||||
1168 | DiagnoseUseOfDecl(Class, NameLoc); | ||||
1169 | |||||
1170 | if (NextToken.is(tok::period)) { | ||||
1171 | // Interface. <something> is parsed as a property reference expression. | ||||
1172 | // Just return "unknown" as a fall-through for now. | ||||
1173 | Result.suppressDiagnostics(); | ||||
1174 | return NameClassification::Unknown(); | ||||
1175 | } | ||||
1176 | |||||
1177 | QualType T = Context.getObjCInterfaceType(Class); | ||||
1178 | return ParsedType::make(T); | ||||
1179 | } | ||||
1180 | |||||
1181 | if (isa<ConceptDecl>(FirstDecl)) | ||||
1182 | return NameClassification::Concept( | ||||
1183 | TemplateName(cast<TemplateDecl>(FirstDecl))); | ||||
1184 | |||||
1185 | if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { | ||||
1186 | (void)DiagnoseUseOfDecl(EmptyD, NameLoc); | ||||
1187 | return NameClassification::Error(); | ||||
1188 | } | ||||
1189 | |||||
1190 | // We can have a type template here if we're classifying a template argument. | ||||
1191 | if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && | ||||
1192 | !isa<VarTemplateDecl>(FirstDecl)) | ||||
1193 | return NameClassification::TypeTemplate( | ||||
1194 | TemplateName(cast<TemplateDecl>(FirstDecl))); | ||||
1195 | |||||
1196 | // Check for a tag type hidden by a non-type decl in a few cases where it | ||||
1197 | // seems likely a type is wanted instead of the non-type that was found. | ||||
1198 | bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); | ||||
1199 | if ((NextToken.is(tok::identifier) || | ||||
1200 | (NextIsOp && | ||||
1201 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && | ||||
1202 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | ||||
1203 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); | ||||
1204 | DiagnoseUseOfDecl(Type, NameLoc); | ||||
1205 | return BuildTypeFor(Type, *Result.begin()); | ||||
1206 | } | ||||
1207 | |||||
1208 | // If we already know which single declaration is referenced, just annotate | ||||
1209 | // that declaration directly. Defer resolving even non-overloaded class | ||||
1210 | // member accesses, as we need to defer certain access checks until we know | ||||
1211 | // the context. | ||||
1212 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | ||||
1213 | if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) | ||||
1214 | return NameClassification::NonType(Result.getRepresentativeDecl()); | ||||
1215 | |||||
1216 | // Otherwise, this is an overload set that we will need to resolve later. | ||||
1217 | Result.suppressDiagnostics(); | ||||
1218 | return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( | ||||
1219 | Context, Result.getNamingClass(), SS.getWithLocInContext(Context), | ||||
1220 | Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), | ||||
1221 | Result.begin(), Result.end())); | ||||
1222 | } | ||||
1223 | |||||
1224 | ExprResult | ||||
1225 | Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, | ||||
1226 | SourceLocation NameLoc) { | ||||
1227 | assert(getLangOpts().CPlusPlus && "ADL-only call in C?")(static_cast <bool> (getLangOpts().CPlusPlus && "ADL-only call in C?") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL-only call in C?\"" , "clang/lib/Sema/SemaDecl.cpp", 1227, __extension__ __PRETTY_FUNCTION__ )); | ||||
1228 | CXXScopeSpec SS; | ||||
1229 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | ||||
1230 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); | ||||
1231 | } | ||||
1232 | |||||
1233 | ExprResult | ||||
1234 | Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, | ||||
1235 | IdentifierInfo *Name, | ||||
1236 | SourceLocation NameLoc, | ||||
1237 | bool IsAddressOfOperand) { | ||||
1238 | DeclarationNameInfo NameInfo(Name, NameLoc); | ||||
1239 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
1240 | NameInfo, IsAddressOfOperand, | ||||
1241 | /*TemplateArgs=*/nullptr); | ||||
1242 | } | ||||
1243 | |||||
1244 | ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, | ||||
1245 | NamedDecl *Found, | ||||
1246 | SourceLocation NameLoc, | ||||
1247 | const Token &NextToken) { | ||||
1248 | if (getCurMethodDecl() && SS.isEmpty()) | ||||
1249 | if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) | ||||
1250 | return BuildIvarRefExpr(S, NameLoc, Ivar); | ||||
1251 | |||||
1252 | // Reconstruct the lookup result. | ||||
1253 | LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); | ||||
1254 | Result.addDecl(Found); | ||||
1255 | Result.resolveKind(); | ||||
1256 | |||||
1257 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | ||||
1258 | return BuildDeclarationNameExpr(SS, Result, ADL); | ||||
1259 | } | ||||
1260 | |||||
1261 | ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { | ||||
1262 | // For an implicit class member access, transform the result into a member | ||||
1263 | // access expression if necessary. | ||||
1264 | auto *ULE = cast<UnresolvedLookupExpr>(E); | ||||
1265 | if ((*ULE->decls_begin())->isCXXClassMember()) { | ||||
1266 | CXXScopeSpec SS; | ||||
1267 | SS.Adopt(ULE->getQualifierLoc()); | ||||
1268 | |||||
1269 | // Reconstruct the lookup result. | ||||
1270 | LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), | ||||
1271 | LookupOrdinaryName); | ||||
1272 | Result.setNamingClass(ULE->getNamingClass()); | ||||
1273 | for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) | ||||
1274 | Result.addDecl(*I, I.getAccess()); | ||||
1275 | Result.resolveKind(); | ||||
1276 | return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, | ||||
1277 | nullptr, S); | ||||
1278 | } | ||||
1279 | |||||
1280 | // Otherwise, this is already in the form we needed, and no further checks | ||||
1281 | // are necessary. | ||||
1282 | return ULE; | ||||
1283 | } | ||||
1284 | |||||
1285 | Sema::TemplateNameKindForDiagnostics | ||||
1286 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { | ||||
1287 | auto *TD = Name.getAsTemplateDecl(); | ||||
1288 | if (!TD) | ||||
1289 | return TemplateNameKindForDiagnostics::DependentTemplate; | ||||
1290 | if (isa<ClassTemplateDecl>(TD)) | ||||
1291 | return TemplateNameKindForDiagnostics::ClassTemplate; | ||||
1292 | if (isa<FunctionTemplateDecl>(TD)) | ||||
1293 | return TemplateNameKindForDiagnostics::FunctionTemplate; | ||||
1294 | if (isa<VarTemplateDecl>(TD)) | ||||
1295 | return TemplateNameKindForDiagnostics::VarTemplate; | ||||
1296 | if (isa<TypeAliasTemplateDecl>(TD)) | ||||
1297 | return TemplateNameKindForDiagnostics::AliasTemplate; | ||||
1298 | if (isa<TemplateTemplateParmDecl>(TD)) | ||||
1299 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; | ||||
1300 | if (isa<ConceptDecl>(TD)) | ||||
1301 | return TemplateNameKindForDiagnostics::Concept; | ||||
1302 | return TemplateNameKindForDiagnostics::DependentTemplate; | ||||
1303 | } | ||||
1304 | |||||
1305 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { | ||||
1306 | assert(DC->getLexicalParent() == CurContext &&(static_cast <bool> (DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "clang/lib/Sema/SemaDecl.cpp", 1307, __extension__ __PRETTY_FUNCTION__ )) | ||||
1307 | "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "clang/lib/Sema/SemaDecl.cpp", 1307, __extension__ __PRETTY_FUNCTION__ )); | ||||
1308 | CurContext = DC; | ||||
1309 | S->setEntity(DC); | ||||
1310 | } | ||||
1311 | |||||
1312 | void Sema::PopDeclContext() { | ||||
1313 | assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!" ) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "clang/lib/Sema/SemaDecl.cpp", 1313, __extension__ __PRETTY_FUNCTION__ )); | ||||
1314 | |||||
1315 | CurContext = CurContext->getLexicalParent(); | ||||
1316 | assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!" ) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "clang/lib/Sema/SemaDecl.cpp", 1316, __extension__ __PRETTY_FUNCTION__ )); | ||||
1317 | } | ||||
1318 | |||||
1319 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, | ||||
1320 | Decl *D) { | ||||
1321 | // Unlike PushDeclContext, the context to which we return is not necessarily | ||||
1322 | // the containing DC of TD, because the new context will be some pre-existing | ||||
1323 | // TagDecl definition instead of a fresh one. | ||||
1324 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); | ||||
1325 | CurContext = cast<TagDecl>(D)->getDefinition(); | ||||
1326 | assert(CurContext && "skipping definition of undefined tag")(static_cast <bool> (CurContext && "skipping definition of undefined tag" ) ? void (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\"" , "clang/lib/Sema/SemaDecl.cpp", 1326, __extension__ __PRETTY_FUNCTION__ )); | ||||
1327 | // Start lookups from the parent of the current context; we don't want to look | ||||
1328 | // into the pre-existing complete definition. | ||||
1329 | S->setEntity(CurContext->getLookupParent()); | ||||
1330 | return Result; | ||||
1331 | } | ||||
1332 | |||||
1333 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { | ||||
1334 | CurContext = static_cast<decltype(CurContext)>(Context); | ||||
1335 | } | ||||
1336 | |||||
1337 | /// EnterDeclaratorContext - Used when we must lookup names in the context | ||||
1338 | /// of a declarator's nested name specifier. | ||||
1339 | /// | ||||
1340 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { | ||||
1341 | // C++0x [basic.lookup.unqual]p13: | ||||
1342 | // A name used in the definition of a static data member of class | ||||
1343 | // X (after the qualified-id of the static member) is looked up as | ||||
1344 | // if the name was used in a member function of X. | ||||
1345 | // C++0x [basic.lookup.unqual]p14: | ||||
1346 | // If a variable member of a namespace is defined outside of the | ||||
1347 | // scope of its namespace then any name used in the definition of | ||||
1348 | // the variable member (after the declarator-id) is looked up as | ||||
1349 | // if the definition of the variable member occurred in its | ||||
1350 | // namespace. | ||||
1351 | // Both of these imply that we should push a scope whose context | ||||
1352 | // is the semantic context of the declaration. We can't use | ||||
1353 | // PushDeclContext here because that context is not necessarily | ||||
1354 | // lexically contained in the current context. Fortunately, | ||||
1355 | // the containing scope should have the appropriate information. | ||||
1356 | |||||
1357 | assert(!S->getEntity() && "scope already has entity")(static_cast <bool> (!S->getEntity() && "scope already has entity" ) ? void (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\"" , "clang/lib/Sema/SemaDecl.cpp", 1357, __extension__ __PRETTY_FUNCTION__ )); | ||||
1358 | |||||
1359 | #ifndef NDEBUG | ||||
1360 | Scope *Ancestor = S->getParent(); | ||||
1361 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | ||||
1362 | assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")(static_cast <bool> (Ancestor->getEntity() == CurContext && "ancestor context mismatch") ? void (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\"" , "clang/lib/Sema/SemaDecl.cpp", 1362, __extension__ __PRETTY_FUNCTION__ )); | ||||
1363 | #endif | ||||
1364 | |||||
1365 | CurContext = DC; | ||||
1366 | S->setEntity(DC); | ||||
1367 | |||||
1368 | if (S->getParent()->isTemplateParamScope()) { | ||||
1369 | // Also set the corresponding entities for all immediately-enclosing | ||||
1370 | // template parameter scopes. | ||||
1371 | EnterTemplatedContext(S->getParent(), DC); | ||||
1372 | } | ||||
1373 | } | ||||
1374 | |||||
1375 | void Sema::ExitDeclaratorContext(Scope *S) { | ||||
1376 | assert(S->getEntity() == CurContext && "Context imbalance!")(static_cast <bool> (S->getEntity() == CurContext && "Context imbalance!") ? void (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\"" , "clang/lib/Sema/SemaDecl.cpp", 1376, __extension__ __PRETTY_FUNCTION__ )); | ||||
1377 | |||||
1378 | // Switch back to the lexical context. The safety of this is | ||||
1379 | // enforced by an assert in EnterDeclaratorContext. | ||||
1380 | Scope *Ancestor = S->getParent(); | ||||
1381 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | ||||
1382 | CurContext = Ancestor->getEntity(); | ||||
1383 | |||||
1384 | // We don't need to do anything with the scope, which is going to | ||||
1385 | // disappear. | ||||
1386 | } | ||||
1387 | |||||
1388 | void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { | ||||
1389 | assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() && "expected to be initializing a template parameter scope") ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\"" , "clang/lib/Sema/SemaDecl.cpp", 1390, __extension__ __PRETTY_FUNCTION__ )) | ||||
1390 | "expected to be initializing a template parameter scope")(static_cast <bool> (S->isTemplateParamScope() && "expected to be initializing a template parameter scope") ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\"" , "clang/lib/Sema/SemaDecl.cpp", 1390, __extension__ __PRETTY_FUNCTION__ )); | ||||
1391 | |||||
1392 | // C++20 [temp.local]p7: | ||||
1393 | // In the definition of a member of a class template that appears outside | ||||
1394 | // of the class template definition, the name of a member of the class | ||||
1395 | // template hides the name of a template-parameter of any enclosing class | ||||
1396 | // templates (but not a template-parameter of the member if the member is a | ||||
1397 | // class or function template). | ||||
1398 | // C++20 [temp.local]p9: | ||||
1399 | // In the definition of a class template or in the definition of a member | ||||
1400 | // of such a template that appears outside of the template definition, for | ||||
1401 | // each non-dependent base class (13.8.2.1), if the name of the base class | ||||
1402 | // or the name of a member of the base class is the same as the name of a | ||||
1403 | // template-parameter, the base class name or member name hides the | ||||
1404 | // template-parameter name (6.4.10). | ||||
1405 | // | ||||
1406 | // This means that a template parameter scope should be searched immediately | ||||
1407 | // after searching the DeclContext for which it is a template parameter | ||||
1408 | // scope. For example, for | ||||
1409 | // template<typename T> template<typename U> template<typename V> | ||||
1410 | // void N::A<T>::B<U>::f(...) | ||||
1411 | // we search V then B<U> (and base classes) then U then A<T> (and base | ||||
1412 | // classes) then T then N then ::. | ||||
1413 | unsigned ScopeDepth = getTemplateDepth(S); | ||||
1414 | for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { | ||||
1415 | DeclContext *SearchDCAfterScope = DC; | ||||
1416 | for (; DC; DC = DC->getLookupParent()) { | ||||
1417 | if (const TemplateParameterList *TPL = | ||||
1418 | cast<Decl>(DC)->getDescribedTemplateParams()) { | ||||
1419 | unsigned DCDepth = TPL->getDepth() + 1; | ||||
1420 | if (DCDepth > ScopeDepth) | ||||
1421 | continue; | ||||
1422 | if (ScopeDepth == DCDepth) | ||||
1423 | SearchDCAfterScope = DC = DC->getLookupParent(); | ||||
1424 | break; | ||||
1425 | } | ||||
1426 | } | ||||
1427 | S->setLookupEntity(SearchDCAfterScope); | ||||
1428 | } | ||||
1429 | } | ||||
1430 | |||||
1431 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { | ||||
1432 | // We assume that the caller has already called | ||||
1433 | // ActOnReenterTemplateScope so getTemplatedDecl() works. | ||||
1434 | FunctionDecl *FD = D->getAsFunction(); | ||||
1435 | if (!FD) | ||||
1436 | return; | ||||
1437 | |||||
1438 | // Same implementation as PushDeclContext, but enters the context | ||||
1439 | // from the lexical parent, rather than the top-level class. | ||||
1440 | assert(CurContext == FD->getLexicalParent() &&(static_cast <bool> (CurContext == FD->getLexicalParent () && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "clang/lib/Sema/SemaDecl.cpp", 1441, __extension__ __PRETTY_FUNCTION__ )) | ||||
1441 | "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (CurContext == FD->getLexicalParent () && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "clang/lib/Sema/SemaDecl.cpp", 1441, __extension__ __PRETTY_FUNCTION__ )); | ||||
1442 | CurContext = FD; | ||||
1443 | S->setEntity(CurContext); | ||||
1444 | |||||
1445 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { | ||||
1446 | ParmVarDecl *Param = FD->getParamDecl(P); | ||||
1447 | // If the parameter has an identifier, then add it to the scope | ||||
1448 | if (Param->getIdentifier()) { | ||||
1449 | S->AddDecl(Param); | ||||
1450 | IdResolver.AddDecl(Param); | ||||
1451 | } | ||||
1452 | } | ||||
1453 | } | ||||
1454 | |||||
1455 | void Sema::ActOnExitFunctionContext() { | ||||
1456 | // Same implementation as PopDeclContext, but returns to the lexical parent, | ||||
1457 | // rather than the top-level class. | ||||
1458 | assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!" ) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "clang/lib/Sema/SemaDecl.cpp", 1458, __extension__ __PRETTY_FUNCTION__ )); | ||||
1459 | CurContext = CurContext->getLexicalParent(); | ||||
1460 | assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!" ) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "clang/lib/Sema/SemaDecl.cpp", 1460, __extension__ __PRETTY_FUNCTION__ )); | ||||
1461 | } | ||||
1462 | |||||
1463 | /// Determine whether we allow overloading of the function | ||||
1464 | /// PrevDecl with another declaration. | ||||
1465 | /// | ||||
1466 | /// This routine determines whether overloading is possible, not | ||||
1467 | /// whether some new function is actually an overload. It will return | ||||
1468 | /// true in C++ (where we can always provide overloads) or, as an | ||||
1469 | /// extension, in C when the previous function is already an | ||||
1470 | /// overloaded function declaration or has the "overloadable" | ||||
1471 | /// attribute. | ||||
1472 | static bool AllowOverloadingOfFunction(LookupResult &Previous, | ||||
1473 | ASTContext &Context, | ||||
1474 | const FunctionDecl *New) { | ||||
1475 | if (Context.getLangOpts().CPlusPlus) | ||||
1476 | return true; | ||||
1477 | |||||
1478 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) | ||||
1479 | return true; | ||||
1480 | |||||
1481 | return Previous.getResultKind() == LookupResult::Found && | ||||
1482 | (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || | ||||
1483 | New->hasAttr<OverloadableAttr>()); | ||||
1484 | } | ||||
1485 | |||||
1486 | /// Add this decl to the scope shadowed decl chains. | ||||
1487 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { | ||||
1488 | // Move up the scope chain until we find the nearest enclosing | ||||
1489 | // non-transparent context. The declaration will be introduced into this | ||||
1490 | // scope. | ||||
1491 | while (S->getEntity() && S->getEntity()->isTransparentContext()) | ||||
1492 | S = S->getParent(); | ||||
1493 | |||||
1494 | // Add scoped declarations into their context, so that they can be | ||||
1495 | // found later. Declarations without a context won't be inserted | ||||
1496 | // into any context. | ||||
1497 | if (AddToContext) | ||||
1498 | CurContext->addDecl(D); | ||||
1499 | |||||
1500 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they | ||||
1501 | // are function-local declarations. | ||||
1502 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) | ||||
1503 | return; | ||||
1504 | |||||
1505 | // Template instantiations should also not be pushed into scope. | ||||
1506 | if (isa<FunctionDecl>(D) && | ||||
1507 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) | ||||
1508 | return; | ||||
1509 | |||||
1510 | // If this replaces anything in the current scope, | ||||
1511 | IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), | ||||
1512 | IEnd = IdResolver.end(); | ||||
1513 | for (; I != IEnd; ++I) { | ||||
1514 | if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { | ||||
1515 | S->RemoveDecl(*I); | ||||
1516 | IdResolver.RemoveDecl(*I); | ||||
1517 | |||||
1518 | // Should only need to replace one decl. | ||||
1519 | break; | ||||
1520 | } | ||||
1521 | } | ||||
1522 | |||||
1523 | S->AddDecl(D); | ||||
1524 | |||||
1525 | if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { | ||||
1526 | // Implicitly-generated labels may end up getting generated in an order that | ||||
1527 | // isn't strictly lexical, which breaks name lookup. Be careful to insert | ||||
1528 | // the label at the appropriate place in the identifier chain. | ||||
1529 | for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { | ||||
1530 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); | ||||
1531 | if (IDC == CurContext) { | ||||
1532 | if (!S->isDeclScope(*I)) | ||||
1533 | continue; | ||||
1534 | } else if (IDC->Encloses(CurContext)) | ||||
1535 | break; | ||||
1536 | } | ||||
1537 | |||||
1538 | IdResolver.InsertDeclAfter(I, D); | ||||
1539 | } else { | ||||
1540 | IdResolver.AddDecl(D); | ||||
1541 | } | ||||
1542 | warnOnReservedIdentifier(D); | ||||
1543 | } | ||||
1544 | |||||
1545 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, | ||||
1546 | bool AllowInlineNamespace) { | ||||
1547 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); | ||||
1548 | } | ||||
1549 | |||||
1550 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { | ||||
1551 | DeclContext *TargetDC = DC->getPrimaryContext(); | ||||
1552 | do { | ||||
1553 | if (DeclContext *ScopeDC = S->getEntity()) | ||||
1554 | if (ScopeDC->getPrimaryContext() == TargetDC) | ||||
1555 | return S; | ||||
1556 | } while ((S = S->getParent())); | ||||
1557 | |||||
1558 | return nullptr; | ||||
1559 | } | ||||
1560 | |||||
1561 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, | ||||
1562 | DeclContext*, | ||||
1563 | ASTContext&); | ||||
1564 | |||||
1565 | /// Filters out lookup results that don't fall within the given scope | ||||
1566 | /// as determined by isDeclInScope. | ||||
1567 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, | ||||
1568 | bool ConsiderLinkage, | ||||
1569 | bool AllowInlineNamespace) { | ||||
1570 | LookupResult::Filter F = R.makeFilter(); | ||||
1571 | while (F.hasNext()) { | ||||
1572 | NamedDecl *D = F.next(); | ||||
1573 | |||||
1574 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) | ||||
1575 | continue; | ||||
1576 | |||||
1577 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) | ||||
1578 | continue; | ||||
1579 | |||||
1580 | F.erase(); | ||||
1581 | } | ||||
1582 | |||||
1583 | F.done(); | ||||
1584 | } | ||||
1585 | |||||
1586 | /// We've determined that \p New is a redeclaration of \p Old. Check that they | ||||
1587 | /// have compatible owning modules. | ||||
1588 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { | ||||
1589 | // FIXME: The Modules TS is not clear about how friend declarations are | ||||
1590 | // to be treated. It's not meaningful to have different owning modules for | ||||
1591 | // linkage in redeclarations of the same entity, so for now allow the | ||||
1592 | // redeclaration and change the owning modules to match. | ||||
1593 | if (New->getFriendObjectKind() && | ||||
1594 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { | ||||
1595 | New->setLocalOwningModule(Old->getOwningModule()); | ||||
1596 | makeMergedDefinitionVisible(New); | ||||
1597 | return false; | ||||
1598 | } | ||||
1599 | |||||
1600 | Module *NewM = New->getOwningModule(); | ||||
1601 | Module *OldM = Old->getOwningModule(); | ||||
1602 | |||||
1603 | if (NewM && NewM->Kind == Module::PrivateModuleFragment) | ||||
1604 | NewM = NewM->Parent; | ||||
1605 | if (OldM && OldM->Kind == Module::PrivateModuleFragment) | ||||
1606 | OldM = OldM->Parent; | ||||
1607 | |||||
1608 | if (NewM == OldM) | ||||
1609 | return false; | ||||
1610 | |||||
1611 | bool NewIsModuleInterface = NewM && NewM->isModulePurview(); | ||||
1612 | bool OldIsModuleInterface = OldM && OldM->isModulePurview(); | ||||
1613 | if (NewIsModuleInterface || OldIsModuleInterface) { | ||||
1614 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: | ||||
1615 | // if a declaration of D [...] appears in the purview of a module, all | ||||
1616 | // other such declarations shall appear in the purview of the same module | ||||
1617 | Diag(New->getLocation(), diag::err_mismatched_owning_module) | ||||
1618 | << New | ||||
1619 | << NewIsModuleInterface | ||||
1620 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "") | ||||
1621 | << OldIsModuleInterface | ||||
1622 | << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); | ||||
1623 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
1624 | New->setInvalidDecl(); | ||||
1625 | return true; | ||||
1626 | } | ||||
1627 | |||||
1628 | return false; | ||||
1629 | } | ||||
1630 | |||||
1631 | static bool isUsingDecl(NamedDecl *D) { | ||||
1632 | return isa<UsingShadowDecl>(D) || | ||||
1633 | isa<UnresolvedUsingTypenameDecl>(D) || | ||||
1634 | isa<UnresolvedUsingValueDecl>(D); | ||||
1635 | } | ||||
1636 | |||||
1637 | /// Removes using shadow declarations from the lookup results. | ||||
1638 | static void RemoveUsingDecls(LookupResult &R) { | ||||
1639 | LookupResult::Filter F = R.makeFilter(); | ||||
1640 | while (F.hasNext()) | ||||
1641 | if (isUsingDecl(F.next())) | ||||
1642 | F.erase(); | ||||
1643 | |||||
1644 | F.done(); | ||||
1645 | } | ||||
1646 | |||||
1647 | /// Check for this common pattern: | ||||
1648 | /// @code | ||||
1649 | /// class S { | ||||
1650 | /// S(const S&); // DO NOT IMPLEMENT | ||||
1651 | /// void operator=(const S&); // DO NOT IMPLEMENT | ||||
1652 | /// }; | ||||
1653 | /// @endcode | ||||
1654 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { | ||||
1655 | // FIXME: Should check for private access too but access is set after we get | ||||
1656 | // the decl here. | ||||
1657 | if (D->doesThisDeclarationHaveABody()) | ||||
1658 | return false; | ||||
1659 | |||||
1660 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) | ||||
1661 | return CD->isCopyConstructor(); | ||||
1662 | return D->isCopyAssignmentOperator(); | ||||
1663 | } | ||||
1664 | |||||
1665 | // We need this to handle | ||||
1666 | // | ||||
1667 | // typedef struct { | ||||
1668 | // void *foo() { return 0; } | ||||
1669 | // } A; | ||||
1670 | // | ||||
1671 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' | ||||
1672 | // for example. If 'A', foo will have external linkage. If we have '*A', | ||||
1673 | // foo will have no linkage. Since we can't know until we get to the end | ||||
1674 | // of the typedef, this function finds out if D might have non-external linkage. | ||||
1675 | // Callers should verify at the end of the TU if it D has external linkage or | ||||
1676 | // not. | ||||
1677 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { | ||||
1678 | const DeclContext *DC = D->getDeclContext(); | ||||
1679 | while (!DC->isTranslationUnit()) { | ||||
1680 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ | ||||
1681 | if (!RD->hasNameForLinkage()) | ||||
1682 | return true; | ||||
1683 | } | ||||
1684 | DC = DC->getParent(); | ||||
1685 | } | ||||
1686 | |||||
1687 | return !D->isExternallyVisible(); | ||||
1688 | } | ||||
1689 | |||||
1690 | // FIXME: This needs to be refactored; some other isInMainFile users want | ||||
1691 | // these semantics. | ||||
1692 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { | ||||
1693 | if (S.TUKind != TU_Complete) | ||||
1694 | return false; | ||||
1695 | return S.SourceMgr.isInMainFile(Loc); | ||||
1696 | } | ||||
1697 | |||||
1698 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { | ||||
1699 | assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D" , "clang/lib/Sema/SemaDecl.cpp", 1699, __extension__ __PRETTY_FUNCTION__ )); | ||||
1700 | |||||
1701 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) | ||||
1702 | return false; | ||||
1703 | |||||
1704 | // Ignore all entities declared within templates, and out-of-line definitions | ||||
1705 | // of members of class templates. | ||||
1706 | if (D->getDeclContext()->isDependentContext() || | ||||
1707 | D->getLexicalDeclContext()->isDependentContext()) | ||||
1708 | return false; | ||||
1709 | |||||
1710 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
1711 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | ||||
1712 | return false; | ||||
1713 | // A non-out-of-line declaration of a member specialization was implicitly | ||||
1714 | // instantiated; it's the out-of-line declaration that we're interested in. | ||||
1715 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | ||||
1716 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) | ||||
1717 | return false; | ||||
1718 | |||||
1719 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||
1720 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) | ||||
1721 | return false; | ||||
1722 | } else { | ||||
1723 | // 'static inline' functions are defined in headers; don't warn. | ||||
1724 | if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) | ||||
1725 | return false; | ||||
1726 | } | ||||
1727 | |||||
1728 | if (FD->doesThisDeclarationHaveABody() && | ||||
1729 | Context.DeclMustBeEmitted(FD)) | ||||
1730 | return false; | ||||
1731 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
1732 | // Constants and utility variables are defined in headers with internal | ||||
1733 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker | ||||
1734 | // like "inline".) | ||||
1735 | if (!isMainFileLoc(*this, VD->getLocation())) | ||||
1736 | return false; | ||||
1737 | |||||
1738 | if (Context.DeclMustBeEmitted(VD)) | ||||
1739 | return false; | ||||
1740 | |||||
1741 | if (VD->isStaticDataMember() && | ||||
1742 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | ||||
1743 | return false; | ||||
1744 | if (VD->isStaticDataMember() && | ||||
1745 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | ||||
1746 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) | ||||
1747 | return false; | ||||
1748 | |||||
1749 | if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) | ||||
1750 | return false; | ||||
1751 | } else { | ||||
1752 | return false; | ||||
1753 | } | ||||
1754 | |||||
1755 | // Only warn for unused decls internal to the translation unit. | ||||
1756 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function | ||||
1757 | // for inline functions defined in the main source file, for instance. | ||||
1758 | return mightHaveNonExternalLinkage(D); | ||||
1759 | } | ||||
1760 | |||||
1761 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { | ||||
1762 | if (!D) | ||||
1763 | return; | ||||
1764 | |||||
1765 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
1766 | const FunctionDecl *First = FD->getFirstDecl(); | ||||
1767 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | ||||
1768 | return; // First should already be in the vector. | ||||
1769 | } | ||||
1770 | |||||
1771 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
1772 | const VarDecl *First = VD->getFirstDecl(); | ||||
1773 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | ||||
1774 | return; // First should already be in the vector. | ||||
1775 | } | ||||
1776 | |||||
1777 | if (ShouldWarnIfUnusedFileScopedDecl(D)) | ||||
1778 | UnusedFileScopedDecls.push_back(D); | ||||
1779 | } | ||||
1780 | |||||
1781 | static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { | ||||
1782 | if (D->isInvalidDecl()) | ||||
1783 | return false; | ||||
1784 | |||||
1785 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) { | ||||
1786 | // For a decomposition declaration, warn if none of the bindings are | ||||
1787 | // referenced, instead of if the variable itself is referenced (which | ||||
1788 | // it is, by the bindings' expressions). | ||||
1789 | for (auto *BD : DD->bindings()) | ||||
1790 | if (BD->isReferenced()) | ||||
1791 | return false; | ||||
1792 | } else if (!D->getDeclName()) { | ||||
1793 | return false; | ||||
1794 | } else if (D->isReferenced() || D->isUsed()) { | ||||
1795 | return false; | ||||
1796 | } | ||||
1797 | |||||
1798 | if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) | ||||
1799 | return false; | ||||
1800 | |||||
1801 | if (isa<LabelDecl>(D)) | ||||
1802 | return true; | ||||
1803 | |||||
1804 | // Except for labels, we only care about unused decls that are local to | ||||
1805 | // functions. | ||||
1806 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); | ||||
1807 | if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) | ||||
1808 | // For dependent types, the diagnostic is deferred. | ||||
1809 | WithinFunction = | ||||
1810 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); | ||||
1811 | if (!WithinFunction) | ||||
1812 | return false; | ||||
1813 | |||||
1814 | if (isa<TypedefNameDecl>(D)) | ||||
1815 | return true; | ||||
1816 | |||||
1817 | // White-list anything that isn't a local variable. | ||||
1818 | if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) | ||||
1819 | return false; | ||||
1820 | |||||
1821 | // Types of valid local variables should be complete, so this should succeed. | ||||
1822 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
1823 | |||||
1824 | // White-list anything with an __attribute__((unused)) type. | ||||
1825 | const auto *Ty = VD->getType().getTypePtr(); | ||||
1826 | |||||
1827 | // Only look at the outermost level of typedef. | ||||
1828 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { | ||||
1829 | if (TT->getDecl()->hasAttr<UnusedAttr>()) | ||||
1830 | return false; | ||||
1831 | } | ||||
1832 | |||||
1833 | // If we failed to complete the type for some reason, or if the type is | ||||
1834 | // dependent, don't diagnose the variable. | ||||
1835 | if (Ty->isIncompleteType() || Ty->isDependentType()) | ||||
1836 | return false; | ||||
1837 | |||||
1838 | // Look at the element type to ensure that the warning behaviour is | ||||
1839 | // consistent for both scalars and arrays. | ||||
1840 | Ty = Ty->getBaseElementTypeUnsafe(); | ||||
1841 | |||||
1842 | if (const TagType *TT = Ty->getAs<TagType>()) { | ||||
1843 | const TagDecl *Tag = TT->getDecl(); | ||||
1844 | if (Tag->hasAttr<UnusedAttr>()) | ||||
1845 | return false; | ||||
1846 | |||||
1847 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { | ||||
1848 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) | ||||
1849 | return false; | ||||
1850 | |||||
1851 | if (const Expr *Init = VD->getInit()) { | ||||
1852 | if (const ExprWithCleanups *Cleanups = | ||||
1853 | dyn_cast<ExprWithCleanups>(Init)) | ||||
1854 | Init = Cleanups->getSubExpr(); | ||||
1855 | const CXXConstructExpr *Construct = | ||||
1856 | dyn_cast<CXXConstructExpr>(Init); | ||||
1857 | if (Construct && !Construct->isElidable()) { | ||||
1858 | CXXConstructorDecl *CD = Construct->getConstructor(); | ||||
1859 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && | ||||
1860 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) | ||||
1861 | return false; | ||||
1862 | } | ||||
1863 | |||||
1864 | // Suppress the warning if we don't know how this is constructed, and | ||||
1865 | // it could possibly be non-trivial constructor. | ||||
1866 | if (Init->isTypeDependent()) | ||||
1867 | for (const CXXConstructorDecl *Ctor : RD->ctors()) | ||||
1868 | if (!Ctor->isTrivial()) | ||||
1869 | return false; | ||||
1870 | } | ||||
1871 | } | ||||
1872 | } | ||||
1873 | |||||
1874 | // TODO: __attribute__((unused)) templates? | ||||
1875 | } | ||||
1876 | |||||
1877 | return true; | ||||
1878 | } | ||||
1879 | |||||
1880 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, | ||||
1881 | FixItHint &Hint) { | ||||
1882 | if (isa<LabelDecl>(D)) { | ||||
1883 | SourceLocation AfterColon = Lexer::findLocationAfterToken( | ||||
1884 | D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), | ||||
1885 | true); | ||||
1886 | if (AfterColon.isInvalid()) | ||||
1887 | return; | ||||
1888 | Hint = FixItHint::CreateRemoval( | ||||
1889 | CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); | ||||
1890 | } | ||||
1891 | } | ||||
1892 | |||||
1893 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { | ||||
1894 | if (D->getTypeForDecl()->isDependentType()) | ||||
1895 | return; | ||||
1896 | |||||
1897 | for (auto *TmpD : D->decls()) { | ||||
1898 | if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) | ||||
1899 | DiagnoseUnusedDecl(T); | ||||
1900 | else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) | ||||
1901 | DiagnoseUnusedNestedTypedefs(R); | ||||
1902 | } | ||||
1903 | } | ||||
1904 | |||||
1905 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used | ||||
1906 | /// unless they are marked attr(unused). | ||||
1907 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { | ||||
1908 | if (!ShouldDiagnoseUnusedDecl(D)) | ||||
1909 | return; | ||||
1910 | |||||
1911 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { | ||||
1912 | // typedefs can be referenced later on, so the diagnostics are emitted | ||||
1913 | // at end-of-translation-unit. | ||||
1914 | UnusedLocalTypedefNameCandidates.insert(TD); | ||||
1915 | return; | ||||
1916 | } | ||||
1917 | |||||
1918 | FixItHint Hint; | ||||
1919 | GenerateFixForUnusedDecl(D, Context, Hint); | ||||
1920 | |||||
1921 | unsigned DiagID; | ||||
1922 | if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) | ||||
1923 | DiagID = diag::warn_unused_exception_param; | ||||
1924 | else if (isa<LabelDecl>(D)) | ||||
1925 | DiagID = diag::warn_unused_label; | ||||
1926 | else | ||||
1927 | DiagID = diag::warn_unused_variable; | ||||
1928 | |||||
1929 | Diag(D->getLocation(), DiagID) << D << Hint; | ||||
1930 | } | ||||
1931 | |||||
1932 | void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { | ||||
1933 | // If it's not referenced, it can't be set. If it has the Cleanup attribute, | ||||
1934 | // it's not really unused. | ||||
1935 | if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || | ||||
1936 | VD->hasAttr<CleanupAttr>()) | ||||
1937 | return; | ||||
1938 | |||||
1939 | const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); | ||||
1940 | |||||
1941 | if (Ty->isReferenceType() || Ty->isDependentType()) | ||||
1942 | return; | ||||
1943 | |||||
1944 | if (const TagType *TT = Ty->getAs<TagType>()) { | ||||
1945 | const TagDecl *Tag = TT->getDecl(); | ||||
1946 | if (Tag->hasAttr<UnusedAttr>()) | ||||
1947 | return; | ||||
1948 | // In C++, don't warn for record types that don't have WarnUnusedAttr, to | ||||
1949 | // mimic gcc's behavior. | ||||
1950 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { | ||||
1951 | if (!RD->hasAttr<WarnUnusedAttr>()) | ||||
1952 | return; | ||||
1953 | } | ||||
1954 | } | ||||
1955 | |||||
1956 | // Don't warn about __block Objective-C pointer variables, as they might | ||||
1957 | // be assigned in the block but not used elsewhere for the purpose of lifetime | ||||
1958 | // extension. | ||||
1959 | if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) | ||||
1960 | return; | ||||
1961 | |||||
1962 | auto iter = RefsMinusAssignments.find(VD); | ||||
1963 | if (iter == RefsMinusAssignments.end()) | ||||
1964 | return; | ||||
1965 | |||||
1966 | assert(iter->getSecond() >= 0 &&(static_cast <bool> (iter->getSecond() >= 0 && "Found a negative number of references to a VarDecl") ? void (0) : __assert_fail ("iter->getSecond() >= 0 && \"Found a negative number of references to a VarDecl\"" , "clang/lib/Sema/SemaDecl.cpp", 1967, __extension__ __PRETTY_FUNCTION__ )) | ||||
1967 | "Found a negative number of references to a VarDecl")(static_cast <bool> (iter->getSecond() >= 0 && "Found a negative number of references to a VarDecl") ? void (0) : __assert_fail ("iter->getSecond() >= 0 && \"Found a negative number of references to a VarDecl\"" , "clang/lib/Sema/SemaDecl.cpp", 1967, __extension__ __PRETTY_FUNCTION__ )); | ||||
1968 | if (iter->getSecond() != 0) | ||||
1969 | return; | ||||
1970 | unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter | ||||
1971 | : diag::warn_unused_but_set_variable; | ||||
1972 | Diag(VD->getLocation(), DiagID) << VD; | ||||
1973 | } | ||||
1974 | |||||
1975 | static void CheckPoppedLabel(LabelDecl *L, Sema &S) { | ||||
1976 | // Verify that we have no forward references left. If so, there was a goto | ||||
1977 | // or address of a label taken, but no definition of it. Label fwd | ||||
1978 | // definitions are indicated with a null substmt which is also not a resolved | ||||
1979 | // MS inline assembly label name. | ||||
1980 | bool Diagnose = false; | ||||
1981 | if (L->isMSAsmLabel()) | ||||
1982 | Diagnose = !L->isResolvedMSAsmLabel(); | ||||
1983 | else | ||||
1984 | Diagnose = L->getStmt() == nullptr; | ||||
1985 | if (Diagnose) | ||||
1986 | S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; | ||||
1987 | } | ||||
1988 | |||||
1989 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { | ||||
1990 | S->mergeNRVOIntoParent(); | ||||
1991 | |||||
1992 | if (S->decl_empty()) return; | ||||
1993 | assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(static_cast <bool> ((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && "Scope shouldn't contain decls!" ) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "clang/lib/Sema/SemaDecl.cpp", 1994, __extension__ __PRETTY_FUNCTION__ )) | ||||
1994 | "Scope shouldn't contain decls!")(static_cast <bool> ((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && "Scope shouldn't contain decls!" ) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "clang/lib/Sema/SemaDecl.cpp", 1994, __extension__ __PRETTY_FUNCTION__ )); | ||||
1995 | |||||
1996 | for (auto *TmpD : S->decls()) { | ||||
1997 | assert(TmpD && "This decl didn't get pushed??")(static_cast <bool> (TmpD && "This decl didn't get pushed??" ) ? void (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\"" , "clang/lib/Sema/SemaDecl.cpp", 1997, __extension__ __PRETTY_FUNCTION__ )); | ||||
1998 | |||||
1999 | assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")(static_cast <bool> (isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?") ? void (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\"" , "clang/lib/Sema/SemaDecl.cpp", 1999, __extension__ __PRETTY_FUNCTION__ )); | ||||
2000 | NamedDecl *D = cast<NamedDecl>(TmpD); | ||||
2001 | |||||
2002 | // Diagnose unused variables in this scope. | ||||
2003 | if (!S->hasUnrecoverableErrorOccurred()) { | ||||
2004 | DiagnoseUnusedDecl(D); | ||||
2005 | if (const auto *RD = dyn_cast<RecordDecl>(D)) | ||||
2006 | DiagnoseUnusedNestedTypedefs(RD); | ||||
2007 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
2008 | DiagnoseUnusedButSetDecl(VD); | ||||
2009 | RefsMinusAssignments.erase(VD); | ||||
2010 | } | ||||
2011 | } | ||||
2012 | |||||
2013 | if (!D->getDeclName()) continue; | ||||
2014 | |||||
2015 | // If this was a forward reference to a label, verify it was defined. | ||||
2016 | if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) | ||||
2017 | CheckPoppedLabel(LD, *this); | ||||
2018 | |||||
2019 | // Remove this name from our lexical scope, and warn on it if we haven't | ||||
2020 | // already. | ||||
2021 | IdResolver.RemoveDecl(D); | ||||
2022 | auto ShadowI = ShadowingDecls.find(D); | ||||
2023 | if (ShadowI != ShadowingDecls.end()) { | ||||
2024 | if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { | ||||
2025 | Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) | ||||
2026 | << D << FD << FD->getParent(); | ||||
2027 | Diag(FD->getLocation(), diag::note_previous_declaration); | ||||
2028 | } | ||||
2029 | ShadowingDecls.erase(ShadowI); | ||||
2030 | } | ||||
2031 | } | ||||
2032 | } | ||||
2033 | |||||
2034 | /// Look for an Objective-C class in the translation unit. | ||||
2035 | /// | ||||
2036 | /// \param Id The name of the Objective-C class we're looking for. If | ||||
2037 | /// typo-correction fixes this name, the Id will be updated | ||||
2038 | /// to the fixed name. | ||||
2039 | /// | ||||
2040 | /// \param IdLoc The location of the name in the translation unit. | ||||
2041 | /// | ||||
2042 | /// \param DoTypoCorrection If true, this routine will attempt typo correction | ||||
2043 | /// if there is no class with the given name. | ||||
2044 | /// | ||||
2045 | /// \returns The declaration of the named Objective-C class, or NULL if the | ||||
2046 | /// class could not be found. | ||||
2047 | ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, | ||||
2048 | SourceLocation IdLoc, | ||||
2049 | bool DoTypoCorrection) { | ||||
2050 | // The third "scope" argument is 0 since we aren't enabling lazy built-in | ||||
2051 | // creation from this context. | ||||
2052 | NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); | ||||
2053 | |||||
2054 | if (!IDecl && DoTypoCorrection) { | ||||
2055 | // Perform typo correction at the given location, but only if we | ||||
2056 | // find an Objective-C class name. | ||||
2057 | DeclFilterCCC<ObjCInterfaceDecl> CCC{}; | ||||
2058 | if (TypoCorrection C = | ||||
2059 | CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, | ||||
2060 | TUScope, nullptr, CCC, CTK_ErrorRecovery)) { | ||||
2061 | diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); | ||||
2062 | IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); | ||||
2063 | Id = IDecl->getIdentifier(); | ||||
2064 | } | ||||
2065 | } | ||||
2066 | ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); | ||||
2067 | // This routine must always return a class definition, if any. | ||||
2068 | if (Def && Def->getDefinition()) | ||||
2069 | Def = Def->getDefinition(); | ||||
2070 | return Def; | ||||
2071 | } | ||||
2072 | |||||
2073 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting | ||||
2074 | /// from S, where a non-field would be declared. This routine copes | ||||
2075 | /// with the difference between C and C++ scoping rules in structs and | ||||
2076 | /// unions. For example, the following code is well-formed in C but | ||||
2077 | /// ill-formed in C++: | ||||
2078 | /// @code | ||||
2079 | /// struct S6 { | ||||
2080 | /// enum { BAR } e; | ||||
2081 | /// }; | ||||
2082 | /// | ||||
2083 | /// void test_S6() { | ||||
2084 | /// struct S6 a; | ||||
2085 | /// a.e = BAR; | ||||
2086 | /// } | ||||
2087 | /// @endcode | ||||
2088 | /// For the declaration of BAR, this routine will return a different | ||||
2089 | /// scope. The scope S will be the scope of the unnamed enumeration | ||||
2090 | /// within S6. In C++, this routine will return the scope associated | ||||
2091 | /// with S6, because the enumeration's scope is a transparent | ||||
2092 | /// context but structures can contain non-field names. In C, this | ||||
2093 | /// routine will return the translation unit scope, since the | ||||
2094 | /// enumeration's scope is a transparent context and structures cannot | ||||
2095 | /// contain non-field names. | ||||
2096 | Scope *Sema::getNonFieldDeclScope(Scope *S) { | ||||
2097 | while (((S->getFlags() & Scope::DeclScope) == 0) || | ||||
2098 | (S->getEntity() && S->getEntity()->isTransparentContext()) || | ||||
2099 | (S->isClassScope() && !getLangOpts().CPlusPlus)) | ||||
2100 | S = S->getParent(); | ||||
2101 | return S; | ||||
2102 | } | ||||
2103 | |||||
2104 | static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, | ||||
2105 | ASTContext::GetBuiltinTypeError Error) { | ||||
2106 | switch (Error) { | ||||
2107 | case ASTContext::GE_None: | ||||
2108 | return ""; | ||||
2109 | case ASTContext::GE_Missing_type: | ||||
2110 | return BuiltinInfo.getHeaderName(ID); | ||||
2111 | case ASTContext::GE_Missing_stdio: | ||||
2112 | return "stdio.h"; | ||||
2113 | case ASTContext::GE_Missing_setjmp: | ||||
2114 | return "setjmp.h"; | ||||
2115 | case ASTContext::GE_Missing_ucontext: | ||||
2116 | return "ucontext.h"; | ||||
2117 | } | ||||
2118 | llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "clang/lib/Sema/SemaDecl.cpp" , 2118); | ||||
2119 | } | ||||
2120 | |||||
2121 | FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, | ||||
2122 | unsigned ID, SourceLocation Loc) { | ||||
2123 | DeclContext *Parent = Context.getTranslationUnitDecl(); | ||||
2124 | |||||
2125 | if (getLangOpts().CPlusPlus) { | ||||
2126 | LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( | ||||
2127 | Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); | ||||
2128 | CLinkageDecl->setImplicit(); | ||||
2129 | Parent->addDecl(CLinkageDecl); | ||||
2130 | Parent = CLinkageDecl; | ||||
2131 | } | ||||
2132 | |||||
2133 | FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, | ||||
2134 | /*TInfo=*/nullptr, SC_Extern, | ||||
2135 | getCurFPFeatures().isFPConstrained(), | ||||
2136 | false, Type->isFunctionProtoType()); | ||||
2137 | New->setImplicit(); | ||||
2138 | New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); | ||||
2139 | |||||
2140 | // Create Decl objects for each parameter, adding them to the | ||||
2141 | // FunctionDecl. | ||||
2142 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { | ||||
2143 | SmallVector<ParmVarDecl *, 16> Params; | ||||
2144 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||
2145 | ParmVarDecl *parm = ParmVarDecl::Create( | ||||
2146 | Context, New, SourceLocation(), SourceLocation(), nullptr, | ||||
2147 | FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); | ||||
2148 | parm->setScopeInfo(0, i); | ||||
2149 | Params.push_back(parm); | ||||
2150 | } | ||||
2151 | New->setParams(Params); | ||||
2152 | } | ||||
2153 | |||||
2154 | AddKnownFunctionAttributes(New); | ||||
2155 | return New; | ||||
2156 | } | ||||
2157 | |||||
2158 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at | ||||
2159 | /// file scope. lazily create a decl for it. ForRedeclaration is true | ||||
2160 | /// if we're creating this built-in in anticipation of redeclaring the | ||||
2161 | /// built-in. | ||||
2162 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, | ||||
2163 | Scope *S, bool ForRedeclaration, | ||||
2164 | SourceLocation Loc) { | ||||
2165 | LookupNecessaryTypesForBuiltin(S, ID); | ||||
2166 | |||||
2167 | ASTContext::GetBuiltinTypeError Error; | ||||
2168 | QualType R = Context.GetBuiltinType(ID, Error); | ||||
2169 | if (Error) { | ||||
2170 | if (!ForRedeclaration) | ||||
2171 | return nullptr; | ||||
2172 | |||||
2173 | // If we have a builtin without an associated type we should not emit a | ||||
2174 | // warning when we were not able to find a type for it. | ||||
2175 | if (Error == ASTContext::GE_Missing_type || | ||||
2176 | Context.BuiltinInfo.allowTypeMismatch(ID)) | ||||
2177 | return nullptr; | ||||
2178 | |||||
2179 | // If we could not find a type for setjmp it is because the jmp_buf type was | ||||
2180 | // not defined prior to the setjmp declaration. | ||||
2181 | if (Error == ASTContext::GE_Missing_setjmp) { | ||||
2182 | Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) | ||||
2183 | << Context.BuiltinInfo.getName(ID); | ||||
2184 | return nullptr; | ||||
2185 | } | ||||
2186 | |||||
2187 | // Generally, we emit a warning that the declaration requires the | ||||
2188 | // appropriate header. | ||||
2189 | Diag(Loc, diag::warn_implicit_decl_requires_sysheader) | ||||
2190 | << getHeaderName(Context.BuiltinInfo, ID, Error) | ||||
2191 | << Context.BuiltinInfo.getName(ID); | ||||
2192 | return nullptr; | ||||
2193 | } | ||||
2194 | |||||
2195 | if (!ForRedeclaration && | ||||
2196 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || | ||||
2197 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { | ||||
2198 | Diag(Loc, diag::ext_implicit_lib_function_decl) | ||||
2199 | << Context.BuiltinInfo.getName(ID) << R; | ||||
2200 | if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) | ||||
2201 | Diag(Loc, diag::note_include_header_or_declare) | ||||
2202 | << Header << Context.BuiltinInfo.getName(ID); | ||||
2203 | } | ||||
2204 | |||||
2205 | if (R.isNull()) | ||||
2206 | return nullptr; | ||||
2207 | |||||
2208 | FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); | ||||
2209 | RegisterLocallyScopedExternCDecl(New, S); | ||||
2210 | |||||
2211 | // TUScope is the translation-unit scope to insert this function into. | ||||
2212 | // FIXME: This is hideous. We need to teach PushOnScopeChains to | ||||
2213 | // relate Scopes to DeclContexts, and probably eliminate CurContext | ||||
2214 | // entirely, but we're not there yet. | ||||
2215 | DeclContext *SavedContext = CurContext; | ||||
2216 | CurContext = New->getDeclContext(); | ||||
2217 | PushOnScopeChains(New, TUScope); | ||||
2218 | CurContext = SavedContext; | ||||
2219 | return New; | ||||
2220 | } | ||||
2221 | |||||
2222 | /// Typedef declarations don't have linkage, but they still denote the same | ||||
2223 | /// entity if their types are the same. | ||||
2224 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's | ||||
2225 | /// isSameEntity. | ||||
2226 | static void filterNonConflictingPreviousTypedefDecls(Sema &S, | ||||
2227 | TypedefNameDecl *Decl, | ||||
2228 | LookupResult &Previous) { | ||||
2229 | // This is only interesting when modules are enabled. | ||||
2230 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) | ||||
2231 | return; | ||||
2232 | |||||
2233 | // Empty sets are uninteresting. | ||||
2234 | if (Previous.empty()) | ||||
2235 | return; | ||||
2236 | |||||
2237 | LookupResult::Filter Filter = Previous.makeFilter(); | ||||
2238 | while (Filter.hasNext()) { | ||||
2239 | NamedDecl *Old = Filter.next(); | ||||
2240 | |||||
2241 | // Non-hidden declarations are never ignored. | ||||
2242 | if (S.isVisible(Old)) | ||||
2243 | continue; | ||||
2244 | |||||
2245 | // Declarations of the same entity are not ignored, even if they have | ||||
2246 | // different linkages. | ||||
2247 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | ||||
2248 | if (S.Context.hasSameType(OldTD->getUnderlyingType(), | ||||
2249 | Decl->getUnderlyingType())) | ||||
2250 | continue; | ||||
2251 | |||||
2252 | // If both declarations give a tag declaration a typedef name for linkage | ||||
2253 | // purposes, then they declare the same entity. | ||||
2254 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && | ||||
2255 | Decl->getAnonDeclWithTypedefName()) | ||||
2256 | continue; | ||||
2257 | } | ||||
2258 | |||||
2259 | Filter.erase(); | ||||
2260 | } | ||||
2261 | |||||
2262 | Filter.done(); | ||||
2263 | } | ||||
2264 | |||||
2265 | bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { | ||||
2266 | QualType OldType; | ||||
2267 | if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) | ||||
2268 | OldType = OldTypedef->getUnderlyingType(); | ||||
2269 | else | ||||
2270 | OldType = Context.getTypeDeclType(Old); | ||||
2271 | QualType NewType = New->getUnderlyingType(); | ||||
2272 | |||||
2273 | if (NewType->isVariablyModifiedType()) { | ||||
2274 | // Must not redefine a typedef with a variably-modified type. | ||||
2275 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | ||||
2276 | Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) | ||||
2277 | << Kind << NewType; | ||||
2278 | if (Old->getLocation().isValid()) | ||||
2279 | notePreviousDefinition(Old, New->getLocation()); | ||||
2280 | New->setInvalidDecl(); | ||||
2281 | return true; | ||||
2282 | } | ||||
2283 | |||||
2284 | if (OldType != NewType && | ||||
2285 | !OldType->isDependentType() && | ||||
2286 | !NewType->isDependentType() && | ||||
2287 | !Context.hasSameType(OldType, NewType)) { | ||||
2288 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | ||||
2289 | Diag(New->getLocation(), diag::err_redefinition_different_typedef) | ||||
2290 | << Kind << NewType << OldType; | ||||
2291 | if (Old->getLocation().isValid()) | ||||
2292 | notePreviousDefinition(Old, New->getLocation()); | ||||
2293 | New->setInvalidDecl(); | ||||
2294 | return true; | ||||
2295 | } | ||||
2296 | return false; | ||||
2297 | } | ||||
2298 | |||||
2299 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the | ||||
2300 | /// same name and scope as a previous declaration 'Old'. Figure out | ||||
2301 | /// how to resolve this situation, merging decls or emitting | ||||
2302 | /// diagnostics as appropriate. If there was an error, set New to be invalid. | ||||
2303 | /// | ||||
2304 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, | ||||
2305 | LookupResult &OldDecls) { | ||||
2306 | // If the new decl is known invalid already, don't bother doing any | ||||
2307 | // merging checks. | ||||
2308 | if (New->isInvalidDecl()) return; | ||||
2309 | |||||
2310 | // Allow multiple definitions for ObjC built-in typedefs. | ||||
2311 | // FIXME: Verify the underlying types are equivalent! | ||||
2312 | if (getLangOpts().ObjC) { | ||||
2313 | const IdentifierInfo *TypeID = New->getIdentifier(); | ||||
2314 | switch (TypeID->getLength()) { | ||||
2315 | default: break; | ||||
2316 | case 2: | ||||
2317 | { | ||||
2318 | if (!TypeID->isStr("id")) | ||||
2319 | break; | ||||
2320 | QualType T = New->getUnderlyingType(); | ||||
2321 | if (!T->isPointerType()) | ||||
2322 | break; | ||||
2323 | if (!T->isVoidPointerType()) { | ||||
2324 | QualType PT = T->castAs<PointerType>()->getPointeeType(); | ||||
2325 | if (!PT->isStructureType()) | ||||
2326 | break; | ||||
2327 | } | ||||
2328 | Context.setObjCIdRedefinitionType(T); | ||||
2329 | // Install the built-in type for 'id', ignoring the current definition. | ||||
2330 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); | ||||
2331 | return; | ||||
2332 | } | ||||
2333 | case 5: | ||||
2334 | if (!TypeID->isStr("Class")) | ||||
2335 | break; | ||||
2336 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); | ||||
2337 | // Install the built-in type for 'Class', ignoring the current definition. | ||||
2338 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); | ||||
2339 | return; | ||||
2340 | case 3: | ||||
2341 | if (!TypeID->isStr("SEL")) | ||||
2342 | break; | ||||
2343 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); | ||||
2344 | // Install the built-in type for 'SEL', ignoring the current definition. | ||||
2345 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); | ||||
2346 | return; | ||||
2347 | } | ||||
2348 | // Fall through - the typedef name was not a builtin type. | ||||
2349 | } | ||||
2350 | |||||
2351 | // Verify the old decl was also a type. | ||||
2352 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); | ||||
2353 | if (!Old) { | ||||
2354 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||
2355 | << New->getDeclName(); | ||||
2356 | |||||
2357 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); | ||||
2358 | if (OldD->getLocation().isValid()) | ||||
2359 | notePreviousDefinition(OldD, New->getLocation()); | ||||
2360 | |||||
2361 | return New->setInvalidDecl(); | ||||
2362 | } | ||||
2363 | |||||
2364 | // If the old declaration is invalid, just give up here. | ||||
2365 | if (Old->isInvalidDecl()) | ||||
2366 | return New->setInvalidDecl(); | ||||
2367 | |||||
2368 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | ||||
2369 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); | ||||
2370 | auto *NewTag = New->getAnonDeclWithTypedefName(); | ||||
2371 | NamedDecl *Hidden = nullptr; | ||||
2372 | if (OldTag && NewTag && | ||||
2373 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && | ||||
2374 | !hasVisibleDefinition(OldTag, &Hidden)) { | ||||
2375 | // There is a definition of this tag, but it is not visible. Use it | ||||
2376 | // instead of our tag. | ||||
2377 | New->setTypeForDecl(OldTD->getTypeForDecl()); | ||||
2378 | if (OldTD->isModed()) | ||||
2379 | New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), | ||||
2380 | OldTD->getUnderlyingType()); | ||||
2381 | else | ||||
2382 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); | ||||
2383 | |||||
2384 | // Make the old tag definition visible. | ||||
2385 | makeMergedDefinitionVisible(Hidden); | ||||
2386 | |||||
2387 | // If this was an unscoped enumeration, yank all of its enumerators | ||||
2388 | // out of the scope. | ||||
2389 | if (isa<EnumDecl>(NewTag)) { | ||||
2390 | Scope *EnumScope = getNonFieldDeclScope(S); | ||||
2391 | for (auto *D : NewTag->decls()) { | ||||
2392 | auto *ED = cast<EnumConstantDecl>(D); | ||||
2393 | assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void (0) : __assert_fail ("EnumScope->isDeclScope(ED)", "clang/lib/Sema/SemaDecl.cpp" , 2393, __extension__ __PRETTY_FUNCTION__)); | ||||
2394 | EnumScope->RemoveDecl(ED); | ||||
2395 | IdResolver.RemoveDecl(ED); | ||||
2396 | ED->getLexicalDeclContext()->removeDecl(ED); | ||||
2397 | } | ||||
2398 | } | ||||
2399 | } | ||||
2400 | } | ||||
2401 | |||||
2402 | // If the typedef types are not identical, reject them in all languages and | ||||
2403 | // with any extensions enabled. | ||||
2404 | if (isIncompatibleTypedef(Old, New)) | ||||
2405 | return; | ||||
2406 | |||||
2407 | // The types match. Link up the redeclaration chain and merge attributes if | ||||
2408 | // the old declaration was a typedef. | ||||
2409 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { | ||||
2410 | New->setPreviousDecl(Typedef); | ||||
2411 | mergeDeclAttributes(New, Old); | ||||
2412 | } | ||||
2413 | |||||
2414 | if (getLangOpts().MicrosoftExt) | ||||
2415 | return; | ||||
2416 | |||||
2417 | if (getLangOpts().CPlusPlus) { | ||||
2418 | // C++ [dcl.typedef]p2: | ||||
2419 | // In a given non-class scope, a typedef specifier can be used to | ||||
2420 | // redefine the name of any type declared in that scope to refer | ||||
2421 | // to the type to which it already refers. | ||||
2422 | if (!isa<CXXRecordDecl>(CurContext)) | ||||
2423 | return; | ||||
2424 | |||||
2425 | // C++0x [dcl.typedef]p4: | ||||
2426 | // In a given class scope, a typedef specifier can be used to redefine | ||||
2427 | // any class-name declared in that scope that is not also a typedef-name | ||||
2428 | // to refer to the type to which it already refers. | ||||
2429 | // | ||||
2430 | // This wording came in via DR424, which was a correction to the | ||||
2431 | // wording in DR56, which accidentally banned code like: | ||||
2432 | // | ||||
2433 | // struct S { | ||||
2434 | // typedef struct A { } A; | ||||
2435 | // }; | ||||
2436 | // | ||||
2437 | // in the C++03 standard. We implement the C++0x semantics, which | ||||
2438 | // allow the above but disallow | ||||
2439 | // | ||||
2440 | // struct S { | ||||
2441 | // typedef int I; | ||||
2442 | // typedef int I; | ||||
2443 | // }; | ||||
2444 | // | ||||
2445 | // since that was the intent of DR56. | ||||
2446 | if (!isa<TypedefNameDecl>(Old)) | ||||
2447 | return; | ||||
2448 | |||||
2449 | Diag(New->getLocation(), diag::err_redefinition) | ||||
2450 | << New->getDeclName(); | ||||
2451 | notePreviousDefinition(Old, New->getLocation()); | ||||
2452 | return New->setInvalidDecl(); | ||||
2453 | } | ||||
2454 | |||||
2455 | // Modules always permit redefinition of typedefs, as does C11. | ||||
2456 | if (getLangOpts().Modules || getLangOpts().C11) | ||||
2457 | return; | ||||
2458 | |||||
2459 | // If we have a redefinition of a typedef in C, emit a warning. This warning | ||||
2460 | // is normally mapped to an error, but can be controlled with | ||||
2461 | // -Wtypedef-redefinition. If either the original or the redefinition is | ||||
2462 | // in a system header, don't emit this for compatibility with GCC. | ||||
2463 | if (getDiagnostics().getSuppressSystemWarnings() && | ||||
2464 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). | ||||
2465 | (Old->isImplicit() || | ||||
2466 | Context.getSourceManager().isInSystemHeader(Old->getLocation()) || | ||||
2467 | Context.getSourceManager().isInSystemHeader(New->getLocation()))) | ||||
2468 | return; | ||||
2469 | |||||
2470 | Diag(New->getLocation(), diag::ext_redefinition_of_typedef) | ||||
2471 | << New->getDeclName(); | ||||
2472 | notePreviousDefinition(Old, New->getLocation()); | ||||
2473 | } | ||||
2474 | |||||
2475 | /// DeclhasAttr - returns true if decl Declaration already has the target | ||||
2476 | /// attribute. | ||||
2477 | static bool DeclHasAttr(const Decl *D, const Attr *A) { | ||||
2478 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); | ||||
2479 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); | ||||
2480 | for (const auto *i : D->attrs()) | ||||
2481 | if (i->getKind() == A->getKind()) { | ||||
2482 | if (Ann) { | ||||
2483 | if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) | ||||
2484 | return true; | ||||
2485 | continue; | ||||
2486 | } | ||||
2487 | // FIXME: Don't hardcode this check | ||||
2488 | if (OA && isa<OwnershipAttr>(i)) | ||||
2489 | return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); | ||||
2490 | return true; | ||||
2491 | } | ||||
2492 | |||||
2493 | return false; | ||||
2494 | } | ||||
2495 | |||||
2496 | static bool isAttributeTargetADefinition(Decl *D) { | ||||
2497 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||
2498 | return VD->isThisDeclarationADefinition(); | ||||
2499 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) | ||||
2500 | return TD->isCompleteDefinition() || TD->isBeingDefined(); | ||||
2501 | return true; | ||||
2502 | } | ||||
2503 | |||||
2504 | /// Merge alignment attributes from \p Old to \p New, taking into account the | ||||
2505 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. | ||||
2506 | /// | ||||
2507 | /// \return \c true if any attributes were added to \p New. | ||||
2508 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { | ||||
2509 | // Look for alignas attributes on Old, and pick out whichever attribute | ||||
2510 | // specifies the strictest alignment requirement. | ||||
2511 | AlignedAttr *OldAlignasAttr = nullptr; | ||||
2512 | AlignedAttr *OldStrictestAlignAttr = nullptr; | ||||
2513 | unsigned OldAlign = 0; | ||||
2514 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { | ||||
2515 | // FIXME: We have no way of representing inherited dependent alignments | ||||
2516 | // in a case like: | ||||
2517 | // template<int A, int B> struct alignas(A) X; | ||||
2518 | // template<int A, int B> struct alignas(B) X {}; | ||||
2519 | // For now, we just ignore any alignas attributes which are not on the | ||||
2520 | // definition in such a case. | ||||
2521 | if (I->isAlignmentDependent()) | ||||
2522 | return false; | ||||
2523 | |||||
2524 | if (I->isAlignas()) | ||||
2525 | OldAlignasAttr = I; | ||||
2526 | |||||
2527 | unsigned Align = I->getAlignment(S.Context); | ||||
2528 | if (Align > OldAlign) { | ||||
2529 | OldAlign = Align; | ||||
2530 | OldStrictestAlignAttr = I; | ||||
2531 | } | ||||
2532 | } | ||||
2533 | |||||
2534 | // Look for alignas attributes on New. | ||||
2535 | AlignedAttr *NewAlignasAttr = nullptr; | ||||
2536 | unsigned NewAlign = 0; | ||||
2537 | for (auto *I : New->specific_attrs<AlignedAttr>()) { | ||||
2538 | if (I->isAlignmentDependent()) | ||||
2539 | return false; | ||||
2540 | |||||
2541 | if (I->isAlignas()) | ||||
2542 | NewAlignasAttr = I; | ||||
2543 | |||||
2544 | unsigned Align = I->getAlignment(S.Context); | ||||
2545 | if (Align > NewAlign) | ||||
2546 | NewAlign = Align; | ||||
2547 | } | ||||
2548 | |||||
2549 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { | ||||
2550 | // Both declarations have 'alignas' attributes. We require them to match. | ||||
2551 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but | ||||
2552 | // fall short. (If two declarations both have alignas, they must both match | ||||
2553 | // every definition, and so must match each other if there is a definition.) | ||||
2554 | |||||
2555 | // If either declaration only contains 'alignas(0)' specifiers, then it | ||||
2556 | // specifies the natural alignment for the type. | ||||
2557 | if (OldAlign == 0 || NewAlign == 0) { | ||||
2558 | QualType Ty; | ||||
2559 | if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) | ||||
2560 | Ty = VD->getType(); | ||||
2561 | else | ||||
2562 | Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); | ||||
2563 | |||||
2564 | if (OldAlign == 0) | ||||
2565 | OldAlign = S.Context.getTypeAlign(Ty); | ||||
2566 | if (NewAlign == 0) | ||||
2567 | NewAlign = S.Context.getTypeAlign(Ty); | ||||
2568 | } | ||||
2569 | |||||
2570 | if (OldAlign != NewAlign) { | ||||
2571 | S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) | ||||
2572 | << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() | ||||
2573 | << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); | ||||
2574 | S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); | ||||
2575 | } | ||||
2576 | } | ||||
2577 | |||||
2578 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { | ||||
2579 | // C++11 [dcl.align]p6: | ||||
2580 | // if any declaration of an entity has an alignment-specifier, | ||||
2581 | // every defining declaration of that entity shall specify an | ||||
2582 | // equivalent alignment. | ||||
2583 | // C11 6.7.5/7: | ||||
2584 | // If the definition of an object does not have an alignment | ||||
2585 | // specifier, any other declaration of that object shall also | ||||
2586 | // have no alignment specifier. | ||||
2587 | S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) | ||||
2588 | << OldAlignasAttr; | ||||
2589 | S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) | ||||
2590 | << OldAlignasAttr; | ||||
2591 | } | ||||
2592 | |||||
2593 | bool AnyAdded = false; | ||||
2594 | |||||
2595 | // Ensure we have an attribute representing the strictest alignment. | ||||
2596 | if (OldAlign > NewAlign) { | ||||
2597 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); | ||||
2598 | Clone->setInherited(true); | ||||
2599 | New->addAttr(Clone); | ||||
2600 | AnyAdded = true; | ||||
2601 | } | ||||
2602 | |||||
2603 | // Ensure we have an alignas attribute if the old declaration had one. | ||||
2604 | if (OldAlignasAttr && !NewAlignasAttr && | ||||
2605 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { | ||||
2606 | AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); | ||||
2607 | Clone->setInherited(true); | ||||
2608 | New->addAttr(Clone); | ||||
2609 | AnyAdded = true; | ||||
2610 | } | ||||
2611 | |||||
2612 | return AnyAdded; | ||||
2613 | } | ||||
2614 | |||||
2615 | #define WANT_DECL_MERGE_LOGIC | ||||
2616 | #include "clang/Sema/AttrParsedAttrImpl.inc" | ||||
2617 | #undef WANT_DECL_MERGE_LOGIC | ||||
2618 | |||||
2619 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, | ||||
2620 | const InheritableAttr *Attr, | ||||
2621 | Sema::AvailabilityMergeKind AMK) { | ||||
2622 | // Diagnose any mutual exclusions between the attribute that we want to add | ||||
2623 | // and attributes that already exist on the declaration. | ||||
2624 | if (!DiagnoseMutualExclusions(S, D, Attr)) | ||||
2625 | return false; | ||||
2626 | |||||
2627 | // This function copies an attribute Attr from a previous declaration to the | ||||
2628 | // new declaration D if the new declaration doesn't itself have that attribute | ||||
2629 | // yet or if that attribute allows duplicates. | ||||
2630 | // If you're adding a new attribute that requires logic different from | ||||
2631 | // "use explicit attribute on decl if present, else use attribute from | ||||
2632 | // previous decl", for example if the attribute needs to be consistent | ||||
2633 | // between redeclarations, you need to call a custom merge function here. | ||||
2634 | InheritableAttr *NewAttr = nullptr; | ||||
2635 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) | ||||
2636 | NewAttr = S.mergeAvailabilityAttr( | ||||
2637 | D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), | ||||
2638 | AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), | ||||
2639 | AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, | ||||
2640 | AA->getPriority()); | ||||
2641 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) | ||||
2642 | NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); | ||||
2643 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) | ||||
2644 | NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); | ||||
2645 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) | ||||
2646 | NewAttr = S.mergeDLLImportAttr(D, *ImportA); | ||||
2647 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) | ||||
2648 | NewAttr = S.mergeDLLExportAttr(D, *ExportA); | ||||
2649 | else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) | ||||
2650 | NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); | ||||
2651 | else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) | ||||
2652 | NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), | ||||
2653 | FA->getFirstArg()); | ||||
2654 | else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) | ||||
2655 | NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); | ||||
2656 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) | ||||
2657 | NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); | ||||
2658 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) | ||||
2659 | NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), | ||||
2660 | IA->getInheritanceModel()); | ||||
2661 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) | ||||
2662 | NewAttr = S.mergeAlwaysInlineAttr(D, *AA, | ||||
2663 | &S.Context.Idents.get(AA->getSpelling())); | ||||
2664 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && | ||||
2665 | (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || | ||||
2666 | isa<CUDAGlobalAttr>(Attr))) { | ||||
2667 | // CUDA target attributes are part of function signature for | ||||
2668 | // overloading purposes and must not be merged. | ||||
2669 | return false; | ||||
2670 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) | ||||
2671 | NewAttr = S.mergeMinSizeAttr(D, *MA); | ||||
2672 | else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) | ||||
2673 | NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); | ||||
2674 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) | ||||
2675 | NewAttr = S.mergeOptimizeNoneAttr(D, *OA); | ||||
2676 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) | ||||
2677 | NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); | ||||
2678 | else if (isa<AlignedAttr>(Attr)) | ||||
2679 | // AlignedAttrs are handled separately, because we need to handle all | ||||
2680 | // such attributes on a declaration at the same time. | ||||
2681 | NewAttr = nullptr; | ||||
2682 | else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && | ||||
2683 | (AMK == Sema::AMK_Override || | ||||
2684 | AMK == Sema::AMK_ProtocolImplementation || | ||||
2685 | AMK == Sema::AMK_OptionalProtocolImplementation)) | ||||
2686 | NewAttr = nullptr; | ||||
2687 | else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) | ||||
2688 | NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); | ||||
2689 | else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) | ||||
2690 | NewAttr = S.mergeImportModuleAttr(D, *IMA); | ||||
2691 | else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) | ||||
2692 | NewAttr = S.mergeImportNameAttr(D, *INA); | ||||
2693 | else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) | ||||
2694 | NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); | ||||
2695 | else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) | ||||
2696 | NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); | ||||
2697 | else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) | ||||
2698 | NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); | ||||
2699 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) | ||||
2700 | NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); | ||||
2701 | |||||
2702 | if (NewAttr) { | ||||
2703 | NewAttr->setInherited(true); | ||||
2704 | D->addAttr(NewAttr); | ||||
2705 | if (isa<MSInheritanceAttr>(NewAttr)) | ||||
2706 | S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); | ||||
2707 | return true; | ||||
2708 | } | ||||
2709 | |||||
2710 | return false; | ||||
2711 | } | ||||
2712 | |||||
2713 | static const NamedDecl *getDefinition(const Decl *D) { | ||||
2714 | if (const TagDecl *TD = dyn_cast<TagDecl>(D)) | ||||
2715 | return TD->getDefinition(); | ||||
2716 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
2717 | const VarDecl *Def = VD->getDefinition(); | ||||
2718 | if (Def) | ||||
2719 | return Def; | ||||
2720 | return VD->getActingDefinition(); | ||||
2721 | } | ||||
2722 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
2723 | const FunctionDecl *Def = nullptr; | ||||
2724 | if (FD->isDefined(Def, true)) | ||||
2725 | return Def; | ||||
2726 | } | ||||
2727 | return nullptr; | ||||
2728 | } | ||||
2729 | |||||
2730 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { | ||||
2731 | for (const auto *Attribute : D->attrs()) | ||||
2732 | if (Attribute->getKind() == Kind) | ||||
2733 | return true; | ||||
2734 | return false; | ||||
2735 | } | ||||
2736 | |||||
2737 | /// checkNewAttributesAfterDef - If we already have a definition, check that | ||||
2738 | /// there are no new attributes in this declaration. | ||||
2739 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { | ||||
2740 | if (!New->hasAttrs()) | ||||
2741 | return; | ||||
2742 | |||||
2743 | const NamedDecl *Def = getDefinition(Old); | ||||
2744 | if (!Def || Def == New) | ||||
2745 | return; | ||||
2746 | |||||
2747 | AttrVec &NewAttributes = New->getAttrs(); | ||||
2748 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { | ||||
2749 | const Attr *NewAttribute = NewAttributes[I]; | ||||
2750 | |||||
2751 | if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { | ||||
2752 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { | ||||
2753 | Sema::SkipBodyInfo SkipBody; | ||||
2754 | S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); | ||||
2755 | |||||
2756 | // If we're skipping this definition, drop the "alias" attribute. | ||||
2757 | if (SkipBody.ShouldSkip) { | ||||
2758 | NewAttributes.erase(NewAttributes.begin() + I); | ||||
2759 | --E; | ||||
2760 | continue; | ||||
2761 | } | ||||
2762 | } else { | ||||
2763 | VarDecl *VD = cast<VarDecl>(New); | ||||
2764 | unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == | ||||
2765 | VarDecl::TentativeDefinition | ||||
2766 | ? diag::err_alias_after_tentative | ||||
2767 | : diag::err_redefinition; | ||||
2768 | S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); | ||||
2769 | if (Diag == diag::err_redefinition) | ||||
2770 | S.notePreviousDefinition(Def, VD->getLocation()); | ||||
2771 | else | ||||
2772 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||
2773 | VD->setInvalidDecl(); | ||||
2774 | } | ||||
2775 | ++I; | ||||
2776 | continue; | ||||
2777 | } | ||||
2778 | |||||
2779 | if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { | ||||
2780 | // Tentative definitions are only interesting for the alias check above. | ||||
2781 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { | ||||
2782 | ++I; | ||||
2783 | continue; | ||||
2784 | } | ||||
2785 | } | ||||
2786 | |||||
2787 | if (hasAttribute(Def, NewAttribute->getKind())) { | ||||
2788 | ++I; | ||||
2789 | continue; // regular attr merging will take care of validating this. | ||||
2790 | } | ||||
2791 | |||||
2792 | if (isa<C11NoReturnAttr>(NewAttribute)) { | ||||
2793 | // C's _Noreturn is allowed to be added to a function after it is defined. | ||||
2794 | ++I; | ||||
2795 | continue; | ||||
2796 | } else if (isa<UuidAttr>(NewAttribute)) { | ||||
2797 | // msvc will allow a subsequent definition to add an uuid to a class | ||||
2798 | ++I; | ||||
2799 | continue; | ||||
2800 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { | ||||
2801 | if (AA->isAlignas()) { | ||||
2802 | // C++11 [dcl.align]p6: | ||||
2803 | // if any declaration of an entity has an alignment-specifier, | ||||
2804 | // every defining declaration of that entity shall specify an | ||||
2805 | // equivalent alignment. | ||||
2806 | // C11 6.7.5/7: | ||||
2807 | // If the definition of an object does not have an alignment | ||||
2808 | // specifier, any other declaration of that object shall also | ||||
2809 | // have no alignment specifier. | ||||
2810 | S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) | ||||
2811 | << AA; | ||||
2812 | S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) | ||||
2813 | << AA; | ||||
2814 | NewAttributes.erase(NewAttributes.begin() + I); | ||||
2815 | --E; | ||||
2816 | continue; | ||||
2817 | } | ||||
2818 | } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { | ||||
2819 | // If there is a C definition followed by a redeclaration with this | ||||
2820 | // attribute then there are two different definitions. In C++, prefer the | ||||
2821 | // standard diagnostics. | ||||
2822 | if (!S.getLangOpts().CPlusPlus) { | ||||
2823 | S.Diag(NewAttribute->getLocation(), | ||||
2824 | diag::err_loader_uninitialized_redeclaration); | ||||
2825 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||
2826 | NewAttributes.erase(NewAttributes.begin() + I); | ||||
2827 | --E; | ||||
2828 | continue; | ||||
2829 | } | ||||
2830 | } else if (isa<SelectAnyAttr>(NewAttribute) && | ||||
2831 | cast<VarDecl>(New)->isInline() && | ||||
2832 | !cast<VarDecl>(New)->isInlineSpecified()) { | ||||
2833 | // Don't warn about applying selectany to implicitly inline variables. | ||||
2834 | // Older compilers and language modes would require the use of selectany | ||||
2835 | // to make such variables inline, and it would have no effect if we | ||||
2836 | // honored it. | ||||
2837 | ++I; | ||||
2838 | continue; | ||||
2839 | } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { | ||||
2840 | // We allow to add OMP[Begin]DeclareVariantAttr to be added to | ||||
2841 | // declarations after defintions. | ||||
2842 | ++I; | ||||
2843 | continue; | ||||
2844 | } | ||||
2845 | |||||
2846 | S.Diag(NewAttribute->getLocation(), | ||||
2847 | diag::warn_attribute_precede_definition); | ||||
2848 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||
2849 | NewAttributes.erase(NewAttributes.begin() + I); | ||||
2850 | --E; | ||||
2851 | } | ||||
2852 | } | ||||
2853 | |||||
2854 | static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, | ||||
2855 | const ConstInitAttr *CIAttr, | ||||
2856 | bool AttrBeforeInit) { | ||||
2857 | SourceLocation InsertLoc = InitDecl->getInnerLocStart(); | ||||
2858 | |||||
2859 | // Figure out a good way to write this specifier on the old declaration. | ||||
2860 | // FIXME: We should just use the spelling of CIAttr, but we don't preserve | ||||
2861 | // enough of the attribute list spelling information to extract that without | ||||
2862 | // heroics. | ||||
2863 | std::string SuitableSpelling; | ||||
2864 | if (S.getLangOpts().CPlusPlus20) | ||||
2865 | SuitableSpelling = std::string( | ||||
2866 | S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); | ||||
2867 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | ||||
2868 | SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( | ||||
2869 | InsertLoc, {tok::l_square, tok::l_square, | ||||
2870 | S.PP.getIdentifierInfo("clang"), tok::coloncolon, | ||||
2871 | S.PP.getIdentifierInfo("require_constant_initialization"), | ||||
2872 | tok::r_square, tok::r_square})); | ||||
2873 | if (SuitableSpelling.empty()) | ||||
2874 | SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( | ||||
2875 | InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, | ||||
2876 | S.PP.getIdentifierInfo("require_constant_initialization"), | ||||
2877 | tok::r_paren, tok::r_paren})); | ||||
2878 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) | ||||
2879 | SuitableSpelling = "constinit"; | ||||
2880 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | ||||
2881 | SuitableSpelling = "[[clang::require_constant_initialization]]"; | ||||
2882 | if (SuitableSpelling.empty()) | ||||
2883 | SuitableSpelling = "__attribute__((require_constant_initialization))"; | ||||
2884 | SuitableSpelling += " "; | ||||
2885 | |||||
2886 | if (AttrBeforeInit) { | ||||
2887 | // extern constinit int a; | ||||
2888 | // int a = 0; // error (missing 'constinit'), accepted as extension | ||||
2889 | assert(CIAttr->isConstinit() && "should not diagnose this for attribute")(static_cast <bool> (CIAttr->isConstinit() && "should not diagnose this for attribute") ? void (0) : __assert_fail ("CIAttr->isConstinit() && \"should not diagnose this for attribute\"" , "clang/lib/Sema/SemaDecl.cpp", 2889, __extension__ __PRETTY_FUNCTION__ )); | ||||
2890 | S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) | ||||
2891 | << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | ||||
2892 | S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); | ||||
2893 | } else { | ||||
2894 | // int a = 0; | ||||
2895 | // constinit extern int a; // error (missing 'constinit') | ||||
2896 | S.Diag(CIAttr->getLocation(), | ||||
2897 | CIAttr->isConstinit() ? diag::err_constinit_added_too_late | ||||
2898 | : diag::warn_require_const_init_added_too_late) | ||||
2899 | << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); | ||||
2900 | S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) | ||||
2901 | << CIAttr->isConstinit() | ||||
2902 | << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | ||||
2903 | } | ||||
2904 | } | ||||
2905 | |||||
2906 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. | ||||
2907 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, | ||||
2908 | AvailabilityMergeKind AMK) { | ||||
2909 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { | ||||
2910 | UsedAttr *NewAttr = OldAttr->clone(Context); | ||||
2911 | NewAttr->setInherited(true); | ||||
2912 | New->addAttr(NewAttr); | ||||
2913 | } | ||||
2914 | if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { | ||||
2915 | RetainAttr *NewAttr = OldAttr->clone(Context); | ||||
2916 | NewAttr->setInherited(true); | ||||
2917 | New->addAttr(NewAttr); | ||||
2918 | } | ||||
2919 | |||||
2920 | if (!Old->hasAttrs() && !New->hasAttrs()) | ||||
2921 | return; | ||||
2922 | |||||
2923 | // [dcl.constinit]p1: | ||||
2924 | // If the [constinit] specifier is applied to any declaration of a | ||||
2925 | // variable, it shall be applied to the initializing declaration. | ||||
2926 | const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); | ||||
2927 | const auto *NewConstInit = New->getAttr<ConstInitAttr>(); | ||||
2928 | if (bool(OldConstInit) != bool(NewConstInit)) { | ||||
2929 | const auto *OldVD = cast<VarDecl>(Old); | ||||
2930 | auto *NewVD = cast<VarDecl>(New); | ||||
2931 | |||||
2932 | // Find the initializing declaration. Note that we might not have linked | ||||
2933 | // the new declaration into the redeclaration chain yet. | ||||
2934 | const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); | ||||
2935 | if (!InitDecl && | ||||
2936 | (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) | ||||
2937 | InitDecl = NewVD; | ||||
2938 | |||||
2939 | if (InitDecl == NewVD) { | ||||
2940 | // This is the initializing declaration. If it would inherit 'constinit', | ||||
2941 | // that's ill-formed. (Note that we do not apply this to the attribute | ||||
2942 | // form). | ||||
2943 | if (OldConstInit && OldConstInit->isConstinit()) | ||||
2944 | diagnoseMissingConstinit(*this, NewVD, OldConstInit, | ||||
2945 | /*AttrBeforeInit=*/true); | ||||
2946 | } else if (NewConstInit) { | ||||
2947 | // This is the first time we've been told that this declaration should | ||||
2948 | // have a constant initializer. If we already saw the initializing | ||||
2949 | // declaration, this is too late. | ||||
2950 | if (InitDecl && InitDecl != NewVD) { | ||||
2951 | diagnoseMissingConstinit(*this, InitDecl, NewConstInit, | ||||
2952 | /*AttrBeforeInit=*/false); | ||||
2953 | NewVD->dropAttr<ConstInitAttr>(); | ||||
2954 | } | ||||
2955 | } | ||||
2956 | } | ||||
2957 | |||||
2958 | // Attributes declared post-definition are currently ignored. | ||||
2959 | checkNewAttributesAfterDef(*this, New, Old); | ||||
2960 | |||||
2961 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { | ||||
2962 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { | ||||
2963 | if (!OldA->isEquivalent(NewA)) { | ||||
2964 | // This redeclaration changes __asm__ label. | ||||
2965 | Diag(New->getLocation(), diag::err_different_asm_label); | ||||
2966 | Diag(OldA->getLocation(), diag::note_previous_declaration); | ||||
2967 | } | ||||
2968 | } else if (Old->isUsed()) { | ||||
2969 | // This redeclaration adds an __asm__ label to a declaration that has | ||||
2970 | // already been ODR-used. | ||||
2971 | Diag(New->getLocation(), diag::err_late_asm_label_name) | ||||
2972 | << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); | ||||
2973 | } | ||||
2974 | } | ||||
2975 | |||||
2976 | // Re-declaration cannot add abi_tag's. | ||||
2977 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { | ||||
2978 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { | ||||
2979 | for (const auto &NewTag : NewAbiTagAttr->tags()) { | ||||
2980 | if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { | ||||
2981 | Diag(NewAbiTagAttr->getLocation(), | ||||
2982 | diag::err_new_abi_tag_on_redeclaration) | ||||
2983 | << NewTag; | ||||
2984 | Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); | ||||
2985 | } | ||||
2986 | } | ||||
2987 | } else { | ||||
2988 | Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); | ||||
2989 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
2990 | } | ||||
2991 | } | ||||
2992 | |||||
2993 | // This redeclaration adds a section attribute. | ||||
2994 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { | ||||
2995 | if (auto *VD = dyn_cast<VarDecl>(New)) { | ||||
2996 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { | ||||
2997 | Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); | ||||
2998 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
2999 | } | ||||
3000 | } | ||||
3001 | } | ||||
3002 | |||||
3003 | // Redeclaration adds code-seg attribute. | ||||
3004 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); | ||||
3005 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && | ||||
3006 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { | ||||
3007 | Diag(New->getLocation(), diag::warn_mismatched_section) | ||||
3008 | << 0 /*codeseg*/; | ||||
3009 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
3010 | } | ||||
3011 | |||||
3012 | if (!Old->hasAttrs()) | ||||
3013 | return; | ||||
3014 | |||||
3015 | bool foundAny = New->hasAttrs(); | ||||
3016 | |||||
3017 | // Ensure that any moving of objects within the allocated map is done before | ||||
3018 | // we process them. | ||||
3019 | if (!foundAny) New->setAttrs(AttrVec()); | ||||
3020 | |||||
3021 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { | ||||
3022 | // Ignore deprecated/unavailable/availability attributes if requested. | ||||
3023 | AvailabilityMergeKind LocalAMK = AMK_None; | ||||
3024 | if (isa<DeprecatedAttr>(I) || | ||||
3025 | isa<UnavailableAttr>(I) || | ||||
3026 | isa<AvailabilityAttr>(I)) { | ||||
3027 | switch (AMK) { | ||||
3028 | case AMK_None: | ||||
3029 | continue; | ||||
3030 | |||||
3031 | case AMK_Redeclaration: | ||||
3032 | case AMK_Override: | ||||
3033 | case AMK_ProtocolImplementation: | ||||
3034 | case AMK_OptionalProtocolImplementation: | ||||
3035 | LocalAMK = AMK; | ||||
3036 | break; | ||||
3037 | } | ||||
3038 | } | ||||
3039 | |||||
3040 | // Already handled. | ||||
3041 | if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) | ||||
3042 | continue; | ||||
3043 | |||||
3044 | if (mergeDeclAttribute(*this, New, I, LocalAMK)) | ||||
3045 | foundAny = true; | ||||
3046 | } | ||||
3047 | |||||
3048 | if (mergeAlignedAttrs(*this, New, Old)) | ||||
3049 | foundAny = true; | ||||
3050 | |||||
3051 | if (!foundAny) New->dropAttrs(); | ||||
3052 | } | ||||
3053 | |||||
3054 | /// mergeParamDeclAttributes - Copy attributes from the old parameter | ||||
3055 | /// to the new one. | ||||
3056 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, | ||||
3057 | const ParmVarDecl *oldDecl, | ||||
3058 | Sema &S) { | ||||
3059 | // C++11 [dcl.attr.depend]p2: | ||||
3060 | // The first declaration of a function shall specify the | ||||
3061 | // carries_dependency attribute for its declarator-id if any declaration | ||||
3062 | // of the function specifies the carries_dependency attribute. | ||||
3063 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); | ||||
3064 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { | ||||
3065 | S.Diag(CDA->getLocation(), | ||||
3066 | diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; | ||||
3067 | // Find the first declaration of the parameter. | ||||
3068 | // FIXME: Should we build redeclaration chains for function parameters? | ||||
3069 | const FunctionDecl *FirstFD = | ||||
3070 | cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); | ||||
3071 | const ParmVarDecl *FirstVD = | ||||
3072 | FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); | ||||
3073 | S.Diag(FirstVD->getLocation(), | ||||
3074 | diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; | ||||
3075 | } | ||||
3076 | |||||
3077 | if (!oldDecl->hasAttrs()) | ||||
3078 | return; | ||||
3079 | |||||
3080 | bool foundAny = newDecl->hasAttrs(); | ||||
3081 | |||||
3082 | // Ensure that any moving of objects within the allocated map is | ||||
3083 | // done before we process them. | ||||
3084 | if (!foundAny) newDecl->setAttrs(AttrVec()); | ||||
3085 | |||||
3086 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { | ||||
3087 | if (!DeclHasAttr(newDecl, I)) { | ||||
3088 | InheritableAttr *newAttr = | ||||
3089 | cast<InheritableParamAttr>(I->clone(S.Context)); | ||||
3090 | newAttr->setInherited(true); | ||||
3091 | newDecl->addAttr(newAttr); | ||||
3092 | foundAny = true; | ||||
3093 | } | ||||
3094 | } | ||||
3095 | |||||
3096 | if (!foundAny) newDecl->dropAttrs(); | ||||
3097 | } | ||||
3098 | |||||
3099 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, | ||||
3100 | const ParmVarDecl *OldParam, | ||||
3101 | Sema &S) { | ||||
3102 | if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { | ||||
3103 | if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { | ||||
3104 | if (*Oldnullability != *Newnullability) { | ||||
3105 | S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) | ||||
3106 | << DiagNullabilityKind( | ||||
3107 | *Newnullability, | ||||
3108 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | ||||
3109 | != 0)) | ||||
3110 | << DiagNullabilityKind( | ||||
3111 | *Oldnullability, | ||||
3112 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | ||||
3113 | != 0)); | ||||
3114 | S.Diag(OldParam->getLocation(), diag::note_previous_declaration); | ||||
3115 | } | ||||
3116 | } else { | ||||
3117 | QualType NewT = NewParam->getType(); | ||||
3118 | NewT = S.Context.getAttributedType( | ||||
3119 | AttributedType::getNullabilityAttrKind(*Oldnullability), | ||||
3120 | NewT, NewT); | ||||
3121 | NewParam->setType(NewT); | ||||
3122 | } | ||||
3123 | } | ||||
3124 | } | ||||
3125 | |||||
3126 | namespace { | ||||
3127 | |||||
3128 | /// Used in MergeFunctionDecl to keep track of function parameters in | ||||
3129 | /// C. | ||||
3130 | struct GNUCompatibleParamWarning { | ||||
3131 | ParmVarDecl *OldParm; | ||||
3132 | ParmVarDecl *NewParm; | ||||
3133 | QualType PromotedType; | ||||
3134 | }; | ||||
3135 | |||||
3136 | } // end anonymous namespace | ||||
3137 | |||||
3138 | // Determine whether the previous declaration was a definition, implicit | ||||
3139 | // declaration, or a declaration. | ||||
3140 | template <typename T> | ||||
3141 | static std::pair<diag::kind, SourceLocation> | ||||
3142 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { | ||||
3143 | diag::kind PrevDiag; | ||||
3144 | SourceLocation OldLocation = Old->getLocation(); | ||||
3145 | if (Old->isThisDeclarationADefinition()) | ||||
3146 | PrevDiag = diag::note_previous_definition; | ||||
3147 | else if (Old->isImplicit()) { | ||||
3148 | PrevDiag = diag::note_previous_implicit_declaration; | ||||
3149 | if (OldLocation.isInvalid()) | ||||
3150 | OldLocation = New->getLocation(); | ||||
3151 | } else | ||||
3152 | PrevDiag = diag::note_previous_declaration; | ||||
3153 | return std::make_pair(PrevDiag, OldLocation); | ||||
3154 | } | ||||
3155 | |||||
3156 | /// canRedefineFunction - checks if a function can be redefined. Currently, | ||||
3157 | /// only extern inline functions can be redefined, and even then only in | ||||
3158 | /// GNU89 mode. | ||||
3159 | static bool canRedefineFunction(const FunctionDecl *FD, | ||||
3160 | const LangOptions& LangOpts) { | ||||
3161 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && | ||||
3162 | !LangOpts.CPlusPlus && | ||||
3163 | FD->isInlineSpecified() && | ||||
3164 | FD->getStorageClass() == SC_Extern); | ||||
3165 | } | ||||
3166 | |||||
3167 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { | ||||
3168 | const AttributedType *AT = T->getAs<AttributedType>(); | ||||
3169 | while (AT && !AT->isCallingConv()) | ||||
3170 | AT = AT->getModifiedType()->getAs<AttributedType>(); | ||||
3171 | return AT; | ||||
3172 | } | ||||
3173 | |||||
3174 | template <typename T> | ||||
3175 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { | ||||
3176 | const DeclContext *DC = Old->getDeclContext(); | ||||
3177 | if (DC->isRecord()) | ||||
3178 | return false; | ||||
3179 | |||||
3180 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); | ||||
3181 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) | ||||
3182 | return true; | ||||
3183 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) | ||||
3184 | return true; | ||||
3185 | return false; | ||||
3186 | } | ||||
3187 | |||||
3188 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } | ||||
3189 | static bool isExternC(VarTemplateDecl *) { return false; } | ||||
3190 | static bool isExternC(FunctionTemplateDecl *) { return false; } | ||||
3191 | |||||
3192 | /// Check whether a redeclaration of an entity introduced by a | ||||
3193 | /// using-declaration is valid, given that we know it's not an overload | ||||
3194 | /// (nor a hidden tag declaration). | ||||
3195 | template<typename ExpectedDecl> | ||||
3196 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, | ||||
3197 | ExpectedDecl *New) { | ||||
3198 | // C++11 [basic.scope.declarative]p4: | ||||
3199 | // Given a set of declarations in a single declarative region, each of | ||||
3200 | // which specifies the same unqualified name, | ||||
3201 | // -- they shall all refer to the same entity, or all refer to functions | ||||
3202 | // and function templates; or | ||||
3203 | // -- exactly one declaration shall declare a class name or enumeration | ||||
3204 | // name that is not a typedef name and the other declarations shall all | ||||
3205 | // refer to the same variable or enumerator, or all refer to functions | ||||
3206 | // and function templates; in this case the class name or enumeration | ||||
3207 | // name is hidden (3.3.10). | ||||
3208 | |||||
3209 | // C++11 [namespace.udecl]p14: | ||||
3210 | // If a function declaration in namespace scope or block scope has the | ||||
3211 | // same name and the same parameter-type-list as a function introduced | ||||
3212 | // by a using-declaration, and the declarations do not declare the same | ||||
3213 | // function, the program is ill-formed. | ||||
3214 | |||||
3215 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); | ||||
3216 | if (Old && | ||||
3217 | !Old->getDeclContext()->getRedeclContext()->Equals( | ||||
3218 | New->getDeclContext()->getRedeclContext()) && | ||||
3219 | !(isExternC(Old) && isExternC(New))) | ||||
3220 | Old = nullptr; | ||||
3221 | |||||
3222 | if (!Old) { | ||||
3223 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); | ||||
3224 | S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); | ||||
3225 | S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; | ||||
3226 | return true; | ||||
3227 | } | ||||
3228 | return false; | ||||
3229 | } | ||||
3230 | |||||
3231 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, | ||||
3232 | const FunctionDecl *B) { | ||||
3233 | assert(A->getNumParams() == B->getNumParams())(static_cast <bool> (A->getNumParams() == B->getNumParams ()) ? void (0) : __assert_fail ("A->getNumParams() == B->getNumParams()" , "clang/lib/Sema/SemaDecl.cpp", 3233, __extension__ __PRETTY_FUNCTION__ )); | ||||
3234 | |||||
3235 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { | ||||
3236 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); | ||||
3237 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); | ||||
3238 | if (AttrA == AttrB) | ||||
3239 | return true; | ||||
3240 | return AttrA && AttrB && AttrA->getType() == AttrB->getType() && | ||||
3241 | AttrA->isDynamic() == AttrB->isDynamic(); | ||||
3242 | }; | ||||
3243 | |||||
3244 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); | ||||
3245 | } | ||||
3246 | |||||
3247 | /// If necessary, adjust the semantic declaration context for a qualified | ||||
3248 | /// declaration to name the correct inline namespace within the qualifier. | ||||
3249 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, | ||||
3250 | DeclaratorDecl *OldD) { | ||||
3251 | // The only case where we need to update the DeclContext is when | ||||
3252 | // redeclaration lookup for a qualified name finds a declaration | ||||
3253 | // in an inline namespace within the context named by the qualifier: | ||||
3254 | // | ||||
3255 | // inline namespace N { int f(); } | ||||
3256 | // int ::f(); // Sema DC needs adjusting from :: to N::. | ||||
3257 | // | ||||
3258 | // For unqualified declarations, the semantic context *can* change | ||||
3259 | // along the redeclaration chain (for local extern declarations, | ||||
3260 | // extern "C" declarations, and friend declarations in particular). | ||||
3261 | if (!NewD->getQualifier()) | ||||
3262 | return; | ||||
3263 | |||||
3264 | // NewD is probably already in the right context. | ||||
3265 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); | ||||
3266 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); | ||||
3267 | if (NamedDC->Equals(SemaDC)) | ||||
3268 | return; | ||||
3269 | |||||
3270 | assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf (SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl ()) && "unexpected context for redeclaration") ? void (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "clang/lib/Sema/SemaDecl.cpp", 3272, __extension__ __PRETTY_FUNCTION__ )) | ||||
3271 | NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf (SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl ()) && "unexpected context for redeclaration") ? void (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "clang/lib/Sema/SemaDecl.cpp", 3272, __extension__ __PRETTY_FUNCTION__ )) | ||||
3272 | "unexpected context for redeclaration")(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf (SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl ()) && "unexpected context for redeclaration") ? void (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "clang/lib/Sema/SemaDecl.cpp", 3272, __extension__ __PRETTY_FUNCTION__ )); | ||||
3273 | |||||
3274 | auto *LexDC = NewD->getLexicalDeclContext(); | ||||
3275 | auto FixSemaDC = [=](NamedDecl *D) { | ||||
3276 | if (!D) | ||||
3277 | return; | ||||
3278 | D->setDeclContext(SemaDC); | ||||
3279 | D->setLexicalDeclContext(LexDC); | ||||
3280 | }; | ||||
3281 | |||||
3282 | FixSemaDC(NewD); | ||||
3283 | if (auto *FD = dyn_cast<FunctionDecl>(NewD)) | ||||
3284 | FixSemaDC(FD->getDescribedFunctionTemplate()); | ||||
3285 | else if (auto *VD = dyn_cast<VarDecl>(NewD)) | ||||
3286 | FixSemaDC(VD->getDescribedVarTemplate()); | ||||
3287 | } | ||||
3288 | |||||
3289 | /// MergeFunctionDecl - We just parsed a function 'New' from | ||||
3290 | /// declarator D which has the same name and scope as a previous | ||||
3291 | /// declaration 'Old'. Figure out how to resolve this situation, | ||||
3292 | /// merging decls or emitting diagnostics as appropriate. | ||||
3293 | /// | ||||
3294 | /// In C++, New and Old must be declarations that are not | ||||
3295 | /// overloaded. Use IsOverload to determine whether New and Old are | ||||
3296 | /// overloaded, and to select the Old declaration that New should be | ||||
3297 | /// merged with. | ||||
3298 | /// | ||||
3299 | /// Returns true if there was an error, false otherwise. | ||||
3300 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, | ||||
3301 | Scope *S, bool MergeTypeWithOld) { | ||||
3302 | // Verify the old decl was also a function. | ||||
3303 | FunctionDecl *Old = OldD->getAsFunction(); | ||||
3304 | if (!Old) { | ||||
3305 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { | ||||
3306 | if (New->getFriendObjectKind()) { | ||||
3307 | Diag(New->getLocation(), diag::err_using_decl_friend); | ||||
3308 | Diag(Shadow->getTargetDecl()->getLocation(), | ||||
3309 | diag::note_using_decl_target); | ||||
3310 | Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) | ||||
3311 | << 0; | ||||
3312 | return true; | ||||
3313 | } | ||||
3314 | |||||
3315 | // Check whether the two declarations might declare the same function or | ||||
3316 | // function template. | ||||
3317 | if (FunctionTemplateDecl *NewTemplate = | ||||
3318 | New->getDescribedFunctionTemplate()) { | ||||
3319 | if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, | ||||
3320 | NewTemplate)) | ||||
3321 | return true; | ||||
3322 | OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) | ||||
3323 | ->getAsFunction(); | ||||
3324 | } else { | ||||
3325 | if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) | ||||
3326 | return true; | ||||
3327 | OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); | ||||
3328 | } | ||||
3329 | } else { | ||||
3330 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||
3331 | << New->getDeclName(); | ||||
3332 | notePreviousDefinition(OldD, New->getLocation()); | ||||
3333 | return true; | ||||
3334 | } | ||||
3335 | } | ||||
3336 | |||||
3337 | // If the old declaration was found in an inline namespace and the new | ||||
3338 | // declaration was qualified, update the DeclContext to match. | ||||
3339 | adjustDeclContextForDeclaratorDecl(New, Old); | ||||
3340 | |||||
3341 | // If the old declaration is invalid, just give up here. | ||||
3342 | if (Old->isInvalidDecl()) | ||||
3343 | return true; | ||||
3344 | |||||
3345 | // Disallow redeclaration of some builtins. | ||||
3346 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { | ||||
3347 | Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); | ||||
3348 | Diag(Old->getLocation(), diag::note_previous_builtin_declaration) | ||||
3349 | << Old << Old->getType(); | ||||
3350 | return true; | ||||
3351 | } | ||||
3352 | |||||
3353 | diag::kind PrevDiag; | ||||
3354 | SourceLocation OldLocation; | ||||
3355 | std::tie(PrevDiag, OldLocation) = | ||||
3356 | getNoteDiagForInvalidRedeclaration(Old, New); | ||||
3357 | |||||
3358 | // Don't complain about this if we're in GNU89 mode and the old function | ||||
3359 | // is an extern inline function. | ||||
3360 | // Don't complain about specializations. They are not supposed to have | ||||
3361 | // storage classes. | ||||
3362 | if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && | ||||
3363 | New->getStorageClass() == SC_Static && | ||||
3364 | Old->hasExternalFormalLinkage() && | ||||
3365 | !New->getTemplateSpecializationInfo() && | ||||
3366 | !canRedefineFunction(Old, getLangOpts())) { | ||||
3367 | if (getLangOpts().MicrosoftExt) { | ||||
3368 | Diag(New->getLocation(), diag::ext_static_non_static) << New; | ||||
3369 | Diag(OldLocation, PrevDiag); | ||||
3370 | } else { | ||||
3371 | Diag(New->getLocation(), diag::err_static_non_static) << New; | ||||
3372 | Diag(OldLocation, PrevDiag); | ||||
3373 | return true; | ||||
3374 | } | ||||
3375 | } | ||||
3376 | |||||
3377 | if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) | ||||
3378 | if (!Old->hasAttr<InternalLinkageAttr>()) { | ||||
3379 | Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) | ||||
3380 | << ILA; | ||||
3381 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
3382 | New->dropAttr<InternalLinkageAttr>(); | ||||
3383 | } | ||||
3384 | |||||
3385 | if (auto *EA = New->getAttr<ErrorAttr>()) { | ||||
3386 | if (!Old->hasAttr<ErrorAttr>()) { | ||||
3387 | Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; | ||||
3388 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
3389 | New->dropAttr<ErrorAttr>(); | ||||
3390 | } | ||||
3391 | } | ||||
3392 | |||||
3393 | if (CheckRedeclarationModuleOwnership(New, Old)) | ||||
3394 | return true; | ||||
3395 | |||||
3396 | if (!getLangOpts().CPlusPlus) { | ||||
3397 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); | ||||
3398 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { | ||||
3399 | Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) | ||||
3400 | << New << OldOvl; | ||||
3401 | |||||
3402 | // Try our best to find a decl that actually has the overloadable | ||||
3403 | // attribute for the note. In most cases (e.g. programs with only one | ||||
3404 | // broken declaration/definition), this won't matter. | ||||
3405 | // | ||||
3406 | // FIXME: We could do this if we juggled some extra state in | ||||
3407 | // OverloadableAttr, rather than just removing it. | ||||
3408 | const Decl *DiagOld = Old; | ||||
3409 | if (OldOvl) { | ||||
3410 | auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { | ||||
3411 | const auto *A = D->getAttr<OverloadableAttr>(); | ||||
3412 | return A && !A->isImplicit(); | ||||
3413 | }); | ||||
3414 | // If we've implicitly added *all* of the overloadable attrs to this | ||||
3415 | // chain, emitting a "previous redecl" note is pointless. | ||||
3416 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; | ||||
3417 | } | ||||
3418 | |||||
3419 | if (DiagOld) | ||||
3420 | Diag(DiagOld->getLocation(), | ||||
3421 | diag::note_attribute_overloadable_prev_overload) | ||||
3422 | << OldOvl; | ||||
3423 | |||||
3424 | if (OldOvl) | ||||
3425 | New->addAttr(OverloadableAttr::CreateImplicit(Context)); | ||||
3426 | else | ||||
3427 | New->dropAttr<OverloadableAttr>(); | ||||
3428 | } | ||||
3429 | } | ||||
3430 | |||||
3431 | // If a function is first declared with a calling convention, but is later | ||||
3432 | // declared or defined without one, all following decls assume the calling | ||||
3433 | // convention of the first. | ||||
3434 | // | ||||
3435 | // It's OK if a function is first declared without a calling convention, | ||||
3436 | // but is later declared or defined with the default calling convention. | ||||
3437 | // | ||||
3438 | // To test if either decl has an explicit calling convention, we look for | ||||
3439 | // AttributedType sugar nodes on the type as written. If they are missing or | ||||
3440 | // were canonicalized away, we assume the calling convention was implicit. | ||||
3441 | // | ||||
3442 | // Note also that we DO NOT return at this point, because we still have | ||||
3443 | // other tests to run. | ||||
3444 | QualType OldQType = Context.getCanonicalType(Old->getType()); | ||||
3445 | QualType NewQType = Context.getCanonicalType(New->getType()); | ||||
3446 | const FunctionType *OldType = cast<FunctionType>(OldQType); | ||||
3447 | const FunctionType *NewType = cast<FunctionType>(NewQType); | ||||
3448 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | ||||
3449 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | ||||
3450 | bool RequiresAdjustment = false; | ||||
3451 | |||||
3452 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { | ||||
3453 | FunctionDecl *First = Old->getFirstDecl(); | ||||
3454 | const FunctionType *FT = | ||||
3455 | First->getType().getCanonicalType()->castAs<FunctionType>(); | ||||
3456 | FunctionType::ExtInfo FI = FT->getExtInfo(); | ||||
3457 | bool NewCCExplicit = getCallingConvAttributedType(New->getType()); | ||||
3458 | if (!NewCCExplicit) { | ||||
3459 | // Inherit the CC from the previous declaration if it was specified | ||||
3460 | // there but not here. | ||||
3461 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | ||||
3462 | RequiresAdjustment = true; | ||||
3463 | } else if (Old->getBuiltinID()) { | ||||
3464 | // Builtin attribute isn't propagated to the new one yet at this point, | ||||
3465 | // so we check if the old one is a builtin. | ||||
3466 | |||||
3467 | // Calling Conventions on a Builtin aren't really useful and setting a | ||||
3468 | // default calling convention and cdecl'ing some builtin redeclarations is | ||||
3469 | // common, so warn and ignore the calling convention on the redeclaration. | ||||
3470 | Diag(New->getLocation(), diag::warn_cconv_unsupported) | ||||
3471 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | ||||
3472 | << (int)CallingConventionIgnoredReason::BuiltinFunction; | ||||
3473 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | ||||
3474 | RequiresAdjustment = true; | ||||
3475 | } else { | ||||
3476 | // Calling conventions aren't compatible, so complain. | ||||
3477 | bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); | ||||
3478 | Diag(New->getLocation(), diag::err_cconv_change) | ||||
3479 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | ||||
3480 | << !FirstCCExplicit | ||||
3481 | << (!FirstCCExplicit ? "" : | ||||
3482 | FunctionType::getNameForCallConv(FI.getCC())); | ||||
3483 | |||||
3484 | // Put the note on the first decl, since it is the one that matters. | ||||
3485 | Diag(First->getLocation(), diag::note_previous_declaration); | ||||
3486 | return true; | ||||
3487 | } | ||||
3488 | } | ||||
3489 | |||||
3490 | // FIXME: diagnose the other way around? | ||||
3491 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { | ||||
3492 | NewTypeInfo = NewTypeInfo.withNoReturn(true); | ||||
3493 | RequiresAdjustment = true; | ||||
3494 | } | ||||
3495 | |||||
3496 | // Merge regparm attribute. | ||||
3497 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || | ||||
3498 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { | ||||
3499 | if (NewTypeInfo.getHasRegParm()) { | ||||
3500 | Diag(New->getLocation(), diag::err_regparm_mismatch) | ||||
3501 | << NewType->getRegParmType() | ||||
3502 | << OldType->getRegParmType(); | ||||
3503 | Diag(OldLocation, diag::note_previous_declaration); | ||||
3504 | return true; | ||||
3505 | } | ||||
3506 | |||||
3507 | NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); | ||||
3508 | RequiresAdjustment = true; | ||||
3509 | } | ||||
3510 | |||||
3511 | // Merge ns_returns_retained attribute. | ||||
3512 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { | ||||
3513 | if (NewTypeInfo.getProducesResult()) { | ||||
3514 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) | ||||
3515 | << "'ns_returns_retained'"; | ||||
3516 | Diag(OldLocation, diag::note_previous_declaration); | ||||
3517 | return true; | ||||
3518 | } | ||||
3519 | |||||
3520 | NewTypeInfo = NewTypeInfo.withProducesResult(true); | ||||
3521 | RequiresAdjustment = true; | ||||
3522 | } | ||||
3523 | |||||
3524 | if (OldTypeInfo.getNoCallerSavedRegs() != | ||||
3525 | NewTypeInfo.getNoCallerSavedRegs()) { | ||||
3526 | if (NewTypeInfo.getNoCallerSavedRegs()) { | ||||
3527 | AnyX86NoCallerSavedRegistersAttr *Attr = | ||||
3528 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); | ||||
3529 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; | ||||
3530 | Diag(OldLocation, diag::note_previous_declaration); | ||||
3531 | return true; | ||||
3532 | } | ||||
3533 | |||||
3534 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); | ||||
3535 | RequiresAdjustment = true; | ||||
3536 | } | ||||
3537 | |||||
3538 | if (RequiresAdjustment) { | ||||
3539 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); | ||||
3540 | AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); | ||||
3541 | New->setType(QualType(AdjustedType, 0)); | ||||
3542 | NewQType = Context.getCanonicalType(New->getType()); | ||||
3543 | } | ||||
3544 | |||||
3545 | // If this redeclaration makes the function inline, we may need to add it to | ||||
3546 | // UndefinedButUsed. | ||||
3547 | if (!Old->isInlined() && New->isInlined() && | ||||
3548 | !New->hasAttr<GNUInlineAttr>() && | ||||
3549 | !getLangOpts().GNUInline && | ||||
3550 | Old->isUsed(false) && | ||||
3551 | !Old->isDefined() && !New->isThisDeclarationADefinition()) | ||||
3552 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | ||||
3553 | SourceLocation())); | ||||
3554 | |||||
3555 | // If this redeclaration makes it newly gnu_inline, we don't want to warn | ||||
3556 | // about it. | ||||
3557 | if (New->hasAttr<GNUInlineAttr>() && | ||||
3558 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { | ||||
3559 | UndefinedButUsed.erase(Old->getCanonicalDecl()); | ||||
3560 | } | ||||
3561 | |||||
3562 | // If pass_object_size params don't match up perfectly, this isn't a valid | ||||
3563 | // redeclaration. | ||||
3564 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && | ||||
3565 | !hasIdenticalPassObjectSizeAttrs(Old, New)) { | ||||
3566 | Diag(New->getLocation(), diag::err_different_pass_object_size_params) | ||||
3567 | << New->getDeclName(); | ||||
3568 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||
3569 | return true; | ||||
3570 | } | ||||
3571 | |||||
3572 | if (getLangOpts().CPlusPlus) { | ||||
3573 | // C++1z [over.load]p2 | ||||
3574 | // Certain function declarations cannot be overloaded: | ||||
3575 | // -- Function declarations that differ only in the return type, | ||||
3576 | // the exception specification, or both cannot be overloaded. | ||||
3577 | |||||
3578 | // Check the exception specifications match. This may recompute the type of | ||||
3579 | // both Old and New if it resolved exception specifications, so grab the | ||||
3580 | // types again after this. Because this updates the type, we do this before | ||||
3581 | // any of the other checks below, which may update the "de facto" NewQType | ||||
3582 | // but do not necessarily update the type of New. | ||||
3583 | if (CheckEquivalentExceptionSpec(Old, New)) | ||||
3584 | return true; | ||||
3585 | OldQType = Context.getCanonicalType(Old->getType()); | ||||
3586 | NewQType = Context.getCanonicalType(New->getType()); | ||||
3587 | |||||
3588 | // Go back to the type source info to compare the declared return types, | ||||
3589 | // per C++1y [dcl.type.auto]p13: | ||||
3590 | // Redeclarations or specializations of a function or function template | ||||
3591 | // with a declared return type that uses a placeholder type shall also | ||||
3592 | // use that placeholder, not a deduced type. | ||||
3593 | QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); | ||||
3594 | QualType NewDeclaredReturnType = New->getDeclaredReturnType(); | ||||
3595 | if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && | ||||
3596 | canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, | ||||
3597 | OldDeclaredReturnType)) { | ||||
3598 | QualType ResQT; | ||||
3599 | if (NewDeclaredReturnType->isObjCObjectPointerType() && | ||||
3600 | OldDeclaredReturnType->isObjCObjectPointerType()) | ||||
3601 | // FIXME: This does the wrong thing for a deduced return type. | ||||
3602 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); | ||||
3603 | if (ResQT.isNull()) { | ||||
3604 | if (New->isCXXClassMember() && New->isOutOfLine()) | ||||
3605 | Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) | ||||
3606 | << New << New->getReturnTypeSourceRange(); | ||||
3607 | else | ||||
3608 | Diag(New->getLocation(), diag::err_ovl_diff_return_type) | ||||
3609 | << New->getReturnTypeSourceRange(); | ||||
3610 | Diag(OldLocation, PrevDiag) << Old << Old->getType() | ||||
3611 | << Old->getReturnTypeSourceRange(); | ||||
3612 | return true; | ||||
3613 | } | ||||
3614 | else | ||||
3615 | NewQType = ResQT; | ||||
3616 | } | ||||
3617 | |||||
3618 | QualType OldReturnType = OldType->getReturnType(); | ||||
3619 | QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); | ||||
3620 | if (OldReturnType != NewReturnType) { | ||||
3621 | // If this function has a deduced return type and has already been | ||||
3622 | // defined, copy the deduced value from the old declaration. | ||||
3623 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); | ||||
3624 | if (OldAT && OldAT->isDeduced()) { | ||||
3625 | QualType DT = OldAT->getDeducedType(); | ||||
3626 | if (DT.isNull()) { | ||||
3627 | New->setType(SubstAutoTypeDependent(New->getType())); | ||||
3628 | NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); | ||||
3629 | } else { | ||||
3630 | New->setType(SubstAutoType(New->getType(), DT)); | ||||
3631 | NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); | ||||
3632 | } | ||||
3633 | } | ||||
3634 | } | ||||
3635 | |||||
3636 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); | ||||
3637 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); | ||||
3638 | if (OldMethod && NewMethod) { | ||||
3639 | // Preserve triviality. | ||||
3640 | NewMethod->setTrivial(OldMethod->isTrivial()); | ||||
3641 | |||||
3642 | // MSVC allows explicit template specialization at class scope: | ||||
3643 | // 2 CXXMethodDecls referring to the same function will be injected. | ||||
3644 | // We don't want a redeclaration error. | ||||
3645 | bool IsClassScopeExplicitSpecialization = | ||||
3646 | OldMethod->isFunctionTemplateSpecialization() && | ||||
3647 | NewMethod->isFunctionTemplateSpecialization(); | ||||
3648 | bool isFriend = NewMethod->getFriendObjectKind(); | ||||
3649 | |||||
3650 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && | ||||
3651 | !IsClassScopeExplicitSpecialization) { | ||||
3652 | // -- Member function declarations with the same name and the | ||||
3653 | // same parameter types cannot be overloaded if any of them | ||||
3654 | // is a static member function declaration. | ||||
3655 | if (OldMethod->isStatic() != NewMethod->isStatic()) { | ||||
3656 | Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); | ||||
3657 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||
3658 | return true; | ||||
3659 | } | ||||
3660 | |||||
3661 | // C++ [class.mem]p1: | ||||
3662 | // [...] A member shall not be declared twice in the | ||||
3663 | // member-specification, except that a nested class or member | ||||
3664 | // class template can be declared and then later defined. | ||||
3665 | if (!inTemplateInstantiation()) { | ||||
3666 | unsigned NewDiag; | ||||
3667 | if (isa<CXXConstructorDecl>(OldMethod)) | ||||
3668 | NewDiag = diag::err_constructor_redeclared; | ||||
3669 | else if (isa<CXXDestructorDecl>(NewMethod)) | ||||
3670 | NewDiag = diag::err_destructor_redeclared; | ||||
3671 | else if (isa<CXXConversionDecl>(NewMethod)) | ||||
3672 | NewDiag = diag::err_conv_function_redeclared; | ||||
3673 | else | ||||
3674 | NewDiag = diag::err_member_redeclared; | ||||
3675 | |||||
3676 | Diag(New->getLocation(), NewDiag); | ||||
3677 | } else { | ||||
3678 | Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) | ||||
3679 | << New << New->getType(); | ||||
3680 | } | ||||
3681 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||
3682 | return true; | ||||
3683 | |||||
3684 | // Complain if this is an explicit declaration of a special | ||||
3685 | // member that was initially declared implicitly. | ||||
3686 | // | ||||
3687 | // As an exception, it's okay to befriend such methods in order | ||||
3688 | // to permit the implicit constructor/destructor/operator calls. | ||||
3689 | } else if (OldMethod->isImplicit()) { | ||||
3690 | if (isFriend) { | ||||
3691 | NewMethod->setImplicit(); | ||||
3692 | } else { | ||||
3693 | Diag(NewMethod->getLocation(), | ||||
3694 | diag::err_definition_of_implicitly_declared_member) | ||||
3695 | << New << getSpecialMember(OldMethod); | ||||
3696 | return true; | ||||
3697 | } | ||||
3698 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { | ||||
3699 | Diag(NewMethod->getLocation(), | ||||
3700 | diag::err_definition_of_explicitly_defaulted_member) | ||||
3701 | << getSpecialMember(OldMethod); | ||||
3702 | return true; | ||||
3703 | } | ||||
3704 | } | ||||
3705 | |||||
3706 | // C++11 [dcl.attr.noreturn]p1: | ||||
3707 | // The first declaration of a function shall specify the noreturn | ||||
3708 | // attribute if any declaration of that function specifies the noreturn | ||||
3709 | // attribute. | ||||
3710 | if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) | ||||
3711 | if (!Old->hasAttr<CXX11NoReturnAttr>()) { | ||||
3712 | Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) | ||||
3713 | << NRA; | ||||
3714 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
3715 | } | ||||
3716 | |||||
3717 | // C++11 [dcl.attr.depend]p2: | ||||
3718 | // The first declaration of a function shall specify the | ||||
3719 | // carries_dependency attribute for its declarator-id if any declaration | ||||
3720 | // of the function specifies the carries_dependency attribute. | ||||
3721 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); | ||||
3722 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { | ||||
3723 | Diag(CDA->getLocation(), | ||||
3724 | diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; | ||||
3725 | Diag(Old->getFirstDecl()->getLocation(), | ||||
3726 | diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; | ||||
3727 | } | ||||
3728 | |||||
3729 | // (C++98 8.3.5p3): | ||||
3730 | // All declarations for a function shall agree exactly in both the | ||||
3731 | // return type and the parameter-type-list. | ||||
3732 | // We also want to respect all the extended bits except noreturn. | ||||
3733 | |||||
3734 | // noreturn should now match unless the old type info didn't have it. | ||||
3735 | QualType OldQTypeForComparison = OldQType; | ||||
3736 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { | ||||
3737 | auto *OldType = OldQType->castAs<FunctionProtoType>(); | ||||
3738 | const FunctionType *OldTypeForComparison | ||||
3739 | = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); | ||||
3740 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); | ||||
3741 | assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical( )) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()" , "clang/lib/Sema/SemaDecl.cpp", 3741, __extension__ __PRETTY_FUNCTION__ )); | ||||
3742 | } | ||||
3743 | |||||
3744 | if (haveIncompatibleLanguageLinkages(Old, New)) { | ||||
3745 | // As a special case, retain the language linkage from previous | ||||
3746 | // declarations of a friend function as an extension. | ||||
3747 | // | ||||
3748 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC | ||||
3749 | // and is useful because there's otherwise no way to specify language | ||||
3750 | // linkage within class scope. | ||||
3751 | // | ||||
3752 | // Check cautiously as the friend object kind isn't yet complete. | ||||
3753 | if (New->getFriendObjectKind() != Decl::FOK_None) { | ||||
3754 | Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; | ||||
3755 | Diag(OldLocation, PrevDiag); | ||||
3756 | } else { | ||||
3757 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | ||||
3758 | Diag(OldLocation, PrevDiag); | ||||
3759 | return true; | ||||
3760 | } | ||||
3761 | } | ||||
3762 | |||||
3763 | // If the function types are compatible, merge the declarations. Ignore the | ||||
3764 | // exception specifier because it was already checked above in | ||||
3765 | // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics | ||||
3766 | // about incompatible types under -fms-compatibility. | ||||
3767 | if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, | ||||
3768 | NewQType)) | ||||
3769 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||
3770 | |||||
3771 | // If the types are imprecise (due to dependent constructs in friends or | ||||
3772 | // local extern declarations), it's OK if they differ. We'll check again | ||||
3773 | // during instantiation. | ||||
3774 | if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) | ||||
3775 | return false; | ||||
3776 | |||||
3777 | // Fall through for conflicting redeclarations and redefinitions. | ||||
3778 | } | ||||
3779 | |||||
3780 | // C: Function types need to be compatible, not identical. This handles | ||||
3781 | // duplicate function decls like "void f(int); void f(enum X);" properly. | ||||
3782 | if (!getLangOpts().CPlusPlus && | ||||
3783 | Context.typesAreCompatible(OldQType, NewQType)) { | ||||
3784 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); | ||||
3785 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); | ||||
3786 | const FunctionProtoType *OldProto = nullptr; | ||||
3787 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && | ||||
3788 | (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { | ||||
3789 | // The old declaration provided a function prototype, but the | ||||
3790 | // new declaration does not. Merge in the prototype. | ||||
3791 | assert(!OldProto->hasExceptionSpec() && "Exception spec in C")(static_cast <bool> (!OldProto->hasExceptionSpec() && "Exception spec in C") ? void (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\"" , "clang/lib/Sema/SemaDecl.cpp", 3791, __extension__ __PRETTY_FUNCTION__ )); | ||||
3792 | SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); | ||||
3793 | NewQType = | ||||
3794 | Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, | ||||
3795 | OldProto->getExtProtoInfo()); | ||||
3796 | New->setType(NewQType); | ||||
3797 | New->setHasInheritedPrototype(); | ||||
3798 | |||||
3799 | // Synthesize parameters with the same types. | ||||
3800 | SmallVector<ParmVarDecl*, 16> Params; | ||||
3801 | for (const auto &ParamType : OldProto->param_types()) { | ||||
3802 | ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), | ||||
3803 | SourceLocation(), nullptr, | ||||
3804 | ParamType, /*TInfo=*/nullptr, | ||||
3805 | SC_None, nullptr); | ||||
3806 | Param->setScopeInfo(0, Params.size()); | ||||
3807 | Param->setImplicit(); | ||||
3808 | Params.push_back(Param); | ||||
3809 | } | ||||
3810 | |||||
3811 | New->setParams(Params); | ||||
3812 | } | ||||
3813 | |||||
3814 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||
3815 | } | ||||
3816 | |||||
3817 | // Check if the function types are compatible when pointer size address | ||||
3818 | // spaces are ignored. | ||||
3819 | if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) | ||||
3820 | return false; | ||||
3821 | |||||
3822 | // GNU C permits a K&R definition to follow a prototype declaration | ||||
3823 | // if the declared types of the parameters in the K&R definition | ||||
3824 | // match the types in the prototype declaration, even when the | ||||
3825 | // promoted types of the parameters from the K&R definition differ | ||||
3826 | // from the types in the prototype. GCC then keeps the types from | ||||
3827 | // the prototype. | ||||
3828 | // | ||||
3829 | // If a variadic prototype is followed by a non-variadic K&R definition, | ||||
3830 | // the K&R definition becomes variadic. This is sort of an edge case, but | ||||
3831 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and | ||||
3832 | // C99 6.9.1p8. | ||||
3833 | if (!getLangOpts().CPlusPlus && | ||||
3834 | Old->hasPrototype() && !New->hasPrototype() && | ||||
3835 | New->getType()->getAs<FunctionProtoType>() && | ||||
3836 | Old->getNumParams() == New->getNumParams()) { | ||||
3837 | SmallVector<QualType, 16> ArgTypes; | ||||
3838 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; | ||||
3839 | const FunctionProtoType *OldProto | ||||
3840 | = Old->getType()->getAs<FunctionProtoType>(); | ||||
3841 | const FunctionProtoType *NewProto | ||||
3842 | = New->getType()->getAs<FunctionProtoType>(); | ||||
3843 | |||||
3844 | // Determine whether this is the GNU C extension. | ||||
3845 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), | ||||
3846 | NewProto->getReturnType()); | ||||
3847 | bool LooseCompatible = !MergedReturn.isNull(); | ||||
3848 | for (unsigned Idx = 0, End = Old->getNumParams(); | ||||
3849 | LooseCompatible && Idx != End; ++Idx) { | ||||
3850 | ParmVarDecl *OldParm = Old->getParamDecl(Idx); | ||||
3851 | ParmVarDecl *NewParm = New->getParamDecl(Idx); | ||||
3852 | if (Context.typesAreCompatible(OldParm->getType(), | ||||
3853 | NewProto->getParamType(Idx))) { | ||||
3854 | ArgTypes.push_back(NewParm->getType()); | ||||
3855 | } else if (Context.typesAreCompatible(OldParm->getType(), | ||||
3856 | NewParm->getType(), | ||||
3857 | /*CompareUnqualified=*/true)) { | ||||
3858 | GNUCompatibleParamWarning Warn = { OldParm, NewParm, | ||||
3859 | NewProto->getParamType(Idx) }; | ||||
3860 | Warnings.push_back(Warn); | ||||
3861 | ArgTypes.push_back(NewParm->getType()); | ||||
3862 | } else | ||||
3863 | LooseCompatible = false; | ||||
3864 | } | ||||
3865 | |||||
3866 | if (LooseCompatible) { | ||||
3867 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { | ||||
3868 | Diag(Warnings[Warn].NewParm->getLocation(), | ||||
3869 | diag::ext_param_promoted_not_compatible_with_prototype) | ||||
3870 | << Warnings[Warn].PromotedType | ||||
3871 | << Warnings[Warn].OldParm->getType(); | ||||
3872 | if (Warnings[Warn].OldParm->getLocation().isValid()) | ||||
3873 | Diag(Warnings[Warn].OldParm->getLocation(), | ||||
3874 | diag::note_previous_declaration); | ||||
3875 | } | ||||
3876 | |||||
3877 | if (MergeTypeWithOld) | ||||
3878 | New->setType(Context.getFunctionType(MergedReturn, ArgTypes, | ||||
3879 | OldProto->getExtProtoInfo())); | ||||
3880 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||
3881 | } | ||||
3882 | |||||
3883 | // Fall through to diagnose conflicting types. | ||||
3884 | } | ||||
3885 | |||||
3886 | // A function that has already been declared has been redeclared or | ||||
3887 | // defined with a different type; show an appropriate diagnostic. | ||||
3888 | |||||
3889 | // If the previous declaration was an implicitly-generated builtin | ||||
3890 | // declaration, then at the very least we should use a specialized note. | ||||
3891 | unsigned BuiltinID; | ||||
3892 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { | ||||
3893 | // If it's actually a library-defined builtin function like 'malloc' | ||||
3894 | // or 'printf', just warn about the incompatible redeclaration. | ||||
3895 | if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { | ||||
3896 | Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; | ||||
3897 | Diag(OldLocation, diag::note_previous_builtin_declaration) | ||||
3898 | << Old << Old->getType(); | ||||
3899 | return false; | ||||
3900 | } | ||||
3901 | |||||
3902 | PrevDiag = diag::note_previous_builtin_declaration; | ||||
3903 | } | ||||
3904 | |||||
3905 | Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); | ||||
3906 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||
3907 | return true; | ||||
3908 | } | ||||
3909 | |||||
3910 | /// Completes the merge of two function declarations that are | ||||
3911 | /// known to be compatible. | ||||
3912 | /// | ||||
3913 | /// This routine handles the merging of attributes and other | ||||
3914 | /// properties of function declarations from the old declaration to | ||||
3915 | /// the new declaration, once we know that New is in fact a | ||||
3916 | /// redeclaration of Old. | ||||
3917 | /// | ||||
3918 | /// \returns false | ||||
3919 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, | ||||
3920 | Scope *S, bool MergeTypeWithOld) { | ||||
3921 | // Merge the attributes | ||||
3922 | mergeDeclAttributes(New, Old); | ||||
3923 | |||||
3924 | // Merge "pure" flag. | ||||
3925 | if (Old->isPure()) | ||||
3926 | New->setPure(); | ||||
3927 | |||||
3928 | // Merge "used" flag. | ||||
3929 | if (Old->getMostRecentDecl()->isUsed(false)) | ||||
3930 | New->setIsUsed(); | ||||
3931 | |||||
3932 | // Merge attributes from the parameters. These can mismatch with K&R | ||||
3933 | // declarations. | ||||
3934 | if (New->getNumParams() == Old->getNumParams()) | ||||
3935 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { | ||||
3936 | ParmVarDecl *NewParam = New->getParamDecl(i); | ||||
3937 | ParmVarDecl *OldParam = Old->getParamDecl(i); | ||||
3938 | mergeParamDeclAttributes(NewParam, OldParam, *this); | ||||
3939 | mergeParamDeclTypes(NewParam, OldParam, *this); | ||||
3940 | } | ||||
3941 | |||||
3942 | if (getLangOpts().CPlusPlus) | ||||
3943 | return MergeCXXFunctionDecl(New, Old, S); | ||||
3944 | |||||
3945 | // Merge the function types so the we get the composite types for the return | ||||
3946 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl | ||||
3947 | // was visible. | ||||
3948 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); | ||||
3949 | if (!Merged.isNull() && MergeTypeWithOld) | ||||
3950 | New->setType(Merged); | ||||
3951 | |||||
3952 | return false; | ||||
3953 | } | ||||
3954 | |||||
3955 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, | ||||
3956 | ObjCMethodDecl *oldMethod) { | ||||
3957 | // Merge the attributes, including deprecated/unavailable | ||||
3958 | AvailabilityMergeKind MergeKind = | ||||
3959 | isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) | ||||
3960 | ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation | ||||
3961 | : AMK_ProtocolImplementation) | ||||
3962 | : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration | ||||
3963 | : AMK_Override; | ||||
3964 | |||||
3965 | mergeDeclAttributes(newMethod, oldMethod, MergeKind); | ||||
3966 | |||||
3967 | // Merge attributes from the parameters. | ||||
3968 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), | ||||
3969 | oe = oldMethod->param_end(); | ||||
3970 | for (ObjCMethodDecl::param_iterator | ||||
3971 | ni = newMethod->param_begin(), ne = newMethod->param_end(); | ||||
3972 | ni != ne && oi != oe; ++ni, ++oi) | ||||
3973 | mergeParamDeclAttributes(*ni, *oi, *this); | ||||
3974 | |||||
3975 | CheckObjCMethodOverride(newMethod, oldMethod); | ||||
3976 | } | ||||
3977 | |||||
3978 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { | ||||
3979 | assert(!S.Context.hasSameType(New->getType(), Old->getType()))(static_cast <bool> (!S.Context.hasSameType(New->getType (), Old->getType())) ? void (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())" , "clang/lib/Sema/SemaDecl.cpp", 3979, __extension__ __PRETTY_FUNCTION__ )); | ||||
3980 | |||||
3981 | S.Diag(New->getLocation(), New->isThisDeclarationADefinition() | ||||
3982 | ? diag::err_redefinition_different_type | ||||
3983 | : diag::err_redeclaration_different_type) | ||||
3984 | << New->getDeclName() << New->getType() << Old->getType(); | ||||
3985 | |||||
3986 | diag::kind PrevDiag; | ||||
3987 | SourceLocation OldLocation; | ||||
3988 | std::tie(PrevDiag, OldLocation) | ||||
3989 | = getNoteDiagForInvalidRedeclaration(Old, New); | ||||
3990 | S.Diag(OldLocation, PrevDiag); | ||||
3991 | New->setInvalidDecl(); | ||||
3992 | } | ||||
3993 | |||||
3994 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and | ||||
3995 | /// scope as a previous declaration 'Old'. Figure out how to merge their types, | ||||
3996 | /// emitting diagnostics as appropriate. | ||||
3997 | /// | ||||
3998 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back | ||||
3999 | /// to here in AddInitializerToDecl. We can't check them before the initializer | ||||
4000 | /// is attached. | ||||
4001 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, | ||||
4002 | bool MergeTypeWithOld) { | ||||
4003 | if (New->isInvalidDecl() || Old->isInvalidDecl()) | ||||
4004 | return; | ||||
4005 | |||||
4006 | QualType MergedT; | ||||
4007 | if (getLangOpts().CPlusPlus) { | ||||
4008 | if (New->getType()->isUndeducedType()) { | ||||
4009 | // We don't know what the new type is until the initializer is attached. | ||||
4010 | return; | ||||
4011 | } else if (Context.hasSameType(New->getType(), Old->getType())) { | ||||
4012 | // These could still be something that needs exception specs checked. | ||||
4013 | return MergeVarDeclExceptionSpecs(New, Old); | ||||
4014 | } | ||||
4015 | // C++ [basic.link]p10: | ||||
4016 | // [...] the types specified by all declarations referring to a given | ||||
4017 | // object or function shall be identical, except that declarations for an | ||||
4018 | // array object can specify array types that differ by the presence or | ||||
4019 | // absence of a major array bound (8.3.4). | ||||
4020 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { | ||||
4021 | const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); | ||||
4022 | const ArrayType *NewArray = Context.getAsArrayType(New->getType()); | ||||
4023 | |||||
4024 | // We are merging a variable declaration New into Old. If it has an array | ||||
4025 | // bound, and that bound differs from Old's bound, we should diagnose the | ||||
4026 | // mismatch. | ||||
4027 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { | ||||
4028 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; | ||||
4029 | PrevVD = PrevVD->getPreviousDecl()) { | ||||
4030 | QualType PrevVDTy = PrevVD->getType(); | ||||
4031 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) | ||||
4032 | continue; | ||||
4033 | |||||
4034 | if (!Context.hasSameType(New->getType(), PrevVDTy)) | ||||
4035 | return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); | ||||
4036 | } | ||||
4037 | } | ||||
4038 | |||||
4039 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { | ||||
4040 | if (Context.hasSameType(OldArray->getElementType(), | ||||
4041 | NewArray->getElementType())) | ||||
4042 | MergedT = New->getType(); | ||||
4043 | } | ||||
4044 | // FIXME: Check visibility. New is hidden but has a complete type. If New | ||||
4045 | // has no array bound, it should not inherit one from Old, if Old is not | ||||
4046 | // visible. | ||||
4047 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { | ||||
4048 | if (Context.hasSameType(OldArray->getElementType(), | ||||
4049 | NewArray->getElementType())) | ||||
4050 | MergedT = Old->getType(); | ||||
4051 | } | ||||
4052 | } | ||||
4053 | else if (New->getType()->isObjCObjectPointerType() && | ||||
4054 | Old->getType()->isObjCObjectPointerType()) { | ||||
4055 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), | ||||
4056 | Old->getType()); | ||||
4057 | } | ||||
4058 | } else { | ||||
4059 | // C 6.2.7p2: | ||||
4060 | // All declarations that refer to the same object or function shall have | ||||
4061 | // compatible type. | ||||
4062 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); | ||||
4063 | } | ||||
4064 | if (MergedT.isNull()) { | ||||
4065 | // It's OK if we couldn't merge types if either type is dependent, for a | ||||
4066 | // block-scope variable. In other cases (static data members of class | ||||
4067 | // templates, variable templates, ...), we require the types to be | ||||
4068 | // equivalent. | ||||
4069 | // FIXME: The C++ standard doesn't say anything about this. | ||||
4070 | if ((New->getType()->isDependentType() || | ||||
4071 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { | ||||
4072 | // If the old type was dependent, we can't merge with it, so the new type | ||||
4073 | // becomes dependent for now. We'll reproduce the original type when we | ||||
4074 | // instantiate the TypeSourceInfo for the variable. | ||||
4075 | if (!New->getType()->isDependentType() && MergeTypeWithOld) | ||||
4076 | New->setType(Context.DependentTy); | ||||
4077 | return; | ||||
4078 | } | ||||
4079 | return diagnoseVarDeclTypeMismatch(*this, New, Old); | ||||
4080 | } | ||||
4081 | |||||
4082 | // Don't actually update the type on the new declaration if the old | ||||
4083 | // declaration was an extern declaration in a different scope. | ||||
4084 | if (MergeTypeWithOld) | ||||
4085 | New->setType(MergedT); | ||||
4086 | } | ||||
4087 | |||||
4088 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, | ||||
4089 | LookupResult &Previous) { | ||||
4090 | // C11 6.2.7p4: | ||||
4091 | // For an identifier with internal or external linkage declared | ||||
4092 | // in a scope in which a prior declaration of that identifier is | ||||
4093 | // visible, if the prior declaration specifies internal or | ||||
4094 | // external linkage, the type of the identifier at the later | ||||
4095 | // declaration becomes the composite type. | ||||
4096 | // | ||||
4097 | // If the variable isn't visible, we do not merge with its type. | ||||
4098 | if (Previous.isShadowed()) | ||||
4099 | return false; | ||||
4100 | |||||
4101 | if (S.getLangOpts().CPlusPlus) { | ||||
4102 | // C++11 [dcl.array]p3: | ||||
4103 | // If there is a preceding declaration of the entity in the same | ||||
4104 | // scope in which the bound was specified, an omitted array bound | ||||
4105 | // is taken to be the same as in that earlier declaration. | ||||
4106 | return NewVD->isPreviousDeclInSameBlockScope() || | ||||
4107 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && | ||||
4108 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); | ||||
4109 | } else { | ||||
4110 | // If the old declaration was function-local, don't merge with its | ||||
4111 | // type unless we're in the same function. | ||||
4112 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || | ||||
4113 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); | ||||
4114 | } | ||||
4115 | } | ||||
4116 | |||||
4117 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name | ||||
4118 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this | ||||
4119 | /// situation, merging decls or emitting diagnostics as appropriate. | ||||
4120 | /// | ||||
4121 | /// Tentative definition rules (C99 6.9.2p2) are checked by | ||||
4122 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative | ||||
4123 | /// definitions here, since the initializer hasn't been attached. | ||||
4124 | /// | ||||
4125 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { | ||||
4126 | // If the new decl is already invalid, don't do any other checking. | ||||
4127 | if (New->isInvalidDecl()) | ||||
4128 | return; | ||||
4129 | |||||
4130 | if (!shouldLinkPossiblyHiddenDecl(Previous, New)) | ||||
4131 | return; | ||||
4132 | |||||
4133 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); | ||||
4134 | |||||
4135 | // Verify the old decl was also a variable or variable template. | ||||
4136 | VarDecl *Old = nullptr; | ||||
4137 | VarTemplateDecl *OldTemplate = nullptr; | ||||
4138 | if (Previous.isSingleResult()) { | ||||
4139 | if (NewTemplate) { | ||||
4140 | OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); | ||||
4141 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; | ||||
4142 | |||||
4143 | if (auto *Shadow = | ||||
4144 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | ||||
4145 | if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) | ||||
4146 | return New->setInvalidDecl(); | ||||
4147 | } else { | ||||
4148 | Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); | ||||
4149 | |||||
4150 | if (auto *Shadow = | ||||
4151 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | ||||
4152 | if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) | ||||
4153 | return New->setInvalidDecl(); | ||||
4154 | } | ||||
4155 | } | ||||
4156 | if (!Old) { | ||||
4157 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||
4158 | << New->getDeclName(); | ||||
4159 | notePreviousDefinition(Previous.getRepresentativeDecl(), | ||||
4160 | New->getLocation()); | ||||
4161 | return New->setInvalidDecl(); | ||||
4162 | } | ||||
4163 | |||||
4164 | // If the old declaration was found in an inline namespace and the new | ||||
4165 | // declaration was qualified, update the DeclContext to match. | ||||
4166 | adjustDeclContextForDeclaratorDecl(New, Old); | ||||
4167 | |||||
4168 | // Ensure the template parameters are compatible. | ||||
4169 | if (NewTemplate && | ||||
4170 | !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), | ||||
4171 | OldTemplate->getTemplateParameters(), | ||||
4172 | /*Complain=*/true, TPL_TemplateMatch)) | ||||
4173 | return New->setInvalidDecl(); | ||||
4174 | |||||
4175 | // C++ [class.mem]p1: | ||||
4176 | // A member shall not be declared twice in the member-specification [...] | ||||
4177 | // | ||||
4178 | // Here, we need only consider static data members. | ||||
4179 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { | ||||
4180 | Diag(New->getLocation(), diag::err_duplicate_member) | ||||
4181 | << New->getIdentifier(); | ||||
4182 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
4183 | New->setInvalidDecl(); | ||||
4184 | } | ||||
4185 | |||||
4186 | mergeDeclAttributes(New, Old); | ||||
4187 | // Warn if an already-declared variable is made a weak_import in a subsequent | ||||
4188 | // declaration | ||||
4189 | if (New->hasAttr<WeakImportAttr>() && | ||||
4190 | Old->getStorageClass() == SC_None && | ||||
4191 | !Old->hasAttr<WeakImportAttr>()) { | ||||
4192 | Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); | ||||
4193 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
4194 | // Remove weak_import attribute on new declaration. | ||||
4195 | New->dropAttr<WeakImportAttr>(); | ||||
4196 | } | ||||
4197 | |||||
4198 | if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) | ||||
4199 | if (!Old->hasAttr<InternalLinkageAttr>()) { | ||||
4200 | Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) | ||||
4201 | << ILA; | ||||
4202 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
4203 | New->dropAttr<InternalLinkageAttr>(); | ||||
4204 | } | ||||
4205 | |||||
4206 | // Merge the types. | ||||
4207 | VarDecl *MostRecent = Old->getMostRecentDecl(); | ||||
4208 | if (MostRecent != Old) { | ||||
4209 | MergeVarDeclTypes(New, MostRecent, | ||||
4210 | mergeTypeWithPrevious(*this, New, MostRecent, Previous)); | ||||
4211 | if (New->isInvalidDecl()) | ||||
4212 | return; | ||||
4213 | } | ||||
4214 | |||||
4215 | MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); | ||||
4216 | if (New->isInvalidDecl()) | ||||
4217 | return; | ||||
4218 | |||||
4219 | diag::kind PrevDiag; | ||||
4220 | SourceLocation OldLocation; | ||||
4221 | std::tie(PrevDiag, OldLocation) = | ||||
4222 | getNoteDiagForInvalidRedeclaration(Old, New); | ||||
4223 | |||||
4224 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. | ||||
4225 | if (New->getStorageClass() == SC_Static && | ||||
4226 | !New->isStaticDataMember() && | ||||
4227 | Old->hasExternalFormalLinkage()) { | ||||
4228 | if (getLangOpts().MicrosoftExt) { | ||||
4229 | Diag(New->getLocation(), diag::ext_static_non_static) | ||||
4230 | << New->getDeclName(); | ||||
4231 | Diag(OldLocation, PrevDiag); | ||||
4232 | } else { | ||||
4233 | Diag(New->getLocation(), diag::err_static_non_static) | ||||
4234 | << New->getDeclName(); | ||||
4235 | Diag(OldLocation, PrevDiag); | ||||
4236 | return New->setInvalidDecl(); | ||||
4237 | } | ||||
4238 | } | ||||
4239 | // C99 6.2.2p4: | ||||
4240 | // For an identifier declared with the storage-class specifier | ||||
4241 | // extern in a scope in which a prior declaration of that | ||||
4242 | // identifier is visible,23) if the prior declaration specifies | ||||
4243 | // internal or external linkage, the linkage of the identifier at | ||||
4244 | // the later declaration is the same as the linkage specified at | ||||
4245 | // the prior declaration. If no prior declaration is visible, or | ||||
4246 | // if the prior declaration specifies no linkage, then the | ||||
4247 | // identifier has external linkage. | ||||
4248 | if (New->hasExternalStorage() && Old->hasLinkage()) | ||||
4249 | /* Okay */; | ||||
4250 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && | ||||
4251 | !New->isStaticDataMember() && | ||||
4252 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { | ||||
4253 | Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); | ||||
4254 | Diag(OldLocation, PrevDiag); | ||||
4255 | return New->setInvalidDecl(); | ||||
4256 | } | ||||
4257 | |||||
4258 | // Check if extern is followed by non-extern and vice-versa. | ||||
4259 | if (New->hasExternalStorage() && | ||||
4260 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { | ||||
4261 | Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); | ||||
4262 | Diag(OldLocation, PrevDiag); | ||||
4263 | return New->setInvalidDecl(); | ||||
4264 | } | ||||
4265 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && | ||||
4266 | !New->hasExternalStorage()) { | ||||
4267 | Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); | ||||
4268 | Diag(OldLocation, PrevDiag); | ||||
4269 | return New->setInvalidDecl(); | ||||
4270 | } | ||||
4271 | |||||
4272 | if (CheckRedeclarationModuleOwnership(New, Old)) | ||||
4273 | return; | ||||
4274 | |||||
4275 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. | ||||
4276 | |||||
4277 | // FIXME: The test for external storage here seems wrong? We still | ||||
4278 | // need to check for mismatches. | ||||
4279 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && | ||||
4280 | // Don't complain about out-of-line definitions of static members. | ||||
4281 | !(Old->getLexicalDeclContext()->isRecord() && | ||||
4282 | !New->getLexicalDeclContext()->isRecord())) { | ||||
4283 | Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); | ||||
4284 | Diag(OldLocation, PrevDiag); | ||||
4285 | return New->setInvalidDecl(); | ||||
4286 | } | ||||
4287 | |||||
4288 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { | ||||
4289 | if (VarDecl *Def = Old->getDefinition()) { | ||||
4290 | // C++1z [dcl.fcn.spec]p4: | ||||
4291 | // If the definition of a variable appears in a translation unit before | ||||
4292 | // its first declaration as inline, the program is ill-formed. | ||||
4293 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; | ||||
4294 | Diag(Def->getLocation(), diag::note_previous_definition); | ||||
4295 | } | ||||
4296 | } | ||||
4297 | |||||
4298 | // If this redeclaration makes the variable inline, we may need to add it to | ||||
4299 | // UndefinedButUsed. | ||||
4300 | if (!Old->isInline() && New->isInline() && Old->isUsed(false) && | ||||
4301 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) | ||||
4302 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | ||||
4303 | SourceLocation())); | ||||
4304 | |||||
4305 | if (New->getTLSKind() != Old->getTLSKind()) { | ||||
4306 | if (!Old->getTLSKind()) { | ||||
4307 | Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); | ||||
4308 | Diag(OldLocation, PrevDiag); | ||||
4309 | } else if (!New->getTLSKind()) { | ||||
4310 | Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); | ||||
4311 | Diag(OldLocation, PrevDiag); | ||||
4312 | } else { | ||||
4313 | // Do not allow redeclaration to change the variable between requiring | ||||
4314 | // static and dynamic initialization. | ||||
4315 | // FIXME: GCC allows this, but uses the TLS keyword on the first | ||||
4316 | // declaration to determine the kind. Do we need to be compatible here? | ||||
4317 | Diag(New->getLocation(), diag::err_thread_thread_different_kind) | ||||
4318 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); | ||||
4319 | Diag(OldLocation, PrevDiag); | ||||
4320 | } | ||||
4321 | } | ||||
4322 | |||||
4323 | // C++ doesn't have tentative definitions, so go right ahead and check here. | ||||
4324 | if (getLangOpts().CPlusPlus && | ||||
4325 | New->isThisDeclarationADefinition() == VarDecl::Definition) { | ||||
4326 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && | ||||
4327 | Old->getCanonicalDecl()->isConstexpr()) { | ||||
4328 | // This definition won't be a definition any more once it's been merged. | ||||
4329 | Diag(New->getLocation(), | ||||
4330 | diag::warn_deprecated_redundant_constexpr_static_def); | ||||
4331 | } else if (VarDecl *Def = Old->getDefinition()) { | ||||
4332 | if (checkVarDeclRedefinition(Def, New)) | ||||
4333 | return; | ||||
4334 | } | ||||
4335 | } | ||||
4336 | |||||
4337 | if (haveIncompatibleLanguageLinkages(Old, New)) { | ||||
4338 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | ||||
4339 | Diag(OldLocation, PrevDiag); | ||||
4340 | New->setInvalidDecl(); | ||||
4341 | return; | ||||
4342 | } | ||||
4343 | |||||
4344 | // Merge "used" flag. | ||||
4345 | if (Old->getMostRecentDecl()->isUsed(false)) | ||||
4346 | New->setIsUsed(); | ||||
4347 | |||||
4348 | // Keep a chain of previous declarations. | ||||
4349 | New->setPreviousDecl(Old); | ||||
4350 | if (NewTemplate) | ||||
4351 | NewTemplate->setPreviousDecl(OldTemplate); | ||||
4352 | |||||
4353 | // Inherit access appropriately. | ||||
4354 | New->setAccess(Old->getAccess()); | ||||
4355 | if (NewTemplate) | ||||
4356 | NewTemplate->setAccess(New->getAccess()); | ||||
4357 | |||||
4358 | if (Old->isInline()) | ||||
4359 | New->setImplicitlyInline(); | ||||
4360 | } | ||||
4361 | |||||
4362 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { | ||||
4363 | SourceManager &SrcMgr = getSourceManager(); | ||||
4364 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); | ||||
4365 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); | ||||
4366 | auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); | ||||
4367 | auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); | ||||
4368 | auto &HSI = PP.getHeaderSearchInfo(); | ||||
4369 | StringRef HdrFilename = | ||||
4370 | SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); | ||||
4371 | |||||
4372 | auto noteFromModuleOrInclude = [&](Module *Mod, | ||||
4373 | SourceLocation IncLoc) -> bool { | ||||
4374 | // Redefinition errors with modules are common with non modular mapped | ||||
4375 | // headers, example: a non-modular header H in module A that also gets | ||||
4376 | // included directly in a TU. Pointing twice to the same header/definition | ||||
4377 | // is confusing, try to get better diagnostics when modules is on. | ||||
4378 | if (IncLoc.isValid()) { | ||||
4379 | if (Mod) { | ||||
4380 | Diag(IncLoc, diag::note_redefinition_modules_same_file) | ||||
4381 | << HdrFilename.str() << Mod->getFullModuleName(); | ||||
4382 | if (!Mod->DefinitionLoc.isInvalid()) | ||||
4383 | Diag(Mod->DefinitionLoc, diag::note_defined_here) | ||||
4384 | << Mod->getFullModuleName(); | ||||
4385 | } else { | ||||
4386 | Diag(IncLoc, diag::note_redefinition_include_same_file) | ||||
4387 | << HdrFilename.str(); | ||||
4388 | } | ||||
4389 | return true; | ||||
4390 | } | ||||
4391 | |||||
4392 | return false; | ||||
4393 | }; | ||||
4394 | |||||
4395 | // Is it the same file and same offset? Provide more information on why | ||||
4396 | // this leads to a redefinition error. | ||||
4397 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { | ||||
4398 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); | ||||
4399 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); | ||||
4400 | bool EmittedDiag = | ||||
4401 | noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); | ||||
4402 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); | ||||
4403 | |||||
4404 | // If the header has no guards, emit a note suggesting one. | ||||
4405 | if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) | ||||
4406 | Diag(Old->getLocation(), diag::note_use_ifdef_guards); | ||||
4407 | |||||
4408 | if (EmittedDiag) | ||||
4409 | return; | ||||
4410 | } | ||||
4411 | |||||
4412 | // Redefinition coming from different files or couldn't do better above. | ||||
4413 | if (Old->getLocation().isValid()) | ||||
4414 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||
4415 | } | ||||
4416 | |||||
4417 | /// We've just determined that \p Old and \p New both appear to be definitions | ||||
4418 | /// of the same variable. Either diagnose or fix the problem. | ||||
4419 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { | ||||
4420 | if (!hasVisibleDefinition(Old) && | ||||
4421 | (New->getFormalLinkage() == InternalLinkage || | ||||
4422 | New->isInline() || | ||||
4423 | New->getDescribedVarTemplate() || | ||||
4424 | New->getNumTemplateParameterLists() || | ||||
4425 | New->getDeclContext()->isDependentContext())) { | ||||
4426 | // The previous definition is hidden, and multiple definitions are | ||||
4427 | // permitted (in separate TUs). Demote this to a declaration. | ||||
4428 | New->demoteThisDefinitionToDeclaration(); | ||||
4429 | |||||
4430 | // Make the canonical definition visible. | ||||
4431 | if (auto *OldTD = Old->getDescribedVarTemplate()) | ||||
4432 | makeMergedDefinitionVisible(OldTD); | ||||
4433 | makeMergedDefinitionVisible(Old); | ||||
4434 | return false; | ||||
4435 | } else { | ||||
4436 | Diag(New->getLocation(), diag::err_redefinition) << New; | ||||
4437 | notePreviousDefinition(Old, New->getLocation()); | ||||
4438 | New->setInvalidDecl(); | ||||
4439 | return true; | ||||
4440 | } | ||||
4441 | } | ||||
4442 | |||||
4443 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | ||||
4444 | /// no declarator (e.g. "struct foo;") is parsed. | ||||
4445 | Decl * | ||||
4446 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | ||||
4447 | RecordDecl *&AnonRecord) { | ||||
4448 | return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, | ||||
4449 | AnonRecord); | ||||
4450 | } | ||||
4451 | |||||
4452 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to | ||||
4453 | // disambiguate entities defined in different scopes. | ||||
4454 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks | ||||
4455 | // compatibility. | ||||
4456 | // We will pick our mangling number depending on which version of MSVC is being | ||||
4457 | // targeted. | ||||
4458 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { | ||||
4459 | return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) | ||||
4460 | ? S->getMSCurManglingNumber() | ||||
4461 | : S->getMSLastManglingNumber(); | ||||
4462 | } | ||||
4463 | |||||
4464 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { | ||||
4465 | if (!Context.getLangOpts().CPlusPlus) | ||||
4466 | return; | ||||
4467 | |||||
4468 | if (isa<CXXRecordDecl>(Tag->getParent())) { | ||||
4469 | // If this tag is the direct child of a class, number it if | ||||
4470 | // it is anonymous. | ||||
4471 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) | ||||
4472 | return; | ||||
4473 | MangleNumberingContext &MCtx = | ||||
4474 | Context.getManglingNumberContext(Tag->getParent()); | ||||
4475 | Context.setManglingNumber( | ||||
4476 | Tag, MCtx.getManglingNumber( | ||||
4477 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | ||||
4478 | return; | ||||
4479 | } | ||||
4480 | |||||
4481 | // If this tag isn't a direct child of a class, number it if it is local. | ||||
4482 | MangleNumberingContext *MCtx; | ||||
4483 | Decl *ManglingContextDecl; | ||||
4484 | std::tie(MCtx, ManglingContextDecl) = | ||||
4485 | getCurrentMangleNumberContext(Tag->getDeclContext()); | ||||
4486 | if (MCtx) { | ||||
4487 | Context.setManglingNumber( | ||||
4488 | Tag, MCtx->getManglingNumber( | ||||
4489 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | ||||
4490 | } | ||||
4491 | } | ||||
4492 | |||||
4493 | namespace { | ||||
4494 | struct NonCLikeKind { | ||||
4495 | enum { | ||||
4496 | None, | ||||
4497 | BaseClass, | ||||
4498 | DefaultMemberInit, | ||||
4499 | Lambda, | ||||
4500 | Friend, | ||||
4501 | OtherMember, | ||||
4502 | Invalid, | ||||
4503 | } Kind = None; | ||||
4504 | SourceRange Range; | ||||
4505 | |||||
4506 | explicit operator bool() { return Kind != None; } | ||||
4507 | }; | ||||
4508 | } | ||||
4509 | |||||
4510 | /// Determine whether a class is C-like, according to the rules of C++ | ||||
4511 | /// [dcl.typedef] for anonymous classes with typedef names for linkage. | ||||
4512 | static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { | ||||
4513 | if (RD->isInvalidDecl()) | ||||
4514 | return {NonCLikeKind::Invalid, {}}; | ||||
4515 | |||||
4516 | // C++ [dcl.typedef]p9: [P1766R1] | ||||
4517 | // An unnamed class with a typedef name for linkage purposes shall not | ||||
4518 | // | ||||
4519 | // -- have any base classes | ||||
4520 | if (RD->getNumBases()) | ||||
4521 | return {NonCLikeKind::BaseClass, | ||||
4522 | SourceRange(RD->bases_begin()->getBeginLoc(), | ||||
4523 | RD->bases_end()[-1].getEndLoc())}; | ||||
4524 | bool Invalid = false; | ||||
4525 | for (Decl *D : RD->decls()) { | ||||
4526 | // Don't complain about things we already diagnosed. | ||||
4527 | if (D->isInvalidDecl()) { | ||||
4528 | Invalid = true; | ||||
4529 | continue; | ||||
4530 | } | ||||
4531 | |||||
4532 | // -- have any [...] default member initializers | ||||
4533 | if (auto *FD = dyn_cast<FieldDecl>(D)) { | ||||
4534 | if (FD->hasInClassInitializer()) { | ||||
4535 | auto *Init = FD->getInClassInitializer(); | ||||
4536 | return {NonCLikeKind::DefaultMemberInit, | ||||
4537 | Init ? Init->getSourceRange() : D->getSourceRange()}; | ||||
4538 | } | ||||
4539 | continue; | ||||
4540 | } | ||||
4541 | |||||
4542 | // FIXME: We don't allow friend declarations. This violates the wording of | ||||
4543 | // P1766, but not the intent. | ||||
4544 | if (isa<FriendDecl>(D)) | ||||
4545 | return {NonCLikeKind::Friend, D->getSourceRange()}; | ||||
4546 | |||||
4547 | // -- declare any members other than non-static data members, member | ||||
4548 | // enumerations, or member classes, | ||||
4549 | if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || | ||||
4550 | isa<EnumDecl>(D)) | ||||
4551 | continue; | ||||
4552 | auto *MemberRD = dyn_cast<CXXRecordDecl>(D); | ||||
4553 | if (!MemberRD) { | ||||
4554 | if (D->isImplicit()) | ||||
4555 | continue; | ||||
4556 | return {NonCLikeKind::OtherMember, D->getSourceRange()}; | ||||
4557 | } | ||||
4558 | |||||
4559 | // -- contain a lambda-expression, | ||||
4560 | if (MemberRD->isLambda()) | ||||
4561 | return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; | ||||
4562 | |||||
4563 | // and all member classes shall also satisfy these requirements | ||||
4564 | // (recursively). | ||||
4565 | if (MemberRD->isThisDeclarationADefinition()) { | ||||
4566 | if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) | ||||
4567 | return Kind; | ||||
4568 | } | ||||
4569 | } | ||||
4570 | |||||
4571 | return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; | ||||
4572 | } | ||||
4573 | |||||
4574 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, | ||||
4575 | TypedefNameDecl *NewTD) { | ||||
4576 | if (TagFromDeclSpec->isInvalidDecl()) | ||||
4577 | return; | ||||
4578 | |||||
4579 | // Do nothing if the tag already has a name for linkage purposes. | ||||
4580 | if (TagFromDeclSpec->hasNameForLinkage()) | ||||
4581 | return; | ||||
4582 | |||||
4583 | // A well-formed anonymous tag must always be a TUK_Definition. | ||||
4584 | assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition ()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()" , "clang/lib/Sema/SemaDecl.cpp", 4584, __extension__ __PRETTY_FUNCTION__ )); | ||||
4585 | |||||
4586 | // The type must match the tag exactly; no qualifiers allowed. | ||||
4587 | if (!Context.hasSameType(NewTD->getUnderlyingType(), | ||||
4588 | Context.getTagDeclType(TagFromDeclSpec))) { | ||||
4589 | if (getLangOpts().CPlusPlus) | ||||
4590 | Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); | ||||
4591 | return; | ||||
4592 | } | ||||
4593 | |||||
4594 | // C++ [dcl.typedef]p9: [P1766R1, applied as DR] | ||||
4595 | // An unnamed class with a typedef name for linkage purposes shall [be | ||||
4596 | // C-like]. | ||||
4597 | // | ||||
4598 | // FIXME: Also diagnose if we've already computed the linkage. That ideally | ||||
4599 | // shouldn't happen, but there are constructs that the language rule doesn't | ||||
4600 | // disallow for which we can't reasonably avoid computing linkage early. | ||||
4601 | const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); | ||||
4602 | NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) | ||||
4603 | : NonCLikeKind(); | ||||
4604 | bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); | ||||
4605 | if (NonCLike || ChangesLinkage) { | ||||
4606 | if (NonCLike.Kind == NonCLikeKind::Invalid) | ||||
4607 | return; | ||||
4608 | |||||
4609 | unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; | ||||
4610 | if (ChangesLinkage) { | ||||
4611 | // If the linkage changes, we can't accept this as an extension. | ||||
4612 | if (NonCLike.Kind == NonCLikeKind::None) | ||||
4613 | DiagID = diag::err_typedef_changes_linkage; | ||||
4614 | else | ||||
4615 | DiagID = diag::err_non_c_like_anon_struct_in_typedef; | ||||
4616 | } | ||||
4617 | |||||
4618 | SourceLocation FixitLoc = | ||||
4619 | getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); | ||||
4620 | llvm::SmallString<40> TextToInsert; | ||||
4621 | TextToInsert += ' '; | ||||
4622 | TextToInsert += NewTD->getIdentifier()->getName(); | ||||
4623 | |||||
4624 | Diag(FixitLoc, DiagID) | ||||
4625 | << isa<TypeAliasDecl>(NewTD) | ||||
4626 | << FixItHint::CreateInsertion(FixitLoc, TextToInsert); | ||||
4627 | if (NonCLike.Kind != NonCLikeKind::None) { | ||||
4628 | Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) | ||||
4629 | << NonCLike.Kind - 1 << NonCLike.Range; | ||||
4630 | } | ||||
4631 | Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) | ||||
4632 | << NewTD << isa<TypeAliasDecl>(NewTD); | ||||
4633 | |||||
4634 | if (ChangesLinkage) | ||||
4635 | return; | ||||
4636 | } | ||||
4637 | |||||
4638 | // Otherwise, set this as the anon-decl typedef for the tag. | ||||
4639 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); | ||||
4640 | } | ||||
4641 | |||||
4642 | static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { | ||||
4643 | switch (T) { | ||||
4644 | case DeclSpec::TST_class: | ||||
4645 | return 0; | ||||
4646 | case DeclSpec::TST_struct: | ||||
4647 | return 1; | ||||
4648 | case DeclSpec::TST_interface: | ||||
4649 | return 2; | ||||
4650 | case DeclSpec::TST_union: | ||||
4651 | return 3; | ||||
4652 | case DeclSpec::TST_enum: | ||||
4653 | return 4; | ||||
4654 | default: | ||||
4655 | llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier" , "clang/lib/Sema/SemaDecl.cpp", 4655); | ||||
4656 | } | ||||
4657 | } | ||||
4658 | |||||
4659 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | ||||
4660 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template | ||||
4661 | /// parameters to cope with template friend declarations. | ||||
4662 | Decl * | ||||
4663 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | ||||
4664 | MultiTemplateParamsArg TemplateParams, | ||||
4665 | bool IsExplicitInstantiation, | ||||
4666 | RecordDecl *&AnonRecord) { | ||||
4667 | Decl *TagD = nullptr; | ||||
4668 | TagDecl *Tag = nullptr; | ||||
4669 | if (DS.getTypeSpecType() == DeclSpec::TST_class || | ||||
4670 | DS.getTypeSpecType() == DeclSpec::TST_struct || | ||||
4671 | DS.getTypeSpecType() == DeclSpec::TST_interface || | ||||
4672 | DS.getTypeSpecType() == DeclSpec::TST_union || | ||||
4673 | DS.getTypeSpecType() == DeclSpec::TST_enum) { | ||||
4674 | TagD = DS.getRepAsDecl(); | ||||
4675 | |||||
4676 | if (!TagD) // We probably had an error | ||||
4677 | return nullptr; | ||||
4678 | |||||
4679 | // Note that the above type specs guarantee that the | ||||
4680 | // type rep is a Decl, whereas in many of the others | ||||
4681 | // it's a Type. | ||||
4682 | if (isa<TagDecl>(TagD)) | ||||
4683 | Tag = cast<TagDecl>(TagD); | ||||
4684 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) | ||||
4685 | Tag = CTD->getTemplatedDecl(); | ||||
4686 | } | ||||
4687 | |||||
4688 | if (Tag) { | ||||
4689 | handleTagNumbering(Tag, S); | ||||
4690 | Tag->setFreeStanding(); | ||||
4691 | if (Tag->isInvalidDecl()) | ||||
4692 | return Tag; | ||||
4693 | } | ||||
4694 | |||||
4695 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | ||||
4696 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object | ||||
4697 | // or incomplete types shall not be restrict-qualified." | ||||
4698 | if (TypeQuals & DeclSpec::TQ_restrict) | ||||
4699 | Diag(DS.getRestrictSpecLoc(), | ||||
4700 | diag::err_typecheck_invalid_restrict_not_pointer_noarg) | ||||
4701 | << DS.getSourceRange(); | ||||
4702 | } | ||||
4703 | |||||
4704 | if (DS.isInlineSpecified()) | ||||
4705 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | ||||
4706 | << getLangOpts().CPlusPlus17; | ||||
4707 | |||||
4708 | if (DS.hasConstexprSpecifier()) { | ||||
4709 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations | ||||
4710 | // and definitions of functions and variables. | ||||
4711 | // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to | ||||
4712 | // the declaration of a function or function template | ||||
4713 | if (Tag) | ||||
4714 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) | ||||
4715 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) | ||||
4716 | << static_cast<int>(DS.getConstexprSpecifier()); | ||||
4717 | else | ||||
4718 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) | ||||
4719 | << static_cast<int>(DS.getConstexprSpecifier()); | ||||
4720 | // Don't emit warnings after this error. | ||||
4721 | return TagD; | ||||
4722 | } | ||||
4723 | |||||
4724 | DiagnoseFunctionSpecifiers(DS); | ||||
4725 | |||||
4726 | if (DS.isFriendSpecified()) { | ||||
4727 | // If we're dealing with a decl but not a TagDecl, assume that | ||||
4728 | // whatever routines created it handled the friendship aspect. | ||||
4729 | if (TagD && !Tag) | ||||
4730 | return nullptr; | ||||
4731 | return ActOnFriendTypeDecl(S, DS, TemplateParams); | ||||
4732 | } | ||||
4733 | |||||
4734 | const CXXScopeSpec &SS = DS.getTypeSpecScope(); | ||||
4735 | bool IsExplicitSpecialization = | ||||
4736 | !TemplateParams.empty() && TemplateParams.back()->size() == 0; | ||||
4737 | if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && | ||||
4738 | !IsExplicitInstantiation && !IsExplicitSpecialization && | ||||
4739 | !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { | ||||
4740 | // Per C++ [dcl.type.elab]p1, a class declaration cannot have a | ||||
4741 | // nested-name-specifier unless it is an explicit instantiation | ||||
4742 | // or an explicit specialization. | ||||
4743 | // | ||||
4744 | // FIXME: We allow class template partial specializations here too, per the | ||||
4745 | // obvious intent of DR1819. | ||||
4746 | // | ||||
4747 | // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. | ||||
4748 | Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) | ||||
4749 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); | ||||
4750 | return nullptr; | ||||
4751 | } | ||||
4752 | |||||
4753 | // Track whether this decl-specifier declares anything. | ||||
4754 | bool DeclaresAnything = true; | ||||
4755 | |||||
4756 | // Handle anonymous struct definitions. | ||||
4757 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { | ||||
4758 | if (!Record->getDeclName() && Record->isCompleteDefinition() && | ||||
4759 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { | ||||
4760 | if (getLangOpts().CPlusPlus || | ||||
4761 | Record->getDeclContext()->isRecord()) { | ||||
4762 | // If CurContext is a DeclContext that can contain statements, | ||||
4763 | // RecursiveASTVisitor won't visit the decls that | ||||
4764 | // BuildAnonymousStructOrUnion() will put into CurContext. | ||||
4765 | // Also store them here so that they can be part of the | ||||
4766 | // DeclStmt that gets created in this case. | ||||
4767 | // FIXME: Also return the IndirectFieldDecls created by | ||||
4768 | // BuildAnonymousStructOr union, for the same reason? | ||||
4769 | if (CurContext->isFunctionOrMethod()) | ||||
4770 | AnonRecord = Record; | ||||
4771 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, | ||||
4772 | Context.getPrintingPolicy()); | ||||
4773 | } | ||||
4774 | |||||
4775 | DeclaresAnything = false; | ||||
4776 | } | ||||
4777 | } | ||||
4778 | |||||
4779 | // C11 6.7.2.1p2: | ||||
4780 | // A struct-declaration that does not declare an anonymous structure or | ||||
4781 | // anonymous union shall contain a struct-declarator-list. | ||||
4782 | // | ||||
4783 | // This rule also existed in C89 and C99; the grammar for struct-declaration | ||||
4784 | // did not permit a struct-declaration without a struct-declarator-list. | ||||
4785 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && | ||||
4786 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { | ||||
4787 | // Check for Microsoft C extension: anonymous struct/union member. | ||||
4788 | // Handle 2 kinds of anonymous struct/union: | ||||
4789 | // struct STRUCT; | ||||
4790 | // union UNION; | ||||
4791 | // and | ||||
4792 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. | ||||
4793 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. | ||||
4794 | if ((Tag && Tag->getDeclName()) || | ||||
4795 | DS.getTypeSpecType() == DeclSpec::TST_typename) { | ||||
4796 | RecordDecl *Record = nullptr; | ||||
4797 | if (Tag) | ||||
4798 | Record = dyn_cast<RecordDecl>(Tag); | ||||
4799 | else if (const RecordType *RT = | ||||
4800 | DS.getRepAsType().get()->getAsStructureType()) | ||||
4801 | Record = RT->getDecl(); | ||||
4802 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) | ||||
4803 | Record = UT->getDecl(); | ||||
4804 | |||||
4805 | if (Record && getLangOpts().MicrosoftExt) { | ||||
4806 | Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) | ||||
4807 | << Record->isUnion() << DS.getSourceRange(); | ||||
4808 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); | ||||
4809 | } | ||||
4810 | |||||
4811 | DeclaresAnything = false; | ||||
4812 | } | ||||
4813 | } | ||||
4814 | |||||
4815 | // Skip all the checks below if we have a type error. | ||||
4816 | if (DS.getTypeSpecType() == DeclSpec::TST_error || | ||||
4817 | (TagD && TagD->isInvalidDecl())) | ||||
4818 | return TagD; | ||||
4819 | |||||
4820 | if (getLangOpts().CPlusPlus && | ||||
4821 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) | ||||
4822 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) | ||||
4823 | if (Enum->enumerator_begin() == Enum->enumerator_end() && | ||||
4824 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) | ||||
4825 | DeclaresAnything = false; | ||||
4826 | |||||
4827 | if (!DS.isMissingDeclaratorOk()) { | ||||
4828 | // Customize diagnostic for a typedef missing a name. | ||||
4829 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||
4830 | Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) | ||||
4831 | << DS.getSourceRange(); | ||||
4832 | else | ||||
4833 | DeclaresAnything = false; | ||||
4834 | } | ||||
4835 | |||||
4836 | if (DS.isModulePrivateSpecified() && | ||||
4837 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) | ||||
4838 | Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) | ||||
4839 | << Tag->getTagKind() | ||||
4840 | << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); | ||||
4841 | |||||
4842 | ActOnDocumentableDecl(TagD); | ||||
4843 | |||||
4844 | // C 6.7/2: | ||||
4845 | // A declaration [...] shall declare at least a declarator [...], a tag, | ||||
4846 | // or the members of an enumeration. | ||||
4847 | // C++ [dcl.dcl]p3: | ||||
4848 | // [If there are no declarators], and except for the declaration of an | ||||
4849 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | ||||
4850 | // names into the program, or shall redeclare a name introduced by a | ||||
4851 | // previous declaration. | ||||
4852 | if (!DeclaresAnything) { | ||||
4853 | // In C, we allow this as a (popular) extension / bug. Don't bother | ||||
4854 | // producing further diagnostics for redundant qualifiers after this. | ||||
4855 | Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) | ||||
4856 | ? diag::err_no_declarators | ||||
4857 | : diag::ext_no_declarators) | ||||
4858 | << DS.getSourceRange(); | ||||
4859 | return TagD; | ||||
4860 | } | ||||
4861 | |||||
4862 | // C++ [dcl.stc]p1: | ||||
4863 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the | ||||
4864 | // init-declarator-list of the declaration shall not be empty. | ||||
4865 | // C++ [dcl.fct.spec]p1: | ||||
4866 | // If a cv-qualifier appears in a decl-specifier-seq, the | ||||
4867 | // init-declarator-list of the declaration shall not be empty. | ||||
4868 | // | ||||
4869 | // Spurious qualifiers here appear to be valid in C. | ||||
4870 | unsigned DiagID = diag::warn_standalone_specifier; | ||||
4871 | if (getLangOpts().CPlusPlus) | ||||
4872 | DiagID = diag::ext_standalone_specifier; | ||||
4873 | |||||
4874 | // Note that a linkage-specification sets a storage class, but | ||||
4875 | // 'extern "C" struct foo;' is actually valid and not theoretically | ||||
4876 | // useless. | ||||
4877 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { | ||||
4878 | if (SCS == DeclSpec::SCS_mutable) | ||||
4879 | // Since mutable is not a viable storage class specifier in C, there is | ||||
4880 | // no reason to treat it as an extension. Instead, diagnose as an error. | ||||
4881 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); | ||||
4882 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) | ||||
4883 | Diag(DS.getStorageClassSpecLoc(), DiagID) | ||||
4884 | << DeclSpec::getSpecifierName(SCS); | ||||
4885 | } | ||||
4886 | |||||
4887 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | ||||
4888 | Diag(DS.getThreadStorageClassSpecLoc(), DiagID) | ||||
4889 | << DeclSpec::getSpecifierName(TSCS); | ||||
4890 | if (DS.getTypeQualifiers()) { | ||||
4891 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||
4892 | Diag(DS.getConstSpecLoc(), DiagID) << "const"; | ||||
4893 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||
4894 | Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; | ||||
4895 | // Restrict is covered above. | ||||
4896 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||
4897 | Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; | ||||
4898 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||
4899 | Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; | ||||
4900 | } | ||||
4901 | |||||
4902 | // Warn about ignored type attributes, for example: | ||||
4903 | // __attribute__((aligned)) struct A; | ||||
4904 | // Attributes should be placed after tag to apply to type declaration. | ||||
4905 | if (!DS.getAttributes().empty()) { | ||||
4906 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); | ||||
4907 | if (TypeSpecType == DeclSpec::TST_class || | ||||
4908 | TypeSpecType == DeclSpec::TST_struct || | ||||
4909 | TypeSpecType == DeclSpec::TST_interface || | ||||
4910 | TypeSpecType == DeclSpec::TST_union || | ||||
4911 | TypeSpecType == DeclSpec::TST_enum) { | ||||
4912 | for (const ParsedAttr &AL : DS.getAttributes()) | ||||
4913 | Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) | ||||
4914 | << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); | ||||
4915 | } | ||||
4916 | } | ||||
4917 | |||||
4918 | return TagD; | ||||
4919 | } | ||||
4920 | |||||
4921 | /// We are trying to inject an anonymous member into the given scope; | ||||
4922 | /// check if there's an existing declaration that can't be overloaded. | ||||
4923 | /// | ||||
4924 | /// \return true if this is a forbidden redeclaration | ||||
4925 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, | ||||
4926 | Scope *S, | ||||
4927 | DeclContext *Owner, | ||||
4928 | DeclarationName Name, | ||||
4929 | SourceLocation NameLoc, | ||||
4930 | bool IsUnion) { | ||||
4931 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, | ||||
4932 | Sema::ForVisibleRedeclaration); | ||||
4933 | if (!SemaRef.LookupName(R, S)) return false; | ||||
4934 | |||||
4935 | // Pick a representative declaration. | ||||
4936 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); | ||||
4937 | assert(PrevDecl && "Expected a non-null Decl")(static_cast <bool> (PrevDecl && "Expected a non-null Decl" ) ? void (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\"" , "clang/lib/Sema/SemaDecl.cpp", 4937, __extension__ __PRETTY_FUNCTION__ )); | ||||
4938 | |||||
4939 | if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) | ||||
4940 | return false; | ||||
4941 | |||||
4942 | SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) | ||||
4943 | << IsUnion << Name; | ||||
4944 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||
4945 | |||||
4946 | return true; | ||||
4947 | } | ||||
4948 | |||||
4949 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the | ||||
4950 | /// anonymous struct or union AnonRecord into the owning context Owner | ||||
4951 | /// and scope S. This routine will be invoked just after we realize | ||||
4952 | /// that an unnamed union or struct is actually an anonymous union or | ||||
4953 | /// struct, e.g., | ||||
4954 | /// | ||||
4955 | /// @code | ||||
4956 | /// union { | ||||
4957 | /// int i; | ||||
4958 | /// float f; | ||||
4959 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and | ||||
4960 | /// // f into the surrounding scope.x | ||||
4961 | /// @endcode | ||||
4962 | /// | ||||
4963 | /// This routine is recursive, injecting the names of nested anonymous | ||||
4964 | /// structs/unions into the owning context and scope as well. | ||||
4965 | static bool | ||||
4966 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, | ||||
4967 | RecordDecl *AnonRecord, AccessSpecifier AS, | ||||
4968 | SmallVectorImpl<NamedDecl *> &Chaining) { | ||||
4969 | bool Invalid = false; | ||||
4970 | |||||
4971 | // Look every FieldDecl and IndirectFieldDecl with a name. | ||||
4972 | for (auto *D : AnonRecord->decls()) { | ||||
4973 | if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && | ||||
4974 | cast<NamedDecl>(D)->getDeclName()) { | ||||
4975 | ValueDecl *VD = cast<ValueDecl>(D); | ||||
4976 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), | ||||
4977 | VD->getLocation(), | ||||
4978 | AnonRecord->isUnion())) { | ||||
4979 | // C++ [class.union]p2: | ||||
4980 | // The names of the members of an anonymous union shall be | ||||
4981 | // distinct from the names of any other entity in the | ||||
4982 | // scope in which the anonymous union is declared. | ||||
4983 | Invalid = true; | ||||
4984 | } else { | ||||
4985 | // C++ [class.union]p2: | ||||
4986 | // For the purpose of name lookup, after the anonymous union | ||||
4987 | // definition, the members of the anonymous union are | ||||
4988 | // considered to have been defined in the scope in which the | ||||
4989 | // anonymous union is declared. | ||||
4990 | unsigned OldChainingSize = Chaining.size(); | ||||
4991 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) | ||||
4992 | Chaining.append(IF->chain_begin(), IF->chain_end()); | ||||
4993 | else | ||||
4994 | Chaining.push_back(VD); | ||||
4995 | |||||
4996 | assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0 ) : __assert_fail ("Chaining.size() >= 2", "clang/lib/Sema/SemaDecl.cpp" , 4996, __extension__ __PRETTY_FUNCTION__)); | ||||
4997 | NamedDecl **NamedChain = | ||||
4998 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; | ||||
4999 | for (unsigned i = 0; i < Chaining.size(); i++) | ||||
5000 | NamedChain[i] = Chaining[i]; | ||||
5001 | |||||
5002 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( | ||||
5003 | SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), | ||||
5004 | VD->getType(), {NamedChain, Chaining.size()}); | ||||
5005 | |||||
5006 | for (const auto *Attr : VD->attrs()) | ||||
5007 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); | ||||
5008 | |||||
5009 | IndirectField->setAccess(AS); | ||||
5010 | IndirectField->setImplicit(); | ||||
5011 | SemaRef.PushOnScopeChains(IndirectField, S); | ||||
5012 | |||||
5013 | // That includes picking up the appropriate access specifier. | ||||
5014 | if (AS != AS_none) IndirectField->setAccess(AS); | ||||
5015 | |||||
5016 | Chaining.resize(OldChainingSize); | ||||
5017 | } | ||||
5018 | } | ||||
5019 | } | ||||
5020 | |||||
5021 | return Invalid; | ||||
5022 | } | ||||
5023 | |||||
5024 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to | ||||
5025 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: | ||||
5026 | /// illegal input values are mapped to SC_None. | ||||
5027 | static StorageClass | ||||
5028 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { | ||||
5029 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); | ||||
5030 | assert(StorageClassSpec != DeclSpec::SCS_typedef &&(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "clang/lib/Sema/SemaDecl.cpp", 5031, __extension__ __PRETTY_FUNCTION__ )) | ||||
5031 | "Parser allowed 'typedef' as storage class VarDecl.")(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "clang/lib/Sema/SemaDecl.cpp", 5031, __extension__ __PRETTY_FUNCTION__ )); | ||||
5032 | switch (StorageClassSpec) { | ||||
5033 | case DeclSpec::SCS_unspecified: return SC_None; | ||||
5034 | case DeclSpec::SCS_extern: | ||||
5035 | if (DS.isExternInLinkageSpec()) | ||||
5036 | return SC_None; | ||||
5037 | return SC_Extern; | ||||
5038 | case DeclSpec::SCS_static: return SC_Static; | ||||
5039 | case DeclSpec::SCS_auto: return SC_Auto; | ||||
5040 | case DeclSpec::SCS_register: return SC_Register; | ||||
5041 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | ||||
5042 | // Illegal SCSs map to None: error reporting is up to the caller. | ||||
5043 | case DeclSpec::SCS_mutable: // Fall through. | ||||
5044 | case DeclSpec::SCS_typedef: return SC_None; | ||||
5045 | } | ||||
5046 | llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier" , "clang/lib/Sema/SemaDecl.cpp", 5046); | ||||
5047 | } | ||||
5048 | |||||
5049 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { | ||||
5050 | assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer() ) ? void (0) : __assert_fail ("Record->hasInClassInitializer()" , "clang/lib/Sema/SemaDecl.cpp", 5050, __extension__ __PRETTY_FUNCTION__ )); | ||||
5051 | |||||
5052 | for (const auto *I : Record->decls()) { | ||||
5053 | const auto *FD = dyn_cast<FieldDecl>(I); | ||||
5054 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | ||||
5055 | FD = IFD->getAnonField(); | ||||
5056 | if (FD && FD->hasInClassInitializer()) | ||||
5057 | return FD->getLocation(); | ||||
5058 | } | ||||
5059 | |||||
5060 | llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer" , "clang/lib/Sema/SemaDecl.cpp", 5060); | ||||
5061 | } | ||||
5062 | |||||
5063 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | ||||
5064 | SourceLocation DefaultInitLoc) { | ||||
5065 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | ||||
5066 | return; | ||||
5067 | |||||
5068 | S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); | ||||
5069 | S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; | ||||
5070 | } | ||||
5071 | |||||
5072 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | ||||
5073 | CXXRecordDecl *AnonUnion) { | ||||
5074 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | ||||
5075 | return; | ||||
5076 | |||||
5077 | checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); | ||||
5078 | } | ||||
5079 | |||||
5080 | /// BuildAnonymousStructOrUnion - Handle the declaration of an | ||||
5081 | /// anonymous structure or union. Anonymous unions are a C++ feature | ||||
5082 | /// (C++ [class.union]) and a C11 feature; anonymous structures | ||||
5083 | /// are a C11 feature and GNU C++ extension. | ||||
5084 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, | ||||
5085 | AccessSpecifier AS, | ||||
5086 | RecordDecl *Record, | ||||
5087 | const PrintingPolicy &Policy) { | ||||
5088 | DeclContext *Owner = Record->getDeclContext(); | ||||
5089 | |||||
5090 | // Diagnose whether this anonymous struct/union is an extension. | ||||
5091 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) | ||||
5092 | Diag(Record->getLocation(), diag::ext_anonymous_union); | ||||
5093 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) | ||||
5094 | Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); | ||||
5095 | else if (!Record->isUnion() && !getLangOpts().C11) | ||||
5096 | Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); | ||||
5097 | |||||
5098 | // C and C++ require different kinds of checks for anonymous | ||||
5099 | // structs/unions. | ||||
5100 | bool Invalid = false; | ||||
5101 | if (getLangOpts().CPlusPlus) { | ||||
5102 | const char *PrevSpec = nullptr; | ||||
5103 | if (Record->isUnion()) { | ||||
5104 | // C++ [class.union]p6: | ||||
5105 | // C++17 [class.union.anon]p2: | ||||
5106 | // Anonymous unions declared in a named namespace or in the | ||||
5107 | // global namespace shall be declared static. | ||||
5108 | unsigned DiagID; | ||||
5109 | DeclContext *OwnerScope = Owner->getRedeclContext(); | ||||
5110 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && | ||||
5111 | (OwnerScope->isTranslationUnit() || | ||||
5112 | (OwnerScope->isNamespace() && | ||||
5113 | !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { | ||||
5114 | Diag(Record->getLocation(), diag::err_anonymous_union_not_static) | ||||
5115 | << FixItHint::CreateInsertion(Record->getLocation(), "static "); | ||||
5116 | |||||
5117 | // Recover by adding 'static'. | ||||
5118 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), | ||||
5119 | PrevSpec, DiagID, Policy); | ||||
5120 | } | ||||
5121 | // C++ [class.union]p6: | ||||
5122 | // A storage class is not allowed in a declaration of an | ||||
5123 | // anonymous union in a class scope. | ||||
5124 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && | ||||
5125 | isa<RecordDecl>(Owner)) { | ||||
5126 | Diag(DS.getStorageClassSpecLoc(), | ||||
5127 | diag::err_anonymous_union_with_storage_spec) | ||||
5128 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||
5129 | |||||
5130 | // Recover by removing the storage specifier. | ||||
5131 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, | ||||
5132 | SourceLocation(), | ||||
5133 | PrevSpec, DiagID, Context.getPrintingPolicy()); | ||||
5134 | } | ||||
5135 | } | ||||
5136 | |||||
5137 | // Ignore const/volatile/restrict qualifiers. | ||||
5138 | if (DS.getTypeQualifiers()) { | ||||
5139 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||
5140 | Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) | ||||
5141 | << Record->isUnion() << "const" | ||||
5142 | << FixItHint::CreateRemoval(DS.getConstSpecLoc()); | ||||
5143 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||
5144 | Diag(DS.getVolatileSpecLoc(), | ||||
5145 | diag::ext_anonymous_struct_union_qualified) | ||||
5146 | << Record->isUnion() << "volatile" | ||||
5147 | << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); | ||||
5148 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) | ||||
5149 | Diag(DS.getRestrictSpecLoc(), | ||||
5150 | diag::ext_anonymous_struct_union_qualified) | ||||
5151 | << Record->isUnion() << "restrict" | ||||
5152 | << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); | ||||
5153 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||
5154 | Diag(DS.getAtomicSpecLoc(), | ||||
5155 | diag::ext_anonymous_struct_union_qualified) | ||||
5156 | << Record->isUnion() << "_Atomic" | ||||
5157 | << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); | ||||
5158 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||
5159 | Diag(DS.getUnalignedSpecLoc(), | ||||
5160 | diag::ext_anonymous_struct_union_qualified) | ||||
5161 | << Record->isUnion() << "__unaligned" | ||||
5162 | << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); | ||||
5163 | |||||
5164 | DS.ClearTypeQualifiers(); | ||||
5165 | } | ||||
5166 | |||||
5167 | // C++ [class.union]p2: | ||||
5168 | // The member-specification of an anonymous union shall only | ||||
5169 | // define non-static data members. [Note: nested types and | ||||
5170 | // functions cannot be declared within an anonymous union. ] | ||||
5171 | for (auto *Mem : Record->decls()) { | ||||
5172 | // Ignore invalid declarations; we already diagnosed them. | ||||
5173 | if (Mem->isInvalidDecl()) | ||||
5174 | continue; | ||||
5175 | |||||
5176 | if (auto *FD = dyn_cast<FieldDecl>(Mem)) { | ||||
5177 | // C++ [class.union]p3: | ||||
5178 | // An anonymous union shall not have private or protected | ||||
5179 | // members (clause 11). | ||||
5180 | assert(FD->getAccess() != AS_none)(static_cast <bool> (FD->getAccess() != AS_none) ? void (0) : __assert_fail ("FD->getAccess() != AS_none", "clang/lib/Sema/SemaDecl.cpp" , 5180, __extension__ __PRETTY_FUNCTION__)); | ||||
5181 | if (FD->getAccess() != AS_public) { | ||||
5182 | Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) | ||||
5183 | << Record->isUnion() << (FD->getAccess() == AS_protected); | ||||
5184 | Invalid = true; | ||||
5185 | } | ||||
5186 | |||||
5187 | // C++ [class.union]p1 | ||||
5188 | // An object of a class with a non-trivial constructor, a non-trivial | ||||
5189 | // copy constructor, a non-trivial destructor, or a non-trivial copy | ||||
5190 | // assignment operator cannot be a member of a union, nor can an | ||||
5191 | // array of such objects. | ||||
5192 | if (CheckNontrivialField(FD)) | ||||
5193 | Invalid = true; | ||||
5194 | } else if (Mem->isImplicit()) { | ||||
5195 | // Any implicit members are fine. | ||||
5196 | } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { | ||||
5197 | // This is a type that showed up in an | ||||
5198 | // elaborated-type-specifier inside the anonymous struct or | ||||
5199 | // union, but which actually declares a type outside of the | ||||
5200 | // anonymous struct or union. It's okay. | ||||
5201 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { | ||||
5202 | if (!MemRecord->isAnonymousStructOrUnion() && | ||||
5203 | MemRecord->getDeclName()) { | ||||
5204 | // Visual C++ allows type definition in anonymous struct or union. | ||||
5205 | if (getLangOpts().MicrosoftExt) | ||||
5206 | Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) | ||||
5207 | << Record->isUnion(); | ||||
5208 | else { | ||||
5209 | // This is a nested type declaration. | ||||
5210 | Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) | ||||
5211 | << Record->isUnion(); | ||||
5212 | Invalid = true; | ||||
5213 | } | ||||
5214 | } else { | ||||
5215 | // This is an anonymous type definition within another anonymous type. | ||||
5216 | // This is a popular extension, provided by Plan9, MSVC and GCC, but | ||||
5217 | // not part of standard C++. | ||||
5218 | Diag(MemRecord->getLocation(), | ||||
5219 | diag::ext_anonymous_record_with_anonymous_type) | ||||
5220 | << Record->isUnion(); | ||||
5221 | } | ||||
5222 | } else if (isa<AccessSpecDecl>(Mem)) { | ||||
5223 | // Any access specifier is fine. | ||||
5224 | } else if (isa<StaticAssertDecl>(Mem)) { | ||||
5225 | // In C++1z, static_assert declarations are also fine. | ||||
5226 | } else { | ||||
5227 | // We have something that isn't a non-static data | ||||
5228 | // member. Complain about it. | ||||
5229 | unsigned DK = diag::err_anonymous_record_bad_member; | ||||
5230 | if (isa<TypeDecl>(Mem)) | ||||
5231 | DK = diag::err_anonymous_record_with_type; | ||||
5232 | else if (isa<FunctionDecl>(Mem)) | ||||
5233 | DK = diag::err_anonymous_record_with_function; | ||||
5234 | else if (isa<VarDecl>(Mem)) | ||||
5235 | DK = diag::err_anonymous_record_with_static; | ||||
5236 | |||||
5237 | // Visual C++ allows type definition in anonymous struct or union. | ||||
5238 | if (getLangOpts().MicrosoftExt && | ||||
5239 | DK == diag::err_anonymous_record_with_type) | ||||
5240 | Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) | ||||
5241 | << Record->isUnion(); | ||||
5242 | else { | ||||
5243 | Diag(Mem->getLocation(), DK) << Record->isUnion(); | ||||
5244 | Invalid = true; | ||||
5245 | } | ||||
5246 | } | ||||
5247 | } | ||||
5248 | |||||
5249 | // C++11 [class.union]p8 (DR1460): | ||||
5250 | // At most one variant member of a union may have a | ||||
5251 | // brace-or-equal-initializer. | ||||
5252 | if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && | ||||
5253 | Owner->isRecord()) | ||||
5254 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), | ||||
5255 | cast<CXXRecordDecl>(Record)); | ||||
5256 | } | ||||
5257 | |||||
5258 | if (!Record->isUnion() && !Owner->isRecord()) { | ||||
5259 | Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) | ||||
5260 | << getLangOpts().CPlusPlus; | ||||
5261 | Invalid = true; | ||||
5262 | } | ||||
5263 | |||||
5264 | // C++ [dcl.dcl]p3: | ||||
5265 | // [If there are no declarators], and except for the declaration of an | ||||
5266 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | ||||
5267 | // names into the program | ||||
5268 | // C++ [class.mem]p2: | ||||
5269 | // each such member-declaration shall either declare at least one member | ||||
5270 | // name of the class or declare at least one unnamed bit-field | ||||
5271 | // | ||||
5272 | // For C this is an error even for a named struct, and is diagnosed elsewhere. | ||||
5273 | if (getLangOpts().CPlusPlus && Record->field_empty()) | ||||
5274 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | ||||
5275 | |||||
5276 | // Mock up a declarator. | ||||
5277 | Declarator Dc(DS, DeclaratorContext::Member); | ||||
5278 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | ||||
5279 | assert(TInfo && "couldn't build declarator info for anonymous struct/union")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct/union" ) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\"" , "clang/lib/Sema/SemaDecl.cpp", 5279, __extension__ __PRETTY_FUNCTION__ )); | ||||
5280 | |||||
5281 | // Create a declaration for this anonymous struct/union. | ||||
5282 | NamedDecl *Anon = nullptr; | ||||
5283 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { | ||||
5284 | Anon = FieldDecl::Create( | ||||
5285 | Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), | ||||
5286 | /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, | ||||
5287 | /*BitWidth=*/nullptr, /*Mutable=*/false, | ||||
5288 | /*InitStyle=*/ICIS_NoInit); | ||||
5289 | Anon->setAccess(AS); | ||||
5290 | ProcessDeclAttributes(S, Anon, Dc); | ||||
5291 | |||||
5292 | if (getLangOpts().CPlusPlus) | ||||
5293 | FieldCollector->Add(cast<FieldDecl>(Anon)); | ||||
5294 | } else { | ||||
5295 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); | ||||
5296 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); | ||||
5297 | if (SCSpec == DeclSpec::SCS_mutable) { | ||||
5298 | // mutable can only appear on non-static class members, so it's always | ||||
5299 | // an error here | ||||
5300 | Diag(Record->getLocation(), diag::err_mutable_nonmember); | ||||
5301 | Invalid = true; | ||||
5302 | SC = SC_None; | ||||
5303 | } | ||||
5304 | |||||
5305 | assert(DS.getAttributes().empty() && "No attribute expected")(static_cast <bool> (DS.getAttributes().empty() && "No attribute expected") ? void (0) : __assert_fail ("DS.getAttributes().empty() && \"No attribute expected\"" , "clang/lib/Sema/SemaDecl.cpp", 5305, __extension__ __PRETTY_FUNCTION__ )); | ||||
5306 | Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), | ||||
5307 | Record->getLocation(), /*IdentifierInfo=*/nullptr, | ||||
5308 | Context.getTypeDeclType(Record), TInfo, SC); | ||||
5309 | |||||
5310 | // Default-initialize the implicit variable. This initialization will be | ||||
5311 | // trivial in almost all cases, except if a union member has an in-class | ||||
5312 | // initializer: | ||||
5313 | // union { int n = 0; }; | ||||
5314 | ActOnUninitializedDecl(Anon); | ||||
5315 | } | ||||
5316 | Anon->setImplicit(); | ||||
5317 | |||||
5318 | // Mark this as an anonymous struct/union type. | ||||
5319 | Record->setAnonymousStructOrUnion(true); | ||||
5320 | |||||
5321 | // Add the anonymous struct/union object to the current | ||||
5322 | // context. We'll be referencing this object when we refer to one of | ||||
5323 | // its members. | ||||
5324 | Owner->addDecl(Anon); | ||||
5325 | |||||
5326 | // Inject the members of the anonymous struct/union into the owning | ||||
5327 | // context and into the identifier resolver chain for name lookup | ||||
5328 | // purposes. | ||||
5329 | SmallVector<NamedDecl*, 2> Chain; | ||||
5330 | Chain.push_back(Anon); | ||||
5331 | |||||
5332 | if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) | ||||
5333 | Invalid = true; | ||||
5334 | |||||
5335 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { | ||||
5336 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | ||||
5337 | MangleNumberingContext *MCtx; | ||||
5338 | Decl *ManglingContextDecl; | ||||
5339 | std::tie(MCtx, ManglingContextDecl) = | ||||
5340 | getCurrentMangleNumberContext(NewVD->getDeclContext()); | ||||
5341 | if (MCtx) { | ||||
5342 | Context.setManglingNumber( | ||||
5343 | NewVD, MCtx->getManglingNumber( | ||||
5344 | NewVD, getMSManglingNumber(getLangOpts(), S))); | ||||
5345 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | ||||
5346 | } | ||||
5347 | } | ||||
5348 | } | ||||
5349 | |||||
5350 | if (Invalid) | ||||
5351 | Anon->setInvalidDecl(); | ||||
5352 | |||||
5353 | return Anon; | ||||
5354 | } | ||||
5355 | |||||
5356 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an | ||||
5357 | /// Microsoft C anonymous structure. | ||||
5358 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx | ||||
5359 | /// Example: | ||||
5360 | /// | ||||
5361 | /// struct A { int a; }; | ||||
5362 | /// struct B { struct A; int b; }; | ||||
5363 | /// | ||||
5364 | /// void foo() { | ||||
5365 | /// B var; | ||||
5366 | /// var.a = 3; | ||||
5367 | /// } | ||||
5368 | /// | ||||
5369 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, | ||||
5370 | RecordDecl *Record) { | ||||
5371 | assert(Record && "expected a record!")(static_cast <bool> (Record && "expected a record!" ) ? void (0) : __assert_fail ("Record && \"expected a record!\"" , "clang/lib/Sema/SemaDecl.cpp", 5371, __extension__ __PRETTY_FUNCTION__ )); | ||||
5372 | |||||
5373 | // Mock up a declarator. | ||||
5374 | Declarator Dc(DS, DeclaratorContext::TypeName); | ||||
5375 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | ||||
5376 | assert(TInfo && "couldn't build declarator info for anonymous struct")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct" ) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\"" , "clang/lib/Sema/SemaDecl.cpp", 5376, __extension__ __PRETTY_FUNCTION__ )); | ||||
5377 | |||||
5378 | auto *ParentDecl = cast<RecordDecl>(CurContext); | ||||
5379 | QualType RecTy = Context.getTypeDeclType(Record); | ||||
5380 | |||||
5381 | // Create a declaration for this anonymous struct. | ||||
5382 | NamedDecl *Anon = | ||||
5383 | FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), | ||||
5384 | /*IdentifierInfo=*/nullptr, RecTy, TInfo, | ||||
5385 | /*BitWidth=*/nullptr, /*Mutable=*/false, | ||||
5386 | /*InitStyle=*/ICIS_NoInit); | ||||
5387 | Anon->setImplicit(); | ||||
5388 | |||||
5389 | // Add the anonymous struct object to the current context. | ||||
5390 | CurContext->addDecl(Anon); | ||||
5391 | |||||
5392 | // Inject the members of the anonymous struct into the current | ||||
5393 | // context and into the identifier resolver chain for name lookup | ||||
5394 | // purposes. | ||||
5395 | SmallVector<NamedDecl*, 2> Chain; | ||||
5396 | Chain.push_back(Anon); | ||||
5397 | |||||
5398 | RecordDecl *RecordDef = Record->getDefinition(); | ||||
5399 | if (RequireCompleteSizedType(Anon->getLocation(), RecTy, | ||||
5400 | diag::err_field_incomplete_or_sizeless) || | ||||
5401 | InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, | ||||
5402 | AS_none, Chain)) { | ||||
5403 | Anon->setInvalidDecl(); | ||||
5404 | ParentDecl->setInvalidDecl(); | ||||
5405 | } | ||||
5406 | |||||
5407 | return Anon; | ||||
5408 | } | ||||
5409 | |||||
5410 | /// GetNameForDeclarator - Determine the full declaration name for the | ||||
5411 | /// given Declarator. | ||||
5412 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { | ||||
5413 | return GetNameFromUnqualifiedId(D.getName()); | ||||
5414 | } | ||||
5415 | |||||
5416 | /// Retrieves the declaration name from a parsed unqualified-id. | ||||
5417 | DeclarationNameInfo | ||||
5418 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { | ||||
5419 | DeclarationNameInfo NameInfo; | ||||
5420 | NameInfo.setLoc(Name.StartLocation); | ||||
5421 | |||||
5422 | switch (Name.getKind()) { | ||||
5423 | |||||
5424 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||
5425 | case UnqualifiedIdKind::IK_Identifier: | ||||
5426 | NameInfo.setName(Name.Identifier); | ||||
5427 | return NameInfo; | ||||
5428 | |||||
5429 | case UnqualifiedIdKind::IK_DeductionGuideName: { | ||||
5430 | // C++ [temp.deduct.guide]p3: | ||||
5431 | // The simple-template-id shall name a class template specialization. | ||||
5432 | // The template-name shall be the same identifier as the template-name | ||||
5433 | // of the simple-template-id. | ||||
5434 | // These together intend to imply that the template-name shall name a | ||||
5435 | // class template. | ||||
5436 | // FIXME: template<typename T> struct X {}; | ||||
5437 | // template<typename T> using Y = X<T>; | ||||
5438 | // Y(int) -> Y<int>; | ||||
5439 | // satisfies these rules but does not name a class template. | ||||
5440 | TemplateName TN = Name.TemplateName.get().get(); | ||||
5441 | auto *Template = TN.getAsTemplateDecl(); | ||||
5442 | if (!Template || !isa<ClassTemplateDecl>(Template)) { | ||||
5443 | Diag(Name.StartLocation, | ||||
5444 | diag::err_deduction_guide_name_not_class_template) | ||||
5445 | << (int)getTemplateNameKindForDiagnostics(TN) << TN; | ||||
5446 | if (Template) | ||||
5447 | Diag(Template->getLocation(), diag::note_template_decl_here); | ||||
5448 | return DeclarationNameInfo(); | ||||
5449 | } | ||||
5450 | |||||
5451 | NameInfo.setName( | ||||
5452 | Context.DeclarationNames.getCXXDeductionGuideName(Template)); | ||||
5453 | return NameInfo; | ||||
5454 | } | ||||
5455 | |||||
5456 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||
5457 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( | ||||
5458 | Name.OperatorFunctionId.Operator)); | ||||
5459 | NameInfo.setCXXOperatorNameRange(SourceRange( | ||||
5460 | Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); | ||||
5461 | return NameInfo; | ||||
5462 | |||||
5463 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||
5464 | NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( | ||||
5465 | Name.Identifier)); | ||||
5466 | NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); | ||||
5467 | return NameInfo; | ||||
5468 | |||||
5469 | case UnqualifiedIdKind::IK_ConversionFunctionId: { | ||||
5470 | TypeSourceInfo *TInfo; | ||||
5471 | QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); | ||||
5472 | if (Ty.isNull()) | ||||
5473 | return DeclarationNameInfo(); | ||||
5474 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( | ||||
5475 | Context.getCanonicalType(Ty))); | ||||
5476 | NameInfo.setNamedTypeInfo(TInfo); | ||||
5477 | return NameInfo; | ||||
5478 | } | ||||
5479 | |||||
5480 | case UnqualifiedIdKind::IK_ConstructorName: { | ||||
5481 | TypeSourceInfo *TInfo; | ||||
5482 | QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); | ||||
5483 | if (Ty.isNull()) | ||||
5484 | return DeclarationNameInfo(); | ||||
5485 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | ||||
5486 | Context.getCanonicalType(Ty))); | ||||
5487 | NameInfo.setNamedTypeInfo(TInfo); | ||||
5488 | return NameInfo; | ||||
5489 | } | ||||
5490 | |||||
5491 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { | ||||
5492 | // In well-formed code, we can only have a constructor | ||||
5493 | // template-id that refers to the current context, so go there | ||||
5494 | // to find the actual type being constructed. | ||||
5495 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); | ||||
5496 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) | ||||
5497 | return DeclarationNameInfo(); | ||||
5498 | |||||
5499 | // Determine the type of the class being constructed. | ||||
5500 | QualType CurClassType = Context.getTypeDeclType(CurClass); | ||||
5501 | |||||
5502 | // FIXME: Check two things: that the template-id names the same type as | ||||
5503 | // CurClassType, and that the template-id does not occur when the name | ||||
5504 | // was qualified. | ||||
5505 | |||||
5506 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | ||||
5507 | Context.getCanonicalType(CurClassType))); | ||||
5508 | // FIXME: should we retrieve TypeSourceInfo? | ||||
5509 | NameInfo.setNamedTypeInfo(nullptr); | ||||
5510 | return NameInfo; | ||||
5511 | } | ||||
5512 | |||||
5513 | case UnqualifiedIdKind::IK_DestructorName: { | ||||
5514 | TypeSourceInfo *TInfo; | ||||
5515 | QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); | ||||
5516 | if (Ty.isNull()) | ||||
5517 | return DeclarationNameInfo(); | ||||
5518 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( | ||||
5519 | Context.getCanonicalType(Ty))); | ||||
5520 | NameInfo.setNamedTypeInfo(TInfo); | ||||
5521 | return NameInfo; | ||||
5522 | } | ||||
5523 | |||||
5524 | case UnqualifiedIdKind::IK_TemplateId: { | ||||
5525 | TemplateName TName = Name.TemplateId->Template.get(); | ||||
5526 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; | ||||
5527 | return Context.getNameForTemplate(TName, TNameLoc); | ||||
5528 | } | ||||
5529 | |||||
5530 | } // switch (Name.getKind()) | ||||
5531 | |||||
5532 | llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "clang/lib/Sema/SemaDecl.cpp" , 5532); | ||||
5533 | } | ||||
5534 | |||||
5535 | static QualType getCoreType(QualType Ty) { | ||||
5536 | do { | ||||
5537 | if (Ty->isPointerType() || Ty->isReferenceType()) | ||||
5538 | Ty = Ty->getPointeeType(); | ||||
5539 | else if (Ty->isArrayType()) | ||||
5540 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); | ||||
5541 | else | ||||
5542 | return Ty.withoutLocalFastQualifiers(); | ||||
5543 | } while (true); | ||||
5544 | } | ||||
5545 | |||||
5546 | /// hasSimilarParameters - Determine whether the C++ functions Declaration | ||||
5547 | /// and Definition have "nearly" matching parameters. This heuristic is | ||||
5548 | /// used to improve diagnostics in the case where an out-of-line function | ||||
5549 | /// definition doesn't match any declaration within the class or namespace. | ||||
5550 | /// Also sets Params to the list of indices to the parameters that differ | ||||
5551 | /// between the declaration and the definition. If hasSimilarParameters | ||||
5552 | /// returns true and Params is empty, then all of the parameters match. | ||||
5553 | static bool hasSimilarParameters(ASTContext &Context, | ||||
5554 | FunctionDecl *Declaration, | ||||
5555 | FunctionDecl *Definition, | ||||
5556 | SmallVectorImpl<unsigned> &Params) { | ||||
5557 | Params.clear(); | ||||
5558 | if (Declaration->param_size() != Definition->param_size()) | ||||
5559 | return false; | ||||
5560 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { | ||||
5561 | QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); | ||||
5562 | QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); | ||||
5563 | |||||
5564 | // The parameter types are identical | ||||
5565 | if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) | ||||
5566 | continue; | ||||
5567 | |||||
5568 | QualType DeclParamBaseTy = getCoreType(DeclParamTy); | ||||
5569 | QualType DefParamBaseTy = getCoreType(DefParamTy); | ||||
5570 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); | ||||
5571 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); | ||||
5572 | |||||
5573 | if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || | ||||
5574 | (DeclTyName && DeclTyName == DefTyName)) | ||||
5575 | Params.push_back(Idx); | ||||
5576 | else // The two parameters aren't even close | ||||
5577 | return false; | ||||
5578 | } | ||||
5579 | |||||
5580 | return true; | ||||
5581 | } | ||||
5582 | |||||
5583 | /// NeedsRebuildingInCurrentInstantiation - Checks whether the given | ||||
5584 | /// declarator needs to be rebuilt in the current instantiation. | ||||
5585 | /// Any bits of declarator which appear before the name are valid for | ||||
5586 | /// consideration here. That's specifically the type in the decl spec | ||||
5587 | /// and the base type in any member-pointer chunks. | ||||
5588 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, | ||||
5589 | DeclarationName Name) { | ||||
5590 | // The types we specifically need to rebuild are: | ||||
5591 | // - typenames, typeofs, and decltypes | ||||
5592 | // - types which will become injected class names | ||||
5593 | // Of course, we also need to rebuild any type referencing such a | ||||
5594 | // type. It's safest to just say "dependent", but we call out a | ||||
5595 | // few cases here. | ||||
5596 | |||||
5597 | DeclSpec &DS = D.getMutableDeclSpec(); | ||||
5598 | switch (DS.getTypeSpecType()) { | ||||
5599 | case DeclSpec::TST_typename: | ||||
5600 | case DeclSpec::TST_typeofType: | ||||
5601 | case DeclSpec::TST_underlyingType: | ||||
5602 | case DeclSpec::TST_atomic: { | ||||
5603 | // Grab the type from the parser. | ||||
5604 | TypeSourceInfo *TSI = nullptr; | ||||
5605 | QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); | ||||
5606 | if (T.isNull() || !T->isInstantiationDependentType()) break; | ||||
5607 | |||||
5608 | // Make sure there's a type source info. This isn't really much | ||||
5609 | // of a waste; most dependent types should have type source info | ||||
5610 | // attached already. | ||||
5611 | if (!TSI) | ||||
5612 | TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); | ||||
5613 | |||||
5614 | // Rebuild the type in the current instantiation. | ||||
5615 | TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); | ||||
5616 | if (!TSI) return true; | ||||
5617 | |||||
5618 | // Store the new type back in the decl spec. | ||||
5619 | ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); | ||||
5620 | DS.UpdateTypeRep(LocType); | ||||
5621 | break; | ||||
5622 | } | ||||
5623 | |||||
5624 | case DeclSpec::TST_decltype: | ||||
5625 | case DeclSpec::TST_typeofExpr: { | ||||
5626 | Expr *E = DS.getRepAsExpr(); | ||||
5627 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); | ||||
5628 | if (Result.isInvalid()) return true; | ||||
5629 | DS.UpdateExprRep(Result.get()); | ||||
5630 | break; | ||||
5631 | } | ||||
5632 | |||||
5633 | default: | ||||
5634 | // Nothing to do for these decl specs. | ||||
5635 | break; | ||||
5636 | } | ||||
5637 | |||||
5638 | // It doesn't matter what order we do this in. | ||||
5639 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | ||||
5640 | DeclaratorChunk &Chunk = D.getTypeObject(I); | ||||
5641 | |||||
5642 | // The only type information in the declarator which can come | ||||
5643 | // before the declaration name is the base type of a member | ||||
5644 | // pointer. | ||||
5645 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) | ||||
5646 | continue; | ||||
5647 | |||||
5648 | // Rebuild the scope specifier in-place. | ||||
5649 | CXXScopeSpec &SS = Chunk.Mem.Scope(); | ||||
5650 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) | ||||
5651 | return true; | ||||
5652 | } | ||||
5653 | |||||
5654 | return false; | ||||
5655 | } | ||||
5656 | |||||
5657 | void Sema::warnOnReservedIdentifier(const NamedDecl *D) { | ||||
5658 | // Avoid warning twice on the same identifier, and don't warn on redeclaration | ||||
5659 | // of system decl. | ||||
5660 | if (D->getPreviousDecl() || D->isImplicit()) | ||||
5661 | return; | ||||
5662 | ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); | ||||
5663 | if (Status != ReservedIdentifierStatus::NotReserved && | ||||
5664 | !Context.getSourceManager().isInSystemHeader(D->getLocation())) | ||||
5665 | Diag(D->getLocation(), diag::warn_reserved_extern_symbol) | ||||
5666 | << D << static_cast<int>(Status); | ||||
5667 | } | ||||
5668 | |||||
5669 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { | ||||
5670 | D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); | ||||
5671 | Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); | ||||
5672 | |||||
5673 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && | ||||
5674 | Dcl && Dcl->getDeclContext()->isFileContext()) | ||||
5675 | Dcl->setTopLevelDeclInObjCContainer(); | ||||
5676 | |||||
5677 | return Dcl; | ||||
5678 | } | ||||
5679 | |||||
5680 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: | ||||
5681 | /// If T is the name of a class, then each of the following shall have a | ||||
5682 | /// name different from T: | ||||
5683 | /// - every static data member of class T; | ||||
5684 | /// - every member function of class T | ||||
5685 | /// - every member of class T that is itself a type; | ||||
5686 | /// \returns true if the declaration name violates these rules. | ||||
5687 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, | ||||
5688 | DeclarationNameInfo NameInfo) { | ||||
5689 | DeclarationName Name = NameInfo.getName(); | ||||
5690 | |||||
5691 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); | ||||
5692 | while (Record && Record->isAnonymousStructOrUnion()) | ||||
5693 | Record = dyn_cast<CXXRecordDecl>(Record->getParent()); | ||||
5694 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { | ||||
5695 | Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; | ||||
5696 | return true; | ||||
5697 | } | ||||
5698 | |||||
5699 | return false; | ||||
5700 | } | ||||
5701 | |||||
5702 | /// Diagnose a declaration whose declarator-id has the given | ||||
5703 | /// nested-name-specifier. | ||||
5704 | /// | ||||
5705 | /// \param SS The nested-name-specifier of the declarator-id. | ||||
5706 | /// | ||||
5707 | /// \param DC The declaration context to which the nested-name-specifier | ||||
5708 | /// resolves. | ||||
5709 | /// | ||||
5710 | /// \param Name The name of the entity being declared. | ||||
5711 | /// | ||||
5712 | /// \param Loc The location of the name of the entity being declared. | ||||
5713 | /// | ||||
5714 | /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus | ||||
5715 | /// we're declaring an explicit / partial specialization / instantiation. | ||||
5716 | /// | ||||
5717 | /// \returns true if we cannot safely recover from this error, false otherwise. | ||||
5718 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, | ||||
5719 | DeclarationName Name, | ||||
5720 | SourceLocation Loc, bool IsTemplateId) { | ||||
5721 | DeclContext *Cur = CurContext; | ||||
5722 | while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) | ||||
5723 | Cur = Cur->getParent(); | ||||
5724 | |||||
5725 | // If the user provided a superfluous scope specifier that refers back to the | ||||
5726 | // class in which the entity is already declared, diagnose and ignore it. | ||||
5727 | // | ||||
5728 | // class X { | ||||
5729 | // void X::f(); | ||||
5730 | // }; | ||||
5731 | // | ||||
5732 | // Note, it was once ill-formed to give redundant qualification in all | ||||
5733 | // contexts, but that rule was removed by DR482. | ||||
5734 | if (Cur->Equals(DC)) { | ||||
5735 | if (Cur->isRecord()) { | ||||
5736 | Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification | ||||
5737 | : diag::err_member_extra_qualification) | ||||
5738 | << Name << FixItHint::CreateRemoval(SS.getRange()); | ||||
5739 | SS.clear(); | ||||
5740 | } else { | ||||
5741 | Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; | ||||
5742 | } | ||||
5743 | return false; | ||||
5744 | } | ||||
5745 | |||||
5746 | // Check whether the qualifying scope encloses the scope of the original | ||||
5747 | // declaration. For a template-id, we perform the checks in | ||||
5748 | // CheckTemplateSpecializationScope. | ||||
5749 | if (!Cur->Encloses(DC) && !IsTemplateId) { | ||||
5750 | if (Cur->isRecord()) | ||||
5751 | Diag(Loc, diag::err_member_qualification) | ||||
5752 | << Name << SS.getRange(); | ||||
5753 | else if (isa<TranslationUnitDecl>(DC)) | ||||
5754 | Diag(Loc, diag::err_invalid_declarator_global_scope) | ||||
5755 | << Name << SS.getRange(); | ||||
5756 | else if (isa<FunctionDecl>(Cur)) | ||||
5757 | Diag(Loc, diag::err_invalid_declarator_in_function) | ||||
5758 | << Name << SS.getRange(); | ||||
5759 | else if (isa<BlockDecl>(Cur)) | ||||
5760 | Diag(Loc, diag::err_invalid_declarator_in_block) | ||||
5761 | << Name << SS.getRange(); | ||||
5762 | else | ||||
5763 | Diag(Loc, diag::err_invalid_declarator_scope) | ||||
5764 | << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); | ||||
5765 | |||||
5766 | return true; | ||||
5767 | } | ||||
5768 | |||||
5769 | if (Cur->isRecord()) { | ||||
5770 | // Cannot qualify members within a class. | ||||
5771 | Diag(Loc, diag::err_member_qualification) | ||||
5772 | << Name << SS.getRange(); | ||||
5773 | SS.clear(); | ||||
5774 | |||||
5775 | // C++ constructors and destructors with incorrect scopes can break | ||||
5776 | // our AST invariants by having the wrong underlying types. If | ||||
5777 | // that's the case, then drop this declaration entirely. | ||||
5778 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || | ||||
5779 | Name.getNameKind() == DeclarationName::CXXDestructorName) && | ||||
5780 | !Context.hasSameType(Name.getCXXNameType(), | ||||
5781 | Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) | ||||
5782 | return true; | ||||
5783 | |||||
5784 | return false; | ||||
5785 | } | ||||
5786 | |||||
5787 | // C++11 [dcl.meaning]p1: | ||||
5788 | // [...] "The nested-name-specifier of the qualified declarator-id shall | ||||
5789 | // not begin with a decltype-specifer" | ||||
5790 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); | ||||
5791 | while (SpecLoc.getPrefix()) | ||||
5792 | SpecLoc = SpecLoc.getPrefix(); | ||||
5793 | if (isa_and_nonnull<DecltypeType>( | ||||
5794 | SpecLoc.getNestedNameSpecifier()->getAsType())) | ||||
5795 | Diag(Loc, diag::err_decltype_in_declarator) | ||||
5796 | << SpecLoc.getTypeLoc().getSourceRange(); | ||||
5797 | |||||
5798 | return false; | ||||
5799 | } | ||||
5800 | |||||
5801 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, | ||||
5802 | MultiTemplateParamsArg TemplateParamLists) { | ||||
5803 | // TODO: consider using NameInfo for diagnostic. | ||||
5804 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||
5805 | DeclarationName Name = NameInfo.getName(); | ||||
5806 | |||||
5807 | // All of these full declarators require an identifier. If it doesn't have | ||||
5808 | // one, the ParsedFreeStandingDeclSpec action should be used. | ||||
5809 | if (D.isDecompositionDeclarator()) { | ||||
5810 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); | ||||
5811 | } else if (!Name) { | ||||
5812 | if (!D.isInvalidType()) // Reject this if we think it is valid. | ||||
5813 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) | ||||
5814 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); | ||||
5815 | return nullptr; | ||||
5816 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) | ||||
5817 | return nullptr; | ||||
5818 | |||||
5819 | // The scope passed in may not be a decl scope. Zip up the scope tree until | ||||
5820 | // we find one that is. | ||||
5821 | while ((S->getFlags() & Scope::DeclScope) == 0 || | ||||
5822 | (S->getFlags() & Scope::TemplateParamScope) != 0) | ||||
5823 | S = S->getParent(); | ||||
5824 | |||||
5825 | DeclContext *DC = CurContext; | ||||
5826 | if (D.getCXXScopeSpec().isInvalid()) | ||||
5827 | D.setInvalidType(); | ||||
5828 | else if (D.getCXXScopeSpec().isSet()) { | ||||
5829 | if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), | ||||
5830 | UPPC_DeclarationQualifier)) | ||||
5831 | return nullptr; | ||||
5832 | |||||
5833 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); | ||||
5834 | DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); | ||||
5835 | if (!DC || isa<EnumDecl>(DC)) { | ||||
5836 | // If we could not compute the declaration context, it's because the | ||||
5837 | // declaration context is dependent but does not refer to a class, | ||||
5838 | // class template, or class template partial specialization. Complain | ||||
5839 | // and return early, to avoid the coming semantic disaster. | ||||
5840 | Diag(D.getIdentifierLoc(), | ||||
5841 | diag::err_template_qualified_declarator_no_match) | ||||
5842 | << D.getCXXScopeSpec().getScopeRep() | ||||
5843 | << D.getCXXScopeSpec().getRange(); | ||||
5844 | return nullptr; | ||||
5845 | } | ||||
5846 | bool IsDependentContext = DC->isDependentContext(); | ||||
5847 | |||||
5848 | if (!IsDependentContext && | ||||
5849 | RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) | ||||
5850 | return nullptr; | ||||
5851 | |||||
5852 | // If a class is incomplete, do not parse entities inside it. | ||||
5853 | if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { | ||||
5854 | Diag(D.getIdentifierLoc(), | ||||
5855 | diag::err_member_def_undefined_record) | ||||
5856 | << Name << DC << D.getCXXScopeSpec().getRange(); | ||||
5857 | return nullptr; | ||||
5858 | } | ||||
5859 | if (!D.getDeclSpec().isFriendSpecified()) { | ||||
5860 | if (diagnoseQualifiedDeclaration( | ||||
5861 | D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), | ||||
5862 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { | ||||
5863 | if (DC->isRecord()) | ||||
5864 | return nullptr; | ||||
5865 | |||||
5866 | D.setInvalidType(); | ||||
5867 | } | ||||
5868 | } | ||||
5869 | |||||
5870 | // Check whether we need to rebuild the type of the given | ||||
5871 | // declaration in the current instantiation. | ||||
5872 | if (EnteringContext && IsDependentContext && | ||||
5873 | TemplateParamLists.size() != 0) { | ||||
5874 | ContextRAII SavedContext(*this, DC); | ||||
5875 | if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) | ||||
5876 | D.setInvalidType(); | ||||
5877 | } | ||||
5878 | } | ||||
5879 | |||||
5880 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||
5881 | QualType R = TInfo->getType(); | ||||
5882 | |||||
5883 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||
5884 | UPPC_DeclarationType)) | ||||
5885 | D.setInvalidType(); | ||||
5886 | |||||
5887 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
5888 | forRedeclarationInCurContext()); | ||||
5889 | |||||
5890 | // See if this is a redefinition of a variable in the same scope. | ||||
5891 | if (!D.getCXXScopeSpec().isSet()) { | ||||
5892 | bool IsLinkageLookup = false; | ||||
5893 | bool CreateBuiltins = false; | ||||
5894 | |||||
5895 | // If the declaration we're planning to build will be a function | ||||
5896 | // or object with linkage, then look for another declaration with | ||||
5897 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). | ||||
5898 | // | ||||
5899 | // If the declaration we're planning to build will be declared with | ||||
5900 | // external linkage in the translation unit, create any builtin with | ||||
5901 | // the same name. | ||||
5902 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||
5903 | /* Do nothing*/; | ||||
5904 | else if (CurContext->isFunctionOrMethod() && | ||||
5905 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || | ||||
5906 | R->isFunctionType())) { | ||||
5907 | IsLinkageLookup = true; | ||||
5908 | CreateBuiltins = | ||||
5909 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); | ||||
5910 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && | ||||
5911 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) | ||||
5912 | CreateBuiltins = true; | ||||
5913 | |||||
5914 | if (IsLinkageLookup) { | ||||
5915 | Previous.clear(LookupRedeclarationWithLinkage); | ||||
5916 | Previous.setRedeclarationKind(ForExternalRedeclaration); | ||||
5917 | } | ||||
5918 | |||||
5919 | LookupName(Previous, S, CreateBuiltins); | ||||
5920 | } else { // Something like "int foo::x;" | ||||
5921 | LookupQualifiedName(Previous, DC); | ||||
5922 | |||||
5923 | // C++ [dcl.meaning]p1: | ||||
5924 | // When the declarator-id is qualified, the declaration shall refer to a | ||||
5925 | // previously declared member of the class or namespace to which the | ||||
5926 | // qualifier refers (or, in the case of a namespace, of an element of the | ||||
5927 | // inline namespace set of that namespace (7.3.1)) or to a specialization | ||||
5928 | // thereof; [...] | ||||
5929 | // | ||||
5930 | // Note that we already checked the context above, and that we do not have | ||||
5931 | // enough information to make sure that Previous contains the declaration | ||||
5932 | // we want to match. For example, given: | ||||
5933 | // | ||||
5934 | // class X { | ||||
5935 | // void f(); | ||||
5936 | // void f(float); | ||||
5937 | // }; | ||||
5938 | // | ||||
5939 | // void X::f(int) { } // ill-formed | ||||
5940 | // | ||||
5941 | // In this case, Previous will point to the overload set | ||||
5942 | // containing the two f's declared in X, but neither of them | ||||
5943 | // matches. | ||||
5944 | |||||
5945 | // C++ [dcl.meaning]p1: | ||||
5946 | // [...] the member shall not merely have been introduced by a | ||||
5947 | // using-declaration in the scope of the class or namespace nominated by | ||||
5948 | // the nested-name-specifier of the declarator-id. | ||||
5949 | RemoveUsingDecls(Previous); | ||||
5950 | } | ||||
5951 | |||||
5952 | if (Previous.isSingleResult() && | ||||
5953 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||
5954 | // Maybe we will complain about the shadowed template parameter. | ||||
5955 | if (!D.isInvalidType()) | ||||
5956 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | ||||
5957 | Previous.getFoundDecl()); | ||||
5958 | |||||
5959 | // Just pretend that we didn't see the previous declaration. | ||||
5960 | Previous.clear(); | ||||
5961 | } | ||||
5962 | |||||
5963 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) | ||||
5964 | // Forget that the previous declaration is the injected-class-name. | ||||
5965 | Previous.clear(); | ||||
5966 | |||||
5967 | // In C++, the previous declaration we find might be a tag type | ||||
5968 | // (class or enum). In this case, the new declaration will hide the | ||||
5969 | // tag type. Note that this applies to functions, function templates, and | ||||
5970 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. | ||||
5971 | if (Previous.isSingleTagDecl() && | ||||
5972 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | ||||
5973 | (TemplateParamLists.size() == 0 || R->isFunctionType())) | ||||
5974 | Previous.clear(); | ||||
5975 | |||||
5976 | // Check that there are no default arguments other than in the parameters | ||||
5977 | // of a function declaration (C++ only). | ||||
5978 | if (getLangOpts().CPlusPlus) | ||||
5979 | CheckExtraCXXDefaultArguments(D); | ||||
5980 | |||||
5981 | NamedDecl *New; | ||||
5982 | |||||
5983 | bool AddToScope = true; | ||||
5984 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { | ||||
5985 | if (TemplateParamLists.size()) { | ||||
5986 | Diag(D.getIdentifierLoc(), diag::err_template_typedef); | ||||
5987 | return nullptr; | ||||
5988 | } | ||||
5989 | |||||
5990 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); | ||||
5991 | } else if (R->isFunctionType()) { | ||||
5992 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, | ||||
5993 | TemplateParamLists, | ||||
5994 | AddToScope); | ||||
5995 | } else { | ||||
5996 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, | ||||
5997 | AddToScope); | ||||
5998 | } | ||||
5999 | |||||
6000 | if (!New) | ||||
6001 | return nullptr; | ||||
6002 | |||||
6003 | // If this has an identifier and is not a function template specialization, | ||||
6004 | // add it to the scope stack. | ||||
6005 | if (New->getDeclName() && AddToScope) | ||||
6006 | PushOnScopeChains(New, S); | ||||
6007 | |||||
6008 | if (isInOpenMPDeclareTargetContext()) | ||||
6009 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | ||||
6010 | |||||
6011 | return New; | ||||
6012 | } | ||||
6013 | |||||
6014 | /// Helper method to turn variable array types into constant array | ||||
6015 | /// types in certain situations which would otherwise be errors (for | ||||
6016 | /// GCC compatibility). | ||||
6017 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, | ||||
6018 | ASTContext &Context, | ||||
6019 | bool &SizeIsNegative, | ||||
6020 | llvm::APSInt &Oversized) { | ||||
6021 | // This method tries to turn a variable array into a constant | ||||
6022 | // array even when the size isn't an ICE. This is necessary | ||||
6023 | // for compatibility with code that depends on gcc's buggy | ||||
6024 | // constant expression folding, like struct {char x[(int)(char*)2];} | ||||
6025 | SizeIsNegative = false; | ||||
6026 | Oversized = 0; | ||||
6027 | |||||
6028 | if (T->isDependentType()) | ||||
6029 | return QualType(); | ||||
6030 | |||||
6031 | QualifierCollector Qs; | ||||
6032 | const Type *Ty = Qs.strip(T); | ||||
6033 | |||||
6034 | if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { | ||||
6035 | QualType Pointee = PTy->getPointeeType(); | ||||
6036 | QualType FixedType = | ||||
6037 | TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, | ||||
6038 | Oversized); | ||||
6039 | if (FixedType.isNull()) return FixedType; | ||||
6040 | FixedType = Context.getPointerType(FixedType); | ||||
6041 | return Qs.apply(Context, FixedType); | ||||
6042 | } | ||||
6043 | if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { | ||||
6044 | QualType Inner = PTy->getInnerType(); | ||||
6045 | QualType FixedType = | ||||
6046 | TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, | ||||
6047 | Oversized); | ||||
6048 | if (FixedType.isNull()) return FixedType; | ||||
6049 | FixedType = Context.getParenType(FixedType); | ||||
6050 | return Qs.apply(Context, FixedType); | ||||
6051 | } | ||||
6052 | |||||
6053 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); | ||||
6054 | if (!VLATy) | ||||
6055 | return QualType(); | ||||
6056 | |||||
6057 | QualType ElemTy = VLATy->getElementType(); | ||||
6058 | if (ElemTy->isVariablyModifiedType()) { | ||||
6059 | ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, | ||||
6060 | SizeIsNegative, Oversized); | ||||
6061 | if (ElemTy.isNull()) | ||||
6062 | return QualType(); | ||||
6063 | } | ||||
6064 | |||||
6065 | Expr::EvalResult Result; | ||||
6066 | if (!VLATy->getSizeExpr() || | ||||
6067 | !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) | ||||
6068 | return QualType(); | ||||
6069 | |||||
6070 | llvm::APSInt Res = Result.Val.getInt(); | ||||
6071 | |||||
6072 | // Check whether the array size is negative. | ||||
6073 | if (Res.isSigned() && Res.isNegative()) { | ||||
6074 | SizeIsNegative = true; | ||||
6075 | return QualType(); | ||||
6076 | } | ||||
6077 | |||||
6078 | // Check whether the array is too large to be addressed. | ||||
6079 | unsigned ActiveSizeBits = | ||||
6080 | (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && | ||||
6081 | !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) | ||||
6082 | ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) | ||||
6083 | : Res.getActiveBits(); | ||||
6084 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | ||||
6085 | Oversized = Res; | ||||
6086 | return QualType(); | ||||
6087 | } | ||||
6088 | |||||
6089 | QualType FoldedArrayType = Context.getConstantArrayType( | ||||
6090 | ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); | ||||
6091 | return Qs.apply(Context, FoldedArrayType); | ||||
6092 | } | ||||
6093 | |||||
6094 | static void | ||||
6095 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { | ||||
6096 | SrcTL = SrcTL.getUnqualifiedLoc(); | ||||
6097 | DstTL = DstTL.getUnqualifiedLoc(); | ||||
6098 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { | ||||
6099 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); | ||||
6100 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), | ||||
6101 | DstPTL.getPointeeLoc()); | ||||
6102 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); | ||||
6103 | return; | ||||
6104 | } | ||||
6105 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { | ||||
6106 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); | ||||
6107 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), | ||||
6108 | DstPTL.getInnerLoc()); | ||||
6109 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); | ||||
6110 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); | ||||
6111 | return; | ||||
6112 | } | ||||
6113 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); | ||||
6114 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); | ||||
6115 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); | ||||
6116 | TypeLoc DstElemTL = DstATL.getElementLoc(); | ||||
6117 | if (VariableArrayTypeLoc SrcElemATL = | ||||
6118 | SrcElemTL.getAs<VariableArrayTypeLoc>()) { | ||||
6119 | ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); | ||||
6120 | FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); | ||||
6121 | } else { | ||||
6122 | DstElemTL.initializeFullCopy(SrcElemTL); | ||||
6123 | } | ||||
6124 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); | ||||
6125 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); | ||||
6126 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); | ||||
6127 | } | ||||
6128 | |||||
6129 | /// Helper method to turn variable array types into constant array | ||||
6130 | /// types in certain situations which would otherwise be errors (for | ||||
6131 | /// GCC compatibility). | ||||
6132 | static TypeSourceInfo* | ||||
6133 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, | ||||
6134 | ASTContext &Context, | ||||
6135 | bool &SizeIsNegative, | ||||
6136 | llvm::APSInt &Oversized) { | ||||
6137 | QualType FixedTy | ||||
6138 | = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, | ||||
6139 | SizeIsNegative, Oversized); | ||||
6140 | if (FixedTy.isNull()) | ||||
6141 | return nullptr; | ||||
6142 | TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); | ||||
6143 | FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), | ||||
6144 | FixedTInfo->getTypeLoc()); | ||||
6145 | return FixedTInfo; | ||||
6146 | } | ||||
6147 | |||||
6148 | /// Attempt to fold a variable-sized type to a constant-sized type, returning | ||||
6149 | /// true if we were successful. | ||||
6150 | bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, | ||||
6151 | QualType &T, SourceLocation Loc, | ||||
6152 | unsigned FailedFoldDiagID) { | ||||
6153 | bool SizeIsNegative; | ||||
6154 | llvm::APSInt Oversized; | ||||
6155 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( | ||||
6156 | TInfo, Context, SizeIsNegative, Oversized); | ||||
6157 | if (FixedTInfo) { | ||||
6158 | Diag(Loc, diag::ext_vla_folded_to_constant); | ||||
6159 | TInfo = FixedTInfo; | ||||
6160 | T = FixedTInfo->getType(); | ||||
6161 | return true; | ||||
6162 | } | ||||
6163 | |||||
6164 | if (SizeIsNegative) | ||||
6165 | Diag(Loc, diag::err_typecheck_negative_array_size); | ||||
6166 | else if (Oversized.getBoolValue()) | ||||
6167 | Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); | ||||
6168 | else if (FailedFoldDiagID) | ||||
6169 | Diag(Loc, FailedFoldDiagID); | ||||
6170 | return false; | ||||
6171 | } | ||||
6172 | |||||
6173 | /// Register the given locally-scoped extern "C" declaration so | ||||
6174 | /// that it can be found later for redeclarations. We include any extern "C" | ||||
6175 | /// declaration that is not visible in the translation unit here, not just | ||||
6176 | /// function-scope declarations. | ||||
6177 | void | ||||
6178 | Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { | ||||
6179 | if (!getLangOpts().CPlusPlus && | ||||
6180 | ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) | ||||
6181 | // Don't need to track declarations in the TU in C. | ||||
6182 | return; | ||||
6183 | |||||
6184 | // Note that we have a locally-scoped external with this name. | ||||
6185 | Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); | ||||
6186 | } | ||||
6187 | |||||
6188 | NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { | ||||
6189 | // FIXME: We can have multiple results via __attribute__((overloadable)). | ||||
6190 | auto Result = Context.getExternCContextDecl()->lookup(Name); | ||||
6191 | return Result.empty() ? nullptr : *Result.begin(); | ||||
6192 | } | ||||
6193 | |||||
6194 | /// Diagnose function specifiers on a declaration of an identifier that | ||||
6195 | /// does not identify a function. | ||||
6196 | void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { | ||||
6197 | // FIXME: We should probably indicate the identifier in question to avoid | ||||
6198 | // confusion for constructs like "virtual int a(), b;" | ||||
6199 | if (DS.isVirtualSpecified()) | ||||
6200 | Diag(DS.getVirtualSpecLoc(), | ||||
6201 | diag::err_virtual_non_function); | ||||
6202 | |||||
6203 | if (DS.hasExplicitSpecifier()) | ||||
6204 | Diag(DS.getExplicitSpecLoc(), | ||||
6205 | diag::err_explicit_non_function); | ||||
6206 | |||||
6207 | if (DS.isNoreturnSpecified()) | ||||
6208 | Diag(DS.getNoreturnSpecLoc(), | ||||
6209 | diag::err_noreturn_non_function); | ||||
6210 | } | ||||
6211 | |||||
6212 | NamedDecl* | ||||
6213 | Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, | ||||
6214 | TypeSourceInfo *TInfo, LookupResult &Previous) { | ||||
6215 | // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). | ||||
6216 | if (D.getCXXScopeSpec().isSet()) { | ||||
6217 | Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) | ||||
6218 | << D.getCXXScopeSpec().getRange(); | ||||
6219 | D.setInvalidType(); | ||||
6220 | // Pretend we didn't see the scope specifier. | ||||
6221 | DC = CurContext; | ||||
6222 | Previous.clear(); | ||||
6223 | } | ||||
6224 | |||||
6225 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||
6226 | |||||
6227 | if (D.getDeclSpec().isInlineSpecified()) | ||||
6228 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||
6229 | << getLangOpts().CPlusPlus17; | ||||
6230 | if (D.getDeclSpec().hasConstexprSpecifier()) | ||||
6231 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) | ||||
6232 | << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); | ||||
6233 | |||||
6234 | if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { | ||||
6235 | if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) | ||||
6236 | Diag(D.getName().StartLocation, | ||||
6237 | diag::err_deduction_guide_invalid_specifier) | ||||
6238 | << "typedef"; | ||||
6239 | else | ||||
6240 | Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) | ||||
6241 | << D.getName().getSourceRange(); | ||||
6242 | return nullptr; | ||||
6243 | } | ||||
6244 | |||||
6245 | TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); | ||||
6246 | if (!NewTD) return nullptr; | ||||
6247 | |||||
6248 | // Handle attributes prior to checking for duplicates in MergeVarDecl | ||||
6249 | ProcessDeclAttributes(S, NewTD, D); | ||||
6250 | |||||
6251 | CheckTypedefForVariablyModifiedType(S, NewTD); | ||||
6252 | |||||
6253 | bool Redeclaration = D.isRedeclaration(); | ||||
6254 | NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); | ||||
6255 | D.setRedeclaration(Redeclaration); | ||||
6256 | return ND; | ||||
6257 | } | ||||
6258 | |||||
6259 | void | ||||
6260 | Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { | ||||
6261 | // C99 6.7.7p2: If a typedef name specifies a variably modified type | ||||
6262 | // then it shall have block scope. | ||||
6263 | // Note that variably modified types must be fixed before merging the decl so | ||||
6264 | // that redeclarations will match. | ||||
6265 | TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); | ||||
6266 | QualType T = TInfo->getType(); | ||||
6267 | if (T->isVariablyModifiedType()) { | ||||
6268 | setFunctionHasBranchProtectedScope(); | ||||
6269 | |||||
6270 | if (S->getFnParent() == nullptr) { | ||||
6271 | bool SizeIsNegative; | ||||
6272 | llvm::APSInt Oversized; | ||||
6273 | TypeSourceInfo *FixedTInfo = | ||||
6274 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | ||||
6275 | SizeIsNegative, | ||||
6276 | Oversized); | ||||
6277 | if (FixedTInfo) { | ||||
6278 | Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); | ||||
6279 | NewTD->setTypeSourceInfo(FixedTInfo); | ||||
6280 | } else { | ||||
6281 | if (SizeIsNegative) | ||||
6282 | Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); | ||||
6283 | else if (T->isVariableArrayType()) | ||||
6284 | Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); | ||||
6285 | else if (Oversized.getBoolValue()) | ||||
6286 | Diag(NewTD->getLocation(), diag::err_array_too_large) | ||||
6287 | << toString(Oversized, 10); | ||||
6288 | else | ||||
6289 | Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); | ||||
6290 | NewTD->setInvalidDecl(); | ||||
6291 | } | ||||
6292 | } | ||||
6293 | } | ||||
6294 | } | ||||
6295 | |||||
6296 | /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which | ||||
6297 | /// declares a typedef-name, either using the 'typedef' type specifier or via | ||||
6298 | /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. | ||||
6299 | NamedDecl* | ||||
6300 | Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, | ||||
6301 | LookupResult &Previous, bool &Redeclaration) { | ||||
6302 | |||||
6303 | // Find the shadowed declaration before filtering for scope. | ||||
6304 | NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); | ||||
6305 | |||||
6306 | // Merge the decl with the existing one if appropriate. If the decl is | ||||
6307 | // in an outer scope, it isn't the same thing. | ||||
6308 | FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, | ||||
6309 | /*AllowInlineNamespace*/false); | ||||
6310 | filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); | ||||
6311 | if (!Previous.empty()) { | ||||
6312 | Redeclaration = true; | ||||
6313 | MergeTypedefNameDecl(S, NewTD, Previous); | ||||
6314 | } else { | ||||
6315 | inferGslPointerAttribute(NewTD); | ||||
6316 | } | ||||
6317 | |||||
6318 | if (ShadowedDecl && !Redeclaration) | ||||
6319 | CheckShadow(NewTD, ShadowedDecl, Previous); | ||||
6320 | |||||
6321 | // If this is the C FILE type, notify the AST context. | ||||
6322 | if (IdentifierInfo *II = NewTD->getIdentifier()) | ||||
6323 | if (!NewTD->isInvalidDecl() && | ||||
6324 | NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||
6325 | if (II->isStr("FILE")) | ||||
6326 | Context.setFILEDecl(NewTD); | ||||
6327 | else if (II->isStr("jmp_buf")) | ||||
6328 | Context.setjmp_bufDecl(NewTD); | ||||
6329 | else if (II->isStr("sigjmp_buf")) | ||||
6330 | Context.setsigjmp_bufDecl(NewTD); | ||||
6331 | else if (II->isStr("ucontext_t")) | ||||
6332 | Context.setucontext_tDecl(NewTD); | ||||
6333 | } | ||||
6334 | |||||
6335 | return NewTD; | ||||
6336 | } | ||||
6337 | |||||
6338 | /// Determines whether the given declaration is an out-of-scope | ||||
6339 | /// previous declaration. | ||||
6340 | /// | ||||
6341 | /// This routine should be invoked when name lookup has found a | ||||
6342 | /// previous declaration (PrevDecl) that is not in the scope where a | ||||
6343 | /// new declaration by the same name is being introduced. If the new | ||||
6344 | /// declaration occurs in a local scope, previous declarations with | ||||
6345 | /// linkage may still be considered previous declarations (C99 | ||||
6346 | /// 6.2.2p4-5, C++ [basic.link]p6). | ||||
6347 | /// | ||||
6348 | /// \param PrevDecl the previous declaration found by name | ||||
6349 | /// lookup | ||||
6350 | /// | ||||
6351 | /// \param DC the context in which the new declaration is being | ||||
6352 | /// declared. | ||||
6353 | /// | ||||
6354 | /// \returns true if PrevDecl is an out-of-scope previous declaration | ||||
6355 | /// for a new delcaration with the same name. | ||||
6356 | static bool | ||||
6357 | isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, | ||||
6358 | ASTContext &Context) { | ||||
6359 | if (!PrevDecl) | ||||
6360 | return false; | ||||
6361 | |||||
6362 | if (!PrevDecl->hasLinkage()) | ||||
6363 | return false; | ||||
6364 | |||||
6365 | if (Context.getLangOpts().CPlusPlus) { | ||||
6366 | // C++ [basic.link]p6: | ||||
6367 | // If there is a visible declaration of an entity with linkage | ||||
6368 | // having the same name and type, ignoring entities declared | ||||
6369 | // outside the innermost enclosing namespace scope, the block | ||||
6370 | // scope declaration declares that same entity and receives the | ||||
6371 | // linkage of the previous declaration. | ||||
6372 | DeclContext *OuterContext = DC->getRedeclContext(); | ||||
6373 | if (!OuterContext->isFunctionOrMethod()) | ||||
6374 | // This rule only applies to block-scope declarations. | ||||
6375 | return false; | ||||
6376 | |||||
6377 | DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); | ||||
6378 | if (PrevOuterContext->isRecord()) | ||||
6379 | // We found a member function: ignore it. | ||||
6380 | return false; | ||||
6381 | |||||
6382 | // Find the innermost enclosing namespace for the new and | ||||
6383 | // previous declarations. | ||||
6384 | OuterContext = OuterContext->getEnclosingNamespaceContext(); | ||||
6385 | PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); | ||||
6386 | |||||
6387 | // The previous declaration is in a different namespace, so it | ||||
6388 | // isn't the same function. | ||||
6389 | if (!OuterContext->Equals(PrevOuterContext)) | ||||
6390 | return false; | ||||
6391 | } | ||||
6392 | |||||
6393 | return true; | ||||
6394 | } | ||||
6395 | |||||
6396 | static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { | ||||
6397 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | ||||
6398 | if (!SS.isSet()) return; | ||||
6399 | DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); | ||||
6400 | } | ||||
6401 | |||||
6402 | bool Sema::inferObjCARCLifetime(ValueDecl *decl) { | ||||
6403 | QualType type = decl->getType(); | ||||
6404 | Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); | ||||
6405 | if (lifetime == Qualifiers::OCL_Autoreleasing) { | ||||
6406 | // Various kinds of declaration aren't allowed to be __autoreleasing. | ||||
6407 | unsigned kind = -1U; | ||||
6408 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | ||||
6409 | if (var->hasAttr<BlocksAttr>()) | ||||
6410 | kind = 0; // __block | ||||
6411 | else if (!var->hasLocalStorage()) | ||||
6412 | kind = 1; // global | ||||
6413 | } else if (isa<ObjCIvarDecl>(decl)) { | ||||
6414 | kind = 3; // ivar | ||||
6415 | } else if (isa<FieldDecl>(decl)) { | ||||
6416 | kind = 2; // field | ||||
6417 | } | ||||
6418 | |||||
6419 | if (kind != -1U) { | ||||
6420 | Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) | ||||
6421 | << kind; | ||||
6422 | } | ||||
6423 | } else if (lifetime == Qualifiers::OCL_None) { | ||||
6424 | // Try to infer lifetime. | ||||
6425 | if (!type->isObjCLifetimeType()) | ||||
6426 | return false; | ||||
6427 | |||||
6428 | lifetime = type->getObjCARCImplicitLifetime(); | ||||
6429 | type = Context.getLifetimeQualifiedType(type, lifetime); | ||||
6430 | decl->setType(type); | ||||
6431 | } | ||||
6432 | |||||
6433 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | ||||
6434 | // Thread-local variables cannot have lifetime. | ||||
6435 | if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && | ||||
6436 | var->getTLSKind()) { | ||||
6437 | Diag(var->getLocation(), diag::err_arc_thread_ownership) | ||||
6438 | << var->getType(); | ||||
6439 | return true; | ||||
6440 | } | ||||
6441 | } | ||||
6442 | |||||
6443 | return false; | ||||
6444 | } | ||||
6445 | |||||
6446 | void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { | ||||
6447 | if (Decl->getType().hasAddressSpace()) | ||||
6448 | return; | ||||
6449 | if (Decl->getType()->isDependentType()) | ||||
6450 | return; | ||||
6451 | if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { | ||||
6452 | QualType Type = Var->getType(); | ||||
6453 | if (Type->isSamplerT() || Type->isVoidType()) | ||||
6454 | return; | ||||
6455 | LangAS ImplAS = LangAS::opencl_private; | ||||
6456 | // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the | ||||
6457 | // __opencl_c_program_scope_global_variables feature, the address space | ||||
6458 | // for a variable at program scope or a static or extern variable inside | ||||
6459 | // a function are inferred to be __global. | ||||
6460 | if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && | ||||
6461 | Var->hasGlobalStorage()) | ||||
6462 | ImplAS = LangAS::opencl_global; | ||||
6463 | // If the original type from a decayed type is an array type and that array | ||||
6464 | // type has no address space yet, deduce it now. | ||||
6465 | if (auto DT = dyn_cast<DecayedType>(Type)) { | ||||
6466 | auto OrigTy = DT->getOriginalType(); | ||||
6467 | if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { | ||||
6468 | // Add the address space to the original array type and then propagate | ||||
6469 | // that to the element type through `getAsArrayType`. | ||||
6470 | OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); | ||||
6471 | OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); | ||||
6472 | // Re-generate the decayed type. | ||||
6473 | Type = Context.getDecayedType(OrigTy); | ||||
6474 | } | ||||
6475 | } | ||||
6476 | Type = Context.getAddrSpaceQualType(Type, ImplAS); | ||||
6477 | // Apply any qualifiers (including address space) from the array type to | ||||
6478 | // the element type. This implements C99 6.7.3p8: "If the specification of | ||||
6479 | // an array type includes any type qualifiers, the element type is so | ||||
6480 | // qualified, not the array type." | ||||
6481 | if (Type->isArrayType()) | ||||
6482 | Type = QualType(Context.getAsArrayType(Type), 0); | ||||
6483 | Decl->setType(Type); | ||||
6484 | } | ||||
6485 | } | ||||
6486 | |||||
6487 | static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { | ||||
6488 | // Ensure that an auto decl is deduced otherwise the checks below might cache | ||||
6489 | // the wrong linkage. | ||||
6490 | assert(S.ParsingInitForAutoVars.count(&ND) == 0)(static_cast <bool> (S.ParsingInitForAutoVars.count(& ND) == 0) ? void (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0" , "clang/lib/Sema/SemaDecl.cpp", 6490, __extension__ __PRETTY_FUNCTION__ )); | ||||
6491 | |||||
6492 | // 'weak' only applies to declarations with external linkage. | ||||
6493 | if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { | ||||
6494 | if (!ND.isExternallyVisible()) { | ||||
6495 | S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); | ||||
6496 | ND.dropAttr<WeakAttr>(); | ||||
6497 | } | ||||
6498 | } | ||||
6499 | if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { | ||||
6500 | if (ND.isExternallyVisible()) { | ||||
6501 | S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); | ||||
6502 | ND.dropAttr<WeakRefAttr>(); | ||||
6503 | ND.dropAttr<AliasAttr>(); | ||||
6504 | } | ||||
6505 | } | ||||
6506 | |||||
6507 | if (auto *VD = dyn_cast<VarDecl>(&ND)) { | ||||
6508 | if (VD->hasInit()) { | ||||
6509 | if (const auto *Attr = VD->getAttr<AliasAttr>()) { | ||||
6510 | assert(VD->isThisDeclarationADefinition() &&(static_cast <bool> (VD->isThisDeclarationADefinition () && !VD->isExternallyVisible() && "Broken AliasAttr handled late!" ) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "clang/lib/Sema/SemaDecl.cpp", 6511, __extension__ __PRETTY_FUNCTION__ )) | ||||
6511 | !VD->isExternallyVisible() && "Broken AliasAttr handled late!")(static_cast <bool> (VD->isThisDeclarationADefinition () && !VD->isExternallyVisible() && "Broken AliasAttr handled late!" ) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "clang/lib/Sema/SemaDecl.cpp", 6511, __extension__ __PRETTY_FUNCTION__ )); | ||||
6512 | S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; | ||||
6513 | VD->dropAttr<AliasAttr>(); | ||||
6514 | } | ||||
6515 | } | ||||
6516 | } | ||||
6517 | |||||
6518 | // 'selectany' only applies to externally visible variable declarations. | ||||
6519 | // It does not apply to functions. | ||||
6520 | if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { | ||||
6521 | if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { | ||||
6522 | S.Diag(Attr->getLocation(), | ||||
6523 | diag::err_attribute_selectany_non_extern_data); | ||||
6524 | ND.dropAttr<SelectAnyAttr>(); | ||||
6525 | } | ||||
6526 | } | ||||
6527 | |||||
6528 | if (const InheritableAttr *Attr = getDLLAttr(&ND)) { | ||||
6529 | auto *VD = dyn_cast<VarDecl>(&ND); | ||||
6530 | bool IsAnonymousNS = false; | ||||
6531 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | ||||
6532 | if (VD) { | ||||
6533 | const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); | ||||
6534 | while (NS && !IsAnonymousNS) { | ||||
6535 | IsAnonymousNS = NS->isAnonymousNamespace(); | ||||
6536 | NS = dyn_cast<NamespaceDecl>(NS->getParent()); | ||||
6537 | } | ||||
6538 | } | ||||
6539 | // dll attributes require external linkage. Static locals may have external | ||||
6540 | // linkage but still cannot be explicitly imported or exported. | ||||
6541 | // In Microsoft mode, a variable defined in anonymous namespace must have | ||||
6542 | // external linkage in order to be exported. | ||||
6543 | bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; | ||||
6544 | if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || | ||||
6545 | (!AnonNSInMicrosoftMode && | ||||
6546 | (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { | ||||
6547 | S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) | ||||
6548 | << &ND << Attr; | ||||
6549 | ND.setInvalidDecl(); | ||||
6550 | } | ||||
6551 | } | ||||
6552 | |||||
6553 | // Check the attributes on the function type, if any. | ||||
6554 | if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { | ||||
6555 | // Don't declare this variable in the second operand of the for-statement; | ||||
6556 | // GCC miscompiles that by ending its lifetime before evaluating the | ||||
6557 | // third operand. See gcc.gnu.org/PR86769. | ||||
6558 | AttributedTypeLoc ATL; | ||||
6559 | for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); | ||||
6560 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | ||||
6561 | TL = ATL.getModifiedLoc()) { | ||||
6562 | // The [[lifetimebound]] attribute can be applied to the implicit object | ||||
6563 | // parameter of a non-static member function (other than a ctor or dtor) | ||||
6564 | // by applying it to the function type. | ||||
6565 | if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { | ||||
6566 | const auto *MD = dyn_cast<CXXMethodDecl>(FD); | ||||
6567 | if (!MD || MD->isStatic()) { | ||||
6568 | S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) | ||||
6569 | << !MD << A->getRange(); | ||||
6570 | } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { | ||||
6571 | S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) | ||||
6572 | << isa<CXXDestructorDecl>(MD) << A->getRange(); | ||||
6573 | } | ||||
6574 | } | ||||
6575 | } | ||||
6576 | } | ||||
6577 | } | ||||
6578 | |||||
6579 | static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, | ||||
6580 | NamedDecl *NewDecl, | ||||
6581 | bool IsSpecialization, | ||||
6582 | bool IsDefinition) { | ||||
6583 | if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) | ||||
6584 | return; | ||||
6585 | |||||
6586 | bool IsTemplate = false; | ||||
6587 | if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { | ||||
6588 | OldDecl = OldTD->getTemplatedDecl(); | ||||
6589 | IsTemplate = true; | ||||
6590 | if (!IsSpecialization) | ||||
6591 | IsDefinition = false; | ||||
6592 | } | ||||
6593 | if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { | ||||
6594 | NewDecl = NewTD->getTemplatedDecl(); | ||||
6595 | IsTemplate = true; | ||||
6596 | } | ||||
6597 | |||||
6598 | if (!OldDecl || !NewDecl) | ||||
6599 | return; | ||||
6600 | |||||
6601 | const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); | ||||
6602 | const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); | ||||
6603 | const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); | ||||
6604 | const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); | ||||
6605 | |||||
6606 | // dllimport and dllexport are inheritable attributes so we have to exclude | ||||
6607 | // inherited attribute instances. | ||||
6608 | bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || | ||||
6609 | (NewExportAttr && !NewExportAttr->isInherited()); | ||||
6610 | |||||
6611 | // A redeclaration is not allowed to add a dllimport or dllexport attribute, | ||||
6612 | // the only exception being explicit specializations. | ||||
6613 | // Implicitly generated declarations are also excluded for now because there | ||||
6614 | // is no other way to switch these to use dllimport or dllexport. | ||||
6615 | bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; | ||||
6616 | |||||
6617 | if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { | ||||
6618 | // Allow with a warning for free functions and global variables. | ||||
6619 | bool JustWarn = false; | ||||
6620 | if (!OldDecl->isCXXClassMember()) { | ||||
6621 | auto *VD = dyn_cast<VarDecl>(OldDecl); | ||||
6622 | if (VD && !VD->getDescribedVarTemplate()) | ||||
6623 | JustWarn = true; | ||||
6624 | auto *FD = dyn_cast<FunctionDecl>(OldDecl); | ||||
6625 | if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) | ||||
6626 | JustWarn = true; | ||||
6627 | } | ||||
6628 | |||||
6629 | // We cannot change a declaration that's been used because IR has already | ||||
6630 | // been emitted. Dllimported functions will still work though (modulo | ||||
6631 | // address equality) as they can use the thunk. | ||||
6632 | if (OldDecl->isUsed()) | ||||
6633 | if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) | ||||
6634 | JustWarn = false; | ||||
6635 | |||||
6636 | unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration | ||||
6637 | : diag::err_attribute_dll_redeclaration; | ||||
6638 | S.Diag(NewDecl->getLocation(), DiagID) | ||||
6639 | << NewDecl | ||||
6640 | << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); | ||||
6641 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||
6642 | if (!JustWarn) { | ||||
6643 | NewDecl->setInvalidDecl(); | ||||
6644 | return; | ||||
6645 | } | ||||
6646 | } | ||||
6647 | |||||
6648 | // A redeclaration is not allowed to drop a dllimport attribute, the only | ||||
6649 | // exceptions being inline function definitions (except for function | ||||
6650 | // templates), local extern declarations, qualified friend declarations or | ||||
6651 | // special MSVC extension: in the last case, the declaration is treated as if | ||||
6652 | // it were marked dllexport. | ||||
6653 | bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; | ||||
6654 | bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); | ||||
6655 | if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { | ||||
6656 | // Ignore static data because out-of-line definitions are diagnosed | ||||
6657 | // separately. | ||||
6658 | IsStaticDataMember = VD->isStaticDataMember(); | ||||
6659 | IsDefinition = VD->isThisDeclarationADefinition(S.Context) != | ||||
6660 | VarDecl::DeclarationOnly; | ||||
6661 | } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { | ||||
6662 | IsInline = FD->isInlined(); | ||||
6663 | IsQualifiedFriend = FD->getQualifier() && | ||||
6664 | FD->getFriendObjectKind() == Decl::FOK_Declared; | ||||
6665 | } | ||||
6666 | |||||
6667 | if (OldImportAttr && !HasNewAttr && | ||||
6668 | (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && | ||||
6669 | !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { | ||||
6670 | if (IsMicrosoftABI && IsDefinition) { | ||||
6671 | S.Diag(NewDecl->getLocation(), | ||||
6672 | diag::warn_redeclaration_without_import_attribute) | ||||
6673 | << NewDecl; | ||||
6674 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||
6675 | NewDecl->dropAttr<DLLImportAttr>(); | ||||
6676 | NewDecl->addAttr( | ||||
6677 | DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); | ||||
6678 | } else { | ||||
6679 | S.Diag(NewDecl->getLocation(), | ||||
6680 | diag::warn_redeclaration_without_attribute_prev_attribute_ignored) | ||||
6681 | << NewDecl << OldImportAttr; | ||||
6682 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||
6683 | S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); | ||||
6684 | OldDecl->dropAttr<DLLImportAttr>(); | ||||
6685 | NewDecl->dropAttr<DLLImportAttr>(); | ||||
6686 | } | ||||
6687 | } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { | ||||
6688 | // In MinGW, seeing a function declared inline drops the dllimport | ||||
6689 | // attribute. | ||||
6690 | OldDecl->dropAttr<DLLImportAttr>(); | ||||
6691 | NewDecl->dropAttr<DLLImportAttr>(); | ||||
6692 | S.Diag(NewDecl->getLocation(), | ||||
6693 | diag::warn_dllimport_dropped_from_inline_function) | ||||
6694 | << NewDecl << OldImportAttr; | ||||
6695 | } | ||||
6696 | |||||
6697 | // A specialization of a class template member function is processed here | ||||
6698 | // since it's a redeclaration. If the parent class is dllexport, the | ||||
6699 | // specialization inherits that attribute. This doesn't happen automatically | ||||
6700 | // since the parent class isn't instantiated until later. | ||||
6701 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { | ||||
6702 | if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && | ||||
6703 | !NewImportAttr && !NewExportAttr) { | ||||
6704 | if (const DLLExportAttr *ParentExportAttr = | ||||
6705 | MD->getParent()->getAttr<DLLExportAttr>()) { | ||||
6706 | DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); | ||||
6707 | NewAttr->setInherited(true); | ||||
6708 | NewDecl->addAttr(NewAttr); | ||||
6709 | } | ||||
6710 | } | ||||
6711 | } | ||||
6712 | } | ||||
6713 | |||||
6714 | /// Given that we are within the definition of the given function, | ||||
6715 | /// will that definition behave like C99's 'inline', where the | ||||
6716 | /// definition is discarded except for optimization purposes? | ||||
6717 | static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { | ||||
6718 | // Try to avoid calling GetGVALinkageForFunction. | ||||
6719 | |||||
6720 | // All cases of this require the 'inline' keyword. | ||||
6721 | if (!FD->isInlined()) return false; | ||||
6722 | |||||
6723 | // This is only possible in C++ with the gnu_inline attribute. | ||||
6724 | if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) | ||||
6725 | return false; | ||||
6726 | |||||
6727 | // Okay, go ahead and call the relatively-more-expensive function. | ||||
6728 | return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; | ||||
6729 | } | ||||
6730 | |||||
6731 | /// Determine whether a variable is extern "C" prior to attaching | ||||
6732 | /// an initializer. We can't just call isExternC() here, because that | ||||
6733 | /// will also compute and cache whether the declaration is externally | ||||
6734 | /// visible, which might change when we attach the initializer. | ||||
6735 | /// | ||||
6736 | /// This can only be used if the declaration is known to not be a | ||||
6737 | /// redeclaration of an internal linkage declaration. | ||||
6738 | /// | ||||
6739 | /// For instance: | ||||
6740 | /// | ||||
6741 | /// auto x = []{}; | ||||
6742 | /// | ||||
6743 | /// Attaching the initializer here makes this declaration not externally | ||||
6744 | /// visible, because its type has internal linkage. | ||||
6745 | /// | ||||
6746 | /// FIXME: This is a hack. | ||||
6747 | template<typename T> | ||||
6748 | static bool isIncompleteDeclExternC(Sema &S, const T *D) { | ||||
6749 | if (S.getLangOpts().CPlusPlus) { | ||||
6750 | // In C++, the overloadable attribute negates the effects of extern "C". | ||||
6751 | if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) | ||||
6752 | return false; | ||||
6753 | |||||
6754 | // So do CUDA's host/device attributes. | ||||
6755 | if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || | ||||
6756 | D->template hasAttr<CUDAHostAttr>())) | ||||
6757 | return false; | ||||
6758 | } | ||||
6759 | return D->isExternC(); | ||||
6760 | } | ||||
6761 | |||||
6762 | static bool shouldConsiderLinkage(const VarDecl *VD) { | ||||
6763 | const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); | ||||
6764 | if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || | ||||
6765 | isa<OMPDeclareMapperDecl>(DC)) | ||||
6766 | return VD->hasExternalStorage(); | ||||
6767 | if (DC->isFileContext()) | ||||
6768 | return true; | ||||
6769 | if (DC->isRecord()) | ||||
6770 | return false; | ||||
6771 | if (isa<RequiresExprBodyDecl>(DC)) | ||||
6772 | return false; | ||||
6773 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "clang/lib/Sema/SemaDecl.cpp" , 6773); | ||||
6774 | } | ||||
6775 | |||||
6776 | static bool shouldConsiderLinkage(const FunctionDecl *FD) { | ||||
6777 | const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); | ||||
6778 | if (DC->isFileContext() || DC->isFunctionOrMethod() || | ||||
6779 | isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) | ||||
6780 | return true; | ||||
6781 | if (DC->isRecord()) | ||||
6782 | return false; | ||||
6783 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "clang/lib/Sema/SemaDecl.cpp" , 6783); | ||||
6784 | } | ||||
6785 | |||||
6786 | static bool hasParsedAttr(Scope *S, const Declarator &PD, | ||||
6787 | ParsedAttr::Kind Kind) { | ||||
6788 | // Check decl attributes on the DeclSpec. | ||||
6789 | if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) | ||||
6790 | return true; | ||||
6791 | |||||
6792 | // Walk the declarator structure, checking decl attributes that were in a type | ||||
6793 | // position to the decl itself. | ||||
6794 | for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { | ||||
6795 | if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) | ||||
6796 | return true; | ||||
6797 | } | ||||
6798 | |||||
6799 | // Finally, check attributes on the decl itself. | ||||
6800 | return PD.getAttributes().hasAttribute(Kind); | ||||
6801 | } | ||||
6802 | |||||
6803 | /// Adjust the \c DeclContext for a function or variable that might be a | ||||
6804 | /// function-local external declaration. | ||||
6805 | bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { | ||||
6806 | if (!DC->isFunctionOrMethod()) | ||||
6807 | return false; | ||||
6808 | |||||
6809 | // If this is a local extern function or variable declared within a function | ||||
6810 | // template, don't add it into the enclosing namespace scope until it is | ||||
6811 | // instantiated; it might have a dependent type right now. | ||||
6812 | if (DC->isDependentContext()) | ||||
6813 | return true; | ||||
6814 | |||||
6815 | // C++11 [basic.link]p7: | ||||
6816 | // When a block scope declaration of an entity with linkage is not found to | ||||
6817 | // refer to some other declaration, then that entity is a member of the | ||||
6818 | // innermost enclosing namespace. | ||||
6819 | // | ||||
6820 | // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a | ||||
6821 | // semantically-enclosing namespace, not a lexically-enclosing one. | ||||
6822 | while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) | ||||
6823 | DC = DC->getParent(); | ||||
6824 | return true; | ||||
6825 | } | ||||
6826 | |||||
6827 | /// Returns true if given declaration has external C language linkage. | ||||
6828 | static bool isDeclExternC(const Decl *D) { | ||||
6829 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) | ||||
6830 | return FD->isExternC(); | ||||
6831 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||
6832 | return VD->isExternC(); | ||||
6833 | |||||
6834 | llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "clang/lib/Sema/SemaDecl.cpp" , 6834); | ||||
6835 | } | ||||
6836 | |||||
6837 | /// Returns true if there hasn't been any invalid type diagnosed. | ||||
6838 | static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { | ||||
6839 | DeclContext *DC = NewVD->getDeclContext(); | ||||
6840 | QualType R = NewVD->getType(); | ||||
6841 | |||||
6842 | // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. | ||||
6843 | // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function | ||||
6844 | // argument. | ||||
6845 | if (R->isImageType() || R->isPipeType()) { | ||||
6846 | Se.Diag(NewVD->getLocation(), | ||||
6847 | diag::err_opencl_type_can_only_be_used_as_function_parameter) | ||||
6848 | << R; | ||||
6849 | NewVD->setInvalidDecl(); | ||||
6850 | return false; | ||||
6851 | } | ||||
6852 | |||||
6853 | // OpenCL v1.2 s6.9.r: | ||||
6854 | // The event type cannot be used to declare a program scope variable. | ||||
6855 | // OpenCL v2.0 s6.9.q: | ||||
6856 | // The clk_event_t and reserve_id_t types cannot be declared in program | ||||
6857 | // scope. | ||||
6858 | if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { | ||||
6859 | if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { | ||||
6860 | Se.Diag(NewVD->getLocation(), | ||||
6861 | diag::err_invalid_type_for_program_scope_var) | ||||
6862 | << R; | ||||
6863 | NewVD->setInvalidDecl(); | ||||
6864 | return false; | ||||
6865 | } | ||||
6866 | } | ||||
6867 | |||||
6868 | // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. | ||||
6869 | if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", | ||||
6870 | Se.getLangOpts())) { | ||||
6871 | QualType NR = R.getCanonicalType(); | ||||
6872 | while (NR->isPointerType() || NR->isMemberFunctionPointerType() || | ||||
6873 | NR->isReferenceType()) { | ||||
6874 | if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || | ||||
6875 | NR->isFunctionReferenceType()) { | ||||
6876 | Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) | ||||
6877 | << NR->isReferenceType(); | ||||
6878 | NewVD->setInvalidDecl(); | ||||
6879 | return false; | ||||
6880 | } | ||||
6881 | NR = NR->getPointeeType(); | ||||
6882 | } | ||||
6883 | } | ||||
6884 | |||||
6885 | if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", | ||||
6886 | Se.getLangOpts())) { | ||||
6887 | // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and | ||||
6888 | // half array type (unless the cl_khr_fp16 extension is enabled). | ||||
6889 | if (Se.Context.getBaseElementType(R)->isHalfType()) { | ||||
6890 | Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; | ||||
6891 | NewVD->setInvalidDecl(); | ||||
6892 | return false; | ||||
6893 | } | ||||
6894 | } | ||||
6895 | |||||
6896 | // OpenCL v1.2 s6.9.r: | ||||
6897 | // The event type cannot be used with the __local, __constant and __global | ||||
6898 | // address space qualifiers. | ||||
6899 | if (R->isEventT()) { | ||||
6900 | if (R.getAddressSpace() != LangAS::opencl_private) { | ||||
6901 | Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); | ||||
6902 | NewVD->setInvalidDecl(); | ||||
6903 | return false; | ||||
6904 | } | ||||
6905 | } | ||||
6906 | |||||
6907 | if (R->isSamplerT()) { | ||||
6908 | // OpenCL v1.2 s6.9.b p4: | ||||
6909 | // The sampler type cannot be used with the __local and __global address | ||||
6910 | // space qualifiers. | ||||
6911 | if (R.getAddressSpace() == LangAS::opencl_local || | ||||
6912 | R.getAddressSpace() == LangAS::opencl_global) { | ||||
6913 | Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); | ||||
6914 | NewVD->setInvalidDecl(); | ||||
6915 | } | ||||
6916 | |||||
6917 | // OpenCL v1.2 s6.12.14.1: | ||||
6918 | // A global sampler must be declared with either the constant address | ||||
6919 | // space qualifier or with the const qualifier. | ||||
6920 | if (DC->isTranslationUnit() && | ||||
6921 | !(R.getAddressSpace() == LangAS::opencl_constant || | ||||
6922 | R.isConstQualified())) { | ||||
6923 | Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); | ||||
6924 | NewVD->setInvalidDecl(); | ||||
6925 | } | ||||
6926 | if (NewVD->isInvalidDecl()) | ||||
6927 | return false; | ||||
6928 | } | ||||
6929 | |||||
6930 | return true; | ||||
6931 | } | ||||
6932 | |||||
6933 | template <typename AttrTy> | ||||
6934 | static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { | ||||
6935 | const TypedefNameDecl *TND = TT->getDecl(); | ||||
6936 | if (const auto *Attribute = TND->getAttr<AttrTy>()) { | ||||
6937 | AttrTy *Clone = Attribute->clone(S.Context); | ||||
6938 | Clone->setInherited(true); | ||||
6939 | D->addAttr(Clone); | ||||
6940 | } | ||||
6941 | } | ||||
6942 | |||||
6943 | NamedDecl *Sema::ActOnVariableDeclarator( | ||||
6944 | Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, | ||||
6945 | LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, | ||||
6946 | bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { | ||||
6947 | QualType R = TInfo->getType(); | ||||
6948 | DeclarationName Name = GetNameForDeclarator(D).getName(); | ||||
6949 | |||||
6950 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||
6951 | |||||
6952 | if (D.isDecompositionDeclarator()) { | ||||
6953 | // Take the name of the first declarator as our name for diagnostic | ||||
6954 | // purposes. | ||||
6955 | auto &Decomp = D.getDecompositionDeclarator(); | ||||
6956 | if (!Decomp.bindings().empty()) { | ||||
6957 | II = Decomp.bindings()[0].Name; | ||||
6958 | Name = II; | ||||
6959 | } | ||||
6960 | } else if (!II) { | ||||
6961 | Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; | ||||
6962 | return nullptr; | ||||
6963 | } | ||||
6964 | |||||
6965 | |||||
6966 | DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); | ||||
6967 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); | ||||
6968 | |||||
6969 | // dllimport globals without explicit storage class are treated as extern. We | ||||
6970 | // have to change the storage class this early to get the right DeclContext. | ||||
6971 | if (SC == SC_None && !DC->isRecord() && | ||||
6972 | hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && | ||||
6973 | !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) | ||||
6974 | SC = SC_Extern; | ||||
6975 | |||||
6976 | DeclContext *OriginalDC = DC; | ||||
6977 | bool IsLocalExternDecl = SC == SC_Extern && | ||||
6978 | adjustContextForLocalExternDecl(DC); | ||||
6979 | |||||
6980 | if (SCSpec == DeclSpec::SCS_mutable) { | ||||
6981 | // mutable can only appear on non-static class members, so it's always | ||||
6982 | // an error here | ||||
6983 | Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); | ||||
6984 | D.setInvalidType(); | ||||
6985 | SC = SC_None; | ||||
6986 | } | ||||
6987 | |||||
6988 | if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && | ||||
6989 | !D.getAsmLabel() && !getSourceManager().isInSystemMacro( | ||||
6990 | D.getDeclSpec().getStorageClassSpecLoc())) { | ||||
6991 | // In C++11, the 'register' storage class specifier is deprecated. | ||||
6992 | // Suppress the warning in system macros, it's used in macros in some | ||||
6993 | // popular C system headers, such as in glibc's htonl() macro. | ||||
6994 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
6995 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | ||||
6996 | : diag::warn_deprecated_register) | ||||
6997 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||
6998 | } | ||||
6999 | |||||
7000 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||
7001 | |||||
7002 | if (!DC->isRecord() && S->getFnParent() == nullptr) { | ||||
7003 | // C99 6.9p2: The storage-class specifiers auto and register shall not | ||||
7004 | // appear in the declaration specifiers in an external declaration. | ||||
7005 | // Global Register+Asm is a GNU extension we support. | ||||
7006 | if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { | ||||
7007 | Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); | ||||
7008 | D.setInvalidType(); | ||||
7009 | } | ||||
7010 | } | ||||
7011 | |||||
7012 | // If this variable has a VLA type and an initializer, try to | ||||
7013 | // fold to a constant-sized type. This is otherwise invalid. | ||||
7014 | if (D.hasInitializer() && R->isVariableArrayType()) | ||||
7015 | tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), | ||||
7016 | /*DiagID=*/0); | ||||
7017 | |||||
7018 | bool IsMemberSpecialization = false; | ||||
7019 | bool IsVariableTemplateSpecialization = false; | ||||
7020 | bool IsPartialSpecialization = false; | ||||
7021 | bool IsVariableTemplate = false; | ||||
7022 | VarDecl *NewVD = nullptr; | ||||
7023 | VarTemplateDecl *NewTemplate = nullptr; | ||||
7024 | TemplateParameterList *TemplateParams = nullptr; | ||||
7025 | if (!getLangOpts().CPlusPlus) { | ||||
7026 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), | ||||
7027 | II, R, TInfo, SC); | ||||
7028 | |||||
7029 | if (R->getContainedDeducedType()) | ||||
7030 | ParsingInitForAutoVars.insert(NewVD); | ||||
7031 | |||||
7032 | if (D.isInvalidType()) | ||||
7033 | NewVD->setInvalidDecl(); | ||||
7034 | |||||
7035 | if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && | ||||
7036 | NewVD->hasLocalStorage()) | ||||
7037 | checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), | ||||
7038 | NTCUC_AutoVar, NTCUK_Destruct); | ||||
7039 | } else { | ||||
7040 | bool Invalid = false; | ||||
7041 | |||||
7042 | if (DC->isRecord() && !CurContext->isRecord()) { | ||||
7043 | // This is an out-of-line definition of a static data member. | ||||
7044 | switch (SC) { | ||||
7045 | case SC_None: | ||||
7046 | break; | ||||
7047 | case SC_Static: | ||||
7048 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
7049 | diag::err_static_out_of_line) | ||||
7050 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||
7051 | break; | ||||
7052 | case SC_Auto: | ||||
7053 | case SC_Register: | ||||
7054 | case SC_Extern: | ||||
7055 | // [dcl.stc] p2: The auto or register specifiers shall be applied only | ||||
7056 | // to names of variables declared in a block or to function parameters. | ||||
7057 | // [dcl.stc] p6: The extern specifier cannot be used in the declaration | ||||
7058 | // of class members | ||||
7059 | |||||
7060 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
7061 | diag::err_storage_class_for_static_member) | ||||
7062 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||
7063 | break; | ||||
7064 | case SC_PrivateExtern: | ||||
7065 | llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "clang/lib/Sema/SemaDecl.cpp" , 7065); | ||||
7066 | } | ||||
7067 | } | ||||
7068 | |||||
7069 | if (SC == SC_Static && CurContext->isRecord()) { | ||||
7070 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { | ||||
7071 | // Walk up the enclosing DeclContexts to check for any that are | ||||
7072 | // incompatible with static data members. | ||||
7073 | const DeclContext *FunctionOrMethod = nullptr; | ||||
7074 | const CXXRecordDecl *AnonStruct = nullptr; | ||||
7075 | for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { | ||||
7076 | if (Ctxt->isFunctionOrMethod()) { | ||||
7077 | FunctionOrMethod = Ctxt; | ||||
7078 | break; | ||||
7079 | } | ||||
7080 | const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); | ||||
7081 | if (ParentDecl && !ParentDecl->getDeclName()) { | ||||
7082 | AnonStruct = ParentDecl; | ||||
7083 | break; | ||||
7084 | } | ||||
7085 | } | ||||
7086 | if (FunctionOrMethod) { | ||||
7087 | // C++ [class.static.data]p5: A local class shall not have static data | ||||
7088 | // members. | ||||
7089 | Diag(D.getIdentifierLoc(), | ||||
7090 | diag::err_static_data_member_not_allowed_in_local_class) | ||||
7091 | << Name << RD->getDeclName() << RD->getTagKind(); | ||||
7092 | } else if (AnonStruct) { | ||||
7093 | // C++ [class.static.data]p4: Unnamed classes and classes contained | ||||
7094 | // directly or indirectly within unnamed classes shall not contain | ||||
7095 | // static data members. | ||||
7096 | Diag(D.getIdentifierLoc(), | ||||
7097 | diag::err_static_data_member_not_allowed_in_anon_struct) | ||||
7098 | << Name << AnonStruct->getTagKind(); | ||||
7099 | Invalid = true; | ||||
7100 | } else if (RD->isUnion()) { | ||||
7101 | // C++98 [class.union]p1: If a union contains a static data member, | ||||
7102 | // the program is ill-formed. C++11 drops this restriction. | ||||
7103 | Diag(D.getIdentifierLoc(), | ||||
7104 | getLangOpts().CPlusPlus11 | ||||
7105 | ? diag::warn_cxx98_compat_static_data_member_in_union | ||||
7106 | : diag::ext_static_data_member_in_union) << Name; | ||||
7107 | } | ||||
7108 | } | ||||
7109 | } | ||||
7110 | |||||
7111 | // Match up the template parameter lists with the scope specifier, then | ||||
7112 | // determine whether we have a template or a template specialization. | ||||
7113 | bool InvalidScope = false; | ||||
7114 | TemplateParams = MatchTemplateParametersToScopeSpecifier( | ||||
7115 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | ||||
7116 | D.getCXXScopeSpec(), | ||||
7117 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | ||||
7118 | ? D.getName().TemplateId | ||||
7119 | : nullptr, | ||||
7120 | TemplateParamLists, | ||||
7121 | /*never a friend*/ false, IsMemberSpecialization, InvalidScope); | ||||
7122 | Invalid |= InvalidScope; | ||||
7123 | |||||
7124 | if (TemplateParams) { | ||||
7125 | if (!TemplateParams->size() && | ||||
7126 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | ||||
7127 | // There is an extraneous 'template<>' for this variable. Complain | ||||
7128 | // about it, but allow the declaration of the variable. | ||||
7129 | Diag(TemplateParams->getTemplateLoc(), | ||||
7130 | diag::err_template_variable_noparams) | ||||
7131 | << II | ||||
7132 | << SourceRange(TemplateParams->getTemplateLoc(), | ||||
7133 | TemplateParams->getRAngleLoc()); | ||||
7134 | TemplateParams = nullptr; | ||||
7135 | } else { | ||||
7136 | // Check that we can declare a template here. | ||||
7137 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||
7138 | return nullptr; | ||||
7139 | |||||
7140 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||
7141 | // This is an explicit specialization or a partial specialization. | ||||
7142 | IsVariableTemplateSpecialization = true; | ||||
7143 | IsPartialSpecialization = TemplateParams->size() > 0; | ||||
7144 | } else { // if (TemplateParams->size() > 0) | ||||
7145 | // This is a template declaration. | ||||
7146 | IsVariableTemplate = true; | ||||
7147 | |||||
7148 | // Only C++1y supports variable templates (N3651). | ||||
7149 | Diag(D.getIdentifierLoc(), | ||||
7150 | getLangOpts().CPlusPlus14 | ||||
7151 | ? diag::warn_cxx11_compat_variable_template | ||||
7152 | : diag::ext_variable_template); | ||||
7153 | } | ||||
7154 | } | ||||
7155 | } else { | ||||
7156 | // Check that we can declare a member specialization here. | ||||
7157 | if (!TemplateParamLists.empty() && IsMemberSpecialization && | ||||
7158 | CheckTemplateDeclScope(S, TemplateParamLists.back())) | ||||
7159 | return nullptr; | ||||
7160 | assert((Invalid ||(static_cast <bool> ((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 7162, __extension__ __PRETTY_FUNCTION__ )) | ||||
7161 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(static_cast <bool> ((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 7162, __extension__ __PRETTY_FUNCTION__ )) | ||||
7162 | "should have a 'template<>' for this decl")(static_cast <bool> ((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 7162, __extension__ __PRETTY_FUNCTION__ )); | ||||
7163 | } | ||||
7164 | |||||
7165 | if (IsVariableTemplateSpecialization) { | ||||
7166 | SourceLocation TemplateKWLoc = | ||||
7167 | TemplateParamLists.size() > 0 | ||||
7168 | ? TemplateParamLists[0]->getTemplateLoc() | ||||
7169 | : SourceLocation(); | ||||
7170 | DeclResult Res = ActOnVarTemplateSpecialization( | ||||
7171 | S, D, TInfo, TemplateKWLoc, TemplateParams, SC, | ||||
7172 | IsPartialSpecialization); | ||||
7173 | if (Res.isInvalid()) | ||||
7174 | return nullptr; | ||||
7175 | NewVD = cast<VarDecl>(Res.get()); | ||||
7176 | AddToScope = false; | ||||
7177 | } else if (D.isDecompositionDeclarator()) { | ||||
7178 | NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), | ||||
7179 | D.getIdentifierLoc(), R, TInfo, SC, | ||||
7180 | Bindings); | ||||
7181 | } else | ||||
7182 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), | ||||
7183 | D.getIdentifierLoc(), II, R, TInfo, SC); | ||||
7184 | |||||
7185 | // If this is supposed to be a variable template, create it as such. | ||||
7186 | if (IsVariableTemplate) { | ||||
7187 | NewTemplate = | ||||
7188 | VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, | ||||
7189 | TemplateParams, NewVD); | ||||
7190 | NewVD->setDescribedVarTemplate(NewTemplate); | ||||
7191 | } | ||||
7192 | |||||
7193 | // If this decl has an auto type in need of deduction, make a note of the | ||||
7194 | // Decl so we can diagnose uses of it in its own initializer. | ||||
7195 | if (R->getContainedDeducedType()) | ||||
7196 | ParsingInitForAutoVars.insert(NewVD); | ||||
7197 | |||||
7198 | if (D.isInvalidType() || Invalid) { | ||||
7199 | NewVD->setInvalidDecl(); | ||||
7200 | if (NewTemplate) | ||||
7201 | NewTemplate->setInvalidDecl(); | ||||
7202 | } | ||||
7203 | |||||
7204 | SetNestedNameSpecifier(*this, NewVD, D); | ||||
7205 | |||||
7206 | // If we have any template parameter lists that don't directly belong to | ||||
7207 | // the variable (matching the scope specifier), store them. | ||||
7208 | unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; | ||||
7209 | if (TemplateParamLists.size() > VDTemplateParamLists) | ||||
7210 | NewVD->setTemplateParameterListsInfo( | ||||
7211 | Context, TemplateParamLists.drop_back(VDTemplateParamLists)); | ||||
7212 | } | ||||
7213 | |||||
7214 | if (D.getDeclSpec().isInlineSpecified()) { | ||||
7215 | if (!getLangOpts().CPlusPlus) { | ||||
7216 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||
7217 | << 0; | ||||
7218 | } else if (CurContext->isFunctionOrMethod()) { | ||||
7219 | // 'inline' is not allowed on block scope variable declaration. | ||||
7220 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||
7221 | diag::err_inline_declaration_block_scope) << Name | ||||
7222 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | ||||
7223 | } else { | ||||
7224 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||
7225 | getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable | ||||
7226 | : diag::ext_inline_variable); | ||||
7227 | NewVD->setInlineSpecified(); | ||||
7228 | } | ||||
7229 | } | ||||
7230 | |||||
7231 | // Set the lexical context. If the declarator has a C++ scope specifier, the | ||||
7232 | // lexical context will be different from the semantic context. | ||||
7233 | NewVD->setLexicalDeclContext(CurContext); | ||||
7234 | if (NewTemplate) | ||||
7235 | NewTemplate->setLexicalDeclContext(CurContext); | ||||
7236 | |||||
7237 | if (IsLocalExternDecl) { | ||||
7238 | if (D.isDecompositionDeclarator()) | ||||
7239 | for (auto *B : Bindings) | ||||
7240 | B->setLocalExternDecl(); | ||||
7241 | else | ||||
7242 | NewVD->setLocalExternDecl(); | ||||
7243 | } | ||||
7244 | |||||
7245 | bool EmitTLSUnsupportedError = false; | ||||
7246 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { | ||||
7247 | // C++11 [dcl.stc]p4: | ||||
7248 | // When thread_local is applied to a variable of block scope the | ||||
7249 | // storage-class-specifier static is implied if it does not appear | ||||
7250 | // explicitly. | ||||
7251 | // Core issue: 'static' is not implied if the variable is declared | ||||
7252 | // 'extern'. | ||||
7253 | if (NewVD->hasLocalStorage() && | ||||
7254 | (SCSpec != DeclSpec::SCS_unspecified || | ||||
7255 | TSCS != DeclSpec::TSCS_thread_local || | ||||
7256 | !DC->isFunctionOrMethod())) | ||||
7257 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
7258 | diag::err_thread_non_global) | ||||
7259 | << DeclSpec::getSpecifierName(TSCS); | ||||
7260 | else if (!Context.getTargetInfo().isTLSSupported()) { | ||||
7261 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || | ||||
7262 | getLangOpts().SYCLIsDevice) { | ||||
7263 | // Postpone error emission until we've collected attributes required to | ||||
7264 | // figure out whether it's a host or device variable and whether the | ||||
7265 | // error should be ignored. | ||||
7266 | EmitTLSUnsupportedError = true; | ||||
7267 | // We still need to mark the variable as TLS so it shows up in AST with | ||||
7268 | // proper storage class for other tools to use even if we're not going | ||||
7269 | // to emit any code for it. | ||||
7270 | NewVD->setTSCSpec(TSCS); | ||||
7271 | } else | ||||
7272 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
7273 | diag::err_thread_unsupported); | ||||
7274 | } else | ||||
7275 | NewVD->setTSCSpec(TSCS); | ||||
7276 | } | ||||
7277 | |||||
7278 | switch (D.getDeclSpec().getConstexprSpecifier()) { | ||||
7279 | case ConstexprSpecKind::Unspecified: | ||||
7280 | break; | ||||
7281 | |||||
7282 | case ConstexprSpecKind::Consteval: | ||||
7283 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||
7284 | diag::err_constexpr_wrong_decl_kind) | ||||
7285 | << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); | ||||
7286 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
7287 | |||||
7288 | case ConstexprSpecKind::Constexpr: | ||||
7289 | NewVD->setConstexpr(true); | ||||
7290 | // C++1z [dcl.spec.constexpr]p1: | ||||
7291 | // A static data member declared with the constexpr specifier is | ||||
7292 | // implicitly an inline variable. | ||||
7293 | if (NewVD->isStaticDataMember() && | ||||
7294 | (getLangOpts().CPlusPlus17 || | ||||
7295 | Context.getTargetInfo().getCXXABI().isMicrosoft())) | ||||
7296 | NewVD->setImplicitlyInline(); | ||||
7297 | break; | ||||
7298 | |||||
7299 | case ConstexprSpecKind::Constinit: | ||||
7300 | if (!NewVD->hasGlobalStorage()) | ||||
7301 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||
7302 | diag::err_constinit_local_variable); | ||||
7303 | else | ||||
7304 | NewVD->addAttr(ConstInitAttr::Create( | ||||
7305 | Context, D.getDeclSpec().getConstexprSpecLoc(), | ||||
7306 | AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); | ||||
7307 | break; | ||||
7308 | } | ||||
7309 | |||||
7310 | // C99 6.7.4p3 | ||||
7311 | // An inline definition of a function with external linkage shall | ||||
7312 | // not contain a definition of a modifiable object with static or | ||||
7313 | // thread storage duration... | ||||
7314 | // We only apply this when the function is required to be defined | ||||
7315 | // elsewhere, i.e. when the function is not 'extern inline'. Note | ||||
7316 | // that a local variable with thread storage duration still has to | ||||
7317 | // be marked 'static'. Also note that it's possible to get these | ||||
7318 | // semantics in C++ using __attribute__((gnu_inline)). | ||||
7319 | if (SC == SC_Static && S->getFnParent() != nullptr && | ||||
7320 | !NewVD->getType().isConstQualified()) { | ||||
7321 | FunctionDecl *CurFD = getCurFunctionDecl(); | ||||
7322 | if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { | ||||
7323 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
7324 | diag::warn_static_local_in_extern_inline); | ||||
7325 | MaybeSuggestAddingStaticToDecl(CurFD); | ||||
7326 | } | ||||
7327 | } | ||||
7328 | |||||
7329 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||
7330 | if (IsVariableTemplateSpecialization) | ||||
7331 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | ||||
7332 | << (IsPartialSpecialization ? 1 : 0) | ||||
7333 | << FixItHint::CreateRemoval( | ||||
7334 | D.getDeclSpec().getModulePrivateSpecLoc()); | ||||
7335 | else if (IsMemberSpecialization) | ||||
7336 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | ||||
7337 | << 2 | ||||
7338 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||
7339 | else if (NewVD->hasLocalStorage()) | ||||
7340 | Diag(NewVD->getLocation(), diag::err_module_private_local) | ||||
7341 | << 0 << NewVD | ||||
7342 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||
7343 | << FixItHint::CreateRemoval( | ||||
7344 | D.getDeclSpec().getModulePrivateSpecLoc()); | ||||
7345 | else { | ||||
7346 | NewVD->setModulePrivate(); | ||||
7347 | if (NewTemplate) | ||||
7348 | NewTemplate->setModulePrivate(); | ||||
7349 | for (auto *B : Bindings) | ||||
7350 | B->setModulePrivate(); | ||||
7351 | } | ||||
7352 | } | ||||
7353 | |||||
7354 | if (getLangOpts().OpenCL) { | ||||
7355 | deduceOpenCLAddressSpace(NewVD); | ||||
7356 | |||||
7357 | DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); | ||||
7358 | if (TSC != TSCS_unspecified) { | ||||
7359 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
7360 | diag::err_opencl_unknown_type_specifier) | ||||
7361 | << getLangOpts().getOpenCLVersionString() | ||||
7362 | << DeclSpec::getSpecifierName(TSC) << 1; | ||||
7363 | NewVD->setInvalidDecl(); | ||||
7364 | } | ||||
7365 | } | ||||
7366 | |||||
7367 | // Handle attributes prior to checking for duplicates in MergeVarDecl | ||||
7368 | ProcessDeclAttributes(S, NewVD, D); | ||||
7369 | |||||
7370 | // FIXME: This is probably the wrong location to be doing this and we should | ||||
7371 | // probably be doing this for more attributes (especially for function | ||||
7372 | // pointer attributes such as format, warn_unused_result, etc.). Ideally | ||||
7373 | // the code to copy attributes would be generated by TableGen. | ||||
7374 | if (R->isFunctionPointerType()) | ||||
7375 | if (const auto *TT = R->getAs<TypedefType>()) | ||||
7376 | copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); | ||||
7377 | |||||
7378 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || | ||||
7379 | getLangOpts().SYCLIsDevice) { | ||||
7380 | if (EmitTLSUnsupportedError && | ||||
7381 | ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || | ||||
7382 | (getLangOpts().OpenMPIsDevice && | ||||
7383 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) | ||||
7384 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
7385 | diag::err_thread_unsupported); | ||||
7386 | |||||
7387 | if (EmitTLSUnsupportedError && | ||||
7388 | (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) | ||||
7389 | targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); | ||||
7390 | // CUDA B.2.5: "__shared__ and __constant__ variables have implied static | ||||
7391 | // storage [duration]." | ||||
7392 | if (SC == SC_None && S->getFnParent() != nullptr && | ||||
7393 | (NewVD->hasAttr<CUDASharedAttr>() || | ||||
7394 | NewVD->hasAttr<CUDAConstantAttr>())) { | ||||
7395 | NewVD->setStorageClass(SC_Static); | ||||
7396 | } | ||||
7397 | } | ||||
7398 | |||||
7399 | // Ensure that dllimport globals without explicit storage class are treated as | ||||
7400 | // extern. The storage class is set above using parsed attributes. Now we can | ||||
7401 | // check the VarDecl itself. | ||||
7402 | assert(!NewVD->hasAttr<DLLImportAttr>() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr >() || NewVD->getAttr<DLLImportAttr>()->isInherited () || NewVD->isStaticDataMember() || NewVD->getStorageClass () != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "clang/lib/Sema/SemaDecl.cpp", 7404, __extension__ __PRETTY_FUNCTION__ )) | ||||
7403 | NewVD->getAttr<DLLImportAttr>()->isInherited() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr >() || NewVD->getAttr<DLLImportAttr>()->isInherited () || NewVD->isStaticDataMember() || NewVD->getStorageClass () != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "clang/lib/Sema/SemaDecl.cpp", 7404, __extension__ __PRETTY_FUNCTION__ )) | ||||
7404 | NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr >() || NewVD->getAttr<DLLImportAttr>()->isInherited () || NewVD->isStaticDataMember() || NewVD->getStorageClass () != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "clang/lib/Sema/SemaDecl.cpp", 7404, __extension__ __PRETTY_FUNCTION__ )); | ||||
7405 | |||||
7406 | // In auto-retain/release, infer strong retension for variables of | ||||
7407 | // retainable type. | ||||
7408 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) | ||||
7409 | NewVD->setInvalidDecl(); | ||||
7410 | |||||
7411 | // Handle GNU asm-label extension (encoded as an attribute). | ||||
7412 | if (Expr *E = (Expr*)D.getAsmLabel()) { | ||||
7413 | // The parser guarantees this is a string. | ||||
7414 | StringLiteral *SE = cast<StringLiteral>(E); | ||||
7415 | StringRef Label = SE->getString(); | ||||
7416 | if (S->getFnParent() != nullptr) { | ||||
7417 | switch (SC) { | ||||
7418 | case SC_None: | ||||
7419 | case SC_Auto: | ||||
7420 | Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; | ||||
7421 | break; | ||||
7422 | case SC_Register: | ||||
7423 | // Local Named register | ||||
7424 | if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && | ||||
7425 | DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) | ||||
7426 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | ||||
7427 | break; | ||||
7428 | case SC_Static: | ||||
7429 | case SC_Extern: | ||||
7430 | case SC_PrivateExtern: | ||||
7431 | break; | ||||
7432 | } | ||||
7433 | } else if (SC == SC_Register) { | ||||
7434 | // Global Named register | ||||
7435 | if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { | ||||
7436 | const auto &TI = Context.getTargetInfo(); | ||||
7437 | bool HasSizeMismatch; | ||||
7438 | |||||
7439 | if (!TI.isValidGCCRegisterName(Label)) | ||||
7440 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | ||||
7441 | else if (!TI.validateGlobalRegisterVariable(Label, | ||||
7442 | Context.getTypeSize(R), | ||||
7443 | HasSizeMismatch)) | ||||
7444 | Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; | ||||
7445 | else if (HasSizeMismatch) | ||||
7446 | Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; | ||||
7447 | } | ||||
7448 | |||||
7449 | if (!R->isIntegralType(Context) && !R->isPointerType()) { | ||||
7450 | Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); | ||||
7451 | NewVD->setInvalidDecl(true); | ||||
7452 | } | ||||
7453 | } | ||||
7454 | |||||
7455 | NewVD->addAttr(AsmLabelAttr::Create(Context, Label, | ||||
7456 | /*IsLiteralLabel=*/true, | ||||
7457 | SE->getStrTokenLoc(0))); | ||||
7458 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | ||||
7459 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | ||||
7460 | ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); | ||||
7461 | if (I != ExtnameUndeclaredIdentifiers.end()) { | ||||
7462 | if (isDeclExternC(NewVD)) { | ||||
7463 | NewVD->addAttr(I->second); | ||||
7464 | ExtnameUndeclaredIdentifiers.erase(I); | ||||
7465 | } else | ||||
7466 | Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) | ||||
7467 | << /*Variable*/1 << NewVD; | ||||
7468 | } | ||||
7469 | } | ||||
7470 | |||||
7471 | // Find the shadowed declaration before filtering for scope. | ||||
7472 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() | ||||
7473 | ? getShadowedDeclaration(NewVD, Previous) | ||||
7474 | : nullptr; | ||||
7475 | |||||
7476 | // Don't consider existing declarations that are in a different | ||||
7477 | // scope and are out-of-semantic-context declarations (if the new | ||||
7478 | // declaration has linkage). | ||||
7479 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), | ||||
7480 | D.getCXXScopeSpec().isNotEmpty() || | ||||
7481 | IsMemberSpecialization || | ||||
7482 | IsVariableTemplateSpecialization); | ||||
7483 | |||||
7484 | // Check whether the previous declaration is in the same block scope. This | ||||
7485 | // affects whether we merge types with it, per C++11 [dcl.array]p3. | ||||
7486 | if (getLangOpts().CPlusPlus && | ||||
7487 | NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) | ||||
7488 | NewVD->setPreviousDeclInSameBlockScope( | ||||
7489 | Previous.isSingleResult() && !Previous.isShadowed() && | ||||
7490 | isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); | ||||
7491 | |||||
7492 | if (!getLangOpts().CPlusPlus) { | ||||
7493 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | ||||
7494 | } else { | ||||
7495 | // If this is an explicit specialization of a static data member, check it. | ||||
7496 | if (IsMemberSpecialization && !NewVD->isInvalidDecl() && | ||||
7497 | CheckMemberSpecialization(NewVD, Previous)) | ||||
7498 | NewVD->setInvalidDecl(); | ||||
7499 | |||||
7500 | // Merge the decl with the existing one if appropriate. | ||||
7501 | if (!Previous.empty()) { | ||||
7502 | if (Previous.isSingleResult() && | ||||
7503 | isa<FieldDecl>(Previous.getFoundDecl()) && | ||||
7504 | D.getCXXScopeSpec().isSet()) { | ||||
7505 | // The user tried to define a non-static data member | ||||
7506 | // out-of-line (C++ [dcl.meaning]p1). | ||||
7507 | Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) | ||||
7508 | << D.getCXXScopeSpec().getRange(); | ||||
7509 | Previous.clear(); | ||||
7510 | NewVD->setInvalidDecl(); | ||||
7511 | } | ||||
7512 | } else if (D.getCXXScopeSpec().isSet()) { | ||||
7513 | // No previous declaration in the qualifying scope. | ||||
7514 | Diag(D.getIdentifierLoc(), diag::err_no_member) | ||||
7515 | << Name << computeDeclContext(D.getCXXScopeSpec(), true) | ||||
7516 | << D.getCXXScopeSpec().getRange(); | ||||
7517 | NewVD->setInvalidDecl(); | ||||
7518 | } | ||||
7519 | |||||
7520 | if (!IsVariableTemplateSpecialization) | ||||
7521 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | ||||
7522 | |||||
7523 | if (NewTemplate) { | ||||
7524 | VarTemplateDecl *PrevVarTemplate = | ||||
7525 | NewVD->getPreviousDecl() | ||||
7526 | ? NewVD->getPreviousDecl()->getDescribedVarTemplate() | ||||
7527 | : nullptr; | ||||
7528 | |||||
7529 | // Check the template parameter list of this declaration, possibly | ||||
7530 | // merging in the template parameter list from the previous variable | ||||
7531 | // template declaration. | ||||
7532 | if (CheckTemplateParameterList( | ||||
7533 | TemplateParams, | ||||
7534 | PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() | ||||
7535 | : nullptr, | ||||
7536 | (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && | ||||
7537 | DC->isDependentContext()) | ||||
7538 | ? TPC_ClassTemplateMember | ||||
7539 | : TPC_VarTemplate)) | ||||
7540 | NewVD->setInvalidDecl(); | ||||
7541 | |||||
7542 | // If we are providing an explicit specialization of a static variable | ||||
7543 | // template, make a note of that. | ||||
7544 | if (PrevVarTemplate && | ||||
7545 | PrevVarTemplate->getInstantiatedFromMemberTemplate()) | ||||
7546 | PrevVarTemplate->setMemberSpecialization(); | ||||
7547 | } | ||||
7548 | } | ||||
7549 | |||||
7550 | // Diagnose shadowed variables iff this isn't a redeclaration. | ||||
7551 | if (ShadowedDecl && !D.isRedeclaration()) | ||||
7552 | CheckShadow(NewVD, ShadowedDecl, Previous); | ||||
7553 | |||||
7554 | ProcessPragmaWeak(S, NewVD); | ||||
7555 | |||||
7556 | // If this is the first declaration of an extern C variable, update | ||||
7557 | // the map of such variables. | ||||
7558 | if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && | ||||
7559 | isIncompleteDeclExternC(*this, NewVD)) | ||||
7560 | RegisterLocallyScopedExternCDecl(NewVD, S); | ||||
7561 | |||||
7562 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | ||||
7563 | MangleNumberingContext *MCtx; | ||||
7564 | Decl *ManglingContextDecl; | ||||
7565 | std::tie(MCtx, ManglingContextDecl) = | ||||
7566 | getCurrentMangleNumberContext(NewVD->getDeclContext()); | ||||
7567 | if (MCtx) { | ||||
7568 | Context.setManglingNumber( | ||||
7569 | NewVD, MCtx->getManglingNumber( | ||||
7570 | NewVD, getMSManglingNumber(getLangOpts(), S))); | ||||
7571 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | ||||
7572 | } | ||||
7573 | } | ||||
7574 | |||||
7575 | // Special handling of variable named 'main'. | ||||
7576 | if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && | ||||
7577 | NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && | ||||
7578 | !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { | ||||
7579 | |||||
7580 | // C++ [basic.start.main]p3 | ||||
7581 | // A program that declares a variable main at global scope is ill-formed. | ||||
7582 | if (getLangOpts().CPlusPlus) | ||||
7583 | Diag(D.getBeginLoc(), diag::err_main_global_variable); | ||||
7584 | |||||
7585 | // In C, and external-linkage variable named main results in undefined | ||||
7586 | // behavior. | ||||
7587 | else if (NewVD->hasExternalFormalLinkage()) | ||||
7588 | Diag(D.getBeginLoc(), diag::warn_main_redefined); | ||||
7589 | } | ||||
7590 | |||||
7591 | if (D.isRedeclaration() && !Previous.empty()) { | ||||
7592 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | ||||
7593 | checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, | ||||
7594 | D.isFunctionDefinition()); | ||||
7595 | } | ||||
7596 | |||||
7597 | if (NewTemplate) { | ||||
7598 | if (NewVD->isInvalidDecl()) | ||||
7599 | NewTemplate->setInvalidDecl(); | ||||
7600 | ActOnDocumentableDecl(NewTemplate); | ||||
7601 | return NewTemplate; | ||||
7602 | } | ||||
7603 | |||||
7604 | if (IsMemberSpecialization && !NewVD->isInvalidDecl()) | ||||
7605 | CompleteMemberSpecialization(NewVD, Previous); | ||||
7606 | |||||
7607 | return NewVD; | ||||
7608 | } | ||||
7609 | |||||
7610 | /// Enum describing the %select options in diag::warn_decl_shadow. | ||||
7611 | enum ShadowedDeclKind { | ||||
7612 | SDK_Local, | ||||
7613 | SDK_Global, | ||||
7614 | SDK_StaticMember, | ||||
7615 | SDK_Field, | ||||
7616 | SDK_Typedef, | ||||
7617 | SDK_Using, | ||||
7618 | SDK_StructuredBinding | ||||
7619 | }; | ||||
7620 | |||||
7621 | /// Determine what kind of declaration we're shadowing. | ||||
7622 | static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, | ||||
7623 | const DeclContext *OldDC) { | ||||
7624 | if (isa<TypeAliasDecl>(ShadowedDecl)) | ||||
7625 | return SDK_Using; | ||||
7626 | else if (isa<TypedefDecl>(ShadowedDecl)) | ||||
7627 | return SDK_Typedef; | ||||
7628 | else if (isa<BindingDecl>(ShadowedDecl)) | ||||
7629 | return SDK_StructuredBinding; | ||||
7630 | else if (isa<RecordDecl>(OldDC)) | ||||
7631 | return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; | ||||
7632 | |||||
7633 | return OldDC->isFileContext() ? SDK_Global : SDK_Local; | ||||
7634 | } | ||||
7635 | |||||
7636 | /// Return the location of the capture if the given lambda captures the given | ||||
7637 | /// variable \p VD, or an invalid source location otherwise. | ||||
7638 | static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, | ||||
7639 | const VarDecl *VD) { | ||||
7640 | for (const Capture &Capture : LSI->Captures) { | ||||
7641 | if (Capture.isVariableCapture() && Capture.getVariable() == VD) | ||||
7642 | return Capture.getLocation(); | ||||
7643 | } | ||||
7644 | return SourceLocation(); | ||||
7645 | } | ||||
7646 | |||||
7647 | static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, | ||||
7648 | const LookupResult &R) { | ||||
7649 | // Only diagnose if we're shadowing an unambiguous field or variable. | ||||
7650 | if (R.getResultKind() != LookupResult::Found) | ||||
7651 | return false; | ||||
7652 | |||||
7653 | // Return false if warning is ignored. | ||||
7654 | return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); | ||||
7655 | } | ||||
7656 | |||||
7657 | /// Return the declaration shadowed by the given variable \p D, or null | ||||
7658 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||
7659 | NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, | ||||
7660 | const LookupResult &R) { | ||||
7661 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||
7662 | return nullptr; | ||||
7663 | |||||
7664 | // Don't diagnose declarations at file scope. | ||||
7665 | if (D->hasGlobalStorage()) | ||||
7666 | return nullptr; | ||||
7667 | |||||
7668 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||
7669 | return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl | ||||
7670 | : nullptr; | ||||
7671 | } | ||||
7672 | |||||
7673 | /// Return the declaration shadowed by the given typedef \p D, or null | ||||
7674 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||
7675 | NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, | ||||
7676 | const LookupResult &R) { | ||||
7677 | // Don't warn if typedef declaration is part of a class | ||||
7678 | if (D->getDeclContext()->isRecord()) | ||||
7679 | return nullptr; | ||||
7680 | |||||
7681 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||
7682 | return nullptr; | ||||
7683 | |||||
7684 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||
7685 | return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; | ||||
7686 | } | ||||
7687 | |||||
7688 | /// Return the declaration shadowed by the given variable \p D, or null | ||||
7689 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||
7690 | NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, | ||||
7691 | const LookupResult &R) { | ||||
7692 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||
7693 | return nullptr; | ||||
7694 | |||||
7695 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||
7696 | return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl | ||||
7697 | : nullptr; | ||||
7698 | } | ||||
7699 | |||||
7700 | /// Diagnose variable or built-in function shadowing. Implements | ||||
7701 | /// -Wshadow. | ||||
7702 | /// | ||||
7703 | /// This method is called whenever a VarDecl is added to a "useful" | ||||
7704 | /// scope. | ||||
7705 | /// | ||||
7706 | /// \param ShadowedDecl the declaration that is shadowed by the given variable | ||||
7707 | /// \param R the lookup of the name | ||||
7708 | /// | ||||
7709 | void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, | ||||
7710 | const LookupResult &R) { | ||||
7711 | DeclContext *NewDC = D->getDeclContext(); | ||||
7712 | |||||
7713 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { | ||||
7714 | // Fields are not shadowed by variables in C++ static methods. | ||||
7715 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) | ||||
7716 | if (MD->isStatic()) | ||||
7717 | return; | ||||
7718 | |||||
7719 | // Fields shadowed by constructor parameters are a special case. Usually | ||||
7720 | // the constructor initializes the field with the parameter. | ||||
7721 | if (isa<CXXConstructorDecl>(NewDC)) | ||||
7722 | if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { | ||||
7723 | // Remember that this was shadowed so we can either warn about its | ||||
7724 | // modification or its existence depending on warning settings. | ||||
7725 | ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); | ||||
7726 | return; | ||||
7727 | } | ||||
7728 | } | ||||
7729 | |||||
7730 | if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) | ||||
7731 | if (shadowedVar->isExternC()) { | ||||
7732 | // For shadowing external vars, make sure that we point to the global | ||||
7733 | // declaration, not a locally scoped extern declaration. | ||||
7734 | for (auto I : shadowedVar->redecls()) | ||||
7735 | if (I->isFileVarDecl()) { | ||||
7736 | ShadowedDecl = I; | ||||
7737 | break; | ||||
7738 | } | ||||
7739 | } | ||||
7740 | |||||
7741 | DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); | ||||
7742 | |||||
7743 | unsigned WarningDiag = diag::warn_decl_shadow; | ||||
7744 | SourceLocation CaptureLoc; | ||||
7745 | if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && | ||||
7746 | isa<CXXMethodDecl>(NewDC)) { | ||||
7747 | if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { | ||||
7748 | if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { | ||||
7749 | if (RD->getLambdaCaptureDefault() == LCD_None) { | ||||
7750 | // Try to avoid warnings for lambdas with an explicit capture list. | ||||
7751 | const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); | ||||
7752 | // Warn only when the lambda captures the shadowed decl explicitly. | ||||
7753 | CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); | ||||
7754 | if (CaptureLoc.isInvalid()) | ||||
7755 | WarningDiag = diag::warn_decl_shadow_uncaptured_local; | ||||
7756 | } else { | ||||
7757 | // Remember that this was shadowed so we can avoid the warning if the | ||||
7758 | // shadowed decl isn't captured and the warning settings allow it. | ||||
7759 | cast<LambdaScopeInfo>(getCurFunction()) | ||||
7760 | ->ShadowingDecls.push_back( | ||||
7761 | {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); | ||||
7762 | return; | ||||
7763 | } | ||||
7764 | } | ||||
7765 | |||||
7766 | if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { | ||||
7767 | // A variable can't shadow a local variable in an enclosing scope, if | ||||
7768 | // they are separated by a non-capturing declaration context. | ||||
7769 | for (DeclContext *ParentDC = NewDC; | ||||
7770 | ParentDC && !ParentDC->Equals(OldDC); | ||||
7771 | ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { | ||||
7772 | // Only block literals, captured statements, and lambda expressions | ||||
7773 | // can capture; other scopes don't. | ||||
7774 | if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && | ||||
7775 | !isLambdaCallOperator(ParentDC)) { | ||||
7776 | return; | ||||
7777 | } | ||||
7778 | } | ||||
7779 | } | ||||
7780 | } | ||||
7781 | } | ||||
7782 | |||||
7783 | // Only warn about certain kinds of shadowing for class members. | ||||
7784 | if (NewDC && NewDC->isRecord()) { | ||||
7785 | // In particular, don't warn about shadowing non-class members. | ||||
7786 | if (!OldDC->isRecord()) | ||||
7787 | return; | ||||
7788 | |||||
7789 | // TODO: should we warn about static data members shadowing | ||||
7790 | // static data members from base classes? | ||||
7791 | |||||
7792 | // TODO: don't diagnose for inaccessible shadowed members. | ||||
7793 | // This is hard to do perfectly because we might friend the | ||||
7794 | // shadowing context, but that's just a false negative. | ||||
7795 | } | ||||
7796 | |||||
7797 | |||||
7798 | DeclarationName Name = R.getLookupName(); | ||||
7799 | |||||
7800 | // Emit warning and note. | ||||
7801 | if (getSourceManager().isInSystemMacro(R.getNameLoc())) | ||||
7802 | return; | ||||
7803 | ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); | ||||
7804 | Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; | ||||
7805 | if (!CaptureLoc.isInvalid()) | ||||
7806 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | ||||
7807 | << Name << /*explicitly*/ 1; | ||||
7808 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||
7809 | } | ||||
7810 | |||||
7811 | /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD | ||||
7812 | /// when these variables are captured by the lambda. | ||||
7813 | void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { | ||||
7814 | for (const auto &Shadow : LSI->ShadowingDecls) { | ||||
7815 | const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; | ||||
7816 | // Try to avoid the warning when the shadowed decl isn't captured. | ||||
7817 | SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); | ||||
7818 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | ||||
7819 | Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() | ||||
7820 | ? diag::warn_decl_shadow_uncaptured_local | ||||
7821 | : diag::warn_decl_shadow) | ||||
7822 | << Shadow.VD->getDeclName() | ||||
7823 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; | ||||
7824 | if (!CaptureLoc.isInvalid()) | ||||
7825 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | ||||
7826 | << Shadow.VD->getDeclName() << /*explicitly*/ 0; | ||||
7827 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||
7828 | } | ||||
7829 | } | ||||
7830 | |||||
7831 | /// Check -Wshadow without the advantage of a previous lookup. | ||||
7832 | void Sema::CheckShadow(Scope *S, VarDecl *D) { | ||||
7833 | if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) | ||||
7834 | return; | ||||
7835 | |||||
7836 | LookupResult R(*this, D->getDeclName(), D->getLocation(), | ||||
7837 | Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); | ||||
7838 | LookupName(R, S); | ||||
7839 | if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) | ||||
7840 | CheckShadow(D, ShadowedDecl, R); | ||||
7841 | } | ||||
7842 | |||||
7843 | /// Check if 'E', which is an expression that is about to be modified, refers | ||||
7844 | /// to a constructor parameter that shadows a field. | ||||
7845 | void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { | ||||
7846 | // Quickly ignore expressions that can't be shadowing ctor parameters. | ||||
7847 | if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) | ||||
7848 | return; | ||||
7849 | E = E->IgnoreParenImpCasts(); | ||||
7850 | auto *DRE = dyn_cast<DeclRefExpr>(E); | ||||
7851 | if (!DRE) | ||||
7852 | return; | ||||
7853 | const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); | ||||
7854 | auto I = ShadowingDecls.find(D); | ||||
7855 | if (I == ShadowingDecls.end()) | ||||
7856 | return; | ||||
7857 | const NamedDecl *ShadowedDecl = I->second; | ||||
7858 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | ||||
7859 | Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; | ||||
7860 | Diag(D->getLocation(), diag::note_var_declared_here) << D; | ||||
7861 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||
7862 | |||||
7863 | // Avoid issuing multiple warnings about the same decl. | ||||
7864 | ShadowingDecls.erase(I); | ||||
7865 | } | ||||
7866 | |||||
7867 | /// Check for conflict between this global or extern "C" declaration and | ||||
7868 | /// previous global or extern "C" declarations. This is only used in C++. | ||||
7869 | template<typename T> | ||||
7870 | static bool checkGlobalOrExternCConflict( | ||||
7871 | Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { | ||||
7872 | assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")(static_cast <bool> (S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\"" , "clang/lib/Sema/SemaDecl.cpp", 7872, __extension__ __PRETTY_FUNCTION__ )); | ||||
7873 | NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); | ||||
7874 | |||||
7875 | if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { | ||||
7876 | // The common case: this global doesn't conflict with any extern "C" | ||||
7877 | // declaration. | ||||
7878 | return false; | ||||
7879 | } | ||||
7880 | |||||
7881 | if (Prev) { | ||||
7882 | if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { | ||||
7883 | // Both the old and new declarations have C language linkage. This is a | ||||
7884 | // redeclaration. | ||||
7885 | Previous.clear(); | ||||
7886 | Previous.addDecl(Prev); | ||||
7887 | return true; | ||||
7888 | } | ||||
7889 | |||||
7890 | // This is a global, non-extern "C" declaration, and there is a previous | ||||
7891 | // non-global extern "C" declaration. Diagnose if this is a variable | ||||
7892 | // declaration. | ||||
7893 | if (!isa<VarDecl>(ND)) | ||||
7894 | return false; | ||||
7895 | } else { | ||||
7896 | // The declaration is extern "C". Check for any declaration in the | ||||
7897 | // translation unit which might conflict. | ||||
7898 | if (IsGlobal) { | ||||
7899 | // We have already performed the lookup into the translation unit. | ||||
7900 | IsGlobal = false; | ||||
7901 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||
7902 | I != E; ++I) { | ||||
7903 | if (isa<VarDecl>(*I)) { | ||||
7904 | Prev = *I; | ||||
7905 | break; | ||||
7906 | } | ||||
7907 | } | ||||
7908 | } else { | ||||
7909 | DeclContext::lookup_result R = | ||||
7910 | S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); | ||||
7911 | for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); | ||||
7912 | I != E; ++I) { | ||||
7913 | if (isa<VarDecl>(*I)) { | ||||
7914 | Prev = *I; | ||||
7915 | break; | ||||
7916 | } | ||||
7917 | // FIXME: If we have any other entity with this name in global scope, | ||||
7918 | // the declaration is ill-formed, but that is a defect: it breaks the | ||||
7919 | // 'stat' hack, for instance. Only variables can have mangled name | ||||
7920 | // clashes with extern "C" declarations, so only they deserve a | ||||
7921 | // diagnostic. | ||||
7922 | } | ||||
7923 | } | ||||
7924 | |||||
7925 | if (!Prev) | ||||
7926 | return false; | ||||
7927 | } | ||||
7928 | |||||
7929 | // Use the first declaration's location to ensure we point at something which | ||||
7930 | // is lexically inside an extern "C" linkage-spec. | ||||
7931 | assert(Prev && "should have found a previous declaration to diagnose")(static_cast <bool> (Prev && "should have found a previous declaration to diagnose" ) ? void (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\"" , "clang/lib/Sema/SemaDecl.cpp", 7931, __extension__ __PRETTY_FUNCTION__ )); | ||||
7932 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) | ||||
7933 | Prev = FD->getFirstDecl(); | ||||
7934 | else | ||||
7935 | Prev = cast<VarDecl>(Prev)->getFirstDecl(); | ||||
7936 | |||||
7937 | S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) | ||||
7938 | << IsGlobal << ND; | ||||
7939 | S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) | ||||
7940 | << IsGlobal; | ||||
7941 | return false; | ||||
7942 | } | ||||
7943 | |||||
7944 | /// Apply special rules for handling extern "C" declarations. Returns \c true | ||||
7945 | /// if we have found that this is a redeclaration of some prior entity. | ||||
7946 | /// | ||||
7947 | /// Per C++ [dcl.link]p6: | ||||
7948 | /// Two declarations [for a function or variable] with C language linkage | ||||
7949 | /// with the same name that appear in different scopes refer to the same | ||||
7950 | /// [entity]. An entity with C language linkage shall not be declared with | ||||
7951 | /// the same name as an entity in global scope. | ||||
7952 | template<typename T> | ||||
7953 | static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, | ||||
7954 | LookupResult &Previous) { | ||||
7955 | if (!S.getLangOpts().CPlusPlus) { | ||||
7956 | // In C, when declaring a global variable, look for a corresponding 'extern' | ||||
7957 | // variable declared in function scope. We don't need this in C++, because | ||||
7958 | // we find local extern decls in the surrounding file-scope DeclContext. | ||||
7959 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||
7960 | if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { | ||||
7961 | Previous.clear(); | ||||
7962 | Previous.addDecl(Prev); | ||||
7963 | return true; | ||||
7964 | } | ||||
7965 | } | ||||
7966 | return false; | ||||
7967 | } | ||||
7968 | |||||
7969 | // A declaration in the translation unit can conflict with an extern "C" | ||||
7970 | // declaration. | ||||
7971 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) | ||||
7972 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); | ||||
7973 | |||||
7974 | // An extern "C" declaration can conflict with a declaration in the | ||||
7975 | // translation unit or can be a redeclaration of an extern "C" declaration | ||||
7976 | // in another scope. | ||||
7977 | if (isIncompleteDeclExternC(S,ND)) | ||||
7978 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); | ||||
7979 | |||||
7980 | // Neither global nor extern "C": nothing to do. | ||||
7981 | return false; | ||||
7982 | } | ||||
7983 | |||||
7984 | void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { | ||||
7985 | // If the decl is already known invalid, don't check it. | ||||
7986 | if (NewVD->isInvalidDecl()) | ||||
7987 | return; | ||||
7988 | |||||
7989 | QualType T = NewVD->getType(); | ||||
7990 | |||||
7991 | // Defer checking an 'auto' type until its initializer is attached. | ||||
7992 | if (T->isUndeducedType()) | ||||
7993 | return; | ||||
7994 | |||||
7995 | if (NewVD->hasAttrs()) | ||||
7996 | CheckAlignasUnderalignment(NewVD); | ||||
7997 | |||||
7998 | if (T->isObjCObjectType()) { | ||||
7999 | Diag(NewVD->getLocation(), diag::err_statically_allocated_object) | ||||
8000 | << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); | ||||
8001 | T = Context.getObjCObjectPointerType(T); | ||||
8002 | NewVD->setType(T); | ||||
8003 | } | ||||
8004 | |||||
8005 | // Emit an error if an address space was applied to decl with local storage. | ||||
8006 | // This includes arrays of objects with address space qualifiers, but not | ||||
8007 | // automatic variables that point to other address spaces. | ||||
8008 | // ISO/IEC TR 18037 S5.1.2 | ||||
8009 | if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && | ||||
8010 | T.getAddressSpace() != LangAS::Default) { | ||||
8011 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; | ||||
8012 | NewVD->setInvalidDecl(); | ||||
8013 | return; | ||||
8014 | } | ||||
8015 | |||||
8016 | // OpenCL v1.2 s6.8 - The static qualifier is valid only in program | ||||
8017 | // scope. | ||||
8018 | if (getLangOpts().OpenCLVersion == 120 && | ||||
8019 | !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", | ||||
8020 | getLangOpts()) && | ||||
8021 | NewVD->isStaticLocal()) { | ||||
8022 | Diag(NewVD->getLocation(), diag::err_static_function_scope); | ||||
8023 | NewVD->setInvalidDecl(); | ||||
8024 | return; | ||||
8025 | } | ||||
8026 | |||||
8027 | if (getLangOpts().OpenCL) { | ||||
8028 | if (!diagnoseOpenCLTypes(*this, NewVD)) | ||||
8029 | return; | ||||
8030 | |||||
8031 | // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. | ||||
8032 | if (NewVD->hasAttr<BlocksAttr>()) { | ||||
8033 | Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); | ||||
8034 | return; | ||||
8035 | } | ||||
8036 | |||||
8037 | if (T->isBlockPointerType()) { | ||||
8038 | // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and | ||||
8039 | // can't use 'extern' storage class. | ||||
8040 | if (!T.isConstQualified()) { | ||||
8041 | Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) | ||||
8042 | << 0 /*const*/; | ||||
8043 | NewVD->setInvalidDecl(); | ||||
8044 | return; | ||||
8045 | } | ||||
8046 | if (NewVD->hasExternalStorage()) { | ||||
8047 | Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); | ||||
8048 | NewVD->setInvalidDecl(); | ||||
8049 | return; | ||||
8050 | } | ||||
8051 | } | ||||
8052 | |||||
8053 | // FIXME: Adding local AS in C++ for OpenCL might make sense. | ||||
8054 | if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || | ||||
8055 | NewVD->hasExternalStorage()) { | ||||
8056 | if (!T->isSamplerT() && !T->isDependentType() && | ||||
8057 | !(T.getAddressSpace() == LangAS::opencl_constant || | ||||
8058 | (T.getAddressSpace() == LangAS::opencl_global && | ||||
8059 | getOpenCLOptions().areProgramScopeVariablesSupported( | ||||
8060 | getLangOpts())))) { | ||||
8061 | int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; | ||||
8062 | if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) | ||||
8063 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | ||||
8064 | << Scope << "global or constant"; | ||||
8065 | else | ||||
8066 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | ||||
8067 | << Scope << "constant"; | ||||
8068 | NewVD->setInvalidDecl(); | ||||
8069 | return; | ||||
8070 | } | ||||
8071 | } else { | ||||
8072 | if (T.getAddressSpace() == LangAS::opencl_global) { | ||||
8073 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||
8074 | << 1 /*is any function*/ << "global"; | ||||
8075 | NewVD->setInvalidDecl(); | ||||
8076 | return; | ||||
8077 | } | ||||
8078 | if (T.getAddressSpace() == LangAS::opencl_constant || | ||||
8079 | T.getAddressSpace() == LangAS::opencl_local) { | ||||
8080 | FunctionDecl *FD = getCurFunctionDecl(); | ||||
8081 | // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables | ||||
8082 | // in functions. | ||||
8083 | if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { | ||||
8084 | if (T.getAddressSpace() == LangAS::opencl_constant) | ||||
8085 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||
8086 | << 0 /*non-kernel only*/ << "constant"; | ||||
8087 | else | ||||
8088 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||
8089 | << 0 /*non-kernel only*/ << "local"; | ||||
8090 | NewVD->setInvalidDecl(); | ||||
8091 | return; | ||||
8092 | } | ||||
8093 | // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be | ||||
8094 | // in the outermost scope of a kernel function. | ||||
8095 | if (FD && FD->hasAttr<OpenCLKernelAttr>()) { | ||||
8096 | if (!getCurScope()->isFunctionScope()) { | ||||
8097 | if (T.getAddressSpace() == LangAS::opencl_constant) | ||||
8098 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | ||||
8099 | << "constant"; | ||||
8100 | else | ||||
8101 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | ||||
8102 | << "local"; | ||||
8103 | NewVD->setInvalidDecl(); | ||||
8104 | return; | ||||
8105 | } | ||||
8106 | } | ||||
8107 | } else if (T.getAddressSpace() != LangAS::opencl_private && | ||||
8108 | // If we are parsing a template we didn't deduce an addr | ||||
8109 | // space yet. | ||||
8110 | T.getAddressSpace() != LangAS::Default) { | ||||
8111 | // Do not allow other address spaces on automatic variable. | ||||
8112 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; | ||||
8113 | NewVD->setInvalidDecl(); | ||||
8114 | return; | ||||
8115 | } | ||||
8116 | } | ||||
8117 | } | ||||
8118 | |||||
8119 | if (NewVD->hasLocalStorage() && T.isObjCGCWeak() | ||||
8120 | && !NewVD->hasAttr<BlocksAttr>()) { | ||||
8121 | if (getLangOpts().getGC() != LangOptions::NonGC) | ||||
8122 | Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); | ||||
8123 | else { | ||||
8124 | assert(!getLangOpts().ObjCAutoRefCount)(static_cast <bool> (!getLangOpts().ObjCAutoRefCount) ? void (0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "clang/lib/Sema/SemaDecl.cpp", 8124, __extension__ __PRETTY_FUNCTION__ )); | ||||
8125 | Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); | ||||
8126 | } | ||||
8127 | } | ||||
8128 | |||||
8129 | bool isVM = T->isVariablyModifiedType(); | ||||
8130 | if (isVM || NewVD->hasAttr<CleanupAttr>() || | ||||
8131 | NewVD->hasAttr<BlocksAttr>()) | ||||
8132 | setFunctionHasBranchProtectedScope(); | ||||
8133 | |||||
8134 | if ((isVM && NewVD->hasLinkage()) || | ||||
8135 | (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { | ||||
8136 | bool SizeIsNegative; | ||||
8137 | llvm::APSInt Oversized; | ||||
8138 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( | ||||
8139 | NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); | ||||
8140 | QualType FixedT; | ||||
8141 | if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) | ||||
8142 | FixedT = FixedTInfo->getType(); | ||||
8143 | else if (FixedTInfo) { | ||||
8144 | // Type and type-as-written are canonically different. We need to fix up | ||||
8145 | // both types separately. | ||||
8146 | FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, | ||||
8147 | Oversized); | ||||
8148 | } | ||||
8149 | if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { | ||||
8150 | const VariableArrayType *VAT = Context.getAsVariableArrayType(T); | ||||
8151 | // FIXME: This won't give the correct result for | ||||
8152 | // int a[10][n]; | ||||
8153 | SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); | ||||
8154 | |||||
8155 | if (NewVD->isFileVarDecl()) | ||||
8156 | Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) | ||||
8157 | << SizeRange; | ||||
8158 | else if (NewVD->isStaticLocal()) | ||||
8159 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) | ||||
8160 | << SizeRange; | ||||
8161 | else | ||||
8162 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) | ||||
8163 | << SizeRange; | ||||
8164 | NewVD->setInvalidDecl(); | ||||
8165 | return; | ||||
8166 | } | ||||
8167 | |||||
8168 | if (!FixedTInfo) { | ||||
8169 | if (NewVD->isFileVarDecl()) | ||||
8170 | Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); | ||||
8171 | else | ||||
8172 | Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); | ||||
8173 | NewVD->setInvalidDecl(); | ||||
8174 | return; | ||||
8175 | } | ||||
8176 | |||||
8177 | Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); | ||||
8178 | NewVD->setType(FixedT); | ||||
8179 | NewVD->setTypeSourceInfo(FixedTInfo); | ||||
8180 | } | ||||
8181 | |||||
8182 | if (T->isVoidType()) { | ||||
8183 | // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names | ||||
8184 | // of objects and functions. | ||||
8185 | if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { | ||||
8186 | Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) | ||||
8187 | << T; | ||||
8188 | NewVD->setInvalidDecl(); | ||||
8189 | return; | ||||
8190 | } | ||||
8191 | } | ||||
8192 | |||||
8193 | if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { | ||||
8194 | Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); | ||||
8195 | NewVD->setInvalidDecl(); | ||||
8196 | return; | ||||
8197 | } | ||||
8198 | |||||
8199 | if (!NewVD->hasLocalStorage() && T->isSizelessType()) { | ||||
8200 | Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; | ||||
8201 | NewVD->setInvalidDecl(); | ||||
8202 | return; | ||||
8203 | } | ||||
8204 | |||||
8205 | if (isVM && NewVD->hasAttr<BlocksAttr>()) { | ||||
8206 | Diag(NewVD->getLocation(), diag::err_block_on_vm); | ||||
8207 | NewVD->setInvalidDecl(); | ||||
8208 | return; | ||||
8209 | } | ||||
8210 | |||||
8211 | if (NewVD->isConstexpr() && !T->isDependentType() && | ||||
8212 | RequireLiteralType(NewVD->getLocation(), T, | ||||
8213 | diag::err_constexpr_var_non_literal)) { | ||||
8214 | NewVD->setInvalidDecl(); | ||||
8215 | return; | ||||
8216 | } | ||||
8217 | |||||
8218 | // PPC MMA non-pointer types are not allowed as non-local variable types. | ||||
8219 | if (Context.getTargetInfo().getTriple().isPPC64() && | ||||
8220 | !NewVD->isLocalVarDecl() && | ||||
8221 | CheckPPCMMAType(T, NewVD->getLocation())) { | ||||
8222 | NewVD->setInvalidDecl(); | ||||
8223 | return; | ||||
8224 | } | ||||
8225 | } | ||||
8226 | |||||
8227 | /// Perform semantic checking on a newly-created variable | ||||
8228 | /// declaration. | ||||
8229 | /// | ||||
8230 | /// This routine performs all of the type-checking required for a | ||||
8231 | /// variable declaration once it has been built. It is used both to | ||||
8232 | /// check variables after they have been parsed and their declarators | ||||
8233 | /// have been translated into a declaration, and to check variables | ||||
8234 | /// that have been instantiated from a template. | ||||
8235 | /// | ||||
8236 | /// Sets NewVD->isInvalidDecl() if an error was encountered. | ||||
8237 | /// | ||||
8238 | /// Returns true if the variable declaration is a redeclaration. | ||||
8239 | bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { | ||||
8240 | CheckVariableDeclarationType(NewVD); | ||||
8241 | |||||
8242 | // If the decl is already known invalid, don't check it. | ||||
8243 | if (NewVD->isInvalidDecl()) | ||||
8244 | return false; | ||||
8245 | |||||
8246 | // If we did not find anything by this name, look for a non-visible | ||||
8247 | // extern "C" declaration with the same name. | ||||
8248 | if (Previous.empty() && | ||||
8249 | checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) | ||||
8250 | Previous.setShadowed(); | ||||
8251 | |||||
8252 | if (!Previous.empty()) { | ||||
8253 | MergeVarDecl(NewVD, Previous); | ||||
8254 | return true; | ||||
8255 | } | ||||
8256 | return false; | ||||
8257 | } | ||||
8258 | |||||
8259 | /// AddOverriddenMethods - See if a method overrides any in the base classes, | ||||
8260 | /// and if so, check that it's a valid override and remember it. | ||||
8261 | bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { | ||||
8262 | llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; | ||||
8263 | |||||
8264 | // Look for methods in base classes that this method might override. | ||||
8265 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, | ||||
8266 | /*DetectVirtual=*/false); | ||||
8267 | auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | ||||
8268 | CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); | ||||
8269 | DeclarationName Name = MD->getDeclName(); | ||||
8270 | |||||
8271 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||
8272 | // We really want to find the base class destructor here. | ||||
8273 | QualType T = Context.getTypeDeclType(BaseRecord); | ||||
8274 | CanQualType CT = Context.getCanonicalType(T); | ||||
8275 | Name = Context.DeclarationNames.getCXXDestructorName(CT); | ||||
8276 | } | ||||
8277 | |||||
8278 | for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { | ||||
8279 | CXXMethodDecl *BaseMD = | ||||
8280 | dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); | ||||
8281 | if (!BaseMD || !BaseMD->isVirtual() || | ||||
8282 | IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, | ||||
8283 | /*ConsiderCudaAttrs=*/true, | ||||
8284 | // C++2a [class.virtual]p2 does not consider requires | ||||
8285 | // clauses when overriding. | ||||
8286 | /*ConsiderRequiresClauses=*/false)) | ||||
8287 | continue; | ||||
8288 | |||||
8289 | if (Overridden.insert(BaseMD).second) { | ||||
8290 | MD->addOverriddenMethod(BaseMD); | ||||
8291 | CheckOverridingFunctionReturnType(MD, BaseMD); | ||||
8292 | CheckOverridingFunctionAttributes(MD, BaseMD); | ||||
8293 | CheckOverridingFunctionExceptionSpec(MD, BaseMD); | ||||
8294 | CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); | ||||
8295 | } | ||||
8296 | |||||
8297 | // A method can only override one function from each base class. We | ||||
8298 | // don't track indirectly overridden methods from bases of bases. | ||||
8299 | return true; | ||||
8300 | } | ||||
8301 | |||||
8302 | return false; | ||||
8303 | }; | ||||
8304 | |||||
8305 | DC->lookupInBases(VisitBase, Paths); | ||||
8306 | return !Overridden.empty(); | ||||
8307 | } | ||||
8308 | |||||
8309 | namespace { | ||||
8310 | // Struct for holding all of the extra arguments needed by | ||||
8311 | // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. | ||||
8312 | struct ActOnFDArgs { | ||||
8313 | Scope *S; | ||||
8314 | Declarator &D; | ||||
8315 | MultiTemplateParamsArg TemplateParamLists; | ||||
8316 | bool AddToScope; | ||||
8317 | }; | ||||
8318 | } // end anonymous namespace | ||||
8319 | |||||
8320 | namespace { | ||||
8321 | |||||
8322 | // Callback to only accept typo corrections that have a non-zero edit distance. | ||||
8323 | // Also only accept corrections that have the same parent decl. | ||||
8324 | class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { | ||||
8325 | public: | ||||
8326 | DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, | ||||
8327 | CXXRecordDecl *Parent) | ||||
8328 | : Context(Context), OriginalFD(TypoFD), | ||||
8329 | ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} | ||||
8330 | |||||
8331 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
8332 | if (candidate.getEditDistance() == 0) | ||||
8333 | return false; | ||||
8334 | |||||
8335 | SmallVector<unsigned, 1> MismatchedParams; | ||||
8336 | for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), | ||||
8337 | CDeclEnd = candidate.end(); | ||||
8338 | CDecl != CDeclEnd; ++CDecl) { | ||||
8339 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | ||||
8340 | |||||
8341 | if (FD && !FD->hasBody() && | ||||
8342 | hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { | ||||
8343 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||
8344 | CXXRecordDecl *Parent = MD->getParent(); | ||||
8345 | if (Parent && Parent->getCanonicalDecl() == ExpectedParent) | ||||
8346 | return true; | ||||
8347 | } else if (!ExpectedParent) { | ||||
8348 | return true; | ||||
8349 | } | ||||
8350 | } | ||||
8351 | } | ||||
8352 | |||||
8353 | return false; | ||||
8354 | } | ||||
8355 | |||||
8356 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
8357 | return std::make_unique<DifferentNameValidatorCCC>(*this); | ||||
8358 | } | ||||
8359 | |||||
8360 | private: | ||||
8361 | ASTContext &Context; | ||||
8362 | FunctionDecl *OriginalFD; | ||||
8363 | CXXRecordDecl *ExpectedParent; | ||||
8364 | }; | ||||
8365 | |||||
8366 | } // end anonymous namespace | ||||
8367 | |||||
8368 | void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { | ||||
8369 | TypoCorrectedFunctionDefinitions.insert(F); | ||||
8370 | } | ||||
8371 | |||||
8372 | /// Generate diagnostics for an invalid function redeclaration. | ||||
8373 | /// | ||||
8374 | /// This routine handles generating the diagnostic messages for an invalid | ||||
8375 | /// function redeclaration, including finding possible similar declarations | ||||
8376 | /// or performing typo correction if there are no previous declarations with | ||||
8377 | /// the same name. | ||||
8378 | /// | ||||
8379 | /// Returns a NamedDecl iff typo correction was performed and substituting in | ||||
8380 | /// the new declaration name does not cause new errors. | ||||
8381 | static NamedDecl *DiagnoseInvalidRedeclaration( | ||||
8382 | Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, | ||||
8383 | ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { | ||||
8384 | DeclarationName Name = NewFD->getDeclName(); | ||||
8385 | DeclContext *NewDC = NewFD->getDeclContext(); | ||||
8386 | SmallVector<unsigned, 1> MismatchedParams; | ||||
8387 | SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; | ||||
8388 | TypoCorrection Correction; | ||||
8389 | bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); | ||||
8390 | unsigned DiagMsg = | ||||
8391 | IsLocalFriend ? diag::err_no_matching_local_friend : | ||||
8392 | NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : | ||||
8393 | diag::err_member_decl_does_not_match; | ||||
8394 | LookupResult Prev(SemaRef, Name, NewFD->getLocation(), | ||||
8395 | IsLocalFriend ? Sema::LookupLocalFriendName | ||||
8396 | : Sema::LookupOrdinaryName, | ||||
8397 | Sema::ForVisibleRedeclaration); | ||||
8398 | |||||
8399 | NewFD->setInvalidDecl(); | ||||
8400 | if (IsLocalFriend) | ||||
8401 | SemaRef.LookupName(Prev, S); | ||||
8402 | else | ||||
8403 | SemaRef.LookupQualifiedName(Prev, NewDC); | ||||
8404 | assert(!Prev.isAmbiguous() &&(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "clang/lib/Sema/SemaDecl.cpp", 8405, __extension__ __PRETTY_FUNCTION__ )) | ||||
8405 | "Cannot have an ambiguity in previous-declaration lookup")(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "clang/lib/Sema/SemaDecl.cpp", 8405, __extension__ __PRETTY_FUNCTION__ )); | ||||
8406 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | ||||
8407 | DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, | ||||
8408 | MD ? MD->getParent() : nullptr); | ||||
8409 | if (!Prev.empty()) { | ||||
8410 | for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); | ||||
8411 | Func != FuncEnd; ++Func) { | ||||
8412 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); | ||||
8413 | if (FD && | ||||
8414 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | ||||
8415 | // Add 1 to the index so that 0 can mean the mismatch didn't | ||||
8416 | // involve a parameter | ||||
8417 | unsigned ParamNum = | ||||
8418 | MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; | ||||
8419 | NearMatches.push_back(std::make_pair(FD, ParamNum)); | ||||
8420 | } | ||||
8421 | } | ||||
8422 | // If the qualified name lookup yielded nothing, try typo correction | ||||
8423 | } else if ((Correction = SemaRef.CorrectTypo( | ||||
8424 | Prev.getLookupNameInfo(), Prev.getLookupKind(), S, | ||||
8425 | &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, | ||||
8426 | IsLocalFriend ? nullptr : NewDC))) { | ||||
8427 | // Set up everything for the call to ActOnFunctionDeclarator | ||||
8428 | ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), | ||||
8429 | ExtraArgs.D.getIdentifierLoc()); | ||||
8430 | Previous.clear(); | ||||
8431 | Previous.setLookupName(Correction.getCorrection()); | ||||
8432 | for (TypoCorrection::decl_iterator CDecl = Correction.begin(), | ||||
8433 | CDeclEnd = Correction.end(); | ||||
8434 | CDecl != CDeclEnd; ++CDecl) { | ||||
8435 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | ||||
8436 | if (FD && !FD->hasBody() && | ||||
8437 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | ||||
8438 | Previous.addDecl(FD); | ||||
8439 | } | ||||
8440 | } | ||||
8441 | bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); | ||||
8442 | |||||
8443 | NamedDecl *Result; | ||||
8444 | // Retry building the function declaration with the new previous | ||||
8445 | // declarations, and with errors suppressed. | ||||
8446 | { | ||||
8447 | // Trap errors. | ||||
8448 | Sema::SFINAETrap Trap(SemaRef); | ||||
8449 | |||||
8450 | // TODO: Refactor ActOnFunctionDeclarator so that we can call only the | ||||
8451 | // pieces need to verify the typo-corrected C++ declaration and hopefully | ||||
8452 | // eliminate the need for the parameter pack ExtraArgs. | ||||
8453 | Result = SemaRef.ActOnFunctionDeclarator( | ||||
8454 | ExtraArgs.S, ExtraArgs.D, | ||||
8455 | Correction.getCorrectionDecl()->getDeclContext(), | ||||
8456 | NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, | ||||
8457 | ExtraArgs.AddToScope); | ||||
8458 | |||||
8459 | if (Trap.hasErrorOccurred()) | ||||
8460 | Result = nullptr; | ||||
8461 | } | ||||
8462 | |||||
8463 | if (Result) { | ||||
8464 | // Determine which correction we picked. | ||||
8465 | Decl *Canonical = Result->getCanonicalDecl(); | ||||
8466 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||
8467 | I != E; ++I) | ||||
8468 | if ((*I)->getCanonicalDecl() == Canonical) | ||||
8469 | Correction.setCorrectionDecl(*I); | ||||
8470 | |||||
8471 | // Let Sema know about the correction. | ||||
8472 | SemaRef.MarkTypoCorrectedFunctionDefinition(Result); | ||||
8473 | SemaRef.diagnoseTypo( | ||||
8474 | Correction, | ||||
8475 | SemaRef.PDiag(IsLocalFriend | ||||
8476 | ? diag::err_no_matching_local_friend_suggest | ||||
8477 | : diag::err_member_decl_does_not_match_suggest) | ||||
8478 | << Name << NewDC << IsDefinition); | ||||
8479 | return Result; | ||||
8480 | } | ||||
8481 | |||||
8482 | // Pretend the typo correction never occurred | ||||
8483 | ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), | ||||
8484 | ExtraArgs.D.getIdentifierLoc()); | ||||
8485 | ExtraArgs.D.setRedeclaration(wasRedeclaration); | ||||
8486 | Previous.clear(); | ||||
8487 | Previous.setLookupName(Name); | ||||
8488 | } | ||||
8489 | |||||
8490 | SemaRef.Diag(NewFD->getLocation(), DiagMsg) | ||||
8491 | << Name << NewDC << IsDefinition << NewFD->getLocation(); | ||||
8492 | |||||
8493 | bool NewFDisConst = false; | ||||
8494 | if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) | ||||
8495 | NewFDisConst = NewMD->isConst(); | ||||
8496 | |||||
8497 | for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator | ||||
8498 | NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); | ||||
8499 | NearMatch != NearMatchEnd; ++NearMatch) { | ||||
8500 | FunctionDecl *FD = NearMatch->first; | ||||
8501 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||
8502 | bool FDisConst = MD && MD->isConst(); | ||||
8503 | bool IsMember = MD || !IsLocalFriend; | ||||
8504 | |||||
8505 | // FIXME: These notes are poorly worded for the local friend case. | ||||
8506 | if (unsigned Idx = NearMatch->second) { | ||||
8507 | ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); | ||||
8508 | SourceLocation Loc = FDParam->getTypeSpecStartLoc(); | ||||
8509 | if (Loc.isInvalid()) Loc = FD->getLocation(); | ||||
8510 | SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match | ||||
8511 | : diag::note_local_decl_close_param_match) | ||||
8512 | << Idx << FDParam->getType() | ||||
8513 | << NewFD->getParamDecl(Idx - 1)->getType(); | ||||
8514 | } else if (FDisConst != NewFDisConst) { | ||||
8515 | SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) | ||||
8516 | << NewFDisConst << FD->getSourceRange().getEnd() | ||||
8517 | << (NewFDisConst | ||||
8518 | ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() | ||||
8519 | .getConstQualifierLoc()) | ||||
8520 | : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() | ||||
8521 | .getRParenLoc() | ||||
8522 | .getLocWithOffset(1), | ||||
8523 | " const")); | ||||
8524 | } else | ||||
8525 | SemaRef.Diag(FD->getLocation(), | ||||
8526 | IsMember ? diag::note_member_def_close_match | ||||
8527 | : diag::note_local_decl_close_match); | ||||
8528 | } | ||||
8529 | return nullptr; | ||||
8530 | } | ||||
8531 | |||||
8532 | static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { | ||||
8533 | switch (D.getDeclSpec().getStorageClassSpec()) { | ||||
8534 | default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "clang/lib/Sema/SemaDecl.cpp" , 8534); | ||||
8535 | case DeclSpec::SCS_auto: | ||||
8536 | case DeclSpec::SCS_register: | ||||
8537 | case DeclSpec::SCS_mutable: | ||||
8538 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
8539 | diag::err_typecheck_sclass_func); | ||||
8540 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||
8541 | D.setInvalidType(); | ||||
8542 | break; | ||||
8543 | case DeclSpec::SCS_unspecified: break; | ||||
8544 | case DeclSpec::SCS_extern: | ||||
8545 | if (D.getDeclSpec().isExternInLinkageSpec()) | ||||
8546 | return SC_None; | ||||
8547 | return SC_Extern; | ||||
8548 | case DeclSpec::SCS_static: { | ||||
8549 | if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { | ||||
8550 | // C99 6.7.1p5: | ||||
8551 | // The declaration of an identifier for a function that has | ||||
8552 | // block scope shall have no explicit storage-class specifier | ||||
8553 | // other than extern | ||||
8554 | // See also (C++ [dcl.stc]p4). | ||||
8555 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
8556 | diag::err_static_block_func); | ||||
8557 | break; | ||||
8558 | } else | ||||
8559 | return SC_Static; | ||||
8560 | } | ||||
8561 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | ||||
8562 | } | ||||
8563 | |||||
8564 | // No explicit storage class has already been returned | ||||
8565 | return SC_None; | ||||
8566 | } | ||||
8567 | |||||
8568 | static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, | ||||
8569 | DeclContext *DC, QualType &R, | ||||
8570 | TypeSourceInfo *TInfo, | ||||
8571 | StorageClass SC, | ||||
8572 | bool &IsVirtualOkay) { | ||||
8573 | DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); | ||||
8574 | DeclarationName Name = NameInfo.getName(); | ||||
8575 | |||||
8576 | FunctionDecl *NewFD = nullptr; | ||||
8577 | bool isInline = D.getDeclSpec().isInlineSpecified(); | ||||
8578 | |||||
8579 | if (!SemaRef.getLangOpts().CPlusPlus) { | ||||
8580 | // Determine whether the function was written with a | ||||
8581 | // prototype. This true when: | ||||
8582 | // - there is a prototype in the declarator, or | ||||
8583 | // - the type R of the function is some kind of typedef or other non- | ||||
8584 | // attributed reference to a type name (which eventually refers to a | ||||
8585 | // function type). | ||||
8586 | bool HasPrototype = | ||||
8587 | (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || | ||||
8588 | (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); | ||||
8589 | |||||
8590 | NewFD = FunctionDecl::Create( | ||||
8591 | SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, | ||||
8592 | SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, | ||||
8593 | ConstexprSpecKind::Unspecified, | ||||
8594 | /*TrailingRequiresClause=*/nullptr); | ||||
8595 | if (D.isInvalidType()) | ||||
8596 | NewFD->setInvalidDecl(); | ||||
8597 | |||||
8598 | return NewFD; | ||||
8599 | } | ||||
8600 | |||||
8601 | ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); | ||||
8602 | |||||
8603 | ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); | ||||
8604 | if (ConstexprKind == ConstexprSpecKind::Constinit) { | ||||
8605 | SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||
8606 | diag::err_constexpr_wrong_decl_kind) | ||||
8607 | << static_cast<int>(ConstexprKind); | ||||
8608 | ConstexprKind = ConstexprSpecKind::Unspecified; | ||||
8609 | D.getMutableDeclSpec().ClearConstexprSpec(); | ||||
8610 | } | ||||
8611 | Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); | ||||
8612 | |||||
8613 | // Check that the return type is not an abstract class type. | ||||
8614 | // For record types, this is done by the AbstractClassUsageDiagnoser once | ||||
8615 | // the class has been completely parsed. | ||||
8616 | if (!DC->isRecord() && | ||||
8617 | SemaRef.RequireNonAbstractType( | ||||
8618 | D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), | ||||
8619 | diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) | ||||
8620 | D.setInvalidType(); | ||||
8621 | |||||
8622 | if (Name.getNameKind() == DeclarationName::CXXConstructorName) { | ||||
8623 | // This is a C++ constructor declaration. | ||||
8624 | assert(DC->isRecord() &&(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context" ) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "clang/lib/Sema/SemaDecl.cpp", 8625, __extension__ __PRETTY_FUNCTION__ )) | ||||
8625 | "Constructors can only be declared in a member context")(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context" ) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "clang/lib/Sema/SemaDecl.cpp", 8625, __extension__ __PRETTY_FUNCTION__ )); | ||||
8626 | |||||
8627 | R = SemaRef.CheckConstructorDeclarator(D, R, SC); | ||||
8628 | return CXXConstructorDecl::Create( | ||||
8629 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||
8630 | TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), | ||||
8631 | isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, | ||||
8632 | InheritedConstructor(), TrailingRequiresClause); | ||||
8633 | |||||
8634 | } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||
8635 | // This is a C++ destructor declaration. | ||||
8636 | if (DC->isRecord()) { | ||||
8637 | R = SemaRef.CheckDestructorDeclarator(D, R, SC); | ||||
8638 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); | ||||
8639 | CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( | ||||
8640 | SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, | ||||
8641 | SemaRef.getCurFPFeatures().isFPConstrained(), isInline, | ||||
8642 | /*isImplicitlyDeclared=*/false, ConstexprKind, | ||||
8643 | TrailingRequiresClause); | ||||
8644 | |||||
8645 | // If the destructor needs an implicit exception specification, set it | ||||
8646 | // now. FIXME: It'd be nice to be able to create the right type to start | ||||
8647 | // with, but the type needs to reference the destructor declaration. | ||||
8648 | if (SemaRef.getLangOpts().CPlusPlus11) | ||||
8649 | SemaRef.AdjustDestructorExceptionSpec(NewDD); | ||||
8650 | |||||
8651 | IsVirtualOkay = true; | ||||
8652 | return NewDD; | ||||
8653 | |||||
8654 | } else { | ||||
8655 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); | ||||
8656 | D.setInvalidType(); | ||||
8657 | |||||
8658 | // Create a FunctionDecl to satisfy the function definition parsing | ||||
8659 | // code path. | ||||
8660 | return FunctionDecl::Create( | ||||
8661 | SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, | ||||
8662 | TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, | ||||
8663 | /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); | ||||
8664 | } | ||||
8665 | |||||
8666 | } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||
8667 | if (!DC->isRecord()) { | ||||
8668 | SemaRef.Diag(D.getIdentifierLoc(), | ||||
8669 | diag::err_conv_function_not_member); | ||||
8670 | return nullptr; | ||||
8671 | } | ||||
8672 | |||||
8673 | SemaRef.CheckConversionDeclarator(D, R, SC); | ||||
8674 | if (D.isInvalidType()) | ||||
8675 | return nullptr; | ||||
8676 | |||||
8677 | IsVirtualOkay = true; | ||||
8678 | return CXXConversionDecl::Create( | ||||
8679 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||
8680 | TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, | ||||
8681 | ExplicitSpecifier, ConstexprKind, SourceLocation(), | ||||
8682 | TrailingRequiresClause); | ||||
8683 | |||||
8684 | } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { | ||||
8685 | if (TrailingRequiresClause) | ||||
8686 | SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), | ||||
8687 | diag::err_trailing_requires_clause_on_deduction_guide) | ||||
8688 | << TrailingRequiresClause->getSourceRange(); | ||||
8689 | SemaRef.CheckDeductionGuideDeclarator(D, R, SC); | ||||
8690 | |||||
8691 | return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | ||||
8692 | ExplicitSpecifier, NameInfo, R, TInfo, | ||||
8693 | D.getEndLoc()); | ||||
8694 | } else if (DC->isRecord()) { | ||||
8695 | // If the name of the function is the same as the name of the record, | ||||
8696 | // then this must be an invalid constructor that has a return type. | ||||
8697 | // (The parser checks for a return type and makes the declarator a | ||||
8698 | // constructor if it has no return type). | ||||
8699 | if (Name.getAsIdentifierInfo() && | ||||
8700 | Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ | ||||
8701 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) | ||||
8702 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | ||||
8703 | << SourceRange(D.getIdentifierLoc()); | ||||
8704 | return nullptr; | ||||
8705 | } | ||||
8706 | |||||
8707 | // This is a C++ method declaration. | ||||
8708 | CXXMethodDecl *Ret = CXXMethodDecl::Create( | ||||
8709 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||
8710 | TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, | ||||
8711 | ConstexprKind, SourceLocation(), TrailingRequiresClause); | ||||
8712 | IsVirtualOkay = !Ret->isStatic(); | ||||
8713 | return Ret; | ||||
8714 | } else { | ||||
8715 | bool isFriend = | ||||
8716 | SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); | ||||
8717 | if (!isFriend
| ||||
8718 | return nullptr; | ||||
8719 | |||||
8720 | // Determine whether the function was written with a | ||||
8721 | // prototype. This true when: | ||||
8722 | // - we're in C++ (where every function has a prototype), | ||||
8723 | return FunctionDecl::Create( | ||||
8724 | SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, | ||||
8725 | SemaRef.getCurFPFeatures().isFPConstrained(), isInline, | ||||
8726 | true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); | ||||
8727 | } | ||||
8728 | } | ||||
8729 | |||||
8730 | enum OpenCLParamType { | ||||
8731 | ValidKernelParam, | ||||
8732 | PtrPtrKernelParam, | ||||
8733 | PtrKernelParam, | ||||
8734 | InvalidAddrSpacePtrKernelParam, | ||||
8735 | InvalidKernelParam, | ||||
8736 | RecordKernelParam | ||||
8737 | }; | ||||
8738 | |||||
8739 | static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { | ||||
8740 | // Size dependent types are just typedefs to normal integer types | ||||
8741 | // (e.g. unsigned long), so we cannot distinguish them from other typedefs to | ||||
8742 | // integers other than by their names. | ||||
8743 | StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; | ||||
8744 | |||||
8745 | // Remove typedefs one by one until we reach a typedef | ||||
8746 | // for a size dependent type. | ||||
8747 | QualType DesugaredTy = Ty; | ||||
8748 | do { | ||||
8749 | ArrayRef<StringRef> Names(SizeTypeNames); | ||||
8750 | auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); | ||||
8751 | if (Names.end() != Match) | ||||
8752 | return true; | ||||
8753 | |||||
8754 | Ty = DesugaredTy; | ||||
8755 | DesugaredTy = Ty.getSingleStepDesugaredType(C); | ||||
8756 | } while (DesugaredTy != Ty); | ||||
8757 | |||||
8758 | return false; | ||||
8759 | } | ||||
8760 | |||||
8761 | static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { | ||||
8762 | if (PT->isDependentType()) | ||||
8763 | return InvalidKernelParam; | ||||
8764 | |||||
8765 | if (PT->isPointerType() || PT->isReferenceType()) { | ||||
8766 | QualType PointeeType = PT->getPointeeType(); | ||||
8767 | if (PointeeType.getAddressSpace() == LangAS::opencl_generic || | ||||
8768 | PointeeType.getAddressSpace() == LangAS::opencl_private || | ||||
8769 | PointeeType.getAddressSpace() == LangAS::Default) | ||||
8770 | return InvalidAddrSpacePtrKernelParam; | ||||
8771 | |||||
8772 | if (PointeeType->isPointerType()) { | ||||
8773 | // This is a pointer to pointer parameter. | ||||
8774 | // Recursively check inner type. | ||||
8775 | OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); | ||||
8776 | if (ParamKind == InvalidAddrSpacePtrKernelParam || | ||||
8777 | ParamKind == InvalidKernelParam) | ||||
8778 | return ParamKind; | ||||
8779 | |||||
8780 | return PtrPtrKernelParam; | ||||
8781 | } | ||||
8782 | |||||
8783 | // C++ for OpenCL v1.0 s2.4: | ||||
8784 | // Moreover the types used in parameters of the kernel functions must be: | ||||
8785 | // Standard layout types for pointer parameters. The same applies to | ||||
8786 | // reference if an implementation supports them in kernel parameters. | ||||
8787 | if (S.getLangOpts().OpenCLCPlusPlus && | ||||
8788 | !S.getOpenCLOptions().isAvailableOption( | ||||
8789 | "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && | ||||
8790 | !PointeeType->isAtomicType() && !PointeeType->isVoidType() && | ||||
8791 | !PointeeType->isStandardLayoutType()) | ||||
8792 | return InvalidKernelParam; | ||||
8793 | |||||
8794 | return PtrKernelParam; | ||||
8795 | } | ||||
8796 | |||||
8797 | // OpenCL v1.2 s6.9.k: | ||||
8798 | // Arguments to kernel functions in a program cannot be declared with the | ||||
8799 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | ||||
8800 | // uintptr_t or a struct and/or union that contain fields declared to be one | ||||
8801 | // of these built-in scalar types. | ||||
8802 | if (isOpenCLSizeDependentType(S.getASTContext(), PT)) | ||||
8803 | return InvalidKernelParam; | ||||
8804 | |||||
8805 | if (PT->isImageType()) | ||||
8806 | return PtrKernelParam; | ||||
8807 | |||||
8808 | if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) | ||||
8809 | return InvalidKernelParam; | ||||
8810 | |||||
8811 | // OpenCL extension spec v1.2 s9.5: | ||||
8812 | // This extension adds support for half scalar and vector types as built-in | ||||
8813 | // types that can be used for arithmetic operations, conversions etc. | ||||
8814 | if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && | ||||
8815 | PT->isHalfType()) | ||||
8816 | return InvalidKernelParam; | ||||
8817 | |||||
8818 | // Look into an array argument to check if it has a forbidden type. | ||||
8819 | if (PT->isArrayType()) { | ||||
8820 | const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); | ||||
8821 | // Call ourself to check an underlying type of an array. Since the | ||||
8822 | // getPointeeOrArrayElementType returns an innermost type which is not an | ||||
8823 | // array, this recursive call only happens once. | ||||
8824 | return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); | ||||
8825 | } | ||||
8826 | |||||
8827 | // C++ for OpenCL v1.0 s2.4: | ||||
8828 | // Moreover the types used in parameters of the kernel functions must be: | ||||
8829 | // Trivial and standard-layout types C++17 [basic.types] (plain old data | ||||
8830 | // types) for parameters passed by value; | ||||
8831 | if (S.getLangOpts().OpenCLCPlusPlus && | ||||
8832 | !S.getOpenCLOptions().isAvailableOption( | ||||
8833 | "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && | ||||
8834 | !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) | ||||
8835 | return InvalidKernelParam; | ||||
8836 | |||||
8837 | if (PT->isRecordType()) | ||||
8838 | return RecordKernelParam; | ||||
8839 | |||||
8840 | return ValidKernelParam; | ||||
8841 | } | ||||
8842 | |||||
8843 | static void checkIsValidOpenCLKernelParameter( | ||||
8844 | Sema &S, | ||||
8845 | Declarator &D, | ||||
8846 | ParmVarDecl *Param, | ||||
8847 | llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { | ||||
8848 | QualType PT = Param->getType(); | ||||
8849 | |||||
8850 | // Cache the valid types we encounter to avoid rechecking structs that are | ||||
8851 | // used again | ||||
8852 | if (ValidTypes.count(PT.getTypePtr())) | ||||
8853 | return; | ||||
8854 | |||||
8855 | switch (getOpenCLKernelParameterType(S, PT)) { | ||||
8856 | case PtrPtrKernelParam: | ||||
8857 | // OpenCL v3.0 s6.11.a: | ||||
8858 | // A kernel function argument cannot be declared as a pointer to a pointer | ||||
8859 | // type. [...] This restriction only applies to OpenCL C 1.2 or below. | ||||
8860 | if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { | ||||
8861 | S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); | ||||
8862 | D.setInvalidType(); | ||||
8863 | return; | ||||
8864 | } | ||||
8865 | |||||
8866 | ValidTypes.insert(PT.getTypePtr()); | ||||
8867 | return; | ||||
8868 | |||||
8869 | case InvalidAddrSpacePtrKernelParam: | ||||
8870 | // OpenCL v1.0 s6.5: | ||||
8871 | // __kernel function arguments declared to be a pointer of a type can point | ||||
8872 | // to one of the following address spaces only : __global, __local or | ||||
8873 | // __constant. | ||||
8874 | S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); | ||||
8875 | D.setInvalidType(); | ||||
8876 | return; | ||||
8877 | |||||
8878 | // OpenCL v1.2 s6.9.k: | ||||
8879 | // Arguments to kernel functions in a program cannot be declared with the | ||||
8880 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | ||||
8881 | // uintptr_t or a struct and/or union that contain fields declared to be | ||||
8882 | // one of these built-in scalar types. | ||||
8883 | |||||
8884 | case InvalidKernelParam: | ||||
8885 | // OpenCL v1.2 s6.8 n: | ||||
8886 | // A kernel function argument cannot be declared | ||||
8887 | // of event_t type. | ||||
8888 | // Do not diagnose half type since it is diagnosed as invalid argument | ||||
8889 | // type for any function elsewhere. | ||||
8890 | if (!PT->isHalfType()) { | ||||
8891 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | ||||
8892 | |||||
8893 | // Explain what typedefs are involved. | ||||
8894 | const TypedefType *Typedef = nullptr; | ||||
8895 | while ((Typedef = PT->getAs<TypedefType>())) { | ||||
8896 | SourceLocation Loc = Typedef->getDecl()->getLocation(); | ||||
8897 | // SourceLocation may be invalid for a built-in type. | ||||
8898 | if (Loc.isValid()) | ||||
8899 | S.Diag(Loc, diag::note_entity_declared_at) << PT; | ||||
8900 | PT = Typedef->desugar(); | ||||
8901 | } | ||||
8902 | } | ||||
8903 | |||||
8904 | D.setInvalidType(); | ||||
8905 | return; | ||||
8906 | |||||
8907 | case PtrKernelParam: | ||||
8908 | case ValidKernelParam: | ||||
8909 | ValidTypes.insert(PT.getTypePtr()); | ||||
8910 | return; | ||||
8911 | |||||
8912 | case RecordKernelParam: | ||||
8913 | break; | ||||
8914 | } | ||||
8915 | |||||
8916 | // Track nested structs we will inspect | ||||
8917 | SmallVector<const Decl *, 4> VisitStack; | ||||
8918 | |||||
8919 | // Track where we are in the nested structs. Items will migrate from | ||||
8920 | // VisitStack to HistoryStack as we do the DFS for bad field. | ||||
8921 | SmallVector<const FieldDecl *, 4> HistoryStack; | ||||
8922 | HistoryStack.push_back(nullptr); | ||||
8923 | |||||
8924 | // At this point we already handled everything except of a RecordType or | ||||
8925 | // an ArrayType of a RecordType. | ||||
8926 | assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(static_cast <bool> ((PT->isArrayType() || PT->isRecordType ()) && "Unexpected type.") ? void (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\"" , "clang/lib/Sema/SemaDecl.cpp", 8926, __extension__ __PRETTY_FUNCTION__ )); | ||||
8927 | const RecordType *RecTy = | ||||
8928 | PT->getPointeeOrArrayElementType()->getAs<RecordType>(); | ||||
8929 | const RecordDecl *OrigRecDecl = RecTy->getDecl(); | ||||
8930 | |||||
8931 | VisitStack.push_back(RecTy->getDecl()); | ||||
8932 | assert(VisitStack.back() && "First decl null?")(static_cast <bool> (VisitStack.back() && "First decl null?" ) ? void (0) : __assert_fail ("VisitStack.back() && \"First decl null?\"" , "clang/lib/Sema/SemaDecl.cpp", 8932, __extension__ __PRETTY_FUNCTION__ )); | ||||
8933 | |||||
8934 | do { | ||||
8935 | const Decl *Next = VisitStack.pop_back_val(); | ||||
8936 | if (!Next) { | ||||
8937 | assert(!HistoryStack.empty())(static_cast <bool> (!HistoryStack.empty()) ? void (0) : __assert_fail ("!HistoryStack.empty()", "clang/lib/Sema/SemaDecl.cpp" , 8937, __extension__ __PRETTY_FUNCTION__)); | ||||
8938 | // Found a marker, we have gone up a level | ||||
8939 | if (const FieldDecl *Hist = HistoryStack.pop_back_val()) | ||||
8940 | ValidTypes.insert(Hist->getType().getTypePtr()); | ||||
8941 | |||||
8942 | continue; | ||||
8943 | } | ||||
8944 | |||||
8945 | // Adds everything except the original parameter declaration (which is not a | ||||
8946 | // field itself) to the history stack. | ||||
8947 | const RecordDecl *RD; | ||||
8948 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { | ||||
8949 | HistoryStack.push_back(Field); | ||||
8950 | |||||
8951 | QualType FieldTy = Field->getType(); | ||||
8952 | // Other field types (known to be valid or invalid) are handled while we | ||||
8953 | // walk around RecordDecl::fields(). | ||||
8954 | assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(static_cast <bool> ((FieldTy->isArrayType() || FieldTy ->isRecordType()) && "Unexpected type.") ? void (0 ) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "clang/lib/Sema/SemaDecl.cpp", 8955, __extension__ __PRETTY_FUNCTION__ )) | ||||
8955 | "Unexpected type.")(static_cast <bool> ((FieldTy->isArrayType() || FieldTy ->isRecordType()) && "Unexpected type.") ? void (0 ) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "clang/lib/Sema/SemaDecl.cpp", 8955, __extension__ __PRETTY_FUNCTION__ )); | ||||
8956 | const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); | ||||
8957 | |||||
8958 | RD = FieldRecTy->castAs<RecordType>()->getDecl(); | ||||
8959 | } else { | ||||
8960 | RD = cast<RecordDecl>(Next); | ||||
8961 | } | ||||
8962 | |||||
8963 | // Add a null marker so we know when we've gone back up a level | ||||
8964 | VisitStack.push_back(nullptr); | ||||
8965 | |||||
8966 | for (const auto *FD : RD->fields()) { | ||||
8967 | QualType QT = FD->getType(); | ||||
8968 | |||||
8969 | if (ValidTypes.count(QT.getTypePtr())) | ||||
8970 | continue; | ||||
8971 | |||||
8972 | OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); | ||||
8973 | if (ParamType == ValidKernelParam) | ||||
8974 | continue; | ||||
8975 | |||||
8976 | if (ParamType == RecordKernelParam) { | ||||
8977 | VisitStack.push_back(FD); | ||||
8978 | continue; | ||||
8979 | } | ||||
8980 | |||||
8981 | // OpenCL v1.2 s6.9.p: | ||||
8982 | // Arguments to kernel functions that are declared to be a struct or union | ||||
8983 | // do not allow OpenCL objects to be passed as elements of the struct or | ||||
8984 | // union. | ||||
8985 | if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || | ||||
8986 | ParamType == InvalidAddrSpacePtrKernelParam) { | ||||
8987 | S.Diag(Param->getLocation(), | ||||
8988 | diag::err_record_with_pointers_kernel_param) | ||||
8989 | << PT->isUnionType() | ||||
8990 | << PT; | ||||
8991 | } else { | ||||
8992 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | ||||
8993 | } | ||||
8994 | |||||
8995 | S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) | ||||
8996 | << OrigRecDecl->getDeclName(); | ||||
8997 | |||||
8998 | // We have an error, now let's go back up through history and show where | ||||
8999 | // the offending field came from | ||||
9000 | for (ArrayRef<const FieldDecl *>::const_iterator | ||||
9001 | I = HistoryStack.begin() + 1, | ||||
9002 | E = HistoryStack.end(); | ||||
9003 | I != E; ++I) { | ||||
9004 | const FieldDecl *OuterField = *I; | ||||
9005 | S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) | ||||
9006 | << OuterField->getType(); | ||||
9007 | } | ||||
9008 | |||||
9009 | S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) | ||||
9010 | << QT->isPointerType() | ||||
9011 | << QT; | ||||
9012 | D.setInvalidType(); | ||||
9013 | return; | ||||
9014 | } | ||||
9015 | } while (!VisitStack.empty()); | ||||
9016 | } | ||||
9017 | |||||
9018 | /// Find the DeclContext in which a tag is implicitly declared if we see an | ||||
9019 | /// elaborated type specifier in the specified context, and lookup finds | ||||
9020 | /// nothing. | ||||
9021 | static DeclContext *getTagInjectionContext(DeclContext *DC) { | ||||
9022 | while (!DC->isFileContext() && !DC->isFunctionOrMethod()) | ||||
9023 | DC = DC->getParent(); | ||||
9024 | return DC; | ||||
9025 | } | ||||
9026 | |||||
9027 | /// Find the Scope in which a tag is implicitly declared if we see an | ||||
9028 | /// elaborated type specifier in the specified context, and lookup finds | ||||
9029 | /// nothing. | ||||
9030 | static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { | ||||
9031 | while (S->isClassScope() || | ||||
9032 | (LangOpts.CPlusPlus && | ||||
9033 | S->isFunctionPrototypeScope()) || | ||||
9034 | ((S->getFlags() & Scope::DeclScope) == 0) || | ||||
9035 | (S->getEntity() && S->getEntity()->isTransparentContext())) | ||||
9036 | S = S->getParent(); | ||||
9037 | return S; | ||||
9038 | } | ||||
9039 | |||||
9040 | NamedDecl* | ||||
9041 | Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, | ||||
9042 | TypeSourceInfo *TInfo, LookupResult &Previous, | ||||
9043 | MultiTemplateParamsArg TemplateParamListsRef, | ||||
9044 | bool &AddToScope) { | ||||
9045 | QualType R = TInfo->getType(); | ||||
9046 | |||||
9047 | assert(R->isFunctionType())(static_cast <bool> (R->isFunctionType()) ? void (0) : __assert_fail ("R->isFunctionType()", "clang/lib/Sema/SemaDecl.cpp" , 9047, __extension__ __PRETTY_FUNCTION__)); | ||||
| |||||
9048 | if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) | ||||
9049 | Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); | ||||
9050 | |||||
9051 | SmallVector<TemplateParameterList *, 4> TemplateParamLists; | ||||
9052 | for (TemplateParameterList *TPL : TemplateParamListsRef) | ||||
9053 | TemplateParamLists.push_back(TPL); | ||||
9054 | if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { | ||||
9055 | if (!TemplateParamLists.empty() && | ||||
9056 | Invented->getDepth() == TemplateParamLists.back()->getDepth()) | ||||
9057 | TemplateParamLists.back() = Invented; | ||||
9058 | else | ||||
9059 | TemplateParamLists.push_back(Invented); | ||||
9060 | } | ||||
9061 | |||||
9062 | // TODO: consider using NameInfo for diagnostic. | ||||
9063 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||
9064 | DeclarationName Name = NameInfo.getName(); | ||||
9065 | StorageClass SC = getFunctionStorageClass(*this, D); | ||||
9066 | |||||
9067 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | ||||
9068 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
9069 | diag::err_invalid_thread) | ||||
9070 | << DeclSpec::getSpecifierName(TSCS); | ||||
9071 | |||||
9072 | if (D.isFirstDeclarationOfMember()) | ||||
9073 | adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), | ||||
9074 | D.getIdentifierLoc()); | ||||
9075 | |||||
9076 | bool isFriend = false; | ||||
9077 | FunctionTemplateDecl *FunctionTemplate = nullptr; | ||||
9078 | bool isMemberSpecialization = false; | ||||
9079 | bool isFunctionTemplateSpecialization = false; | ||||
9080 | |||||
9081 | bool isDependentClassScopeExplicitSpecialization = false; | ||||
9082 | bool HasExplicitTemplateArgs = false; | ||||
9083 | TemplateArgumentListInfo TemplateArgs; | ||||
9084 | |||||
9085 | bool isVirtualOkay = false; | ||||
9086 | |||||
9087 | DeclContext *OriginalDC = DC; | ||||
9088 | bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); | ||||
9089 | |||||
9090 | FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, | ||||
9091 | isVirtualOkay); | ||||
9092 | if (!NewFD) return nullptr; | ||||
9093 | |||||
9094 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) | ||||
9095 | NewFD->setTopLevelDeclInObjCContainer(); | ||||
9096 | |||||
9097 | // Set the lexical context. If this is a function-scope declaration, or has a | ||||
9098 | // C++ scope specifier, or is the object of a friend declaration, the lexical | ||||
9099 | // context will be different from the semantic context. | ||||
9100 | NewFD->setLexicalDeclContext(CurContext); | ||||
9101 | |||||
9102 | if (IsLocalExternDecl
| ||||
9103 | NewFD->setLocalExternDecl(); | ||||
9104 | |||||
9105 | if (getLangOpts().CPlusPlus
| ||||
9106 | bool isInline = D.getDeclSpec().isInlineSpecified(); | ||||
9107 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | ||||
9108 | bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); | ||||
9109 | isFriend = D.getDeclSpec().isFriendSpecified(); | ||||
9110 | if (isFriend && !isInline && D.isFunctionDefinition()) { | ||||
9111 | // C++ [class.friend]p5 | ||||
9112 | // A function can be defined in a friend declaration of a | ||||
9113 | // class . . . . Such a function is implicitly inline. | ||||
9114 | NewFD->setImplicitlyInline(); | ||||
9115 | } | ||||
9116 | |||||
9117 | // If this is a method defined in an __interface, and is not a constructor | ||||
9118 | // or an overloaded operator, then set the pure flag (isVirtual will already | ||||
9119 | // return true). | ||||
9120 | if (const CXXRecordDecl *Parent = | ||||
9121 | dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { | ||||
9122 | if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) | ||||
9123 | NewFD->setPure(true); | ||||
9124 | |||||
9125 | // C++ [class.union]p2 | ||||
9126 | // A union can have member functions, but not virtual functions. | ||||
9127 | if (isVirtual && Parent->isUnion()) { | ||||
9128 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); | ||||
9129 | NewFD->setInvalidDecl(); | ||||
9130 | } | ||||
9131 | } | ||||
9132 | |||||
9133 | SetNestedNameSpecifier(*this, NewFD, D); | ||||
9134 | isMemberSpecialization = false; | ||||
9135 | isFunctionTemplateSpecialization = false; | ||||
9136 | if (D.isInvalidType()) | ||||
9137 | NewFD->setInvalidDecl(); | ||||
9138 | |||||
9139 | // Match up the template parameter lists with the scope specifier, then | ||||
9140 | // determine whether we have a template or a template specialization. | ||||
9141 | bool Invalid = false; | ||||
9142 | TemplateParameterList *TemplateParams = | ||||
9143 | MatchTemplateParametersToScopeSpecifier( | ||||
9144 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | ||||
9145 | D.getCXXScopeSpec(), | ||||
9146 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | ||||
9147 | ? D.getName().TemplateId | ||||
9148 | : nullptr, | ||||
9149 | TemplateParamLists, isFriend, isMemberSpecialization, | ||||
9150 | Invalid); | ||||
9151 | if (TemplateParams) { | ||||
9152 | // Check that we can declare a template here. | ||||
9153 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||
9154 | NewFD->setInvalidDecl(); | ||||
9155 | |||||
9156 | if (TemplateParams->size() > 0) { | ||||
9157 | // This is a function template | ||||
9158 | |||||
9159 | // A destructor cannot be a template. | ||||
9160 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||
9161 | Diag(NewFD->getLocation(), diag::err_destructor_template); | ||||
9162 | NewFD->setInvalidDecl(); | ||||
9163 | } | ||||
9164 | |||||
9165 | // If we're adding a template to a dependent context, we may need to | ||||
9166 | // rebuilding some of the types used within the template parameter list, | ||||
9167 | // now that we know what the current instantiation is. | ||||
9168 | if (DC->isDependentContext()) { | ||||
9169 | ContextRAII SavedContext(*this, DC); | ||||
9170 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) | ||||
9171 | Invalid = true; | ||||
9172 | } | ||||
9173 | |||||
9174 | FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, | ||||
9175 | NewFD->getLocation(), | ||||
9176 | Name, TemplateParams, | ||||
9177 | NewFD); | ||||
9178 | FunctionTemplate->setLexicalDeclContext(CurContext); | ||||
9179 | NewFD->setDescribedFunctionTemplate(FunctionTemplate); | ||||
9180 | |||||
9181 | // For source fidelity, store the other template param lists. | ||||
9182 | if (TemplateParamLists.size() > 1) { | ||||
9183 | NewFD->setTemplateParameterListsInfo(Context, | ||||
9184 | ArrayRef<TemplateParameterList *>(TemplateParamLists) | ||||
9185 | .drop_back(1)); | ||||
9186 | } | ||||
9187 | } else { | ||||
9188 | // This is a function template specialization. | ||||
9189 | isFunctionTemplateSpecialization = true; | ||||
9190 | // For source fidelity, store all the template param lists. | ||||
9191 | if (TemplateParamLists.size() > 0) | ||||
9192 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | ||||
9193 | |||||
9194 | // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". | ||||
9195 | if (isFriend) { | ||||
9196 | // We want to remove the "template<>", found here. | ||||
9197 | SourceRange RemoveRange = TemplateParams->getSourceRange(); | ||||
9198 | |||||
9199 | // If we remove the template<> and the name is not a | ||||
9200 | // template-id, we're actually silently creating a problem: | ||||
9201 | // the friend declaration will refer to an untemplated decl, | ||||
9202 | // and clearly the user wants a template specialization. So | ||||
9203 | // we need to insert '<>' after the name. | ||||
9204 | SourceLocation InsertLoc; | ||||
9205 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | ||||
9206 | InsertLoc = D.getName().getSourceRange().getEnd(); | ||||
9207 | InsertLoc = getLocForEndOfToken(InsertLoc); | ||||
9208 | } | ||||
9209 | |||||
9210 | Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) | ||||
9211 | << Name << RemoveRange | ||||
9212 | << FixItHint::CreateRemoval(RemoveRange) | ||||
9213 | << FixItHint::CreateInsertion(InsertLoc, "<>"); | ||||
9214 | Invalid = true; | ||||
9215 | } | ||||
9216 | } | ||||
9217 | } else { | ||||
9218 | // Check that we can declare a template here. | ||||
9219 | if (!TemplateParamLists.empty() && isMemberSpecialization && | ||||
9220 | CheckTemplateDeclScope(S, TemplateParamLists.back())) | ||||
9221 | NewFD->setInvalidDecl(); | ||||
9222 | |||||
9223 | // All template param lists were matched against the scope specifier: | ||||
9224 | // this is NOT (an explicit specialization of) a template. | ||||
9225 | if (TemplateParamLists.size() > 0) | ||||
9226 | // For source fidelity, store all the template param lists. | ||||
9227 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | ||||
9228 | } | ||||
9229 | |||||
9230 | if (Invalid) { | ||||
9231 | NewFD->setInvalidDecl(); | ||||
9232 | if (FunctionTemplate) | ||||
9233 | FunctionTemplate->setInvalidDecl(); | ||||
9234 | } | ||||
9235 | |||||
9236 | // C++ [dcl.fct.spec]p5: | ||||
9237 | // The virtual specifier shall only be used in declarations of | ||||
9238 | // nonstatic class member functions that appear within a | ||||
9239 | // member-specification of a class declaration; see 10.3. | ||||
9240 | // | ||||
9241 | if (isVirtual && !NewFD->isInvalidDecl()) { | ||||
9242 | if (!isVirtualOkay) { | ||||
9243 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||
9244 | diag::err_virtual_non_function); | ||||
9245 | } else if (!CurContext->isRecord()) { | ||||
9246 | // 'virtual' was specified outside of the class. | ||||
9247 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||
9248 | diag::err_virtual_out_of_class) | ||||
9249 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | ||||
9250 | } else if (NewFD->getDescribedFunctionTemplate()) { | ||||
9251 | // C++ [temp.mem]p3: | ||||
9252 | // A member function template shall not be virtual. | ||||
9253 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||
9254 | diag::err_virtual_member_function_template) | ||||
9255 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | ||||
9256 | } else { | ||||
9257 | // Okay: Add virtual to the method. | ||||
9258 | NewFD->setVirtualAsWritten(true); | ||||
9259 | } | ||||
9260 | |||||
9261 | if (getLangOpts().CPlusPlus14 && | ||||
9262 | NewFD->getReturnType()->isUndeducedType()) | ||||
9263 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); | ||||
9264 | } | ||||
9265 | |||||
9266 | if (getLangOpts().CPlusPlus14 && | ||||
9267 | (NewFD->isDependentContext() || | ||||
9268 | (isFriend && CurContext->isDependentContext())) && | ||||
9269 | NewFD->getReturnType()->isUndeducedType()) { | ||||
9270 | // If the function template is referenced directly (for instance, as a | ||||
9271 | // member of the current instantiation), pretend it has a dependent type. | ||||
9272 | // This is not really justified by the standard, but is the only sane | ||||
9273 | // thing to do. | ||||
9274 | // FIXME: For a friend function, we have not marked the function as being | ||||
9275 | // a friend yet, so 'isDependentContext' on the FD doesn't work. | ||||
9276 | const FunctionProtoType *FPT = | ||||
9277 | NewFD->getType()->castAs<FunctionProtoType>(); | ||||
9278 | QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); | ||||
9279 | NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), | ||||
9280 | FPT->getExtProtoInfo())); | ||||
9281 | } | ||||
9282 | |||||
9283 | // C++ [dcl.fct.spec]p3: | ||||
9284 | // The inline specifier shall not appear on a block scope function | ||||
9285 | // declaration. | ||||
9286 | if (isInline && !NewFD->isInvalidDecl()) { | ||||
9287 | if (CurContext->isFunctionOrMethod()) { | ||||
9288 | // 'inline' is not allowed on block scope function declaration. | ||||
9289 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||
9290 | diag::err_inline_declaration_block_scope) << Name | ||||
9291 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | ||||
9292 | } | ||||
9293 | } | ||||
9294 | |||||
9295 | // C++ [dcl.fct.spec]p6: | ||||
9296 | // The explicit specifier shall be used only in the declaration of a | ||||
9297 | // constructor or conversion function within its class definition; | ||||
9298 | // see 12.3.1 and 12.3.2. | ||||
9299 | if (hasExplicit && !NewFD->isInvalidDecl() && | ||||
9300 | !isa<CXXDeductionGuideDecl>(NewFD)) { | ||||
9301 | if (!CurContext->isRecord()) { | ||||
9302 | // 'explicit' was specified outside of the class. | ||||
9303 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | ||||
9304 | diag::err_explicit_out_of_class) | ||||
9305 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | ||||
9306 | } else if (!isa<CXXConstructorDecl>(NewFD) && | ||||
9307 | !isa<CXXConversionDecl>(NewFD)) { | ||||
9308 | // 'explicit' was specified on a function that wasn't a constructor | ||||
9309 | // or conversion function. | ||||
9310 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | ||||
9311 | diag::err_explicit_non_ctor_or_conv_function) | ||||
9312 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | ||||
9313 | } | ||||
9314 | } | ||||
9315 | |||||
9316 | ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); | ||||
9317 | if (ConstexprKind != ConstexprSpecKind::Unspecified) { | ||||
9318 | // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors | ||||
9319 | // are implicitly inline. | ||||
9320 | NewFD->setImplicitlyInline(); | ||||
9321 | |||||
9322 | // C++11 [dcl.constexpr]p3: functions declared constexpr are required to | ||||
9323 | // be either constructors or to return a literal type. Therefore, | ||||
9324 | // destructors cannot be declared constexpr. | ||||
9325 | if (isa<CXXDestructorDecl>(NewFD) && | ||||
9326 | (!getLangOpts().CPlusPlus20 || | ||||
9327 | ConstexprKind == ConstexprSpecKind::Consteval)) { | ||||
9328 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) | ||||
9329 | << static_cast<int>(ConstexprKind); | ||||
9330 | NewFD->setConstexprKind(getLangOpts().CPlusPlus20 | ||||
9331 | ? ConstexprSpecKind::Unspecified | ||||
9332 | : ConstexprSpecKind::Constexpr); | ||||
9333 | } | ||||
9334 | // C++20 [dcl.constexpr]p2: An allocation function, or a | ||||
9335 | // deallocation function shall not be declared with the consteval | ||||
9336 | // specifier. | ||||
9337 | if (ConstexprKind == ConstexprSpecKind::Consteval && | ||||
9338 | (NewFD->getOverloadedOperator() == OO_New || | ||||
9339 | NewFD->getOverloadedOperator() == OO_Array_New || | ||||
9340 | NewFD->getOverloadedOperator() == OO_Delete || | ||||
9341 | NewFD->getOverloadedOperator() == OO_Array_Delete)) { | ||||
9342 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||
9343 | diag::err_invalid_consteval_decl_kind) | ||||
9344 | << NewFD; | ||||
9345 | NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); | ||||
9346 | } | ||||
9347 | } | ||||
9348 | |||||
9349 | // If __module_private__ was specified, mark the function accordingly. | ||||
9350 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||
9351 | if (isFunctionTemplateSpecialization) { | ||||
9352 | SourceLocation ModulePrivateLoc | ||||
9353 | = D.getDeclSpec().getModulePrivateSpecLoc(); | ||||
9354 | Diag(ModulePrivateLoc, diag::err_module_private_specialization) | ||||
9355 | << 0 | ||||
9356 | << FixItHint::CreateRemoval(ModulePrivateLoc); | ||||
9357 | } else { | ||||
9358 | NewFD->setModulePrivate(); | ||||
9359 | if (FunctionTemplate) | ||||
9360 | FunctionTemplate->setModulePrivate(); | ||||
9361 | } | ||||
9362 | } | ||||
9363 | |||||
9364 | if (isFriend) { | ||||
9365 | if (FunctionTemplate) { | ||||
9366 | FunctionTemplate->setObjectOfFriendDecl(); | ||||
9367 | FunctionTemplate->setAccess(AS_public); | ||||
9368 | } | ||||
9369 | NewFD->setObjectOfFriendDecl(); | ||||
9370 | NewFD->setAccess(AS_public); | ||||
9371 | } | ||||
9372 | |||||
9373 | // If a function is defined as defaulted or deleted, mark it as such now. | ||||
9374 | // We'll do the relevant checks on defaulted / deleted functions later. | ||||
9375 | switch (D.getFunctionDefinitionKind()) { | ||||
9376 | case FunctionDefinitionKind::Declaration: | ||||
9377 | case FunctionDefinitionKind::Definition: | ||||
9378 | break; | ||||
9379 | |||||
9380 | case FunctionDefinitionKind::Defaulted: | ||||
9381 | NewFD->setDefaulted(); | ||||
9382 | break; | ||||
9383 | |||||
9384 | case FunctionDefinitionKind::Deleted: | ||||
9385 | NewFD->setDeletedAsWritten(); | ||||
9386 | break; | ||||
9387 | } | ||||
9388 | |||||
9389 | if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && | ||||
9390 | D.isFunctionDefinition()) { | ||||
9391 | // C++ [class.mfct]p2: | ||||
9392 | // A member function may be defined (8.4) in its class definition, in | ||||
9393 | // which case it is an inline member function (7.1.2) | ||||
9394 | NewFD->setImplicitlyInline(); | ||||
9395 | } | ||||
9396 | |||||
9397 | if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && | ||||
9398 | !CurContext->isRecord()) { | ||||
9399 | // C++ [class.static]p1: | ||||
9400 | // A data or function member of a class may be declared static | ||||
9401 | // in a class definition, in which case it is a static member of | ||||
9402 | // the class. | ||||
9403 | |||||
9404 | // Complain about the 'static' specifier if it's on an out-of-line | ||||
9405 | // member function definition. | ||||
9406 | |||||
9407 | // MSVC permits the use of a 'static' storage specifier on an out-of-line | ||||
9408 | // member function template declaration and class member template | ||||
9409 | // declaration (MSVC versions before 2015), warn about this. | ||||
9410 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
9411 | ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | ||||
9412 | cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || | ||||
9413 | (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) | ||||
9414 | ? diag::ext_static_out_of_line : diag::err_static_out_of_line) | ||||
9415 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||
9416 | } | ||||
9417 | |||||
9418 | // C++11 [except.spec]p15: | ||||
9419 | // A deallocation function with no exception-specification is treated | ||||
9420 | // as if it were specified with noexcept(true). | ||||
9421 | const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); | ||||
9422 | if ((Name.getCXXOverloadedOperator() == OO_Delete || | ||||
9423 | Name.getCXXOverloadedOperator() == OO_Array_Delete) && | ||||
9424 | getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) | ||||
9425 | NewFD->setType(Context.getFunctionType( | ||||
9426 | FPT->getReturnType(), FPT->getParamTypes(), | ||||
9427 | FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); | ||||
9428 | } | ||||
9429 | |||||
9430 | // Filter out previous declarations that don't match the scope. | ||||
9431 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), | ||||
9432 | D.getCXXScopeSpec().isNotEmpty() || | ||||
9433 | isMemberSpecialization || | ||||
9434 | isFunctionTemplateSpecialization); | ||||
9435 | |||||
9436 | // Handle GNU asm-label extension (encoded as an attribute). | ||||
9437 | if (Expr *E = (Expr*) D.getAsmLabel()) { | ||||
9438 | // The parser guarantees this is a string. | ||||
9439 | StringLiteral *SE = cast<StringLiteral>(E); | ||||
9440 | NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), | ||||
9441 | /*IsLiteralLabel=*/true, | ||||
9442 | SE->getStrTokenLoc(0))); | ||||
9443 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | ||||
9444 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | ||||
9445 | ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); | ||||
9446 | if (I != ExtnameUndeclaredIdentifiers.end()) { | ||||
9447 | if (isDeclExternC(NewFD)) { | ||||
9448 | NewFD->addAttr(I->second); | ||||
9449 | ExtnameUndeclaredIdentifiers.erase(I); | ||||
9450 | } else | ||||
9451 | Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) | ||||
9452 | << /*Variable*/0 << NewFD; | ||||
9453 | } | ||||
9454 | } | ||||
9455 | |||||
9456 | // Copy the parameter declarations from the declarator D to the function | ||||
9457 | // declaration NewFD, if they are available. First scavenge them into Params. | ||||
9458 | SmallVector<ParmVarDecl*, 16> Params; | ||||
9459 | unsigned FTIIdx; | ||||
9460 | if (D.isFunctionDeclarator(FTIIdx)) { | ||||
9461 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; | ||||
9462 | |||||
9463 | // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs | ||||
9464 | // function that takes no arguments, not a function that takes a | ||||
9465 | // single void argument. | ||||
9466 | // We let through "const void" here because Sema::GetTypeForDeclarator | ||||
9467 | // already checks for that case. | ||||
9468 | if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { | ||||
9469 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | ||||
9470 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | ||||
9471 | assert(Param->getDeclContext() != NewFD && "Was set before ?")(static_cast <bool> (Param->getDeclContext() != NewFD && "Was set before ?") ? void (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\"" , "clang/lib/Sema/SemaDecl.cpp", 9471, __extension__ __PRETTY_FUNCTION__ )); | ||||
9472 | Param->setDeclContext(NewFD); | ||||
9473 | Params.push_back(Param); | ||||
9474 | |||||
9475 | if (Param->isInvalidDecl()) | ||||
9476 | NewFD->setInvalidDecl(); | ||||
9477 | } | ||||
9478 | } | ||||
9479 | |||||
9480 | if (!getLangOpts().CPlusPlus) { | ||||
9481 | // In C, find all the tag declarations from the prototype and move them | ||||
9482 | // into the function DeclContext. Remove them from the surrounding tag | ||||
9483 | // injection context of the function, which is typically but not always | ||||
9484 | // the TU. | ||||
9485 | DeclContext *PrototypeTagContext = | ||||
9486 | getTagInjectionContext(NewFD->getLexicalDeclContext()); | ||||
9487 | for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { | ||||
9488 | auto *TD = dyn_cast<TagDecl>(NonParmDecl); | ||||
9489 | |||||
9490 | // We don't want to reparent enumerators. Look at their parent enum | ||||
9491 | // instead. | ||||
9492 | if (!TD) { | ||||
9493 | if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) | ||||
9494 | TD = cast<EnumDecl>(ECD->getDeclContext()); | ||||
9495 | } | ||||
9496 | if (!TD) | ||||
9497 | continue; | ||||
9498 | DeclContext *TagDC = TD->getLexicalDeclContext(); | ||||
9499 | if (!TagDC->containsDecl(TD)) | ||||
9500 | continue; | ||||
9501 | TagDC->removeDecl(TD); | ||||
9502 | TD->setDeclContext(NewFD); | ||||
9503 | NewFD->addDecl(TD); | ||||
9504 | |||||
9505 | // Preserve the lexical DeclContext if it is not the surrounding tag | ||||
9506 | // injection context of the FD. In this example, the semantic context of | ||||
9507 | // E will be f and the lexical context will be S, while both the | ||||
9508 | // semantic and lexical contexts of S will be f: | ||||
9509 | // void f(struct S { enum E { a } f; } s); | ||||
9510 | if (TagDC != PrototypeTagContext) | ||||
9511 | TD->setLexicalDeclContext(TagDC); | ||||
9512 | } | ||||
9513 | } | ||||
9514 | } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { | ||||
9515 | // When we're declaring a function with a typedef, typeof, etc as in the | ||||
9516 | // following example, we'll need to synthesize (unnamed) | ||||
9517 | // parameters for use in the declaration. | ||||
9518 | // | ||||
9519 | // @code | ||||
9520 | // typedef void fn(int); | ||||
9521 | // fn f; | ||||
9522 | // @endcode | ||||
9523 | |||||
9524 | // Synthesize a parameter for each argument type. | ||||
9525 | for (const auto &AI : FT->param_types()) { | ||||
9526 | ParmVarDecl *Param = | ||||
9527 | BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); | ||||
9528 | Param->setScopeInfo(0, Params.size()); | ||||
9529 | Params.push_back(Param); | ||||
9530 | } | ||||
9531 | } else { | ||||
9532 | assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&(static_cast <bool> (R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn" ) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "clang/lib/Sema/SemaDecl.cpp", 9533, __extension__ __PRETTY_FUNCTION__ )) | ||||
9533 | "Should not need args for typedef of non-prototype fn")(static_cast <bool> (R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn" ) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "clang/lib/Sema/SemaDecl.cpp", 9533, __extension__ __PRETTY_FUNCTION__ )); | ||||
9534 | } | ||||
9535 | |||||
9536 | // Finally, we know we have the right number of parameters, install them. | ||||
9537 | NewFD->setParams(Params); | ||||
9538 | |||||
9539 | if (D.getDeclSpec().isNoreturnSpecified()) | ||||
9540 | NewFD->addAttr(C11NoReturnAttr::Create(Context, | ||||
9541 | D.getDeclSpec().getNoreturnSpecLoc(), | ||||
9542 | AttributeCommonInfo::AS_Keyword)); | ||||
9543 | |||||
9544 | // Functions returning a variably modified type violate C99 6.7.5.2p2 | ||||
9545 | // because all functions have linkage. | ||||
9546 | if (!NewFD->isInvalidDecl() && | ||||
9547 | NewFD->getReturnType()->isVariablyModifiedType()) { | ||||
9548 | Diag(NewFD->getLocation(), diag::err_vm_func_decl); | ||||
9549 | NewFD->setInvalidDecl(); | ||||
9550 | } | ||||
9551 | |||||
9552 | // Apply an implicit SectionAttr if '#pragma clang section text' is active | ||||
9553 | if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && | ||||
9554 | !NewFD->hasAttr<SectionAttr>()) | ||||
9555 | NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( | ||||
9556 | Context, PragmaClangTextSection.SectionName, | ||||
9557 | PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); | ||||
9558 | |||||
9559 | // Apply an implicit SectionAttr if #pragma code_seg is active. | ||||
9560 | if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && | ||||
9561 | !NewFD->hasAttr<SectionAttr>()) { | ||||
9562 | NewFD->addAttr(SectionAttr::CreateImplicit( | ||||
9563 | Context, CodeSegStack.CurrentValue->getString(), | ||||
9564 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||
9565 | SectionAttr::Declspec_allocate)); | ||||
9566 | if (UnifySection(CodeSegStack.CurrentValue->getString(), | ||||
9567 | ASTContext::PSF_Implicit | ASTContext::PSF_Execute | | ||||
9568 | ASTContext::PSF_Read, | ||||
9569 | NewFD)) | ||||
9570 | NewFD->dropAttr<SectionAttr>(); | ||||
9571 | } | ||||
9572 | |||||
9573 | // Apply an implicit CodeSegAttr from class declspec or | ||||
9574 | // apply an implicit SectionAttr from #pragma code_seg if active. | ||||
9575 | if (!NewFD->hasAttr<CodeSegAttr>()) { | ||||
9576 | if (Attr *SAttr
| ||||
9577 | D.isFunctionDefinition())) { | ||||
9578 | NewFD->addAttr(SAttr); | ||||
9579 | } | ||||
9580 | } | ||||
9581 | |||||
9582 | // Handle attributes. | ||||
9583 | ProcessDeclAttributes(S, NewFD, D); | ||||
9584 | |||||
9585 | if (getLangOpts().OpenCL) { | ||||
9586 | // OpenCL v1.1 s6.5: Using an address space qualifier in a function return | ||||
9587 | // type declaration will generate a compilation error. | ||||
9588 | LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); | ||||
9589 | if (AddressSpace != LangAS::Default) { | ||||
9590 | Diag(NewFD->getLocation(), | ||||
9591 | diag::err_opencl_return_value_with_address_space); | ||||
9592 | NewFD->setInvalidDecl(); | ||||
9593 | } | ||||
9594 | } | ||||
9595 | |||||
9596 | if (!getLangOpts().CPlusPlus) { | ||||
9597 | // Perform semantic checking on the function declaration. | ||||
9598 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | ||||
9599 | CheckMain(NewFD, D.getDeclSpec()); | ||||
9600 | |||||
9601 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | ||||
9602 | CheckMSVCRTEntryPoint(NewFD); | ||||
9603 | |||||
9604 | if (!NewFD->isInvalidDecl()) | ||||
9605 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | ||||
9606 | isMemberSpecialization)); | ||||
9607 | else if (!Previous.empty()) | ||||
9608 | // Recover gracefully from an invalid redeclaration. | ||||
9609 | D.setRedeclaration(true); | ||||
9610 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 9612, __extension__ __PRETTY_FUNCTION__ )) | ||||
9611 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 9612, __extension__ __PRETTY_FUNCTION__ )) | ||||
9612 | "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 9612, __extension__ __PRETTY_FUNCTION__ )); | ||||
9613 | |||||
9614 | // Diagnose no-prototype function declarations with calling conventions that | ||||
9615 | // don't support variadic calls. Only do this in C and do it after merging | ||||
9616 | // possibly prototyped redeclarations. | ||||
9617 | const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); | ||||
9618 | if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { | ||||
9619 | CallingConv CC = FT->getExtInfo().getCC(); | ||||
9620 | if (!supportsVariadicCall(CC)) { | ||||
9621 | // Windows system headers sometimes accidentally use stdcall without | ||||
9622 | // (void) parameters, so we relax this to a warning. | ||||
9623 | int DiagID = | ||||
9624 | CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; | ||||
9625 | Diag(NewFD->getLocation(), DiagID) | ||||
9626 | << FunctionType::getNameForCallConv(CC); | ||||
9627 | } | ||||
9628 | } | ||||
9629 | |||||
9630 | if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||
9631 | NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
9632 | checkNonTrivialCUnion(NewFD->getReturnType(), | ||||
9633 | NewFD->getReturnTypeSourceRange().getBegin(), | ||||
9634 | NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); | ||||
9635 | } else { | ||||
9636 | // C++11 [replacement.functions]p3: | ||||
9637 | // The program's definitions shall not be specified as inline. | ||||
9638 | // | ||||
9639 | // N.B. We diagnose declarations instead of definitions per LWG issue 2340. | ||||
9640 | // | ||||
9641 | // Suppress the diagnostic if the function is __attribute__((used)), since | ||||
9642 | // that forces an external definition to be emitted. | ||||
9643 | if (D.getDeclSpec().isInlineSpecified() && | ||||
9644 | NewFD->isReplaceableGlobalAllocationFunction() && | ||||
9645 | !NewFD->hasAttr<UsedAttr>()) | ||||
9646 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||
9647 | diag::ext_operator_new_delete_declared_inline) | ||||
9648 | << NewFD->getDeclName(); | ||||
9649 | |||||
9650 | // If the declarator is a template-id, translate the parser's template | ||||
9651 | // argument list into our AST format. | ||||
9652 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||
9653 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; | ||||
9654 | TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); | ||||
9655 | TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); | ||||
9656 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | ||||
9657 | TemplateId->NumArgs); | ||||
9658 | translateTemplateArguments(TemplateArgsPtr, | ||||
9659 | TemplateArgs); | ||||
9660 | |||||
9661 | HasExplicitTemplateArgs = true; | ||||
9662 | |||||
9663 | if (NewFD->isInvalidDecl()) { | ||||
9664 | HasExplicitTemplateArgs = false; | ||||
9665 | } else if (FunctionTemplate) { | ||||
9666 | // Function template with explicit template arguments. | ||||
9667 | Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) | ||||
9668 | << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); | ||||
9669 | |||||
9670 | HasExplicitTemplateArgs = false; | ||||
9671 | } else { | ||||
9672 | assert((isFunctionTemplateSpecialization ||(static_cast <bool> ((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 9674, __extension__ __PRETTY_FUNCTION__ )) | ||||
9673 | D.getDeclSpec().isFriendSpecified()) &&(static_cast <bool> ((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 9674, __extension__ __PRETTY_FUNCTION__ )) | ||||
9674 | "should have a 'template<>' for this decl")(static_cast <bool> ((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 9674, __extension__ __PRETTY_FUNCTION__ )); | ||||
9675 | // "friend void foo<>(int);" is an implicit specialization decl. | ||||
9676 | isFunctionTemplateSpecialization = true; | ||||
9677 | } | ||||
9678 | } else if (isFriend
| ||||
9679 | // This combination is only possible in a recovery case; the user | ||||
9680 | // wrote something like: | ||||
9681 | // template <> friend void foo(int); | ||||
9682 | // which we're recovering from as if the user had written: | ||||
9683 | // friend void foo<>(int); | ||||
9684 | // Go ahead and fake up a template id. | ||||
9685 | HasExplicitTemplateArgs = true; | ||||
9686 | TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); | ||||
9687 | TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); | ||||
9688 | } | ||||
9689 | |||||
9690 | // We do not add HD attributes to specializations here because | ||||
9691 | // they may have different constexpr-ness compared to their | ||||
9692 | // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, | ||||
9693 | // may end up with different effective targets. Instead, a | ||||
9694 | // specialization inherits its target attributes from its template | ||||
9695 | // in the CheckFunctionTemplateSpecialization() call below. | ||||
9696 | if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) | ||||
9697 | maybeAddCUDAHostDeviceAttrs(NewFD, Previous); | ||||
9698 | |||||
9699 | // If it's a friend (and only if it's a friend), it's possible | ||||
9700 | // that either the specialized function type or the specialized | ||||
9701 | // template is dependent, and therefore matching will fail. In | ||||
9702 | // this case, don't check the specialization yet. | ||||
9703 | if (isFunctionTemplateSpecialization
| ||||
9704 | (NewFD->getType()->isDependentType() || DC->isDependentContext() || | ||||
9705 | TemplateSpecializationType::anyInstantiationDependentTemplateArguments( | ||||
9706 | TemplateArgs.arguments()))) { | ||||
9707 | assert(HasExplicitTemplateArgs &&(static_cast <bool> (HasExplicitTemplateArgs && "friend function specialization without template args") ? void (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "clang/lib/Sema/SemaDecl.cpp", 9708, __extension__ __PRETTY_FUNCTION__ )) | ||||
9708 | "friend function specialization without template args")(static_cast <bool> (HasExplicitTemplateArgs && "friend function specialization without template args") ? void (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "clang/lib/Sema/SemaDecl.cpp", 9708, __extension__ __PRETTY_FUNCTION__ )); | ||||
9709 | if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, | ||||
9710 | Previous)) | ||||
9711 | NewFD->setInvalidDecl(); | ||||
9712 | } else if (isFunctionTemplateSpecialization
| ||||
9713 | if (CurContext->isDependentContext() && CurContext->isRecord() | ||||
9714 | && !isFriend) { | ||||
9715 | isDependentClassScopeExplicitSpecialization = true; | ||||
9716 | } else if (!NewFD->isInvalidDecl() && | ||||
9717 | CheckFunctionTemplateSpecialization( | ||||
9718 | NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), | ||||
9719 | Previous)) | ||||
9720 | NewFD->setInvalidDecl(); | ||||
9721 | |||||
9722 | // C++ [dcl.stc]p1: | ||||
9723 | // A storage-class-specifier shall not be specified in an explicit | ||||
9724 | // specialization (14.7.3) | ||||
9725 | FunctionTemplateSpecializationInfo *Info = | ||||
9726 | NewFD->getTemplateSpecializationInfo(); | ||||
9727 | if (Info && SC != SC_None) { | ||||
9728 | if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) | ||||
9729 | Diag(NewFD->getLocation(), | ||||
9730 | diag::err_explicit_specialization_inconsistent_storage_class) | ||||
9731 | << SC | ||||
9732 | << FixItHint::CreateRemoval( | ||||
9733 | D.getDeclSpec().getStorageClassSpecLoc()); | ||||
9734 | |||||
9735 | else | ||||
9736 | Diag(NewFD->getLocation(), | ||||
9737 | diag::ext_explicit_specialization_storage_class) | ||||
9738 | << FixItHint::CreateRemoval( | ||||
9739 | D.getDeclSpec().getStorageClassSpecLoc()); | ||||
9740 | } | ||||
9741 | } else if (isMemberSpecialization
| ||||
9742 | if (CheckMemberSpecialization(NewFD, Previous)) | ||||
9743 | NewFD->setInvalidDecl(); | ||||
9744 | } | ||||
9745 | |||||
9746 | // Perform semantic checking on the function declaration. | ||||
9747 | if (!isDependentClassScopeExplicitSpecialization
| ||||
9748 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | ||||
9749 | CheckMain(NewFD, D.getDeclSpec()); | ||||
9750 | |||||
9751 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | ||||
9752 | CheckMSVCRTEntryPoint(NewFD); | ||||
9753 | |||||
9754 | if (!NewFD->isInvalidDecl()) | ||||
9755 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | ||||
9756 | isMemberSpecialization)); | ||||
9757 | else if (!Previous.empty()) | ||||
9758 | // Recover gracefully from an invalid redeclaration. | ||||
9759 | D.setRedeclaration(true); | ||||
9760 | } | ||||
9761 | |||||
9762 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 9764, __extension__ __PRETTY_FUNCTION__ )) | ||||
9763 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 9764, __extension__ __PRETTY_FUNCTION__ )) | ||||
9764 | "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 9764, __extension__ __PRETTY_FUNCTION__ )); | ||||
9765 | |||||
9766 | NamedDecl *PrincipalDecl = (FunctionTemplate
|
77.1 | 'FunctionTemplate' is null |
78.1 | 'isFriend' is false |
78.1 | 'isFriend' is false |
78.2 | 'FunctionTemplate' is null |
78.2 | 'FunctionTemplate' is null |
88 | Called C++ object pointer is null |
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 ObjCContainerDecl; |
56 | class ObjCMethodDecl; |
57 | struct PrintingPolicy; |
58 | class RecordDecl; |
59 | class SourceManager; |
60 | class Stmt; |
61 | class StoredDeclsMap; |
62 | class TemplateDecl; |
63 | class TemplateParameterList; |
64 | class TranslationUnitDecl; |
65 | class UsingDirectiveDecl; |
66 | |
67 | /// Captures the result of checking the availability of a |
68 | /// declaration. |
69 | enum AvailabilityResult { |
70 | AR_Available = 0, |
71 | AR_NotYetIntroduced, |
72 | AR_Deprecated, |
73 | AR_Unavailable |
74 | }; |
75 | |
76 | /// Decl - This represents one declaration (or definition), e.g. a variable, |
77 | /// typedef, function, struct, etc. |
78 | /// |
79 | /// Note: There are objects tacked on before the *beginning* of Decl |
80 | /// (and its subclasses) in its Decl::operator new(). Proper alignment |
81 | /// of all subclasses (not requiring more than the alignment of Decl) is |
82 | /// asserted in DeclBase.cpp. |
83 | class alignas(8) Decl { |
84 | public: |
85 | /// Lists the kind of concrete classes of Decl. |
86 | enum Kind { |
87 | #define DECL(DERIVED, BASE) DERIVED, |
88 | #define ABSTRACT_DECL(DECL) |
89 | #define DECL_RANGE(BASE, START, END) \ |
90 | first##BASE = START, last##BASE = END, |
91 | #define LAST_DECL_RANGE(BASE, START, END) \ |
92 | first##BASE = START, last##BASE = END |
93 | #include "clang/AST/DeclNodes.inc" |
94 | }; |
95 | |
96 | /// A placeholder type used to construct an empty shell of a |
97 | /// decl-derived type that will be filled in later (e.g., by some |
98 | /// deserialization method). |
99 | struct EmptyShell {}; |
100 | |
101 | /// IdentifierNamespace - The different namespaces in which |
102 | /// declarations may appear. According to C99 6.2.3, there are |
103 | /// four namespaces, labels, tags, members and ordinary |
104 | /// identifiers. C++ describes lookup completely differently: |
105 | /// certain lookups merely "ignore" certain kinds of declarations, |
106 | /// usually based on whether the declaration is of a type, etc. |
107 | /// |
108 | /// These are meant as bitmasks, so that searches in |
109 | /// C++ can look into the "tag" namespace during ordinary lookup. |
110 | /// |
111 | /// Decl currently provides 15 bits of IDNS bits. |
112 | enum IdentifierNamespace { |
113 | /// Labels, declared with 'x:' and referenced with 'goto x'. |
114 | IDNS_Label = 0x0001, |
115 | |
116 | /// Tags, declared with 'struct foo;' and referenced with |
117 | /// 'struct foo'. All tags are also types. This is what |
118 | /// elaborated-type-specifiers look for in C. |
119 | /// This also contains names that conflict with tags in the |
120 | /// same scope but that are otherwise ordinary names (non-type |
121 | /// template parameters and indirect field declarations). |
122 | IDNS_Tag = 0x0002, |
123 | |
124 | /// Types, declared with 'struct foo', typedefs, etc. |
125 | /// This is what elaborated-type-specifiers look for in C++, |
126 | /// but note that it's ill-formed to find a non-tag. |
127 | IDNS_Type = 0x0004, |
128 | |
129 | /// Members, declared with object declarations within tag |
130 | /// definitions. In C, these can only be found by "qualified" |
131 | /// lookup in member expressions. In C++, they're found by |
132 | /// normal lookup. |
133 | IDNS_Member = 0x0008, |
134 | |
135 | /// Namespaces, declared with 'namespace foo {}'. |
136 | /// Lookup for nested-name-specifiers find these. |
137 | IDNS_Namespace = 0x0010, |
138 | |
139 | /// Ordinary names. In C, everything that's not a label, tag, |
140 | /// member, or function-local extern ends up here. |
141 | IDNS_Ordinary = 0x0020, |
142 | |
143 | /// Objective C \@protocol. |
144 | IDNS_ObjCProtocol = 0x0040, |
145 | |
146 | /// This declaration is a friend function. A friend function |
147 | /// declaration is always in this namespace but may also be in |
148 | /// IDNS_Ordinary if it was previously declared. |
149 | IDNS_OrdinaryFriend = 0x0080, |
150 | |
151 | /// This declaration is a friend class. A friend class |
152 | /// declaration is always in this namespace but may also be in |
153 | /// IDNS_Tag|IDNS_Type if it was previously declared. |
154 | IDNS_TagFriend = 0x0100, |
155 | |
156 | /// This declaration is a using declaration. A using declaration |
157 | /// *introduces* a number of other declarations into the current |
158 | /// scope, and those declarations use the IDNS of their targets, |
159 | /// but the actual using declarations go in this namespace. |
160 | IDNS_Using = 0x0200, |
161 | |
162 | /// This declaration is a C++ operator declared in a non-class |
163 | /// context. All such operators are also in IDNS_Ordinary. |
164 | /// C++ lexical operator lookup looks for these. |
165 | IDNS_NonMemberOperator = 0x0400, |
166 | |
167 | /// This declaration is a function-local extern declaration of a |
168 | /// variable or function. This may also be IDNS_Ordinary if it |
169 | /// has been declared outside any function. These act mostly like |
170 | /// invisible friend declarations, but are also visible to unqualified |
171 | /// lookup within the scope of the declaring function. |
172 | IDNS_LocalExtern = 0x0800, |
173 | |
174 | /// This declaration is an OpenMP user defined reduction construction. |
175 | IDNS_OMPReduction = 0x1000, |
176 | |
177 | /// This declaration is an OpenMP user defined mapper. |
178 | IDNS_OMPMapper = 0x2000, |
179 | }; |
180 | |
181 | /// ObjCDeclQualifier - 'Qualifiers' written next to the return and |
182 | /// parameter types in method declarations. Other than remembering |
183 | /// them and mangling them into the method's signature string, these |
184 | /// are ignored by the compiler; they are consumed by certain |
185 | /// remote-messaging frameworks. |
186 | /// |
187 | /// in, inout, and out are mutually exclusive and apply only to |
188 | /// method parameters. bycopy and byref are mutually exclusive and |
189 | /// apply only to method parameters (?). oneway applies only to |
190 | /// results. All of these expect their corresponding parameter to |
191 | /// have a particular type. None of this is currently enforced by |
192 | /// clang. |
193 | /// |
194 | /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier. |
195 | enum ObjCDeclQualifier { |
196 | OBJC_TQ_None = 0x0, |
197 | OBJC_TQ_In = 0x1, |
198 | OBJC_TQ_Inout = 0x2, |
199 | OBJC_TQ_Out = 0x4, |
200 | OBJC_TQ_Bycopy = 0x8, |
201 | OBJC_TQ_Byref = 0x10, |
202 | OBJC_TQ_Oneway = 0x20, |
203 | |
204 | /// The nullability qualifier is set when the nullability of the |
205 | /// result or parameter was expressed via a context-sensitive |
206 | /// keyword. |
207 | OBJC_TQ_CSNullability = 0x40 |
208 | }; |
209 | |
210 | /// The kind of ownership a declaration has, for visibility purposes. |
211 | /// This enumeration is designed such that higher values represent higher |
212 | /// levels of name hiding. |
213 | enum class ModuleOwnershipKind : unsigned { |
214 | /// This declaration is not owned by a module. |
215 | Unowned, |
216 | |
217 | /// This declaration has an owning module, but is globally visible |
218 | /// (typically because its owning module is visible and we know that |
219 | /// modules cannot later become hidden in this compilation). |
220 | /// After serialization and deserialization, this will be converted |
221 | /// to VisibleWhenImported. |
222 | Visible, |
223 | |
224 | /// This declaration has an owning module, and is visible when that |
225 | /// module is imported. |
226 | VisibleWhenImported, |
227 | |
228 | /// This declaration has an owning module, but is only visible to |
229 | /// lookups that occur within that module. |
230 | ModulePrivate |
231 | }; |
232 | |
233 | protected: |
234 | /// The next declaration within the same lexical |
235 | /// DeclContext. These pointers form the linked list that is |
236 | /// traversed via DeclContext's decls_begin()/decls_end(). |
237 | /// |
238 | /// The extra two bits are used for the ModuleOwnershipKind. |
239 | llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits; |
240 | |
241 | private: |
242 | friend class DeclContext; |
243 | |
244 | struct MultipleDC { |
245 | DeclContext *SemanticDC; |
246 | DeclContext *LexicalDC; |
247 | }; |
248 | |
249 | /// DeclCtx - Holds either a DeclContext* or a MultipleDC*. |
250 | /// For declarations that don't contain C++ scope specifiers, it contains |
251 | /// the DeclContext where the Decl was declared. |
252 | /// For declarations with C++ scope specifiers, it contains a MultipleDC* |
253 | /// with the context where it semantically belongs (SemanticDC) and the |
254 | /// context where it was lexically declared (LexicalDC). |
255 | /// e.g.: |
256 | /// |
257 | /// namespace A { |
258 | /// void f(); // SemanticDC == LexicalDC == 'namespace A' |
259 | /// } |
260 | /// void A::f(); // SemanticDC == namespace 'A' |
261 | /// // LexicalDC == global namespace |
262 | llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx; |
263 | |
264 | bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); } |
265 | bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); } |
266 | |
267 | MultipleDC *getMultipleDC() const { |
268 | return DeclCtx.get<MultipleDC*>(); |
269 | } |
270 | |
271 | DeclContext *getSemanticDC() const { |
272 | return DeclCtx.get<DeclContext*>(); |
273 | } |
274 | |
275 | /// Loc - The location of this decl. |
276 | SourceLocation Loc; |
277 | |
278 | /// DeclKind - This indicates which class this is. |
279 | unsigned DeclKind : 7; |
280 | |
281 | /// InvalidDecl - This indicates a semantic error occurred. |
282 | unsigned InvalidDecl : 1; |
283 | |
284 | /// HasAttrs - This indicates whether the decl has attributes or not. |
285 | unsigned HasAttrs : 1; |
286 | |
287 | /// Implicit - Whether this declaration was implicitly generated by |
288 | /// the implementation rather than explicitly written by the user. |
289 | unsigned Implicit : 1; |
290 | |
291 | /// Whether this declaration was "used", meaning that a definition is |
292 | /// required. |
293 | unsigned Used : 1; |
294 | |
295 | /// Whether this declaration was "referenced". |
296 | /// The difference with 'Used' is whether the reference appears in a |
297 | /// evaluated context or not, e.g. functions used in uninstantiated templates |
298 | /// are regarded as "referenced" but not "used". |
299 | unsigned Referenced : 1; |
300 | |
301 | /// Whether this declaration is a top-level declaration (function, |
302 | /// global variable, etc.) that is lexically inside an objc container |
303 | /// definition. |
304 | unsigned TopLevelDeclInObjCContainer : 1; |
305 | |
306 | /// Whether statistic collection is enabled. |
307 | static bool StatisticsEnabled; |
308 | |
309 | protected: |
310 | friend class ASTDeclReader; |
311 | friend class ASTDeclWriter; |
312 | friend class ASTNodeImporter; |
313 | friend class ASTReader; |
314 | friend class CXXClassMemberWrapper; |
315 | friend class LinkageComputer; |
316 | template<typename decl_type> friend class Redeclarable; |
317 | |
318 | /// Access - Used by C++ decls for the access specifier. |
319 | // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum |
320 | unsigned Access : 2; |
321 | |
322 | /// Whether this declaration was loaded from an AST file. |
323 | unsigned FromASTFile : 1; |
324 | |
325 | /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in. |
326 | unsigned IdentifierNamespace : 14; |
327 | |
328 | /// If 0, we have not computed the linkage of this declaration. |
329 | /// Otherwise, it is the linkage + 1. |
330 | mutable unsigned CacheValidAndLinkage : 3; |
331 | |
332 | /// Allocate memory for a deserialized declaration. |
333 | /// |
334 | /// This routine must be used to allocate memory for any declaration that is |
335 | /// deserialized from a module file. |
336 | /// |
337 | /// \param Size The size of the allocated object. |
338 | /// \param Ctx The context in which we will allocate memory. |
339 | /// \param ID The global ID of the deserialized declaration. |
340 | /// \param Extra The amount of extra space to allocate after the object. |
341 | void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID, |
342 | std::size_t Extra = 0); |
343 | |
344 | /// Allocate memory for a non-deserialized declaration. |
345 | void *operator new(std::size_t Size, const ASTContext &Ctx, |
346 | DeclContext *Parent, std::size_t Extra = 0); |
347 | |
348 | private: |
349 | bool AccessDeclContextCheck() const; |
350 | |
351 | /// Get the module ownership kind to use for a local lexical child of \p DC, |
352 | /// which may be either a local or (rarely) an imported declaration. |
353 | static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) { |
354 | if (DC) { |
355 | auto *D = cast<Decl>(DC); |
356 | auto MOK = D->getModuleOwnershipKind(); |
357 | if (MOK != ModuleOwnershipKind::Unowned && |
358 | (!D->isFromASTFile() || D->hasLocalOwningModuleStorage())) |
359 | return MOK; |
360 | // If D is not local and we have no local module storage, then we don't |
361 | // need to track module ownership at all. |
362 | } |
363 | return ModuleOwnershipKind::Unowned; |
364 | } |
365 | |
366 | public: |
367 | Decl() = delete; |
368 | Decl(const Decl&) = delete; |
369 | Decl(Decl &&) = delete; |
370 | Decl &operator=(const Decl&) = delete; |
371 | Decl &operator=(Decl&&) = delete; |
372 | |
373 | protected: |
374 | Decl(Kind DK, DeclContext *DC, SourceLocation L) |
375 | : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)), |
376 | DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false), |
377 | Implicit(false), Used(false), Referenced(false), |
378 | TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0), |
379 | IdentifierNamespace(getIdentifierNamespaceForKind(DK)), |
380 | CacheValidAndLinkage(0) { |
381 | if (StatisticsEnabled) add(DK); |
382 | } |
383 | |
384 | Decl(Kind DK, EmptyShell Empty) |
385 | : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false), |
386 | Used(false), Referenced(false), TopLevelDeclInObjCContainer(false), |
387 | Access(AS_none), FromASTFile(0), |
388 | IdentifierNamespace(getIdentifierNamespaceForKind(DK)), |
389 | CacheValidAndLinkage(0) { |
390 | if (StatisticsEnabled) add(DK); |
391 | } |
392 | |
393 | virtual ~Decl(); |
394 | |
395 | /// Update a potentially out-of-date declaration. |
396 | void updateOutOfDate(IdentifierInfo &II) const; |
397 | |
398 | Linkage getCachedLinkage() const { |
399 | return Linkage(CacheValidAndLinkage - 1); |
400 | } |
401 | |
402 | void setCachedLinkage(Linkage L) const { |
403 | CacheValidAndLinkage = L + 1; |
404 | } |
405 | |
406 | bool hasCachedLinkage() const { |
407 | return CacheValidAndLinkage; |
408 | } |
409 | |
410 | public: |
411 | /// Source range that this declaration covers. |
412 | virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { |
413 | return SourceRange(getLocation(), getLocation()); |
414 | } |
415 | |
416 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
417 | return getSourceRange().getBegin(); |
418 | } |
419 | |
420 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
421 | return getSourceRange().getEnd(); |
422 | } |
423 | |
424 | SourceLocation getLocation() const { return Loc; } |
425 | void setLocation(SourceLocation L) { Loc = L; } |
426 | |
427 | Kind getKind() const { return static_cast<Kind>(DeclKind); } |
428 | const char *getDeclKindName() const; |
429 | |
430 | Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); } |
431 | const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();} |
432 | |
433 | DeclContext *getDeclContext() { |
434 | if (isInSemaDC()) |
435 | return getSemanticDC(); |
436 | return getMultipleDC()->SemanticDC; |
437 | } |
438 | const DeclContext *getDeclContext() const { |
439 | return const_cast<Decl*>(this)->getDeclContext(); |
440 | } |
441 | |
442 | /// Find the innermost non-closure ancestor of this declaration, |
443 | /// walking up through blocks, lambdas, etc. If that ancestor is |
444 | /// not a code context (!isFunctionOrMethod()), returns null. |
445 | /// |
446 | /// A declaration may be its own non-closure context. |
447 | Decl *getNonClosureContext(); |
448 | const Decl *getNonClosureContext() const { |
449 | return const_cast<Decl*>(this)->getNonClosureContext(); |
450 | } |
451 | |
452 | TranslationUnitDecl *getTranslationUnitDecl(); |
453 | const TranslationUnitDecl *getTranslationUnitDecl() const { |
454 | return const_cast<Decl*>(this)->getTranslationUnitDecl(); |
455 | } |
456 | |
457 | bool isInAnonymousNamespace() const; |
458 | |
459 | bool isInStdNamespace() const; |
460 | |
461 | ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__)); |
462 | |
463 | /// Helper to get the language options from the ASTContext. |
464 | /// Defined out of line to avoid depending on ASTContext.h. |
465 | const LangOptions &getLangOpts() const LLVM_READONLY__attribute__((__pure__)); |
466 | |
467 | void setAccess(AccessSpecifier AS) { |
468 | Access = AS; |
469 | assert(AccessDeclContextCheck())(static_cast <bool> (AccessDeclContextCheck()) ? void ( 0) : __assert_fail ("AccessDeclContextCheck()", "clang/include/clang/AST/DeclBase.h" , 469, __extension__ __PRETTY_FUNCTION__)); |
470 | } |
471 | |
472 | AccessSpecifier getAccess() const { |
473 | assert(AccessDeclContextCheck())(static_cast <bool> (AccessDeclContextCheck()) ? void ( 0) : __assert_fail ("AccessDeclContextCheck()", "clang/include/clang/AST/DeclBase.h" , 473, __extension__ __PRETTY_FUNCTION__)); |
474 | return AccessSpecifier(Access); |
475 | } |
476 | |
477 | /// Retrieve the access specifier for this declaration, even though |
478 | /// it may not yet have been properly set. |
479 | AccessSpecifier getAccessUnsafe() const { |
480 | return AccessSpecifier(Access); |
481 | } |
482 | |
483 | bool hasAttrs() const { return HasAttrs; } |
484 | |
485 | void setAttrs(const AttrVec& Attrs) { |
486 | return setAttrsImpl(Attrs, getASTContext()); |
487 | } |
488 | |
489 | AttrVec &getAttrs() { |
490 | return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs()); |
491 | } |
492 | |
493 | const AttrVec &getAttrs() const; |
494 | void dropAttrs(); |
495 | void addAttr(Attr *A); |
496 | |
497 | using attr_iterator = AttrVec::const_iterator; |
498 | using attr_range = llvm::iterator_range<attr_iterator>; |
499 | |
500 | attr_range attrs() const { |
501 | return attr_range(attr_begin(), attr_end()); |
502 | } |
503 | |
504 | attr_iterator attr_begin() const { |
505 | return hasAttrs() ? getAttrs().begin() : nullptr; |
506 | } |
507 | attr_iterator attr_end() const { |
508 | return hasAttrs() ? getAttrs().end() : nullptr; |
509 | } |
510 | |
511 | template <typename T> |
512 | void dropAttr() { |
513 | if (!HasAttrs) return; |
514 | |
515 | AttrVec &Vec = getAttrs(); |
516 | llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); }); |
517 | |
518 | if (Vec.empty()) |
519 | HasAttrs = false; |
520 | } |
521 | |
522 | template <typename T> |
523 | llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const { |
524 | return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>()); |
525 | } |
526 | |
527 | template <typename T> |
528 | specific_attr_iterator<T> specific_attr_begin() const { |
529 | return specific_attr_iterator<T>(attr_begin()); |
530 | } |
531 | |
532 | template <typename T> |
533 | specific_attr_iterator<T> specific_attr_end() const { |
534 | return specific_attr_iterator<T>(attr_end()); |
535 | } |
536 | |
537 | template<typename T> T *getAttr() const { |
538 | return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr; |
539 | } |
540 | |
541 | template<typename T> bool hasAttr() const { |
542 | return hasAttrs() && hasSpecificAttr<T>(getAttrs()); |
543 | } |
544 | |
545 | /// getMaxAlignment - return the maximum alignment specified by attributes |
546 | /// on this decl, 0 if there are none. |
547 | unsigned getMaxAlignment() const; |
548 | |
549 | /// setInvalidDecl - Indicates the Decl had a semantic error. This |
550 | /// allows for graceful error recovery. |
551 | void setInvalidDecl(bool Invalid = true); |
552 | bool isInvalidDecl() const { return (bool) InvalidDecl; } |
553 | |
554 | /// isImplicit - Indicates whether the declaration was implicitly |
555 | /// generated by the implementation. If false, this declaration |
556 | /// was written explicitly in the source code. |
557 | bool isImplicit() const { return Implicit; } |
558 | void setImplicit(bool I = true) { Implicit = I; } |
559 | |
560 | /// Whether *any* (re-)declaration of the entity was used, meaning that |
561 | /// a definition is required. |
562 | /// |
563 | /// \param CheckUsedAttr When true, also consider the "used" attribute |
564 | /// (in addition to the "used" bit set by \c setUsed()) when determining |
565 | /// whether the function is used. |
566 | bool isUsed(bool CheckUsedAttr = true) const; |
567 | |
568 | /// Set whether the declaration is used, in the sense of odr-use. |
569 | /// |
570 | /// This should only be used immediately after creating a declaration. |
571 | /// It intentionally doesn't notify any listeners. |
572 | void setIsUsed() { getCanonicalDecl()->Used = true; } |
573 | |
574 | /// Mark the declaration used, in the sense of odr-use. |
575 | /// |
576 | /// This notifies any mutation listeners in addition to setting a bit |
577 | /// indicating the declaration is used. |
578 | void markUsed(ASTContext &C); |
579 | |
580 | /// Whether any declaration of this entity was referenced. |
581 | bool isReferenced() const; |
582 | |
583 | /// Whether this declaration was referenced. This should not be relied |
584 | /// upon for anything other than debugging. |
585 | bool isThisDeclarationReferenced() const { return Referenced; } |
586 | |
587 | void setReferenced(bool R = true) { Referenced = R; } |
588 | |
589 | /// Whether this declaration is a top-level declaration (function, |
590 | /// global variable, etc.) that is lexically inside an objc container |
591 | /// definition. |
592 | bool isTopLevelDeclInObjCContainer() const { |
593 | return TopLevelDeclInObjCContainer; |
594 | } |
595 | |
596 | void setTopLevelDeclInObjCContainer(bool V = true) { |
597 | TopLevelDeclInObjCContainer = V; |
598 | } |
599 | |
600 | /// Looks on this and related declarations for an applicable |
601 | /// external source symbol attribute. |
602 | ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const; |
603 | |
604 | /// Whether this declaration was marked as being private to the |
605 | /// module in which it was defined. |
606 | bool isModulePrivate() const { |
607 | return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate; |
608 | } |
609 | |
610 | /// Return true if this declaration has an attribute which acts as |
611 | /// definition of the entity, such as 'alias' or 'ifunc'. |
612 | bool hasDefiningAttr() const; |
613 | |
614 | /// Return this declaration's defining attribute if it has one. |
615 | const Attr *getDefiningAttr() const; |
616 | |
617 | protected: |
618 | /// Specify that this declaration was marked as being private |
619 | /// to the module in which it was defined. |
620 | void setModulePrivate() { |
621 | // The module-private specifier has no effect on unowned declarations. |
622 | // FIXME: We should track this in some way for source fidelity. |
623 | if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned) |
624 | return; |
625 | setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate); |
626 | } |
627 | |
628 | public: |
629 | /// Set the FromASTFile flag. This indicates that this declaration |
630 | /// was deserialized and not parsed from source code and enables |
631 | /// features such as module ownership information. |
632 | void setFromASTFile() { |
633 | FromASTFile = true; |
634 | } |
635 | |
636 | /// Set the owning module ID. This may only be called for |
637 | /// deserialized Decls. |
638 | void setOwningModuleID(unsigned ID) { |
639 | assert(isFromASTFile() && "Only works on a deserialized declaration")(static_cast <bool> (isFromASTFile() && "Only works on a deserialized declaration" ) ? void (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\"" , "clang/include/clang/AST/DeclBase.h", 639, __extension__ __PRETTY_FUNCTION__ )); |
640 | *((unsigned*)this - 2) = ID; |
641 | } |
642 | |
643 | public: |
644 | /// Determine the availability of the given declaration. |
645 | /// |
646 | /// This routine will determine the most restrictive availability of |
647 | /// the given declaration (e.g., preferring 'unavailable' to |
648 | /// 'deprecated'). |
649 | /// |
650 | /// \param Message If non-NULL and the result is not \c |
651 | /// AR_Available, will be set to a (possibly empty) message |
652 | /// describing why the declaration has not been introduced, is |
653 | /// deprecated, or is unavailable. |
654 | /// |
655 | /// \param EnclosingVersion The version to compare with. If empty, assume the |
656 | /// deployment target version. |
657 | /// |
658 | /// \param RealizedPlatform If non-NULL and the availability result is found |
659 | /// in an available attribute it will set to the platform which is written in |
660 | /// the available attribute. |
661 | AvailabilityResult |
662 | getAvailability(std::string *Message = nullptr, |
663 | VersionTuple EnclosingVersion = VersionTuple(), |
664 | StringRef *RealizedPlatform = nullptr) const; |
665 | |
666 | /// Retrieve the version of the target platform in which this |
667 | /// declaration was introduced. |
668 | /// |
669 | /// \returns An empty version tuple if this declaration has no 'introduced' |
670 | /// availability attributes, or the version tuple that's specified in the |
671 | /// attribute otherwise. |
672 | VersionTuple getVersionIntroduced() const; |
673 | |
674 | /// Determine whether this declaration is marked 'deprecated'. |
675 | /// |
676 | /// \param Message If non-NULL and the declaration is deprecated, |
677 | /// this will be set to the message describing why the declaration |
678 | /// was deprecated (which may be empty). |
679 | bool isDeprecated(std::string *Message = nullptr) const { |
680 | return getAvailability(Message) == AR_Deprecated; |
681 | } |
682 | |
683 | /// Determine whether this declaration is marked 'unavailable'. |
684 | /// |
685 | /// \param Message If non-NULL and the declaration is unavailable, |
686 | /// this will be set to the message describing why the declaration |
687 | /// was made unavailable (which may be empty). |
688 | bool isUnavailable(std::string *Message = nullptr) const { |
689 | return getAvailability(Message) == AR_Unavailable; |
690 | } |
691 | |
692 | /// Determine whether this is a weak-imported symbol. |
693 | /// |
694 | /// Weak-imported symbols are typically marked with the |
695 | /// 'weak_import' attribute, but may also be marked with an |
696 | /// 'availability' attribute where we're targing a platform prior to |
697 | /// the introduction of this feature. |
698 | bool isWeakImported() const; |
699 | |
700 | /// Determines whether this symbol can be weak-imported, |
701 | /// e.g., whether it would be well-formed to add the weak_import |
702 | /// attribute. |
703 | /// |
704 | /// \param IsDefinition Set to \c true to indicate that this |
705 | /// declaration cannot be weak-imported because it has a definition. |
706 | bool canBeWeakImported(bool &IsDefinition) const; |
707 | |
708 | /// Determine whether this declaration came from an AST file (such as |
709 | /// a precompiled header or module) rather than having been parsed. |
710 | bool isFromASTFile() const { return FromASTFile; } |
711 | |
712 | /// Retrieve the global declaration ID associated with this |
713 | /// declaration, which specifies where this Decl was loaded from. |
714 | unsigned getGlobalID() const { |
715 | if (isFromASTFile()) |
716 | return *((const unsigned*)this - 1); |
717 | return 0; |
718 | } |
719 | |
720 | /// Retrieve the global ID of the module that owns this particular |
721 | /// declaration. |
722 | unsigned getOwningModuleID() const { |
723 | if (isFromASTFile()) |
724 | return *((const unsigned*)this - 2); |
725 | return 0; |
726 | } |
727 | |
728 | private: |
729 | Module *getOwningModuleSlow() const; |
730 | |
731 | protected: |
732 | bool hasLocalOwningModuleStorage() const; |
733 | |
734 | public: |
735 | /// Get the imported owning module, if this decl is from an imported |
736 | /// (non-local) module. |
737 | Module *getImportedOwningModule() const { |
738 | if (!isFromASTFile() || !hasOwningModule()) |
739 | return nullptr; |
740 | |
741 | return getOwningModuleSlow(); |
742 | } |
743 | |
744 | /// Get the local owning module, if known. Returns nullptr if owner is |
745 | /// not yet known or declaration is not from a module. |
746 | Module *getLocalOwningModule() const { |
747 | if (isFromASTFile() || !hasOwningModule()) |
748 | return nullptr; |
749 | |
750 | assert(hasLocalOwningModuleStorage() &&(static_cast <bool> (hasLocalOwningModuleStorage() && "owned local decl but no local module storage") ? void (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\"" , "clang/include/clang/AST/DeclBase.h", 751, __extension__ __PRETTY_FUNCTION__ )) |
751 | "owned local decl but no local module storage")(static_cast <bool> (hasLocalOwningModuleStorage() && "owned local decl but no local module storage") ? void (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\"" , "clang/include/clang/AST/DeclBase.h", 751, __extension__ __PRETTY_FUNCTION__ )); |
752 | return reinterpret_cast<Module *const *>(this)[-1]; |
753 | } |
754 | void setLocalOwningModule(Module *M) { |
755 | assert(!isFromASTFile() && hasOwningModule() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule () && hasLocalOwningModuleStorage() && "should not have a cached owning module" ) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\"" , "clang/include/clang/AST/DeclBase.h", 757, __extension__ __PRETTY_FUNCTION__ )) |
756 | hasLocalOwningModuleStorage() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule () && hasLocalOwningModuleStorage() && "should not have a cached owning module" ) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\"" , "clang/include/clang/AST/DeclBase.h", 757, __extension__ __PRETTY_FUNCTION__ )) |
757 | "should not have a cached owning module")(static_cast <bool> (!isFromASTFile() && hasOwningModule () && hasLocalOwningModuleStorage() && "should not have a cached owning module" ) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\"" , "clang/include/clang/AST/DeclBase.h", 757, __extension__ __PRETTY_FUNCTION__ )); |
758 | reinterpret_cast<Module **>(this)[-1] = M; |
759 | } |
760 | |
761 | /// Is this declaration owned by some module? |
762 | bool hasOwningModule() const { |
763 | return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned; |
764 | } |
765 | |
766 | /// Get the module that owns this declaration (for visibility purposes). |
767 | Module *getOwningModule() const { |
768 | return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule(); |
769 | } |
770 | |
771 | /// Get the module that owns this declaration for linkage purposes. |
772 | /// There only ever is such a module under the C++ Modules TS. |
773 | /// |
774 | /// \param IgnoreLinkage Ignore the linkage of the entity; assume that |
775 | /// all declarations in a global module fragment are unowned. |
776 | Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const; |
777 | |
778 | /// Determine whether this declaration is definitely visible to name lookup, |
779 | /// independent of whether the owning module is visible. |
780 | /// Note: The declaration may be visible even if this returns \c false if the |
781 | /// owning module is visible within the query context. This is a low-level |
782 | /// helper function; most code should be calling Sema::isVisible() instead. |
783 | bool isUnconditionallyVisible() const { |
784 | return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible; |
785 | } |
786 | |
787 | /// Set that this declaration is globally visible, even if it came from a |
788 | /// module that is not visible. |
789 | void setVisibleDespiteOwningModule() { |
790 | if (!isUnconditionallyVisible()) |
791 | setModuleOwnershipKind(ModuleOwnershipKind::Visible); |
792 | } |
793 | |
794 | /// Get the kind of module ownership for this declaration. |
795 | ModuleOwnershipKind getModuleOwnershipKind() const { |
796 | return NextInContextAndBits.getInt(); |
797 | } |
798 | |
799 | /// Set whether this declaration is hidden from name lookup. |
800 | void setModuleOwnershipKind(ModuleOwnershipKind MOK) { |
801 | assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind ::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "clang/include/clang/AST/DeclBase.h", 804, __extension__ __PRETTY_FUNCTION__ )) |
802 | MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind ::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "clang/include/clang/AST/DeclBase.h", 804, __extension__ __PRETTY_FUNCTION__ )) |
803 | !hasLocalOwningModuleStorage()) &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind ::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "clang/include/clang/AST/DeclBase.h", 804, __extension__ __PRETTY_FUNCTION__ )) |
804 | "no storage available for owning module for this declaration")(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind ::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "clang/include/clang/AST/DeclBase.h", 804, __extension__ __PRETTY_FUNCTION__ )); |
805 | NextInContextAndBits.setInt(MOK); |
806 | } |
807 | |
808 | unsigned getIdentifierNamespace() const { |
809 | return IdentifierNamespace; |
810 | } |
811 | |
812 | bool isInIdentifierNamespace(unsigned NS) const { |
813 | return getIdentifierNamespace() & NS; |
814 | } |
815 | |
816 | static unsigned getIdentifierNamespaceForKind(Kind DK); |
817 | |
818 | bool hasTagIdentifierNamespace() const { |
819 | return isTagIdentifierNamespace(getIdentifierNamespace()); |
820 | } |
821 | |
822 | static bool isTagIdentifierNamespace(unsigned NS) { |
823 | // TagDecls have Tag and Type set and may also have TagFriend. |
824 | return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type); |
825 | } |
826 | |
827 | /// getLexicalDeclContext - The declaration context where this Decl was |
828 | /// lexically declared (LexicalDC). May be different from |
829 | /// getDeclContext() (SemanticDC). |
830 | /// e.g.: |
831 | /// |
832 | /// namespace A { |
833 | /// void f(); // SemanticDC == LexicalDC == 'namespace A' |
834 | /// } |
835 | /// void A::f(); // SemanticDC == namespace 'A' |
836 | /// // LexicalDC == global namespace |
837 | DeclContext *getLexicalDeclContext() { |
838 | if (isInSemaDC()) |
839 | return getSemanticDC(); |
840 | return getMultipleDC()->LexicalDC; |
841 | } |
842 | const DeclContext *getLexicalDeclContext() const { |
843 | return const_cast<Decl*>(this)->getLexicalDeclContext(); |
844 | } |
845 | |
846 | /// Determine whether this declaration is declared out of line (outside its |
847 | /// semantic context). |
848 | virtual bool isOutOfLine() const; |
849 | |
850 | /// setDeclContext - Set both the semantic and lexical DeclContext |
851 | /// to DC. |
852 | void setDeclContext(DeclContext *DC); |
853 | |
854 | void setLexicalDeclContext(DeclContext *DC); |
855 | |
856 | /// Determine whether this declaration is a templated entity (whether it is |
857 | // within the scope of a template parameter). |
858 | bool isTemplated() const; |
859 | |
860 | /// Determine the number of levels of template parameter surrounding this |
861 | /// declaration. |
862 | unsigned getTemplateDepth() const; |
863 | |
864 | /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this |
865 | /// scoped decl is defined outside the current function or method. This is |
866 | /// roughly global variables and functions, but also handles enums (which |
867 | /// could be defined inside or outside a function etc). |
868 | bool isDefinedOutsideFunctionOrMethod() const { |
869 | return getParentFunctionOrMethod() == nullptr; |
870 | } |
871 | |
872 | /// Determine whether a substitution into this declaration would occur as |
873 | /// part of a substitution into a dependent local scope. Such a substitution |
874 | /// transitively substitutes into all constructs nested within this |
875 | /// declaration. |
876 | /// |
877 | /// This recognizes non-defining declarations as well as members of local |
878 | /// classes and lambdas: |
879 | /// \code |
880 | /// template<typename T> void foo() { void bar(); } |
881 | /// template<typename T> void foo2() { class ABC { void bar(); }; } |
882 | /// template<typename T> inline int x = [](){ return 0; }(); |
883 | /// \endcode |
884 | bool isInLocalScopeForInstantiation() const; |
885 | |
886 | /// If this decl is defined inside a function/method/block it returns |
887 | /// the corresponding DeclContext, otherwise it returns null. |
888 | const DeclContext *getParentFunctionOrMethod() const; |
889 | DeclContext *getParentFunctionOrMethod() { |
890 | return const_cast<DeclContext*>( |
891 | const_cast<const Decl*>(this)->getParentFunctionOrMethod()); |
892 | } |
893 | |
894 | /// Retrieves the "canonical" declaration of the given declaration. |
895 | virtual Decl *getCanonicalDecl() { return this; } |
896 | const Decl *getCanonicalDecl() const { |
897 | return const_cast<Decl*>(this)->getCanonicalDecl(); |
898 | } |
899 | |
900 | /// Whether this particular Decl is a canonical one. |
901 | bool isCanonicalDecl() const { return getCanonicalDecl() == this; } |
902 | |
903 | protected: |
904 | /// Returns the next redeclaration or itself if this is the only decl. |
905 | /// |
906 | /// Decl subclasses that can be redeclared should override this method so that |
907 | /// Decl::redecl_iterator can iterate over them. |
908 | virtual Decl *getNextRedeclarationImpl() { return this; } |
909 | |
910 | /// Implementation of getPreviousDecl(), to be overridden by any |
911 | /// subclass that has a redeclaration chain. |
912 | virtual Decl *getPreviousDeclImpl() { return nullptr; } |
913 | |
914 | /// Implementation of getMostRecentDecl(), to be overridden by any |
915 | /// subclass that has a redeclaration chain. |
916 | virtual Decl *getMostRecentDeclImpl() { return this; } |
917 | |
918 | public: |
919 | /// Iterates through all the redeclarations of the same decl. |
920 | class redecl_iterator { |
921 | /// Current - The current declaration. |
922 | Decl *Current = nullptr; |
923 | Decl *Starter; |
924 | |
925 | public: |
926 | using value_type = Decl *; |
927 | using reference = const value_type &; |
928 | using pointer = const value_type *; |
929 | using iterator_category = std::forward_iterator_tag; |
930 | using difference_type = std::ptrdiff_t; |
931 | |
932 | redecl_iterator() = default; |
933 | explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {} |
934 | |
935 | reference operator*() const { return Current; } |
936 | value_type operator->() const { return Current; } |
937 | |
938 | redecl_iterator& operator++() { |
939 | assert(Current && "Advancing while iterator has reached end")(static_cast <bool> (Current && "Advancing while iterator has reached end" ) ? void (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\"" , "clang/include/clang/AST/DeclBase.h", 939, __extension__ __PRETTY_FUNCTION__ )); |
940 | // Get either previous decl or latest decl. |
941 | Decl *Next = Current->getNextRedeclarationImpl(); |
942 | assert(Next && "Should return next redeclaration or itself, never null!")(static_cast <bool> (Next && "Should return next redeclaration or itself, never null!" ) ? void (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\"" , "clang/include/clang/AST/DeclBase.h", 942, __extension__ __PRETTY_FUNCTION__ )); |
943 | Current = (Next != Starter) ? Next : nullptr; |
944 | return *this; |
945 | } |
946 | |
947 | redecl_iterator operator++(int) { |
948 | redecl_iterator tmp(*this); |
949 | ++(*this); |
950 | return tmp; |
951 | } |
952 | |
953 | friend bool operator==(redecl_iterator x, redecl_iterator y) { |
954 | return x.Current == y.Current; |
955 | } |
956 | |
957 | friend bool operator!=(redecl_iterator x, redecl_iterator y) { |
958 | return x.Current != y.Current; |
959 | } |
960 | }; |
961 | |
962 | using redecl_range = llvm::iterator_range<redecl_iterator>; |
963 | |
964 | /// Returns an iterator range for all the redeclarations of the same |
965 | /// decl. It will iterate at least once (when this decl is the only one). |
966 | redecl_range redecls() const { |
967 | return redecl_range(redecls_begin(), redecls_end()); |
968 | } |
969 | |
970 | redecl_iterator redecls_begin() const { |
971 | return redecl_iterator(const_cast<Decl *>(this)); |
972 | } |
973 | |
974 | redecl_iterator redecls_end() const { return redecl_iterator(); } |
975 | |
976 | /// Retrieve the previous declaration that declares the same entity |
977 | /// as this declaration, or NULL if there is no previous declaration. |
978 | Decl *getPreviousDecl() { return getPreviousDeclImpl(); } |
979 | |
980 | /// Retrieve the previous declaration that declares the same entity |
981 | /// as this declaration, or NULL if there is no previous declaration. |
982 | const Decl *getPreviousDecl() const { |
983 | return const_cast<Decl *>(this)->getPreviousDeclImpl(); |
984 | } |
985 | |
986 | /// True if this is the first declaration in its redeclaration chain. |
987 | bool isFirstDecl() const { |
988 | return getPreviousDecl() == nullptr; |
989 | } |
990 | |
991 | /// Retrieve the most recent declaration that declares the same entity |
992 | /// as this declaration (which may be this declaration). |
993 | Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); } |
994 | |
995 | /// Retrieve the most recent declaration that declares the same entity |
996 | /// as this declaration (which may be this declaration). |
997 | const Decl *getMostRecentDecl() const { |
998 | return const_cast<Decl *>(this)->getMostRecentDeclImpl(); |
999 | } |
1000 | |
1001 | /// getBody - If this Decl represents a declaration for a body of code, |
1002 | /// such as a function or method definition, this method returns the |
1003 | /// top-level Stmt* of that body. Otherwise this method returns null. |
1004 | virtual Stmt* getBody() const { return nullptr; } |
1005 | |
1006 | /// Returns true if this \c Decl represents a declaration for a body of |
1007 | /// code, such as a function or method definition. |
1008 | /// Note that \c hasBody can also return true if any redeclaration of this |
1009 | /// \c Decl represents a declaration for a body of code. |
1010 | virtual bool hasBody() const { return getBody() != nullptr; } |
1011 | |
1012 | /// getBodyRBrace - Gets the right brace of the body, if a body exists. |
1013 | /// This works whether the body is a CompoundStmt or a CXXTryStmt. |
1014 | SourceLocation getBodyRBrace() const; |
1015 | |
1016 | // global temp stats (until we have a per-module visitor) |
1017 | static void add(Kind k); |
1018 | static void EnableStatistics(); |
1019 | static void PrintStats(); |
1020 | |
1021 | /// isTemplateParameter - Determines whether this declaration is a |
1022 | /// template parameter. |
1023 | bool isTemplateParameter() const; |
1024 | |
1025 | /// isTemplateParameter - Determines whether this declaration is a |
1026 | /// template parameter pack. |
1027 | bool isTemplateParameterPack() const; |
1028 | |
1029 | /// Whether this declaration is a parameter pack. |
1030 | bool isParameterPack() const; |
1031 | |
1032 | /// returns true if this declaration is a template |
1033 | bool isTemplateDecl() const; |
1034 | |
1035 | /// Whether this declaration is a function or function template. |
1036 | bool isFunctionOrFunctionTemplate() const { |
1037 | return (DeclKind >= Decl::firstFunction && |
1038 | DeclKind <= Decl::lastFunction) || |
1039 | DeclKind == FunctionTemplate; |
1040 | } |
1041 | |
1042 | /// If this is a declaration that describes some template, this |
1043 | /// method returns that template declaration. |
1044 | /// |
1045 | /// Note that this returns nullptr for partial specializations, because they |
1046 | /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle |
1047 | /// those cases. |
1048 | TemplateDecl *getDescribedTemplate() const; |
1049 | |
1050 | /// If this is a declaration that describes some template or partial |
1051 | /// specialization, this returns the corresponding template parameter list. |
1052 | const TemplateParameterList *getDescribedTemplateParams() const; |
1053 | |
1054 | /// Returns the function itself, or the templated function if this is a |
1055 | /// function template. |
1056 | FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__)); |
1057 | |
1058 | const FunctionDecl *getAsFunction() const { |
1059 | return const_cast<Decl *>(this)->getAsFunction(); |
1060 | } |
1061 | |
1062 | /// Changes the namespace of this declaration to reflect that it's |
1063 | /// a function-local extern declaration. |
1064 | /// |
1065 | /// These declarations appear in the lexical context of the extern |
1066 | /// declaration, but in the semantic context of the enclosing namespace |
1067 | /// scope. |
1068 | void setLocalExternDecl() { |
1069 | Decl *Prev = getPreviousDecl(); |
1070 | IdentifierNamespace &= ~IDNS_Ordinary; |
1071 | |
1072 | // It's OK for the declaration to still have the "invisible friend" flag or |
1073 | // the "conflicts with tag declarations in this scope" flag for the outer |
1074 | // scope. |
1075 | assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && "namespace is not ordinary") ? void (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\"" , "clang/include/clang/AST/DeclBase.h", 1076, __extension__ __PRETTY_FUNCTION__ )) |
1076 | "namespace is not ordinary")(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && "namespace is not ordinary") ? void (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\"" , "clang/include/clang/AST/DeclBase.h", 1076, __extension__ __PRETTY_FUNCTION__ )); |
1077 | |
1078 | IdentifierNamespace |= IDNS_LocalExtern; |
1079 | if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary) |
1080 | IdentifierNamespace |= IDNS_Ordinary; |
1081 | } |
1082 | |
1083 | /// Determine whether this is a block-scope declaration with linkage. |
1084 | /// This will either be a local variable declaration declared 'extern', or a |
1085 | /// local function declaration. |
1086 | bool isLocalExternDecl() { |
1087 | return IdentifierNamespace & IDNS_LocalExtern; |
1088 | } |
1089 | |
1090 | /// Changes the namespace of this declaration to reflect that it's |
1091 | /// the object of a friend declaration. |
1092 | /// |
1093 | /// These declarations appear in the lexical context of the friending |
1094 | /// class, but in the semantic context of the actual entity. This property |
1095 | /// applies only to a specific decl object; other redeclarations of the |
1096 | /// same entity may not (and probably don't) share this property. |
1097 | void setObjectOfFriendDecl(bool PerformFriendInjection = false) { |
1098 | unsigned OldNS = IdentifierNamespace; |
1099 | assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes neither ordinary nor tag") ? void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "clang/include/clang/AST/DeclBase.h", 1102, __extension__ __PRETTY_FUNCTION__ )) |
1100 | IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes neither ordinary nor tag") ? void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "clang/include/clang/AST/DeclBase.h", 1102, __extension__ __PRETTY_FUNCTION__ )) |
1101 | IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes neither ordinary nor tag") ? void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "clang/include/clang/AST/DeclBase.h", 1102, __extension__ __PRETTY_FUNCTION__ )) |
1102 | "namespace includes neither ordinary nor tag")(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes neither ordinary nor tag") ? void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "clang/include/clang/AST/DeclBase.h", 1102, __extension__ __PRETTY_FUNCTION__ )); |
1103 | assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag" ) ? 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\"" , "clang/include/clang/AST/DeclBase.h", 1106, __extension__ __PRETTY_FUNCTION__ )) |
1104 | IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag" ) ? 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\"" , "clang/include/clang/AST/DeclBase.h", 1106, __extension__ __PRETTY_FUNCTION__ )) |
1105 | IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag" ) ? 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\"" , "clang/include/clang/AST/DeclBase.h", 1106, __extension__ __PRETTY_FUNCTION__ )) |
1106 | "namespace includes other than ordinary or tag")(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag" ) ? 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\"" , "clang/include/clang/AST/DeclBase.h", 1106, __extension__ __PRETTY_FUNCTION__ )); |
1107 | |
1108 | Decl *Prev = getPreviousDecl(); |
1109 | IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type); |
1110 | |
1111 | if (OldNS & (IDNS_Tag | IDNS_TagFriend)) { |
1112 | IdentifierNamespace |= IDNS_TagFriend; |
1113 | if (PerformFriendInjection || |
1114 | (Prev && Prev->getIdentifierNamespace() & IDNS_Tag)) |
1115 | IdentifierNamespace |= IDNS_Tag | IDNS_Type; |
1116 | } |
1117 | |
1118 | if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | |
1119 | IDNS_LocalExtern | IDNS_NonMemberOperator)) { |
1120 | IdentifierNamespace |= IDNS_OrdinaryFriend; |
1121 | if (PerformFriendInjection || |
1122 | (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)) |
1123 | IdentifierNamespace |= IDNS_Ordinary; |
1124 | } |
1125 | } |
1126 | |
1127 | enum FriendObjectKind { |
1128 | FOK_None, ///< Not a friend object. |
1129 | FOK_Declared, ///< A friend of a previously-declared entity. |
1130 | FOK_Undeclared ///< A friend of a previously-undeclared entity. |
1131 | }; |
1132 | |
1133 | /// Determines whether this declaration is the object of a |
1134 | /// friend declaration and, if so, what kind. |
1135 | /// |
1136 | /// There is currently no direct way to find the associated FriendDecl. |
1137 | FriendObjectKind getFriendObjectKind() const { |
1138 | unsigned mask = |
1139 | (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend)); |
1140 | if (!mask) return FOK_None; |
1141 | return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared |
1142 | : FOK_Undeclared); |
1143 | } |
1144 | |
1145 | /// Specifies that this declaration is a C++ overloaded non-member. |
1146 | void setNonMemberOperator() { |
1147 | assert(getKind() == Function || getKind() == FunctionTemplate)(static_cast <bool> (getKind() == Function || getKind() == FunctionTemplate) ? void (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate" , "clang/include/clang/AST/DeclBase.h", 1147, __extension__ __PRETTY_FUNCTION__ )); |
1148 | assert((IdentifierNamespace & IDNS_Ordinary) &&(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary ) && "visible non-member operators should be in ordinary namespace" ) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\"" , "clang/include/clang/AST/DeclBase.h", 1149, __extension__ __PRETTY_FUNCTION__ )) |
1149 | "visible non-member operators should be in ordinary namespace")(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary ) && "visible non-member operators should be in ordinary namespace" ) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\"" , "clang/include/clang/AST/DeclBase.h", 1149, __extension__ __PRETTY_FUNCTION__ )); |
1150 | IdentifierNamespace |= IDNS_NonMemberOperator; |
1151 | } |
1152 | |
1153 | static bool classofKind(Kind K) { return true; } |
1154 | static DeclContext *castToDeclContext(const Decl *); |
1155 | static Decl *castFromDeclContext(const DeclContext *); |
1156 | |
1157 | void print(raw_ostream &Out, unsigned Indentation = 0, |
1158 | bool PrintInstantiation = false) const; |
1159 | void print(raw_ostream &Out, const PrintingPolicy &Policy, |
1160 | unsigned Indentation = 0, bool PrintInstantiation = false) const; |
1161 | static void printGroup(Decl** Begin, unsigned NumDecls, |
1162 | raw_ostream &Out, const PrintingPolicy &Policy, |
1163 | unsigned Indentation = 0); |
1164 | |
1165 | // Debuggers don't usually respect default arguments. |
1166 | void dump() const; |
1167 | |
1168 | // Same as dump(), but forces color printing. |
1169 | void dumpColor() const; |
1170 | |
1171 | void dump(raw_ostream &Out, bool Deserialize = false, |
1172 | ASTDumpOutputFormat OutputFormat = ADOF_Default) const; |
1173 | |
1174 | /// \return Unique reproducible object identifier |
1175 | int64_t getID() const; |
1176 | |
1177 | /// Looks through the Decl's underlying type to extract a FunctionType |
1178 | /// when possible. Will return null if the type underlying the Decl does not |
1179 | /// have a FunctionType. |
1180 | const FunctionType *getFunctionType(bool BlocksToo = true) const; |
1181 | |
1182 | private: |
1183 | void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx); |
1184 | void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC, |
1185 | ASTContext &Ctx); |
1186 | |
1187 | protected: |
1188 | ASTMutationListener *getASTMutationListener() const; |
1189 | }; |
1190 | |
1191 | /// Determine whether two declarations declare the same entity. |
1192 | inline bool declaresSameEntity(const Decl *D1, const Decl *D2) { |
1193 | if (!D1 || !D2) |
1194 | return false; |
1195 | |
1196 | if (D1 == D2) |
1197 | return true; |
1198 | |
1199 | return D1->getCanonicalDecl() == D2->getCanonicalDecl(); |
1200 | } |
1201 | |
1202 | /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when |
1203 | /// doing something to a specific decl. |
1204 | class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry { |
1205 | const Decl *TheDecl; |
1206 | SourceLocation Loc; |
1207 | SourceManager &SM; |
1208 | const char *Message; |
1209 | |
1210 | public: |
1211 | PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L, |
1212 | SourceManager &sm, const char *Msg) |
1213 | : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {} |
1214 | |
1215 | void print(raw_ostream &OS) const override; |
1216 | }; |
1217 | } // namespace clang |
1218 | |
1219 | // Required to determine the layout of the PointerUnion<NamedDecl*> before |
1220 | // seeing the NamedDecl definition being first used in DeclListNode::operator*. |
1221 | namespace llvm { |
1222 | template <> struct PointerLikeTypeTraits<::clang::NamedDecl *> { |
1223 | static inline void *getAsVoidPointer(::clang::NamedDecl *P) { return P; } |
1224 | static inline ::clang::NamedDecl *getFromVoidPointer(void *P) { |
1225 | return static_cast<::clang::NamedDecl *>(P); |
1226 | } |
1227 | static constexpr int NumLowBitsAvailable = 3; |
1228 | }; |
1229 | } |
1230 | |
1231 | namespace clang { |
1232 | /// A list storing NamedDecls in the lookup tables. |
1233 | class DeclListNode { |
1234 | friend class ASTContext; // allocate, deallocate nodes. |
1235 | friend class StoredDeclsList; |
1236 | public: |
1237 | using Decls = llvm::PointerUnion<NamedDecl*, DeclListNode*>; |
1238 | class iterator { |
1239 | friend class DeclContextLookupResult; |
1240 | friend class StoredDeclsList; |
1241 | |
1242 | Decls Ptr; |
1243 | iterator(Decls Node) : Ptr(Node) { } |
1244 | public: |
1245 | using difference_type = ptrdiff_t; |
1246 | using value_type = NamedDecl*; |
1247 | using pointer = void; |
1248 | using reference = value_type; |
1249 | using iterator_category = std::forward_iterator_tag; |
1250 | |
1251 | iterator() = default; |
1252 | |
1253 | reference operator*() const { |
1254 | assert(Ptr && "dereferencing end() iterator")(static_cast <bool> (Ptr && "dereferencing end() iterator" ) ? void (0) : __assert_fail ("Ptr && \"dereferencing end() iterator\"" , "clang/include/clang/AST/DeclBase.h", 1254, __extension__ __PRETTY_FUNCTION__ )); |
1255 | if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>()) |
1256 | return CurNode->D; |
1257 | return Ptr.get<NamedDecl*>(); |
1258 | } |
1259 | void operator->() const { } // Unsupported. |
1260 | bool operator==(const iterator &X) const { return Ptr == X.Ptr; } |
1261 | bool operator!=(const iterator &X) const { return Ptr != X.Ptr; } |
1262 | inline iterator &operator++() { // ++It |
1263 | assert(!Ptr.isNull() && "Advancing empty iterator")(static_cast <bool> (!Ptr.isNull() && "Advancing empty iterator" ) ? void (0) : __assert_fail ("!Ptr.isNull() && \"Advancing empty iterator\"" , "clang/include/clang/AST/DeclBase.h", 1263, __extension__ __PRETTY_FUNCTION__ )); |
1264 | |
1265 | if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>()) |
1266 | Ptr = CurNode->Rest; |
1267 | else |
1268 | Ptr = nullptr; |
1269 | return *this; |
1270 | } |
1271 | iterator operator++(int) { // It++ |
1272 | iterator temp = *this; |
1273 | ++(*this); |
1274 | return temp; |
1275 | } |
1276 | // Enables the pattern for (iterator I =..., E = I.end(); I != E; ++I) |
1277 | iterator end() { return iterator(); } |
1278 | }; |
1279 | private: |
1280 | NamedDecl *D = nullptr; |
1281 | Decls Rest = nullptr; |
1282 | DeclListNode(NamedDecl *ND) : D(ND) {} |
1283 | }; |
1284 | |
1285 | /// The results of name lookup within a DeclContext. |
1286 | class DeclContextLookupResult { |
1287 | using Decls = DeclListNode::Decls; |
1288 | |
1289 | /// When in collection form, this is what the Data pointer points to. |
1290 | Decls Result; |
1291 | |
1292 | public: |
1293 | DeclContextLookupResult() = default; |
1294 | DeclContextLookupResult(Decls Result) : Result(Result) {} |
1295 | |
1296 | using iterator = DeclListNode::iterator; |
1297 | using const_iterator = iterator; |
1298 | using reference = iterator::reference; |
1299 | |
1300 | iterator begin() { return iterator(Result); } |
1301 | iterator end() { return iterator(); } |
1302 | const_iterator begin() const { |
1303 | return const_cast<DeclContextLookupResult*>(this)->begin(); |
1304 | } |
1305 | const_iterator end() const { return iterator(); } |
1306 | |
1307 | bool empty() const { return Result.isNull(); } |
1308 | bool isSingleResult() const { return Result.dyn_cast<NamedDecl*>(); } |
1309 | reference front() const { return *begin(); } |
1310 | |
1311 | // Find the first declaration of the given type in the list. Note that this |
1312 | // is not in general the earliest-declared declaration, and should only be |
1313 | // used when it's not possible for there to be more than one match or where |
1314 | // it doesn't matter which one is found. |
1315 | template<class T> T *find_first() const { |
1316 | for (auto *D : *this) |
1317 | if (T *Decl = dyn_cast<T>(D)) |
1318 | return Decl; |
1319 | |
1320 | return nullptr; |
1321 | } |
1322 | }; |
1323 | |
1324 | /// DeclContext - This is used only as base class of specific decl types that |
1325 | /// can act as declaration contexts. These decls are (only the top classes |
1326 | /// that directly derive from DeclContext are mentioned, not their subclasses): |
1327 | /// |
1328 | /// TranslationUnitDecl |
1329 | /// ExternCContext |
1330 | /// NamespaceDecl |
1331 | /// TagDecl |
1332 | /// OMPDeclareReductionDecl |
1333 | /// OMPDeclareMapperDecl |
1334 | /// FunctionDecl |
1335 | /// ObjCMethodDecl |
1336 | /// ObjCContainerDecl |
1337 | /// LinkageSpecDecl |
1338 | /// ExportDecl |
1339 | /// BlockDecl |
1340 | /// CapturedDecl |
1341 | class DeclContext { |
1342 | /// For makeDeclVisibleInContextImpl |
1343 | friend class ASTDeclReader; |
1344 | /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap, |
1345 | /// hasNeedToReconcileExternalVisibleStorage |
1346 | friend class ExternalASTSource; |
1347 | /// For CreateStoredDeclsMap |
1348 | friend class DependentDiagnostic; |
1349 | /// For hasNeedToReconcileExternalVisibleStorage, |
1350 | /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups |
1351 | friend class ASTWriter; |
1352 | |
1353 | // We use uint64_t in the bit-fields below since some bit-fields |
1354 | // cross the unsigned boundary and this breaks the packing. |
1355 | |
1356 | /// Stores the bits used by DeclContext. |
1357 | /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor |
1358 | /// methods in DeclContext should be updated appropriately. |
1359 | class DeclContextBitfields { |
1360 | friend class DeclContext; |
1361 | /// DeclKind - This indicates which class this is. |
1362 | uint64_t DeclKind : 7; |
1363 | |
1364 | /// Whether this declaration context also has some external |
1365 | /// storage that contains additional declarations that are lexically |
1366 | /// part of this context. |
1367 | mutable uint64_t ExternalLexicalStorage : 1; |
1368 | |
1369 | /// Whether this declaration context also has some external |
1370 | /// storage that contains additional declarations that are visible |
1371 | /// in this context. |
1372 | mutable uint64_t ExternalVisibleStorage : 1; |
1373 | |
1374 | /// Whether this declaration context has had externally visible |
1375 | /// storage added since the last lookup. In this case, \c LookupPtr's |
1376 | /// invariant may not hold and needs to be fixed before we perform |
1377 | /// another lookup. |
1378 | mutable uint64_t NeedToReconcileExternalVisibleStorage : 1; |
1379 | |
1380 | /// If \c true, this context may have local lexical declarations |
1381 | /// that are missing from the lookup table. |
1382 | mutable uint64_t HasLazyLocalLexicalLookups : 1; |
1383 | |
1384 | /// If \c true, the external source may have lexical declarations |
1385 | /// that are missing from the lookup table. |
1386 | mutable uint64_t HasLazyExternalLexicalLookups : 1; |
1387 | |
1388 | /// If \c true, lookups should only return identifier from |
1389 | /// DeclContext scope (for example TranslationUnit). Used in |
1390 | /// LookupQualifiedName() |
1391 | mutable uint64_t UseQualifiedLookup : 1; |
1392 | }; |
1393 | |
1394 | /// Number of bits in DeclContextBitfields. |
1395 | enum { NumDeclContextBits = 13 }; |
1396 | |
1397 | /// Stores the bits used by TagDecl. |
1398 | /// If modified NumTagDeclBits and the accessor |
1399 | /// methods in TagDecl should be updated appropriately. |
1400 | class TagDeclBitfields { |
1401 | friend class TagDecl; |
1402 | /// For the bits in DeclContextBitfields |
1403 | uint64_t : NumDeclContextBits; |
1404 | |
1405 | /// The TagKind enum. |
1406 | uint64_t TagDeclKind : 3; |
1407 | |
1408 | /// True if this is a definition ("struct foo {};"), false if it is a |
1409 | /// declaration ("struct foo;"). It is not considered a definition |
1410 | /// until the definition has been fully processed. |
1411 | uint64_t IsCompleteDefinition : 1; |
1412 | |
1413 | /// True if this is currently being defined. |
1414 | uint64_t IsBeingDefined : 1; |
1415 | |
1416 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
1417 | /// for the very first time) in the syntax of a declarator. |
1418 | uint64_t IsEmbeddedInDeclarator : 1; |
1419 | |
1420 | /// True if this tag is free standing, e.g. "struct foo;". |
1421 | uint64_t IsFreeStanding : 1; |
1422 | |
1423 | /// Indicates whether it is possible for declarations of this kind |
1424 | /// to have an out-of-date definition. |
1425 | /// |
1426 | /// This option is only enabled when modules are enabled. |
1427 | uint64_t MayHaveOutOfDateDef : 1; |
1428 | |
1429 | /// Has the full definition of this type been required by a use somewhere in |
1430 | /// the TU. |
1431 | uint64_t IsCompleteDefinitionRequired : 1; |
1432 | }; |
1433 | |
1434 | /// Number of non-inherited bits in TagDeclBitfields. |
1435 | enum { NumTagDeclBits = 9 }; |
1436 | |
1437 | /// Stores the bits used by EnumDecl. |
1438 | /// If modified NumEnumDeclBit and the accessor |
1439 | /// methods in EnumDecl should be updated appropriately. |
1440 | class EnumDeclBitfields { |
1441 | friend class EnumDecl; |
1442 | /// For the bits in DeclContextBitfields. |
1443 | uint64_t : NumDeclContextBits; |
1444 | /// For the bits in TagDeclBitfields. |
1445 | uint64_t : NumTagDeclBits; |
1446 | |
1447 | /// Width in bits required to store all the non-negative |
1448 | /// enumerators of this enum. |
1449 | uint64_t NumPositiveBits : 8; |
1450 | |
1451 | /// Width in bits required to store all the negative |
1452 | /// enumerators of this enum. |
1453 | uint64_t NumNegativeBits : 8; |
1454 | |
1455 | /// True if this tag declaration is a scoped enumeration. Only |
1456 | /// possible in C++11 mode. |
1457 | uint64_t IsScoped : 1; |
1458 | |
1459 | /// If this tag declaration is a scoped enum, |
1460 | /// then this is true if the scoped enum was declared using the class |
1461 | /// tag, false if it was declared with the struct tag. No meaning is |
1462 | /// associated if this tag declaration is not a scoped enum. |
1463 | uint64_t IsScopedUsingClassTag : 1; |
1464 | |
1465 | /// True if this is an enumeration with fixed underlying type. Only |
1466 | /// possible in C++11, Microsoft extensions, or Objective C mode. |
1467 | uint64_t IsFixed : 1; |
1468 | |
1469 | /// True if a valid hash is stored in ODRHash. |
1470 | uint64_t HasODRHash : 1; |
1471 | }; |
1472 | |
1473 | /// Number of non-inherited bits in EnumDeclBitfields. |
1474 | enum { NumEnumDeclBits = 20 }; |
1475 | |
1476 | /// Stores the bits used by RecordDecl. |
1477 | /// If modified NumRecordDeclBits and the accessor |
1478 | /// methods in RecordDecl should be updated appropriately. |
1479 | class RecordDeclBitfields { |
1480 | friend class RecordDecl; |
1481 | /// For the bits in DeclContextBitfields. |
1482 | uint64_t : NumDeclContextBits; |
1483 | /// For the bits in TagDeclBitfields. |
1484 | uint64_t : NumTagDeclBits; |
1485 | |
1486 | /// This is true if this struct ends with a flexible |
1487 | /// array member (e.g. int X[]) or if this union contains a struct that does. |
1488 | /// If so, this cannot be contained in arrays or other structs as a member. |
1489 | uint64_t HasFlexibleArrayMember : 1; |
1490 | |
1491 | /// Whether this is the type of an anonymous struct or union. |
1492 | uint64_t AnonymousStructOrUnion : 1; |
1493 | |
1494 | /// This is true if this struct has at least one member |
1495 | /// containing an Objective-C object pointer type. |
1496 | uint64_t HasObjectMember : 1; |
1497 | |
1498 | /// This is true if struct has at least one member of |
1499 | /// 'volatile' type. |
1500 | uint64_t HasVolatileMember : 1; |
1501 | |
1502 | /// Whether the field declarations of this record have been loaded |
1503 | /// from external storage. To avoid unnecessary deserialization of |
1504 | /// methods/nested types we allow deserialization of just the fields |
1505 | /// when needed. |
1506 | mutable uint64_t LoadedFieldsFromExternalStorage : 1; |
1507 | |
1508 | /// Basic properties of non-trivial C structs. |
1509 | uint64_t NonTrivialToPrimitiveDefaultInitialize : 1; |
1510 | uint64_t NonTrivialToPrimitiveCopy : 1; |
1511 | uint64_t NonTrivialToPrimitiveDestroy : 1; |
1512 | |
1513 | /// The following bits indicate whether this is or contains a C union that |
1514 | /// is non-trivial to default-initialize, destruct, or copy. These bits |
1515 | /// imply the associated basic non-triviality predicates declared above. |
1516 | uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1; |
1517 | uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1; |
1518 | uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1; |
1519 | |
1520 | /// Indicates whether this struct is destroyed in the callee. |
1521 | uint64_t ParamDestroyedInCallee : 1; |
1522 | |
1523 | /// Represents the way this type is passed to a function. |
1524 | uint64_t ArgPassingRestrictions : 2; |
1525 | }; |
1526 | |
1527 | /// Number of non-inherited bits in RecordDeclBitfields. |
1528 | enum { NumRecordDeclBits = 14 }; |
1529 | |
1530 | /// Stores the bits used by OMPDeclareReductionDecl. |
1531 | /// If modified NumOMPDeclareReductionDeclBits and the accessor |
1532 | /// methods in OMPDeclareReductionDecl should be updated appropriately. |
1533 | class OMPDeclareReductionDeclBitfields { |
1534 | friend class OMPDeclareReductionDecl; |
1535 | /// For the bits in DeclContextBitfields |
1536 | uint64_t : NumDeclContextBits; |
1537 | |
1538 | /// Kind of initializer, |
1539 | /// function call or omp_priv<init_expr> initializtion. |
1540 | uint64_t InitializerKind : 2; |
1541 | }; |
1542 | |
1543 | /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields. |
1544 | enum { NumOMPDeclareReductionDeclBits = 2 }; |
1545 | |
1546 | /// Stores the bits used by FunctionDecl. |
1547 | /// If modified NumFunctionDeclBits and the accessor |
1548 | /// methods in FunctionDecl and CXXDeductionGuideDecl |
1549 | /// (for IsCopyDeductionCandidate) should be updated appropriately. |
1550 | class FunctionDeclBitfields { |
1551 | friend class FunctionDecl; |
1552 | /// For IsCopyDeductionCandidate |
1553 | friend class CXXDeductionGuideDecl; |
1554 | /// For the bits in DeclContextBitfields. |
1555 | uint64_t : NumDeclContextBits; |
1556 | |
1557 | uint64_t SClass : 3; |
1558 | uint64_t IsInline : 1; |
1559 | uint64_t IsInlineSpecified : 1; |
1560 | |
1561 | uint64_t IsVirtualAsWritten : 1; |
1562 | uint64_t IsPure : 1; |
1563 | uint64_t HasInheritedPrototype : 1; |
1564 | uint64_t HasWrittenPrototype : 1; |
1565 | uint64_t IsDeleted : 1; |
1566 | /// Used by CXXMethodDecl |
1567 | uint64_t IsTrivial : 1; |
1568 | |
1569 | /// This flag indicates whether this function is trivial for the purpose of |
1570 | /// calls. This is meaningful only when this function is a copy/move |
1571 | /// constructor or a destructor. |
1572 | uint64_t IsTrivialForCall : 1; |
1573 | |
1574 | uint64_t IsDefaulted : 1; |
1575 | uint64_t IsExplicitlyDefaulted : 1; |
1576 | uint64_t HasDefaultedFunctionInfo : 1; |
1577 | uint64_t HasImplicitReturnZero : 1; |
1578 | uint64_t IsLateTemplateParsed : 1; |
1579 | |
1580 | /// Kind of contexpr specifier as defined by ConstexprSpecKind. |
1581 | uint64_t ConstexprKind : 2; |
1582 | uint64_t InstantiationIsPending : 1; |
1583 | |
1584 | /// Indicates if the function uses __try. |
1585 | uint64_t UsesSEHTry : 1; |
1586 | |
1587 | /// Indicates if the function was a definition |
1588 | /// but its body was skipped. |
1589 | uint64_t HasSkippedBody : 1; |
1590 | |
1591 | /// Indicates if the function declaration will |
1592 | /// have a body, once we're done parsing it. |
1593 | uint64_t WillHaveBody : 1; |
1594 | |
1595 | /// Indicates that this function is a multiversioned |
1596 | /// function using attribute 'target'. |
1597 | uint64_t IsMultiVersion : 1; |
1598 | |
1599 | /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that |
1600 | /// the Deduction Guide is the implicitly generated 'copy |
1601 | /// deduction candidate' (is used during overload resolution). |
1602 | uint64_t IsCopyDeductionCandidate : 1; |
1603 | |
1604 | /// Store the ODRHash after first calculation. |
1605 | uint64_t HasODRHash : 1; |
1606 | |
1607 | /// Indicates if the function uses Floating Point Constrained Intrinsics |
1608 | uint64_t UsesFPIntrin : 1; |
1609 | }; |
1610 | |
1611 | /// Number of non-inherited bits in FunctionDeclBitfields. |
1612 | enum { NumFunctionDeclBits = 27 }; |
1613 | |
1614 | /// Stores the bits used by CXXConstructorDecl. If modified |
1615 | /// NumCXXConstructorDeclBits and the accessor |
1616 | /// methods in CXXConstructorDecl should be updated appropriately. |
1617 | class CXXConstructorDeclBitfields { |
1618 | friend class CXXConstructorDecl; |
1619 | /// For the bits in DeclContextBitfields. |
1620 | uint64_t : NumDeclContextBits; |
1621 | /// For the bits in FunctionDeclBitfields. |
1622 | uint64_t : NumFunctionDeclBits; |
1623 | |
1624 | /// 24 bits to fit in the remaining available space. |
1625 | /// Note that this makes CXXConstructorDeclBitfields take |
1626 | /// exactly 64 bits and thus the width of NumCtorInitializers |
1627 | /// will need to be shrunk if some bit is added to NumDeclContextBitfields, |
1628 | /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields. |
1629 | uint64_t NumCtorInitializers : 21; |
1630 | uint64_t IsInheritingConstructor : 1; |
1631 | |
1632 | /// Whether this constructor has a trail-allocated explicit specifier. |
1633 | uint64_t HasTrailingExplicitSpecifier : 1; |
1634 | /// If this constructor does't have a trail-allocated explicit specifier. |
1635 | /// Whether this constructor is explicit specified. |
1636 | uint64_t IsSimpleExplicit : 1; |
1637 | }; |
1638 | |
1639 | /// Number of non-inherited bits in CXXConstructorDeclBitfields. |
1640 | enum { |
1641 | NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits |
1642 | }; |
1643 | |
1644 | /// Stores the bits used by ObjCMethodDecl. |
1645 | /// If modified NumObjCMethodDeclBits and the accessor |
1646 | /// methods in ObjCMethodDecl should be updated appropriately. |
1647 | class ObjCMethodDeclBitfields { |
1648 | friend class ObjCMethodDecl; |
1649 | |
1650 | /// For the bits in DeclContextBitfields. |
1651 | uint64_t : NumDeclContextBits; |
1652 | |
1653 | /// The conventional meaning of this method; an ObjCMethodFamily. |
1654 | /// This is not serialized; instead, it is computed on demand and |
1655 | /// cached. |
1656 | mutable uint64_t Family : ObjCMethodFamilyBitWidth; |
1657 | |
1658 | /// instance (true) or class (false) method. |
1659 | uint64_t IsInstance : 1; |
1660 | uint64_t IsVariadic : 1; |
1661 | |
1662 | /// True if this method is the getter or setter for an explicit property. |
1663 | uint64_t IsPropertyAccessor : 1; |
1664 | |
1665 | /// True if this method is a synthesized property accessor stub. |
1666 | uint64_t IsSynthesizedAccessorStub : 1; |
1667 | |
1668 | /// Method has a definition. |
1669 | uint64_t IsDefined : 1; |
1670 | |
1671 | /// Method redeclaration in the same interface. |
1672 | uint64_t IsRedeclaration : 1; |
1673 | |
1674 | /// Is redeclared in the same interface. |
1675 | mutable uint64_t HasRedeclaration : 1; |
1676 | |
1677 | /// \@required/\@optional |
1678 | uint64_t DeclImplementation : 2; |
1679 | |
1680 | /// in, inout, etc. |
1681 | uint64_t objcDeclQualifier : 7; |
1682 | |
1683 | /// Indicates whether this method has a related result type. |
1684 | uint64_t RelatedResultType : 1; |
1685 | |
1686 | /// Whether the locations of the selector identifiers are in a |
1687 | /// "standard" position, a enum SelectorLocationsKind. |
1688 | uint64_t SelLocsKind : 2; |
1689 | |
1690 | /// Whether this method overrides any other in the class hierarchy. |
1691 | /// |
1692 | /// A method is said to override any method in the class's |
1693 | /// base classes, its protocols, or its categories' protocols, that has |
1694 | /// the same selector and is of the same kind (class or instance). |
1695 | /// A method in an implementation is not considered as overriding the same |
1696 | /// method in the interface or its categories. |
1697 | uint64_t IsOverriding : 1; |
1698 | |
1699 | /// Indicates if the method was a definition but its body was skipped. |
1700 | uint64_t HasSkippedBody : 1; |
1701 | }; |
1702 | |
1703 | /// Number of non-inherited bits in ObjCMethodDeclBitfields. |
1704 | enum { NumObjCMethodDeclBits = 24 }; |
1705 | |
1706 | /// Stores the bits used by ObjCContainerDecl. |
1707 | /// If modified NumObjCContainerDeclBits and the accessor |
1708 | /// methods in ObjCContainerDecl should be updated appropriately. |
1709 | class ObjCContainerDeclBitfields { |
1710 | friend class ObjCContainerDecl; |
1711 | /// For the bits in DeclContextBitfields |
1712 | uint32_t : NumDeclContextBits; |
1713 | |
1714 | // Not a bitfield but this saves space. |
1715 | // Note that ObjCContainerDeclBitfields is full. |
1716 | SourceLocation AtStart; |
1717 | }; |
1718 | |
1719 | /// Number of non-inherited bits in ObjCContainerDeclBitfields. |
1720 | /// Note that here we rely on the fact that SourceLocation is 32 bits |
1721 | /// wide. We check this with the static_assert in the ctor of DeclContext. |
1722 | enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits }; |
1723 | |
1724 | /// Stores the bits used by LinkageSpecDecl. |
1725 | /// If modified NumLinkageSpecDeclBits and the accessor |
1726 | /// methods in LinkageSpecDecl should be updated appropriately. |
1727 | class LinkageSpecDeclBitfields { |
1728 | friend class LinkageSpecDecl; |
1729 | /// For the bits in DeclContextBitfields. |
1730 | uint64_t : NumDeclContextBits; |
1731 | |
1732 | /// The language for this linkage specification with values |
1733 | /// in the enum LinkageSpecDecl::LanguageIDs. |
1734 | uint64_t Language : 3; |
1735 | |
1736 | /// True if this linkage spec has braces. |
1737 | /// This is needed so that hasBraces() returns the correct result while the |
1738 | /// linkage spec body is being parsed. Once RBraceLoc has been set this is |
1739 | /// not used, so it doesn't need to be serialized. |
1740 | uint64_t HasBraces : 1; |
1741 | }; |
1742 | |
1743 | /// Number of non-inherited bits in LinkageSpecDeclBitfields. |
1744 | enum { NumLinkageSpecDeclBits = 4 }; |
1745 | |
1746 | /// Stores the bits used by BlockDecl. |
1747 | /// If modified NumBlockDeclBits and the accessor |
1748 | /// methods in BlockDecl should be updated appropriately. |
1749 | class BlockDeclBitfields { |
1750 | friend class BlockDecl; |
1751 | /// For the bits in DeclContextBitfields. |
1752 | uint64_t : NumDeclContextBits; |
1753 | |
1754 | uint64_t IsVariadic : 1; |
1755 | uint64_t CapturesCXXThis : 1; |
1756 | uint64_t BlockMissingReturnType : 1; |
1757 | uint64_t IsConversionFromLambda : 1; |
1758 | |
1759 | /// A bit that indicates this block is passed directly to a function as a |
1760 | /// non-escaping parameter. |
1761 | uint64_t DoesNotEscape : 1; |
1762 | |
1763 | /// A bit that indicates whether it's possible to avoid coying this block to |
1764 | /// the heap when it initializes or is assigned to a local variable with |
1765 | /// automatic storage. |
1766 | uint64_t CanAvoidCopyToHeap : 1; |
1767 | }; |
1768 | |
1769 | /// Number of non-inherited bits in BlockDeclBitfields. |
1770 | enum { NumBlockDeclBits = 5 }; |
1771 | |
1772 | /// Pointer to the data structure used to lookup declarations |
1773 | /// within this context (or a DependentStoredDeclsMap if this is a |
1774 | /// dependent context). We maintain the invariant that, if the map |
1775 | /// contains an entry for a DeclarationName (and we haven't lazily |
1776 | /// omitted anything), then it contains all relevant entries for that |
1777 | /// name (modulo the hasExternalDecls() flag). |
1778 | mutable StoredDeclsMap *LookupPtr = nullptr; |
1779 | |
1780 | protected: |
1781 | /// This anonymous union stores the bits belonging to DeclContext and classes |
1782 | /// deriving from it. The goal is to use otherwise wasted |
1783 | /// space in DeclContext to store data belonging to derived classes. |
1784 | /// The space saved is especially significient when pointers are aligned |
1785 | /// to 8 bytes. In this case due to alignment requirements we have a |
1786 | /// little less than 8 bytes free in DeclContext which we can use. |
1787 | /// We check that none of the classes in this union is larger than |
1788 | /// 8 bytes with static_asserts in the ctor of DeclContext. |
1789 | union { |
1790 | DeclContextBitfields DeclContextBits; |
1791 | TagDeclBitfields TagDeclBits; |
1792 | EnumDeclBitfields EnumDeclBits; |
1793 | RecordDeclBitfields RecordDeclBits; |
1794 | OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits; |
1795 | FunctionDeclBitfields FunctionDeclBits; |
1796 | CXXConstructorDeclBitfields CXXConstructorDeclBits; |
1797 | ObjCMethodDeclBitfields ObjCMethodDeclBits; |
1798 | ObjCContainerDeclBitfields ObjCContainerDeclBits; |
1799 | LinkageSpecDeclBitfields LinkageSpecDeclBits; |
1800 | BlockDeclBitfields BlockDeclBits; |
1801 | |
1802 | static_assert(sizeof(DeclContextBitfields) <= 8, |
1803 | "DeclContextBitfields is larger than 8 bytes!"); |
1804 | static_assert(sizeof(TagDeclBitfields) <= 8, |
1805 | "TagDeclBitfields is larger than 8 bytes!"); |
1806 | static_assert(sizeof(EnumDeclBitfields) <= 8, |
1807 | "EnumDeclBitfields is larger than 8 bytes!"); |
1808 | static_assert(sizeof(RecordDeclBitfields) <= 8, |
1809 | "RecordDeclBitfields is larger than 8 bytes!"); |
1810 | static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8, |
1811 | "OMPDeclareReductionDeclBitfields is larger than 8 bytes!"); |
1812 | static_assert(sizeof(FunctionDeclBitfields) <= 8, |
1813 | "FunctionDeclBitfields is larger than 8 bytes!"); |
1814 | static_assert(sizeof(CXXConstructorDeclBitfields) <= 8, |
1815 | "CXXConstructorDeclBitfields is larger than 8 bytes!"); |
1816 | static_assert(sizeof(ObjCMethodDeclBitfields) <= 8, |
1817 | "ObjCMethodDeclBitfields is larger than 8 bytes!"); |
1818 | static_assert(sizeof(ObjCContainerDeclBitfields) <= 8, |
1819 | "ObjCContainerDeclBitfields is larger than 8 bytes!"); |
1820 | static_assert(sizeof(LinkageSpecDeclBitfields) <= 8, |
1821 | "LinkageSpecDeclBitfields is larger than 8 bytes!"); |
1822 | static_assert(sizeof(BlockDeclBitfields) <= 8, |
1823 | "BlockDeclBitfields is larger than 8 bytes!"); |
1824 | }; |
1825 | |
1826 | /// FirstDecl - The first declaration stored within this declaration |
1827 | /// context. |
1828 | mutable Decl *FirstDecl = nullptr; |
1829 | |
1830 | /// LastDecl - The last declaration stored within this declaration |
1831 | /// context. FIXME: We could probably cache this value somewhere |
1832 | /// outside of the DeclContext, to reduce the size of DeclContext by |
1833 | /// another pointer. |
1834 | mutable Decl *LastDecl = nullptr; |
1835 | |
1836 | /// Build up a chain of declarations. |
1837 | /// |
1838 | /// \returns the first/last pair of declarations. |
1839 | static std::pair<Decl *, Decl *> |
1840 | BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded); |
1841 | |
1842 | DeclContext(Decl::Kind K); |
1843 | |
1844 | public: |
1845 | ~DeclContext(); |
1846 | |
1847 | Decl::Kind getDeclKind() const { |
1848 | return static_cast<Decl::Kind>(DeclContextBits.DeclKind); |
1849 | } |
1850 | |
1851 | const char *getDeclKindName() const; |
1852 | |
1853 | /// getParent - Returns the containing DeclContext. |
1854 | DeclContext *getParent() { |
1855 | return cast<Decl>(this)->getDeclContext(); |
1856 | } |
1857 | const DeclContext *getParent() const { |
1858 | return const_cast<DeclContext*>(this)->getParent(); |
1859 | } |
1860 | |
1861 | /// getLexicalParent - Returns the containing lexical DeclContext. May be |
1862 | /// different from getParent, e.g.: |
1863 | /// |
1864 | /// namespace A { |
1865 | /// struct S; |
1866 | /// } |
1867 | /// struct A::S {}; // getParent() == namespace 'A' |
1868 | /// // getLexicalParent() == translation unit |
1869 | /// |
1870 | DeclContext *getLexicalParent() { |
1871 | return cast<Decl>(this)->getLexicalDeclContext(); |
1872 | } |
1873 | const DeclContext *getLexicalParent() const { |
1874 | return const_cast<DeclContext*>(this)->getLexicalParent(); |
1875 | } |
1876 | |
1877 | DeclContext *getLookupParent(); |
1878 | |
1879 | const DeclContext *getLookupParent() const { |
1880 | return const_cast<DeclContext*>(this)->getLookupParent(); |
1881 | } |
1882 | |
1883 | ASTContext &getParentASTContext() const { |
1884 | return cast<Decl>(this)->getASTContext(); |
1885 | } |
1886 | |
1887 | bool isClosure() const { return getDeclKind() == Decl::Block; } |
1888 | |
1889 | /// Return this DeclContext if it is a BlockDecl. Otherwise, return the |
1890 | /// innermost enclosing BlockDecl or null if there are no enclosing blocks. |
1891 | const BlockDecl *getInnermostBlockDecl() const; |
1892 | |
1893 | bool isObjCContainer() const { |
1894 | switch (getDeclKind()) { |
1895 | case Decl::ObjCCategory: |
1896 | case Decl::ObjCCategoryImpl: |
1897 | case Decl::ObjCImplementation: |
1898 | case Decl::ObjCInterface: |
1899 | case Decl::ObjCProtocol: |
1900 | return true; |
1901 | default: |
1902 | return false; |
1903 | } |
1904 | } |
1905 | |
1906 | bool isFunctionOrMethod() const { |
1907 | switch (getDeclKind()) { |
1908 | case Decl::Block: |
1909 | case Decl::Captured: |
1910 | case Decl::ObjCMethod: |
1911 | return true; |
1912 | default: |
1913 | return getDeclKind() >= Decl::firstFunction && |
1914 | getDeclKind() <= Decl::lastFunction; |
1915 | } |
1916 | } |
1917 | |
1918 | /// Test whether the context supports looking up names. |
1919 | bool isLookupContext() const { |
1920 | return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec && |
1921 | getDeclKind() != Decl::Export; |
1922 | } |
1923 | |
1924 | bool isFileContext() const { |
1925 | return getDeclKind() == Decl::TranslationUnit || |
1926 | getDeclKind() == Decl::Namespace; |
1927 | } |
1928 | |
1929 | bool isTranslationUnit() const { |
1930 | return getDeclKind() == Decl::TranslationUnit; |
1931 | } |
1932 | |
1933 | bool isRecord() const { |
1934 | return getDeclKind() >= Decl::firstRecord && |
1935 | getDeclKind() <= Decl::lastRecord; |
1936 | } |
1937 | |
1938 | bool isNamespace() const { return getDeclKind() == Decl::Namespace; } |
1939 | |
1940 | bool isStdNamespace() const; |
1941 | |
1942 | bool isInlineNamespace() const; |
1943 | |
1944 | /// Determines whether this context is dependent on a |
1945 | /// template parameter. |
1946 | bool isDependentContext() const; |
1947 | |
1948 | /// isTransparentContext - Determines whether this context is a |
1949 | /// "transparent" context, meaning that the members declared in this |
1950 | /// context are semantically declared in the nearest enclosing |
1951 | /// non-transparent (opaque) context but are lexically declared in |
1952 | /// this context. For example, consider the enumerators of an |
1953 | /// enumeration type: |
1954 | /// @code |
1955 | /// enum E { |
1956 | /// Val1 |
1957 | /// }; |
1958 | /// @endcode |
1959 | /// Here, E is a transparent context, so its enumerator (Val1) will |
1960 | /// appear (semantically) that it is in the same context of E. |
1961 | /// Examples of transparent contexts include: enumerations (except for |
1962 | /// C++0x scoped enums), and C++ linkage specifications. |
1963 | bool isTransparentContext() const; |
1964 | |
1965 | /// Determines whether this context or some of its ancestors is a |
1966 | /// linkage specification context that specifies C linkage. |
1967 | bool isExternCContext() const; |
1968 | |
1969 | /// Retrieve the nearest enclosing C linkage specification context. |
1970 | const LinkageSpecDecl *getExternCContext() const; |
1971 | |
1972 | /// Determines whether this context or some of its ancestors is a |
1973 | /// linkage specification context that specifies C++ linkage. |
1974 | bool isExternCXXContext() const; |
1975 | |
1976 | /// Determine whether this declaration context is equivalent |
1977 | /// to the declaration context DC. |
1978 | bool Equals(const DeclContext *DC) const { |
1979 | return DC && this->getPrimaryContext() == DC->getPrimaryContext(); |
1980 | } |
1981 | |
1982 | /// Determine whether this declaration context encloses the |
1983 | /// declaration context DC. |
1984 | bool Encloses(const DeclContext *DC) const; |
1985 | |
1986 | /// Find the nearest non-closure ancestor of this context, |
1987 | /// i.e. the innermost semantic parent of this context which is not |
1988 | /// a closure. A context may be its own non-closure ancestor. |
1989 | Decl *getNonClosureAncestor(); |
1990 | const Decl *getNonClosureAncestor() const { |
1991 | return const_cast<DeclContext*>(this)->getNonClosureAncestor(); |
1992 | } |
1993 | |
1994 | // Retrieve the nearest context that is not a transparent context. |
1995 | DeclContext *getNonTransparentContext(); |
1996 | const DeclContext *getNonTransparentContext() const { |
1997 | return const_cast<DeclContext *>(this)->getNonTransparentContext(); |
1998 | } |
1999 | |
2000 | /// getPrimaryContext - There may be many different |
2001 | /// declarations of the same entity (including forward declarations |
2002 | /// of classes, multiple definitions of namespaces, etc.), each with |
2003 | /// a different set of declarations. This routine returns the |
2004 | /// "primary" DeclContext structure, which will contain the |
2005 | /// information needed to perform name lookup into this context. |
2006 | DeclContext *getPrimaryContext(); |
2007 | const DeclContext *getPrimaryContext() const { |
2008 | return const_cast<DeclContext*>(this)->getPrimaryContext(); |
2009 | } |
2010 | |
2011 | /// getRedeclContext - Retrieve the context in which an entity conflicts with |
2012 | /// other entities of the same name, or where it is a redeclaration if the |
2013 | /// two entities are compatible. This skips through transparent contexts. |
2014 | DeclContext *getRedeclContext(); |
2015 | const DeclContext *getRedeclContext() const { |
2016 | return const_cast<DeclContext *>(this)->getRedeclContext(); |
2017 | } |
2018 | |
2019 | /// Retrieve the nearest enclosing namespace context. |
2020 | DeclContext *getEnclosingNamespaceContext(); |
2021 | const DeclContext *getEnclosingNamespaceContext() const { |
2022 | return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext(); |
2023 | } |
2024 | |
2025 | /// Retrieve the outermost lexically enclosing record context. |
2026 | RecordDecl *getOuterLexicalRecordContext(); |
2027 | const RecordDecl *getOuterLexicalRecordContext() const { |
2028 | return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext(); |
2029 | } |
2030 | |
2031 | /// Test if this context is part of the enclosing namespace set of |
2032 | /// the context NS, as defined in C++0x [namespace.def]p9. If either context |
2033 | /// isn't a namespace, this is equivalent to Equals(). |
2034 | /// |
2035 | /// The enclosing namespace set of a namespace is the namespace and, if it is |
2036 | /// inline, its enclosing namespace, recursively. |
2037 | bool InEnclosingNamespaceSetOf(const DeclContext *NS) const; |
2038 | |
2039 | /// Collects all of the declaration contexts that are semantically |
2040 | /// connected to this declaration context. |
2041 | /// |
2042 | /// For declaration contexts that have multiple semantically connected but |
2043 | /// syntactically distinct contexts, such as C++ namespaces, this routine |
2044 | /// retrieves the complete set of such declaration contexts in source order. |
2045 | /// For example, given: |
2046 | /// |
2047 | /// \code |
2048 | /// namespace N { |
2049 | /// int x; |
2050 | /// } |
2051 | /// namespace N { |
2052 | /// int y; |
2053 | /// } |
2054 | /// \endcode |
2055 | /// |
2056 | /// The \c Contexts parameter will contain both definitions of N. |
2057 | /// |
2058 | /// \param Contexts Will be cleared and set to the set of declaration |
2059 | /// contexts that are semanticaly connected to this declaration context, |
2060 | /// in source order, including this context (which may be the only result, |
2061 | /// for non-namespace contexts). |
2062 | void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts); |
2063 | |
2064 | /// decl_iterator - Iterates through the declarations stored |
2065 | /// within this context. |
2066 | class decl_iterator { |
2067 | /// Current - The current declaration. |
2068 | Decl *Current = nullptr; |
2069 | |
2070 | public: |
2071 | using value_type = Decl *; |
2072 | using reference = const value_type &; |
2073 | using pointer = const value_type *; |
2074 | using iterator_category = std::forward_iterator_tag; |
2075 | using difference_type = std::ptrdiff_t; |
2076 | |
2077 | decl_iterator() = default; |
2078 | explicit decl_iterator(Decl *C) : Current(C) {} |
2079 | |
2080 | reference operator*() const { return Current; } |
2081 | |
2082 | // This doesn't meet the iterator requirements, but it's convenient |
2083 | value_type operator->() const { return Current; } |
2084 | |
2085 | decl_iterator& operator++() { |
2086 | Current = Current->getNextDeclInContext(); |
2087 | return *this; |
2088 | } |
2089 | |
2090 | decl_iterator operator++(int) { |
2091 | decl_iterator tmp(*this); |
2092 | ++(*this); |
2093 | return tmp; |
2094 | } |
2095 | |
2096 | friend bool operator==(decl_iterator x, decl_iterator y) { |
2097 | return x.Current == y.Current; |
2098 | } |
2099 | |
2100 | friend bool operator!=(decl_iterator x, decl_iterator y) { |
2101 | return x.Current != y.Current; |
2102 | } |
2103 | }; |
2104 | |
2105 | using decl_range = llvm::iterator_range<decl_iterator>; |
2106 | |
2107 | /// decls_begin/decls_end - Iterate over the declarations stored in |
2108 | /// this context. |
2109 | decl_range decls() const { return decl_range(decls_begin(), decls_end()); } |
2110 | decl_iterator decls_begin() const; |
2111 | decl_iterator decls_end() const { return decl_iterator(); } |
2112 | bool decls_empty() const; |
2113 | |
2114 | /// noload_decls_begin/end - Iterate over the declarations stored in this |
2115 | /// context that are currently loaded; don't attempt to retrieve anything |
2116 | /// from an external source. |
2117 | decl_range noload_decls() const { |
2118 | return decl_range(noload_decls_begin(), noload_decls_end()); |
2119 | } |
2120 | decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); } |
2121 | decl_iterator noload_decls_end() const { return decl_iterator(); } |
2122 | |
2123 | /// specific_decl_iterator - Iterates over a subrange of |
2124 | /// declarations stored in a DeclContext, providing only those that |
2125 | /// are of type SpecificDecl (or a class derived from it). This |
2126 | /// iterator is used, for example, to provide iteration over just |
2127 | /// the fields within a RecordDecl (with SpecificDecl = FieldDecl). |
2128 | template<typename SpecificDecl> |
2129 | class specific_decl_iterator { |
2130 | /// Current - The current, underlying declaration iterator, which |
2131 | /// will either be NULL or will point to a declaration of |
2132 | /// type SpecificDecl. |
2133 | DeclContext::decl_iterator Current; |
2134 | |
2135 | /// SkipToNextDecl - Advances the current position up to the next |
2136 | /// declaration of type SpecificDecl that also meets the criteria |
2137 | /// required by Acceptable. |
2138 | void SkipToNextDecl() { |
2139 | while (*Current && !isa<SpecificDecl>(*Current)) |
2140 | ++Current; |
2141 | } |
2142 | |
2143 | public: |
2144 | using value_type = SpecificDecl *; |
2145 | // TODO: Add reference and pointer types (with some appropriate proxy type) |
2146 | // if we ever have a need for them. |
2147 | using reference = void; |
2148 | using pointer = void; |
2149 | using difference_type = |
2150 | std::iterator_traits<DeclContext::decl_iterator>::difference_type; |
2151 | using iterator_category = std::forward_iterator_tag; |
2152 | |
2153 | specific_decl_iterator() = default; |
2154 | |
2155 | /// specific_decl_iterator - Construct a new iterator over a |
2156 | /// subset of the declarations the range [C, |
2157 | /// end-of-declarations). If A is non-NULL, it is a pointer to a |
2158 | /// member function of SpecificDecl that should return true for |
2159 | /// all of the SpecificDecl instances that will be in the subset |
2160 | /// of iterators. For example, if you want Objective-C instance |
2161 | /// methods, SpecificDecl will be ObjCMethodDecl and A will be |
2162 | /// &ObjCMethodDecl::isInstanceMethod. |
2163 | explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) { |
2164 | SkipToNextDecl(); |
2165 | } |
2166 | |
2167 | value_type operator*() const { return cast<SpecificDecl>(*Current); } |
2168 | |
2169 | // This doesn't meet the iterator requirements, but it's convenient |
2170 | value_type operator->() const { return **this; } |
2171 | |
2172 | specific_decl_iterator& operator++() { |
2173 | ++Current; |
2174 | SkipToNextDecl(); |
2175 | return *this; |
2176 | } |
2177 | |
2178 | specific_decl_iterator operator++(int) { |
2179 | specific_decl_iterator tmp(*this); |
2180 | ++(*this); |
2181 | return tmp; |
2182 | } |
2183 | |
2184 | friend bool operator==(const specific_decl_iterator& x, |
2185 | const specific_decl_iterator& y) { |
2186 | return x.Current == y.Current; |
2187 | } |
2188 | |
2189 | friend bool operator!=(const specific_decl_iterator& x, |
2190 | const specific_decl_iterator& y) { |
2191 | return x.Current != y.Current; |
2192 | } |
2193 | }; |
2194 | |
2195 | /// Iterates over a filtered subrange of declarations stored |
2196 | /// in a DeclContext. |
2197 | /// |
2198 | /// This iterator visits only those declarations that are of type |
2199 | /// SpecificDecl (or a class derived from it) and that meet some |
2200 | /// additional run-time criteria. This iterator is used, for |
2201 | /// example, to provide access to the instance methods within an |
2202 | /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and |
2203 | /// Acceptable = ObjCMethodDecl::isInstanceMethod). |
2204 | template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const> |
2205 | class filtered_decl_iterator { |
2206 | /// Current - The current, underlying declaration iterator, which |
2207 | /// will either be NULL or will point to a declaration of |
2208 | /// type SpecificDecl. |
2209 | DeclContext::decl_iterator Current; |
2210 | |
2211 | /// SkipToNextDecl - Advances the current position up to the next |
2212 | /// declaration of type SpecificDecl that also meets the criteria |
2213 | /// required by Acceptable. |
2214 | void SkipToNextDecl() { |
2215 | while (*Current && |
2216 | (!isa<SpecificDecl>(*Current) || |
2217 | (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)()))) |
2218 | ++Current; |
2219 | } |
2220 | |
2221 | public: |
2222 | using value_type = SpecificDecl *; |
2223 | // TODO: Add reference and pointer types (with some appropriate proxy type) |
2224 | // if we ever have a need for them. |
2225 | using reference = void; |
2226 | using pointer = void; |
2227 | using difference_type = |
2228 | std::iterator_traits<DeclContext::decl_iterator>::difference_type; |
2229 | using iterator_category = std::forward_iterator_tag; |
2230 | |
2231 | filtered_decl_iterator() = default; |
2232 | |
2233 | /// filtered_decl_iterator - Construct a new iterator over a |
2234 | /// subset of the declarations the range [C, |
2235 | /// end-of-declarations). If A is non-NULL, it is a pointer to a |
2236 | /// member function of SpecificDecl that should return true for |
2237 | /// all of the SpecificDecl instances that will be in the subset |
2238 | /// of iterators. For example, if you want Objective-C instance |
2239 | /// methods, SpecificDecl will be ObjCMethodDecl and A will be |
2240 | /// &ObjCMethodDecl::isInstanceMethod. |
2241 | explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) { |
2242 | SkipToNextDecl(); |
2243 | } |
2244 | |
2245 | value_type operator*() const { return cast<SpecificDecl>(*Current); } |
2246 | value_type operator->() const { return cast<SpecificDecl>(*Current); } |
2247 | |
2248 | filtered_decl_iterator& operator++() { |
2249 | ++Current; |
2250 | SkipToNextDecl(); |
2251 | return *this; |
2252 | } |
2253 | |
2254 | filtered_decl_iterator operator++(int) { |
2255 | filtered_decl_iterator tmp(*this); |
2256 | ++(*this); |
2257 | return tmp; |
2258 | } |
2259 | |
2260 | friend bool operator==(const filtered_decl_iterator& x, |
2261 | const filtered_decl_iterator& y) { |
2262 | return x.Current == y.Current; |
2263 | } |
2264 | |
2265 | friend bool operator!=(const filtered_decl_iterator& x, |
2266 | const filtered_decl_iterator& y) { |
2267 | return x.Current != y.Current; |
2268 | } |
2269 | }; |
2270 | |
2271 | /// Add the declaration D into this context. |
2272 | /// |
2273 | /// This routine should be invoked when the declaration D has first |
2274 | /// been declared, to place D into the context where it was |
2275 | /// (lexically) defined. Every declaration must be added to one |
2276 | /// (and only one!) context, where it can be visited via |
2277 | /// [decls_begin(), decls_end()). Once a declaration has been added |
2278 | /// to its lexical context, the corresponding DeclContext owns the |
2279 | /// declaration. |
2280 | /// |
2281 | /// If D is also a NamedDecl, it will be made visible within its |
2282 | /// semantic context via makeDeclVisibleInContext. |
2283 | void addDecl(Decl *D); |
2284 | |
2285 | /// Add the declaration D into this context, but suppress |
2286 | /// searches for external declarations with the same name. |
2287 | /// |
2288 | /// Although analogous in function to addDecl, this removes an |
2289 | /// important check. This is only useful if the Decl is being |
2290 | /// added in response to an external search; in all other cases, |
2291 | /// addDecl() is the right function to use. |
2292 | /// See the ASTImporter for use cases. |
2293 | void addDeclInternal(Decl *D); |
2294 | |
2295 | /// Add the declaration D to this context without modifying |
2296 | /// any lookup tables. |
2297 | /// |
2298 | /// This is useful for some operations in dependent contexts where |
2299 | /// the semantic context might not be dependent; this basically |
2300 | /// only happens with friends. |
2301 | void addHiddenDecl(Decl *D); |
2302 | |
2303 | /// Removes a declaration from this context. |
2304 | void removeDecl(Decl *D); |
2305 | |
2306 | /// Checks whether a declaration is in this context. |
2307 | bool containsDecl(Decl *D) const; |
2308 | |
2309 | /// Checks whether a declaration is in this context. |
2310 | /// This also loads the Decls from the external source before the check. |
2311 | bool containsDeclAndLoad(Decl *D) const; |
2312 | |
2313 | using lookup_result = DeclContextLookupResult; |
2314 | using lookup_iterator = lookup_result::iterator; |
2315 | |
2316 | /// lookup - Find the declarations (if any) with the given Name in |
2317 | /// this context. Returns a range of iterators that contains all of |
2318 | /// the declarations with this name, with object, function, member, |
2319 | /// and enumerator names preceding any tag name. Note that this |
2320 | /// routine will not look into parent contexts. |
2321 | lookup_result lookup(DeclarationName Name) const; |
2322 | |
2323 | /// Find the declarations with the given name that are visible |
2324 | /// within this context; don't attempt to retrieve anything from an |
2325 | /// external source. |
2326 | lookup_result noload_lookup(DeclarationName Name); |
2327 | |
2328 | /// A simplistic name lookup mechanism that performs name lookup |
2329 | /// into this declaration context without consulting the external source. |
2330 | /// |
2331 | /// This function should almost never be used, because it subverts the |
2332 | /// usual relationship between a DeclContext and the external source. |
2333 | /// See the ASTImporter for the (few, but important) use cases. |
2334 | /// |
2335 | /// FIXME: This is very inefficient; replace uses of it with uses of |
2336 | /// noload_lookup. |
2337 | void localUncachedLookup(DeclarationName Name, |
2338 | SmallVectorImpl<NamedDecl *> &Results); |
2339 | |
2340 | /// Makes a declaration visible within this context. |
2341 | /// |
2342 | /// This routine makes the declaration D visible to name lookup |
2343 | /// within this context and, if this is a transparent context, |
2344 | /// within its parent contexts up to the first enclosing |
2345 | /// non-transparent context. Making a declaration visible within a |
2346 | /// context does not transfer ownership of a declaration, and a |
2347 | /// declaration can be visible in many contexts that aren't its |
2348 | /// lexical context. |
2349 | /// |
2350 | /// If D is a redeclaration of an existing declaration that is |
2351 | /// visible from this context, as determined by |
2352 | /// NamedDecl::declarationReplaces, the previous declaration will be |
2353 | /// replaced with D. |
2354 | void makeDeclVisibleInContext(NamedDecl *D); |
2355 | |
2356 | /// all_lookups_iterator - An iterator that provides a view over the results |
2357 | /// of looking up every possible name. |
2358 | class all_lookups_iterator; |
2359 | |
2360 | using lookups_range = llvm::iterator_range<all_lookups_iterator>; |
2361 | |
2362 | lookups_range lookups() const; |
2363 | // Like lookups(), but avoids loading external declarations. |
2364 | // If PreserveInternalState, avoids building lookup data structures too. |
2365 | lookups_range noload_lookups(bool PreserveInternalState) const; |
2366 | |
2367 | /// Iterators over all possible lookups within this context. |
2368 | all_lookups_iterator lookups_begin() const; |
2369 | all_lookups_iterator lookups_end() const; |
2370 | |
2371 | /// Iterators over all possible lookups within this context that are |
2372 | /// currently loaded; don't attempt to retrieve anything from an external |
2373 | /// source. |
2374 | all_lookups_iterator noload_lookups_begin() const; |
2375 | all_lookups_iterator noload_lookups_end() const; |
2376 | |
2377 | struct udir_iterator; |
2378 | |
2379 | using udir_iterator_base = |
2380 | llvm::iterator_adaptor_base<udir_iterator, lookup_iterator, |
2381 | typename lookup_iterator::iterator_category, |
2382 | UsingDirectiveDecl *>; |
2383 | |
2384 | struct udir_iterator : udir_iterator_base { |
2385 | udir_iterator(lookup_iterator I) : udir_iterator_base(I) {} |
2386 | |
2387 | UsingDirectiveDecl *operator*() const; |
2388 | }; |
2389 | |
2390 | using udir_range = llvm::iterator_range<udir_iterator>; |
2391 | |
2392 | udir_range using_directives() const; |
2393 | |
2394 | // These are all defined in DependentDiagnostic.h. |
2395 | class ddiag_iterator; |
2396 | |
2397 | using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>; |
2398 | |
2399 | inline ddiag_range ddiags() const; |
2400 | |
2401 | // Low-level accessors |
2402 | |
2403 | /// Mark that there are external lexical declarations that we need |
2404 | /// to include in our lookup table (and that are not available as external |
2405 | /// visible lookups). These extra lookup results will be found by walking |
2406 | /// the lexical declarations of this context. This should be used only if |
2407 | /// setHasExternalLexicalStorage() has been called on any decl context for |
2408 | /// which this is the primary context. |
2409 | void setMustBuildLookupTable() { |
2410 | assert(this == getPrimaryContext() &&(static_cast <bool> (this == getPrimaryContext() && "should only be called on primary context") ? void (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\"" , "clang/include/clang/AST/DeclBase.h", 2411, __extension__ __PRETTY_FUNCTION__ )) |
2411 | "should only be called on primary context")(static_cast <bool> (this == getPrimaryContext() && "should only be called on primary context") ? void (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\"" , "clang/include/clang/AST/DeclBase.h", 2411, __extension__ __PRETTY_FUNCTION__ )); |
2412 | DeclContextBits.HasLazyExternalLexicalLookups = true; |
2413 | } |
2414 | |
2415 | /// Retrieve the internal representation of the lookup structure. |
2416 | /// This may omit some names if we are lazily building the structure. |
2417 | StoredDeclsMap *getLookupPtr() const { return LookupPtr; } |
2418 | |
2419 | /// Ensure the lookup structure is fully-built and return it. |
2420 | StoredDeclsMap *buildLookup(); |
2421 | |
2422 | /// Whether this DeclContext has external storage containing |
2423 | /// additional declarations that are lexically in this context. |
2424 | bool hasExternalLexicalStorage() const { |
2425 | return DeclContextBits.ExternalLexicalStorage; |
2426 | } |
2427 | |
2428 | /// State whether this DeclContext has external storage for |
2429 | /// declarations lexically in this context. |
2430 | void setHasExternalLexicalStorage(bool ES = true) const { |
2431 | DeclContextBits.ExternalLexicalStorage = ES; |
2432 | } |
2433 | |
2434 | /// Whether this DeclContext has external storage containing |
2435 | /// additional declarations that are visible in this context. |
2436 | bool hasExternalVisibleStorage() const { |
2437 | return DeclContextBits.ExternalVisibleStorage; |
2438 | } |
2439 | |
2440 | /// State whether this DeclContext has external storage for |
2441 | /// declarations visible in this context. |
2442 | void setHasExternalVisibleStorage(bool ES = true) const { |
2443 | DeclContextBits.ExternalVisibleStorage = ES; |
2444 | if (ES && LookupPtr) |
2445 | DeclContextBits.NeedToReconcileExternalVisibleStorage = true; |
2446 | } |
2447 | |
2448 | /// Determine whether the given declaration is stored in the list of |
2449 | /// declarations lexically within this context. |
2450 | bool isDeclInLexicalTraversal(const Decl *D) const { |
2451 | return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl || |
2452 | D == LastDecl); |
2453 | } |
2454 | |
2455 | bool setUseQualifiedLookup(bool use = true) const { |
2456 | bool old_value = DeclContextBits.UseQualifiedLookup; |
2457 | DeclContextBits.UseQualifiedLookup = use; |
2458 | return old_value; |
2459 | } |
2460 | |
2461 | bool shouldUseQualifiedLookup() const { |
2462 | return DeclContextBits.UseQualifiedLookup; |
2463 | } |
2464 | |
2465 | static bool classof(const Decl *D); |
2466 | static bool classof(const DeclContext *D) { return true; } |
2467 | |
2468 | void dumpDeclContext() const; |
2469 | void dumpLookups() const; |
2470 | void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false, |
2471 | bool Deserialize = false) const; |
2472 | |
2473 | private: |
2474 | /// Whether this declaration context has had externally visible |
2475 | /// storage added since the last lookup. In this case, \c LookupPtr's |
2476 | /// invariant may not hold and needs to be fixed before we perform |
2477 | /// another lookup. |
2478 | bool hasNeedToReconcileExternalVisibleStorage() const { |
2479 | return DeclContextBits.NeedToReconcileExternalVisibleStorage; |
2480 | } |
2481 | |
2482 | /// State that this declaration context has had externally visible |
2483 | /// storage added since the last lookup. In this case, \c LookupPtr's |
2484 | /// invariant may not hold and needs to be fixed before we perform |
2485 | /// another lookup. |
2486 | void setNeedToReconcileExternalVisibleStorage(bool Need = true) const { |
2487 | DeclContextBits.NeedToReconcileExternalVisibleStorage = Need; |
2488 | } |
2489 | |
2490 | /// If \c true, this context may have local lexical declarations |
2491 | /// that are missing from the lookup table. |
2492 | bool hasLazyLocalLexicalLookups() const { |
2493 | return DeclContextBits.HasLazyLocalLexicalLookups; |
2494 | } |
2495 | |
2496 | /// If \c true, this context may have local lexical declarations |
2497 | /// that are missing from the lookup table. |
2498 | void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const { |
2499 | DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL; |
2500 | } |
2501 | |
2502 | /// If \c true, the external source may have lexical declarations |
2503 | /// that are missing from the lookup table. |
2504 | bool hasLazyExternalLexicalLookups() const { |
2505 | return DeclContextBits.HasLazyExternalLexicalLookups; |
2506 | } |
2507 | |
2508 | /// If \c true, the external source may have lexical declarations |
2509 | /// that are missing from the lookup table. |
2510 | void setHasLazyExternalLexicalLookups(bool HasLELL = true) const { |
2511 | DeclContextBits.HasLazyExternalLexicalLookups = HasLELL; |
2512 | } |
2513 | |
2514 | void reconcileExternalVisibleStorage() const; |
2515 | bool LoadLexicalDeclsFromExternalStorage() const; |
2516 | |
2517 | /// Makes a declaration visible within this context, but |
2518 | /// suppresses searches for external declarations with the same |
2519 | /// name. |
2520 | /// |
2521 | /// Analogous to makeDeclVisibleInContext, but for the exclusive |
2522 | /// use of addDeclInternal(). |
2523 | void makeDeclVisibleInContextInternal(NamedDecl *D); |
2524 | |
2525 | StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const; |
2526 | |
2527 | void loadLazyLocalLexicalLookups(); |
2528 | void buildLookupImpl(DeclContext *DCtx, bool Internal); |
2529 | void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, |
2530 | bool Rediscoverable); |
2531 | void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal); |
2532 | }; |
2533 | |
2534 | inline bool Decl::isTemplateParameter() const { |
2535 | return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm || |
2536 | getKind() == TemplateTemplateParm; |
2537 | } |
2538 | |
2539 | // Specialization selected when ToTy is not a known subclass of DeclContext. |
2540 | template <class ToTy, |
2541 | bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value> |
2542 | struct cast_convert_decl_context { |
2543 | static const ToTy *doit(const DeclContext *Val) { |
2544 | return static_cast<const ToTy*>(Decl::castFromDeclContext(Val)); |
2545 | } |
2546 | |
2547 | static ToTy *doit(DeclContext *Val) { |
2548 | return static_cast<ToTy*>(Decl::castFromDeclContext(Val)); |
2549 | } |
2550 | }; |
2551 | |
2552 | // Specialization selected when ToTy is a known subclass of DeclContext. |
2553 | template <class ToTy> |
2554 | struct cast_convert_decl_context<ToTy, true> { |
2555 | static const ToTy *doit(const DeclContext *Val) { |
2556 | return static_cast<const ToTy*>(Val); |
2557 | } |
2558 | |
2559 | static ToTy *doit(DeclContext *Val) { |
2560 | return static_cast<ToTy*>(Val); |
2561 | } |
2562 | }; |
2563 | |
2564 | } // namespace clang |
2565 | |
2566 | namespace llvm { |
2567 | |
2568 | /// isa<T>(DeclContext*) |
2569 | template <typename To> |
2570 | struct isa_impl<To, ::clang::DeclContext> { |
2571 | static bool doit(const ::clang::DeclContext &Val) { |
2572 | return To::classofKind(Val.getDeclKind()); |
2573 | } |
2574 | }; |
2575 | |
2576 | /// cast<T>(DeclContext*) |
2577 | template<class ToTy> |
2578 | struct cast_convert_val<ToTy, |
2579 | const ::clang::DeclContext,const ::clang::DeclContext> { |
2580 | static const ToTy &doit(const ::clang::DeclContext &Val) { |
2581 | return *::clang::cast_convert_decl_context<ToTy>::doit(&Val); |
2582 | } |
2583 | }; |
2584 | |
2585 | template<class ToTy> |
2586 | struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> { |
2587 | static ToTy &doit(::clang::DeclContext &Val) { |
2588 | return *::clang::cast_convert_decl_context<ToTy>::doit(&Val); |
2589 | } |
2590 | }; |
2591 | |
2592 | template<class ToTy> |
2593 | struct cast_convert_val<ToTy, |
2594 | const ::clang::DeclContext*, const ::clang::DeclContext*> { |
2595 | static const ToTy *doit(const ::clang::DeclContext *Val) { |
2596 | return ::clang::cast_convert_decl_context<ToTy>::doit(Val); |
2597 | } |
2598 | }; |
2599 | |
2600 | template<class ToTy> |
2601 | struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> { |
2602 | static ToTy *doit(::clang::DeclContext *Val) { |
2603 | return ::clang::cast_convert_decl_context<ToTy>::doit(Val); |
2604 | } |
2605 | }; |
2606 | |
2607 | /// Implement cast_convert_val for Decl -> DeclContext conversions. |
2608 | template<class FromTy> |
2609 | struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> { |
2610 | static ::clang::DeclContext &doit(const FromTy &Val) { |
2611 | return *FromTy::castToDeclContext(&Val); |
2612 | } |
2613 | }; |
2614 | |
2615 | template<class FromTy> |
2616 | struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> { |
2617 | static ::clang::DeclContext *doit(const FromTy *Val) { |
2618 | return FromTy::castToDeclContext(Val); |
2619 | } |
2620 | }; |
2621 | |
2622 | template<class FromTy> |
2623 | struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> { |
2624 | static const ::clang::DeclContext &doit(const FromTy &Val) { |
2625 | return *FromTy::castToDeclContext(&Val); |
2626 | } |
2627 | }; |
2628 | |
2629 | template<class FromTy> |
2630 | struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> { |
2631 | static const ::clang::DeclContext *doit(const FromTy *Val) { |
2632 | return FromTy::castToDeclContext(Val); |
2633 | } |
2634 | }; |
2635 | |
2636 | } // namespace llvm |
2637 | |
2638 | #endif // LLVM_CLANG_AST_DECLBASE_H |