File: | tools/clang/lib/Sema/SemaDecl.cpp |
Warning: | line 12024, column 16 Called C++ object pointer is uninitialized |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file implements semantic analysis for declarations. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "TypeLocBuilder.h" | |||
14 | #include "clang/AST/ASTConsumer.h" | |||
15 | #include "clang/AST/ASTContext.h" | |||
16 | #include "clang/AST/ASTLambda.h" | |||
17 | #include "clang/AST/CXXInheritance.h" | |||
18 | #include "clang/AST/CharUnits.h" | |||
19 | #include "clang/AST/CommentDiagnostic.h" | |||
20 | #include "clang/AST/DeclCXX.h" | |||
21 | #include "clang/AST/DeclObjC.h" | |||
22 | #include "clang/AST/DeclTemplate.h" | |||
23 | #include "clang/AST/EvaluatedExprVisitor.h" | |||
24 | #include "clang/AST/ExprCXX.h" | |||
25 | #include "clang/AST/StmtCXX.h" | |||
26 | #include "clang/Basic/Builtins.h" | |||
27 | #include "clang/Basic/PartialDiagnostic.h" | |||
28 | #include "clang/Basic/SourceManager.h" | |||
29 | #include "clang/Basic/TargetInfo.h" | |||
30 | #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex | |||
31 | #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. | |||
32 | #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex | |||
33 | #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() | |||
34 | #include "clang/Sema/CXXFieldCollector.h" | |||
35 | #include "clang/Sema/DeclSpec.h" | |||
36 | #include "clang/Sema/DelayedDiagnostic.h" | |||
37 | #include "clang/Sema/Initialization.h" | |||
38 | #include "clang/Sema/Lookup.h" | |||
39 | #include "clang/Sema/ParsedTemplate.h" | |||
40 | #include "clang/Sema/Scope.h" | |||
41 | #include "clang/Sema/ScopeInfo.h" | |||
42 | #include "clang/Sema/SemaInternal.h" | |||
43 | #include "clang/Sema/Template.h" | |||
44 | #include "llvm/ADT/SmallString.h" | |||
45 | #include "llvm/ADT/Triple.h" | |||
46 | #include <algorithm> | |||
47 | #include <cstring> | |||
48 | #include <functional> | |||
49 | ||||
50 | using namespace clang; | |||
51 | using namespace sema; | |||
52 | ||||
53 | Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { | |||
54 | if (OwnedType) { | |||
55 | Decl *Group[2] = { OwnedType, Ptr }; | |||
56 | return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); | |||
57 | } | |||
58 | ||||
59 | return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); | |||
60 | } | |||
61 | ||||
62 | namespace { | |||
63 | ||||
64 | class TypeNameValidatorCCC final : public CorrectionCandidateCallback { | |||
65 | public: | |||
66 | TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, | |||
67 | bool AllowTemplates = false, | |||
68 | bool AllowNonTemplates = true) | |||
69 | : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), | |||
70 | AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { | |||
71 | WantExpressionKeywords = false; | |||
72 | WantCXXNamedCasts = false; | |||
73 | WantRemainingKeywords = false; | |||
74 | } | |||
75 | ||||
76 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
77 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | |||
78 | if (!AllowInvalidDecl && ND->isInvalidDecl()) | |||
79 | return false; | |||
80 | ||||
81 | if (getAsTypeTemplateDecl(ND)) | |||
82 | return AllowTemplates; | |||
83 | ||||
84 | bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); | |||
85 | if (!IsType) | |||
86 | return false; | |||
87 | ||||
88 | if (AllowNonTemplates) | |||
89 | return true; | |||
90 | ||||
91 | // An injected-class-name of a class template (specialization) is valid | |||
92 | // as a template or as a non-template. | |||
93 | if (AllowTemplates) { | |||
94 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | |||
95 | if (!RD || !RD->isInjectedClassName()) | |||
96 | return false; | |||
97 | RD = cast<CXXRecordDecl>(RD->getDeclContext()); | |||
98 | return RD->getDescribedClassTemplate() || | |||
99 | isa<ClassTemplateSpecializationDecl>(RD); | |||
100 | } | |||
101 | ||||
102 | return false; | |||
103 | } | |||
104 | ||||
105 | return !WantClassName && candidate.isKeyword(); | |||
106 | } | |||
107 | ||||
108 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
109 | return llvm::make_unique<TypeNameValidatorCCC>(*this); | |||
110 | } | |||
111 | ||||
112 | private: | |||
113 | bool AllowInvalidDecl; | |||
114 | bool WantClassName; | |||
115 | bool AllowTemplates; | |||
116 | bool AllowNonTemplates; | |||
117 | }; | |||
118 | ||||
119 | } // end anonymous namespace | |||
120 | ||||
121 | /// Determine whether the token kind starts a simple-type-specifier. | |||
122 | bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { | |||
123 | switch (Kind) { | |||
124 | // FIXME: Take into account the current language when deciding whether a | |||
125 | // token kind is a valid type specifier | |||
126 | case tok::kw_short: | |||
127 | case tok::kw_long: | |||
128 | case tok::kw___int64: | |||
129 | case tok::kw___int128: | |||
130 | case tok::kw_signed: | |||
131 | case tok::kw_unsigned: | |||
132 | case tok::kw_void: | |||
133 | case tok::kw_char: | |||
134 | case tok::kw_int: | |||
135 | case tok::kw_half: | |||
136 | case tok::kw_float: | |||
137 | case tok::kw_double: | |||
138 | case tok::kw__Float16: | |||
139 | case tok::kw___float128: | |||
140 | case tok::kw_wchar_t: | |||
141 | case tok::kw_bool: | |||
142 | case tok::kw___underlying_type: | |||
143 | case tok::kw___auto_type: | |||
144 | return true; | |||
145 | ||||
146 | case tok::annot_typename: | |||
147 | case tok::kw_char16_t: | |||
148 | case tok::kw_char32_t: | |||
149 | case tok::kw_typeof: | |||
150 | case tok::annot_decltype: | |||
151 | case tok::kw_decltype: | |||
152 | return getLangOpts().CPlusPlus; | |||
153 | ||||
154 | case tok::kw_char8_t: | |||
155 | return getLangOpts().Char8; | |||
156 | ||||
157 | default: | |||
158 | break; | |||
159 | } | |||
160 | ||||
161 | return false; | |||
162 | } | |||
163 | ||||
164 | namespace { | |||
165 | enum class UnqualifiedTypeNameLookupResult { | |||
166 | NotFound, | |||
167 | FoundNonType, | |||
168 | FoundType | |||
169 | }; | |||
170 | } // end anonymous namespace | |||
171 | ||||
172 | /// Tries to perform unqualified lookup of the type decls in bases for | |||
173 | /// dependent class. | |||
174 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a | |||
175 | /// type decl, \a FoundType if only type decls are found. | |||
176 | static UnqualifiedTypeNameLookupResult | |||
177 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, | |||
178 | SourceLocation NameLoc, | |||
179 | const CXXRecordDecl *RD) { | |||
180 | if (!RD->hasDefinition()) | |||
181 | return UnqualifiedTypeNameLookupResult::NotFound; | |||
182 | // Look for type decls in base classes. | |||
183 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | |||
184 | UnqualifiedTypeNameLookupResult::NotFound; | |||
185 | for (const auto &Base : RD->bases()) { | |||
186 | const CXXRecordDecl *BaseRD = nullptr; | |||
187 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) | |||
188 | BaseRD = BaseTT->getAsCXXRecordDecl(); | |||
189 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { | |||
190 | // Look for type decls in dependent base classes that have known primary | |||
191 | // templates. | |||
192 | if (!TST || !TST->isDependentType()) | |||
193 | continue; | |||
194 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); | |||
195 | if (!TD) | |||
196 | continue; | |||
197 | if (auto *BasePrimaryTemplate = | |||
198 | dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { | |||
199 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) | |||
200 | BaseRD = BasePrimaryTemplate; | |||
201 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { | |||
202 | if (const ClassTemplatePartialSpecializationDecl *PS = | |||
203 | CTD->findPartialSpecialization(Base.getType())) | |||
204 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) | |||
205 | BaseRD = PS; | |||
206 | } | |||
207 | } | |||
208 | } | |||
209 | if (BaseRD) { | |||
210 | for (NamedDecl *ND : BaseRD->lookup(&II)) { | |||
211 | if (!isa<TypeDecl>(ND)) | |||
212 | return UnqualifiedTypeNameLookupResult::FoundNonType; | |||
213 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | |||
214 | } | |||
215 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { | |||
216 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { | |||
217 | case UnqualifiedTypeNameLookupResult::FoundNonType: | |||
218 | return UnqualifiedTypeNameLookupResult::FoundNonType; | |||
219 | case UnqualifiedTypeNameLookupResult::FoundType: | |||
220 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | |||
221 | break; | |||
222 | case UnqualifiedTypeNameLookupResult::NotFound: | |||
223 | break; | |||
224 | } | |||
225 | } | |||
226 | } | |||
227 | } | |||
228 | ||||
229 | return FoundTypeDecl; | |||
230 | } | |||
231 | ||||
232 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, | |||
233 | const IdentifierInfo &II, | |||
234 | SourceLocation NameLoc) { | |||
235 | // Lookup in the parent class template context, if any. | |||
236 | const CXXRecordDecl *RD = nullptr; | |||
237 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | |||
238 | UnqualifiedTypeNameLookupResult::NotFound; | |||
239 | for (DeclContext *DC = S.CurContext; | |||
240 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; | |||
241 | DC = DC->getParent()) { | |||
242 | // Look for type decls in dependent base classes that have known primary | |||
243 | // templates. | |||
244 | RD = dyn_cast<CXXRecordDecl>(DC); | |||
245 | if (RD && RD->getDescribedClassTemplate()) | |||
246 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); | |||
247 | } | |||
248 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) | |||
249 | return nullptr; | |||
250 | ||||
251 | // We found some types in dependent base classes. Recover as if the user | |||
252 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the | |||
253 | // lookup during template instantiation. | |||
254 | S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; | |||
255 | ||||
256 | ASTContext &Context = S.Context; | |||
257 | auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, | |||
258 | cast<Type>(Context.getRecordType(RD))); | |||
259 | QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); | |||
260 | ||||
261 | CXXScopeSpec SS; | |||
262 | SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
263 | ||||
264 | TypeLocBuilder Builder; | |||
265 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | |||
266 | DepTL.setNameLoc(NameLoc); | |||
267 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | |||
268 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
269 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
270 | } | |||
271 | ||||
272 | /// If the identifier refers to a type name within this scope, | |||
273 | /// return the declaration of that type. | |||
274 | /// | |||
275 | /// This routine performs ordinary name lookup of the identifier II | |||
276 | /// within the given scope, with optional C++ scope specifier SS, to | |||
277 | /// determine whether the name refers to a type. If so, returns an | |||
278 | /// opaque pointer (actually a QualType) corresponding to that | |||
279 | /// type. Otherwise, returns NULL. | |||
280 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, | |||
281 | Scope *S, CXXScopeSpec *SS, | |||
282 | bool isClassName, bool HasTrailingDot, | |||
283 | ParsedType ObjectTypePtr, | |||
284 | bool IsCtorOrDtorName, | |||
285 | bool WantNontrivialTypeSourceInfo, | |||
286 | bool IsClassTemplateDeductionContext, | |||
287 | IdentifierInfo **CorrectedII) { | |||
288 | // FIXME: Consider allowing this outside C++1z mode as an extension. | |||
289 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && | |||
290 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && | |||
291 | !isClassName && !HasTrailingDot; | |||
292 | ||||
293 | // Determine where we will perform name lookup. | |||
294 | DeclContext *LookupCtx = nullptr; | |||
295 | if (ObjectTypePtr) { | |||
296 | QualType ObjectType = ObjectTypePtr.get(); | |||
297 | if (ObjectType->isRecordType()) | |||
298 | LookupCtx = computeDeclContext(ObjectType); | |||
299 | } else if (SS && SS->isNotEmpty()) { | |||
300 | LookupCtx = computeDeclContext(*SS, false); | |||
301 | ||||
302 | if (!LookupCtx) { | |||
303 | if (isDependentScopeSpecifier(*SS)) { | |||
304 | // C++ [temp.res]p3: | |||
305 | // A qualified-id that refers to a type and in which the | |||
306 | // nested-name-specifier depends on a template-parameter (14.6.2) | |||
307 | // shall be prefixed by the keyword typename to indicate that the | |||
308 | // qualified-id denotes a type, forming an | |||
309 | // elaborated-type-specifier (7.1.5.3). | |||
310 | // | |||
311 | // We therefore do not perform any name lookup if the result would | |||
312 | // refer to a member of an unknown specialization. | |||
313 | if (!isClassName && !IsCtorOrDtorName) | |||
314 | return nullptr; | |||
315 | ||||
316 | // We know from the grammar that this name refers to a type, | |||
317 | // so build a dependent node to describe the type. | |||
318 | if (WantNontrivialTypeSourceInfo) | |||
319 | return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); | |||
320 | ||||
321 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); | |||
322 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, | |||
323 | II, NameLoc); | |||
324 | return ParsedType::make(T); | |||
325 | } | |||
326 | ||||
327 | return nullptr; | |||
328 | } | |||
329 | ||||
330 | if (!LookupCtx->isDependentContext() && | |||
331 | RequireCompleteDeclContext(*SS, LookupCtx)) | |||
332 | return nullptr; | |||
333 | } | |||
334 | ||||
335 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of | |||
336 | // lookup for class-names. | |||
337 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : | |||
338 | LookupOrdinaryName; | |||
339 | LookupResult Result(*this, &II, NameLoc, Kind); | |||
340 | if (LookupCtx) { | |||
341 | // Perform "qualified" name lookup into the declaration context we | |||
342 | // computed, which is either the type of the base of a member access | |||
343 | // expression or the declaration context associated with a prior | |||
344 | // nested-name-specifier. | |||
345 | LookupQualifiedName(Result, LookupCtx); | |||
346 | ||||
347 | if (ObjectTypePtr && Result.empty()) { | |||
348 | // C++ [basic.lookup.classref]p3: | |||
349 | // If the unqualified-id is ~type-name, the type-name is looked up | |||
350 | // in the context of the entire postfix-expression. If the type T of | |||
351 | // the object expression is of a class type C, the type-name is also | |||
352 | // looked up in the scope of class C. At least one of the lookups shall | |||
353 | // find a name that refers to (possibly cv-qualified) T. | |||
354 | LookupName(Result, S); | |||
355 | } | |||
356 | } else { | |||
357 | // Perform unqualified name lookup. | |||
358 | LookupName(Result, S); | |||
359 | ||||
360 | // For unqualified lookup in a class template in MSVC mode, look into | |||
361 | // dependent base classes where the primary class template is known. | |||
362 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { | |||
363 | if (ParsedType TypeInBase = | |||
364 | recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) | |||
365 | return TypeInBase; | |||
366 | } | |||
367 | } | |||
368 | ||||
369 | NamedDecl *IIDecl = nullptr; | |||
370 | switch (Result.getResultKind()) { | |||
371 | case LookupResult::NotFound: | |||
372 | case LookupResult::NotFoundInCurrentInstantiation: | |||
373 | if (CorrectedII) { | |||
374 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, | |||
375 | AllowDeducedTemplate); | |||
376 | TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, | |||
377 | S, SS, CCC, CTK_ErrorRecovery); | |||
378 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); | |||
379 | TemplateTy Template; | |||
380 | bool MemberOfUnknownSpecialization; | |||
381 | UnqualifiedId TemplateName; | |||
382 | TemplateName.setIdentifier(NewII, NameLoc); | |||
383 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); | |||
384 | CXXScopeSpec NewSS, *NewSSPtr = SS; | |||
385 | if (SS && NNS) { | |||
386 | NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
387 | NewSSPtr = &NewSS; | |||
388 | } | |||
389 | if (Correction && (NNS || NewII != &II) && | |||
390 | // Ignore a correction to a template type as the to-be-corrected | |||
391 | // identifier is not a template (typo correction for template names | |||
392 | // is handled elsewhere). | |||
393 | !(getLangOpts().CPlusPlus && NewSSPtr && | |||
394 | isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, | |||
395 | Template, MemberOfUnknownSpecialization))) { | |||
396 | ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, | |||
397 | isClassName, HasTrailingDot, ObjectTypePtr, | |||
398 | IsCtorOrDtorName, | |||
399 | WantNontrivialTypeSourceInfo, | |||
400 | IsClassTemplateDeductionContext); | |||
401 | if (Ty) { | |||
402 | diagnoseTypo(Correction, | |||
403 | PDiag(diag::err_unknown_type_or_class_name_suggest) | |||
404 | << Result.getLookupName() << isClassName); | |||
405 | if (SS && NNS) | |||
406 | SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
407 | *CorrectedII = NewII; | |||
408 | return Ty; | |||
409 | } | |||
410 | } | |||
411 | } | |||
412 | // If typo correction failed or was not performed, fall through | |||
413 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
414 | case LookupResult::FoundOverloaded: | |||
415 | case LookupResult::FoundUnresolvedValue: | |||
416 | Result.suppressDiagnostics(); | |||
417 | return nullptr; | |||
418 | ||||
419 | case LookupResult::Ambiguous: | |||
420 | // Recover from type-hiding ambiguities by hiding the type. We'll | |||
421 | // do the lookup again when looking for an object, and we can | |||
422 | // diagnose the error then. If we don't do this, then the error | |||
423 | // about hiding the type will be immediately followed by an error | |||
424 | // that only makes sense if the identifier was treated like a type. | |||
425 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { | |||
426 | Result.suppressDiagnostics(); | |||
427 | return nullptr; | |||
428 | } | |||
429 | ||||
430 | // Look to see if we have a type anywhere in the list of results. | |||
431 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); | |||
432 | Res != ResEnd; ++Res) { | |||
433 | if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || | |||
434 | (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { | |||
435 | if (!IIDecl || | |||
436 | (*Res)->getLocation().getRawEncoding() < | |||
437 | IIDecl->getLocation().getRawEncoding()) | |||
438 | IIDecl = *Res; | |||
439 | } | |||
440 | } | |||
441 | ||||
442 | if (!IIDecl) { | |||
443 | // None of the entities we found is a type, so there is no way | |||
444 | // to even assume that the result is a type. In this case, don't | |||
445 | // complain about the ambiguity. The parser will either try to | |||
446 | // perform this lookup again (e.g., as an object name), which | |||
447 | // will produce the ambiguity, or will complain that it expected | |||
448 | // a type name. | |||
449 | Result.suppressDiagnostics(); | |||
450 | return nullptr; | |||
451 | } | |||
452 | ||||
453 | // We found a type within the ambiguous lookup; diagnose the | |||
454 | // ambiguity and then return that type. This might be the right | |||
455 | // answer, or it might not be, but it suppresses any attempt to | |||
456 | // perform the name lookup again. | |||
457 | break; | |||
458 | ||||
459 | case LookupResult::Found: | |||
460 | IIDecl = Result.getFoundDecl(); | |||
461 | break; | |||
462 | } | |||
463 | ||||
464 | assert(IIDecl && "Didn't find decl")((IIDecl && "Didn't find decl") ? static_cast<void > (0) : __assert_fail ("IIDecl && \"Didn't find decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 464, __PRETTY_FUNCTION__)); | |||
465 | ||||
466 | QualType T; | |||
467 | if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { | |||
468 | // C++ [class.qual]p2: A lookup that would find the injected-class-name | |||
469 | // instead names the constructors of the class, except when naming a class. | |||
470 | // This is ill-formed when we're not actually forming a ctor or dtor name. | |||
471 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); | |||
472 | auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); | |||
473 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && | |||
474 | FoundRD->isInjectedClassName() && | |||
475 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) | |||
476 | Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) | |||
477 | << &II << /*Type*/1; | |||
478 | ||||
479 | DiagnoseUseOfDecl(IIDecl, NameLoc); | |||
480 | ||||
481 | T = Context.getTypeDeclType(TD); | |||
482 | MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); | |||
483 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { | |||
484 | (void)DiagnoseUseOfDecl(IDecl, NameLoc); | |||
485 | if (!HasTrailingDot) | |||
486 | T = Context.getObjCInterfaceType(IDecl); | |||
487 | } else if (AllowDeducedTemplate) { | |||
488 | if (auto *TD = getAsTypeTemplateDecl(IIDecl)) | |||
489 | T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), | |||
490 | QualType(), false); | |||
491 | } | |||
492 | ||||
493 | if (T.isNull()) { | |||
494 | // If it's not plausibly a type, suppress diagnostics. | |||
495 | Result.suppressDiagnostics(); | |||
496 | return nullptr; | |||
497 | } | |||
498 | ||||
499 | // NOTE: avoid constructing an ElaboratedType(Loc) if this is a | |||
500 | // constructor or destructor name (in such a case, the scope specifier | |||
501 | // will be attached to the enclosing Expr or Decl node). | |||
502 | if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && | |||
503 | !isa<ObjCInterfaceDecl>(IIDecl)) { | |||
504 | if (WantNontrivialTypeSourceInfo) { | |||
505 | // Construct a type with type-source information. | |||
506 | TypeLocBuilder Builder; | |||
507 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | |||
508 | ||||
509 | T = getElaboratedType(ETK_None, *SS, T); | |||
510 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | |||
511 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | |||
512 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); | |||
513 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
514 | } else { | |||
515 | T = getElaboratedType(ETK_None, *SS, T); | |||
516 | } | |||
517 | } | |||
518 | ||||
519 | return ParsedType::make(T); | |||
520 | } | |||
521 | ||||
522 | // Builds a fake NNS for the given decl context. | |||
523 | static NestedNameSpecifier * | |||
524 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { | |||
525 | for (;; DC = DC->getLookupParent()) { | |||
526 | DC = DC->getPrimaryContext(); | |||
527 | auto *ND = dyn_cast<NamespaceDecl>(DC); | |||
528 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) | |||
529 | return NestedNameSpecifier::Create(Context, nullptr, ND); | |||
530 | else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) | |||
531 | return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | |||
532 | RD->getTypeForDecl()); | |||
533 | else if (isa<TranslationUnitDecl>(DC)) | |||
534 | return NestedNameSpecifier::GlobalSpecifier(Context); | |||
535 | } | |||
536 | llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 536); | |||
537 | } | |||
538 | ||||
539 | /// Find the parent class with dependent bases of the innermost enclosing method | |||
540 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end | |||
541 | /// up allowing unqualified dependent type names at class-level, which MSVC | |||
542 | /// correctly rejects. | |||
543 | static const CXXRecordDecl * | |||
544 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { | |||
545 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { | |||
546 | DC = DC->getPrimaryContext(); | |||
547 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | |||
548 | if (MD->getParent()->hasAnyDependentBases()) | |||
549 | return MD->getParent(); | |||
550 | } | |||
551 | return nullptr; | |||
552 | } | |||
553 | ||||
554 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, | |||
555 | SourceLocation NameLoc, | |||
556 | bool IsTemplateTypeArg) { | |||
557 | assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 557, __PRETTY_FUNCTION__)); | |||
558 | ||||
559 | NestedNameSpecifier *NNS = nullptr; | |||
560 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { | |||
561 | // If we weren't able to parse a default template argument, delay lookup | |||
562 | // until instantiation time by making a non-dependent DependentTypeName. We | |||
563 | // pretend we saw a NestedNameSpecifier referring to the current scope, and | |||
564 | // lookup is retried. | |||
565 | // FIXME: This hurts our diagnostic quality, since we get errors like "no | |||
566 | // type named 'Foo' in 'current_namespace'" when the user didn't write any | |||
567 | // name specifiers. | |||
568 | NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); | |||
569 | Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; | |||
570 | } else if (const CXXRecordDecl *RD = | |||
571 | findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { | |||
572 | // Build a DependentNameType that will perform lookup into RD at | |||
573 | // instantiation time. | |||
574 | NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | |||
575 | RD->getTypeForDecl()); | |||
576 | ||||
577 | // Diagnose that this identifier was undeclared, and retry the lookup during | |||
578 | // template instantiation. | |||
579 | Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II | |||
580 | << RD; | |||
581 | } else { | |||
582 | // This is not a situation that we should recover from. | |||
583 | return ParsedType(); | |||
584 | } | |||
585 | ||||
586 | QualType T = Context.getDependentNameType(ETK_None, NNS, &II); | |||
587 | ||||
588 | // Build type location information. We synthesized the qualifier, so we have | |||
589 | // to build a fake NestedNameSpecifierLoc. | |||
590 | NestedNameSpecifierLocBuilder NNSLocBuilder; | |||
591 | NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
592 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); | |||
593 | ||||
594 | TypeLocBuilder Builder; | |||
595 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | |||
596 | DepTL.setNameLoc(NameLoc); | |||
597 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | |||
598 | DepTL.setQualifierLoc(QualifierLoc); | |||
599 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
600 | } | |||
601 | ||||
602 | /// isTagName() - This method is called *for error recovery purposes only* | |||
603 | /// to determine if the specified name is a valid tag name ("struct foo"). If | |||
604 | /// so, this returns the TST for the tag corresponding to it (TST_enum, | |||
605 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose | |||
606 | /// cases in C where the user forgot to specify the tag. | |||
607 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { | |||
608 | // Do a tag name lookup in this scope. | |||
609 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); | |||
610 | LookupName(R, S, false); | |||
611 | R.suppressDiagnostics(); | |||
612 | if (R.getResultKind() == LookupResult::Found) | |||
613 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { | |||
614 | switch (TD->getTagKind()) { | |||
615 | case TTK_Struct: return DeclSpec::TST_struct; | |||
616 | case TTK_Interface: return DeclSpec::TST_interface; | |||
617 | case TTK_Union: return DeclSpec::TST_union; | |||
618 | case TTK_Class: return DeclSpec::TST_class; | |||
619 | case TTK_Enum: return DeclSpec::TST_enum; | |||
620 | } | |||
621 | } | |||
622 | ||||
623 | return DeclSpec::TST_unspecified; | |||
624 | } | |||
625 | ||||
626 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, | |||
627 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes | |||
628 | /// then downgrade the missing typename error to a warning. | |||
629 | /// This is needed for MSVC compatibility; Example: | |||
630 | /// @code | |||
631 | /// template<class T> class A { | |||
632 | /// public: | |||
633 | /// typedef int TYPE; | |||
634 | /// }; | |||
635 | /// template<class T> class B : public A<T> { | |||
636 | /// public: | |||
637 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. | |||
638 | /// }; | |||
639 | /// @endcode | |||
640 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { | |||
641 | if (CurContext->isRecord()) { | |||
642 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) | |||
643 | return true; | |||
644 | ||||
645 | const Type *Ty = SS->getScopeRep()->getAsType(); | |||
646 | ||||
647 | CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); | |||
648 | for (const auto &Base : RD->bases()) | |||
649 | if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) | |||
650 | return true; | |||
651 | return S->isFunctionPrototypeScope(); | |||
652 | } | |||
653 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); | |||
654 | } | |||
655 | ||||
656 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, | |||
657 | SourceLocation IILoc, | |||
658 | Scope *S, | |||
659 | CXXScopeSpec *SS, | |||
660 | ParsedType &SuggestedType, | |||
661 | bool IsTemplateName) { | |||
662 | // Don't report typename errors for editor placeholders. | |||
663 | if (II->isEditorPlaceholder()) | |||
664 | return; | |||
665 | // We don't have anything to suggest (yet). | |||
666 | SuggestedType = nullptr; | |||
667 | ||||
668 | // There may have been a typo in the name of the type. Look up typo | |||
669 | // results, in case we have something that we can suggest. | |||
670 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, | |||
671 | /*AllowTemplates=*/IsTemplateName, | |||
672 | /*AllowNonTemplates=*/!IsTemplateName); | |||
673 | if (TypoCorrection Corrected = | |||
674 | CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, | |||
675 | CCC, CTK_ErrorRecovery)) { | |||
676 | // FIXME: Support error recovery for the template-name case. | |||
677 | bool CanRecover = !IsTemplateName; | |||
678 | if (Corrected.isKeyword()) { | |||
679 | // We corrected to a keyword. | |||
680 | diagnoseTypo(Corrected, | |||
681 | PDiag(IsTemplateName ? diag::err_no_template_suggest | |||
682 | : diag::err_unknown_typename_suggest) | |||
683 | << II); | |||
684 | II = Corrected.getCorrectionAsIdentifierInfo(); | |||
685 | } else { | |||
686 | // We found a similarly-named type or interface; suggest that. | |||
687 | if (!SS || !SS->isSet()) { | |||
688 | diagnoseTypo(Corrected, | |||
689 | PDiag(IsTemplateName ? diag::err_no_template_suggest | |||
690 | : diag::err_unknown_typename_suggest) | |||
691 | << II, CanRecover); | |||
692 | } else if (DeclContext *DC = computeDeclContext(*SS, false)) { | |||
693 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | |||
694 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | |||
695 | II->getName().equals(CorrectedStr); | |||
696 | diagnoseTypo(Corrected, | |||
697 | PDiag(IsTemplateName | |||
698 | ? diag::err_no_member_template_suggest | |||
699 | : diag::err_unknown_nested_typename_suggest) | |||
700 | << II << DC << DroppedSpecifier << SS->getRange(), | |||
701 | CanRecover); | |||
702 | } else { | |||
703 | llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 703); | |||
704 | } | |||
705 | ||||
706 | if (!CanRecover) | |||
707 | return; | |||
708 | ||||
709 | CXXScopeSpec tmpSS; | |||
710 | if (Corrected.getCorrectionSpecifier()) | |||
711 | tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | |||
712 | SourceRange(IILoc)); | |||
713 | // FIXME: Support class template argument deduction here. | |||
714 | SuggestedType = | |||
715 | getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, | |||
716 | tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, | |||
717 | /*IsCtorOrDtorName=*/false, | |||
718 | /*NonTrivialTypeSourceInfo=*/true); | |||
719 | } | |||
720 | return; | |||
721 | } | |||
722 | ||||
723 | if (getLangOpts().CPlusPlus && !IsTemplateName) { | |||
724 | // See if II is a class template that the user forgot to pass arguments to. | |||
725 | UnqualifiedId Name; | |||
726 | Name.setIdentifier(II, IILoc); | |||
727 | CXXScopeSpec EmptySS; | |||
728 | TemplateTy TemplateResult; | |||
729 | bool MemberOfUnknownSpecialization; | |||
730 | if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, | |||
731 | Name, nullptr, true, TemplateResult, | |||
732 | MemberOfUnknownSpecialization) == TNK_Type_template) { | |||
733 | diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); | |||
734 | return; | |||
735 | } | |||
736 | } | |||
737 | ||||
738 | // FIXME: Should we move the logic that tries to recover from a missing tag | |||
739 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? | |||
740 | ||||
741 | if (!SS || (!SS->isSet() && !SS->isInvalid())) | |||
742 | Diag(IILoc, IsTemplateName ? diag::err_no_template | |||
743 | : diag::err_unknown_typename) | |||
744 | << II; | |||
745 | else if (DeclContext *DC = computeDeclContext(*SS, false)) | |||
746 | Diag(IILoc, IsTemplateName ? diag::err_no_member_template | |||
747 | : diag::err_typename_nested_not_found) | |||
748 | << II << DC << SS->getRange(); | |||
749 | else if (isDependentScopeSpecifier(*SS)) { | |||
750 | unsigned DiagID = diag::err_typename_missing; | |||
751 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) | |||
752 | DiagID = diag::ext_typename_missing; | |||
753 | ||||
754 | Diag(SS->getRange().getBegin(), DiagID) | |||
755 | << SS->getScopeRep() << II->getName() | |||
756 | << SourceRange(SS->getRange().getBegin(), IILoc) | |||
757 | << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); | |||
758 | SuggestedType = ActOnTypenameType(S, SourceLocation(), | |||
759 | *SS, *II, IILoc).get(); | |||
760 | } else { | |||
761 | assert(SS && SS->isInvalid() &&((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed" ) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 762, __PRETTY_FUNCTION__)) | |||
762 | "Invalid scope specifier has already been diagnosed")((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed" ) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 762, __PRETTY_FUNCTION__)); | |||
763 | } | |||
764 | } | |||
765 | ||||
766 | /// Determine whether the given result set contains either a type name | |||
767 | /// or | |||
768 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { | |||
769 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && | |||
770 | NextToken.is(tok::less); | |||
771 | ||||
772 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { | |||
773 | if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) | |||
774 | return true; | |||
775 | ||||
776 | if (CheckTemplate && isa<TemplateDecl>(*I)) | |||
777 | return true; | |||
778 | } | |||
779 | ||||
780 | return false; | |||
781 | } | |||
782 | ||||
783 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, | |||
784 | Scope *S, CXXScopeSpec &SS, | |||
785 | IdentifierInfo *&Name, | |||
786 | SourceLocation NameLoc) { | |||
787 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); | |||
788 | SemaRef.LookupParsedName(R, S, &SS); | |||
789 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { | |||
790 | StringRef FixItTagName; | |||
791 | switch (Tag->getTagKind()) { | |||
792 | case TTK_Class: | |||
793 | FixItTagName = "class "; | |||
794 | break; | |||
795 | ||||
796 | case TTK_Enum: | |||
797 | FixItTagName = "enum "; | |||
798 | break; | |||
799 | ||||
800 | case TTK_Struct: | |||
801 | FixItTagName = "struct "; | |||
802 | break; | |||
803 | ||||
804 | case TTK_Interface: | |||
805 | FixItTagName = "__interface "; | |||
806 | break; | |||
807 | ||||
808 | case TTK_Union: | |||
809 | FixItTagName = "union "; | |||
810 | break; | |||
811 | } | |||
812 | ||||
813 | StringRef TagName = FixItTagName.drop_back(); | |||
814 | SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) | |||
815 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus | |||
816 | << FixItHint::CreateInsertion(NameLoc, FixItTagName); | |||
817 | ||||
818 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); | |||
819 | I != IEnd; ++I) | |||
820 | SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) | |||
821 | << Name << TagName; | |||
822 | ||||
823 | // Replace lookup results with just the tag decl. | |||
824 | Result.clear(Sema::LookupTagName); | |||
825 | SemaRef.LookupParsedName(Result, S, &SS); | |||
826 | return true; | |||
827 | } | |||
828 | ||||
829 | return false; | |||
830 | } | |||
831 | ||||
832 | /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. | |||
833 | static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, | |||
834 | QualType T, SourceLocation NameLoc) { | |||
835 | ASTContext &Context = S.Context; | |||
836 | ||||
837 | TypeLocBuilder Builder; | |||
838 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | |||
839 | ||||
840 | T = S.getElaboratedType(ETK_None, SS, T); | |||
841 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | |||
842 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | |||
843 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
844 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
845 | } | |||
846 | ||||
847 | Sema::NameClassification | |||
848 | Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, | |||
849 | SourceLocation NameLoc, const Token &NextToken, | |||
850 | bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) { | |||
851 | DeclarationNameInfo NameInfo(Name, NameLoc); | |||
852 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | |||
853 | ||||
854 | if (NextToken.is(tok::coloncolon)) { | |||
855 | NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); | |||
856 | BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); | |||
857 | } else if (getLangOpts().CPlusPlus && SS.isSet() && | |||
858 | isCurrentClassName(*Name, S, &SS)) { | |||
859 | // Per [class.qual]p2, this names the constructors of SS, not the | |||
860 | // injected-class-name. We don't have a classification for that. | |||
861 | // There's not much point caching this result, since the parser | |||
862 | // will reject it later. | |||
863 | return NameClassification::Unknown(); | |||
864 | } | |||
865 | ||||
866 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | |||
867 | LookupParsedName(Result, S, &SS, !CurMethod); | |||
868 | ||||
869 | // For unqualified lookup in a class template in MSVC mode, look into | |||
870 | // dependent base classes where the primary class template is known. | |||
871 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { | |||
872 | if (ParsedType TypeInBase = | |||
873 | recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) | |||
874 | return TypeInBase; | |||
875 | } | |||
876 | ||||
877 | // Perform lookup for Objective-C instance variables (including automatically | |||
878 | // synthesized instance variables), if we're in an Objective-C method. | |||
879 | // FIXME: This lookup really, really needs to be folded in to the normal | |||
880 | // unqualified lookup mechanism. | |||
881 | if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { | |||
882 | ExprResult E = LookupInObjCMethod(Result, S, Name, true); | |||
883 | if (E.get() || E.isInvalid()) | |||
884 | return E; | |||
885 | } | |||
886 | ||||
887 | bool SecondTry = false; | |||
888 | bool IsFilteredTemplateName = false; | |||
889 | ||||
890 | Corrected: | |||
891 | switch (Result.getResultKind()) { | |||
892 | case LookupResult::NotFound: | |||
893 | // If an unqualified-id is followed by a '(', then we have a function | |||
894 | // call. | |||
895 | if (!SS.isSet() && NextToken.is(tok::l_paren)) { | |||
896 | // In C++, this is an ADL-only call. | |||
897 | // FIXME: Reference? | |||
898 | if (getLangOpts().CPlusPlus) | |||
899 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); | |||
900 | ||||
901 | // C90 6.3.2.2: | |||
902 | // If the expression that precedes the parenthesized argument list in a | |||
903 | // function call consists solely of an identifier, and if no | |||
904 | // declaration is visible for this identifier, the identifier is | |||
905 | // implicitly declared exactly as if, in the innermost block containing | |||
906 | // the function call, the declaration | |||
907 | // | |||
908 | // extern int identifier (); | |||
909 | // | |||
910 | // appeared. | |||
911 | // | |||
912 | // We also allow this in C99 as an extension. | |||
913 | if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { | |||
914 | Result.addDecl(D); | |||
915 | Result.resolveKind(); | |||
916 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); | |||
917 | } | |||
918 | } | |||
919 | ||||
920 | if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) { | |||
921 | // In C++20 onwards, this could be an ADL-only call to a function | |||
922 | // template, and we're required to assume that this is a template name. | |||
923 | // | |||
924 | // FIXME: Find a way to still do typo correction in this case. | |||
925 | TemplateName Template = | |||
926 | Context.getAssumedTemplateName(NameInfo.getName()); | |||
927 | return NameClassification::UndeclaredTemplate(Template); | |||
928 | } | |||
929 | ||||
930 | // In C, we first see whether there is a tag type by the same name, in | |||
931 | // which case it's likely that the user just forgot to write "enum", | |||
932 | // "struct", or "union". | |||
933 | if (!getLangOpts().CPlusPlus && !SecondTry && | |||
934 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | |||
935 | break; | |||
936 | } | |||
937 | ||||
938 | // Perform typo correction to determine if there is another name that is | |||
939 | // close to this name. | |||
940 | if (!SecondTry && CCC) { | |||
941 | SecondTry = true; | |||
942 | if (TypoCorrection Corrected = | |||
943 | CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, | |||
944 | &SS, *CCC, CTK_ErrorRecovery)) { | |||
945 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; | |||
946 | unsigned QualifiedDiag = diag::err_no_member_suggest; | |||
947 | ||||
948 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); | |||
949 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); | |||
950 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | |||
951 | UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { | |||
952 | UnqualifiedDiag = diag::err_no_template_suggest; | |||
953 | QualifiedDiag = diag::err_no_member_template_suggest; | |||
954 | } else if (UnderlyingFirstDecl && | |||
955 | (isa<TypeDecl>(UnderlyingFirstDecl) || | |||
956 | isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || | |||
957 | isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { | |||
958 | UnqualifiedDiag = diag::err_unknown_typename_suggest; | |||
959 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; | |||
960 | } | |||
961 | ||||
962 | if (SS.isEmpty()) { | |||
963 | diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); | |||
964 | } else {// FIXME: is this even reachable? Test it. | |||
965 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | |||
966 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | |||
967 | Name->getName().equals(CorrectedStr); | |||
968 | diagnoseTypo(Corrected, PDiag(QualifiedDiag) | |||
969 | << Name << computeDeclContext(SS, false) | |||
970 | << DroppedSpecifier << SS.getRange()); | |||
971 | } | |||
972 | ||||
973 | // Update the name, so that the caller has the new name. | |||
974 | Name = Corrected.getCorrectionAsIdentifierInfo(); | |||
975 | ||||
976 | // Typo correction corrected to a keyword. | |||
977 | if (Corrected.isKeyword()) | |||
978 | return Name; | |||
979 | ||||
980 | // Also update the LookupResult... | |||
981 | // FIXME: This should probably go away at some point | |||
982 | Result.clear(); | |||
983 | Result.setLookupName(Corrected.getCorrection()); | |||
984 | if (FirstDecl) | |||
985 | Result.addDecl(FirstDecl); | |||
986 | ||||
987 | // If we found an Objective-C instance variable, let | |||
988 | // LookupInObjCMethod build the appropriate expression to | |||
989 | // reference the ivar. | |||
990 | // FIXME: This is a gross hack. | |||
991 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { | |||
992 | Result.clear(); | |||
993 | ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); | |||
994 | return E; | |||
995 | } | |||
996 | ||||
997 | goto Corrected; | |||
998 | } | |||
999 | } | |||
1000 | ||||
1001 | // We failed to correct; just fall through and let the parser deal with it. | |||
1002 | Result.suppressDiagnostics(); | |||
1003 | return NameClassification::Unknown(); | |||
1004 | ||||
1005 | case LookupResult::NotFoundInCurrentInstantiation: { | |||
1006 | // We performed name lookup into the current instantiation, and there were | |||
1007 | // dependent bases, so we treat this result the same way as any other | |||
1008 | // dependent nested-name-specifier. | |||
1009 | ||||
1010 | // C++ [temp.res]p2: | |||
1011 | // A name used in a template declaration or definition and that is | |||
1012 | // dependent on a template-parameter is assumed not to name a type | |||
1013 | // unless the applicable name lookup finds a type name or the name is | |||
1014 | // qualified by the keyword typename. | |||
1015 | // | |||
1016 | // FIXME: If the next token is '<', we might want to ask the parser to | |||
1017 | // perform some heroics to see if we actually have a | |||
1018 | // template-argument-list, which would indicate a missing 'template' | |||
1019 | // keyword here. | |||
1020 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
1021 | NameInfo, IsAddressOfOperand, | |||
1022 | /*TemplateArgs=*/nullptr); | |||
1023 | } | |||
1024 | ||||
1025 | case LookupResult::Found: | |||
1026 | case LookupResult::FoundOverloaded: | |||
1027 | case LookupResult::FoundUnresolvedValue: | |||
1028 | break; | |||
1029 | ||||
1030 | case LookupResult::Ambiguous: | |||
1031 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | |||
1032 | hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, | |||
1033 | /*AllowDependent=*/false)) { | |||
1034 | // C++ [temp.local]p3: | |||
1035 | // A lookup that finds an injected-class-name (10.2) can result in an | |||
1036 | // ambiguity in certain cases (for example, if it is found in more than | |||
1037 | // one base class). If all of the injected-class-names that are found | |||
1038 | // refer to specializations of the same class template, and if the name | |||
1039 | // is followed by a template-argument-list, the reference refers to the | |||
1040 | // class template itself and not a specialization thereof, and is not | |||
1041 | // ambiguous. | |||
1042 | // | |||
1043 | // This filtering can make an ambiguous result into an unambiguous one, | |||
1044 | // so try again after filtering out template names. | |||
1045 | FilterAcceptableTemplateNames(Result); | |||
1046 | if (!Result.isAmbiguous()) { | |||
1047 | IsFilteredTemplateName = true; | |||
1048 | break; | |||
1049 | } | |||
1050 | } | |||
1051 | ||||
1052 | // Diagnose the ambiguity and return an error. | |||
1053 | return NameClassification::Error(); | |||
1054 | } | |||
1055 | ||||
1056 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | |||
1057 | (IsFilteredTemplateName || | |||
1058 | hasAnyAcceptableTemplateNames( | |||
1059 | Result, /*AllowFunctionTemplates=*/true, | |||
1060 | /*AllowDependent=*/false, | |||
1061 | /*AllowNonTemplateFunctions*/ !SS.isSet() && | |||
1062 | getLangOpts().CPlusPlus2a))) { | |||
1063 | // C++ [temp.names]p3: | |||
1064 | // After name lookup (3.4) finds that a name is a template-name or that | |||
1065 | // an operator-function-id or a literal- operator-id refers to a set of | |||
1066 | // overloaded functions any member of which is a function template if | |||
1067 | // this is followed by a <, the < is always taken as the delimiter of a | |||
1068 | // template-argument-list and never as the less-than operator. | |||
1069 | // C++2a [temp.names]p2: | |||
1070 | // A name is also considered to refer to a template if it is an | |||
1071 | // unqualified-id followed by a < and name lookup finds either one | |||
1072 | // or more functions or finds nothing. | |||
1073 | if (!IsFilteredTemplateName) | |||
1074 | FilterAcceptableTemplateNames(Result); | |||
1075 | ||||
1076 | bool IsFunctionTemplate; | |||
1077 | bool IsVarTemplate; | |||
1078 | TemplateName Template; | |||
1079 | if (Result.end() - Result.begin() > 1) { | |||
1080 | IsFunctionTemplate = true; | |||
1081 | Template = Context.getOverloadedTemplateName(Result.begin(), | |||
1082 | Result.end()); | |||
1083 | } else if (!Result.empty()) { | |||
1084 | auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( | |||
1085 | *Result.begin(), /*AllowFunctionTemplates=*/true, | |||
1086 | /*AllowDependent=*/false)); | |||
1087 | IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); | |||
1088 | IsVarTemplate = isa<VarTemplateDecl>(TD); | |||
1089 | ||||
1090 | if (SS.isSet() && !SS.isInvalid()) | |||
1091 | Template = | |||
1092 | Context.getQualifiedTemplateName(SS.getScopeRep(), | |||
1093 | /*TemplateKeyword=*/false, TD); | |||
1094 | else | |||
1095 | Template = TemplateName(TD); | |||
1096 | } else { | |||
1097 | // All results were non-template functions. This is a function template | |||
1098 | // name. | |||
1099 | IsFunctionTemplate = true; | |||
1100 | Template = Context.getAssumedTemplateName(NameInfo.getName()); | |||
1101 | } | |||
1102 | ||||
1103 | if (IsFunctionTemplate) { | |||
1104 | // Function templates always go through overload resolution, at which | |||
1105 | // point we'll perform the various checks (e.g., accessibility) we need | |||
1106 | // to based on which function we selected. | |||
1107 | Result.suppressDiagnostics(); | |||
1108 | ||||
1109 | return NameClassification::FunctionTemplate(Template); | |||
1110 | } | |||
1111 | ||||
1112 | return IsVarTemplate ? NameClassification::VarTemplate(Template) | |||
1113 | : NameClassification::TypeTemplate(Template); | |||
1114 | } | |||
1115 | ||||
1116 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); | |||
1117 | if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { | |||
1118 | DiagnoseUseOfDecl(Type, NameLoc); | |||
1119 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | |||
1120 | QualType T = Context.getTypeDeclType(Type); | |||
1121 | if (SS.isNotEmpty()) | |||
1122 | return buildNestedType(*this, SS, T, NameLoc); | |||
1123 | return ParsedType::make(T); | |||
1124 | } | |||
1125 | ||||
1126 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); | |||
1127 | if (!Class) { | |||
1128 | // FIXME: It's unfortunate that we don't have a Type node for handling this. | |||
1129 | if (ObjCCompatibleAliasDecl *Alias = | |||
1130 | dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) | |||
1131 | Class = Alias->getClassInterface(); | |||
1132 | } | |||
1133 | ||||
1134 | if (Class) { | |||
1135 | DiagnoseUseOfDecl(Class, NameLoc); | |||
1136 | ||||
1137 | if (NextToken.is(tok::period)) { | |||
1138 | // Interface. <something> is parsed as a property reference expression. | |||
1139 | // Just return "unknown" as a fall-through for now. | |||
1140 | Result.suppressDiagnostics(); | |||
1141 | return NameClassification::Unknown(); | |||
1142 | } | |||
1143 | ||||
1144 | QualType T = Context.getObjCInterfaceType(Class); | |||
1145 | return ParsedType::make(T); | |||
1146 | } | |||
1147 | ||||
1148 | // We can have a type template here if we're classifying a template argument. | |||
1149 | if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && | |||
1150 | !isa<VarTemplateDecl>(FirstDecl)) | |||
1151 | return NameClassification::TypeTemplate( | |||
1152 | TemplateName(cast<TemplateDecl>(FirstDecl))); | |||
1153 | ||||
1154 | // Check for a tag type hidden by a non-type decl in a few cases where it | |||
1155 | // seems likely a type is wanted instead of the non-type that was found. | |||
1156 | bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); | |||
1157 | if ((NextToken.is(tok::identifier) || | |||
1158 | (NextIsOp && | |||
1159 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && | |||
1160 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | |||
1161 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); | |||
1162 | DiagnoseUseOfDecl(Type, NameLoc); | |||
1163 | QualType T = Context.getTypeDeclType(Type); | |||
1164 | if (SS.isNotEmpty()) | |||
1165 | return buildNestedType(*this, SS, T, NameLoc); | |||
1166 | return ParsedType::make(T); | |||
1167 | } | |||
1168 | ||||
1169 | if (FirstDecl->isCXXClassMember()) | |||
1170 | return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, | |||
1171 | nullptr, S); | |||
1172 | ||||
1173 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | |||
1174 | return BuildDeclarationNameExpr(SS, Result, ADL); | |||
1175 | } | |||
1176 | ||||
1177 | Sema::TemplateNameKindForDiagnostics | |||
1178 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { | |||
1179 | auto *TD = Name.getAsTemplateDecl(); | |||
1180 | if (!TD) | |||
1181 | return TemplateNameKindForDiagnostics::DependentTemplate; | |||
1182 | if (isa<ClassTemplateDecl>(TD)) | |||
1183 | return TemplateNameKindForDiagnostics::ClassTemplate; | |||
1184 | if (isa<FunctionTemplateDecl>(TD)) | |||
1185 | return TemplateNameKindForDiagnostics::FunctionTemplate; | |||
1186 | if (isa<VarTemplateDecl>(TD)) | |||
1187 | return TemplateNameKindForDiagnostics::VarTemplate; | |||
1188 | if (isa<TypeAliasTemplateDecl>(TD)) | |||
1189 | return TemplateNameKindForDiagnostics::AliasTemplate; | |||
1190 | if (isa<TemplateTemplateParmDecl>(TD)) | |||
1191 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; | |||
1192 | return TemplateNameKindForDiagnostics::DependentTemplate; | |||
1193 | } | |||
1194 | ||||
1195 | // Determines the context to return to after temporarily entering a | |||
1196 | // context. This depends in an unnecessarily complicated way on the | |||
1197 | // exact ordering of callbacks from the parser. | |||
1198 | DeclContext *Sema::getContainingDC(DeclContext *DC) { | |||
1199 | ||||
1200 | // Functions defined inline within classes aren't parsed until we've | |||
1201 | // finished parsing the top-level class, so the top-level class is | |||
1202 | // the context we'll need to return to. | |||
1203 | // A Lambda call operator whose parent is a class must not be treated | |||
1204 | // as an inline member function. A Lambda can be used legally | |||
1205 | // either as an in-class member initializer or a default argument. These | |||
1206 | // are parsed once the class has been marked complete and so the containing | |||
1207 | // context would be the nested class (when the lambda is defined in one); | |||
1208 | // If the class is not complete, then the lambda is being used in an | |||
1209 | // ill-formed fashion (such as to specify the width of a bit-field, or | |||
1210 | // in an array-bound) - in which case we still want to return the | |||
1211 | // lexically containing DC (which could be a nested class). | |||
1212 | if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { | |||
1213 | DC = DC->getLexicalParent(); | |||
1214 | ||||
1215 | // A function not defined within a class will always return to its | |||
1216 | // lexical context. | |||
1217 | if (!isa<CXXRecordDecl>(DC)) | |||
1218 | return DC; | |||
1219 | ||||
1220 | // A C++ inline method/friend is parsed *after* the topmost class | |||
1221 | // it was declared in is fully parsed ("complete"); the topmost | |||
1222 | // class is the context we need to return to. | |||
1223 | while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) | |||
1224 | DC = RD; | |||
1225 | ||||
1226 | // Return the declaration context of the topmost class the inline method is | |||
1227 | // declared in. | |||
1228 | return DC; | |||
1229 | } | |||
1230 | ||||
1231 | return DC->getLexicalParent(); | |||
1232 | } | |||
1233 | ||||
1234 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { | |||
1235 | assert(getContainingDC(DC) == CurContext &&((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1236, __PRETTY_FUNCTION__)) | |||
1236 | "The next DeclContext should be lexically contained in the current one.")((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1236, __PRETTY_FUNCTION__)); | |||
1237 | CurContext = DC; | |||
1238 | S->setEntity(DC); | |||
1239 | } | |||
1240 | ||||
1241 | void Sema::PopDeclContext() { | |||
1242 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1242, __PRETTY_FUNCTION__)); | |||
1243 | ||||
1244 | CurContext = getContainingDC(CurContext); | |||
1245 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1245, __PRETTY_FUNCTION__)); | |||
1246 | } | |||
1247 | ||||
1248 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, | |||
1249 | Decl *D) { | |||
1250 | // Unlike PushDeclContext, the context to which we return is not necessarily | |||
1251 | // the containing DC of TD, because the new context will be some pre-existing | |||
1252 | // TagDecl definition instead of a fresh one. | |||
1253 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); | |||
1254 | CurContext = cast<TagDecl>(D)->getDefinition(); | |||
1255 | assert(CurContext && "skipping definition of undefined tag")((CurContext && "skipping definition of undefined tag" ) ? static_cast<void> (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1255, __PRETTY_FUNCTION__)); | |||
1256 | // Start lookups from the parent of the current context; we don't want to look | |||
1257 | // into the pre-existing complete definition. | |||
1258 | S->setEntity(CurContext->getLookupParent()); | |||
1259 | return Result; | |||
1260 | } | |||
1261 | ||||
1262 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { | |||
1263 | CurContext = static_cast<decltype(CurContext)>(Context); | |||
1264 | } | |||
1265 | ||||
1266 | /// EnterDeclaratorContext - Used when we must lookup names in the context | |||
1267 | /// of a declarator's nested name specifier. | |||
1268 | /// | |||
1269 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { | |||
1270 | // C++0x [basic.lookup.unqual]p13: | |||
1271 | // A name used in the definition of a static data member of class | |||
1272 | // X (after the qualified-id of the static member) is looked up as | |||
1273 | // if the name was used in a member function of X. | |||
1274 | // C++0x [basic.lookup.unqual]p14: | |||
1275 | // If a variable member of a namespace is defined outside of the | |||
1276 | // scope of its namespace then any name used in the definition of | |||
1277 | // the variable member (after the declarator-id) is looked up as | |||
1278 | // if the definition of the variable member occurred in its | |||
1279 | // namespace. | |||
1280 | // Both of these imply that we should push a scope whose context | |||
1281 | // is the semantic context of the declaration. We can't use | |||
1282 | // PushDeclContext here because that context is not necessarily | |||
1283 | // lexically contained in the current context. Fortunately, | |||
1284 | // the containing scope should have the appropriate information. | |||
1285 | ||||
1286 | assert(!S->getEntity() && "scope already has entity")((!S->getEntity() && "scope already has entity") ? static_cast<void> (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1286, __PRETTY_FUNCTION__)); | |||
1287 | ||||
1288 | #ifndef NDEBUG | |||
1289 | Scope *Ancestor = S->getParent(); | |||
1290 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | |||
1291 | assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((Ancestor->getEntity() == CurContext && "ancestor context mismatch" ) ? static_cast<void> (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1291, __PRETTY_FUNCTION__)); | |||
1292 | #endif | |||
1293 | ||||
1294 | CurContext = DC; | |||
1295 | S->setEntity(DC); | |||
1296 | } | |||
1297 | ||||
1298 | void Sema::ExitDeclaratorContext(Scope *S) { | |||
1299 | assert(S->getEntity() == CurContext && "Context imbalance!")((S->getEntity() == CurContext && "Context imbalance!" ) ? static_cast<void> (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1299, __PRETTY_FUNCTION__)); | |||
1300 | ||||
1301 | // Switch back to the lexical context. The safety of this is | |||
1302 | // enforced by an assert in EnterDeclaratorContext. | |||
1303 | Scope *Ancestor = S->getParent(); | |||
1304 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | |||
1305 | CurContext = Ancestor->getEntity(); | |||
1306 | ||||
1307 | // We don't need to do anything with the scope, which is going to | |||
1308 | // disappear. | |||
1309 | } | |||
1310 | ||||
1311 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { | |||
1312 | // We assume that the caller has already called | |||
1313 | // ActOnReenterTemplateScope so getTemplatedDecl() works. | |||
1314 | FunctionDecl *FD = D->getAsFunction(); | |||
1315 | if (!FD) | |||
1316 | return; | |||
1317 | ||||
1318 | // Same implementation as PushDeclContext, but enters the context | |||
1319 | // from the lexical parent, rather than the top-level class. | |||
1320 | assert(CurContext == FD->getLexicalParent() &&((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1321, __PRETTY_FUNCTION__)) | |||
1321 | "The next DeclContext should be lexically contained in the current one.")((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1321, __PRETTY_FUNCTION__)); | |||
1322 | CurContext = FD; | |||
1323 | S->setEntity(CurContext); | |||
1324 | ||||
1325 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { | |||
1326 | ParmVarDecl *Param = FD->getParamDecl(P); | |||
1327 | // If the parameter has an identifier, then add it to the scope | |||
1328 | if (Param->getIdentifier()) { | |||
1329 | S->AddDecl(Param); | |||
1330 | IdResolver.AddDecl(Param); | |||
1331 | } | |||
1332 | } | |||
1333 | } | |||
1334 | ||||
1335 | void Sema::ActOnExitFunctionContext() { | |||
1336 | // Same implementation as PopDeclContext, but returns to the lexical parent, | |||
1337 | // rather than the top-level class. | |||
1338 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1338, __PRETTY_FUNCTION__)); | |||
1339 | CurContext = CurContext->getLexicalParent(); | |||
1340 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1340, __PRETTY_FUNCTION__)); | |||
1341 | } | |||
1342 | ||||
1343 | /// Determine whether we allow overloading of the function | |||
1344 | /// PrevDecl with another declaration. | |||
1345 | /// | |||
1346 | /// This routine determines whether overloading is possible, not | |||
1347 | /// whether some new function is actually an overload. It will return | |||
1348 | /// true in C++ (where we can always provide overloads) or, as an | |||
1349 | /// extension, in C when the previous function is already an | |||
1350 | /// overloaded function declaration or has the "overloadable" | |||
1351 | /// attribute. | |||
1352 | static bool AllowOverloadingOfFunction(LookupResult &Previous, | |||
1353 | ASTContext &Context, | |||
1354 | const FunctionDecl *New) { | |||
1355 | if (Context.getLangOpts().CPlusPlus) | |||
1356 | return true; | |||
1357 | ||||
1358 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) | |||
1359 | return true; | |||
1360 | ||||
1361 | return Previous.getResultKind() == LookupResult::Found && | |||
1362 | (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || | |||
1363 | New->hasAttr<OverloadableAttr>()); | |||
1364 | } | |||
1365 | ||||
1366 | /// Add this decl to the scope shadowed decl chains. | |||
1367 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { | |||
1368 | // Move up the scope chain until we find the nearest enclosing | |||
1369 | // non-transparent context. The declaration will be introduced into this | |||
1370 | // scope. | |||
1371 | while (S->getEntity() && S->getEntity()->isTransparentContext()) | |||
1372 | S = S->getParent(); | |||
1373 | ||||
1374 | // Add scoped declarations into their context, so that they can be | |||
1375 | // found later. Declarations without a context won't be inserted | |||
1376 | // into any context. | |||
1377 | if (AddToContext) | |||
1378 | CurContext->addDecl(D); | |||
1379 | ||||
1380 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they | |||
1381 | // are function-local declarations. | |||
1382 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && | |||
1383 | !D->getDeclContext()->getRedeclContext()->Equals( | |||
1384 | D->getLexicalDeclContext()->getRedeclContext()) && | |||
1385 | !D->getLexicalDeclContext()->isFunctionOrMethod()) | |||
1386 | return; | |||
1387 | ||||
1388 | // Template instantiations should also not be pushed into scope. | |||
1389 | if (isa<FunctionDecl>(D) && | |||
1390 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) | |||
1391 | return; | |||
1392 | ||||
1393 | // If this replaces anything in the current scope, | |||
1394 | IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), | |||
1395 | IEnd = IdResolver.end(); | |||
1396 | for (; I != IEnd; ++I) { | |||
1397 | if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { | |||
1398 | S->RemoveDecl(*I); | |||
1399 | IdResolver.RemoveDecl(*I); | |||
1400 | ||||
1401 | // Should only need to replace one decl. | |||
1402 | break; | |||
1403 | } | |||
1404 | } | |||
1405 | ||||
1406 | S->AddDecl(D); | |||
1407 | ||||
1408 | if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { | |||
1409 | // Implicitly-generated labels may end up getting generated in an order that | |||
1410 | // isn't strictly lexical, which breaks name lookup. Be careful to insert | |||
1411 | // the label at the appropriate place in the identifier chain. | |||
1412 | for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { | |||
1413 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); | |||
1414 | if (IDC == CurContext) { | |||
1415 | if (!S->isDeclScope(*I)) | |||
1416 | continue; | |||
1417 | } else if (IDC->Encloses(CurContext)) | |||
1418 | break; | |||
1419 | } | |||
1420 | ||||
1421 | IdResolver.InsertDeclAfter(I, D); | |||
1422 | } else { | |||
1423 | IdResolver.AddDecl(D); | |||
1424 | } | |||
1425 | } | |||
1426 | ||||
1427 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, | |||
1428 | bool AllowInlineNamespace) { | |||
1429 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); | |||
1430 | } | |||
1431 | ||||
1432 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { | |||
1433 | DeclContext *TargetDC = DC->getPrimaryContext(); | |||
1434 | do { | |||
1435 | if (DeclContext *ScopeDC = S->getEntity()) | |||
1436 | if (ScopeDC->getPrimaryContext() == TargetDC) | |||
1437 | return S; | |||
1438 | } while ((S = S->getParent())); | |||
1439 | ||||
1440 | return nullptr; | |||
1441 | } | |||
1442 | ||||
1443 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, | |||
1444 | DeclContext*, | |||
1445 | ASTContext&); | |||
1446 | ||||
1447 | /// Filters out lookup results that don't fall within the given scope | |||
1448 | /// as determined by isDeclInScope. | |||
1449 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, | |||
1450 | bool ConsiderLinkage, | |||
1451 | bool AllowInlineNamespace) { | |||
1452 | LookupResult::Filter F = R.makeFilter(); | |||
1453 | while (F.hasNext()) { | |||
1454 | NamedDecl *D = F.next(); | |||
1455 | ||||
1456 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) | |||
1457 | continue; | |||
1458 | ||||
1459 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) | |||
1460 | continue; | |||
1461 | ||||
1462 | F.erase(); | |||
1463 | } | |||
1464 | ||||
1465 | F.done(); | |||
1466 | } | |||
1467 | ||||
1468 | /// We've determined that \p New is a redeclaration of \p Old. Check that they | |||
1469 | /// have compatible owning modules. | |||
1470 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { | |||
1471 | // FIXME: The Modules TS is not clear about how friend declarations are | |||
1472 | // to be treated. It's not meaningful to have different owning modules for | |||
1473 | // linkage in redeclarations of the same entity, so for now allow the | |||
1474 | // redeclaration and change the owning modules to match. | |||
1475 | if (New->getFriendObjectKind() && | |||
1476 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { | |||
1477 | New->setLocalOwningModule(Old->getOwningModule()); | |||
1478 | makeMergedDefinitionVisible(New); | |||
1479 | return false; | |||
1480 | } | |||
1481 | ||||
1482 | Module *NewM = New->getOwningModule(); | |||
1483 | Module *OldM = Old->getOwningModule(); | |||
1484 | ||||
1485 | if (NewM && NewM->Kind == Module::PrivateModuleFragment) | |||
1486 | NewM = NewM->Parent; | |||
1487 | if (OldM && OldM->Kind == Module::PrivateModuleFragment) | |||
1488 | OldM = OldM->Parent; | |||
1489 | ||||
1490 | if (NewM == OldM) | |||
1491 | return false; | |||
1492 | ||||
1493 | bool NewIsModuleInterface = NewM && NewM->isModulePurview(); | |||
1494 | bool OldIsModuleInterface = OldM && OldM->isModulePurview(); | |||
1495 | if (NewIsModuleInterface || OldIsModuleInterface) { | |||
1496 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: | |||
1497 | // if a declaration of D [...] appears in the purview of a module, all | |||
1498 | // other such declarations shall appear in the purview of the same module | |||
1499 | Diag(New->getLocation(), diag::err_mismatched_owning_module) | |||
1500 | << New | |||
1501 | << NewIsModuleInterface | |||
1502 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "") | |||
1503 | << OldIsModuleInterface | |||
1504 | << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); | |||
1505 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
1506 | New->setInvalidDecl(); | |||
1507 | return true; | |||
1508 | } | |||
1509 | ||||
1510 | return false; | |||
1511 | } | |||
1512 | ||||
1513 | static bool isUsingDecl(NamedDecl *D) { | |||
1514 | return isa<UsingShadowDecl>(D) || | |||
1515 | isa<UnresolvedUsingTypenameDecl>(D) || | |||
1516 | isa<UnresolvedUsingValueDecl>(D); | |||
1517 | } | |||
1518 | ||||
1519 | /// Removes using shadow declarations from the lookup results. | |||
1520 | static void RemoveUsingDecls(LookupResult &R) { | |||
1521 | LookupResult::Filter F = R.makeFilter(); | |||
1522 | while (F.hasNext()) | |||
1523 | if (isUsingDecl(F.next())) | |||
1524 | F.erase(); | |||
1525 | ||||
1526 | F.done(); | |||
1527 | } | |||
1528 | ||||
1529 | /// Check for this common pattern: | |||
1530 | /// @code | |||
1531 | /// class S { | |||
1532 | /// S(const S&); // DO NOT IMPLEMENT | |||
1533 | /// void operator=(const S&); // DO NOT IMPLEMENT | |||
1534 | /// }; | |||
1535 | /// @endcode | |||
1536 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { | |||
1537 | // FIXME: Should check for private access too but access is set after we get | |||
1538 | // the decl here. | |||
1539 | if (D->doesThisDeclarationHaveABody()) | |||
1540 | return false; | |||
1541 | ||||
1542 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) | |||
1543 | return CD->isCopyConstructor(); | |||
1544 | return D->isCopyAssignmentOperator(); | |||
1545 | } | |||
1546 | ||||
1547 | // We need this to handle | |||
1548 | // | |||
1549 | // typedef struct { | |||
1550 | // void *foo() { return 0; } | |||
1551 | // } A; | |||
1552 | // | |||
1553 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' | |||
1554 | // for example. If 'A', foo will have external linkage. If we have '*A', | |||
1555 | // foo will have no linkage. Since we can't know until we get to the end | |||
1556 | // of the typedef, this function finds out if D might have non-external linkage. | |||
1557 | // Callers should verify at the end of the TU if it D has external linkage or | |||
1558 | // not. | |||
1559 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { | |||
1560 | const DeclContext *DC = D->getDeclContext(); | |||
1561 | while (!DC->isTranslationUnit()) { | |||
1562 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ | |||
1563 | if (!RD->hasNameForLinkage()) | |||
1564 | return true; | |||
1565 | } | |||
1566 | DC = DC->getParent(); | |||
1567 | } | |||
1568 | ||||
1569 | return !D->isExternallyVisible(); | |||
1570 | } | |||
1571 | ||||
1572 | // FIXME: This needs to be refactored; some other isInMainFile users want | |||
1573 | // these semantics. | |||
1574 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { | |||
1575 | if (S.TUKind != TU_Complete) | |||
1576 | return false; | |||
1577 | return S.SourceMgr.isInMainFile(Loc); | |||
1578 | } | |||
1579 | ||||
1580 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { | |||
1581 | assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1581, __PRETTY_FUNCTION__)); | |||
1582 | ||||
1583 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) | |||
1584 | return false; | |||
1585 | ||||
1586 | // Ignore all entities declared within templates, and out-of-line definitions | |||
1587 | // of members of class templates. | |||
1588 | if (D->getDeclContext()->isDependentContext() || | |||
1589 | D->getLexicalDeclContext()->isDependentContext()) | |||
1590 | return false; | |||
1591 | ||||
1592 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
1593 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | |||
1594 | return false; | |||
1595 | // A non-out-of-line declaration of a member specialization was implicitly | |||
1596 | // instantiated; it's the out-of-line declaration that we're interested in. | |||
1597 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | |||
1598 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) | |||
1599 | return false; | |||
1600 | ||||
1601 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | |||
1602 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) | |||
1603 | return false; | |||
1604 | } else { | |||
1605 | // 'static inline' functions are defined in headers; don't warn. | |||
1606 | if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) | |||
1607 | return false; | |||
1608 | } | |||
1609 | ||||
1610 | if (FD->doesThisDeclarationHaveABody() && | |||
1611 | Context.DeclMustBeEmitted(FD)) | |||
1612 | return false; | |||
1613 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1614 | // Constants and utility variables are defined in headers with internal | |||
1615 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker | |||
1616 | // like "inline".) | |||
1617 | if (!isMainFileLoc(*this, VD->getLocation())) | |||
1618 | return false; | |||
1619 | ||||
1620 | if (Context.DeclMustBeEmitted(VD)) | |||
1621 | return false; | |||
1622 | ||||
1623 | if (VD->isStaticDataMember() && | |||
1624 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | |||
1625 | return false; | |||
1626 | if (VD->isStaticDataMember() && | |||
1627 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | |||
1628 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) | |||
1629 | return false; | |||
1630 | ||||
1631 | if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) | |||
1632 | return false; | |||
1633 | } else { | |||
1634 | return false; | |||
1635 | } | |||
1636 | ||||
1637 | // Only warn for unused decls internal to the translation unit. | |||
1638 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function | |||
1639 | // for inline functions defined in the main source file, for instance. | |||
1640 | return mightHaveNonExternalLinkage(D); | |||
1641 | } | |||
1642 | ||||
1643 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { | |||
1644 | if (!D) | |||
1645 | return; | |||
1646 | ||||
1647 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
1648 | const FunctionDecl *First = FD->getFirstDecl(); | |||
1649 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | |||
1650 | return; // First should already be in the vector. | |||
1651 | } | |||
1652 | ||||
1653 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1654 | const VarDecl *First = VD->getFirstDecl(); | |||
1655 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | |||
1656 | return; // First should already be in the vector. | |||
1657 | } | |||
1658 | ||||
1659 | if (ShouldWarnIfUnusedFileScopedDecl(D)) | |||
1660 | UnusedFileScopedDecls.push_back(D); | |||
1661 | } | |||
1662 | ||||
1663 | static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { | |||
1664 | if (D->isInvalidDecl()) | |||
1665 | return false; | |||
1666 | ||||
1667 | bool Referenced = false; | |||
1668 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) { | |||
1669 | // For a decomposition declaration, warn if none of the bindings are | |||
1670 | // referenced, instead of if the variable itself is referenced (which | |||
1671 | // it is, by the bindings' expressions). | |||
1672 | for (auto *BD : DD->bindings()) { | |||
1673 | if (BD->isReferenced()) { | |||
1674 | Referenced = true; | |||
1675 | break; | |||
1676 | } | |||
1677 | } | |||
1678 | } else if (!D->getDeclName()) { | |||
1679 | return false; | |||
1680 | } else if (D->isReferenced() || D->isUsed()) { | |||
1681 | Referenced = true; | |||
1682 | } | |||
1683 | ||||
1684 | if (Referenced || D->hasAttr<UnusedAttr>() || | |||
1685 | D->hasAttr<ObjCPreciseLifetimeAttr>()) | |||
1686 | return false; | |||
1687 | ||||
1688 | if (isa<LabelDecl>(D)) | |||
1689 | return true; | |||
1690 | ||||
1691 | // Except for labels, we only care about unused decls that are local to | |||
1692 | // functions. | |||
1693 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); | |||
1694 | if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) | |||
1695 | // For dependent types, the diagnostic is deferred. | |||
1696 | WithinFunction = | |||
1697 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); | |||
1698 | if (!WithinFunction) | |||
1699 | return false; | |||
1700 | ||||
1701 | if (isa<TypedefNameDecl>(D)) | |||
1702 | return true; | |||
1703 | ||||
1704 | // White-list anything that isn't a local variable. | |||
1705 | if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) | |||
1706 | return false; | |||
1707 | ||||
1708 | // Types of valid local variables should be complete, so this should succeed. | |||
1709 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1710 | ||||
1711 | // White-list anything with an __attribute__((unused)) type. | |||
1712 | const auto *Ty = VD->getType().getTypePtr(); | |||
1713 | ||||
1714 | // Only look at the outermost level of typedef. | |||
1715 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { | |||
1716 | if (TT->getDecl()->hasAttr<UnusedAttr>()) | |||
1717 | return false; | |||
1718 | } | |||
1719 | ||||
1720 | // If we failed to complete the type for some reason, or if the type is | |||
1721 | // dependent, don't diagnose the variable. | |||
1722 | if (Ty->isIncompleteType() || Ty->isDependentType()) | |||
1723 | return false; | |||
1724 | ||||
1725 | // Look at the element type to ensure that the warning behaviour is | |||
1726 | // consistent for both scalars and arrays. | |||
1727 | Ty = Ty->getBaseElementTypeUnsafe(); | |||
1728 | ||||
1729 | if (const TagType *TT = Ty->getAs<TagType>()) { | |||
1730 | const TagDecl *Tag = TT->getDecl(); | |||
1731 | if (Tag->hasAttr<UnusedAttr>()) | |||
1732 | return false; | |||
1733 | ||||
1734 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { | |||
1735 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) | |||
1736 | return false; | |||
1737 | ||||
1738 | if (const Expr *Init = VD->getInit()) { | |||
1739 | if (const ExprWithCleanups *Cleanups = | |||
1740 | dyn_cast<ExprWithCleanups>(Init)) | |||
1741 | Init = Cleanups->getSubExpr(); | |||
1742 | const CXXConstructExpr *Construct = | |||
1743 | dyn_cast<CXXConstructExpr>(Init); | |||
1744 | if (Construct && !Construct->isElidable()) { | |||
1745 | CXXConstructorDecl *CD = Construct->getConstructor(); | |||
1746 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && | |||
1747 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) | |||
1748 | return false; | |||
1749 | } | |||
1750 | } | |||
1751 | } | |||
1752 | } | |||
1753 | ||||
1754 | // TODO: __attribute__((unused)) templates? | |||
1755 | } | |||
1756 | ||||
1757 | return true; | |||
1758 | } | |||
1759 | ||||
1760 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, | |||
1761 | FixItHint &Hint) { | |||
1762 | if (isa<LabelDecl>(D)) { | |||
1763 | SourceLocation AfterColon = Lexer::findLocationAfterToken( | |||
1764 | D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), | |||
1765 | true); | |||
1766 | if (AfterColon.isInvalid()) | |||
1767 | return; | |||
1768 | Hint = FixItHint::CreateRemoval( | |||
1769 | CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); | |||
1770 | } | |||
1771 | } | |||
1772 | ||||
1773 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { | |||
1774 | if (D->getTypeForDecl()->isDependentType()) | |||
1775 | return; | |||
1776 | ||||
1777 | for (auto *TmpD : D->decls()) { | |||
1778 | if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) | |||
1779 | DiagnoseUnusedDecl(T); | |||
1780 | else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) | |||
1781 | DiagnoseUnusedNestedTypedefs(R); | |||
1782 | } | |||
1783 | } | |||
1784 | ||||
1785 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used | |||
1786 | /// unless they are marked attr(unused). | |||
1787 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { | |||
1788 | if (!ShouldDiagnoseUnusedDecl(D)) | |||
1789 | return; | |||
1790 | ||||
1791 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { | |||
1792 | // typedefs can be referenced later on, so the diagnostics are emitted | |||
1793 | // at end-of-translation-unit. | |||
1794 | UnusedLocalTypedefNameCandidates.insert(TD); | |||
1795 | return; | |||
1796 | } | |||
1797 | ||||
1798 | FixItHint Hint; | |||
1799 | GenerateFixForUnusedDecl(D, Context, Hint); | |||
1800 | ||||
1801 | unsigned DiagID; | |||
1802 | if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) | |||
1803 | DiagID = diag::warn_unused_exception_param; | |||
1804 | else if (isa<LabelDecl>(D)) | |||
1805 | DiagID = diag::warn_unused_label; | |||
1806 | else | |||
1807 | DiagID = diag::warn_unused_variable; | |||
1808 | ||||
1809 | Diag(D->getLocation(), DiagID) << D << Hint; | |||
1810 | } | |||
1811 | ||||
1812 | static void CheckPoppedLabel(LabelDecl *L, Sema &S) { | |||
1813 | // Verify that we have no forward references left. If so, there was a goto | |||
1814 | // or address of a label taken, but no definition of it. Label fwd | |||
1815 | // definitions are indicated with a null substmt which is also not a resolved | |||
1816 | // MS inline assembly label name. | |||
1817 | bool Diagnose = false; | |||
1818 | if (L->isMSAsmLabel()) | |||
1819 | Diagnose = !L->isResolvedMSAsmLabel(); | |||
1820 | else | |||
1821 | Diagnose = L->getStmt() == nullptr; | |||
1822 | if (Diagnose) | |||
1823 | S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); | |||
1824 | } | |||
1825 | ||||
1826 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { | |||
1827 | S->mergeNRVOIntoParent(); | |||
1828 | ||||
1829 | if (S->decl_empty()) return; | |||
1830 | assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope )) && "Scope shouldn't contain decls!") ? static_cast <void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1831, __PRETTY_FUNCTION__)) | |||
1831 | "Scope shouldn't contain decls!")(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope )) && "Scope shouldn't contain decls!") ? static_cast <void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1831, __PRETTY_FUNCTION__)); | |||
1832 | ||||
1833 | for (auto *TmpD : S->decls()) { | |||
1834 | assert(TmpD && "This decl didn't get pushed??")((TmpD && "This decl didn't get pushed??") ? static_cast <void> (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1834, __PRETTY_FUNCTION__)); | |||
1835 | ||||
1836 | assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?" ) ? static_cast<void> (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1836, __PRETTY_FUNCTION__)); | |||
1837 | NamedDecl *D = cast<NamedDecl>(TmpD); | |||
1838 | ||||
1839 | // Diagnose unused variables in this scope. | |||
1840 | if (!S->hasUnrecoverableErrorOccurred()) { | |||
1841 | DiagnoseUnusedDecl(D); | |||
1842 | if (const auto *RD = dyn_cast<RecordDecl>(D)) | |||
1843 | DiagnoseUnusedNestedTypedefs(RD); | |||
1844 | } | |||
1845 | ||||
1846 | if (!D->getDeclName()) continue; | |||
1847 | ||||
1848 | // If this was a forward reference to a label, verify it was defined. | |||
1849 | if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) | |||
1850 | CheckPoppedLabel(LD, *this); | |||
1851 | ||||
1852 | // Remove this name from our lexical scope, and warn on it if we haven't | |||
1853 | // already. | |||
1854 | IdResolver.RemoveDecl(D); | |||
1855 | auto ShadowI = ShadowingDecls.find(D); | |||
1856 | if (ShadowI != ShadowingDecls.end()) { | |||
1857 | if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { | |||
1858 | Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) | |||
1859 | << D << FD << FD->getParent(); | |||
1860 | Diag(FD->getLocation(), diag::note_previous_declaration); | |||
1861 | } | |||
1862 | ShadowingDecls.erase(ShadowI); | |||
1863 | } | |||
1864 | } | |||
1865 | } | |||
1866 | ||||
1867 | /// Look for an Objective-C class in the translation unit. | |||
1868 | /// | |||
1869 | /// \param Id The name of the Objective-C class we're looking for. If | |||
1870 | /// typo-correction fixes this name, the Id will be updated | |||
1871 | /// to the fixed name. | |||
1872 | /// | |||
1873 | /// \param IdLoc The location of the name in the translation unit. | |||
1874 | /// | |||
1875 | /// \param DoTypoCorrection If true, this routine will attempt typo correction | |||
1876 | /// if there is no class with the given name. | |||
1877 | /// | |||
1878 | /// \returns The declaration of the named Objective-C class, or NULL if the | |||
1879 | /// class could not be found. | |||
1880 | ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, | |||
1881 | SourceLocation IdLoc, | |||
1882 | bool DoTypoCorrection) { | |||
1883 | // The third "scope" argument is 0 since we aren't enabling lazy built-in | |||
1884 | // creation from this context. | |||
1885 | NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); | |||
1886 | ||||
1887 | if (!IDecl && DoTypoCorrection) { | |||
1888 | // Perform typo correction at the given location, but only if we | |||
1889 | // find an Objective-C class name. | |||
1890 | DeclFilterCCC<ObjCInterfaceDecl> CCC{}; | |||
1891 | if (TypoCorrection C = | |||
1892 | CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, | |||
1893 | TUScope, nullptr, CCC, CTK_ErrorRecovery)) { | |||
1894 | diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); | |||
1895 | IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); | |||
1896 | Id = IDecl->getIdentifier(); | |||
1897 | } | |||
1898 | } | |||
1899 | ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); | |||
1900 | // This routine must always return a class definition, if any. | |||
1901 | if (Def && Def->getDefinition()) | |||
1902 | Def = Def->getDefinition(); | |||
1903 | return Def; | |||
1904 | } | |||
1905 | ||||
1906 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting | |||
1907 | /// from S, where a non-field would be declared. This routine copes | |||
1908 | /// with the difference between C and C++ scoping rules in structs and | |||
1909 | /// unions. For example, the following code is well-formed in C but | |||
1910 | /// ill-formed in C++: | |||
1911 | /// @code | |||
1912 | /// struct S6 { | |||
1913 | /// enum { BAR } e; | |||
1914 | /// }; | |||
1915 | /// | |||
1916 | /// void test_S6() { | |||
1917 | /// struct S6 a; | |||
1918 | /// a.e = BAR; | |||
1919 | /// } | |||
1920 | /// @endcode | |||
1921 | /// For the declaration of BAR, this routine will return a different | |||
1922 | /// scope. The scope S will be the scope of the unnamed enumeration | |||
1923 | /// within S6. In C++, this routine will return the scope associated | |||
1924 | /// with S6, because the enumeration's scope is a transparent | |||
1925 | /// context but structures can contain non-field names. In C, this | |||
1926 | /// routine will return the translation unit scope, since the | |||
1927 | /// enumeration's scope is a transparent context and structures cannot | |||
1928 | /// contain non-field names. | |||
1929 | Scope *Sema::getNonFieldDeclScope(Scope *S) { | |||
1930 | while (((S->getFlags() & Scope::DeclScope) == 0) || | |||
1931 | (S->getEntity() && S->getEntity()->isTransparentContext()) || | |||
1932 | (S->isClassScope() && !getLangOpts().CPlusPlus)) | |||
1933 | S = S->getParent(); | |||
1934 | return S; | |||
1935 | } | |||
1936 | ||||
1937 | /// Looks up the declaration of "struct objc_super" and | |||
1938 | /// saves it for later use in building builtin declaration of | |||
1939 | /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such | |||
1940 | /// pre-existing declaration exists no action takes place. | |||
1941 | static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, | |||
1942 | IdentifierInfo *II) { | |||
1943 | if (!II->isStr("objc_msgSendSuper")) | |||
1944 | return; | |||
1945 | ASTContext &Context = ThisSema.Context; | |||
1946 | ||||
1947 | LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), | |||
1948 | SourceLocation(), Sema::LookupTagName); | |||
1949 | ThisSema.LookupName(Result, S); | |||
1950 | if (Result.getResultKind() == LookupResult::Found) | |||
1951 | if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) | |||
1952 | Context.setObjCSuperType(Context.getTagDeclType(TD)); | |||
1953 | } | |||
1954 | ||||
1955 | static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, | |||
1956 | ASTContext::GetBuiltinTypeError Error) { | |||
1957 | switch (Error) { | |||
1958 | case ASTContext::GE_None: | |||
1959 | return ""; | |||
1960 | case ASTContext::GE_Missing_type: | |||
1961 | return BuiltinInfo.getHeaderName(ID); | |||
1962 | case ASTContext::GE_Missing_stdio: | |||
1963 | return "stdio.h"; | |||
1964 | case ASTContext::GE_Missing_setjmp: | |||
1965 | return "setjmp.h"; | |||
1966 | case ASTContext::GE_Missing_ucontext: | |||
1967 | return "ucontext.h"; | |||
1968 | } | |||
1969 | llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 1969); | |||
1970 | } | |||
1971 | ||||
1972 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at | |||
1973 | /// file scope. lazily create a decl for it. ForRedeclaration is true | |||
1974 | /// if we're creating this built-in in anticipation of redeclaring the | |||
1975 | /// built-in. | |||
1976 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, | |||
1977 | Scope *S, bool ForRedeclaration, | |||
1978 | SourceLocation Loc) { | |||
1979 | LookupPredefedObjCSuperType(*this, S, II); | |||
1980 | ||||
1981 | ASTContext::GetBuiltinTypeError Error; | |||
1982 | QualType R = Context.GetBuiltinType(ID, Error); | |||
1983 | if (Error) { | |||
1984 | if (ForRedeclaration) | |||
1985 | Diag(Loc, diag::warn_implicit_decl_requires_sysheader) | |||
1986 | << getHeaderName(Context.BuiltinInfo, ID, Error) | |||
1987 | << Context.BuiltinInfo.getName(ID); | |||
1988 | return nullptr; | |||
1989 | } | |||
1990 | ||||
1991 | if (!ForRedeclaration && | |||
1992 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || | |||
1993 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { | |||
1994 | Diag(Loc, diag::ext_implicit_lib_function_decl) | |||
1995 | << Context.BuiltinInfo.getName(ID) << R; | |||
1996 | if (Context.BuiltinInfo.getHeaderName(ID) && | |||
1997 | !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) | |||
1998 | Diag(Loc, diag::note_include_header_or_declare) | |||
1999 | << Context.BuiltinInfo.getHeaderName(ID) | |||
2000 | << Context.BuiltinInfo.getName(ID); | |||
2001 | } | |||
2002 | ||||
2003 | if (R.isNull()) | |||
2004 | return nullptr; | |||
2005 | ||||
2006 | DeclContext *Parent = Context.getTranslationUnitDecl(); | |||
2007 | if (getLangOpts().CPlusPlus) { | |||
2008 | LinkageSpecDecl *CLinkageDecl = | |||
2009 | LinkageSpecDecl::Create(Context, Parent, Loc, Loc, | |||
2010 | LinkageSpecDecl::lang_c, false); | |||
2011 | CLinkageDecl->setImplicit(); | |||
2012 | Parent->addDecl(CLinkageDecl); | |||
2013 | Parent = CLinkageDecl; | |||
2014 | } | |||
2015 | ||||
2016 | FunctionDecl *New = FunctionDecl::Create(Context, | |||
2017 | Parent, | |||
2018 | Loc, Loc, II, R, /*TInfo=*/nullptr, | |||
2019 | SC_Extern, | |||
2020 | false, | |||
2021 | R->isFunctionProtoType()); | |||
2022 | New->setImplicit(); | |||
2023 | ||||
2024 | // Create Decl objects for each parameter, adding them to the | |||
2025 | // FunctionDecl. | |||
2026 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { | |||
2027 | SmallVector<ParmVarDecl*, 16> Params; | |||
2028 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | |||
2029 | ParmVarDecl *parm = | |||
2030 | ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), | |||
2031 | nullptr, FT->getParamType(i), /*TInfo=*/nullptr, | |||
2032 | SC_None, nullptr); | |||
2033 | parm->setScopeInfo(0, i); | |||
2034 | Params.push_back(parm); | |||
2035 | } | |||
2036 | New->setParams(Params); | |||
2037 | } | |||
2038 | ||||
2039 | AddKnownFunctionAttributes(New); | |||
2040 | RegisterLocallyScopedExternCDecl(New, S); | |||
2041 | ||||
2042 | // TUScope is the translation-unit scope to insert this function into. | |||
2043 | // FIXME: This is hideous. We need to teach PushOnScopeChains to | |||
2044 | // relate Scopes to DeclContexts, and probably eliminate CurContext | |||
2045 | // entirely, but we're not there yet. | |||
2046 | DeclContext *SavedContext = CurContext; | |||
2047 | CurContext = Parent; | |||
2048 | PushOnScopeChains(New, TUScope); | |||
2049 | CurContext = SavedContext; | |||
2050 | return New; | |||
2051 | } | |||
2052 | ||||
2053 | /// Typedef declarations don't have linkage, but they still denote the same | |||
2054 | /// entity if their types are the same. | |||
2055 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's | |||
2056 | /// isSameEntity. | |||
2057 | static void filterNonConflictingPreviousTypedefDecls(Sema &S, | |||
2058 | TypedefNameDecl *Decl, | |||
2059 | LookupResult &Previous) { | |||
2060 | // This is only interesting when modules are enabled. | |||
2061 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) | |||
2062 | return; | |||
2063 | ||||
2064 | // Empty sets are uninteresting. | |||
2065 | if (Previous.empty()) | |||
2066 | return; | |||
2067 | ||||
2068 | LookupResult::Filter Filter = Previous.makeFilter(); | |||
2069 | while (Filter.hasNext()) { | |||
2070 | NamedDecl *Old = Filter.next(); | |||
2071 | ||||
2072 | // Non-hidden declarations are never ignored. | |||
2073 | if (S.isVisible(Old)) | |||
2074 | continue; | |||
2075 | ||||
2076 | // Declarations of the same entity are not ignored, even if they have | |||
2077 | // different linkages. | |||
2078 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | |||
2079 | if (S.Context.hasSameType(OldTD->getUnderlyingType(), | |||
2080 | Decl->getUnderlyingType())) | |||
2081 | continue; | |||
2082 | ||||
2083 | // If both declarations give a tag declaration a typedef name for linkage | |||
2084 | // purposes, then they declare the same entity. | |||
2085 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && | |||
2086 | Decl->getAnonDeclWithTypedefName()) | |||
2087 | continue; | |||
2088 | } | |||
2089 | ||||
2090 | Filter.erase(); | |||
2091 | } | |||
2092 | ||||
2093 | Filter.done(); | |||
2094 | } | |||
2095 | ||||
2096 | bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { | |||
2097 | QualType OldType; | |||
2098 | if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) | |||
2099 | OldType = OldTypedef->getUnderlyingType(); | |||
2100 | else | |||
2101 | OldType = Context.getTypeDeclType(Old); | |||
2102 | QualType NewType = New->getUnderlyingType(); | |||
2103 | ||||
2104 | if (NewType->isVariablyModifiedType()) { | |||
2105 | // Must not redefine a typedef with a variably-modified type. | |||
2106 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | |||
2107 | Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) | |||
2108 | << Kind << NewType; | |||
2109 | if (Old->getLocation().isValid()) | |||
2110 | notePreviousDefinition(Old, New->getLocation()); | |||
2111 | New->setInvalidDecl(); | |||
2112 | return true; | |||
2113 | } | |||
2114 | ||||
2115 | if (OldType != NewType && | |||
2116 | !OldType->isDependentType() && | |||
2117 | !NewType->isDependentType() && | |||
2118 | !Context.hasSameType(OldType, NewType)) { | |||
2119 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | |||
2120 | Diag(New->getLocation(), diag::err_redefinition_different_typedef) | |||
2121 | << Kind << NewType << OldType; | |||
2122 | if (Old->getLocation().isValid()) | |||
2123 | notePreviousDefinition(Old, New->getLocation()); | |||
2124 | New->setInvalidDecl(); | |||
2125 | return true; | |||
2126 | } | |||
2127 | return false; | |||
2128 | } | |||
2129 | ||||
2130 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the | |||
2131 | /// same name and scope as a previous declaration 'Old'. Figure out | |||
2132 | /// how to resolve this situation, merging decls or emitting | |||
2133 | /// diagnostics as appropriate. If there was an error, set New to be invalid. | |||
2134 | /// | |||
2135 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, | |||
2136 | LookupResult &OldDecls) { | |||
2137 | // If the new decl is known invalid already, don't bother doing any | |||
2138 | // merging checks. | |||
2139 | if (New->isInvalidDecl()) return; | |||
2140 | ||||
2141 | // Allow multiple definitions for ObjC built-in typedefs. | |||
2142 | // FIXME: Verify the underlying types are equivalent! | |||
2143 | if (getLangOpts().ObjC) { | |||
2144 | const IdentifierInfo *TypeID = New->getIdentifier(); | |||
2145 | switch (TypeID->getLength()) { | |||
2146 | default: break; | |||
2147 | case 2: | |||
2148 | { | |||
2149 | if (!TypeID->isStr("id")) | |||
2150 | break; | |||
2151 | QualType T = New->getUnderlyingType(); | |||
2152 | if (!T->isPointerType()) | |||
2153 | break; | |||
2154 | if (!T->isVoidPointerType()) { | |||
2155 | QualType PT = T->getAs<PointerType>()->getPointeeType(); | |||
2156 | if (!PT->isStructureType()) | |||
2157 | break; | |||
2158 | } | |||
2159 | Context.setObjCIdRedefinitionType(T); | |||
2160 | // Install the built-in type for 'id', ignoring the current definition. | |||
2161 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); | |||
2162 | return; | |||
2163 | } | |||
2164 | case 5: | |||
2165 | if (!TypeID->isStr("Class")) | |||
2166 | break; | |||
2167 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); | |||
2168 | // Install the built-in type for 'Class', ignoring the current definition. | |||
2169 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); | |||
2170 | return; | |||
2171 | case 3: | |||
2172 | if (!TypeID->isStr("SEL")) | |||
2173 | break; | |||
2174 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); | |||
2175 | // Install the built-in type for 'SEL', ignoring the current definition. | |||
2176 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); | |||
2177 | return; | |||
2178 | } | |||
2179 | // Fall through - the typedef name was not a builtin type. | |||
2180 | } | |||
2181 | ||||
2182 | // Verify the old decl was also a type. | |||
2183 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); | |||
2184 | if (!Old) { | |||
2185 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | |||
2186 | << New->getDeclName(); | |||
2187 | ||||
2188 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); | |||
2189 | if (OldD->getLocation().isValid()) | |||
2190 | notePreviousDefinition(OldD, New->getLocation()); | |||
2191 | ||||
2192 | return New->setInvalidDecl(); | |||
2193 | } | |||
2194 | ||||
2195 | // If the old declaration is invalid, just give up here. | |||
2196 | if (Old->isInvalidDecl()) | |||
2197 | return New->setInvalidDecl(); | |||
2198 | ||||
2199 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | |||
2200 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); | |||
2201 | auto *NewTag = New->getAnonDeclWithTypedefName(); | |||
2202 | NamedDecl *Hidden = nullptr; | |||
2203 | if (OldTag && NewTag && | |||
2204 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && | |||
2205 | !hasVisibleDefinition(OldTag, &Hidden)) { | |||
2206 | // There is a definition of this tag, but it is not visible. Use it | |||
2207 | // instead of our tag. | |||
2208 | New->setTypeForDecl(OldTD->getTypeForDecl()); | |||
2209 | if (OldTD->isModed()) | |||
2210 | New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), | |||
2211 | OldTD->getUnderlyingType()); | |||
2212 | else | |||
2213 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); | |||
2214 | ||||
2215 | // Make the old tag definition visible. | |||
2216 | makeMergedDefinitionVisible(Hidden); | |||
2217 | ||||
2218 | // If this was an unscoped enumeration, yank all of its enumerators | |||
2219 | // out of the scope. | |||
2220 | if (isa<EnumDecl>(NewTag)) { | |||
2221 | Scope *EnumScope = getNonFieldDeclScope(S); | |||
2222 | for (auto *D : NewTag->decls()) { | |||
2223 | auto *ED = cast<EnumConstantDecl>(D); | |||
2224 | assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0 ) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 2224, __PRETTY_FUNCTION__)); | |||
2225 | EnumScope->RemoveDecl(ED); | |||
2226 | IdResolver.RemoveDecl(ED); | |||
2227 | ED->getLexicalDeclContext()->removeDecl(ED); | |||
2228 | } | |||
2229 | } | |||
2230 | } | |||
2231 | } | |||
2232 | ||||
2233 | // If the typedef types are not identical, reject them in all languages and | |||
2234 | // with any extensions enabled. | |||
2235 | if (isIncompatibleTypedef(Old, New)) | |||
2236 | return; | |||
2237 | ||||
2238 | // The types match. Link up the redeclaration chain and merge attributes if | |||
2239 | // the old declaration was a typedef. | |||
2240 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { | |||
2241 | New->setPreviousDecl(Typedef); | |||
2242 | mergeDeclAttributes(New, Old); | |||
2243 | } | |||
2244 | ||||
2245 | if (getLangOpts().MicrosoftExt) | |||
2246 | return; | |||
2247 | ||||
2248 | if (getLangOpts().CPlusPlus) { | |||
2249 | // C++ [dcl.typedef]p2: | |||
2250 | // In a given non-class scope, a typedef specifier can be used to | |||
2251 | // redefine the name of any type declared in that scope to refer | |||
2252 | // to the type to which it already refers. | |||
2253 | if (!isa<CXXRecordDecl>(CurContext)) | |||
2254 | return; | |||
2255 | ||||
2256 | // C++0x [dcl.typedef]p4: | |||
2257 | // In a given class scope, a typedef specifier can be used to redefine | |||
2258 | // any class-name declared in that scope that is not also a typedef-name | |||
2259 | // to refer to the type to which it already refers. | |||
2260 | // | |||
2261 | // This wording came in via DR424, which was a correction to the | |||
2262 | // wording in DR56, which accidentally banned code like: | |||
2263 | // | |||
2264 | // struct S { | |||
2265 | // typedef struct A { } A; | |||
2266 | // }; | |||
2267 | // | |||
2268 | // in the C++03 standard. We implement the C++0x semantics, which | |||
2269 | // allow the above but disallow | |||
2270 | // | |||
2271 | // struct S { | |||
2272 | // typedef int I; | |||
2273 | // typedef int I; | |||
2274 | // }; | |||
2275 | // | |||
2276 | // since that was the intent of DR56. | |||
2277 | if (!isa<TypedefNameDecl>(Old)) | |||
2278 | return; | |||
2279 | ||||
2280 | Diag(New->getLocation(), diag::err_redefinition) | |||
2281 | << New->getDeclName(); | |||
2282 | notePreviousDefinition(Old, New->getLocation()); | |||
2283 | return New->setInvalidDecl(); | |||
2284 | } | |||
2285 | ||||
2286 | // Modules always permit redefinition of typedefs, as does C11. | |||
2287 | if (getLangOpts().Modules || getLangOpts().C11) | |||
2288 | return; | |||
2289 | ||||
2290 | // If we have a redefinition of a typedef in C, emit a warning. This warning | |||
2291 | // is normally mapped to an error, but can be controlled with | |||
2292 | // -Wtypedef-redefinition. If either the original or the redefinition is | |||
2293 | // in a system header, don't emit this for compatibility with GCC. | |||
2294 | if (getDiagnostics().getSuppressSystemWarnings() && | |||
2295 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). | |||
2296 | (Old->isImplicit() || | |||
2297 | Context.getSourceManager().isInSystemHeader(Old->getLocation()) || | |||
2298 | Context.getSourceManager().isInSystemHeader(New->getLocation()))) | |||
2299 | return; | |||
2300 | ||||
2301 | Diag(New->getLocation(), diag::ext_redefinition_of_typedef) | |||
2302 | << New->getDeclName(); | |||
2303 | notePreviousDefinition(Old, New->getLocation()); | |||
2304 | } | |||
2305 | ||||
2306 | /// DeclhasAttr - returns true if decl Declaration already has the target | |||
2307 | /// attribute. | |||
2308 | static bool DeclHasAttr(const Decl *D, const Attr *A) { | |||
2309 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); | |||
2310 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); | |||
2311 | for (const auto *i : D->attrs()) | |||
2312 | if (i->getKind() == A->getKind()) { | |||
2313 | if (Ann) { | |||
2314 | if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) | |||
2315 | return true; | |||
2316 | continue; | |||
2317 | } | |||
2318 | // FIXME: Don't hardcode this check | |||
2319 | if (OA && isa<OwnershipAttr>(i)) | |||
2320 | return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); | |||
2321 | return true; | |||
2322 | } | |||
2323 | ||||
2324 | return false; | |||
2325 | } | |||
2326 | ||||
2327 | static bool isAttributeTargetADefinition(Decl *D) { | |||
2328 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) | |||
2329 | return VD->isThisDeclarationADefinition(); | |||
2330 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) | |||
2331 | return TD->isCompleteDefinition() || TD->isBeingDefined(); | |||
2332 | return true; | |||
2333 | } | |||
2334 | ||||
2335 | /// Merge alignment attributes from \p Old to \p New, taking into account the | |||
2336 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. | |||
2337 | /// | |||
2338 | /// \return \c true if any attributes were added to \p New. | |||
2339 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { | |||
2340 | // Look for alignas attributes on Old, and pick out whichever attribute | |||
2341 | // specifies the strictest alignment requirement. | |||
2342 | AlignedAttr *OldAlignasAttr = nullptr; | |||
2343 | AlignedAttr *OldStrictestAlignAttr = nullptr; | |||
2344 | unsigned OldAlign = 0; | |||
2345 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { | |||
2346 | // FIXME: We have no way of representing inherited dependent alignments | |||
2347 | // in a case like: | |||
2348 | // template<int A, int B> struct alignas(A) X; | |||
2349 | // template<int A, int B> struct alignas(B) X {}; | |||
2350 | // For now, we just ignore any alignas attributes which are not on the | |||
2351 | // definition in such a case. | |||
2352 | if (I->isAlignmentDependent()) | |||
2353 | return false; | |||
2354 | ||||
2355 | if (I->isAlignas()) | |||
2356 | OldAlignasAttr = I; | |||
2357 | ||||
2358 | unsigned Align = I->getAlignment(S.Context); | |||
2359 | if (Align > OldAlign) { | |||
2360 | OldAlign = Align; | |||
2361 | OldStrictestAlignAttr = I; | |||
2362 | } | |||
2363 | } | |||
2364 | ||||
2365 | // Look for alignas attributes on New. | |||
2366 | AlignedAttr *NewAlignasAttr = nullptr; | |||
2367 | unsigned NewAlign = 0; | |||
2368 | for (auto *I : New->specific_attrs<AlignedAttr>()) { | |||
2369 | if (I->isAlignmentDependent()) | |||
2370 | return false; | |||
2371 | ||||
2372 | if (I->isAlignas()) | |||
2373 | NewAlignasAttr = I; | |||
2374 | ||||
2375 | unsigned Align = I->getAlignment(S.Context); | |||
2376 | if (Align > NewAlign) | |||
2377 | NewAlign = Align; | |||
2378 | } | |||
2379 | ||||
2380 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { | |||
2381 | // Both declarations have 'alignas' attributes. We require them to match. | |||
2382 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but | |||
2383 | // fall short. (If two declarations both have alignas, they must both match | |||
2384 | // every definition, and so must match each other if there is a definition.) | |||
2385 | ||||
2386 | // If either declaration only contains 'alignas(0)' specifiers, then it | |||
2387 | // specifies the natural alignment for the type. | |||
2388 | if (OldAlign == 0 || NewAlign == 0) { | |||
2389 | QualType Ty; | |||
2390 | if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) | |||
2391 | Ty = VD->getType(); | |||
2392 | else | |||
2393 | Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); | |||
2394 | ||||
2395 | if (OldAlign == 0) | |||
2396 | OldAlign = S.Context.getTypeAlign(Ty); | |||
2397 | if (NewAlign == 0) | |||
2398 | NewAlign = S.Context.getTypeAlign(Ty); | |||
2399 | } | |||
2400 | ||||
2401 | if (OldAlign != NewAlign) { | |||
2402 | S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) | |||
2403 | << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() | |||
2404 | << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); | |||
2405 | S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); | |||
2406 | } | |||
2407 | } | |||
2408 | ||||
2409 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { | |||
2410 | // C++11 [dcl.align]p6: | |||
2411 | // if any declaration of an entity has an alignment-specifier, | |||
2412 | // every defining declaration of that entity shall specify an | |||
2413 | // equivalent alignment. | |||
2414 | // C11 6.7.5/7: | |||
2415 | // If the definition of an object does not have an alignment | |||
2416 | // specifier, any other declaration of that object shall also | |||
2417 | // have no alignment specifier. | |||
2418 | S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) | |||
2419 | << OldAlignasAttr; | |||
2420 | S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) | |||
2421 | << OldAlignasAttr; | |||
2422 | } | |||
2423 | ||||
2424 | bool AnyAdded = false; | |||
2425 | ||||
2426 | // Ensure we have an attribute representing the strictest alignment. | |||
2427 | if (OldAlign > NewAlign) { | |||
2428 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); | |||
2429 | Clone->setInherited(true); | |||
2430 | New->addAttr(Clone); | |||
2431 | AnyAdded = true; | |||
2432 | } | |||
2433 | ||||
2434 | // Ensure we have an alignas attribute if the old declaration had one. | |||
2435 | if (OldAlignasAttr && !NewAlignasAttr && | |||
2436 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { | |||
2437 | AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); | |||
2438 | Clone->setInherited(true); | |||
2439 | New->addAttr(Clone); | |||
2440 | AnyAdded = true; | |||
2441 | } | |||
2442 | ||||
2443 | return AnyAdded; | |||
2444 | } | |||
2445 | ||||
2446 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, | |||
2447 | const InheritableAttr *Attr, | |||
2448 | Sema::AvailabilityMergeKind AMK) { | |||
2449 | // This function copies an attribute Attr from a previous declaration to the | |||
2450 | // new declaration D if the new declaration doesn't itself have that attribute | |||
2451 | // yet or if that attribute allows duplicates. | |||
2452 | // If you're adding a new attribute that requires logic different from | |||
2453 | // "use explicit attribute on decl if present, else use attribute from | |||
2454 | // previous decl", for example if the attribute needs to be consistent | |||
2455 | // between redeclarations, you need to call a custom merge function here. | |||
2456 | InheritableAttr *NewAttr = nullptr; | |||
2457 | unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); | |||
2458 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) | |||
2459 | NewAttr = S.mergeAvailabilityAttr( | |||
2460 | D, AA->getRange(), AA->getPlatform(), AA->isImplicit(), | |||
2461 | AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(), | |||
2462 | AA->getUnavailable(), AA->getMessage(), AA->getStrict(), | |||
2463 | AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex); | |||
2464 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) | |||
2465 | NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), | |||
2466 | AttrSpellingListIndex); | |||
2467 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) | |||
2468 | NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), | |||
2469 | AttrSpellingListIndex); | |||
2470 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) | |||
2471 | NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), | |||
2472 | AttrSpellingListIndex); | |||
2473 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) | |||
2474 | NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), | |||
2475 | AttrSpellingListIndex); | |||
2476 | else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) | |||
2477 | NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), | |||
2478 | FA->getFormatIdx(), FA->getFirstArg(), | |||
2479 | AttrSpellingListIndex); | |||
2480 | else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) | |||
2481 | NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), | |||
2482 | AttrSpellingListIndex); | |||
2483 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) | |||
2484 | NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(), | |||
2485 | AttrSpellingListIndex); | |||
2486 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) | |||
2487 | NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), | |||
2488 | AttrSpellingListIndex, | |||
2489 | IA->getSemanticSpelling()); | |||
2490 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) | |||
2491 | NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), | |||
2492 | &S.Context.Idents.get(AA->getSpelling()), | |||
2493 | AttrSpellingListIndex); | |||
2494 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && | |||
2495 | (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || | |||
2496 | isa<CUDAGlobalAttr>(Attr))) { | |||
2497 | // CUDA target attributes are part of function signature for | |||
2498 | // overloading purposes and must not be merged. | |||
2499 | return false; | |||
2500 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) | |||
2501 | NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); | |||
2502 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) | |||
2503 | NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); | |||
2504 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) | |||
2505 | NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); | |||
2506 | else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) | |||
2507 | NewAttr = S.mergeCommonAttr(D, *CommonA); | |||
2508 | else if (isa<AlignedAttr>(Attr)) | |||
2509 | // AlignedAttrs are handled separately, because we need to handle all | |||
2510 | // such attributes on a declaration at the same time. | |||
2511 | NewAttr = nullptr; | |||
2512 | else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && | |||
2513 | (AMK == Sema::AMK_Override || | |||
2514 | AMK == Sema::AMK_ProtocolImplementation)) | |||
2515 | NewAttr = nullptr; | |||
2516 | else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) | |||
2517 | NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, | |||
2518 | UA->getGuid()); | |||
2519 | else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) | |||
2520 | NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); | |||
2521 | else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) | |||
2522 | NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); | |||
2523 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) | |||
2524 | NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); | |||
2525 | ||||
2526 | if (NewAttr) { | |||
2527 | NewAttr->setInherited(true); | |||
2528 | D->addAttr(NewAttr); | |||
2529 | if (isa<MSInheritanceAttr>(NewAttr)) | |||
2530 | S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); | |||
2531 | return true; | |||
2532 | } | |||
2533 | ||||
2534 | return false; | |||
2535 | } | |||
2536 | ||||
2537 | static const NamedDecl *getDefinition(const Decl *D) { | |||
2538 | if (const TagDecl *TD = dyn_cast<TagDecl>(D)) | |||
2539 | return TD->getDefinition(); | |||
2540 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
2541 | const VarDecl *Def = VD->getDefinition(); | |||
2542 | if (Def) | |||
2543 | return Def; | |||
2544 | return VD->getActingDefinition(); | |||
2545 | } | |||
2546 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) | |||
2547 | return FD->getDefinition(); | |||
2548 | return nullptr; | |||
2549 | } | |||
2550 | ||||
2551 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { | |||
2552 | for (const auto *Attribute : D->attrs()) | |||
2553 | if (Attribute->getKind() == Kind) | |||
2554 | return true; | |||
2555 | return false; | |||
2556 | } | |||
2557 | ||||
2558 | /// checkNewAttributesAfterDef - If we already have a definition, check that | |||
2559 | /// there are no new attributes in this declaration. | |||
2560 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { | |||
2561 | if (!New->hasAttrs()) | |||
2562 | return; | |||
2563 | ||||
2564 | const NamedDecl *Def = getDefinition(Old); | |||
2565 | if (!Def || Def == New) | |||
2566 | return; | |||
2567 | ||||
2568 | AttrVec &NewAttributes = New->getAttrs(); | |||
2569 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { | |||
2570 | const Attr *NewAttribute = NewAttributes[I]; | |||
2571 | ||||
2572 | if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { | |||
2573 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { | |||
2574 | Sema::SkipBodyInfo SkipBody; | |||
2575 | S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); | |||
2576 | ||||
2577 | // If we're skipping this definition, drop the "alias" attribute. | |||
2578 | if (SkipBody.ShouldSkip) { | |||
2579 | NewAttributes.erase(NewAttributes.begin() + I); | |||
2580 | --E; | |||
2581 | continue; | |||
2582 | } | |||
2583 | } else { | |||
2584 | VarDecl *VD = cast<VarDecl>(New); | |||
2585 | unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == | |||
2586 | VarDecl::TentativeDefinition | |||
2587 | ? diag::err_alias_after_tentative | |||
2588 | : diag::err_redefinition; | |||
2589 | S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); | |||
2590 | if (Diag == diag::err_redefinition) | |||
2591 | S.notePreviousDefinition(Def, VD->getLocation()); | |||
2592 | else | |||
2593 | S.Diag(Def->getLocation(), diag::note_previous_definition); | |||
2594 | VD->setInvalidDecl(); | |||
2595 | } | |||
2596 | ++I; | |||
2597 | continue; | |||
2598 | } | |||
2599 | ||||
2600 | if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { | |||
2601 | // Tentative definitions are only interesting for the alias check above. | |||
2602 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { | |||
2603 | ++I; | |||
2604 | continue; | |||
2605 | } | |||
2606 | } | |||
2607 | ||||
2608 | if (hasAttribute(Def, NewAttribute->getKind())) { | |||
2609 | ++I; | |||
2610 | continue; // regular attr merging will take care of validating this. | |||
2611 | } | |||
2612 | ||||
2613 | if (isa<C11NoReturnAttr>(NewAttribute)) { | |||
2614 | // C's _Noreturn is allowed to be added to a function after it is defined. | |||
2615 | ++I; | |||
2616 | continue; | |||
2617 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { | |||
2618 | if (AA->isAlignas()) { | |||
2619 | // C++11 [dcl.align]p6: | |||
2620 | // if any declaration of an entity has an alignment-specifier, | |||
2621 | // every defining declaration of that entity shall specify an | |||
2622 | // equivalent alignment. | |||
2623 | // C11 6.7.5/7: | |||
2624 | // If the definition of an object does not have an alignment | |||
2625 | // specifier, any other declaration of that object shall also | |||
2626 | // have no alignment specifier. | |||
2627 | S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) | |||
2628 | << AA; | |||
2629 | S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) | |||
2630 | << AA; | |||
2631 | NewAttributes.erase(NewAttributes.begin() + I); | |||
2632 | --E; | |||
2633 | continue; | |||
2634 | } | |||
2635 | } | |||
2636 | ||||
2637 | S.Diag(NewAttribute->getLocation(), | |||
2638 | diag::warn_attribute_precede_definition); | |||
2639 | S.Diag(Def->getLocation(), diag::note_previous_definition); | |||
2640 | NewAttributes.erase(NewAttributes.begin() + I); | |||
2641 | --E; | |||
2642 | } | |||
2643 | } | |||
2644 | ||||
2645 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. | |||
2646 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, | |||
2647 | AvailabilityMergeKind AMK) { | |||
2648 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { | |||
2649 | UsedAttr *NewAttr = OldAttr->clone(Context); | |||
2650 | NewAttr->setInherited(true); | |||
2651 | New->addAttr(NewAttr); | |||
2652 | } | |||
2653 | ||||
2654 | if (!Old->hasAttrs() && !New->hasAttrs()) | |||
2655 | return; | |||
2656 | ||||
2657 | // Attributes declared post-definition are currently ignored. | |||
2658 | checkNewAttributesAfterDef(*this, New, Old); | |||
2659 | ||||
2660 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { | |||
2661 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { | |||
2662 | if (OldA->getLabel() != NewA->getLabel()) { | |||
2663 | // This redeclaration changes __asm__ label. | |||
2664 | Diag(New->getLocation(), diag::err_different_asm_label); | |||
2665 | Diag(OldA->getLocation(), diag::note_previous_declaration); | |||
2666 | } | |||
2667 | } else if (Old->isUsed()) { | |||
2668 | // This redeclaration adds an __asm__ label to a declaration that has | |||
2669 | // already been ODR-used. | |||
2670 | Diag(New->getLocation(), diag::err_late_asm_label_name) | |||
2671 | << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); | |||
2672 | } | |||
2673 | } | |||
2674 | ||||
2675 | // Re-declaration cannot add abi_tag's. | |||
2676 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { | |||
2677 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { | |||
2678 | for (const auto &NewTag : NewAbiTagAttr->tags()) { | |||
2679 | if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), | |||
2680 | NewTag) == OldAbiTagAttr->tags_end()) { | |||
2681 | Diag(NewAbiTagAttr->getLocation(), | |||
2682 | diag::err_new_abi_tag_on_redeclaration) | |||
2683 | << NewTag; | |||
2684 | Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); | |||
2685 | } | |||
2686 | } | |||
2687 | } else { | |||
2688 | Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); | |||
2689 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
2690 | } | |||
2691 | } | |||
2692 | ||||
2693 | // This redeclaration adds a section attribute. | |||
2694 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { | |||
2695 | if (auto *VD = dyn_cast<VarDecl>(New)) { | |||
2696 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { | |||
2697 | Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); | |||
2698 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
2699 | } | |||
2700 | } | |||
2701 | } | |||
2702 | ||||
2703 | // Redeclaration adds code-seg attribute. | |||
2704 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); | |||
2705 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && | |||
2706 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { | |||
2707 | Diag(New->getLocation(), diag::warn_mismatched_section) | |||
2708 | << 0 /*codeseg*/; | |||
2709 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
2710 | } | |||
2711 | ||||
2712 | if (!Old->hasAttrs()) | |||
2713 | return; | |||
2714 | ||||
2715 | bool foundAny = New->hasAttrs(); | |||
2716 | ||||
2717 | // Ensure that any moving of objects within the allocated map is done before | |||
2718 | // we process them. | |||
2719 | if (!foundAny) New->setAttrs(AttrVec()); | |||
2720 | ||||
2721 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { | |||
2722 | // Ignore deprecated/unavailable/availability attributes if requested. | |||
2723 | AvailabilityMergeKind LocalAMK = AMK_None; | |||
2724 | if (isa<DeprecatedAttr>(I) || | |||
2725 | isa<UnavailableAttr>(I) || | |||
2726 | isa<AvailabilityAttr>(I)) { | |||
2727 | switch (AMK) { | |||
2728 | case AMK_None: | |||
2729 | continue; | |||
2730 | ||||
2731 | case AMK_Redeclaration: | |||
2732 | case AMK_Override: | |||
2733 | case AMK_ProtocolImplementation: | |||
2734 | LocalAMK = AMK; | |||
2735 | break; | |||
2736 | } | |||
2737 | } | |||
2738 | ||||
2739 | // Already handled. | |||
2740 | if (isa<UsedAttr>(I)) | |||
2741 | continue; | |||
2742 | ||||
2743 | if (mergeDeclAttribute(*this, New, I, LocalAMK)) | |||
2744 | foundAny = true; | |||
2745 | } | |||
2746 | ||||
2747 | if (mergeAlignedAttrs(*this, New, Old)) | |||
2748 | foundAny = true; | |||
2749 | ||||
2750 | if (!foundAny) New->dropAttrs(); | |||
2751 | } | |||
2752 | ||||
2753 | /// mergeParamDeclAttributes - Copy attributes from the old parameter | |||
2754 | /// to the new one. | |||
2755 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, | |||
2756 | const ParmVarDecl *oldDecl, | |||
2757 | Sema &S) { | |||
2758 | // C++11 [dcl.attr.depend]p2: | |||
2759 | // The first declaration of a function shall specify the | |||
2760 | // carries_dependency attribute for its declarator-id if any declaration | |||
2761 | // of the function specifies the carries_dependency attribute. | |||
2762 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); | |||
2763 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { | |||
2764 | S.Diag(CDA->getLocation(), | |||
2765 | diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; | |||
2766 | // Find the first declaration of the parameter. | |||
2767 | // FIXME: Should we build redeclaration chains for function parameters? | |||
2768 | const FunctionDecl *FirstFD = | |||
2769 | cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); | |||
2770 | const ParmVarDecl *FirstVD = | |||
2771 | FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); | |||
2772 | S.Diag(FirstVD->getLocation(), | |||
2773 | diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; | |||
2774 | } | |||
2775 | ||||
2776 | if (!oldDecl->hasAttrs()) | |||
2777 | return; | |||
2778 | ||||
2779 | bool foundAny = newDecl->hasAttrs(); | |||
2780 | ||||
2781 | // Ensure that any moving of objects within the allocated map is | |||
2782 | // done before we process them. | |||
2783 | if (!foundAny) newDecl->setAttrs(AttrVec()); | |||
2784 | ||||
2785 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { | |||
2786 | if (!DeclHasAttr(newDecl, I)) { | |||
2787 | InheritableAttr *newAttr = | |||
2788 | cast<InheritableParamAttr>(I->clone(S.Context)); | |||
2789 | newAttr->setInherited(true); | |||
2790 | newDecl->addAttr(newAttr); | |||
2791 | foundAny = true; | |||
2792 | } | |||
2793 | } | |||
2794 | ||||
2795 | if (!foundAny) newDecl->dropAttrs(); | |||
2796 | } | |||
2797 | ||||
2798 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, | |||
2799 | const ParmVarDecl *OldParam, | |||
2800 | Sema &S) { | |||
2801 | if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { | |||
2802 | if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { | |||
2803 | if (*Oldnullability != *Newnullability) { | |||
2804 | S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) | |||
2805 | << DiagNullabilityKind( | |||
2806 | *Newnullability, | |||
2807 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | |||
2808 | != 0)) | |||
2809 | << DiagNullabilityKind( | |||
2810 | *Oldnullability, | |||
2811 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | |||
2812 | != 0)); | |||
2813 | S.Diag(OldParam->getLocation(), diag::note_previous_declaration); | |||
2814 | } | |||
2815 | } else { | |||
2816 | QualType NewT = NewParam->getType(); | |||
2817 | NewT = S.Context.getAttributedType( | |||
2818 | AttributedType::getNullabilityAttrKind(*Oldnullability), | |||
2819 | NewT, NewT); | |||
2820 | NewParam->setType(NewT); | |||
2821 | } | |||
2822 | } | |||
2823 | } | |||
2824 | ||||
2825 | namespace { | |||
2826 | ||||
2827 | /// Used in MergeFunctionDecl to keep track of function parameters in | |||
2828 | /// C. | |||
2829 | struct GNUCompatibleParamWarning { | |||
2830 | ParmVarDecl *OldParm; | |||
2831 | ParmVarDecl *NewParm; | |||
2832 | QualType PromotedType; | |||
2833 | }; | |||
2834 | ||||
2835 | } // end anonymous namespace | |||
2836 | ||||
2837 | /// getSpecialMember - get the special member enum for a method. | |||
2838 | Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { | |||
2839 | if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { | |||
2840 | if (Ctor->isDefaultConstructor()) | |||
2841 | return Sema::CXXDefaultConstructor; | |||
2842 | ||||
2843 | if (Ctor->isCopyConstructor()) | |||
2844 | return Sema::CXXCopyConstructor; | |||
2845 | ||||
2846 | if (Ctor->isMoveConstructor()) | |||
2847 | return Sema::CXXMoveConstructor; | |||
2848 | } else if (isa<CXXDestructorDecl>(MD)) { | |||
2849 | return Sema::CXXDestructor; | |||
2850 | } else if (MD->isCopyAssignmentOperator()) { | |||
2851 | return Sema::CXXCopyAssignment; | |||
2852 | } else if (MD->isMoveAssignmentOperator()) { | |||
2853 | return Sema::CXXMoveAssignment; | |||
2854 | } | |||
2855 | ||||
2856 | return Sema::CXXInvalid; | |||
2857 | } | |||
2858 | ||||
2859 | // Determine whether the previous declaration was a definition, implicit | |||
2860 | // declaration, or a declaration. | |||
2861 | template <typename T> | |||
2862 | static std::pair<diag::kind, SourceLocation> | |||
2863 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { | |||
2864 | diag::kind PrevDiag; | |||
2865 | SourceLocation OldLocation = Old->getLocation(); | |||
2866 | if (Old->isThisDeclarationADefinition()) | |||
2867 | PrevDiag = diag::note_previous_definition; | |||
2868 | else if (Old->isImplicit()) { | |||
2869 | PrevDiag = diag::note_previous_implicit_declaration; | |||
2870 | if (OldLocation.isInvalid()) | |||
2871 | OldLocation = New->getLocation(); | |||
2872 | } else | |||
2873 | PrevDiag = diag::note_previous_declaration; | |||
2874 | return std::make_pair(PrevDiag, OldLocation); | |||
2875 | } | |||
2876 | ||||
2877 | /// canRedefineFunction - checks if a function can be redefined. Currently, | |||
2878 | /// only extern inline functions can be redefined, and even then only in | |||
2879 | /// GNU89 mode. | |||
2880 | static bool canRedefineFunction(const FunctionDecl *FD, | |||
2881 | const LangOptions& LangOpts) { | |||
2882 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && | |||
2883 | !LangOpts.CPlusPlus && | |||
2884 | FD->isInlineSpecified() && | |||
2885 | FD->getStorageClass() == SC_Extern); | |||
2886 | } | |||
2887 | ||||
2888 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { | |||
2889 | const AttributedType *AT = T->getAs<AttributedType>(); | |||
2890 | while (AT && !AT->isCallingConv()) | |||
2891 | AT = AT->getModifiedType()->getAs<AttributedType>(); | |||
2892 | return AT; | |||
2893 | } | |||
2894 | ||||
2895 | template <typename T> | |||
2896 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { | |||
2897 | const DeclContext *DC = Old->getDeclContext(); | |||
2898 | if (DC->isRecord()) | |||
2899 | return false; | |||
2900 | ||||
2901 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); | |||
2902 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) | |||
2903 | return true; | |||
2904 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) | |||
2905 | return true; | |||
2906 | return false; | |||
2907 | } | |||
2908 | ||||
2909 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } | |||
2910 | static bool isExternC(VarTemplateDecl *) { return false; } | |||
2911 | ||||
2912 | /// Check whether a redeclaration of an entity introduced by a | |||
2913 | /// using-declaration is valid, given that we know it's not an overload | |||
2914 | /// (nor a hidden tag declaration). | |||
2915 | template<typename ExpectedDecl> | |||
2916 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, | |||
2917 | ExpectedDecl *New) { | |||
2918 | // C++11 [basic.scope.declarative]p4: | |||
2919 | // Given a set of declarations in a single declarative region, each of | |||
2920 | // which specifies the same unqualified name, | |||
2921 | // -- they shall all refer to the same entity, or all refer to functions | |||
2922 | // and function templates; or | |||
2923 | // -- exactly one declaration shall declare a class name or enumeration | |||
2924 | // name that is not a typedef name and the other declarations shall all | |||
2925 | // refer to the same variable or enumerator, or all refer to functions | |||
2926 | // and function templates; in this case the class name or enumeration | |||
2927 | // name is hidden (3.3.10). | |||
2928 | ||||
2929 | // C++11 [namespace.udecl]p14: | |||
2930 | // If a function declaration in namespace scope or block scope has the | |||
2931 | // same name and the same parameter-type-list as a function introduced | |||
2932 | // by a using-declaration, and the declarations do not declare the same | |||
2933 | // function, the program is ill-formed. | |||
2934 | ||||
2935 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); | |||
2936 | if (Old && | |||
2937 | !Old->getDeclContext()->getRedeclContext()->Equals( | |||
2938 | New->getDeclContext()->getRedeclContext()) && | |||
2939 | !(isExternC(Old) && isExternC(New))) | |||
2940 | Old = nullptr; | |||
2941 | ||||
2942 | if (!Old) { | |||
2943 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); | |||
2944 | S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); | |||
2945 | S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; | |||
2946 | return true; | |||
2947 | } | |||
2948 | return false; | |||
2949 | } | |||
2950 | ||||
2951 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, | |||
2952 | const FunctionDecl *B) { | |||
2953 | assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast <void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 2953, __PRETTY_FUNCTION__)); | |||
2954 | ||||
2955 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { | |||
2956 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); | |||
2957 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); | |||
2958 | if (AttrA == AttrB) | |||
2959 | return true; | |||
2960 | return AttrA && AttrB && AttrA->getType() == AttrB->getType() && | |||
2961 | AttrA->isDynamic() == AttrB->isDynamic(); | |||
2962 | }; | |||
2963 | ||||
2964 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); | |||
2965 | } | |||
2966 | ||||
2967 | /// If necessary, adjust the semantic declaration context for a qualified | |||
2968 | /// declaration to name the correct inline namespace within the qualifier. | |||
2969 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, | |||
2970 | DeclaratorDecl *OldD) { | |||
2971 | // The only case where we need to update the DeclContext is when | |||
2972 | // redeclaration lookup for a qualified name finds a declaration | |||
2973 | // in an inline namespace within the context named by the qualifier: | |||
2974 | // | |||
2975 | // inline namespace N { int f(); } | |||
2976 | // int ::f(); // Sema DC needs adjusting from :: to N::. | |||
2977 | // | |||
2978 | // For unqualified declarations, the semantic context *can* change | |||
2979 | // along the redeclaration chain (for local extern declarations, | |||
2980 | // extern "C" declarations, and friend declarations in particular). | |||
2981 | if (!NewD->getQualifier()) | |||
2982 | return; | |||
2983 | ||||
2984 | // NewD is probably already in the right context. | |||
2985 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); | |||
2986 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); | |||
2987 | if (NamedDC->Equals(SemaDC)) | |||
2988 | return; | |||
2989 | ||||
2990 | assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 2992, __PRETTY_FUNCTION__)) | |||
2991 | NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 2992, __PRETTY_FUNCTION__)) | |||
2992 | "unexpected context for redeclaration")(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 2992, __PRETTY_FUNCTION__)); | |||
2993 | ||||
2994 | auto *LexDC = NewD->getLexicalDeclContext(); | |||
2995 | auto FixSemaDC = [=](NamedDecl *D) { | |||
2996 | if (!D) | |||
2997 | return; | |||
2998 | D->setDeclContext(SemaDC); | |||
2999 | D->setLexicalDeclContext(LexDC); | |||
3000 | }; | |||
3001 | ||||
3002 | FixSemaDC(NewD); | |||
3003 | if (auto *FD = dyn_cast<FunctionDecl>(NewD)) | |||
3004 | FixSemaDC(FD->getDescribedFunctionTemplate()); | |||
3005 | else if (auto *VD = dyn_cast<VarDecl>(NewD)) | |||
3006 | FixSemaDC(VD->getDescribedVarTemplate()); | |||
3007 | } | |||
3008 | ||||
3009 | /// MergeFunctionDecl - We just parsed a function 'New' from | |||
3010 | /// declarator D which has the same name and scope as a previous | |||
3011 | /// declaration 'Old'. Figure out how to resolve this situation, | |||
3012 | /// merging decls or emitting diagnostics as appropriate. | |||
3013 | /// | |||
3014 | /// In C++, New and Old must be declarations that are not | |||
3015 | /// overloaded. Use IsOverload to determine whether New and Old are | |||
3016 | /// overloaded, and to select the Old declaration that New should be | |||
3017 | /// merged with. | |||
3018 | /// | |||
3019 | /// Returns true if there was an error, false otherwise. | |||
3020 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, | |||
3021 | Scope *S, bool MergeTypeWithOld) { | |||
3022 | // Verify the old decl was also a function. | |||
3023 | FunctionDecl *Old = OldD->getAsFunction(); | |||
3024 | if (!Old) { | |||
3025 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { | |||
3026 | if (New->getFriendObjectKind()) { | |||
3027 | Diag(New->getLocation(), diag::err_using_decl_friend); | |||
3028 | Diag(Shadow->getTargetDecl()->getLocation(), | |||
3029 | diag::note_using_decl_target); | |||
3030 | Diag(Shadow->getUsingDecl()->getLocation(), | |||
3031 | diag::note_using_decl) << 0; | |||
3032 | return true; | |||
3033 | } | |||
3034 | ||||
3035 | // Check whether the two declarations might declare the same function. | |||
3036 | if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) | |||
3037 | return true; | |||
3038 | OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); | |||
3039 | } else { | |||
3040 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | |||
3041 | << New->getDeclName(); | |||
3042 | notePreviousDefinition(OldD, New->getLocation()); | |||
3043 | return true; | |||
3044 | } | |||
3045 | } | |||
3046 | ||||
3047 | // If the old declaration is invalid, just give up here. | |||
3048 | if (Old->isInvalidDecl()) | |||
3049 | return true; | |||
3050 | ||||
3051 | // Disallow redeclaration of some builtins. | |||
3052 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { | |||
3053 | Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); | |||
3054 | Diag(Old->getLocation(), diag::note_previous_builtin_declaration) | |||
3055 | << Old << Old->getType(); | |||
3056 | return true; | |||
3057 | } | |||
3058 | ||||
3059 | diag::kind PrevDiag; | |||
3060 | SourceLocation OldLocation; | |||
3061 | std::tie(PrevDiag, OldLocation) = | |||
3062 | getNoteDiagForInvalidRedeclaration(Old, New); | |||
3063 | ||||
3064 | // Don't complain about this if we're in GNU89 mode and the old function | |||
3065 | // is an extern inline function. | |||
3066 | // Don't complain about specializations. They are not supposed to have | |||
3067 | // storage classes. | |||
3068 | if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && | |||
3069 | New->getStorageClass() == SC_Static && | |||
3070 | Old->hasExternalFormalLinkage() && | |||
3071 | !New->getTemplateSpecializationInfo() && | |||
3072 | !canRedefineFunction(Old, getLangOpts())) { | |||
3073 | if (getLangOpts().MicrosoftExt) { | |||
3074 | Diag(New->getLocation(), diag::ext_static_non_static) << New; | |||
3075 | Diag(OldLocation, PrevDiag); | |||
3076 | } else { | |||
3077 | Diag(New->getLocation(), diag::err_static_non_static) << New; | |||
3078 | Diag(OldLocation, PrevDiag); | |||
3079 | return true; | |||
3080 | } | |||
3081 | } | |||
3082 | ||||
3083 | if (New->hasAttr<InternalLinkageAttr>() && | |||
3084 | !Old->hasAttr<InternalLinkageAttr>()) { | |||
3085 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | |||
3086 | << New->getDeclName(); | |||
3087 | notePreviousDefinition(Old, New->getLocation()); | |||
3088 | New->dropAttr<InternalLinkageAttr>(); | |||
3089 | } | |||
3090 | ||||
3091 | if (CheckRedeclarationModuleOwnership(New, Old)) | |||
3092 | return true; | |||
3093 | ||||
3094 | if (!getLangOpts().CPlusPlus) { | |||
3095 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); | |||
3096 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { | |||
3097 | Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) | |||
3098 | << New << OldOvl; | |||
3099 | ||||
3100 | // Try our best to find a decl that actually has the overloadable | |||
3101 | // attribute for the note. In most cases (e.g. programs with only one | |||
3102 | // broken declaration/definition), this won't matter. | |||
3103 | // | |||
3104 | // FIXME: We could do this if we juggled some extra state in | |||
3105 | // OverloadableAttr, rather than just removing it. | |||
3106 | const Decl *DiagOld = Old; | |||
3107 | if (OldOvl) { | |||
3108 | auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { | |||
3109 | const auto *A = D->getAttr<OverloadableAttr>(); | |||
3110 | return A && !A->isImplicit(); | |||
3111 | }); | |||
3112 | // If we've implicitly added *all* of the overloadable attrs to this | |||
3113 | // chain, emitting a "previous redecl" note is pointless. | |||
3114 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; | |||
3115 | } | |||
3116 | ||||
3117 | if (DiagOld) | |||
3118 | Diag(DiagOld->getLocation(), | |||
3119 | diag::note_attribute_overloadable_prev_overload) | |||
3120 | << OldOvl; | |||
3121 | ||||
3122 | if (OldOvl) | |||
3123 | New->addAttr(OverloadableAttr::CreateImplicit(Context)); | |||
3124 | else | |||
3125 | New->dropAttr<OverloadableAttr>(); | |||
3126 | } | |||
3127 | } | |||
3128 | ||||
3129 | // If a function is first declared with a calling convention, but is later | |||
3130 | // declared or defined without one, all following decls assume the calling | |||
3131 | // convention of the first. | |||
3132 | // | |||
3133 | // It's OK if a function is first declared without a calling convention, | |||
3134 | // but is later declared or defined with the default calling convention. | |||
3135 | // | |||
3136 | // To test if either decl has an explicit calling convention, we look for | |||
3137 | // AttributedType sugar nodes on the type as written. If they are missing or | |||
3138 | // were canonicalized away, we assume the calling convention was implicit. | |||
3139 | // | |||
3140 | // Note also that we DO NOT return at this point, because we still have | |||
3141 | // other tests to run. | |||
3142 | QualType OldQType = Context.getCanonicalType(Old->getType()); | |||
3143 | QualType NewQType = Context.getCanonicalType(New->getType()); | |||
3144 | const FunctionType *OldType = cast<FunctionType>(OldQType); | |||
3145 | const FunctionType *NewType = cast<FunctionType>(NewQType); | |||
3146 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | |||
3147 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | |||
3148 | bool RequiresAdjustment = false; | |||
3149 | ||||
3150 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { | |||
3151 | FunctionDecl *First = Old->getFirstDecl(); | |||
3152 | const FunctionType *FT = | |||
3153 | First->getType().getCanonicalType()->castAs<FunctionType>(); | |||
3154 | FunctionType::ExtInfo FI = FT->getExtInfo(); | |||
3155 | bool NewCCExplicit = getCallingConvAttributedType(New->getType()); | |||
3156 | if (!NewCCExplicit) { | |||
3157 | // Inherit the CC from the previous declaration if it was specified | |||
3158 | // there but not here. | |||
3159 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | |||
3160 | RequiresAdjustment = true; | |||
3161 | } else if (New->getBuiltinID()) { | |||
3162 | // Calling Conventions on a Builtin aren't really useful and setting a | |||
3163 | // default calling convention and cdecl'ing some builtin redeclarations is | |||
3164 | // common, so warn and ignore the calling convention on the redeclaration. | |||
3165 | Diag(New->getLocation(), diag::warn_cconv_ignored) | |||
3166 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | |||
3167 | << (int)CallingConventionIgnoredReason::BuiltinFunction; | |||
3168 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | |||
3169 | RequiresAdjustment = true; | |||
3170 | } else { | |||
3171 | // Calling conventions aren't compatible, so complain. | |||
3172 | bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); | |||
3173 | Diag(New->getLocation(), diag::err_cconv_change) | |||
3174 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | |||
3175 | << !FirstCCExplicit | |||
3176 | << (!FirstCCExplicit ? "" : | |||
3177 | FunctionType::getNameForCallConv(FI.getCC())); | |||
3178 | ||||
3179 | // Put the note on the first decl, since it is the one that matters. | |||
3180 | Diag(First->getLocation(), diag::note_previous_declaration); | |||
3181 | return true; | |||
3182 | } | |||
3183 | } | |||
3184 | ||||
3185 | // FIXME: diagnose the other way around? | |||
3186 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { | |||
3187 | NewTypeInfo = NewTypeInfo.withNoReturn(true); | |||
3188 | RequiresAdjustment = true; | |||
3189 | } | |||
3190 | ||||
3191 | // Merge regparm attribute. | |||
3192 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || | |||
3193 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { | |||
3194 | if (NewTypeInfo.getHasRegParm()) { | |||
3195 | Diag(New->getLocation(), diag::err_regparm_mismatch) | |||
3196 | << NewType->getRegParmType() | |||
3197 | << OldType->getRegParmType(); | |||
3198 | Diag(OldLocation, diag::note_previous_declaration); | |||
3199 | return true; | |||
3200 | } | |||
3201 | ||||
3202 | NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); | |||
3203 | RequiresAdjustment = true; | |||
3204 | } | |||
3205 | ||||
3206 | // Merge ns_returns_retained attribute. | |||
3207 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { | |||
3208 | if (NewTypeInfo.getProducesResult()) { | |||
3209 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) | |||
3210 | << "'ns_returns_retained'"; | |||
3211 | Diag(OldLocation, diag::note_previous_declaration); | |||
3212 | return true; | |||
3213 | } | |||
3214 | ||||
3215 | NewTypeInfo = NewTypeInfo.withProducesResult(true); | |||
3216 | RequiresAdjustment = true; | |||
3217 | } | |||
3218 | ||||
3219 | if (OldTypeInfo.getNoCallerSavedRegs() != | |||
3220 | NewTypeInfo.getNoCallerSavedRegs()) { | |||
3221 | if (NewTypeInfo.getNoCallerSavedRegs()) { | |||
3222 | AnyX86NoCallerSavedRegistersAttr *Attr = | |||
3223 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); | |||
3224 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; | |||
3225 | Diag(OldLocation, diag::note_previous_declaration); | |||
3226 | return true; | |||
3227 | } | |||
3228 | ||||
3229 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); | |||
3230 | RequiresAdjustment = true; | |||
3231 | } | |||
3232 | ||||
3233 | if (RequiresAdjustment) { | |||
3234 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); | |||
3235 | AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); | |||
3236 | New->setType(QualType(AdjustedType, 0)); | |||
3237 | NewQType = Context.getCanonicalType(New->getType()); | |||
3238 | NewType = cast<FunctionType>(NewQType); | |||
3239 | } | |||
3240 | ||||
3241 | // If this redeclaration makes the function inline, we may need to add it to | |||
3242 | // UndefinedButUsed. | |||
3243 | if (!Old->isInlined() && New->isInlined() && | |||
3244 | !New->hasAttr<GNUInlineAttr>() && | |||
3245 | !getLangOpts().GNUInline && | |||
3246 | Old->isUsed(false) && | |||
3247 | !Old->isDefined() && !New->isThisDeclarationADefinition()) | |||
3248 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | |||
3249 | SourceLocation())); | |||
3250 | ||||
3251 | // If this redeclaration makes it newly gnu_inline, we don't want to warn | |||
3252 | // about it. | |||
3253 | if (New->hasAttr<GNUInlineAttr>() && | |||
3254 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { | |||
3255 | UndefinedButUsed.erase(Old->getCanonicalDecl()); | |||
3256 | } | |||
3257 | ||||
3258 | // If pass_object_size params don't match up perfectly, this isn't a valid | |||
3259 | // redeclaration. | |||
3260 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && | |||
3261 | !hasIdenticalPassObjectSizeAttrs(Old, New)) { | |||
3262 | Diag(New->getLocation(), diag::err_different_pass_object_size_params) | |||
3263 | << New->getDeclName(); | |||
3264 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3265 | return true; | |||
3266 | } | |||
3267 | ||||
3268 | if (getLangOpts().CPlusPlus) { | |||
3269 | // C++1z [over.load]p2 | |||
3270 | // Certain function declarations cannot be overloaded: | |||
3271 | // -- Function declarations that differ only in the return type, | |||
3272 | // the exception specification, or both cannot be overloaded. | |||
3273 | ||||
3274 | // Check the exception specifications match. This may recompute the type of | |||
3275 | // both Old and New if it resolved exception specifications, so grab the | |||
3276 | // types again after this. Because this updates the type, we do this before | |||
3277 | // any of the other checks below, which may update the "de facto" NewQType | |||
3278 | // but do not necessarily update the type of New. | |||
3279 | if (CheckEquivalentExceptionSpec(Old, New)) | |||
3280 | return true; | |||
3281 | OldQType = Context.getCanonicalType(Old->getType()); | |||
3282 | NewQType = Context.getCanonicalType(New->getType()); | |||
3283 | ||||
3284 | // Go back to the type source info to compare the declared return types, | |||
3285 | // per C++1y [dcl.type.auto]p13: | |||
3286 | // Redeclarations or specializations of a function or function template | |||
3287 | // with a declared return type that uses a placeholder type shall also | |||
3288 | // use that placeholder, not a deduced type. | |||
3289 | QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); | |||
3290 | QualType NewDeclaredReturnType = New->getDeclaredReturnType(); | |||
3291 | if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && | |||
3292 | canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, | |||
3293 | OldDeclaredReturnType)) { | |||
3294 | QualType ResQT; | |||
3295 | if (NewDeclaredReturnType->isObjCObjectPointerType() && | |||
3296 | OldDeclaredReturnType->isObjCObjectPointerType()) | |||
3297 | // FIXME: This does the wrong thing for a deduced return type. | |||
3298 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); | |||
3299 | if (ResQT.isNull()) { | |||
3300 | if (New->isCXXClassMember() && New->isOutOfLine()) | |||
3301 | Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) | |||
3302 | << New << New->getReturnTypeSourceRange(); | |||
3303 | else | |||
3304 | Diag(New->getLocation(), diag::err_ovl_diff_return_type) | |||
3305 | << New->getReturnTypeSourceRange(); | |||
3306 | Diag(OldLocation, PrevDiag) << Old << Old->getType() | |||
3307 | << Old->getReturnTypeSourceRange(); | |||
3308 | return true; | |||
3309 | } | |||
3310 | else | |||
3311 | NewQType = ResQT; | |||
3312 | } | |||
3313 | ||||
3314 | QualType OldReturnType = OldType->getReturnType(); | |||
3315 | QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); | |||
3316 | if (OldReturnType != NewReturnType) { | |||
3317 | // If this function has a deduced return type and has already been | |||
3318 | // defined, copy the deduced value from the old declaration. | |||
3319 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); | |||
3320 | if (OldAT && OldAT->isDeduced()) { | |||
3321 | New->setType( | |||
3322 | SubstAutoType(New->getType(), | |||
3323 | OldAT->isDependentType() ? Context.DependentTy | |||
3324 | : OldAT->getDeducedType())); | |||
3325 | NewQType = Context.getCanonicalType( | |||
3326 | SubstAutoType(NewQType, | |||
3327 | OldAT->isDependentType() ? Context.DependentTy | |||
3328 | : OldAT->getDeducedType())); | |||
3329 | } | |||
3330 | } | |||
3331 | ||||
3332 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); | |||
3333 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); | |||
3334 | if (OldMethod && NewMethod) { | |||
3335 | // Preserve triviality. | |||
3336 | NewMethod->setTrivial(OldMethod->isTrivial()); | |||
3337 | ||||
3338 | // MSVC allows explicit template specialization at class scope: | |||
3339 | // 2 CXXMethodDecls referring to the same function will be injected. | |||
3340 | // We don't want a redeclaration error. | |||
3341 | bool IsClassScopeExplicitSpecialization = | |||
3342 | OldMethod->isFunctionTemplateSpecialization() && | |||
3343 | NewMethod->isFunctionTemplateSpecialization(); | |||
3344 | bool isFriend = NewMethod->getFriendObjectKind(); | |||
3345 | ||||
3346 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && | |||
3347 | !IsClassScopeExplicitSpecialization) { | |||
3348 | // -- Member function declarations with the same name and the | |||
3349 | // same parameter types cannot be overloaded if any of them | |||
3350 | // is a static member function declaration. | |||
3351 | if (OldMethod->isStatic() != NewMethod->isStatic()) { | |||
3352 | Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); | |||
3353 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3354 | return true; | |||
3355 | } | |||
3356 | ||||
3357 | // C++ [class.mem]p1: | |||
3358 | // [...] A member shall not be declared twice in the | |||
3359 | // member-specification, except that a nested class or member | |||
3360 | // class template can be declared and then later defined. | |||
3361 | if (!inTemplateInstantiation()) { | |||
3362 | unsigned NewDiag; | |||
3363 | if (isa<CXXConstructorDecl>(OldMethod)) | |||
3364 | NewDiag = diag::err_constructor_redeclared; | |||
3365 | else if (isa<CXXDestructorDecl>(NewMethod)) | |||
3366 | NewDiag = diag::err_destructor_redeclared; | |||
3367 | else if (isa<CXXConversionDecl>(NewMethod)) | |||
3368 | NewDiag = diag::err_conv_function_redeclared; | |||
3369 | else | |||
3370 | NewDiag = diag::err_member_redeclared; | |||
3371 | ||||
3372 | Diag(New->getLocation(), NewDiag); | |||
3373 | } else { | |||
3374 | Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) | |||
3375 | << New << New->getType(); | |||
3376 | } | |||
3377 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3378 | return true; | |||
3379 | ||||
3380 | // Complain if this is an explicit declaration of a special | |||
3381 | // member that was initially declared implicitly. | |||
3382 | // | |||
3383 | // As an exception, it's okay to befriend such methods in order | |||
3384 | // to permit the implicit constructor/destructor/operator calls. | |||
3385 | } else if (OldMethod->isImplicit()) { | |||
3386 | if (isFriend) { | |||
3387 | NewMethod->setImplicit(); | |||
3388 | } else { | |||
3389 | Diag(NewMethod->getLocation(), | |||
3390 | diag::err_definition_of_implicitly_declared_member) | |||
3391 | << New << getSpecialMember(OldMethod); | |||
3392 | return true; | |||
3393 | } | |||
3394 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { | |||
3395 | Diag(NewMethod->getLocation(), | |||
3396 | diag::err_definition_of_explicitly_defaulted_member) | |||
3397 | << getSpecialMember(OldMethod); | |||
3398 | return true; | |||
3399 | } | |||
3400 | } | |||
3401 | ||||
3402 | // C++11 [dcl.attr.noreturn]p1: | |||
3403 | // The first declaration of a function shall specify the noreturn | |||
3404 | // attribute if any declaration of that function specifies the noreturn | |||
3405 | // attribute. | |||
3406 | const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); | |||
3407 | if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { | |||
3408 | Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); | |||
3409 | Diag(Old->getFirstDecl()->getLocation(), | |||
3410 | diag::note_noreturn_missing_first_decl); | |||
3411 | } | |||
3412 | ||||
3413 | // C++11 [dcl.attr.depend]p2: | |||
3414 | // The first declaration of a function shall specify the | |||
3415 | // carries_dependency attribute for its declarator-id if any declaration | |||
3416 | // of the function specifies the carries_dependency attribute. | |||
3417 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); | |||
3418 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { | |||
3419 | Diag(CDA->getLocation(), | |||
3420 | diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; | |||
3421 | Diag(Old->getFirstDecl()->getLocation(), | |||
3422 | diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; | |||
3423 | } | |||
3424 | ||||
3425 | // (C++98 8.3.5p3): | |||
3426 | // All declarations for a function shall agree exactly in both the | |||
3427 | // return type and the parameter-type-list. | |||
3428 | // We also want to respect all the extended bits except noreturn. | |||
3429 | ||||
3430 | // noreturn should now match unless the old type info didn't have it. | |||
3431 | QualType OldQTypeForComparison = OldQType; | |||
3432 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { | |||
3433 | auto *OldType = OldQType->castAs<FunctionProtoType>(); | |||
3434 | const FunctionType *OldTypeForComparison | |||
3435 | = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); | |||
3436 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); | |||
3437 | assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void> (0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 3437, __PRETTY_FUNCTION__)); | |||
3438 | } | |||
3439 | ||||
3440 | if (haveIncompatibleLanguageLinkages(Old, New)) { | |||
3441 | // As a special case, retain the language linkage from previous | |||
3442 | // declarations of a friend function as an extension. | |||
3443 | // | |||
3444 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC | |||
3445 | // and is useful because there's otherwise no way to specify language | |||
3446 | // linkage within class scope. | |||
3447 | // | |||
3448 | // Check cautiously as the friend object kind isn't yet complete. | |||
3449 | if (New->getFriendObjectKind() != Decl::FOK_None) { | |||
3450 | Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; | |||
3451 | Diag(OldLocation, PrevDiag); | |||
3452 | } else { | |||
3453 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | |||
3454 | Diag(OldLocation, PrevDiag); | |||
3455 | return true; | |||
3456 | } | |||
3457 | } | |||
3458 | ||||
3459 | if (OldQTypeForComparison == NewQType) | |||
3460 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | |||
3461 | ||||
3462 | // If the types are imprecise (due to dependent constructs in friends or | |||
3463 | // local extern declarations), it's OK if they differ. We'll check again | |||
3464 | // during instantiation. | |||
3465 | if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) | |||
3466 | return false; | |||
3467 | ||||
3468 | // Fall through for conflicting redeclarations and redefinitions. | |||
3469 | } | |||
3470 | ||||
3471 | // C: Function types need to be compatible, not identical. This handles | |||
3472 | // duplicate function decls like "void f(int); void f(enum X);" properly. | |||
3473 | if (!getLangOpts().CPlusPlus && | |||
3474 | Context.typesAreCompatible(OldQType, NewQType)) { | |||
3475 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); | |||
3476 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); | |||
3477 | const FunctionProtoType *OldProto = nullptr; | |||
3478 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && | |||
3479 | (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { | |||
3480 | // The old declaration provided a function prototype, but the | |||
3481 | // new declaration does not. Merge in the prototype. | |||
3482 | assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((!OldProto->hasExceptionSpec() && "Exception spec in C" ) ? static_cast<void> (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 3482, __PRETTY_FUNCTION__)); | |||
3483 | SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); | |||
3484 | NewQType = | |||
3485 | Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, | |||
3486 | OldProto->getExtProtoInfo()); | |||
3487 | New->setType(NewQType); | |||
3488 | New->setHasInheritedPrototype(); | |||
3489 | ||||
3490 | // Synthesize parameters with the same types. | |||
3491 | SmallVector<ParmVarDecl*, 16> Params; | |||
3492 | for (const auto &ParamType : OldProto->param_types()) { | |||
3493 | ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), | |||
3494 | SourceLocation(), nullptr, | |||
3495 | ParamType, /*TInfo=*/nullptr, | |||
3496 | SC_None, nullptr); | |||
3497 | Param->setScopeInfo(0, Params.size()); | |||
3498 | Param->setImplicit(); | |||
3499 | Params.push_back(Param); | |||
3500 | } | |||
3501 | ||||
3502 | New->setParams(Params); | |||
3503 | } | |||
3504 | ||||
3505 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | |||
3506 | } | |||
3507 | ||||
3508 | // GNU C permits a K&R definition to follow a prototype declaration | |||
3509 | // if the declared types of the parameters in the K&R definition | |||
3510 | // match the types in the prototype declaration, even when the | |||
3511 | // promoted types of the parameters from the K&R definition differ | |||
3512 | // from the types in the prototype. GCC then keeps the types from | |||
3513 | // the prototype. | |||
3514 | // | |||
3515 | // If a variadic prototype is followed by a non-variadic K&R definition, | |||
3516 | // the K&R definition becomes variadic. This is sort of an edge case, but | |||
3517 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and | |||
3518 | // C99 6.9.1p8. | |||
3519 | if (!getLangOpts().CPlusPlus && | |||
3520 | Old->hasPrototype() && !New->hasPrototype() && | |||
3521 | New->getType()->getAs<FunctionProtoType>() && | |||
3522 | Old->getNumParams() == New->getNumParams()) { | |||
3523 | SmallVector<QualType, 16> ArgTypes; | |||
3524 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; | |||
3525 | const FunctionProtoType *OldProto | |||
3526 | = Old->getType()->getAs<FunctionProtoType>(); | |||
3527 | const FunctionProtoType *NewProto | |||
3528 | = New->getType()->getAs<FunctionProtoType>(); | |||
3529 | ||||
3530 | // Determine whether this is the GNU C extension. | |||
3531 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), | |||
3532 | NewProto->getReturnType()); | |||
3533 | bool LooseCompatible = !MergedReturn.isNull(); | |||
3534 | for (unsigned Idx = 0, End = Old->getNumParams(); | |||
3535 | LooseCompatible && Idx != End; ++Idx) { | |||
3536 | ParmVarDecl *OldParm = Old->getParamDecl(Idx); | |||
3537 | ParmVarDecl *NewParm = New->getParamDecl(Idx); | |||
3538 | if (Context.typesAreCompatible(OldParm->getType(), | |||
3539 | NewProto->getParamType(Idx))) { | |||
3540 | ArgTypes.push_back(NewParm->getType()); | |||
3541 | } else if (Context.typesAreCompatible(OldParm->getType(), | |||
3542 | NewParm->getType(), | |||
3543 | /*CompareUnqualified=*/true)) { | |||
3544 | GNUCompatibleParamWarning Warn = { OldParm, NewParm, | |||
3545 | NewProto->getParamType(Idx) }; | |||
3546 | Warnings.push_back(Warn); | |||
3547 | ArgTypes.push_back(NewParm->getType()); | |||
3548 | } else | |||
3549 | LooseCompatible = false; | |||
3550 | } | |||
3551 | ||||
3552 | if (LooseCompatible) { | |||
3553 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { | |||
3554 | Diag(Warnings[Warn].NewParm->getLocation(), | |||
3555 | diag::ext_param_promoted_not_compatible_with_prototype) | |||
3556 | << Warnings[Warn].PromotedType | |||
3557 | << Warnings[Warn].OldParm->getType(); | |||
3558 | if (Warnings[Warn].OldParm->getLocation().isValid()) | |||
3559 | Diag(Warnings[Warn].OldParm->getLocation(), | |||
3560 | diag::note_previous_declaration); | |||
3561 | } | |||
3562 | ||||
3563 | if (MergeTypeWithOld) | |||
3564 | New->setType(Context.getFunctionType(MergedReturn, ArgTypes, | |||
3565 | OldProto->getExtProtoInfo())); | |||
3566 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | |||
3567 | } | |||
3568 | ||||
3569 | // Fall through to diagnose conflicting types. | |||
3570 | } | |||
3571 | ||||
3572 | // A function that has already been declared has been redeclared or | |||
3573 | // defined with a different type; show an appropriate diagnostic. | |||
3574 | ||||
3575 | // If the previous declaration was an implicitly-generated builtin | |||
3576 | // declaration, then at the very least we should use a specialized note. | |||
3577 | unsigned BuiltinID; | |||
3578 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { | |||
3579 | // If it's actually a library-defined builtin function like 'malloc' | |||
3580 | // or 'printf', just warn about the incompatible redeclaration. | |||
3581 | if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { | |||
3582 | Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; | |||
3583 | Diag(OldLocation, diag::note_previous_builtin_declaration) | |||
3584 | << Old << Old->getType(); | |||
3585 | ||||
3586 | // If this is a global redeclaration, just forget hereafter | |||
3587 | // about the "builtin-ness" of the function. | |||
3588 | // | |||
3589 | // Doing this for local extern declarations is problematic. If | |||
3590 | // the builtin declaration remains visible, a second invalid | |||
3591 | // local declaration will produce a hard error; if it doesn't | |||
3592 | // remain visible, a single bogus local redeclaration (which is | |||
3593 | // actually only a warning) could break all the downstream code. | |||
3594 | if (!New->getLexicalDeclContext()->isFunctionOrMethod()) | |||
3595 | New->getIdentifier()->revertBuiltin(); | |||
3596 | ||||
3597 | return false; | |||
3598 | } | |||
3599 | ||||
3600 | PrevDiag = diag::note_previous_builtin_declaration; | |||
3601 | } | |||
3602 | ||||
3603 | Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); | |||
3604 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3605 | return true; | |||
3606 | } | |||
3607 | ||||
3608 | /// Completes the merge of two function declarations that are | |||
3609 | /// known to be compatible. | |||
3610 | /// | |||
3611 | /// This routine handles the merging of attributes and other | |||
3612 | /// properties of function declarations from the old declaration to | |||
3613 | /// the new declaration, once we know that New is in fact a | |||
3614 | /// redeclaration of Old. | |||
3615 | /// | |||
3616 | /// \returns false | |||
3617 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, | |||
3618 | Scope *S, bool MergeTypeWithOld) { | |||
3619 | // Merge the attributes | |||
3620 | mergeDeclAttributes(New, Old); | |||
3621 | ||||
3622 | // Merge "pure" flag. | |||
3623 | if (Old->isPure()) | |||
3624 | New->setPure(); | |||
3625 | ||||
3626 | // Merge "used" flag. | |||
3627 | if (Old->getMostRecentDecl()->isUsed(false)) | |||
3628 | New->setIsUsed(); | |||
3629 | ||||
3630 | // Merge attributes from the parameters. These can mismatch with K&R | |||
3631 | // declarations. | |||
3632 | if (New->getNumParams() == Old->getNumParams()) | |||
3633 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { | |||
3634 | ParmVarDecl *NewParam = New->getParamDecl(i); | |||
3635 | ParmVarDecl *OldParam = Old->getParamDecl(i); | |||
3636 | mergeParamDeclAttributes(NewParam, OldParam, *this); | |||
3637 | mergeParamDeclTypes(NewParam, OldParam, *this); | |||
3638 | } | |||
3639 | ||||
3640 | if (getLangOpts().CPlusPlus) | |||
3641 | return MergeCXXFunctionDecl(New, Old, S); | |||
3642 | ||||
3643 | // Merge the function types so the we get the composite types for the return | |||
3644 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl | |||
3645 | // was visible. | |||
3646 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); | |||
3647 | if (!Merged.isNull() && MergeTypeWithOld) | |||
3648 | New->setType(Merged); | |||
3649 | ||||
3650 | return false; | |||
3651 | } | |||
3652 | ||||
3653 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, | |||
3654 | ObjCMethodDecl *oldMethod) { | |||
3655 | // Merge the attributes, including deprecated/unavailable | |||
3656 | AvailabilityMergeKind MergeKind = | |||
3657 | isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) | |||
3658 | ? AMK_ProtocolImplementation | |||
3659 | : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration | |||
3660 | : AMK_Override; | |||
3661 | ||||
3662 | mergeDeclAttributes(newMethod, oldMethod, MergeKind); | |||
3663 | ||||
3664 | // Merge attributes from the parameters. | |||
3665 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), | |||
3666 | oe = oldMethod->param_end(); | |||
3667 | for (ObjCMethodDecl::param_iterator | |||
3668 | ni = newMethod->param_begin(), ne = newMethod->param_end(); | |||
3669 | ni != ne && oi != oe; ++ni, ++oi) | |||
3670 | mergeParamDeclAttributes(*ni, *oi, *this); | |||
3671 | ||||
3672 | CheckObjCMethodOverride(newMethod, oldMethod); | |||
3673 | } | |||
3674 | ||||
3675 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { | |||
3676 | assert(!S.Context.hasSameType(New->getType(), Old->getType()))((!S.Context.hasSameType(New->getType(), Old->getType() )) ? static_cast<void> (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 3676, __PRETTY_FUNCTION__)); | |||
3677 | ||||
3678 | S.Diag(New->getLocation(), New->isThisDeclarationADefinition() | |||
3679 | ? diag::err_redefinition_different_type | |||
3680 | : diag::err_redeclaration_different_type) | |||
3681 | << New->getDeclName() << New->getType() << Old->getType(); | |||
3682 | ||||
3683 | diag::kind PrevDiag; | |||
3684 | SourceLocation OldLocation; | |||
3685 | std::tie(PrevDiag, OldLocation) | |||
3686 | = getNoteDiagForInvalidRedeclaration(Old, New); | |||
3687 | S.Diag(OldLocation, PrevDiag); | |||
3688 | New->setInvalidDecl(); | |||
3689 | } | |||
3690 | ||||
3691 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and | |||
3692 | /// scope as a previous declaration 'Old'. Figure out how to merge their types, | |||
3693 | /// emitting diagnostics as appropriate. | |||
3694 | /// | |||
3695 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back | |||
3696 | /// to here in AddInitializerToDecl. We can't check them before the initializer | |||
3697 | /// is attached. | |||
3698 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, | |||
3699 | bool MergeTypeWithOld) { | |||
3700 | if (New->isInvalidDecl() || Old->isInvalidDecl()) | |||
3701 | return; | |||
3702 | ||||
3703 | QualType MergedT; | |||
3704 | if (getLangOpts().CPlusPlus) { | |||
3705 | if (New->getType()->isUndeducedType()) { | |||
3706 | // We don't know what the new type is until the initializer is attached. | |||
3707 | return; | |||
3708 | } else if (Context.hasSameType(New->getType(), Old->getType())) { | |||
3709 | // These could still be something that needs exception specs checked. | |||
3710 | return MergeVarDeclExceptionSpecs(New, Old); | |||
3711 | } | |||
3712 | // C++ [basic.link]p10: | |||
3713 | // [...] the types specified by all declarations referring to a given | |||
3714 | // object or function shall be identical, except that declarations for an | |||
3715 | // array object can specify array types that differ by the presence or | |||
3716 | // absence of a major array bound (8.3.4). | |||
3717 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { | |||
3718 | const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); | |||
3719 | const ArrayType *NewArray = Context.getAsArrayType(New->getType()); | |||
3720 | ||||
3721 | // We are merging a variable declaration New into Old. If it has an array | |||
3722 | // bound, and that bound differs from Old's bound, we should diagnose the | |||
3723 | // mismatch. | |||
3724 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { | |||
3725 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; | |||
3726 | PrevVD = PrevVD->getPreviousDecl()) { | |||
3727 | const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); | |||
3728 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) | |||
3729 | continue; | |||
3730 | ||||
3731 | if (!Context.hasSameType(NewArray, PrevVDTy)) | |||
3732 | return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); | |||
3733 | } | |||
3734 | } | |||
3735 | ||||
3736 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { | |||
3737 | if (Context.hasSameType(OldArray->getElementType(), | |||
3738 | NewArray->getElementType())) | |||
3739 | MergedT = New->getType(); | |||
3740 | } | |||
3741 | // FIXME: Check visibility. New is hidden but has a complete type. If New | |||
3742 | // has no array bound, it should not inherit one from Old, if Old is not | |||
3743 | // visible. | |||
3744 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { | |||
3745 | if (Context.hasSameType(OldArray->getElementType(), | |||
3746 | NewArray->getElementType())) | |||
3747 | MergedT = Old->getType(); | |||
3748 | } | |||
3749 | } | |||
3750 | else if (New->getType()->isObjCObjectPointerType() && | |||
3751 | Old->getType()->isObjCObjectPointerType()) { | |||
3752 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), | |||
3753 | Old->getType()); | |||
3754 | } | |||
3755 | } else { | |||
3756 | // C 6.2.7p2: | |||
3757 | // All declarations that refer to the same object or function shall have | |||
3758 | // compatible type. | |||
3759 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); | |||
3760 | } | |||
3761 | if (MergedT.isNull()) { | |||
3762 | // It's OK if we couldn't merge types if either type is dependent, for a | |||
3763 | // block-scope variable. In other cases (static data members of class | |||
3764 | // templates, variable templates, ...), we require the types to be | |||
3765 | // equivalent. | |||
3766 | // FIXME: The C++ standard doesn't say anything about this. | |||
3767 | if ((New->getType()->isDependentType() || | |||
3768 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { | |||
3769 | // If the old type was dependent, we can't merge with it, so the new type | |||
3770 | // becomes dependent for now. We'll reproduce the original type when we | |||
3771 | // instantiate the TypeSourceInfo for the variable. | |||
3772 | if (!New->getType()->isDependentType() && MergeTypeWithOld) | |||
3773 | New->setType(Context.DependentTy); | |||
3774 | return; | |||
3775 | } | |||
3776 | return diagnoseVarDeclTypeMismatch(*this, New, Old); | |||
3777 | } | |||
3778 | ||||
3779 | // Don't actually update the type on the new declaration if the old | |||
3780 | // declaration was an extern declaration in a different scope. | |||
3781 | if (MergeTypeWithOld) | |||
3782 | New->setType(MergedT); | |||
3783 | } | |||
3784 | ||||
3785 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, | |||
3786 | LookupResult &Previous) { | |||
3787 | // C11 6.2.7p4: | |||
3788 | // For an identifier with internal or external linkage declared | |||
3789 | // in a scope in which a prior declaration of that identifier is | |||
3790 | // visible, if the prior declaration specifies internal or | |||
3791 | // external linkage, the type of the identifier at the later | |||
3792 | // declaration becomes the composite type. | |||
3793 | // | |||
3794 | // If the variable isn't visible, we do not merge with its type. | |||
3795 | if (Previous.isShadowed()) | |||
3796 | return false; | |||
3797 | ||||
3798 | if (S.getLangOpts().CPlusPlus) { | |||
3799 | // C++11 [dcl.array]p3: | |||
3800 | // If there is a preceding declaration of the entity in the same | |||
3801 | // scope in which the bound was specified, an omitted array bound | |||
3802 | // is taken to be the same as in that earlier declaration. | |||
3803 | return NewVD->isPreviousDeclInSameBlockScope() || | |||
3804 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && | |||
3805 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); | |||
3806 | } else { | |||
3807 | // If the old declaration was function-local, don't merge with its | |||
3808 | // type unless we're in the same function. | |||
3809 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || | |||
3810 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); | |||
3811 | } | |||
3812 | } | |||
3813 | ||||
3814 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name | |||
3815 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this | |||
3816 | /// situation, merging decls or emitting diagnostics as appropriate. | |||
3817 | /// | |||
3818 | /// Tentative definition rules (C99 6.9.2p2) are checked by | |||
3819 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative | |||
3820 | /// definitions here, since the initializer hasn't been attached. | |||
3821 | /// | |||
3822 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { | |||
3823 | // If the new decl is already invalid, don't do any other checking. | |||
3824 | if (New->isInvalidDecl()) | |||
3825 | return; | |||
3826 | ||||
3827 | if (!shouldLinkPossiblyHiddenDecl(Previous, New)) | |||
3828 | return; | |||
3829 | ||||
3830 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); | |||
3831 | ||||
3832 | // Verify the old decl was also a variable or variable template. | |||
3833 | VarDecl *Old = nullptr; | |||
3834 | VarTemplateDecl *OldTemplate = nullptr; | |||
3835 | if (Previous.isSingleResult()) { | |||
3836 | if (NewTemplate) { | |||
3837 | OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); | |||
3838 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; | |||
3839 | ||||
3840 | if (auto *Shadow = | |||
3841 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | |||
3842 | if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) | |||
3843 | return New->setInvalidDecl(); | |||
3844 | } else { | |||
3845 | Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); | |||
3846 | ||||
3847 | if (auto *Shadow = | |||
3848 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | |||
3849 | if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) | |||
3850 | return New->setInvalidDecl(); | |||
3851 | } | |||
3852 | } | |||
3853 | if (!Old) { | |||
3854 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | |||
3855 | << New->getDeclName(); | |||
3856 | notePreviousDefinition(Previous.getRepresentativeDecl(), | |||
3857 | New->getLocation()); | |||
3858 | return New->setInvalidDecl(); | |||
3859 | } | |||
3860 | ||||
3861 | // Ensure the template parameters are compatible. | |||
3862 | if (NewTemplate && | |||
3863 | !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), | |||
3864 | OldTemplate->getTemplateParameters(), | |||
3865 | /*Complain=*/true, TPL_TemplateMatch)) | |||
3866 | return New->setInvalidDecl(); | |||
3867 | ||||
3868 | // C++ [class.mem]p1: | |||
3869 | // A member shall not be declared twice in the member-specification [...] | |||
3870 | // | |||
3871 | // Here, we need only consider static data members. | |||
3872 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { | |||
3873 | Diag(New->getLocation(), diag::err_duplicate_member) | |||
3874 | << New->getIdentifier(); | |||
3875 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
3876 | New->setInvalidDecl(); | |||
3877 | } | |||
3878 | ||||
3879 | mergeDeclAttributes(New, Old); | |||
3880 | // Warn if an already-declared variable is made a weak_import in a subsequent | |||
3881 | // declaration | |||
3882 | if (New->hasAttr<WeakImportAttr>() && | |||
3883 | Old->getStorageClass() == SC_None && | |||
3884 | !Old->hasAttr<WeakImportAttr>()) { | |||
3885 | Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); | |||
3886 | notePreviousDefinition(Old, New->getLocation()); | |||
3887 | // Remove weak_import attribute on new declaration. | |||
3888 | New->dropAttr<WeakImportAttr>(); | |||
3889 | } | |||
3890 | ||||
3891 | if (New->hasAttr<InternalLinkageAttr>() && | |||
3892 | !Old->hasAttr<InternalLinkageAttr>()) { | |||
3893 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | |||
3894 | << New->getDeclName(); | |||
3895 | notePreviousDefinition(Old, New->getLocation()); | |||
3896 | New->dropAttr<InternalLinkageAttr>(); | |||
3897 | } | |||
3898 | ||||
3899 | // Merge the types. | |||
3900 | VarDecl *MostRecent = Old->getMostRecentDecl(); | |||
3901 | if (MostRecent != Old) { | |||
3902 | MergeVarDeclTypes(New, MostRecent, | |||
3903 | mergeTypeWithPrevious(*this, New, MostRecent, Previous)); | |||
3904 | if (New->isInvalidDecl()) | |||
3905 | return; | |||
3906 | } | |||
3907 | ||||
3908 | MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); | |||
3909 | if (New->isInvalidDecl()) | |||
3910 | return; | |||
3911 | ||||
3912 | diag::kind PrevDiag; | |||
3913 | SourceLocation OldLocation; | |||
3914 | std::tie(PrevDiag, OldLocation) = | |||
3915 | getNoteDiagForInvalidRedeclaration(Old, New); | |||
3916 | ||||
3917 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. | |||
3918 | if (New->getStorageClass() == SC_Static && | |||
3919 | !New->isStaticDataMember() && | |||
3920 | Old->hasExternalFormalLinkage()) { | |||
3921 | if (getLangOpts().MicrosoftExt) { | |||
3922 | Diag(New->getLocation(), diag::ext_static_non_static) | |||
3923 | << New->getDeclName(); | |||
3924 | Diag(OldLocation, PrevDiag); | |||
3925 | } else { | |||
3926 | Diag(New->getLocation(), diag::err_static_non_static) | |||
3927 | << New->getDeclName(); | |||
3928 | Diag(OldLocation, PrevDiag); | |||
3929 | return New->setInvalidDecl(); | |||
3930 | } | |||
3931 | } | |||
3932 | // C99 6.2.2p4: | |||
3933 | // For an identifier declared with the storage-class specifier | |||
3934 | // extern in a scope in which a prior declaration of that | |||
3935 | // identifier is visible,23) if the prior declaration specifies | |||
3936 | // internal or external linkage, the linkage of the identifier at | |||
3937 | // the later declaration is the same as the linkage specified at | |||
3938 | // the prior declaration. If no prior declaration is visible, or | |||
3939 | // if the prior declaration specifies no linkage, then the | |||
3940 | // identifier has external linkage. | |||
3941 | if (New->hasExternalStorage() && Old->hasLinkage()) | |||
3942 | /* Okay */; | |||
3943 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && | |||
3944 | !New->isStaticDataMember() && | |||
3945 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { | |||
3946 | Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); | |||
3947 | Diag(OldLocation, PrevDiag); | |||
3948 | return New->setInvalidDecl(); | |||
3949 | } | |||
3950 | ||||
3951 | // Check if extern is followed by non-extern and vice-versa. | |||
3952 | if (New->hasExternalStorage() && | |||
3953 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { | |||
3954 | Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); | |||
3955 | Diag(OldLocation, PrevDiag); | |||
3956 | return New->setInvalidDecl(); | |||
3957 | } | |||
3958 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && | |||
3959 | !New->hasExternalStorage()) { | |||
3960 | Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); | |||
3961 | Diag(OldLocation, PrevDiag); | |||
3962 | return New->setInvalidDecl(); | |||
3963 | } | |||
3964 | ||||
3965 | if (CheckRedeclarationModuleOwnership(New, Old)) | |||
3966 | return; | |||
3967 | ||||
3968 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. | |||
3969 | ||||
3970 | // FIXME: The test for external storage here seems wrong? We still | |||
3971 | // need to check for mismatches. | |||
3972 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && | |||
3973 | // Don't complain about out-of-line definitions of static members. | |||
3974 | !(Old->getLexicalDeclContext()->isRecord() && | |||
3975 | !New->getLexicalDeclContext()->isRecord())) { | |||
3976 | Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); | |||
3977 | Diag(OldLocation, PrevDiag); | |||
3978 | return New->setInvalidDecl(); | |||
3979 | } | |||
3980 | ||||
3981 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { | |||
3982 | if (VarDecl *Def = Old->getDefinition()) { | |||
3983 | // C++1z [dcl.fcn.spec]p4: | |||
3984 | // If the definition of a variable appears in a translation unit before | |||
3985 | // its first declaration as inline, the program is ill-formed. | |||
3986 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; | |||
3987 | Diag(Def->getLocation(), diag::note_previous_definition); | |||
3988 | } | |||
3989 | } | |||
3990 | ||||
3991 | // If this redeclaration makes the variable inline, we may need to add it to | |||
3992 | // UndefinedButUsed. | |||
3993 | if (!Old->isInline() && New->isInline() && Old->isUsed(false) && | |||
3994 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) | |||
3995 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | |||
3996 | SourceLocation())); | |||
3997 | ||||
3998 | if (New->getTLSKind() != Old->getTLSKind()) { | |||
3999 | if (!Old->getTLSKind()) { | |||
4000 | Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); | |||
4001 | Diag(OldLocation, PrevDiag); | |||
4002 | } else if (!New->getTLSKind()) { | |||
4003 | Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); | |||
4004 | Diag(OldLocation, PrevDiag); | |||
4005 | } else { | |||
4006 | // Do not allow redeclaration to change the variable between requiring | |||
4007 | // static and dynamic initialization. | |||
4008 | // FIXME: GCC allows this, but uses the TLS keyword on the first | |||
4009 | // declaration to determine the kind. Do we need to be compatible here? | |||
4010 | Diag(New->getLocation(), diag::err_thread_thread_different_kind) | |||
4011 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); | |||
4012 | Diag(OldLocation, PrevDiag); | |||
4013 | } | |||
4014 | } | |||
4015 | ||||
4016 | // C++ doesn't have tentative definitions, so go right ahead and check here. | |||
4017 | if (getLangOpts().CPlusPlus && | |||
4018 | New->isThisDeclarationADefinition() == VarDecl::Definition) { | |||
4019 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && | |||
4020 | Old->getCanonicalDecl()->isConstexpr()) { | |||
4021 | // This definition won't be a definition any more once it's been merged. | |||
4022 | Diag(New->getLocation(), | |||
4023 | diag::warn_deprecated_redundant_constexpr_static_def); | |||
4024 | } else if (VarDecl *Def = Old->getDefinition()) { | |||
4025 | if (checkVarDeclRedefinition(Def, New)) | |||
4026 | return; | |||
4027 | } | |||
4028 | } | |||
4029 | ||||
4030 | if (haveIncompatibleLanguageLinkages(Old, New)) { | |||
4031 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | |||
4032 | Diag(OldLocation, PrevDiag); | |||
4033 | New->setInvalidDecl(); | |||
4034 | return; | |||
4035 | } | |||
4036 | ||||
4037 | // Merge "used" flag. | |||
4038 | if (Old->getMostRecentDecl()->isUsed(false)) | |||
4039 | New->setIsUsed(); | |||
4040 | ||||
4041 | // Keep a chain of previous declarations. | |||
4042 | New->setPreviousDecl(Old); | |||
4043 | if (NewTemplate) | |||
4044 | NewTemplate->setPreviousDecl(OldTemplate); | |||
4045 | adjustDeclContextForDeclaratorDecl(New, Old); | |||
4046 | ||||
4047 | // Inherit access appropriately. | |||
4048 | New->setAccess(Old->getAccess()); | |||
4049 | if (NewTemplate) | |||
4050 | NewTemplate->setAccess(New->getAccess()); | |||
4051 | ||||
4052 | if (Old->isInline()) | |||
4053 | New->setImplicitlyInline(); | |||
4054 | } | |||
4055 | ||||
4056 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { | |||
4057 | SourceManager &SrcMgr = getSourceManager(); | |||
4058 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); | |||
4059 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); | |||
4060 | auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); | |||
4061 | auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); | |||
4062 | auto &HSI = PP.getHeaderSearchInfo(); | |||
4063 | StringRef HdrFilename = | |||
4064 | SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); | |||
4065 | ||||
4066 | auto noteFromModuleOrInclude = [&](Module *Mod, | |||
4067 | SourceLocation IncLoc) -> bool { | |||
4068 | // Redefinition errors with modules are common with non modular mapped | |||
4069 | // headers, example: a non-modular header H in module A that also gets | |||
4070 | // included directly in a TU. Pointing twice to the same header/definition | |||
4071 | // is confusing, try to get better diagnostics when modules is on. | |||
4072 | if (IncLoc.isValid()) { | |||
4073 | if (Mod) { | |||
4074 | Diag(IncLoc, diag::note_redefinition_modules_same_file) | |||
4075 | << HdrFilename.str() << Mod->getFullModuleName(); | |||
4076 | if (!Mod->DefinitionLoc.isInvalid()) | |||
4077 | Diag(Mod->DefinitionLoc, diag::note_defined_here) | |||
4078 | << Mod->getFullModuleName(); | |||
4079 | } else { | |||
4080 | Diag(IncLoc, diag::note_redefinition_include_same_file) | |||
4081 | << HdrFilename.str(); | |||
4082 | } | |||
4083 | return true; | |||
4084 | } | |||
4085 | ||||
4086 | return false; | |||
4087 | }; | |||
4088 | ||||
4089 | // Is it the same file and same offset? Provide more information on why | |||
4090 | // this leads to a redefinition error. | |||
4091 | bool EmittedDiag = false; | |||
4092 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { | |||
4093 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); | |||
4094 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); | |||
4095 | EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); | |||
4096 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); | |||
4097 | ||||
4098 | // If the header has no guards, emit a note suggesting one. | |||
4099 | if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) | |||
4100 | Diag(Old->getLocation(), diag::note_use_ifdef_guards); | |||
4101 | ||||
4102 | if (EmittedDiag) | |||
4103 | return; | |||
4104 | } | |||
4105 | ||||
4106 | // Redefinition coming from different files or couldn't do better above. | |||
4107 | if (Old->getLocation().isValid()) | |||
4108 | Diag(Old->getLocation(), diag::note_previous_definition); | |||
4109 | } | |||
4110 | ||||
4111 | /// We've just determined that \p Old and \p New both appear to be definitions | |||
4112 | /// of the same variable. Either diagnose or fix the problem. | |||
4113 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { | |||
4114 | if (!hasVisibleDefinition(Old) && | |||
4115 | (New->getFormalLinkage() == InternalLinkage || | |||
4116 | New->isInline() || | |||
4117 | New->getDescribedVarTemplate() || | |||
4118 | New->getNumTemplateParameterLists() || | |||
4119 | New->getDeclContext()->isDependentContext())) { | |||
4120 | // The previous definition is hidden, and multiple definitions are | |||
4121 | // permitted (in separate TUs). Demote this to a declaration. | |||
4122 | New->demoteThisDefinitionToDeclaration(); | |||
4123 | ||||
4124 | // Make the canonical definition visible. | |||
4125 | if (auto *OldTD = Old->getDescribedVarTemplate()) | |||
4126 | makeMergedDefinitionVisible(OldTD); | |||
4127 | makeMergedDefinitionVisible(Old); | |||
4128 | return false; | |||
4129 | } else { | |||
4130 | Diag(New->getLocation(), diag::err_redefinition) << New; | |||
4131 | notePreviousDefinition(Old, New->getLocation()); | |||
4132 | New->setInvalidDecl(); | |||
4133 | return true; | |||
4134 | } | |||
4135 | } | |||
4136 | ||||
4137 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | |||
4138 | /// no declarator (e.g. "struct foo;") is parsed. | |||
4139 | Decl * | |||
4140 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | |||
4141 | RecordDecl *&AnonRecord) { | |||
4142 | return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, | |||
4143 | AnonRecord); | |||
4144 | } | |||
4145 | ||||
4146 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to | |||
4147 | // disambiguate entities defined in different scopes. | |||
4148 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks | |||
4149 | // compatibility. | |||
4150 | // We will pick our mangling number depending on which version of MSVC is being | |||
4151 | // targeted. | |||
4152 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { | |||
4153 | return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) | |||
4154 | ? S->getMSCurManglingNumber() | |||
4155 | : S->getMSLastManglingNumber(); | |||
4156 | } | |||
4157 | ||||
4158 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { | |||
4159 | if (!Context.getLangOpts().CPlusPlus) | |||
4160 | return; | |||
4161 | ||||
4162 | if (isa<CXXRecordDecl>(Tag->getParent())) { | |||
4163 | // If this tag is the direct child of a class, number it if | |||
4164 | // it is anonymous. | |||
4165 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) | |||
4166 | return; | |||
4167 | MangleNumberingContext &MCtx = | |||
4168 | Context.getManglingNumberContext(Tag->getParent()); | |||
4169 | Context.setManglingNumber( | |||
4170 | Tag, MCtx.getManglingNumber( | |||
4171 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | |||
4172 | return; | |||
4173 | } | |||
4174 | ||||
4175 | // If this tag isn't a direct child of a class, number it if it is local. | |||
4176 | Decl *ManglingContextDecl; | |||
4177 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( | |||
4178 | Tag->getDeclContext(), ManglingContextDecl)) { | |||
4179 | Context.setManglingNumber( | |||
4180 | Tag, MCtx->getManglingNumber( | |||
4181 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | |||
4182 | } | |||
4183 | } | |||
4184 | ||||
4185 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, | |||
4186 | TypedefNameDecl *NewTD) { | |||
4187 | if (TagFromDeclSpec->isInvalidDecl()) | |||
4188 | return; | |||
4189 | ||||
4190 | // Do nothing if the tag already has a name for linkage purposes. | |||
4191 | if (TagFromDeclSpec->hasNameForLinkage()) | |||
4192 | return; | |||
4193 | ||||
4194 | // A well-formed anonymous tag must always be a TUK_Definition. | |||
4195 | assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast <void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4195, __PRETTY_FUNCTION__)); | |||
4196 | ||||
4197 | // The type must match the tag exactly; no qualifiers allowed. | |||
4198 | if (!Context.hasSameType(NewTD->getUnderlyingType(), | |||
4199 | Context.getTagDeclType(TagFromDeclSpec))) { | |||
4200 | if (getLangOpts().CPlusPlus) | |||
4201 | Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); | |||
4202 | return; | |||
4203 | } | |||
4204 | ||||
4205 | // If we've already computed linkage for the anonymous tag, then | |||
4206 | // adding a typedef name for the anonymous decl can change that | |||
4207 | // linkage, which might be a serious problem. Diagnose this as | |||
4208 | // unsupported and ignore the typedef name. TODO: we should | |||
4209 | // pursue this as a language defect and establish a formal rule | |||
4210 | // for how to handle it. | |||
4211 | if (TagFromDeclSpec->hasLinkageBeenComputed()) { | |||
4212 | Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); | |||
4213 | ||||
4214 | SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); | |||
4215 | tagLoc = getLocForEndOfToken(tagLoc); | |||
4216 | ||||
4217 | llvm::SmallString<40> textToInsert; | |||
4218 | textToInsert += ' '; | |||
4219 | textToInsert += NewTD->getIdentifier()->getName(); | |||
4220 | Diag(tagLoc, diag::note_typedef_changes_linkage) | |||
4221 | << FixItHint::CreateInsertion(tagLoc, textToInsert); | |||
4222 | return; | |||
4223 | } | |||
4224 | ||||
4225 | // Otherwise, set this is the anon-decl typedef for the tag. | |||
4226 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); | |||
4227 | } | |||
4228 | ||||
4229 | static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { | |||
4230 | switch (T) { | |||
4231 | case DeclSpec::TST_class: | |||
4232 | return 0; | |||
4233 | case DeclSpec::TST_struct: | |||
4234 | return 1; | |||
4235 | case DeclSpec::TST_interface: | |||
4236 | return 2; | |||
4237 | case DeclSpec::TST_union: | |||
4238 | return 3; | |||
4239 | case DeclSpec::TST_enum: | |||
4240 | return 4; | |||
4241 | default: | |||
4242 | llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4242); | |||
4243 | } | |||
4244 | } | |||
4245 | ||||
4246 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | |||
4247 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template | |||
4248 | /// parameters to cope with template friend declarations. | |||
4249 | Decl * | |||
4250 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | |||
4251 | MultiTemplateParamsArg TemplateParams, | |||
4252 | bool IsExplicitInstantiation, | |||
4253 | RecordDecl *&AnonRecord) { | |||
4254 | Decl *TagD = nullptr; | |||
4255 | TagDecl *Tag = nullptr; | |||
4256 | if (DS.getTypeSpecType() == DeclSpec::TST_class || | |||
4257 | DS.getTypeSpecType() == DeclSpec::TST_struct || | |||
4258 | DS.getTypeSpecType() == DeclSpec::TST_interface || | |||
4259 | DS.getTypeSpecType() == DeclSpec::TST_union || | |||
4260 | DS.getTypeSpecType() == DeclSpec::TST_enum) { | |||
4261 | TagD = DS.getRepAsDecl(); | |||
4262 | ||||
4263 | if (!TagD) // We probably had an error | |||
4264 | return nullptr; | |||
4265 | ||||
4266 | // Note that the above type specs guarantee that the | |||
4267 | // type rep is a Decl, whereas in many of the others | |||
4268 | // it's a Type. | |||
4269 | if (isa<TagDecl>(TagD)) | |||
4270 | Tag = cast<TagDecl>(TagD); | |||
4271 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) | |||
4272 | Tag = CTD->getTemplatedDecl(); | |||
4273 | } | |||
4274 | ||||
4275 | if (Tag) { | |||
4276 | handleTagNumbering(Tag, S); | |||
4277 | Tag->setFreeStanding(); | |||
4278 | if (Tag->isInvalidDecl()) | |||
4279 | return Tag; | |||
4280 | } | |||
4281 | ||||
4282 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | |||
4283 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object | |||
4284 | // or incomplete types shall not be restrict-qualified." | |||
4285 | if (TypeQuals & DeclSpec::TQ_restrict) | |||
4286 | Diag(DS.getRestrictSpecLoc(), | |||
4287 | diag::err_typecheck_invalid_restrict_not_pointer_noarg) | |||
4288 | << DS.getSourceRange(); | |||
4289 | } | |||
4290 | ||||
4291 | if (DS.isInlineSpecified()) | |||
4292 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | |||
4293 | << getLangOpts().CPlusPlus17; | |||
4294 | ||||
4295 | if (DS.isConstexprSpecified()) { | |||
4296 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations | |||
4297 | // and definitions of functions and variables. | |||
4298 | if (Tag) | |||
4299 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) | |||
4300 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); | |||
4301 | else | |||
4302 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); | |||
4303 | // Don't emit warnings after this error. | |||
4304 | return TagD; | |||
4305 | } | |||
4306 | ||||
4307 | DiagnoseFunctionSpecifiers(DS); | |||
4308 | ||||
4309 | if (DS.isFriendSpecified()) { | |||
4310 | // If we're dealing with a decl but not a TagDecl, assume that | |||
4311 | // whatever routines created it handled the friendship aspect. | |||
4312 | if (TagD && !Tag) | |||
4313 | return nullptr; | |||
4314 | return ActOnFriendTypeDecl(S, DS, TemplateParams); | |||
4315 | } | |||
4316 | ||||
4317 | const CXXScopeSpec &SS = DS.getTypeSpecScope(); | |||
4318 | bool IsExplicitSpecialization = | |||
4319 | !TemplateParams.empty() && TemplateParams.back()->size() == 0; | |||
4320 | if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && | |||
4321 | !IsExplicitInstantiation && !IsExplicitSpecialization && | |||
4322 | !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { | |||
4323 | // Per C++ [dcl.type.elab]p1, a class declaration cannot have a | |||
4324 | // nested-name-specifier unless it is an explicit instantiation | |||
4325 | // or an explicit specialization. | |||
4326 | // | |||
4327 | // FIXME: We allow class template partial specializations here too, per the | |||
4328 | // obvious intent of DR1819. | |||
4329 | // | |||
4330 | // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. | |||
4331 | Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) | |||
4332 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); | |||
4333 | return nullptr; | |||
4334 | } | |||
4335 | ||||
4336 | // Track whether this decl-specifier declares anything. | |||
4337 | bool DeclaresAnything = true; | |||
4338 | ||||
4339 | // Handle anonymous struct definitions. | |||
4340 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { | |||
4341 | if (!Record->getDeclName() && Record->isCompleteDefinition() && | |||
4342 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { | |||
4343 | if (getLangOpts().CPlusPlus || | |||
4344 | Record->getDeclContext()->isRecord()) { | |||
4345 | // If CurContext is a DeclContext that can contain statements, | |||
4346 | // RecursiveASTVisitor won't visit the decls that | |||
4347 | // BuildAnonymousStructOrUnion() will put into CurContext. | |||
4348 | // Also store them here so that they can be part of the | |||
4349 | // DeclStmt that gets created in this case. | |||
4350 | // FIXME: Also return the IndirectFieldDecls created by | |||
4351 | // BuildAnonymousStructOr union, for the same reason? | |||
4352 | if (CurContext->isFunctionOrMethod()) | |||
4353 | AnonRecord = Record; | |||
4354 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, | |||
4355 | Context.getPrintingPolicy()); | |||
4356 | } | |||
4357 | ||||
4358 | DeclaresAnything = false; | |||
4359 | } | |||
4360 | } | |||
4361 | ||||
4362 | // C11 6.7.2.1p2: | |||
4363 | // A struct-declaration that does not declare an anonymous structure or | |||
4364 | // anonymous union shall contain a struct-declarator-list. | |||
4365 | // | |||
4366 | // This rule also existed in C89 and C99; the grammar for struct-declaration | |||
4367 | // did not permit a struct-declaration without a struct-declarator-list. | |||
4368 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && | |||
4369 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { | |||
4370 | // Check for Microsoft C extension: anonymous struct/union member. | |||
4371 | // Handle 2 kinds of anonymous struct/union: | |||
4372 | // struct STRUCT; | |||
4373 | // union UNION; | |||
4374 | // and | |||
4375 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. | |||
4376 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. | |||
4377 | if ((Tag && Tag->getDeclName()) || | |||
4378 | DS.getTypeSpecType() == DeclSpec::TST_typename) { | |||
4379 | RecordDecl *Record = nullptr; | |||
4380 | if (Tag) | |||
4381 | Record = dyn_cast<RecordDecl>(Tag); | |||
4382 | else if (const RecordType *RT = | |||
4383 | DS.getRepAsType().get()->getAsStructureType()) | |||
4384 | Record = RT->getDecl(); | |||
4385 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) | |||
4386 | Record = UT->getDecl(); | |||
4387 | ||||
4388 | if (Record && getLangOpts().MicrosoftExt) { | |||
4389 | Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) | |||
4390 | << Record->isUnion() << DS.getSourceRange(); | |||
4391 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); | |||
4392 | } | |||
4393 | ||||
4394 | DeclaresAnything = false; | |||
4395 | } | |||
4396 | } | |||
4397 | ||||
4398 | // Skip all the checks below if we have a type error. | |||
4399 | if (DS.getTypeSpecType() == DeclSpec::TST_error || | |||
4400 | (TagD && TagD->isInvalidDecl())) | |||
4401 | return TagD; | |||
4402 | ||||
4403 | if (getLangOpts().CPlusPlus && | |||
4404 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) | |||
4405 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) | |||
4406 | if (Enum->enumerator_begin() == Enum->enumerator_end() && | |||
4407 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) | |||
4408 | DeclaresAnything = false; | |||
4409 | ||||
4410 | if (!DS.isMissingDeclaratorOk()) { | |||
4411 | // Customize diagnostic for a typedef missing a name. | |||
4412 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
4413 | Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) | |||
4414 | << DS.getSourceRange(); | |||
4415 | else | |||
4416 | DeclaresAnything = false; | |||
4417 | } | |||
4418 | ||||
4419 | if (DS.isModulePrivateSpecified() && | |||
4420 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) | |||
4421 | Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) | |||
4422 | << Tag->getTagKind() | |||
4423 | << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); | |||
4424 | ||||
4425 | ActOnDocumentableDecl(TagD); | |||
4426 | ||||
4427 | // C 6.7/2: | |||
4428 | // A declaration [...] shall declare at least a declarator [...], a tag, | |||
4429 | // or the members of an enumeration. | |||
4430 | // C++ [dcl.dcl]p3: | |||
4431 | // [If there are no declarators], and except for the declaration of an | |||
4432 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | |||
4433 | // names into the program, or shall redeclare a name introduced by a | |||
4434 | // previous declaration. | |||
4435 | if (!DeclaresAnything) { | |||
4436 | // In C, we allow this as a (popular) extension / bug. Don't bother | |||
4437 | // producing further diagnostics for redundant qualifiers after this. | |||
4438 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | |||
4439 | return TagD; | |||
4440 | } | |||
4441 | ||||
4442 | // C++ [dcl.stc]p1: | |||
4443 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the | |||
4444 | // init-declarator-list of the declaration shall not be empty. | |||
4445 | // C++ [dcl.fct.spec]p1: | |||
4446 | // If a cv-qualifier appears in a decl-specifier-seq, the | |||
4447 | // init-declarator-list of the declaration shall not be empty. | |||
4448 | // | |||
4449 | // Spurious qualifiers here appear to be valid in C. | |||
4450 | unsigned DiagID = diag::warn_standalone_specifier; | |||
4451 | if (getLangOpts().CPlusPlus) | |||
4452 | DiagID = diag::ext_standalone_specifier; | |||
4453 | ||||
4454 | // Note that a linkage-specification sets a storage class, but | |||
4455 | // 'extern "C" struct foo;' is actually valid and not theoretically | |||
4456 | // useless. | |||
4457 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { | |||
4458 | if (SCS == DeclSpec::SCS_mutable) | |||
4459 | // Since mutable is not a viable storage class specifier in C, there is | |||
4460 | // no reason to treat it as an extension. Instead, diagnose as an error. | |||
4461 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); | |||
4462 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) | |||
4463 | Diag(DS.getStorageClassSpecLoc(), DiagID) | |||
4464 | << DeclSpec::getSpecifierName(SCS); | |||
4465 | } | |||
4466 | ||||
4467 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | |||
4468 | Diag(DS.getThreadStorageClassSpecLoc(), DiagID) | |||
4469 | << DeclSpec::getSpecifierName(TSCS); | |||
4470 | if (DS.getTypeQualifiers()) { | |||
4471 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | |||
4472 | Diag(DS.getConstSpecLoc(), DiagID) << "const"; | |||
4473 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | |||
4474 | Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; | |||
4475 | // Restrict is covered above. | |||
4476 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | |||
4477 | Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; | |||
4478 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | |||
4479 | Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; | |||
4480 | } | |||
4481 | ||||
4482 | // Warn about ignored type attributes, for example: | |||
4483 | // __attribute__((aligned)) struct A; | |||
4484 | // Attributes should be placed after tag to apply to type declaration. | |||
4485 | if (!DS.getAttributes().empty()) { | |||
4486 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); | |||
4487 | if (TypeSpecType == DeclSpec::TST_class || | |||
4488 | TypeSpecType == DeclSpec::TST_struct || | |||
4489 | TypeSpecType == DeclSpec::TST_interface || | |||
4490 | TypeSpecType == DeclSpec::TST_union || | |||
4491 | TypeSpecType == DeclSpec::TST_enum) { | |||
4492 | for (const ParsedAttr &AL : DS.getAttributes()) | |||
4493 | Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) | |||
4494 | << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); | |||
4495 | } | |||
4496 | } | |||
4497 | ||||
4498 | return TagD; | |||
4499 | } | |||
4500 | ||||
4501 | /// We are trying to inject an anonymous member into the given scope; | |||
4502 | /// check if there's an existing declaration that can't be overloaded. | |||
4503 | /// | |||
4504 | /// \return true if this is a forbidden redeclaration | |||
4505 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, | |||
4506 | Scope *S, | |||
4507 | DeclContext *Owner, | |||
4508 | DeclarationName Name, | |||
4509 | SourceLocation NameLoc, | |||
4510 | bool IsUnion) { | |||
4511 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, | |||
4512 | Sema::ForVisibleRedeclaration); | |||
4513 | if (!SemaRef.LookupName(R, S)) return false; | |||
4514 | ||||
4515 | // Pick a representative declaration. | |||
4516 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); | |||
4517 | assert(PrevDecl && "Expected a non-null Decl")((PrevDecl && "Expected a non-null Decl") ? static_cast <void> (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4517, __PRETTY_FUNCTION__)); | |||
4518 | ||||
4519 | if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) | |||
4520 | return false; | |||
4521 | ||||
4522 | SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) | |||
4523 | << IsUnion << Name; | |||
4524 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
4525 | ||||
4526 | return true; | |||
4527 | } | |||
4528 | ||||
4529 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the | |||
4530 | /// anonymous struct or union AnonRecord into the owning context Owner | |||
4531 | /// and scope S. This routine will be invoked just after we realize | |||
4532 | /// that an unnamed union or struct is actually an anonymous union or | |||
4533 | /// struct, e.g., | |||
4534 | /// | |||
4535 | /// @code | |||
4536 | /// union { | |||
4537 | /// int i; | |||
4538 | /// float f; | |||
4539 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and | |||
4540 | /// // f into the surrounding scope.x | |||
4541 | /// @endcode | |||
4542 | /// | |||
4543 | /// This routine is recursive, injecting the names of nested anonymous | |||
4544 | /// structs/unions into the owning context and scope as well. | |||
4545 | static bool | |||
4546 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, | |||
4547 | RecordDecl *AnonRecord, AccessSpecifier AS, | |||
4548 | SmallVectorImpl<NamedDecl *> &Chaining) { | |||
4549 | bool Invalid = false; | |||
4550 | ||||
4551 | // Look every FieldDecl and IndirectFieldDecl with a name. | |||
4552 | for (auto *D : AnonRecord->decls()) { | |||
4553 | if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && | |||
4554 | cast<NamedDecl>(D)->getDeclName()) { | |||
4555 | ValueDecl *VD = cast<ValueDecl>(D); | |||
4556 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), | |||
4557 | VD->getLocation(), | |||
4558 | AnonRecord->isUnion())) { | |||
4559 | // C++ [class.union]p2: | |||
4560 | // The names of the members of an anonymous union shall be | |||
4561 | // distinct from the names of any other entity in the | |||
4562 | // scope in which the anonymous union is declared. | |||
4563 | Invalid = true; | |||
4564 | } else { | |||
4565 | // C++ [class.union]p2: | |||
4566 | // For the purpose of name lookup, after the anonymous union | |||
4567 | // definition, the members of the anonymous union are | |||
4568 | // considered to have been defined in the scope in which the | |||
4569 | // anonymous union is declared. | |||
4570 | unsigned OldChainingSize = Chaining.size(); | |||
4571 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) | |||
4572 | Chaining.append(IF->chain_begin(), IF->chain_end()); | |||
4573 | else | |||
4574 | Chaining.push_back(VD); | |||
4575 | ||||
4576 | assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4576, __PRETTY_FUNCTION__)); | |||
4577 | NamedDecl **NamedChain = | |||
4578 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; | |||
4579 | for (unsigned i = 0; i < Chaining.size(); i++) | |||
4580 | NamedChain[i] = Chaining[i]; | |||
4581 | ||||
4582 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( | |||
4583 | SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), | |||
4584 | VD->getType(), {NamedChain, Chaining.size()}); | |||
4585 | ||||
4586 | for (const auto *Attr : VD->attrs()) | |||
4587 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); | |||
4588 | ||||
4589 | IndirectField->setAccess(AS); | |||
4590 | IndirectField->setImplicit(); | |||
4591 | SemaRef.PushOnScopeChains(IndirectField, S); | |||
4592 | ||||
4593 | // That includes picking up the appropriate access specifier. | |||
4594 | if (AS != AS_none) IndirectField->setAccess(AS); | |||
4595 | ||||
4596 | Chaining.resize(OldChainingSize); | |||
4597 | } | |||
4598 | } | |||
4599 | } | |||
4600 | ||||
4601 | return Invalid; | |||
4602 | } | |||
4603 | ||||
4604 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to | |||
4605 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: | |||
4606 | /// illegal input values are mapped to SC_None. | |||
4607 | static StorageClass | |||
4608 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { | |||
4609 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); | |||
4610 | assert(StorageClassSpec != DeclSpec::SCS_typedef &&((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4611, __PRETTY_FUNCTION__)) | |||
4611 | "Parser allowed 'typedef' as storage class VarDecl.")((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4611, __PRETTY_FUNCTION__)); | |||
4612 | switch (StorageClassSpec) { | |||
4613 | case DeclSpec::SCS_unspecified: return SC_None; | |||
4614 | case DeclSpec::SCS_extern: | |||
4615 | if (DS.isExternInLinkageSpec()) | |||
4616 | return SC_None; | |||
4617 | return SC_Extern; | |||
4618 | case DeclSpec::SCS_static: return SC_Static; | |||
4619 | case DeclSpec::SCS_auto: return SC_Auto; | |||
4620 | case DeclSpec::SCS_register: return SC_Register; | |||
4621 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | |||
4622 | // Illegal SCSs map to None: error reporting is up to the caller. | |||
4623 | case DeclSpec::SCS_mutable: // Fall through. | |||
4624 | case DeclSpec::SCS_typedef: return SC_None; | |||
4625 | } | |||
4626 | llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4626); | |||
4627 | } | |||
4628 | ||||
4629 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { | |||
4630 | assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void> (0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4630, __PRETTY_FUNCTION__)); | |||
4631 | ||||
4632 | for (const auto *I : Record->decls()) { | |||
4633 | const auto *FD = dyn_cast<FieldDecl>(I); | |||
4634 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | |||
4635 | FD = IFD->getAnonField(); | |||
4636 | if (FD && FD->hasInClassInitializer()) | |||
4637 | return FD->getLocation(); | |||
4638 | } | |||
4639 | ||||
4640 | llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4640); | |||
4641 | } | |||
4642 | ||||
4643 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | |||
4644 | SourceLocation DefaultInitLoc) { | |||
4645 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | |||
4646 | return; | |||
4647 | ||||
4648 | S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); | |||
4649 | S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; | |||
4650 | } | |||
4651 | ||||
4652 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | |||
4653 | CXXRecordDecl *AnonUnion) { | |||
4654 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | |||
4655 | return; | |||
4656 | ||||
4657 | checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); | |||
4658 | } | |||
4659 | ||||
4660 | /// BuildAnonymousStructOrUnion - Handle the declaration of an | |||
4661 | /// anonymous structure or union. Anonymous unions are a C++ feature | |||
4662 | /// (C++ [class.union]) and a C11 feature; anonymous structures | |||
4663 | /// are a C11 feature and GNU C++ extension. | |||
4664 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, | |||
4665 | AccessSpecifier AS, | |||
4666 | RecordDecl *Record, | |||
4667 | const PrintingPolicy &Policy) { | |||
4668 | DeclContext *Owner = Record->getDeclContext(); | |||
4669 | ||||
4670 | // Diagnose whether this anonymous struct/union is an extension. | |||
4671 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) | |||
4672 | Diag(Record->getLocation(), diag::ext_anonymous_union); | |||
4673 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) | |||
4674 | Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); | |||
4675 | else if (!Record->isUnion() && !getLangOpts().C11) | |||
4676 | Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); | |||
4677 | ||||
4678 | // C and C++ require different kinds of checks for anonymous | |||
4679 | // structs/unions. | |||
4680 | bool Invalid = false; | |||
4681 | if (getLangOpts().CPlusPlus) { | |||
4682 | const char *PrevSpec = nullptr; | |||
4683 | unsigned DiagID; | |||
4684 | if (Record->isUnion()) { | |||
4685 | // C++ [class.union]p6: | |||
4686 | // C++17 [class.union.anon]p2: | |||
4687 | // Anonymous unions declared in a named namespace or in the | |||
4688 | // global namespace shall be declared static. | |||
4689 | DeclContext *OwnerScope = Owner->getRedeclContext(); | |||
4690 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && | |||
4691 | (OwnerScope->isTranslationUnit() || | |||
4692 | (OwnerScope->isNamespace() && | |||
4693 | !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { | |||
4694 | Diag(Record->getLocation(), diag::err_anonymous_union_not_static) | |||
4695 | << FixItHint::CreateInsertion(Record->getLocation(), "static "); | |||
4696 | ||||
4697 | // Recover by adding 'static'. | |||
4698 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), | |||
4699 | PrevSpec, DiagID, Policy); | |||
4700 | } | |||
4701 | // C++ [class.union]p6: | |||
4702 | // A storage class is not allowed in a declaration of an | |||
4703 | // anonymous union in a class scope. | |||
4704 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && | |||
4705 | isa<RecordDecl>(Owner)) { | |||
4706 | Diag(DS.getStorageClassSpecLoc(), | |||
4707 | diag::err_anonymous_union_with_storage_spec) | |||
4708 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | |||
4709 | ||||
4710 | // Recover by removing the storage specifier. | |||
4711 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, | |||
4712 | SourceLocation(), | |||
4713 | PrevSpec, DiagID, Context.getPrintingPolicy()); | |||
4714 | } | |||
4715 | } | |||
4716 | ||||
4717 | // Ignore const/volatile/restrict qualifiers. | |||
4718 | if (DS.getTypeQualifiers()) { | |||
4719 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | |||
4720 | Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) | |||
4721 | << Record->isUnion() << "const" | |||
4722 | << FixItHint::CreateRemoval(DS.getConstSpecLoc()); | |||
4723 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | |||
4724 | Diag(DS.getVolatileSpecLoc(), | |||
4725 | diag::ext_anonymous_struct_union_qualified) | |||
4726 | << Record->isUnion() << "volatile" | |||
4727 | << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); | |||
4728 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) | |||
4729 | Diag(DS.getRestrictSpecLoc(), | |||
4730 | diag::ext_anonymous_struct_union_qualified) | |||
4731 | << Record->isUnion() << "restrict" | |||
4732 | << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); | |||
4733 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | |||
4734 | Diag(DS.getAtomicSpecLoc(), | |||
4735 | diag::ext_anonymous_struct_union_qualified) | |||
4736 | << Record->isUnion() << "_Atomic" | |||
4737 | << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); | |||
4738 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | |||
4739 | Diag(DS.getUnalignedSpecLoc(), | |||
4740 | diag::ext_anonymous_struct_union_qualified) | |||
4741 | << Record->isUnion() << "__unaligned" | |||
4742 | << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); | |||
4743 | ||||
4744 | DS.ClearTypeQualifiers(); | |||
4745 | } | |||
4746 | ||||
4747 | // C++ [class.union]p2: | |||
4748 | // The member-specification of an anonymous union shall only | |||
4749 | // define non-static data members. [Note: nested types and | |||
4750 | // functions cannot be declared within an anonymous union. ] | |||
4751 | for (auto *Mem : Record->decls()) { | |||
4752 | if (auto *FD = dyn_cast<FieldDecl>(Mem)) { | |||
4753 | // C++ [class.union]p3: | |||
4754 | // An anonymous union shall not have private or protected | |||
4755 | // members (clause 11). | |||
4756 | assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0 ) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4756, __PRETTY_FUNCTION__)); | |||
4757 | if (FD->getAccess() != AS_public) { | |||
4758 | Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) | |||
4759 | << Record->isUnion() << (FD->getAccess() == AS_protected); | |||
4760 | Invalid = true; | |||
4761 | } | |||
4762 | ||||
4763 | // C++ [class.union]p1 | |||
4764 | // An object of a class with a non-trivial constructor, a non-trivial | |||
4765 | // copy constructor, a non-trivial destructor, or a non-trivial copy | |||
4766 | // assignment operator cannot be a member of a union, nor can an | |||
4767 | // array of such objects. | |||
4768 | if (CheckNontrivialField(FD)) | |||
4769 | Invalid = true; | |||
4770 | } else if (Mem->isImplicit()) { | |||
4771 | // Any implicit members are fine. | |||
4772 | } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { | |||
4773 | // This is a type that showed up in an | |||
4774 | // elaborated-type-specifier inside the anonymous struct or | |||
4775 | // union, but which actually declares a type outside of the | |||
4776 | // anonymous struct or union. It's okay. | |||
4777 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { | |||
4778 | if (!MemRecord->isAnonymousStructOrUnion() && | |||
4779 | MemRecord->getDeclName()) { | |||
4780 | // Visual C++ allows type definition in anonymous struct or union. | |||
4781 | if (getLangOpts().MicrosoftExt) | |||
4782 | Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) | |||
4783 | << Record->isUnion(); | |||
4784 | else { | |||
4785 | // This is a nested type declaration. | |||
4786 | Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) | |||
4787 | << Record->isUnion(); | |||
4788 | Invalid = true; | |||
4789 | } | |||
4790 | } else { | |||
4791 | // This is an anonymous type definition within another anonymous type. | |||
4792 | // This is a popular extension, provided by Plan9, MSVC and GCC, but | |||
4793 | // not part of standard C++. | |||
4794 | Diag(MemRecord->getLocation(), | |||
4795 | diag::ext_anonymous_record_with_anonymous_type) | |||
4796 | << Record->isUnion(); | |||
4797 | } | |||
4798 | } else if (isa<AccessSpecDecl>(Mem)) { | |||
4799 | // Any access specifier is fine. | |||
4800 | } else if (isa<StaticAssertDecl>(Mem)) { | |||
4801 | // In C++1z, static_assert declarations are also fine. | |||
4802 | } else { | |||
4803 | // We have something that isn't a non-static data | |||
4804 | // member. Complain about it. | |||
4805 | unsigned DK = diag::err_anonymous_record_bad_member; | |||
4806 | if (isa<TypeDecl>(Mem)) | |||
4807 | DK = diag::err_anonymous_record_with_type; | |||
4808 | else if (isa<FunctionDecl>(Mem)) | |||
4809 | DK = diag::err_anonymous_record_with_function; | |||
4810 | else if (isa<VarDecl>(Mem)) | |||
4811 | DK = diag::err_anonymous_record_with_static; | |||
4812 | ||||
4813 | // Visual C++ allows type definition in anonymous struct or union. | |||
4814 | if (getLangOpts().MicrosoftExt && | |||
4815 | DK == diag::err_anonymous_record_with_type) | |||
4816 | Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) | |||
4817 | << Record->isUnion(); | |||
4818 | else { | |||
4819 | Diag(Mem->getLocation(), DK) << Record->isUnion(); | |||
4820 | Invalid = true; | |||
4821 | } | |||
4822 | } | |||
4823 | } | |||
4824 | ||||
4825 | // C++11 [class.union]p8 (DR1460): | |||
4826 | // At most one variant member of a union may have a | |||
4827 | // brace-or-equal-initializer. | |||
4828 | if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && | |||
4829 | Owner->isRecord()) | |||
4830 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), | |||
4831 | cast<CXXRecordDecl>(Record)); | |||
4832 | } | |||
4833 | ||||
4834 | if (!Record->isUnion() && !Owner->isRecord()) { | |||
4835 | Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) | |||
4836 | << getLangOpts().CPlusPlus; | |||
4837 | Invalid = true; | |||
4838 | } | |||
4839 | ||||
4840 | // C++ [dcl.dcl]p3: | |||
4841 | // [If there are no declarators], and except for the declaration of an | |||
4842 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | |||
4843 | // names into the program | |||
4844 | // C++ [class.mem]p2: | |||
4845 | // each such member-declaration shall either declare at least one member | |||
4846 | // name of the class or declare at least one unnamed bit-field | |||
4847 | // | |||
4848 | // For C this is an error even for a named struct, and is diagnosed elsewhere. | |||
4849 | if (getLangOpts().CPlusPlus && Record->field_empty()) | |||
4850 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | |||
4851 | ||||
4852 | // Mock up a declarator. | |||
4853 | Declarator Dc(DS, DeclaratorContext::MemberContext); | |||
4854 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | |||
4855 | assert(TInfo && "couldn't build declarator info for anonymous struct/union")((TInfo && "couldn't build declarator info for anonymous struct/union" ) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4855, __PRETTY_FUNCTION__)); | |||
4856 | ||||
4857 | // Create a declaration for this anonymous struct/union. | |||
4858 | NamedDecl *Anon = nullptr; | |||
4859 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { | |||
4860 | Anon = FieldDecl::Create( | |||
4861 | Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), | |||
4862 | /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, | |||
4863 | /*BitWidth=*/nullptr, /*Mutable=*/false, | |||
4864 | /*InitStyle=*/ICIS_NoInit); | |||
4865 | Anon->setAccess(AS); | |||
4866 | if (getLangOpts().CPlusPlus) | |||
4867 | FieldCollector->Add(cast<FieldDecl>(Anon)); | |||
4868 | } else { | |||
4869 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); | |||
4870 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); | |||
4871 | if (SCSpec == DeclSpec::SCS_mutable) { | |||
4872 | // mutable can only appear on non-static class members, so it's always | |||
4873 | // an error here | |||
4874 | Diag(Record->getLocation(), diag::err_mutable_nonmember); | |||
4875 | Invalid = true; | |||
4876 | SC = SC_None; | |||
4877 | } | |||
4878 | ||||
4879 | Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), | |||
4880 | Record->getLocation(), /*IdentifierInfo=*/nullptr, | |||
4881 | Context.getTypeDeclType(Record), TInfo, SC); | |||
4882 | ||||
4883 | // Default-initialize the implicit variable. This initialization will be | |||
4884 | // trivial in almost all cases, except if a union member has an in-class | |||
4885 | // initializer: | |||
4886 | // union { int n = 0; }; | |||
4887 | ActOnUninitializedDecl(Anon); | |||
4888 | } | |||
4889 | Anon->setImplicit(); | |||
4890 | ||||
4891 | // Mark this as an anonymous struct/union type. | |||
4892 | Record->setAnonymousStructOrUnion(true); | |||
4893 | ||||
4894 | // Add the anonymous struct/union object to the current | |||
4895 | // context. We'll be referencing this object when we refer to one of | |||
4896 | // its members. | |||
4897 | Owner->addDecl(Anon); | |||
4898 | ||||
4899 | // Inject the members of the anonymous struct/union into the owning | |||
4900 | // context and into the identifier resolver chain for name lookup | |||
4901 | // purposes. | |||
4902 | SmallVector<NamedDecl*, 2> Chain; | |||
4903 | Chain.push_back(Anon); | |||
4904 | ||||
4905 | if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) | |||
4906 | Invalid = true; | |||
4907 | ||||
4908 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { | |||
4909 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | |||
4910 | Decl *ManglingContextDecl; | |||
4911 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( | |||
4912 | NewVD->getDeclContext(), ManglingContextDecl)) { | |||
4913 | Context.setManglingNumber( | |||
4914 | NewVD, MCtx->getManglingNumber( | |||
4915 | NewVD, getMSManglingNumber(getLangOpts(), S))); | |||
4916 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | |||
4917 | } | |||
4918 | } | |||
4919 | } | |||
4920 | ||||
4921 | if (Invalid) | |||
4922 | Anon->setInvalidDecl(); | |||
4923 | ||||
4924 | return Anon; | |||
4925 | } | |||
4926 | ||||
4927 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an | |||
4928 | /// Microsoft C anonymous structure. | |||
4929 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx | |||
4930 | /// Example: | |||
4931 | /// | |||
4932 | /// struct A { int a; }; | |||
4933 | /// struct B { struct A; int b; }; | |||
4934 | /// | |||
4935 | /// void foo() { | |||
4936 | /// B var; | |||
4937 | /// var.a = 3; | |||
4938 | /// } | |||
4939 | /// | |||
4940 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, | |||
4941 | RecordDecl *Record) { | |||
4942 | assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void > (0) : __assert_fail ("Record && \"expected a record!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4942, __PRETTY_FUNCTION__)); | |||
4943 | ||||
4944 | // Mock up a declarator. | |||
4945 | Declarator Dc(DS, DeclaratorContext::TypeNameContext); | |||
4946 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | |||
4947 | assert(TInfo && "couldn't build declarator info for anonymous struct")((TInfo && "couldn't build declarator info for anonymous struct" ) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 4947, __PRETTY_FUNCTION__)); | |||
4948 | ||||
4949 | auto *ParentDecl = cast<RecordDecl>(CurContext); | |||
4950 | QualType RecTy = Context.getTypeDeclType(Record); | |||
4951 | ||||
4952 | // Create a declaration for this anonymous struct. | |||
4953 | NamedDecl *Anon = | |||
4954 | FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), | |||
4955 | /*IdentifierInfo=*/nullptr, RecTy, TInfo, | |||
4956 | /*BitWidth=*/nullptr, /*Mutable=*/false, | |||
4957 | /*InitStyle=*/ICIS_NoInit); | |||
4958 | Anon->setImplicit(); | |||
4959 | ||||
4960 | // Add the anonymous struct object to the current context. | |||
4961 | CurContext->addDecl(Anon); | |||
4962 | ||||
4963 | // Inject the members of the anonymous struct into the current | |||
4964 | // context and into the identifier resolver chain for name lookup | |||
4965 | // purposes. | |||
4966 | SmallVector<NamedDecl*, 2> Chain; | |||
4967 | Chain.push_back(Anon); | |||
4968 | ||||
4969 | RecordDecl *RecordDef = Record->getDefinition(); | |||
4970 | if (RequireCompleteType(Anon->getLocation(), RecTy, | |||
4971 | diag::err_field_incomplete) || | |||
4972 | InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, | |||
4973 | AS_none, Chain)) { | |||
4974 | Anon->setInvalidDecl(); | |||
4975 | ParentDecl->setInvalidDecl(); | |||
4976 | } | |||
4977 | ||||
4978 | return Anon; | |||
4979 | } | |||
4980 | ||||
4981 | /// GetNameForDeclarator - Determine the full declaration name for the | |||
4982 | /// given Declarator. | |||
4983 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { | |||
4984 | return GetNameFromUnqualifiedId(D.getName()); | |||
4985 | } | |||
4986 | ||||
4987 | /// Retrieves the declaration name from a parsed unqualified-id. | |||
4988 | DeclarationNameInfo | |||
4989 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { | |||
4990 | DeclarationNameInfo NameInfo; | |||
4991 | NameInfo.setLoc(Name.StartLocation); | |||
4992 | ||||
4993 | switch (Name.getKind()) { | |||
4994 | ||||
4995 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
4996 | case UnqualifiedIdKind::IK_Identifier: | |||
4997 | NameInfo.setName(Name.Identifier); | |||
4998 | return NameInfo; | |||
4999 | ||||
5000 | case UnqualifiedIdKind::IK_DeductionGuideName: { | |||
5001 | // C++ [temp.deduct.guide]p3: | |||
5002 | // The simple-template-id shall name a class template specialization. | |||
5003 | // The template-name shall be the same identifier as the template-name | |||
5004 | // of the simple-template-id. | |||
5005 | // These together intend to imply that the template-name shall name a | |||
5006 | // class template. | |||
5007 | // FIXME: template<typename T> struct X {}; | |||
5008 | // template<typename T> using Y = X<T>; | |||
5009 | // Y(int) -> Y<int>; | |||
5010 | // satisfies these rules but does not name a class template. | |||
5011 | TemplateName TN = Name.TemplateName.get().get(); | |||
5012 | auto *Template = TN.getAsTemplateDecl(); | |||
5013 | if (!Template || !isa<ClassTemplateDecl>(Template)) { | |||
5014 | Diag(Name.StartLocation, | |||
5015 | diag::err_deduction_guide_name_not_class_template) | |||
5016 | << (int)getTemplateNameKindForDiagnostics(TN) << TN; | |||
5017 | if (Template) | |||
5018 | Diag(Template->getLocation(), diag::note_template_decl_here); | |||
5019 | return DeclarationNameInfo(); | |||
5020 | } | |||
5021 | ||||
5022 | NameInfo.setName( | |||
5023 | Context.DeclarationNames.getCXXDeductionGuideName(Template)); | |||
5024 | return NameInfo; | |||
5025 | } | |||
5026 | ||||
5027 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
5028 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( | |||
5029 | Name.OperatorFunctionId.Operator)); | |||
5030 | NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc | |||
5031 | = Name.OperatorFunctionId.SymbolLocations[0]; | |||
5032 | NameInfo.getInfo().CXXOperatorName.EndOpNameLoc | |||
5033 | = Name.EndLocation.getRawEncoding(); | |||
5034 | return NameInfo; | |||
5035 | ||||
5036 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
5037 | NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( | |||
5038 | Name.Identifier)); | |||
5039 | NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); | |||
5040 | return NameInfo; | |||
5041 | ||||
5042 | case UnqualifiedIdKind::IK_ConversionFunctionId: { | |||
5043 | TypeSourceInfo *TInfo; | |||
5044 | QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); | |||
5045 | if (Ty.isNull()) | |||
5046 | return DeclarationNameInfo(); | |||
5047 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( | |||
5048 | Context.getCanonicalType(Ty))); | |||
5049 | NameInfo.setNamedTypeInfo(TInfo); | |||
5050 | return NameInfo; | |||
5051 | } | |||
5052 | ||||
5053 | case UnqualifiedIdKind::IK_ConstructorName: { | |||
5054 | TypeSourceInfo *TInfo; | |||
5055 | QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); | |||
5056 | if (Ty.isNull()) | |||
5057 | return DeclarationNameInfo(); | |||
5058 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | |||
5059 | Context.getCanonicalType(Ty))); | |||
5060 | NameInfo.setNamedTypeInfo(TInfo); | |||
5061 | return NameInfo; | |||
5062 | } | |||
5063 | ||||
5064 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { | |||
5065 | // In well-formed code, we can only have a constructor | |||
5066 | // template-id that refers to the current context, so go there | |||
5067 | // to find the actual type being constructed. | |||
5068 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); | |||
5069 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) | |||
5070 | return DeclarationNameInfo(); | |||
5071 | ||||
5072 | // Determine the type of the class being constructed. | |||
5073 | QualType CurClassType = Context.getTypeDeclType(CurClass); | |||
5074 | ||||
5075 | // FIXME: Check two things: that the template-id names the same type as | |||
5076 | // CurClassType, and that the template-id does not occur when the name | |||
5077 | // was qualified. | |||
5078 | ||||
5079 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | |||
5080 | Context.getCanonicalType(CurClassType))); | |||
5081 | // FIXME: should we retrieve TypeSourceInfo? | |||
5082 | NameInfo.setNamedTypeInfo(nullptr); | |||
5083 | return NameInfo; | |||
5084 | } | |||
5085 | ||||
5086 | case UnqualifiedIdKind::IK_DestructorName: { | |||
5087 | TypeSourceInfo *TInfo; | |||
5088 | QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); | |||
5089 | if (Ty.isNull()) | |||
5090 | return DeclarationNameInfo(); | |||
5091 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( | |||
5092 | Context.getCanonicalType(Ty))); | |||
5093 | NameInfo.setNamedTypeInfo(TInfo); | |||
5094 | return NameInfo; | |||
5095 | } | |||
5096 | ||||
5097 | case UnqualifiedIdKind::IK_TemplateId: { | |||
5098 | TemplateName TName = Name.TemplateId->Template.get(); | |||
5099 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; | |||
5100 | return Context.getNameForTemplate(TName, TNameLoc); | |||
5101 | } | |||
5102 | ||||
5103 | } // switch (Name.getKind()) | |||
5104 | ||||
5105 | llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 5105); | |||
5106 | } | |||
5107 | ||||
5108 | static QualType getCoreType(QualType Ty) { | |||
5109 | do { | |||
5110 | if (Ty->isPointerType() || Ty->isReferenceType()) | |||
5111 | Ty = Ty->getPointeeType(); | |||
5112 | else if (Ty->isArrayType()) | |||
5113 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); | |||
5114 | else | |||
5115 | return Ty.withoutLocalFastQualifiers(); | |||
5116 | } while (true); | |||
5117 | } | |||
5118 | ||||
5119 | /// hasSimilarParameters - Determine whether the C++ functions Declaration | |||
5120 | /// and Definition have "nearly" matching parameters. This heuristic is | |||
5121 | /// used to improve diagnostics in the case where an out-of-line function | |||
5122 | /// definition doesn't match any declaration within the class or namespace. | |||
5123 | /// Also sets Params to the list of indices to the parameters that differ | |||
5124 | /// between the declaration and the definition. If hasSimilarParameters | |||
5125 | /// returns true and Params is empty, then all of the parameters match. | |||
5126 | static bool hasSimilarParameters(ASTContext &Context, | |||
5127 | FunctionDecl *Declaration, | |||
5128 | FunctionDecl *Definition, | |||
5129 | SmallVectorImpl<unsigned> &Params) { | |||
5130 | Params.clear(); | |||
5131 | if (Declaration->param_size() != Definition->param_size()) | |||
5132 | return false; | |||
5133 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { | |||
5134 | QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); | |||
5135 | QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); | |||
5136 | ||||
5137 | // The parameter types are identical | |||
5138 | if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) | |||
5139 | continue; | |||
5140 | ||||
5141 | QualType DeclParamBaseTy = getCoreType(DeclParamTy); | |||
5142 | QualType DefParamBaseTy = getCoreType(DefParamTy); | |||
5143 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); | |||
5144 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); | |||
5145 | ||||
5146 | if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || | |||
5147 | (DeclTyName && DeclTyName == DefTyName)) | |||
5148 | Params.push_back(Idx); | |||
5149 | else // The two parameters aren't even close | |||
5150 | return false; | |||
5151 | } | |||
5152 | ||||
5153 | return true; | |||
5154 | } | |||
5155 | ||||
5156 | /// NeedsRebuildingInCurrentInstantiation - Checks whether the given | |||
5157 | /// declarator needs to be rebuilt in the current instantiation. | |||
5158 | /// Any bits of declarator which appear before the name are valid for | |||
5159 | /// consideration here. That's specifically the type in the decl spec | |||
5160 | /// and the base type in any member-pointer chunks. | |||
5161 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, | |||
5162 | DeclarationName Name) { | |||
5163 | // The types we specifically need to rebuild are: | |||
5164 | // - typenames, typeofs, and decltypes | |||
5165 | // - types which will become injected class names | |||
5166 | // Of course, we also need to rebuild any type referencing such a | |||
5167 | // type. It's safest to just say "dependent", but we call out a | |||
5168 | // few cases here. | |||
5169 | ||||
5170 | DeclSpec &DS = D.getMutableDeclSpec(); | |||
5171 | switch (DS.getTypeSpecType()) { | |||
5172 | case DeclSpec::TST_typename: | |||
5173 | case DeclSpec::TST_typeofType: | |||
5174 | case DeclSpec::TST_underlyingType: | |||
5175 | case DeclSpec::TST_atomic: { | |||
5176 | // Grab the type from the parser. | |||
5177 | TypeSourceInfo *TSI = nullptr; | |||
5178 | QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); | |||
5179 | if (T.isNull() || !T->isDependentType()) break; | |||
5180 | ||||
5181 | // Make sure there's a type source info. This isn't really much | |||
5182 | // of a waste; most dependent types should have type source info | |||
5183 | // attached already. | |||
5184 | if (!TSI) | |||
5185 | TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); | |||
5186 | ||||
5187 | // Rebuild the type in the current instantiation. | |||
5188 | TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); | |||
5189 | if (!TSI) return true; | |||
5190 | ||||
5191 | // Store the new type back in the decl spec. | |||
5192 | ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); | |||
5193 | DS.UpdateTypeRep(LocType); | |||
5194 | break; | |||
5195 | } | |||
5196 | ||||
5197 | case DeclSpec::TST_decltype: | |||
5198 | case DeclSpec::TST_typeofExpr: { | |||
5199 | Expr *E = DS.getRepAsExpr(); | |||
5200 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); | |||
5201 | if (Result.isInvalid()) return true; | |||
5202 | DS.UpdateExprRep(Result.get()); | |||
5203 | break; | |||
5204 | } | |||
5205 | ||||
5206 | default: | |||
5207 | // Nothing to do for these decl specs. | |||
5208 | break; | |||
5209 | } | |||
5210 | ||||
5211 | // It doesn't matter what order we do this in. | |||
5212 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | |||
5213 | DeclaratorChunk &Chunk = D.getTypeObject(I); | |||
5214 | ||||
5215 | // The only type information in the declarator which can come | |||
5216 | // before the declaration name is the base type of a member | |||
5217 | // pointer. | |||
5218 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) | |||
5219 | continue; | |||
5220 | ||||
5221 | // Rebuild the scope specifier in-place. | |||
5222 | CXXScopeSpec &SS = Chunk.Mem.Scope(); | |||
5223 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) | |||
5224 | return true; | |||
5225 | } | |||
5226 | ||||
5227 | return false; | |||
5228 | } | |||
5229 | ||||
5230 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { | |||
5231 | D.setFunctionDefinitionKind(FDK_Declaration); | |||
5232 | Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); | |||
5233 | ||||
5234 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && | |||
5235 | Dcl && Dcl->getDeclContext()->isFileContext()) | |||
5236 | Dcl->setTopLevelDeclInObjCContainer(); | |||
5237 | ||||
5238 | if (getLangOpts().OpenCL) | |||
5239 | setCurrentOpenCLExtensionForDecl(Dcl); | |||
5240 | ||||
5241 | return Dcl; | |||
5242 | } | |||
5243 | ||||
5244 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: | |||
5245 | /// If T is the name of a class, then each of the following shall have a | |||
5246 | /// name different from T: | |||
5247 | /// - every static data member of class T; | |||
5248 | /// - every member function of class T | |||
5249 | /// - every member of class T that is itself a type; | |||
5250 | /// \returns true if the declaration name violates these rules. | |||
5251 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, | |||
5252 | DeclarationNameInfo NameInfo) { | |||
5253 | DeclarationName Name = NameInfo.getName(); | |||
5254 | ||||
5255 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); | |||
5256 | while (Record && Record->isAnonymousStructOrUnion()) | |||
5257 | Record = dyn_cast<CXXRecordDecl>(Record->getParent()); | |||
5258 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { | |||
5259 | Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; | |||
5260 | return true; | |||
5261 | } | |||
5262 | ||||
5263 | return false; | |||
5264 | } | |||
5265 | ||||
5266 | /// Diagnose a declaration whose declarator-id has the given | |||
5267 | /// nested-name-specifier. | |||
5268 | /// | |||
5269 | /// \param SS The nested-name-specifier of the declarator-id. | |||
5270 | /// | |||
5271 | /// \param DC The declaration context to which the nested-name-specifier | |||
5272 | /// resolves. | |||
5273 | /// | |||
5274 | /// \param Name The name of the entity being declared. | |||
5275 | /// | |||
5276 | /// \param Loc The location of the name of the entity being declared. | |||
5277 | /// | |||
5278 | /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus | |||
5279 | /// we're declaring an explicit / partial specialization / instantiation. | |||
5280 | /// | |||
5281 | /// \returns true if we cannot safely recover from this error, false otherwise. | |||
5282 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, | |||
5283 | DeclarationName Name, | |||
5284 | SourceLocation Loc, bool IsTemplateId) { | |||
5285 | DeclContext *Cur = CurContext; | |||
5286 | while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) | |||
5287 | Cur = Cur->getParent(); | |||
5288 | ||||
5289 | // If the user provided a superfluous scope specifier that refers back to the | |||
5290 | // class in which the entity is already declared, diagnose and ignore it. | |||
5291 | // | |||
5292 | // class X { | |||
5293 | // void X::f(); | |||
5294 | // }; | |||
5295 | // | |||
5296 | // Note, it was once ill-formed to give redundant qualification in all | |||
5297 | // contexts, but that rule was removed by DR482. | |||
5298 | if (Cur->Equals(DC)) { | |||
5299 | if (Cur->isRecord()) { | |||
5300 | Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification | |||
5301 | : diag::err_member_extra_qualification) | |||
5302 | << Name << FixItHint::CreateRemoval(SS.getRange()); | |||
5303 | SS.clear(); | |||
5304 | } else { | |||
5305 | Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; | |||
5306 | } | |||
5307 | return false; | |||
5308 | } | |||
5309 | ||||
5310 | // Check whether the qualifying scope encloses the scope of the original | |||
5311 | // declaration. For a template-id, we perform the checks in | |||
5312 | // CheckTemplateSpecializationScope. | |||
5313 | if (!Cur->Encloses(DC) && !IsTemplateId) { | |||
5314 | if (Cur->isRecord()) | |||
5315 | Diag(Loc, diag::err_member_qualification) | |||
5316 | << Name << SS.getRange(); | |||
5317 | else if (isa<TranslationUnitDecl>(DC)) | |||
5318 | Diag(Loc, diag::err_invalid_declarator_global_scope) | |||
5319 | << Name << SS.getRange(); | |||
5320 | else if (isa<FunctionDecl>(Cur)) | |||
5321 | Diag(Loc, diag::err_invalid_declarator_in_function) | |||
5322 | << Name << SS.getRange(); | |||
5323 | else if (isa<BlockDecl>(Cur)) | |||
5324 | Diag(Loc, diag::err_invalid_declarator_in_block) | |||
5325 | << Name << SS.getRange(); | |||
5326 | else | |||
5327 | Diag(Loc, diag::err_invalid_declarator_scope) | |||
5328 | << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); | |||
5329 | ||||
5330 | return true; | |||
5331 | } | |||
5332 | ||||
5333 | if (Cur->isRecord()) { | |||
5334 | // Cannot qualify members within a class. | |||
5335 | Diag(Loc, diag::err_member_qualification) | |||
5336 | << Name << SS.getRange(); | |||
5337 | SS.clear(); | |||
5338 | ||||
5339 | // C++ constructors and destructors with incorrect scopes can break | |||
5340 | // our AST invariants by having the wrong underlying types. If | |||
5341 | // that's the case, then drop this declaration entirely. | |||
5342 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || | |||
5343 | Name.getNameKind() == DeclarationName::CXXDestructorName) && | |||
5344 | !Context.hasSameType(Name.getCXXNameType(), | |||
5345 | Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) | |||
5346 | return true; | |||
5347 | ||||
5348 | return false; | |||
5349 | } | |||
5350 | ||||
5351 | // C++11 [dcl.meaning]p1: | |||
5352 | // [...] "The nested-name-specifier of the qualified declarator-id shall | |||
5353 | // not begin with a decltype-specifer" | |||
5354 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); | |||
5355 | while (SpecLoc.getPrefix()) | |||
5356 | SpecLoc = SpecLoc.getPrefix(); | |||
5357 | if (dyn_cast_or_null<DecltypeType>( | |||
5358 | SpecLoc.getNestedNameSpecifier()->getAsType())) | |||
5359 | Diag(Loc, diag::err_decltype_in_declarator) | |||
5360 | << SpecLoc.getTypeLoc().getSourceRange(); | |||
5361 | ||||
5362 | return false; | |||
5363 | } | |||
5364 | ||||
5365 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, | |||
5366 | MultiTemplateParamsArg TemplateParamLists) { | |||
5367 | // TODO: consider using NameInfo for diagnostic. | |||
5368 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | |||
5369 | DeclarationName Name = NameInfo.getName(); | |||
5370 | ||||
5371 | // All of these full declarators require an identifier. If it doesn't have | |||
5372 | // one, the ParsedFreeStandingDeclSpec action should be used. | |||
5373 | if (D.isDecompositionDeclarator()) { | |||
5374 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); | |||
5375 | } else if (!Name) { | |||
5376 | if (!D.isInvalidType()) // Reject this if we think it is valid. | |||
5377 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) | |||
5378 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); | |||
5379 | return nullptr; | |||
5380 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) | |||
5381 | return nullptr; | |||
5382 | ||||
5383 | // The scope passed in may not be a decl scope. Zip up the scope tree until | |||
5384 | // we find one that is. | |||
5385 | while ((S->getFlags() & Scope::DeclScope) == 0 || | |||
5386 | (S->getFlags() & Scope::TemplateParamScope) != 0) | |||
5387 | S = S->getParent(); | |||
5388 | ||||
5389 | DeclContext *DC = CurContext; | |||
5390 | if (D.getCXXScopeSpec().isInvalid()) | |||
5391 | D.setInvalidType(); | |||
5392 | else if (D.getCXXScopeSpec().isSet()) { | |||
5393 | if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), | |||
5394 | UPPC_DeclarationQualifier)) | |||
5395 | return nullptr; | |||
5396 | ||||
5397 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); | |||
5398 | DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); | |||
5399 | if (!DC || isa<EnumDecl>(DC)) { | |||
5400 | // If we could not compute the declaration context, it's because the | |||
5401 | // declaration context is dependent but does not refer to a class, | |||
5402 | // class template, or class template partial specialization. Complain | |||
5403 | // and return early, to avoid the coming semantic disaster. | |||
5404 | Diag(D.getIdentifierLoc(), | |||
5405 | diag::err_template_qualified_declarator_no_match) | |||
5406 | << D.getCXXScopeSpec().getScopeRep() | |||
5407 | << D.getCXXScopeSpec().getRange(); | |||
5408 | return nullptr; | |||
5409 | } | |||
5410 | bool IsDependentContext = DC->isDependentContext(); | |||
5411 | ||||
5412 | if (!IsDependentContext && | |||
5413 | RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) | |||
5414 | return nullptr; | |||
5415 | ||||
5416 | // If a class is incomplete, do not parse entities inside it. | |||
5417 | if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { | |||
5418 | Diag(D.getIdentifierLoc(), | |||
5419 | diag::err_member_def_undefined_record) | |||
5420 | << Name << DC << D.getCXXScopeSpec().getRange(); | |||
5421 | return nullptr; | |||
5422 | } | |||
5423 | if (!D.getDeclSpec().isFriendSpecified()) { | |||
5424 | if (diagnoseQualifiedDeclaration( | |||
5425 | D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), | |||
5426 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { | |||
5427 | if (DC->isRecord()) | |||
5428 | return nullptr; | |||
5429 | ||||
5430 | D.setInvalidType(); | |||
5431 | } | |||
5432 | } | |||
5433 | ||||
5434 | // Check whether we need to rebuild the type of the given | |||
5435 | // declaration in the current instantiation. | |||
5436 | if (EnteringContext && IsDependentContext && | |||
5437 | TemplateParamLists.size() != 0) { | |||
5438 | ContextRAII SavedContext(*this, DC); | |||
5439 | if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) | |||
5440 | D.setInvalidType(); | |||
5441 | } | |||
5442 | } | |||
5443 | ||||
5444 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
5445 | QualType R = TInfo->getType(); | |||
5446 | ||||
5447 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
5448 | UPPC_DeclarationType)) | |||
5449 | D.setInvalidType(); | |||
5450 | ||||
5451 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
5452 | forRedeclarationInCurContext()); | |||
5453 | ||||
5454 | // See if this is a redefinition of a variable in the same scope. | |||
5455 | if (!D.getCXXScopeSpec().isSet()) { | |||
5456 | bool IsLinkageLookup = false; | |||
5457 | bool CreateBuiltins = false; | |||
5458 | ||||
5459 | // If the declaration we're planning to build will be a function | |||
5460 | // or object with linkage, then look for another declaration with | |||
5461 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). | |||
5462 | // | |||
5463 | // If the declaration we're planning to build will be declared with | |||
5464 | // external linkage in the translation unit, create any builtin with | |||
5465 | // the same name. | |||
5466 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
5467 | /* Do nothing*/; | |||
5468 | else if (CurContext->isFunctionOrMethod() && | |||
5469 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || | |||
5470 | R->isFunctionType())) { | |||
5471 | IsLinkageLookup = true; | |||
5472 | CreateBuiltins = | |||
5473 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); | |||
5474 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && | |||
5475 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) | |||
5476 | CreateBuiltins = true; | |||
5477 | ||||
5478 | if (IsLinkageLookup) { | |||
5479 | Previous.clear(LookupRedeclarationWithLinkage); | |||
5480 | Previous.setRedeclarationKind(ForExternalRedeclaration); | |||
5481 | } | |||
5482 | ||||
5483 | LookupName(Previous, S, CreateBuiltins); | |||
5484 | } else { // Something like "int foo::x;" | |||
5485 | LookupQualifiedName(Previous, DC); | |||
5486 | ||||
5487 | // C++ [dcl.meaning]p1: | |||
5488 | // When the declarator-id is qualified, the declaration shall refer to a | |||
5489 | // previously declared member of the class or namespace to which the | |||
5490 | // qualifier refers (or, in the case of a namespace, of an element of the | |||
5491 | // inline namespace set of that namespace (7.3.1)) or to a specialization | |||
5492 | // thereof; [...] | |||
5493 | // | |||
5494 | // Note that we already checked the context above, and that we do not have | |||
5495 | // enough information to make sure that Previous contains the declaration | |||
5496 | // we want to match. For example, given: | |||
5497 | // | |||
5498 | // class X { | |||
5499 | // void f(); | |||
5500 | // void f(float); | |||
5501 | // }; | |||
5502 | // | |||
5503 | // void X::f(int) { } // ill-formed | |||
5504 | // | |||
5505 | // In this case, Previous will point to the overload set | |||
5506 | // containing the two f's declared in X, but neither of them | |||
5507 | // matches. | |||
5508 | ||||
5509 | // C++ [dcl.meaning]p1: | |||
5510 | // [...] the member shall not merely have been introduced by a | |||
5511 | // using-declaration in the scope of the class or namespace nominated by | |||
5512 | // the nested-name-specifier of the declarator-id. | |||
5513 | RemoveUsingDecls(Previous); | |||
5514 | } | |||
5515 | ||||
5516 | if (Previous.isSingleResult() && | |||
5517 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
5518 | // Maybe we will complain about the shadowed template parameter. | |||
5519 | if (!D.isInvalidType()) | |||
5520 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | |||
5521 | Previous.getFoundDecl()); | |||
5522 | ||||
5523 | // Just pretend that we didn't see the previous declaration. | |||
5524 | Previous.clear(); | |||
5525 | } | |||
5526 | ||||
5527 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) | |||
5528 | // Forget that the previous declaration is the injected-class-name. | |||
5529 | Previous.clear(); | |||
5530 | ||||
5531 | // In C++, the previous declaration we find might be a tag type | |||
5532 | // (class or enum). In this case, the new declaration will hide the | |||
5533 | // tag type. Note that this applies to functions, function templates, and | |||
5534 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. | |||
5535 | if (Previous.isSingleTagDecl() && | |||
5536 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | |||
5537 | (TemplateParamLists.size() == 0 || R->isFunctionType())) | |||
5538 | Previous.clear(); | |||
5539 | ||||
5540 | // Check that there are no default arguments other than in the parameters | |||
5541 | // of a function declaration (C++ only). | |||
5542 | if (getLangOpts().CPlusPlus) | |||
5543 | CheckExtraCXXDefaultArguments(D); | |||
5544 | ||||
5545 | NamedDecl *New; | |||
5546 | ||||
5547 | bool AddToScope = true; | |||
5548 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { | |||
5549 | if (TemplateParamLists.size()) { | |||
5550 | Diag(D.getIdentifierLoc(), diag::err_template_typedef); | |||
5551 | return nullptr; | |||
5552 | } | |||
5553 | ||||
5554 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); | |||
5555 | } else if (R->isFunctionType()) { | |||
5556 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, | |||
5557 | TemplateParamLists, | |||
5558 | AddToScope); | |||
5559 | } else { | |||
5560 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, | |||
5561 | AddToScope); | |||
5562 | } | |||
5563 | ||||
5564 | if (!New) | |||
5565 | return nullptr; | |||
5566 | ||||
5567 | // If this has an identifier and is not a function template specialization, | |||
5568 | // add it to the scope stack. | |||
5569 | if (New->getDeclName() && AddToScope) | |||
5570 | PushOnScopeChains(New, S); | |||
5571 | ||||
5572 | if (isInOpenMPDeclareTargetContext()) | |||
5573 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | |||
5574 | ||||
5575 | return New; | |||
5576 | } | |||
5577 | ||||
5578 | /// Helper method to turn variable array types into constant array | |||
5579 | /// types in certain situations which would otherwise be errors (for | |||
5580 | /// GCC compatibility). | |||
5581 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, | |||
5582 | ASTContext &Context, | |||
5583 | bool &SizeIsNegative, | |||
5584 | llvm::APSInt &Oversized) { | |||
5585 | // This method tries to turn a variable array into a constant | |||
5586 | // array even when the size isn't an ICE. This is necessary | |||
5587 | // for compatibility with code that depends on gcc's buggy | |||
5588 | // constant expression folding, like struct {char x[(int)(char*)2];} | |||
5589 | SizeIsNegative = false; | |||
5590 | Oversized = 0; | |||
5591 | ||||
5592 | if (T->isDependentType()) | |||
5593 | return QualType(); | |||
5594 | ||||
5595 | QualifierCollector Qs; | |||
5596 | const Type *Ty = Qs.strip(T); | |||
5597 | ||||
5598 | if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { | |||
5599 | QualType Pointee = PTy->getPointeeType(); | |||
5600 | QualType FixedType = | |||
5601 | TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, | |||
5602 | Oversized); | |||
5603 | if (FixedType.isNull()) return FixedType; | |||
5604 | FixedType = Context.getPointerType(FixedType); | |||
5605 | return Qs.apply(Context, FixedType); | |||
5606 | } | |||
5607 | if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { | |||
5608 | QualType Inner = PTy->getInnerType(); | |||
5609 | QualType FixedType = | |||
5610 | TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, | |||
5611 | Oversized); | |||
5612 | if (FixedType.isNull()) return FixedType; | |||
5613 | FixedType = Context.getParenType(FixedType); | |||
5614 | return Qs.apply(Context, FixedType); | |||
5615 | } | |||
5616 | ||||
5617 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); | |||
5618 | if (!VLATy) | |||
5619 | return QualType(); | |||
5620 | // FIXME: We should probably handle this case | |||
5621 | if (VLATy->getElementType()->isVariablyModifiedType()) | |||
5622 | return QualType(); | |||
5623 | ||||
5624 | Expr::EvalResult Result; | |||
5625 | if (!VLATy->getSizeExpr() || | |||
5626 | !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) | |||
5627 | return QualType(); | |||
5628 | ||||
5629 | llvm::APSInt Res = Result.Val.getInt(); | |||
5630 | ||||
5631 | // Check whether the array size is negative. | |||
5632 | if (Res.isSigned() && Res.isNegative()) { | |||
5633 | SizeIsNegative = true; | |||
5634 | return QualType(); | |||
5635 | } | |||
5636 | ||||
5637 | // Check whether the array is too large to be addressed. | |||
5638 | unsigned ActiveSizeBits | |||
5639 | = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), | |||
5640 | Res); | |||
5641 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | |||
5642 | Oversized = Res; | |||
5643 | return QualType(); | |||
5644 | } | |||
5645 | ||||
5646 | return Context.getConstantArrayType(VLATy->getElementType(), | |||
5647 | Res, ArrayType::Normal, 0); | |||
5648 | } | |||
5649 | ||||
5650 | static void | |||
5651 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { | |||
5652 | SrcTL = SrcTL.getUnqualifiedLoc(); | |||
5653 | DstTL = DstTL.getUnqualifiedLoc(); | |||
5654 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { | |||
5655 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); | |||
5656 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), | |||
5657 | DstPTL.getPointeeLoc()); | |||
5658 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); | |||
5659 | return; | |||
5660 | } | |||
5661 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { | |||
5662 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); | |||
5663 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), | |||
5664 | DstPTL.getInnerLoc()); | |||
5665 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); | |||
5666 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); | |||
5667 | return; | |||
5668 | } | |||
5669 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); | |||
5670 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); | |||
5671 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); | |||
5672 | TypeLoc DstElemTL = DstATL.getElementLoc(); | |||
5673 | DstElemTL.initializeFullCopy(SrcElemTL); | |||
5674 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); | |||
5675 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); | |||
5676 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); | |||
5677 | } | |||
5678 | ||||
5679 | /// Helper method to turn variable array types into constant array | |||
5680 | /// types in certain situations which would otherwise be errors (for | |||
5681 | /// GCC compatibility). | |||
5682 | static TypeSourceInfo* | |||
5683 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, | |||
5684 | ASTContext &Context, | |||
5685 | bool &SizeIsNegative, | |||
5686 | llvm::APSInt &Oversized) { | |||
5687 | QualType FixedTy | |||
5688 | = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, | |||
5689 | SizeIsNegative, Oversized); | |||
5690 | if (FixedTy.isNull()) | |||
5691 | return nullptr; | |||
5692 | TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); | |||
5693 | FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), | |||
5694 | FixedTInfo->getTypeLoc()); | |||
5695 | return FixedTInfo; | |||
5696 | } | |||
5697 | ||||
5698 | /// Register the given locally-scoped extern "C" declaration so | |||
5699 | /// that it can be found later for redeclarations. We include any extern "C" | |||
5700 | /// declaration that is not visible in the translation unit here, not just | |||
5701 | /// function-scope declarations. | |||
5702 | void | |||
5703 | Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { | |||
5704 | if (!getLangOpts().CPlusPlus && | |||
5705 | ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) | |||
5706 | // Don't need to track declarations in the TU in C. | |||
5707 | return; | |||
5708 | ||||
5709 | // Note that we have a locally-scoped external with this name. | |||
5710 | Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); | |||
5711 | } | |||
5712 | ||||
5713 | NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { | |||
5714 | // FIXME: We can have multiple results via __attribute__((overloadable)). | |||
5715 | auto Result = Context.getExternCContextDecl()->lookup(Name); | |||
5716 | return Result.empty() ? nullptr : *Result.begin(); | |||
5717 | } | |||
5718 | ||||
5719 | /// Diagnose function specifiers on a declaration of an identifier that | |||
5720 | /// does not identify a function. | |||
5721 | void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { | |||
5722 | // FIXME: We should probably indicate the identifier in question to avoid | |||
5723 | // confusion for constructs like "virtual int a(), b;" | |||
5724 | if (DS.isVirtualSpecified()) | |||
5725 | Diag(DS.getVirtualSpecLoc(), | |||
5726 | diag::err_virtual_non_function); | |||
5727 | ||||
5728 | if (DS.hasExplicitSpecifier()) | |||
5729 | Diag(DS.getExplicitSpecLoc(), | |||
5730 | diag::err_explicit_non_function); | |||
5731 | ||||
5732 | if (DS.isNoreturnSpecified()) | |||
5733 | Diag(DS.getNoreturnSpecLoc(), | |||
5734 | diag::err_noreturn_non_function); | |||
5735 | } | |||
5736 | ||||
5737 | NamedDecl* | |||
5738 | Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, | |||
5739 | TypeSourceInfo *TInfo, LookupResult &Previous) { | |||
5740 | // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). | |||
5741 | if (D.getCXXScopeSpec().isSet()) { | |||
5742 | Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) | |||
5743 | << D.getCXXScopeSpec().getRange(); | |||
5744 | D.setInvalidType(); | |||
5745 | // Pretend we didn't see the scope specifier. | |||
5746 | DC = CurContext; | |||
5747 | Previous.clear(); | |||
5748 | } | |||
5749 | ||||
5750 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
5751 | ||||
5752 | if (D.getDeclSpec().isInlineSpecified()) | |||
5753 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
5754 | << getLangOpts().CPlusPlus17; | |||
5755 | if (D.getDeclSpec().isConstexprSpecified()) | |||
5756 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) | |||
5757 | << 1; | |||
5758 | ||||
5759 | if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { | |||
5760 | if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) | |||
5761 | Diag(D.getName().StartLocation, | |||
5762 | diag::err_deduction_guide_invalid_specifier) | |||
5763 | << "typedef"; | |||
5764 | else | |||
5765 | Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) | |||
5766 | << D.getName().getSourceRange(); | |||
5767 | return nullptr; | |||
5768 | } | |||
5769 | ||||
5770 | TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); | |||
5771 | if (!NewTD) return nullptr; | |||
5772 | ||||
5773 | // Handle attributes prior to checking for duplicates in MergeVarDecl | |||
5774 | ProcessDeclAttributes(S, NewTD, D); | |||
5775 | ||||
5776 | CheckTypedefForVariablyModifiedType(S, NewTD); | |||
5777 | ||||
5778 | bool Redeclaration = D.isRedeclaration(); | |||
5779 | NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); | |||
5780 | D.setRedeclaration(Redeclaration); | |||
5781 | return ND; | |||
5782 | } | |||
5783 | ||||
5784 | void | |||
5785 | Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { | |||
5786 | // C99 6.7.7p2: If a typedef name specifies a variably modified type | |||
5787 | // then it shall have block scope. | |||
5788 | // Note that variably modified types must be fixed before merging the decl so | |||
5789 | // that redeclarations will match. | |||
5790 | TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); | |||
5791 | QualType T = TInfo->getType(); | |||
5792 | if (T->isVariablyModifiedType()) { | |||
5793 | setFunctionHasBranchProtectedScope(); | |||
5794 | ||||
5795 | if (S->getFnParent() == nullptr) { | |||
5796 | bool SizeIsNegative; | |||
5797 | llvm::APSInt Oversized; | |||
5798 | TypeSourceInfo *FixedTInfo = | |||
5799 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | |||
5800 | SizeIsNegative, | |||
5801 | Oversized); | |||
5802 | if (FixedTInfo) { | |||
5803 | Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); | |||
5804 | NewTD->setTypeSourceInfo(FixedTInfo); | |||
5805 | } else { | |||
5806 | if (SizeIsNegative) | |||
5807 | Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); | |||
5808 | else if (T->isVariableArrayType()) | |||
5809 | Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); | |||
5810 | else if (Oversized.getBoolValue()) | |||
5811 | Diag(NewTD->getLocation(), diag::err_array_too_large) | |||
5812 | << Oversized.toString(10); | |||
5813 | else | |||
5814 | Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); | |||
5815 | NewTD->setInvalidDecl(); | |||
5816 | } | |||
5817 | } | |||
5818 | } | |||
5819 | } | |||
5820 | ||||
5821 | /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which | |||
5822 | /// declares a typedef-name, either using the 'typedef' type specifier or via | |||
5823 | /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. | |||
5824 | NamedDecl* | |||
5825 | Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, | |||
5826 | LookupResult &Previous, bool &Redeclaration) { | |||
5827 | ||||
5828 | // Find the shadowed declaration before filtering for scope. | |||
5829 | NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); | |||
5830 | ||||
5831 | // Merge the decl with the existing one if appropriate. If the decl is | |||
5832 | // in an outer scope, it isn't the same thing. | |||
5833 | FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, | |||
5834 | /*AllowInlineNamespace*/false); | |||
5835 | filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); | |||
5836 | if (!Previous.empty()) { | |||
5837 | Redeclaration = true; | |||
5838 | MergeTypedefNameDecl(S, NewTD, Previous); | |||
5839 | } | |||
5840 | ||||
5841 | if (ShadowedDecl && !Redeclaration) | |||
5842 | CheckShadow(NewTD, ShadowedDecl, Previous); | |||
5843 | ||||
5844 | // If this is the C FILE type, notify the AST context. | |||
5845 | if (IdentifierInfo *II = NewTD->getIdentifier()) | |||
5846 | if (!NewTD->isInvalidDecl() && | |||
5847 | NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | |||
5848 | if (II->isStr("FILE")) | |||
5849 | Context.setFILEDecl(NewTD); | |||
5850 | else if (II->isStr("jmp_buf")) | |||
5851 | Context.setjmp_bufDecl(NewTD); | |||
5852 | else if (II->isStr("sigjmp_buf")) | |||
5853 | Context.setsigjmp_bufDecl(NewTD); | |||
5854 | else if (II->isStr("ucontext_t")) | |||
5855 | Context.setucontext_tDecl(NewTD); | |||
5856 | } | |||
5857 | ||||
5858 | return NewTD; | |||
5859 | } | |||
5860 | ||||
5861 | /// Determines whether the given declaration is an out-of-scope | |||
5862 | /// previous declaration. | |||
5863 | /// | |||
5864 | /// This routine should be invoked when name lookup has found a | |||
5865 | /// previous declaration (PrevDecl) that is not in the scope where a | |||
5866 | /// new declaration by the same name is being introduced. If the new | |||
5867 | /// declaration occurs in a local scope, previous declarations with | |||
5868 | /// linkage may still be considered previous declarations (C99 | |||
5869 | /// 6.2.2p4-5, C++ [basic.link]p6). | |||
5870 | /// | |||
5871 | /// \param PrevDecl the previous declaration found by name | |||
5872 | /// lookup | |||
5873 | /// | |||
5874 | /// \param DC the context in which the new declaration is being | |||
5875 | /// declared. | |||
5876 | /// | |||
5877 | /// \returns true if PrevDecl is an out-of-scope previous declaration | |||
5878 | /// for a new delcaration with the same name. | |||
5879 | static bool | |||
5880 | isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, | |||
5881 | ASTContext &Context) { | |||
5882 | if (!PrevDecl) | |||
5883 | return false; | |||
5884 | ||||
5885 | if (!PrevDecl->hasLinkage()) | |||
5886 | return false; | |||
5887 | ||||
5888 | if (Context.getLangOpts().CPlusPlus) { | |||
5889 | // C++ [basic.link]p6: | |||
5890 | // If there is a visible declaration of an entity with linkage | |||
5891 | // having the same name and type, ignoring entities declared | |||
5892 | // outside the innermost enclosing namespace scope, the block | |||
5893 | // scope declaration declares that same entity and receives the | |||
5894 | // linkage of the previous declaration. | |||
5895 | DeclContext *OuterContext = DC->getRedeclContext(); | |||
5896 | if (!OuterContext->isFunctionOrMethod()) | |||
5897 | // This rule only applies to block-scope declarations. | |||
5898 | return false; | |||
5899 | ||||
5900 | DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); | |||
5901 | if (PrevOuterContext->isRecord()) | |||
5902 | // We found a member function: ignore it. | |||
5903 | return false; | |||
5904 | ||||
5905 | // Find the innermost enclosing namespace for the new and | |||
5906 | // previous declarations. | |||
5907 | OuterContext = OuterContext->getEnclosingNamespaceContext(); | |||
5908 | PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); | |||
5909 | ||||
5910 | // The previous declaration is in a different namespace, so it | |||
5911 | // isn't the same function. | |||
5912 | if (!OuterContext->Equals(PrevOuterContext)) | |||
5913 | return false; | |||
5914 | } | |||
5915 | ||||
5916 | return true; | |||
5917 | } | |||
5918 | ||||
5919 | static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { | |||
5920 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | |||
5921 | if (!SS.isSet()) return; | |||
5922 | DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); | |||
5923 | } | |||
5924 | ||||
5925 | bool Sema::inferObjCARCLifetime(ValueDecl *decl) { | |||
5926 | QualType type = decl->getType(); | |||
5927 | Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); | |||
5928 | if (lifetime == Qualifiers::OCL_Autoreleasing) { | |||
5929 | // Various kinds of declaration aren't allowed to be __autoreleasing. | |||
5930 | unsigned kind = -1U; | |||
5931 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | |||
5932 | if (var->hasAttr<BlocksAttr>()) | |||
5933 | kind = 0; // __block | |||
5934 | else if (!var->hasLocalStorage()) | |||
5935 | kind = 1; // global | |||
5936 | } else if (isa<ObjCIvarDecl>(decl)) { | |||
5937 | kind = 3; // ivar | |||
5938 | } else if (isa<FieldDecl>(decl)) { | |||
5939 | kind = 2; // field | |||
5940 | } | |||
5941 | ||||
5942 | if (kind != -1U) { | |||
5943 | Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) | |||
5944 | << kind; | |||
5945 | } | |||
5946 | } else if (lifetime == Qualifiers::OCL_None) { | |||
5947 | // Try to infer lifetime. | |||
5948 | if (!type->isObjCLifetimeType()) | |||
5949 | return false; | |||
5950 | ||||
5951 | lifetime = type->getObjCARCImplicitLifetime(); | |||
5952 | type = Context.getLifetimeQualifiedType(type, lifetime); | |||
5953 | decl->setType(type); | |||
5954 | } | |||
5955 | ||||
5956 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | |||
5957 | // Thread-local variables cannot have lifetime. | |||
5958 | if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && | |||
5959 | var->getTLSKind()) { | |||
5960 | Diag(var->getLocation(), diag::err_arc_thread_ownership) | |||
5961 | << var->getType(); | |||
5962 | return true; | |||
5963 | } | |||
5964 | } | |||
5965 | ||||
5966 | return false; | |||
5967 | } | |||
5968 | ||||
5969 | static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { | |||
5970 | // Ensure that an auto decl is deduced otherwise the checks below might cache | |||
5971 | // the wrong linkage. | |||
5972 | assert(S.ParsingInitForAutoVars.count(&ND) == 0)((S.ParsingInitForAutoVars.count(&ND) == 0) ? static_cast <void> (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 5972, __PRETTY_FUNCTION__)); | |||
5973 | ||||
5974 | // 'weak' only applies to declarations with external linkage. | |||
5975 | if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { | |||
5976 | if (!ND.isExternallyVisible()) { | |||
5977 | S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); | |||
5978 | ND.dropAttr<WeakAttr>(); | |||
5979 | } | |||
5980 | } | |||
5981 | if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { | |||
5982 | if (ND.isExternallyVisible()) { | |||
5983 | S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); | |||
5984 | ND.dropAttr<WeakRefAttr>(); | |||
5985 | ND.dropAttr<AliasAttr>(); | |||
5986 | } | |||
5987 | } | |||
5988 | ||||
5989 | if (auto *VD = dyn_cast<VarDecl>(&ND)) { | |||
5990 | if (VD->hasInit()) { | |||
5991 | if (const auto *Attr = VD->getAttr<AliasAttr>()) { | |||
5992 | assert(VD->isThisDeclarationADefinition() &&((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible () && "Broken AliasAttr handled late!") ? static_cast <void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 5993, __PRETTY_FUNCTION__)) | |||
5993 | !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible () && "Broken AliasAttr handled late!") ? static_cast <void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 5993, __PRETTY_FUNCTION__)); | |||
5994 | S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; | |||
5995 | VD->dropAttr<AliasAttr>(); | |||
5996 | } | |||
5997 | } | |||
5998 | } | |||
5999 | ||||
6000 | // 'selectany' only applies to externally visible variable declarations. | |||
6001 | // It does not apply to functions. | |||
6002 | if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { | |||
6003 | if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { | |||
6004 | S.Diag(Attr->getLocation(), | |||
6005 | diag::err_attribute_selectany_non_extern_data); | |||
6006 | ND.dropAttr<SelectAnyAttr>(); | |||
6007 | } | |||
6008 | } | |||
6009 | ||||
6010 | if (const InheritableAttr *Attr = getDLLAttr(&ND)) { | |||
6011 | auto *VD = dyn_cast<VarDecl>(&ND); | |||
6012 | bool IsAnonymousNS = false; | |||
6013 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | |||
6014 | if (VD) { | |||
6015 | const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); | |||
6016 | while (NS && !IsAnonymousNS) { | |||
6017 | IsAnonymousNS = NS->isAnonymousNamespace(); | |||
6018 | NS = dyn_cast<NamespaceDecl>(NS->getParent()); | |||
6019 | } | |||
6020 | } | |||
6021 | // dll attributes require external linkage. Static locals may have external | |||
6022 | // linkage but still cannot be explicitly imported or exported. | |||
6023 | // In Microsoft mode, a variable defined in anonymous namespace must have | |||
6024 | // external linkage in order to be exported. | |||
6025 | bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; | |||
6026 | if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || | |||
6027 | (!AnonNSInMicrosoftMode && | |||
6028 | (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { | |||
6029 | S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) | |||
6030 | << &ND << Attr; | |||
6031 | ND.setInvalidDecl(); | |||
6032 | } | |||
6033 | } | |||
6034 | ||||
6035 | // Virtual functions cannot be marked as 'notail'. | |||
6036 | if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) | |||
6037 | if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) | |||
6038 | if (MD->isVirtual()) { | |||
6039 | S.Diag(ND.getLocation(), | |||
6040 | diag::err_invalid_attribute_on_virtual_function) | |||
6041 | << Attr; | |||
6042 | ND.dropAttr<NotTailCalledAttr>(); | |||
6043 | } | |||
6044 | ||||
6045 | // Check the attributes on the function type, if any. | |||
6046 | if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { | |||
6047 | // Don't declare this variable in the second operand of the for-statement; | |||
6048 | // GCC miscompiles that by ending its lifetime before evaluating the | |||
6049 | // third operand. See gcc.gnu.org/PR86769. | |||
6050 | AttributedTypeLoc ATL; | |||
6051 | for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); | |||
6052 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | |||
6053 | TL = ATL.getModifiedLoc()) { | |||
6054 | // The [[lifetimebound]] attribute can be applied to the implicit object | |||
6055 | // parameter of a non-static member function (other than a ctor or dtor) | |||
6056 | // by applying it to the function type. | |||
6057 | if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { | |||
6058 | const auto *MD = dyn_cast<CXXMethodDecl>(FD); | |||
6059 | if (!MD || MD->isStatic()) { | |||
6060 | S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) | |||
6061 | << !MD << A->getRange(); | |||
6062 | } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { | |||
6063 | S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) | |||
6064 | << isa<CXXDestructorDecl>(MD) << A->getRange(); | |||
6065 | } | |||
6066 | } | |||
6067 | } | |||
6068 | } | |||
6069 | } | |||
6070 | ||||
6071 | static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, | |||
6072 | NamedDecl *NewDecl, | |||
6073 | bool IsSpecialization, | |||
6074 | bool IsDefinition) { | |||
6075 | if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) | |||
6076 | return; | |||
6077 | ||||
6078 | bool IsTemplate = false; | |||
6079 | if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { | |||
6080 | OldDecl = OldTD->getTemplatedDecl(); | |||
6081 | IsTemplate = true; | |||
6082 | if (!IsSpecialization) | |||
6083 | IsDefinition = false; | |||
6084 | } | |||
6085 | if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { | |||
6086 | NewDecl = NewTD->getTemplatedDecl(); | |||
6087 | IsTemplate = true; | |||
6088 | } | |||
6089 | ||||
6090 | if (!OldDecl || !NewDecl) | |||
6091 | return; | |||
6092 | ||||
6093 | const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); | |||
6094 | const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); | |||
6095 | const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); | |||
6096 | const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); | |||
6097 | ||||
6098 | // dllimport and dllexport are inheritable attributes so we have to exclude | |||
6099 | // inherited attribute instances. | |||
6100 | bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || | |||
6101 | (NewExportAttr && !NewExportAttr->isInherited()); | |||
6102 | ||||
6103 | // A redeclaration is not allowed to add a dllimport or dllexport attribute, | |||
6104 | // the only exception being explicit specializations. | |||
6105 | // Implicitly generated declarations are also excluded for now because there | |||
6106 | // is no other way to switch these to use dllimport or dllexport. | |||
6107 | bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; | |||
6108 | ||||
6109 | if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { | |||
6110 | // Allow with a warning for free functions and global variables. | |||
6111 | bool JustWarn = false; | |||
6112 | if (!OldDecl->isCXXClassMember()) { | |||
6113 | auto *VD = dyn_cast<VarDecl>(OldDecl); | |||
6114 | if (VD && !VD->getDescribedVarTemplate()) | |||
6115 | JustWarn = true; | |||
6116 | auto *FD = dyn_cast<FunctionDecl>(OldDecl); | |||
6117 | if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) | |||
6118 | JustWarn = true; | |||
6119 | } | |||
6120 | ||||
6121 | // We cannot change a declaration that's been used because IR has already | |||
6122 | // been emitted. Dllimported functions will still work though (modulo | |||
6123 | // address equality) as they can use the thunk. | |||
6124 | if (OldDecl->isUsed()) | |||
6125 | if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) | |||
6126 | JustWarn = false; | |||
6127 | ||||
6128 | unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration | |||
6129 | : diag::err_attribute_dll_redeclaration; | |||
6130 | S.Diag(NewDecl->getLocation(), DiagID) | |||
6131 | << NewDecl | |||
6132 | << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); | |||
6133 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | |||
6134 | if (!JustWarn) { | |||
6135 | NewDecl->setInvalidDecl(); | |||
6136 | return; | |||
6137 | } | |||
6138 | } | |||
6139 | ||||
6140 | // A redeclaration is not allowed to drop a dllimport attribute, the only | |||
6141 | // exceptions being inline function definitions (except for function | |||
6142 | // templates), local extern declarations, qualified friend declarations or | |||
6143 | // special MSVC extension: in the last case, the declaration is treated as if | |||
6144 | // it were marked dllexport. | |||
6145 | bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; | |||
6146 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | |||
6147 | if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { | |||
6148 | // Ignore static data because out-of-line definitions are diagnosed | |||
6149 | // separately. | |||
6150 | IsStaticDataMember = VD->isStaticDataMember(); | |||
6151 | IsDefinition = VD->isThisDeclarationADefinition(S.Context) != | |||
6152 | VarDecl::DeclarationOnly; | |||
6153 | } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { | |||
6154 | IsInline = FD->isInlined(); | |||
6155 | IsQualifiedFriend = FD->getQualifier() && | |||
6156 | FD->getFriendObjectKind() == Decl::FOK_Declared; | |||
6157 | } | |||
6158 | ||||
6159 | if (OldImportAttr && !HasNewAttr && | |||
6160 | (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && | |||
6161 | !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { | |||
6162 | if (IsMicrosoft && IsDefinition) { | |||
6163 | S.Diag(NewDecl->getLocation(), | |||
6164 | diag::warn_redeclaration_without_import_attribute) | |||
6165 | << NewDecl; | |||
6166 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | |||
6167 | NewDecl->dropAttr<DLLImportAttr>(); | |||
6168 | NewDecl->addAttr(::new (S.Context) DLLExportAttr( | |||
6169 | NewImportAttr->getRange(), S.Context, | |||
6170 | NewImportAttr->getSpellingListIndex())); | |||
6171 | } else { | |||
6172 | S.Diag(NewDecl->getLocation(), | |||
6173 | diag::warn_redeclaration_without_attribute_prev_attribute_ignored) | |||
6174 | << NewDecl << OldImportAttr; | |||
6175 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | |||
6176 | S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); | |||
6177 | OldDecl->dropAttr<DLLImportAttr>(); | |||
6178 | NewDecl->dropAttr<DLLImportAttr>(); | |||
6179 | } | |||
6180 | } else if (IsInline && OldImportAttr && !IsMicrosoft) { | |||
6181 | // In MinGW, seeing a function declared inline drops the dllimport | |||
6182 | // attribute. | |||
6183 | OldDecl->dropAttr<DLLImportAttr>(); | |||
6184 | NewDecl->dropAttr<DLLImportAttr>(); | |||
6185 | S.Diag(NewDecl->getLocation(), | |||
6186 | diag::warn_dllimport_dropped_from_inline_function) | |||
6187 | << NewDecl << OldImportAttr; | |||
6188 | } | |||
6189 | ||||
6190 | // A specialization of a class template member function is processed here | |||
6191 | // since it's a redeclaration. If the parent class is dllexport, the | |||
6192 | // specialization inherits that attribute. This doesn't happen automatically | |||
6193 | // since the parent class isn't instantiated until later. | |||
6194 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { | |||
6195 | if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && | |||
6196 | !NewImportAttr && !NewExportAttr) { | |||
6197 | if (const DLLExportAttr *ParentExportAttr = | |||
6198 | MD->getParent()->getAttr<DLLExportAttr>()) { | |||
6199 | DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); | |||
6200 | NewAttr->setInherited(true); | |||
6201 | NewDecl->addAttr(NewAttr); | |||
6202 | } | |||
6203 | } | |||
6204 | } | |||
6205 | } | |||
6206 | ||||
6207 | /// Given that we are within the definition of the given function, | |||
6208 | /// will that definition behave like C99's 'inline', where the | |||
6209 | /// definition is discarded except for optimization purposes? | |||
6210 | static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { | |||
6211 | // Try to avoid calling GetGVALinkageForFunction. | |||
6212 | ||||
6213 | // All cases of this require the 'inline' keyword. | |||
6214 | if (!FD->isInlined()) return false; | |||
6215 | ||||
6216 | // This is only possible in C++ with the gnu_inline attribute. | |||
6217 | if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) | |||
6218 | return false; | |||
6219 | ||||
6220 | // Okay, go ahead and call the relatively-more-expensive function. | |||
6221 | return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; | |||
6222 | } | |||
6223 | ||||
6224 | /// Determine whether a variable is extern "C" prior to attaching | |||
6225 | /// an initializer. We can't just call isExternC() here, because that | |||
6226 | /// will also compute and cache whether the declaration is externally | |||
6227 | /// visible, which might change when we attach the initializer. | |||
6228 | /// | |||
6229 | /// This can only be used if the declaration is known to not be a | |||
6230 | /// redeclaration of an internal linkage declaration. | |||
6231 | /// | |||
6232 | /// For instance: | |||
6233 | /// | |||
6234 | /// auto x = []{}; | |||
6235 | /// | |||
6236 | /// Attaching the initializer here makes this declaration not externally | |||
6237 | /// visible, because its type has internal linkage. | |||
6238 | /// | |||
6239 | /// FIXME: This is a hack. | |||
6240 | template<typename T> | |||
6241 | static bool isIncompleteDeclExternC(Sema &S, const T *D) { | |||
6242 | if (S.getLangOpts().CPlusPlus) { | |||
6243 | // In C++, the overloadable attribute negates the effects of extern "C". | |||
6244 | if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) | |||
6245 | return false; | |||
6246 | ||||
6247 | // So do CUDA's host/device attributes. | |||
6248 | if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || | |||
6249 | D->template hasAttr<CUDAHostAttr>())) | |||
6250 | return false; | |||
6251 | } | |||
6252 | return D->isExternC(); | |||
6253 | } | |||
6254 | ||||
6255 | static bool shouldConsiderLinkage(const VarDecl *VD) { | |||
6256 | const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); | |||
6257 | if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || | |||
6258 | isa<OMPDeclareMapperDecl>(DC)) | |||
6259 | return VD->hasExternalStorage(); | |||
6260 | if (DC->isFileContext()) | |||
6261 | return true; | |||
6262 | if (DC->isRecord()) | |||
6263 | return false; | |||
6264 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 6264); | |||
6265 | } | |||
6266 | ||||
6267 | static bool shouldConsiderLinkage(const FunctionDecl *FD) { | |||
6268 | const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); | |||
6269 | if (DC->isFileContext() || DC->isFunctionOrMethod() || | |||
6270 | isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) | |||
6271 | return true; | |||
6272 | if (DC->isRecord()) | |||
6273 | return false; | |||
6274 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 6274); | |||
6275 | } | |||
6276 | ||||
6277 | static bool hasParsedAttr(Scope *S, const Declarator &PD, | |||
6278 | ParsedAttr::Kind Kind) { | |||
6279 | // Check decl attributes on the DeclSpec. | |||
6280 | if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) | |||
6281 | return true; | |||
6282 | ||||
6283 | // Walk the declarator structure, checking decl attributes that were in a type | |||
6284 | // position to the decl itself. | |||
6285 | for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { | |||
6286 | if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) | |||
6287 | return true; | |||
6288 | } | |||
6289 | ||||
6290 | // Finally, check attributes on the decl itself. | |||
6291 | return PD.getAttributes().hasAttribute(Kind); | |||
6292 | } | |||
6293 | ||||
6294 | /// Adjust the \c DeclContext for a function or variable that might be a | |||
6295 | /// function-local external declaration. | |||
6296 | bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { | |||
6297 | if (!DC->isFunctionOrMethod()) | |||
6298 | return false; | |||
6299 | ||||
6300 | // If this is a local extern function or variable declared within a function | |||
6301 | // template, don't add it into the enclosing namespace scope until it is | |||
6302 | // instantiated; it might have a dependent type right now. | |||
6303 | if (DC->isDependentContext()) | |||
6304 | return true; | |||
6305 | ||||
6306 | // C++11 [basic.link]p7: | |||
6307 | // When a block scope declaration of an entity with linkage is not found to | |||
6308 | // refer to some other declaration, then that entity is a member of the | |||
6309 | // innermost enclosing namespace. | |||
6310 | // | |||
6311 | // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a | |||
6312 | // semantically-enclosing namespace, not a lexically-enclosing one. | |||
6313 | while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) | |||
6314 | DC = DC->getParent(); | |||
6315 | return true; | |||
6316 | } | |||
6317 | ||||
6318 | /// Returns true if given declaration has external C language linkage. | |||
6319 | static bool isDeclExternC(const Decl *D) { | |||
6320 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) | |||
6321 | return FD->isExternC(); | |||
6322 | if (const auto *VD = dyn_cast<VarDecl>(D)) | |||
6323 | return VD->isExternC(); | |||
6324 | ||||
6325 | llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 6325); | |||
6326 | } | |||
6327 | ||||
6328 | NamedDecl *Sema::ActOnVariableDeclarator( | |||
6329 | Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, | |||
6330 | LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, | |||
6331 | bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { | |||
6332 | QualType R = TInfo->getType(); | |||
6333 | DeclarationName Name = GetNameForDeclarator(D).getName(); | |||
6334 | ||||
6335 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
6336 | ||||
6337 | if (D.isDecompositionDeclarator()) { | |||
6338 | // Take the name of the first declarator as our name for diagnostic | |||
6339 | // purposes. | |||
6340 | auto &Decomp = D.getDecompositionDeclarator(); | |||
6341 | if (!Decomp.bindings().empty()) { | |||
6342 | II = Decomp.bindings()[0].Name; | |||
6343 | Name = II; | |||
6344 | } | |||
6345 | } else if (!II) { | |||
6346 | Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; | |||
6347 | return nullptr; | |||
6348 | } | |||
6349 | ||||
6350 | if (getLangOpts().OpenCL) { | |||
6351 | // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. | |||
6352 | // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function | |||
6353 | // argument. | |||
6354 | if (R->isImageType() || R->isPipeType()) { | |||
6355 | Diag(D.getIdentifierLoc(), | |||
6356 | diag::err_opencl_type_can_only_be_used_as_function_parameter) | |||
6357 | << R; | |||
6358 | D.setInvalidType(); | |||
6359 | return nullptr; | |||
6360 | } | |||
6361 | ||||
6362 | // OpenCL v1.2 s6.9.r: | |||
6363 | // The event type cannot be used to declare a program scope variable. | |||
6364 | // OpenCL v2.0 s6.9.q: | |||
6365 | // The clk_event_t and reserve_id_t types cannot be declared in program scope. | |||
6366 | if (NULL__null == S->getParent()) { | |||
6367 | if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { | |||
6368 | Diag(D.getIdentifierLoc(), | |||
6369 | diag::err_invalid_type_for_program_scope_var) << R; | |||
6370 | D.setInvalidType(); | |||
6371 | return nullptr; | |||
6372 | } | |||
6373 | } | |||
6374 | ||||
6375 | // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. | |||
6376 | QualType NR = R; | |||
6377 | while (NR->isPointerType()) { | |||
6378 | if (NR->isFunctionPointerType()) { | |||
6379 | Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); | |||
6380 | D.setInvalidType(); | |||
6381 | break; | |||
6382 | } | |||
6383 | NR = NR->getPointeeType(); | |||
6384 | } | |||
6385 | ||||
6386 | if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { | |||
6387 | // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and | |||
6388 | // half array type (unless the cl_khr_fp16 extension is enabled). | |||
6389 | if (Context.getBaseElementType(R)->isHalfType()) { | |||
6390 | Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; | |||
6391 | D.setInvalidType(); | |||
6392 | } | |||
6393 | } | |||
6394 | ||||
6395 | if (R->isSamplerT()) { | |||
6396 | // OpenCL v1.2 s6.9.b p4: | |||
6397 | // The sampler type cannot be used with the __local and __global address | |||
6398 | // space qualifiers. | |||
6399 | if (R.getAddressSpace() == LangAS::opencl_local || | |||
6400 | R.getAddressSpace() == LangAS::opencl_global) { | |||
6401 | Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); | |||
6402 | } | |||
6403 | ||||
6404 | // OpenCL v1.2 s6.12.14.1: | |||
6405 | // A global sampler must be declared with either the constant address | |||
6406 | // space qualifier or with the const qualifier. | |||
6407 | if (DC->isTranslationUnit() && | |||
6408 | !(R.getAddressSpace() == LangAS::opencl_constant || | |||
6409 | R.isConstQualified())) { | |||
6410 | Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); | |||
6411 | D.setInvalidType(); | |||
6412 | } | |||
6413 | } | |||
6414 | ||||
6415 | // OpenCL v1.2 s6.9.r: | |||
6416 | // The event type cannot be used with the __local, __constant and __global | |||
6417 | // address space qualifiers. | |||
6418 | if (R->isEventT()) { | |||
6419 | if (R.getAddressSpace() != LangAS::opencl_private) { | |||
6420 | Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); | |||
6421 | D.setInvalidType(); | |||
6422 | } | |||
6423 | } | |||
6424 | ||||
6425 | // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not | |||
6426 | // supported. OpenCL C does not support thread_local either, and | |||
6427 | // also reject all other thread storage class specifiers. | |||
6428 | DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); | |||
6429 | if (TSC != TSCS_unspecified) { | |||
6430 | bool IsCXX = getLangOpts().OpenCLCPlusPlus; | |||
6431 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
6432 | diag::err_opencl_unknown_type_specifier) | |||
6433 | << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() | |||
6434 | << DeclSpec::getSpecifierName(TSC) << 1; | |||
6435 | D.setInvalidType(); | |||
6436 | return nullptr; | |||
6437 | } | |||
6438 | } | |||
6439 | ||||
6440 | DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); | |||
6441 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); | |||
6442 | ||||
6443 | // dllimport globals without explicit storage class are treated as extern. We | |||
6444 | // have to change the storage class this early to get the right DeclContext. | |||
6445 | if (SC == SC_None && !DC->isRecord() && | |||
6446 | hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && | |||
6447 | !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) | |||
6448 | SC = SC_Extern; | |||
6449 | ||||
6450 | DeclContext *OriginalDC = DC; | |||
6451 | bool IsLocalExternDecl = SC == SC_Extern && | |||
6452 | adjustContextForLocalExternDecl(DC); | |||
6453 | ||||
6454 | if (SCSpec == DeclSpec::SCS_mutable) { | |||
6455 | // mutable can only appear on non-static class members, so it's always | |||
6456 | // an error here | |||
6457 | Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); | |||
6458 | D.setInvalidType(); | |||
6459 | SC = SC_None; | |||
6460 | } | |||
6461 | ||||
6462 | if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && | |||
6463 | !D.getAsmLabel() && !getSourceManager().isInSystemMacro( | |||
6464 | D.getDeclSpec().getStorageClassSpecLoc())) { | |||
6465 | // In C++11, the 'register' storage class specifier is deprecated. | |||
6466 | // Suppress the warning in system macros, it's used in macros in some | |||
6467 | // popular C system headers, such as in glibc's htonl() macro. | |||
6468 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
6469 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | |||
6470 | : diag::warn_deprecated_register) | |||
6471 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
6472 | } | |||
6473 | ||||
6474 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
6475 | ||||
6476 | if (!DC->isRecord() && S->getFnParent() == nullptr) { | |||
6477 | // C99 6.9p2: The storage-class specifiers auto and register shall not | |||
6478 | // appear in the declaration specifiers in an external declaration. | |||
6479 | // Global Register+Asm is a GNU extension we support. | |||
6480 | if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { | |||
6481 | Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); | |||
6482 | D.setInvalidType(); | |||
6483 | } | |||
6484 | } | |||
6485 | ||||
6486 | bool IsMemberSpecialization = false; | |||
6487 | bool IsVariableTemplateSpecialization = false; | |||
6488 | bool IsPartialSpecialization = false; | |||
6489 | bool IsVariableTemplate = false; | |||
6490 | VarDecl *NewVD = nullptr; | |||
6491 | VarTemplateDecl *NewTemplate = nullptr; | |||
6492 | TemplateParameterList *TemplateParams = nullptr; | |||
6493 | if (!getLangOpts().CPlusPlus) { | |||
6494 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), | |||
6495 | II, R, TInfo, SC); | |||
6496 | ||||
6497 | if (R->getContainedDeducedType()) | |||
6498 | ParsingInitForAutoVars.insert(NewVD); | |||
6499 | ||||
6500 | if (D.isInvalidType()) | |||
6501 | NewVD->setInvalidDecl(); | |||
6502 | } else { | |||
6503 | bool Invalid = false; | |||
6504 | ||||
6505 | if (DC->isRecord() && !CurContext->isRecord()) { | |||
6506 | // This is an out-of-line definition of a static data member. | |||
6507 | switch (SC) { | |||
6508 | case SC_None: | |||
6509 | break; | |||
6510 | case SC_Static: | |||
6511 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
6512 | diag::err_static_out_of_line) | |||
6513 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
6514 | break; | |||
6515 | case SC_Auto: | |||
6516 | case SC_Register: | |||
6517 | case SC_Extern: | |||
6518 | // [dcl.stc] p2: The auto or register specifiers shall be applied only | |||
6519 | // to names of variables declared in a block or to function parameters. | |||
6520 | // [dcl.stc] p6: The extern specifier cannot be used in the declaration | |||
6521 | // of class members | |||
6522 | ||||
6523 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
6524 | diag::err_storage_class_for_static_member) | |||
6525 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
6526 | break; | |||
6527 | case SC_PrivateExtern: | |||
6528 | llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 6528); | |||
6529 | } | |||
6530 | } | |||
6531 | ||||
6532 | if (SC == SC_Static && CurContext->isRecord()) { | |||
6533 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { | |||
6534 | if (RD->isLocalClass()) | |||
6535 | Diag(D.getIdentifierLoc(), | |||
6536 | diag::err_static_data_member_not_allowed_in_local_class) | |||
6537 | << Name << RD->getDeclName(); | |||
6538 | ||||
6539 | // C++98 [class.union]p1: If a union contains a static data member, | |||
6540 | // the program is ill-formed. C++11 drops this restriction. | |||
6541 | if (RD->isUnion()) | |||
6542 | Diag(D.getIdentifierLoc(), | |||
6543 | getLangOpts().CPlusPlus11 | |||
6544 | ? diag::warn_cxx98_compat_static_data_member_in_union | |||
6545 | : diag::ext_static_data_member_in_union) << Name; | |||
6546 | // We conservatively disallow static data members in anonymous structs. | |||
6547 | else if (!RD->getDeclName()) | |||
6548 | Diag(D.getIdentifierLoc(), | |||
6549 | diag::err_static_data_member_not_allowed_in_anon_struct) | |||
6550 | << Name << RD->isUnion(); | |||
6551 | } | |||
6552 | } | |||
6553 | ||||
6554 | // Match up the template parameter lists with the scope specifier, then | |||
6555 | // determine whether we have a template or a template specialization. | |||
6556 | TemplateParams = MatchTemplateParametersToScopeSpecifier( | |||
6557 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | |||
6558 | D.getCXXScopeSpec(), | |||
6559 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | |||
6560 | ? D.getName().TemplateId | |||
6561 | : nullptr, | |||
6562 | TemplateParamLists, | |||
6563 | /*never a friend*/ false, IsMemberSpecialization, Invalid); | |||
6564 | ||||
6565 | if (TemplateParams) { | |||
6566 | if (!TemplateParams->size() && | |||
6567 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | |||
6568 | // There is an extraneous 'template<>' for this variable. Complain | |||
6569 | // about it, but allow the declaration of the variable. | |||
6570 | Diag(TemplateParams->getTemplateLoc(), | |||
6571 | diag::err_template_variable_noparams) | |||
6572 | << II | |||
6573 | << SourceRange(TemplateParams->getTemplateLoc(), | |||
6574 | TemplateParams->getRAngleLoc()); | |||
6575 | TemplateParams = nullptr; | |||
6576 | } else { | |||
6577 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | |||
6578 | // This is an explicit specialization or a partial specialization. | |||
6579 | // FIXME: Check that we can declare a specialization here. | |||
6580 | IsVariableTemplateSpecialization = true; | |||
6581 | IsPartialSpecialization = TemplateParams->size() > 0; | |||
6582 | } else { // if (TemplateParams->size() > 0) | |||
6583 | // This is a template declaration. | |||
6584 | IsVariableTemplate = true; | |||
6585 | ||||
6586 | // Check that we can declare a template here. | |||
6587 | if (CheckTemplateDeclScope(S, TemplateParams)) | |||
6588 | return nullptr; | |||
6589 | ||||
6590 | // Only C++1y supports variable templates (N3651). | |||
6591 | Diag(D.getIdentifierLoc(), | |||
6592 | getLangOpts().CPlusPlus14 | |||
6593 | ? diag::warn_cxx11_compat_variable_template | |||
6594 | : diag::ext_variable_template); | |||
6595 | } | |||
6596 | } | |||
6597 | } else { | |||
6598 | assert((Invalid ||(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 6600, __PRETTY_FUNCTION__)) | |||
6599 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 6600, __PRETTY_FUNCTION__)) | |||
6600 | "should have a 'template<>' for this decl")(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 6600, __PRETTY_FUNCTION__)); | |||
6601 | } | |||
6602 | ||||
6603 | if (IsVariableTemplateSpecialization) { | |||
6604 | SourceLocation TemplateKWLoc = | |||
6605 | TemplateParamLists.size() > 0 | |||
6606 | ? TemplateParamLists[0]->getTemplateLoc() | |||
6607 | : SourceLocation(); | |||
6608 | DeclResult Res = ActOnVarTemplateSpecialization( | |||
6609 | S, D, TInfo, TemplateKWLoc, TemplateParams, SC, | |||
6610 | IsPartialSpecialization); | |||
6611 | if (Res.isInvalid()) | |||
6612 | return nullptr; | |||
6613 | NewVD = cast<VarDecl>(Res.get()); | |||
6614 | AddToScope = false; | |||
6615 | } else if (D.isDecompositionDeclarator()) { | |||
6616 | NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), | |||
6617 | D.getIdentifierLoc(), R, TInfo, SC, | |||
6618 | Bindings); | |||
6619 | } else | |||
6620 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), | |||
6621 | D.getIdentifierLoc(), II, R, TInfo, SC); | |||
6622 | ||||
6623 | // If this is supposed to be a variable template, create it as such. | |||
6624 | if (IsVariableTemplate) { | |||
6625 | NewTemplate = | |||
6626 | VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, | |||
6627 | TemplateParams, NewVD); | |||
6628 | NewVD->setDescribedVarTemplate(NewTemplate); | |||
6629 | } | |||
6630 | ||||
6631 | // If this decl has an auto type in need of deduction, make a note of the | |||
6632 | // Decl so we can diagnose uses of it in its own initializer. | |||
6633 | if (R->getContainedDeducedType()) | |||
6634 | ParsingInitForAutoVars.insert(NewVD); | |||
6635 | ||||
6636 | if (D.isInvalidType() || Invalid) { | |||
6637 | NewVD->setInvalidDecl(); | |||
6638 | if (NewTemplate) | |||
6639 | NewTemplate->setInvalidDecl(); | |||
6640 | } | |||
6641 | ||||
6642 | SetNestedNameSpecifier(*this, NewVD, D); | |||
6643 | ||||
6644 | // If we have any template parameter lists that don't directly belong to | |||
6645 | // the variable (matching the scope specifier), store them. | |||
6646 | unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; | |||
6647 | if (TemplateParamLists.size() > VDTemplateParamLists) | |||
6648 | NewVD->setTemplateParameterListsInfo( | |||
6649 | Context, TemplateParamLists.drop_back(VDTemplateParamLists)); | |||
6650 | ||||
6651 | if (D.getDeclSpec().isConstexprSpecified()) { | |||
6652 | NewVD->setConstexpr(true); | |||
6653 | // C++1z [dcl.spec.constexpr]p1: | |||
6654 | // A static data member declared with the constexpr specifier is | |||
6655 | // implicitly an inline variable. | |||
6656 | if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) | |||
6657 | NewVD->setImplicitlyInline(); | |||
6658 | } | |||
6659 | } | |||
6660 | ||||
6661 | if (D.getDeclSpec().isInlineSpecified()) { | |||
6662 | if (!getLangOpts().CPlusPlus) { | |||
6663 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
6664 | << 0; | |||
6665 | } else if (CurContext->isFunctionOrMethod()) { | |||
6666 | // 'inline' is not allowed on block scope variable declaration. | |||
6667 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
6668 | diag::err_inline_declaration_block_scope) << Name | |||
6669 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | |||
6670 | } else { | |||
6671 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
6672 | getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable | |||
6673 | : diag::ext_inline_variable); | |||
6674 | NewVD->setInlineSpecified(); | |||
6675 | } | |||
6676 | } | |||
6677 | ||||
6678 | // Set the lexical context. If the declarator has a C++ scope specifier, the | |||
6679 | // lexical context will be different from the semantic context. | |||
6680 | NewVD->setLexicalDeclContext(CurContext); | |||
6681 | if (NewTemplate) | |||
6682 | NewTemplate->setLexicalDeclContext(CurContext); | |||
6683 | ||||
6684 | if (IsLocalExternDecl) { | |||
6685 | if (D.isDecompositionDeclarator()) | |||
6686 | for (auto *B : Bindings) | |||
6687 | B->setLocalExternDecl(); | |||
6688 | else | |||
6689 | NewVD->setLocalExternDecl(); | |||
6690 | } | |||
6691 | ||||
6692 | bool EmitTLSUnsupportedError = false; | |||
6693 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { | |||
6694 | // C++11 [dcl.stc]p4: | |||
6695 | // When thread_local is applied to a variable of block scope the | |||
6696 | // storage-class-specifier static is implied if it does not appear | |||
6697 | // explicitly. | |||
6698 | // Core issue: 'static' is not implied if the variable is declared | |||
6699 | // 'extern'. | |||
6700 | if (NewVD->hasLocalStorage() && | |||
6701 | (SCSpec != DeclSpec::SCS_unspecified || | |||
6702 | TSCS != DeclSpec::TSCS_thread_local || | |||
6703 | !DC->isFunctionOrMethod())) | |||
6704 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
6705 | diag::err_thread_non_global) | |||
6706 | << DeclSpec::getSpecifierName(TSCS); | |||
6707 | else if (!Context.getTargetInfo().isTLSSupported()) { | |||
6708 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { | |||
6709 | // Postpone error emission until we've collected attributes required to | |||
6710 | // figure out whether it's a host or device variable and whether the | |||
6711 | // error should be ignored. | |||
6712 | EmitTLSUnsupportedError = true; | |||
6713 | // We still need to mark the variable as TLS so it shows up in AST with | |||
6714 | // proper storage class for other tools to use even if we're not going | |||
6715 | // to emit any code for it. | |||
6716 | NewVD->setTSCSpec(TSCS); | |||
6717 | } else | |||
6718 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
6719 | diag::err_thread_unsupported); | |||
6720 | } else | |||
6721 | NewVD->setTSCSpec(TSCS); | |||
6722 | } | |||
6723 | ||||
6724 | // C99 6.7.4p3 | |||
6725 | // An inline definition of a function with external linkage shall | |||
6726 | // not contain a definition of a modifiable object with static or | |||
6727 | // thread storage duration... | |||
6728 | // We only apply this when the function is required to be defined | |||
6729 | // elsewhere, i.e. when the function is not 'extern inline'. Note | |||
6730 | // that a local variable with thread storage duration still has to | |||
6731 | // be marked 'static'. Also note that it's possible to get these | |||
6732 | // semantics in C++ using __attribute__((gnu_inline)). | |||
6733 | if (SC == SC_Static && S->getFnParent() != nullptr && | |||
6734 | !NewVD->getType().isConstQualified()) { | |||
6735 | FunctionDecl *CurFD = getCurFunctionDecl(); | |||
6736 | if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { | |||
6737 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
6738 | diag::warn_static_local_in_extern_inline); | |||
6739 | MaybeSuggestAddingStaticToDecl(CurFD); | |||
6740 | } | |||
6741 | } | |||
6742 | ||||
6743 | if (D.getDeclSpec().isModulePrivateSpecified()) { | |||
6744 | if (IsVariableTemplateSpecialization) | |||
6745 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | |||
6746 | << (IsPartialSpecialization ? 1 : 0) | |||
6747 | << FixItHint::CreateRemoval( | |||
6748 | D.getDeclSpec().getModulePrivateSpecLoc()); | |||
6749 | else if (IsMemberSpecialization) | |||
6750 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | |||
6751 | << 2 | |||
6752 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | |||
6753 | else if (NewVD->hasLocalStorage()) | |||
6754 | Diag(NewVD->getLocation(), diag::err_module_private_local) | |||
6755 | << 0 << NewVD->getDeclName() | |||
6756 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | |||
6757 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | |||
6758 | else { | |||
6759 | NewVD->setModulePrivate(); | |||
6760 | if (NewTemplate) | |||
6761 | NewTemplate->setModulePrivate(); | |||
6762 | for (auto *B : Bindings) | |||
6763 | B->setModulePrivate(); | |||
6764 | } | |||
6765 | } | |||
6766 | ||||
6767 | // Handle attributes prior to checking for duplicates in MergeVarDecl | |||
6768 | ProcessDeclAttributes(S, NewVD, D); | |||
6769 | ||||
6770 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { | |||
6771 | if (EmitTLSUnsupportedError && | |||
6772 | ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || | |||
6773 | (getLangOpts().OpenMPIsDevice && | |||
6774 | NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) | |||
6775 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
6776 | diag::err_thread_unsupported); | |||
6777 | // CUDA B.2.5: "__shared__ and __constant__ variables have implied static | |||
6778 | // storage [duration]." | |||
6779 | if (SC == SC_None && S->getFnParent() != nullptr && | |||
6780 | (NewVD->hasAttr<CUDASharedAttr>() || | |||
6781 | NewVD->hasAttr<CUDAConstantAttr>())) { | |||
6782 | NewVD->setStorageClass(SC_Static); | |||
6783 | } | |||
6784 | } | |||
6785 | ||||
6786 | // Ensure that dllimport globals without explicit storage class are treated as | |||
6787 | // extern. The storage class is set above using parsed attributes. Now we can | |||
6788 | // check the VarDecl itself. | |||
6789 | assert(!NewVD->hasAttr<DLLImportAttr>() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 6791, __PRETTY_FUNCTION__)) | |||
6790 | NewVD->getAttr<DLLImportAttr>()->isInherited() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 6791, __PRETTY_FUNCTION__)) | |||
6791 | NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 6791, __PRETTY_FUNCTION__)); | |||
6792 | ||||
6793 | // In auto-retain/release, infer strong retension for variables of | |||
6794 | // retainable type. | |||
6795 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) | |||
6796 | NewVD->setInvalidDecl(); | |||
6797 | ||||
6798 | // Handle GNU asm-label extension (encoded as an attribute). | |||
6799 | if (Expr *E = (Expr*)D.getAsmLabel()) { | |||
6800 | // The parser guarantees this is a string. | |||
6801 | StringLiteral *SE = cast<StringLiteral>(E); | |||
6802 | StringRef Label = SE->getString(); | |||
6803 | if (S->getFnParent() != nullptr) { | |||
6804 | switch (SC) { | |||
6805 | case SC_None: | |||
6806 | case SC_Auto: | |||
6807 | Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; | |||
6808 | break; | |||
6809 | case SC_Register: | |||
6810 | // Local Named register | |||
6811 | if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && | |||
6812 | DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) | |||
6813 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | |||
6814 | break; | |||
6815 | case SC_Static: | |||
6816 | case SC_Extern: | |||
6817 | case SC_PrivateExtern: | |||
6818 | break; | |||
6819 | } | |||
6820 | } else if (SC == SC_Register) { | |||
6821 | // Global Named register | |||
6822 | if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { | |||
6823 | const auto &TI = Context.getTargetInfo(); | |||
6824 | bool HasSizeMismatch; | |||
6825 | ||||
6826 | if (!TI.isValidGCCRegisterName(Label)) | |||
6827 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | |||
6828 | else if (!TI.validateGlobalRegisterVariable(Label, | |||
6829 | Context.getTypeSize(R), | |||
6830 | HasSizeMismatch)) | |||
6831 | Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; | |||
6832 | else if (HasSizeMismatch) | |||
6833 | Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; | |||
6834 | } | |||
6835 | ||||
6836 | if (!R->isIntegralType(Context) && !R->isPointerType()) { | |||
6837 | Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); | |||
6838 | NewVD->setInvalidDecl(true); | |||
6839 | } | |||
6840 | } | |||
6841 | ||||
6842 | NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), | |||
6843 | Context, Label, 0)); | |||
6844 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | |||
6845 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | |||
6846 | ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); | |||
6847 | if (I != ExtnameUndeclaredIdentifiers.end()) { | |||
6848 | if (isDeclExternC(NewVD)) { | |||
6849 | NewVD->addAttr(I->second); | |||
6850 | ExtnameUndeclaredIdentifiers.erase(I); | |||
6851 | } else | |||
6852 | Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) | |||
6853 | << /*Variable*/1 << NewVD; | |||
6854 | } | |||
6855 | } | |||
6856 | ||||
6857 | // Find the shadowed declaration before filtering for scope. | |||
6858 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() | |||
6859 | ? getShadowedDeclaration(NewVD, Previous) | |||
6860 | : nullptr; | |||
6861 | ||||
6862 | // Don't consider existing declarations that are in a different | |||
6863 | // scope and are out-of-semantic-context declarations (if the new | |||
6864 | // declaration has linkage). | |||
6865 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), | |||
6866 | D.getCXXScopeSpec().isNotEmpty() || | |||
6867 | IsMemberSpecialization || | |||
6868 | IsVariableTemplateSpecialization); | |||
6869 | ||||
6870 | // Check whether the previous declaration is in the same block scope. This | |||
6871 | // affects whether we merge types with it, per C++11 [dcl.array]p3. | |||
6872 | if (getLangOpts().CPlusPlus && | |||
6873 | NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) | |||
6874 | NewVD->setPreviousDeclInSameBlockScope( | |||
6875 | Previous.isSingleResult() && !Previous.isShadowed() && | |||
6876 | isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); | |||
6877 | ||||
6878 | if (!getLangOpts().CPlusPlus) { | |||
6879 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | |||
6880 | } else { | |||
6881 | // If this is an explicit specialization of a static data member, check it. | |||
6882 | if (IsMemberSpecialization && !NewVD->isInvalidDecl() && | |||
6883 | CheckMemberSpecialization(NewVD, Previous)) | |||
6884 | NewVD->setInvalidDecl(); | |||
6885 | ||||
6886 | // Merge the decl with the existing one if appropriate. | |||
6887 | if (!Previous.empty()) { | |||
6888 | if (Previous.isSingleResult() && | |||
6889 | isa<FieldDecl>(Previous.getFoundDecl()) && | |||
6890 | D.getCXXScopeSpec().isSet()) { | |||
6891 | // The user tried to define a non-static data member | |||
6892 | // out-of-line (C++ [dcl.meaning]p1). | |||
6893 | Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) | |||
6894 | << D.getCXXScopeSpec().getRange(); | |||
6895 | Previous.clear(); | |||
6896 | NewVD->setInvalidDecl(); | |||
6897 | } | |||
6898 | } else if (D.getCXXScopeSpec().isSet()) { | |||
6899 | // No previous declaration in the qualifying scope. | |||
6900 | Diag(D.getIdentifierLoc(), diag::err_no_member) | |||
6901 | << Name << computeDeclContext(D.getCXXScopeSpec(), true) | |||
6902 | << D.getCXXScopeSpec().getRange(); | |||
6903 | NewVD->setInvalidDecl(); | |||
6904 | } | |||
6905 | ||||
6906 | if (!IsVariableTemplateSpecialization) | |||
6907 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | |||
6908 | ||||
6909 | if (NewTemplate) { | |||
6910 | VarTemplateDecl *PrevVarTemplate = | |||
6911 | NewVD->getPreviousDecl() | |||
6912 | ? NewVD->getPreviousDecl()->getDescribedVarTemplate() | |||
6913 | : nullptr; | |||
6914 | ||||
6915 | // Check the template parameter list of this declaration, possibly | |||
6916 | // merging in the template parameter list from the previous variable | |||
6917 | // template declaration. | |||
6918 | if (CheckTemplateParameterList( | |||
6919 | TemplateParams, | |||
6920 | PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() | |||
6921 | : nullptr, | |||
6922 | (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && | |||
6923 | DC->isDependentContext()) | |||
6924 | ? TPC_ClassTemplateMember | |||
6925 | : TPC_VarTemplate)) | |||
6926 | NewVD->setInvalidDecl(); | |||
6927 | ||||
6928 | // If we are providing an explicit specialization of a static variable | |||
6929 | // template, make a note of that. | |||
6930 | if (PrevVarTemplate && | |||
6931 | PrevVarTemplate->getInstantiatedFromMemberTemplate()) | |||
6932 | PrevVarTemplate->setMemberSpecialization(); | |||
6933 | } | |||
6934 | } | |||
6935 | ||||
6936 | // Diagnose shadowed variables iff this isn't a redeclaration. | |||
6937 | if (ShadowedDecl && !D.isRedeclaration()) | |||
6938 | CheckShadow(NewVD, ShadowedDecl, Previous); | |||
6939 | ||||
6940 | ProcessPragmaWeak(S, NewVD); | |||
6941 | ||||
6942 | // If this is the first declaration of an extern C variable, update | |||
6943 | // the map of such variables. | |||
6944 | if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && | |||
6945 | isIncompleteDeclExternC(*this, NewVD)) | |||
6946 | RegisterLocallyScopedExternCDecl(NewVD, S); | |||
6947 | ||||
6948 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | |||
6949 | Decl *ManglingContextDecl; | |||
6950 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( | |||
6951 | NewVD->getDeclContext(), ManglingContextDecl)) { | |||
6952 | Context.setManglingNumber( | |||
6953 | NewVD, MCtx->getManglingNumber( | |||
6954 | NewVD, getMSManglingNumber(getLangOpts(), S))); | |||
6955 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | |||
6956 | } | |||
6957 | } | |||
6958 | ||||
6959 | // Special handling of variable named 'main'. | |||
6960 | if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && | |||
6961 | NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && | |||
6962 | !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { | |||
6963 | ||||
6964 | // C++ [basic.start.main]p3 | |||
6965 | // A program that declares a variable main at global scope is ill-formed. | |||
6966 | if (getLangOpts().CPlusPlus) | |||
6967 | Diag(D.getBeginLoc(), diag::err_main_global_variable); | |||
6968 | ||||
6969 | // In C, and external-linkage variable named main results in undefined | |||
6970 | // behavior. | |||
6971 | else if (NewVD->hasExternalFormalLinkage()) | |||
6972 | Diag(D.getBeginLoc(), diag::warn_main_redefined); | |||
6973 | } | |||
6974 | ||||
6975 | if (D.isRedeclaration() && !Previous.empty()) { | |||
6976 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | |||
6977 | checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, | |||
6978 | D.isFunctionDefinition()); | |||
6979 | } | |||
6980 | ||||
6981 | if (NewTemplate) { | |||
6982 | if (NewVD->isInvalidDecl()) | |||
6983 | NewTemplate->setInvalidDecl(); | |||
6984 | ActOnDocumentableDecl(NewTemplate); | |||
6985 | return NewTemplate; | |||
6986 | } | |||
6987 | ||||
6988 | if (IsMemberSpecialization && !NewVD->isInvalidDecl()) | |||
6989 | CompleteMemberSpecialization(NewVD, Previous); | |||
6990 | ||||
6991 | return NewVD; | |||
6992 | } | |||
6993 | ||||
6994 | /// Enum describing the %select options in diag::warn_decl_shadow. | |||
6995 | enum ShadowedDeclKind { | |||
6996 | SDK_Local, | |||
6997 | SDK_Global, | |||
6998 | SDK_StaticMember, | |||
6999 | SDK_Field, | |||
7000 | SDK_Typedef, | |||
7001 | SDK_Using | |||
7002 | }; | |||
7003 | ||||
7004 | /// Determine what kind of declaration we're shadowing. | |||
7005 | static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, | |||
7006 | const DeclContext *OldDC) { | |||
7007 | if (isa<TypeAliasDecl>(ShadowedDecl)) | |||
7008 | return SDK_Using; | |||
7009 | else if (isa<TypedefDecl>(ShadowedDecl)) | |||
7010 | return SDK_Typedef; | |||
7011 | else if (isa<RecordDecl>(OldDC)) | |||
7012 | return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; | |||
7013 | ||||
7014 | return OldDC->isFileContext() ? SDK_Global : SDK_Local; | |||
7015 | } | |||
7016 | ||||
7017 | /// Return the location of the capture if the given lambda captures the given | |||
7018 | /// variable \p VD, or an invalid source location otherwise. | |||
7019 | static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, | |||
7020 | const VarDecl *VD) { | |||
7021 | for (const Capture &Capture : LSI->Captures) { | |||
7022 | if (Capture.isVariableCapture() && Capture.getVariable() == VD) | |||
7023 | return Capture.getLocation(); | |||
7024 | } | |||
7025 | return SourceLocation(); | |||
7026 | } | |||
7027 | ||||
7028 | static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, | |||
7029 | const LookupResult &R) { | |||
7030 | // Only diagnose if we're shadowing an unambiguous field or variable. | |||
7031 | if (R.getResultKind() != LookupResult::Found) | |||
7032 | return false; | |||
7033 | ||||
7034 | // Return false if warning is ignored. | |||
7035 | return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); | |||
7036 | } | |||
7037 | ||||
7038 | /// Return the declaration shadowed by the given variable \p D, or null | |||
7039 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | |||
7040 | NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, | |||
7041 | const LookupResult &R) { | |||
7042 | if (!shouldWarnIfShadowedDecl(Diags, R)) | |||
7043 | return nullptr; | |||
7044 | ||||
7045 | // Don't diagnose declarations at file scope. | |||
7046 | if (D->hasGlobalStorage()) | |||
7047 | return nullptr; | |||
7048 | ||||
7049 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | |||
7050 | return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) | |||
7051 | ? ShadowedDecl | |||
7052 | : nullptr; | |||
7053 | } | |||
7054 | ||||
7055 | /// Return the declaration shadowed by the given typedef \p D, or null | |||
7056 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | |||
7057 | NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, | |||
7058 | const LookupResult &R) { | |||
7059 | // Don't warn if typedef declaration is part of a class | |||
7060 | if (D->getDeclContext()->isRecord()) | |||
7061 | return nullptr; | |||
7062 | ||||
7063 | if (!shouldWarnIfShadowedDecl(Diags, R)) | |||
7064 | return nullptr; | |||
7065 | ||||
7066 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | |||
7067 | return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; | |||
7068 | } | |||
7069 | ||||
7070 | /// Diagnose variable or built-in function shadowing. Implements | |||
7071 | /// -Wshadow. | |||
7072 | /// | |||
7073 | /// This method is called whenever a VarDecl is added to a "useful" | |||
7074 | /// scope. | |||
7075 | /// | |||
7076 | /// \param ShadowedDecl the declaration that is shadowed by the given variable | |||
7077 | /// \param R the lookup of the name | |||
7078 | /// | |||
7079 | void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, | |||
7080 | const LookupResult &R) { | |||
7081 | DeclContext *NewDC = D->getDeclContext(); | |||
7082 | ||||
7083 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { | |||
7084 | // Fields are not shadowed by variables in C++ static methods. | |||
7085 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) | |||
7086 | if (MD->isStatic()) | |||
7087 | return; | |||
7088 | ||||
7089 | // Fields shadowed by constructor parameters are a special case. Usually | |||
7090 | // the constructor initializes the field with the parameter. | |||
7091 | if (isa<CXXConstructorDecl>(NewDC)) | |||
7092 | if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { | |||
7093 | // Remember that this was shadowed so we can either warn about its | |||
7094 | // modification or its existence depending on warning settings. | |||
7095 | ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); | |||
7096 | return; | |||
7097 | } | |||
7098 | } | |||
7099 | ||||
7100 | if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) | |||
7101 | if (shadowedVar->isExternC()) { | |||
7102 | // For shadowing external vars, make sure that we point to the global | |||
7103 | // declaration, not a locally scoped extern declaration. | |||
7104 | for (auto I : shadowedVar->redecls()) | |||
7105 | if (I->isFileVarDecl()) { | |||
7106 | ShadowedDecl = I; | |||
7107 | break; | |||
7108 | } | |||
7109 | } | |||
7110 | ||||
7111 | DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); | |||
7112 | ||||
7113 | unsigned WarningDiag = diag::warn_decl_shadow; | |||
7114 | SourceLocation CaptureLoc; | |||
7115 | if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && | |||
7116 | isa<CXXMethodDecl>(NewDC)) { | |||
7117 | if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { | |||
7118 | if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { | |||
7119 | if (RD->getLambdaCaptureDefault() == LCD_None) { | |||
7120 | // Try to avoid warnings for lambdas with an explicit capture list. | |||
7121 | const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); | |||
7122 | // Warn only when the lambda captures the shadowed decl explicitly. | |||
7123 | CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); | |||
7124 | if (CaptureLoc.isInvalid()) | |||
7125 | WarningDiag = diag::warn_decl_shadow_uncaptured_local; | |||
7126 | } else { | |||
7127 | // Remember that this was shadowed so we can avoid the warning if the | |||
7128 | // shadowed decl isn't captured and the warning settings allow it. | |||
7129 | cast<LambdaScopeInfo>(getCurFunction()) | |||
7130 | ->ShadowingDecls.push_back( | |||
7131 | {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); | |||
7132 | return; | |||
7133 | } | |||
7134 | } | |||
7135 | ||||
7136 | if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { | |||
7137 | // A variable can't shadow a local variable in an enclosing scope, if | |||
7138 | // they are separated by a non-capturing declaration context. | |||
7139 | for (DeclContext *ParentDC = NewDC; | |||
7140 | ParentDC && !ParentDC->Equals(OldDC); | |||
7141 | ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { | |||
7142 | // Only block literals, captured statements, and lambda expressions | |||
7143 | // can capture; other scopes don't. | |||
7144 | if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && | |||
7145 | !isLambdaCallOperator(ParentDC)) { | |||
7146 | return; | |||
7147 | } | |||
7148 | } | |||
7149 | } | |||
7150 | } | |||
7151 | } | |||
7152 | ||||
7153 | // Only warn about certain kinds of shadowing for class members. | |||
7154 | if (NewDC && NewDC->isRecord()) { | |||
7155 | // In particular, don't warn about shadowing non-class members. | |||
7156 | if (!OldDC->isRecord()) | |||
7157 | return; | |||
7158 | ||||
7159 | // TODO: should we warn about static data members shadowing | |||
7160 | // static data members from base classes? | |||
7161 | ||||
7162 | // TODO: don't diagnose for inaccessible shadowed members. | |||
7163 | // This is hard to do perfectly because we might friend the | |||
7164 | // shadowing context, but that's just a false negative. | |||
7165 | } | |||
7166 | ||||
7167 | ||||
7168 | DeclarationName Name = R.getLookupName(); | |||
7169 | ||||
7170 | // Emit warning and note. | |||
7171 | if (getSourceManager().isInSystemMacro(R.getNameLoc())) | |||
7172 | return; | |||
7173 | ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); | |||
7174 | Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; | |||
7175 | if (!CaptureLoc.isInvalid()) | |||
7176 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | |||
7177 | << Name << /*explicitly*/ 1; | |||
7178 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | |||
7179 | } | |||
7180 | ||||
7181 | /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD | |||
7182 | /// when these variables are captured by the lambda. | |||
7183 | void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { | |||
7184 | for (const auto &Shadow : LSI->ShadowingDecls) { | |||
7185 | const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; | |||
7186 | // Try to avoid the warning when the shadowed decl isn't captured. | |||
7187 | SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); | |||
7188 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | |||
7189 | Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() | |||
7190 | ? diag::warn_decl_shadow_uncaptured_local | |||
7191 | : diag::warn_decl_shadow) | |||
7192 | << Shadow.VD->getDeclName() | |||
7193 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; | |||
7194 | if (!CaptureLoc.isInvalid()) | |||
7195 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | |||
7196 | << Shadow.VD->getDeclName() << /*explicitly*/ 0; | |||
7197 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | |||
7198 | } | |||
7199 | } | |||
7200 | ||||
7201 | /// Check -Wshadow without the advantage of a previous lookup. | |||
7202 | void Sema::CheckShadow(Scope *S, VarDecl *D) { | |||
7203 | if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) | |||
7204 | return; | |||
7205 | ||||
7206 | LookupResult R(*this, D->getDeclName(), D->getLocation(), | |||
7207 | Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); | |||
7208 | LookupName(R, S); | |||
7209 | if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) | |||
7210 | CheckShadow(D, ShadowedDecl, R); | |||
7211 | } | |||
7212 | ||||
7213 | /// Check if 'E', which is an expression that is about to be modified, refers | |||
7214 | /// to a constructor parameter that shadows a field. | |||
7215 | void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { | |||
7216 | // Quickly ignore expressions that can't be shadowing ctor parameters. | |||
7217 | if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) | |||
7218 | return; | |||
7219 | E = E->IgnoreParenImpCasts(); | |||
7220 | auto *DRE = dyn_cast<DeclRefExpr>(E); | |||
7221 | if (!DRE) | |||
7222 | return; | |||
7223 | const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); | |||
7224 | auto I = ShadowingDecls.find(D); | |||
7225 | if (I == ShadowingDecls.end()) | |||
7226 | return; | |||
7227 | const NamedDecl *ShadowedDecl = I->second; | |||
7228 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | |||
7229 | Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; | |||
7230 | Diag(D->getLocation(), diag::note_var_declared_here) << D; | |||
7231 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | |||
7232 | ||||
7233 | // Avoid issuing multiple warnings about the same decl. | |||
7234 | ShadowingDecls.erase(I); | |||
7235 | } | |||
7236 | ||||
7237 | /// Check for conflict between this global or extern "C" declaration and | |||
7238 | /// previous global or extern "C" declarations. This is only used in C++. | |||
7239 | template<typename T> | |||
7240 | static bool checkGlobalOrExternCConflict( | |||
7241 | Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { | |||
7242 | assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"" ) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 7242, __PRETTY_FUNCTION__)); | |||
7243 | NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); | |||
7244 | ||||
7245 | if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { | |||
7246 | // The common case: this global doesn't conflict with any extern "C" | |||
7247 | // declaration. | |||
7248 | return false; | |||
7249 | } | |||
7250 | ||||
7251 | if (Prev) { | |||
7252 | if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { | |||
7253 | // Both the old and new declarations have C language linkage. This is a | |||
7254 | // redeclaration. | |||
7255 | Previous.clear(); | |||
7256 | Previous.addDecl(Prev); | |||
7257 | return true; | |||
7258 | } | |||
7259 | ||||
7260 | // This is a global, non-extern "C" declaration, and there is a previous | |||
7261 | // non-global extern "C" declaration. Diagnose if this is a variable | |||
7262 | // declaration. | |||
7263 | if (!isa<VarDecl>(ND)) | |||
7264 | return false; | |||
7265 | } else { | |||
7266 | // The declaration is extern "C". Check for any declaration in the | |||
7267 | // translation unit which might conflict. | |||
7268 | if (IsGlobal) { | |||
7269 | // We have already performed the lookup into the translation unit. | |||
7270 | IsGlobal = false; | |||
7271 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | |||
7272 | I != E; ++I) { | |||
7273 | if (isa<VarDecl>(*I)) { | |||
7274 | Prev = *I; | |||
7275 | break; | |||
7276 | } | |||
7277 | } | |||
7278 | } else { | |||
7279 | DeclContext::lookup_result R = | |||
7280 | S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); | |||
7281 | for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); | |||
7282 | I != E; ++I) { | |||
7283 | if (isa<VarDecl>(*I)) { | |||
7284 | Prev = *I; | |||
7285 | break; | |||
7286 | } | |||
7287 | // FIXME: If we have any other entity with this name in global scope, | |||
7288 | // the declaration is ill-formed, but that is a defect: it breaks the | |||
7289 | // 'stat' hack, for instance. Only variables can have mangled name | |||
7290 | // clashes with extern "C" declarations, so only they deserve a | |||
7291 | // diagnostic. | |||
7292 | } | |||
7293 | } | |||
7294 | ||||
7295 | if (!Prev) | |||
7296 | return false; | |||
7297 | } | |||
7298 | ||||
7299 | // Use the first declaration's location to ensure we point at something which | |||
7300 | // is lexically inside an extern "C" linkage-spec. | |||
7301 | assert(Prev && "should have found a previous declaration to diagnose")((Prev && "should have found a previous declaration to diagnose" ) ? static_cast<void> (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 7301, __PRETTY_FUNCTION__)); | |||
7302 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) | |||
7303 | Prev = FD->getFirstDecl(); | |||
7304 | else | |||
7305 | Prev = cast<VarDecl>(Prev)->getFirstDecl(); | |||
7306 | ||||
7307 | S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) | |||
7308 | << IsGlobal << ND; | |||
7309 | S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) | |||
7310 | << IsGlobal; | |||
7311 | return false; | |||
7312 | } | |||
7313 | ||||
7314 | /// Apply special rules for handling extern "C" declarations. Returns \c true | |||
7315 | /// if we have found that this is a redeclaration of some prior entity. | |||
7316 | /// | |||
7317 | /// Per C++ [dcl.link]p6: | |||
7318 | /// Two declarations [for a function or variable] with C language linkage | |||
7319 | /// with the same name that appear in different scopes refer to the same | |||
7320 | /// [entity]. An entity with C language linkage shall not be declared with | |||
7321 | /// the same name as an entity in global scope. | |||
7322 | template<typename T> | |||
7323 | static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, | |||
7324 | LookupResult &Previous) { | |||
7325 | if (!S.getLangOpts().CPlusPlus) { | |||
7326 | // In C, when declaring a global variable, look for a corresponding 'extern' | |||
7327 | // variable declared in function scope. We don't need this in C++, because | |||
7328 | // we find local extern decls in the surrounding file-scope DeclContext. | |||
7329 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | |||
7330 | if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { | |||
7331 | Previous.clear(); | |||
7332 | Previous.addDecl(Prev); | |||
7333 | return true; | |||
7334 | } | |||
7335 | } | |||
7336 | return false; | |||
7337 | } | |||
7338 | ||||
7339 | // A declaration in the translation unit can conflict with an extern "C" | |||
7340 | // declaration. | |||
7341 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) | |||
7342 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); | |||
7343 | ||||
7344 | // An extern "C" declaration can conflict with a declaration in the | |||
7345 | // translation unit or can be a redeclaration of an extern "C" declaration | |||
7346 | // in another scope. | |||
7347 | if (isIncompleteDeclExternC(S,ND)) | |||
7348 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); | |||
7349 | ||||
7350 | // Neither global nor extern "C": nothing to do. | |||
7351 | return false; | |||
7352 | } | |||
7353 | ||||
7354 | void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { | |||
7355 | // If the decl is already known invalid, don't check it. | |||
7356 | if (NewVD->isInvalidDecl()) | |||
7357 | return; | |||
7358 | ||||
7359 | QualType T = NewVD->getType(); | |||
7360 | ||||
7361 | // Defer checking an 'auto' type until its initializer is attached. | |||
7362 | if (T->isUndeducedType()) | |||
7363 | return; | |||
7364 | ||||
7365 | if (NewVD->hasAttrs()) | |||
7366 | CheckAlignasUnderalignment(NewVD); | |||
7367 | ||||
7368 | if (T->isObjCObjectType()) { | |||
7369 | Diag(NewVD->getLocation(), diag::err_statically_allocated_object) | |||
7370 | << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); | |||
7371 | T = Context.getObjCObjectPointerType(T); | |||
7372 | NewVD->setType(T); | |||
7373 | } | |||
7374 | ||||
7375 | // Emit an error if an address space was applied to decl with local storage. | |||
7376 | // This includes arrays of objects with address space qualifiers, but not | |||
7377 | // automatic variables that point to other address spaces. | |||
7378 | // ISO/IEC TR 18037 S5.1.2 | |||
7379 | if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && | |||
7380 | T.getAddressSpace() != LangAS::Default) { | |||
7381 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; | |||
7382 | NewVD->setInvalidDecl(); | |||
7383 | return; | |||
7384 | } | |||
7385 | ||||
7386 | // OpenCL v1.2 s6.8 - The static qualifier is valid only in program | |||
7387 | // scope. | |||
7388 | if (getLangOpts().OpenCLVersion == 120 && | |||
7389 | !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && | |||
7390 | NewVD->isStaticLocal()) { | |||
7391 | Diag(NewVD->getLocation(), diag::err_static_function_scope); | |||
7392 | NewVD->setInvalidDecl(); | |||
7393 | return; | |||
7394 | } | |||
7395 | ||||
7396 | if (getLangOpts().OpenCL) { | |||
7397 | // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. | |||
7398 | if (NewVD->hasAttr<BlocksAttr>()) { | |||
7399 | Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); | |||
7400 | return; | |||
7401 | } | |||
7402 | ||||
7403 | if (T->isBlockPointerType()) { | |||
7404 | // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and | |||
7405 | // can't use 'extern' storage class. | |||
7406 | if (!T.isConstQualified()) { | |||
7407 | Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) | |||
7408 | << 0 /*const*/; | |||
7409 | NewVD->setInvalidDecl(); | |||
7410 | return; | |||
7411 | } | |||
7412 | if (NewVD->hasExternalStorage()) { | |||
7413 | Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); | |||
7414 | NewVD->setInvalidDecl(); | |||
7415 | return; | |||
7416 | } | |||
7417 | } | |||
7418 | // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the | |||
7419 | // __constant address space. | |||
7420 | // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static | |||
7421 | // variables inside a function can also be declared in the global | |||
7422 | // address space. | |||
7423 | // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local | |||
7424 | // address space additionally. | |||
7425 | // FIXME: Add local AS for OpenCL C++. | |||
7426 | if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || | |||
7427 | NewVD->hasExternalStorage()) { | |||
7428 | if (!T->isSamplerT() && | |||
7429 | !(T.getAddressSpace() == LangAS::opencl_constant || | |||
7430 | (T.getAddressSpace() == LangAS::opencl_global && | |||
7431 | (getLangOpts().OpenCLVersion == 200 || | |||
7432 | getLangOpts().OpenCLCPlusPlus)))) { | |||
7433 | int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; | |||
7434 | if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) | |||
7435 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | |||
7436 | << Scope << "global or constant"; | |||
7437 | else | |||
7438 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | |||
7439 | << Scope << "constant"; | |||
7440 | NewVD->setInvalidDecl(); | |||
7441 | return; | |||
7442 | } | |||
7443 | } else { | |||
7444 | if (T.getAddressSpace() == LangAS::opencl_global) { | |||
7445 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | |||
7446 | << 1 /*is any function*/ << "global"; | |||
7447 | NewVD->setInvalidDecl(); | |||
7448 | return; | |||
7449 | } | |||
7450 | if (T.getAddressSpace() == LangAS::opencl_constant || | |||
7451 | T.getAddressSpace() == LangAS::opencl_local) { | |||
7452 | FunctionDecl *FD = getCurFunctionDecl(); | |||
7453 | // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables | |||
7454 | // in functions. | |||
7455 | if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { | |||
7456 | if (T.getAddressSpace() == LangAS::opencl_constant) | |||
7457 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | |||
7458 | << 0 /*non-kernel only*/ << "constant"; | |||
7459 | else | |||
7460 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | |||
7461 | << 0 /*non-kernel only*/ << "local"; | |||
7462 | NewVD->setInvalidDecl(); | |||
7463 | return; | |||
7464 | } | |||
7465 | // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be | |||
7466 | // in the outermost scope of a kernel function. | |||
7467 | if (FD && FD->hasAttr<OpenCLKernelAttr>()) { | |||
7468 | if (!getCurScope()->isFunctionScope()) { | |||
7469 | if (T.getAddressSpace() == LangAS::opencl_constant) | |||
7470 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | |||
7471 | << "constant"; | |||
7472 | else | |||
7473 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | |||
7474 | << "local"; | |||
7475 | NewVD->setInvalidDecl(); | |||
7476 | return; | |||
7477 | } | |||
7478 | } | |||
7479 | } else if (T.getAddressSpace() != LangAS::opencl_private) { | |||
7480 | // Do not allow other address spaces on automatic variable. | |||
7481 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; | |||
7482 | NewVD->setInvalidDecl(); | |||
7483 | return; | |||
7484 | } | |||
7485 | } | |||
7486 | } | |||
7487 | ||||
7488 | if (NewVD->hasLocalStorage() && T.isObjCGCWeak() | |||
7489 | && !NewVD->hasAttr<BlocksAttr>()) { | |||
7490 | if (getLangOpts().getGC() != LangOptions::NonGC) | |||
7491 | Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); | |||
7492 | else { | |||
7493 | assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> ( 0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 7493, __PRETTY_FUNCTION__)); | |||
7494 | Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); | |||
7495 | } | |||
7496 | } | |||
7497 | ||||
7498 | bool isVM = T->isVariablyModifiedType(); | |||
7499 | if (isVM || NewVD->hasAttr<CleanupAttr>() || | |||
7500 | NewVD->hasAttr<BlocksAttr>()) | |||
7501 | setFunctionHasBranchProtectedScope(); | |||
7502 | ||||
7503 | if ((isVM && NewVD->hasLinkage()) || | |||
7504 | (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { | |||
7505 | bool SizeIsNegative; | |||
7506 | llvm::APSInt Oversized; | |||
7507 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( | |||
7508 | NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); | |||
7509 | QualType FixedT; | |||
7510 | if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) | |||
7511 | FixedT = FixedTInfo->getType(); | |||
7512 | else if (FixedTInfo) { | |||
7513 | // Type and type-as-written are canonically different. We need to fix up | |||
7514 | // both types separately. | |||
7515 | FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, | |||
7516 | Oversized); | |||
7517 | } | |||
7518 | if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { | |||
7519 | const VariableArrayType *VAT = Context.getAsVariableArrayType(T); | |||
7520 | // FIXME: This won't give the correct result for | |||
7521 | // int a[10][n]; | |||
7522 | SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); | |||
7523 | ||||
7524 | if (NewVD->isFileVarDecl()) | |||
7525 | Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) | |||
7526 | << SizeRange; | |||
7527 | else if (NewVD->isStaticLocal()) | |||
7528 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) | |||
7529 | << SizeRange; | |||
7530 | else | |||
7531 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) | |||
7532 | << SizeRange; | |||
7533 | NewVD->setInvalidDecl(); | |||
7534 | return; | |||
7535 | } | |||
7536 | ||||
7537 | if (!FixedTInfo) { | |||
7538 | if (NewVD->isFileVarDecl()) | |||
7539 | Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); | |||
7540 | else | |||
7541 | Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); | |||
7542 | NewVD->setInvalidDecl(); | |||
7543 | return; | |||
7544 | } | |||
7545 | ||||
7546 | Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); | |||
7547 | NewVD->setType(FixedT); | |||
7548 | NewVD->setTypeSourceInfo(FixedTInfo); | |||
7549 | } | |||
7550 | ||||
7551 | if (T->isVoidType()) { | |||
7552 | // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names | |||
7553 | // of objects and functions. | |||
7554 | if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { | |||
7555 | Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) | |||
7556 | << T; | |||
7557 | NewVD->setInvalidDecl(); | |||
7558 | return; | |||
7559 | } | |||
7560 | } | |||
7561 | ||||
7562 | if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { | |||
7563 | Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); | |||
7564 | NewVD->setInvalidDecl(); | |||
7565 | return; | |||
7566 | } | |||
7567 | ||||
7568 | if (isVM && NewVD->hasAttr<BlocksAttr>()) { | |||
7569 | Diag(NewVD->getLocation(), diag::err_block_on_vm); | |||
7570 | NewVD->setInvalidDecl(); | |||
7571 | return; | |||
7572 | } | |||
7573 | ||||
7574 | if (NewVD->isConstexpr() && !T->isDependentType() && | |||
7575 | RequireLiteralType(NewVD->getLocation(), T, | |||
7576 | diag::err_constexpr_var_non_literal)) { | |||
7577 | NewVD->setInvalidDecl(); | |||
7578 | return; | |||
7579 | } | |||
7580 | } | |||
7581 | ||||
7582 | /// Perform semantic checking on a newly-created variable | |||
7583 | /// declaration. | |||
7584 | /// | |||
7585 | /// This routine performs all of the type-checking required for a | |||
7586 | /// variable declaration once it has been built. It is used both to | |||
7587 | /// check variables after they have been parsed and their declarators | |||
7588 | /// have been translated into a declaration, and to check variables | |||
7589 | /// that have been instantiated from a template. | |||
7590 | /// | |||
7591 | /// Sets NewVD->isInvalidDecl() if an error was encountered. | |||
7592 | /// | |||
7593 | /// Returns true if the variable declaration is a redeclaration. | |||
7594 | bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { | |||
7595 | CheckVariableDeclarationType(NewVD); | |||
7596 | ||||
7597 | // If the decl is already known invalid, don't check it. | |||
7598 | if (NewVD->isInvalidDecl()) | |||
7599 | return false; | |||
7600 | ||||
7601 | // If we did not find anything by this name, look for a non-visible | |||
7602 | // extern "C" declaration with the same name. | |||
7603 | if (Previous.empty() && | |||
7604 | checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) | |||
7605 | Previous.setShadowed(); | |||
7606 | ||||
7607 | if (!Previous.empty()) { | |||
7608 | MergeVarDecl(NewVD, Previous); | |||
7609 | return true; | |||
7610 | } | |||
7611 | return false; | |||
7612 | } | |||
7613 | ||||
7614 | namespace { | |||
7615 | struct FindOverriddenMethod { | |||
7616 | Sema *S; | |||
7617 | CXXMethodDecl *Method; | |||
7618 | ||||
7619 | /// Member lookup function that determines whether a given C++ | |||
7620 | /// method overrides a method in a base class, to be used with | |||
7621 | /// CXXRecordDecl::lookupInBases(). | |||
7622 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | |||
7623 | RecordDecl *BaseRecord = | |||
7624 | Specifier->getType()->getAs<RecordType>()->getDecl(); | |||
7625 | ||||
7626 | DeclarationName Name = Method->getDeclName(); | |||
7627 | ||||
7628 | // FIXME: Do we care about other names here too? | |||
7629 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | |||
7630 | // We really want to find the base class destructor here. | |||
7631 | QualType T = S->Context.getTypeDeclType(BaseRecord); | |||
7632 | CanQualType CT = S->Context.getCanonicalType(T); | |||
7633 | ||||
7634 | Name = S->Context.DeclarationNames.getCXXDestructorName(CT); | |||
7635 | } | |||
7636 | ||||
7637 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); | |||
7638 | Path.Decls = Path.Decls.slice(1)) { | |||
7639 | NamedDecl *D = Path.Decls.front(); | |||
7640 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { | |||
7641 | if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) | |||
7642 | return true; | |||
7643 | } | |||
7644 | } | |||
7645 | ||||
7646 | return false; | |||
7647 | } | |||
7648 | }; | |||
7649 | ||||
7650 | enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; | |||
7651 | } // end anonymous namespace | |||
7652 | ||||
7653 | /// Report an error regarding overriding, along with any relevant | |||
7654 | /// overridden methods. | |||
7655 | /// | |||
7656 | /// \param DiagID the primary error to report. | |||
7657 | /// \param MD the overriding method. | |||
7658 | /// \param OEK which overrides to include as notes. | |||
7659 | static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, | |||
7660 | OverrideErrorKind OEK = OEK_All) { | |||
7661 | S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); | |||
7662 | for (const CXXMethodDecl *O : MD->overridden_methods()) { | |||
7663 | // This check (& the OEK parameter) could be replaced by a predicate, but | |||
7664 | // without lambdas that would be overkill. This is still nicer than writing | |||
7665 | // out the diag loop 3 times. | |||
7666 | if ((OEK == OEK_All) || | |||
7667 | (OEK == OEK_NonDeleted && !O->isDeleted()) || | |||
7668 | (OEK == OEK_Deleted && O->isDeleted())) | |||
7669 | S.Diag(O->getLocation(), diag::note_overridden_virtual_function); | |||
7670 | } | |||
7671 | } | |||
7672 | ||||
7673 | /// AddOverriddenMethods - See if a method overrides any in the base classes, | |||
7674 | /// and if so, check that it's a valid override and remember it. | |||
7675 | bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { | |||
7676 | // Look for methods in base classes that this method might override. | |||
7677 | CXXBasePaths Paths; | |||
7678 | FindOverriddenMethod FOM; | |||
7679 | FOM.Method = MD; | |||
7680 | FOM.S = this; | |||
7681 | bool hasDeletedOverridenMethods = false; | |||
7682 | bool hasNonDeletedOverridenMethods = false; | |||
7683 | bool AddedAny = false; | |||
7684 | if (DC->lookupInBases(FOM, Paths)) { | |||
7685 | for (auto *I : Paths.found_decls()) { | |||
7686 | if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { | |||
7687 | MD->addOverriddenMethod(OldMD->getCanonicalDecl()); | |||
7688 | if (!CheckOverridingFunctionReturnType(MD, OldMD) && | |||
7689 | !CheckOverridingFunctionAttributes(MD, OldMD) && | |||
7690 | !CheckOverridingFunctionExceptionSpec(MD, OldMD) && | |||
7691 | !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { | |||
7692 | hasDeletedOverridenMethods |= OldMD->isDeleted(); | |||
7693 | hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); | |||
7694 | AddedAny = true; | |||
7695 | } | |||
7696 | } | |||
7697 | } | |||
7698 | } | |||
7699 | ||||
7700 | if (hasDeletedOverridenMethods && !MD->isDeleted()) { | |||
7701 | ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); | |||
7702 | } | |||
7703 | if (hasNonDeletedOverridenMethods && MD->isDeleted()) { | |||
7704 | ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); | |||
7705 | } | |||
7706 | ||||
7707 | return AddedAny; | |||
7708 | } | |||
7709 | ||||
7710 | namespace { | |||
7711 | // Struct for holding all of the extra arguments needed by | |||
7712 | // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. | |||
7713 | struct ActOnFDArgs { | |||
7714 | Scope *S; | |||
7715 | Declarator &D; | |||
7716 | MultiTemplateParamsArg TemplateParamLists; | |||
7717 | bool AddToScope; | |||
7718 | }; | |||
7719 | } // end anonymous namespace | |||
7720 | ||||
7721 | namespace { | |||
7722 | ||||
7723 | // Callback to only accept typo corrections that have a non-zero edit distance. | |||
7724 | // Also only accept corrections that have the same parent decl. | |||
7725 | class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { | |||
7726 | public: | |||
7727 | DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, | |||
7728 | CXXRecordDecl *Parent) | |||
7729 | : Context(Context), OriginalFD(TypoFD), | |||
7730 | ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} | |||
7731 | ||||
7732 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
7733 | if (candidate.getEditDistance() == 0) | |||
7734 | return false; | |||
7735 | ||||
7736 | SmallVector<unsigned, 1> MismatchedParams; | |||
7737 | for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), | |||
7738 | CDeclEnd = candidate.end(); | |||
7739 | CDecl != CDeclEnd; ++CDecl) { | |||
7740 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | |||
7741 | ||||
7742 | if (FD && !FD->hasBody() && | |||
7743 | hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { | |||
7744 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | |||
7745 | CXXRecordDecl *Parent = MD->getParent(); | |||
7746 | if (Parent && Parent->getCanonicalDecl() == ExpectedParent) | |||
7747 | return true; | |||
7748 | } else if (!ExpectedParent) { | |||
7749 | return true; | |||
7750 | } | |||
7751 | } | |||
7752 | } | |||
7753 | ||||
7754 | return false; | |||
7755 | } | |||
7756 | ||||
7757 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
7758 | return llvm::make_unique<DifferentNameValidatorCCC>(*this); | |||
7759 | } | |||
7760 | ||||
7761 | private: | |||
7762 | ASTContext &Context; | |||
7763 | FunctionDecl *OriginalFD; | |||
7764 | CXXRecordDecl *ExpectedParent; | |||
7765 | }; | |||
7766 | ||||
7767 | } // end anonymous namespace | |||
7768 | ||||
7769 | void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { | |||
7770 | TypoCorrectedFunctionDefinitions.insert(F); | |||
7771 | } | |||
7772 | ||||
7773 | /// Generate diagnostics for an invalid function redeclaration. | |||
7774 | /// | |||
7775 | /// This routine handles generating the diagnostic messages for an invalid | |||
7776 | /// function redeclaration, including finding possible similar declarations | |||
7777 | /// or performing typo correction if there are no previous declarations with | |||
7778 | /// the same name. | |||
7779 | /// | |||
7780 | /// Returns a NamedDecl iff typo correction was performed and substituting in | |||
7781 | /// the new declaration name does not cause new errors. | |||
7782 | static NamedDecl *DiagnoseInvalidRedeclaration( | |||
7783 | Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, | |||
7784 | ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { | |||
7785 | DeclarationName Name = NewFD->getDeclName(); | |||
7786 | DeclContext *NewDC = NewFD->getDeclContext(); | |||
7787 | SmallVector<unsigned, 1> MismatchedParams; | |||
7788 | SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; | |||
7789 | TypoCorrection Correction; | |||
7790 | bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); | |||
7791 | unsigned DiagMsg = | |||
7792 | IsLocalFriend ? diag::err_no_matching_local_friend : | |||
7793 | NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : | |||
7794 | diag::err_member_decl_does_not_match; | |||
7795 | LookupResult Prev(SemaRef, Name, NewFD->getLocation(), | |||
7796 | IsLocalFriend ? Sema::LookupLocalFriendName | |||
7797 | : Sema::LookupOrdinaryName, | |||
7798 | Sema::ForVisibleRedeclaration); | |||
7799 | ||||
7800 | NewFD->setInvalidDecl(); | |||
7801 | if (IsLocalFriend) | |||
7802 | SemaRef.LookupName(Prev, S); | |||
7803 | else | |||
7804 | SemaRef.LookupQualifiedName(Prev, NewDC); | |||
7805 | assert(!Prev.isAmbiguous() &&((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 7806, __PRETTY_FUNCTION__)) | |||
7806 | "Cannot have an ambiguity in previous-declaration lookup")((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 7806, __PRETTY_FUNCTION__)); | |||
7807 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | |||
7808 | DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, | |||
7809 | MD ? MD->getParent() : nullptr); | |||
7810 | if (!Prev.empty()) { | |||
7811 | for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); | |||
7812 | Func != FuncEnd; ++Func) { | |||
7813 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); | |||
7814 | if (FD && | |||
7815 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | |||
7816 | // Add 1 to the index so that 0 can mean the mismatch didn't | |||
7817 | // involve a parameter | |||
7818 | unsigned ParamNum = | |||
7819 | MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; | |||
7820 | NearMatches.push_back(std::make_pair(FD, ParamNum)); | |||
7821 | } | |||
7822 | } | |||
7823 | // If the qualified name lookup yielded nothing, try typo correction | |||
7824 | } else if ((Correction = SemaRef.CorrectTypo( | |||
7825 | Prev.getLookupNameInfo(), Prev.getLookupKind(), S, | |||
7826 | &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, | |||
7827 | IsLocalFriend ? nullptr : NewDC))) { | |||
7828 | // Set up everything for the call to ActOnFunctionDeclarator | |||
7829 | ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), | |||
7830 | ExtraArgs.D.getIdentifierLoc()); | |||
7831 | Previous.clear(); | |||
7832 | Previous.setLookupName(Correction.getCorrection()); | |||
7833 | for (TypoCorrection::decl_iterator CDecl = Correction.begin(), | |||
7834 | CDeclEnd = Correction.end(); | |||
7835 | CDecl != CDeclEnd; ++CDecl) { | |||
7836 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | |||
7837 | if (FD && !FD->hasBody() && | |||
7838 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | |||
7839 | Previous.addDecl(FD); | |||
7840 | } | |||
7841 | } | |||
7842 | bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); | |||
7843 | ||||
7844 | NamedDecl *Result; | |||
7845 | // Retry building the function declaration with the new previous | |||
7846 | // declarations, and with errors suppressed. | |||
7847 | { | |||
7848 | // Trap errors. | |||
7849 | Sema::SFINAETrap Trap(SemaRef); | |||
7850 | ||||
7851 | // TODO: Refactor ActOnFunctionDeclarator so that we can call only the | |||
7852 | // pieces need to verify the typo-corrected C++ declaration and hopefully | |||
7853 | // eliminate the need for the parameter pack ExtraArgs. | |||
7854 | Result = SemaRef.ActOnFunctionDeclarator( | |||
7855 | ExtraArgs.S, ExtraArgs.D, | |||
7856 | Correction.getCorrectionDecl()->getDeclContext(), | |||
7857 | NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, | |||
7858 | ExtraArgs.AddToScope); | |||
7859 | ||||
7860 | if (Trap.hasErrorOccurred()) | |||
7861 | Result = nullptr; | |||
7862 | } | |||
7863 | ||||
7864 | if (Result) { | |||
7865 | // Determine which correction we picked. | |||
7866 | Decl *Canonical = Result->getCanonicalDecl(); | |||
7867 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | |||
7868 | I != E; ++I) | |||
7869 | if ((*I)->getCanonicalDecl() == Canonical) | |||
7870 | Correction.setCorrectionDecl(*I); | |||
7871 | ||||
7872 | // Let Sema know about the correction. | |||
7873 | SemaRef.MarkTypoCorrectedFunctionDefinition(Result); | |||
7874 | SemaRef.diagnoseTypo( | |||
7875 | Correction, | |||
7876 | SemaRef.PDiag(IsLocalFriend | |||
7877 | ? diag::err_no_matching_local_friend_suggest | |||
7878 | : diag::err_member_decl_does_not_match_suggest) | |||
7879 | << Name << NewDC << IsDefinition); | |||
7880 | return Result; | |||
7881 | } | |||
7882 | ||||
7883 | // Pretend the typo correction never occurred | |||
7884 | ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), | |||
7885 | ExtraArgs.D.getIdentifierLoc()); | |||
7886 | ExtraArgs.D.setRedeclaration(wasRedeclaration); | |||
7887 | Previous.clear(); | |||
7888 | Previous.setLookupName(Name); | |||
7889 | } | |||
7890 | ||||
7891 | SemaRef.Diag(NewFD->getLocation(), DiagMsg) | |||
7892 | << Name << NewDC << IsDefinition << NewFD->getLocation(); | |||
7893 | ||||
7894 | bool NewFDisConst = false; | |||
7895 | if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) | |||
7896 | NewFDisConst = NewMD->isConst(); | |||
7897 | ||||
7898 | for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator | |||
7899 | NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); | |||
7900 | NearMatch != NearMatchEnd; ++NearMatch) { | |||
7901 | FunctionDecl *FD = NearMatch->first; | |||
7902 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | |||
7903 | bool FDisConst = MD && MD->isConst(); | |||
7904 | bool IsMember = MD || !IsLocalFriend; | |||
7905 | ||||
7906 | // FIXME: These notes are poorly worded for the local friend case. | |||
7907 | if (unsigned Idx = NearMatch->second) { | |||
7908 | ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); | |||
7909 | SourceLocation Loc = FDParam->getTypeSpecStartLoc(); | |||
7910 | if (Loc.isInvalid()) Loc = FD->getLocation(); | |||
7911 | SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match | |||
7912 | : diag::note_local_decl_close_param_match) | |||
7913 | << Idx << FDParam->getType() | |||
7914 | << NewFD->getParamDecl(Idx - 1)->getType(); | |||
7915 | } else if (FDisConst != NewFDisConst) { | |||
7916 | SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) | |||
7917 | << NewFDisConst << FD->getSourceRange().getEnd(); | |||
7918 | } else | |||
7919 | SemaRef.Diag(FD->getLocation(), | |||
7920 | IsMember ? diag::note_member_def_close_match | |||
7921 | : diag::note_local_decl_close_match); | |||
7922 | } | |||
7923 | return nullptr; | |||
7924 | } | |||
7925 | ||||
7926 | static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { | |||
7927 | switch (D.getDeclSpec().getStorageClassSpec()) { | |||
7928 | default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 7928); | |||
7929 | case DeclSpec::SCS_auto: | |||
7930 | case DeclSpec::SCS_register: | |||
7931 | case DeclSpec::SCS_mutable: | |||
7932 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
7933 | diag::err_typecheck_sclass_func); | |||
7934 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | |||
7935 | D.setInvalidType(); | |||
7936 | break; | |||
7937 | case DeclSpec::SCS_unspecified: break; | |||
7938 | case DeclSpec::SCS_extern: | |||
7939 | if (D.getDeclSpec().isExternInLinkageSpec()) | |||
7940 | return SC_None; | |||
7941 | return SC_Extern; | |||
7942 | case DeclSpec::SCS_static: { | |||
7943 | if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { | |||
7944 | // C99 6.7.1p5: | |||
7945 | // The declaration of an identifier for a function that has | |||
7946 | // block scope shall have no explicit storage-class specifier | |||
7947 | // other than extern | |||
7948 | // See also (C++ [dcl.stc]p4). | |||
7949 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
7950 | diag::err_static_block_func); | |||
7951 | break; | |||
7952 | } else | |||
7953 | return SC_Static; | |||
7954 | } | |||
7955 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | |||
7956 | } | |||
7957 | ||||
7958 | // No explicit storage class has already been returned | |||
7959 | return SC_None; | |||
7960 | } | |||
7961 | ||||
7962 | static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, | |||
7963 | DeclContext *DC, QualType &R, | |||
7964 | TypeSourceInfo *TInfo, | |||
7965 | StorageClass SC, | |||
7966 | bool &IsVirtualOkay) { | |||
7967 | DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); | |||
7968 | DeclarationName Name = NameInfo.getName(); | |||
7969 | ||||
7970 | FunctionDecl *NewFD = nullptr; | |||
7971 | bool isInline = D.getDeclSpec().isInlineSpecified(); | |||
7972 | ||||
7973 | if (!SemaRef.getLangOpts().CPlusPlus) { | |||
7974 | // Determine whether the function was written with a | |||
7975 | // prototype. This true when: | |||
7976 | // - there is a prototype in the declarator, or | |||
7977 | // - the type R of the function is some kind of typedef or other non- | |||
7978 | // attributed reference to a type name (which eventually refers to a | |||
7979 | // function type). | |||
7980 | bool HasPrototype = | |||
7981 | (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || | |||
7982 | (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); | |||
7983 | ||||
7984 | NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, | |||
7985 | R, TInfo, SC, isInline, HasPrototype, false); | |||
7986 | if (D.isInvalidType()) | |||
7987 | NewFD->setInvalidDecl(); | |||
7988 | ||||
7989 | return NewFD; | |||
7990 | } | |||
7991 | ||||
7992 | ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); | |||
7993 | bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); | |||
7994 | ||||
7995 | // Check that the return type is not an abstract class type. | |||
7996 | // For record types, this is done by the AbstractClassUsageDiagnoser once | |||
7997 | // the class has been completely parsed. | |||
7998 | if (!DC->isRecord() && | |||
7999 | SemaRef.RequireNonAbstractType( | |||
8000 | D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), | |||
8001 | diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) | |||
8002 | D.setInvalidType(); | |||
8003 | ||||
8004 | if (Name.getNameKind() == DeclarationName::CXXConstructorName) { | |||
8005 | // This is a C++ constructor declaration. | |||
8006 | assert(DC->isRecord() &&((DC->isRecord() && "Constructors can only be declared in a member context" ) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8007, __PRETTY_FUNCTION__)) | |||
8007 | "Constructors can only be declared in a member context")((DC->isRecord() && "Constructors can only be declared in a member context" ) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8007, __PRETTY_FUNCTION__)); | |||
8008 | ||||
8009 | R = SemaRef.CheckConstructorDeclarator(D, R, SC); | |||
8010 | return CXXConstructorDecl::Create( | |||
8011 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | |||
8012 | TInfo, ExplicitSpecifier, isInline, | |||
8013 | /*isImplicitlyDeclared=*/false, isConstexpr); | |||
8014 | ||||
8015 | } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | |||
8016 | // This is a C++ destructor declaration. | |||
8017 | if (DC->isRecord()) { | |||
8018 | R = SemaRef.CheckDestructorDeclarator(D, R, SC); | |||
8019 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); | |||
8020 | CXXDestructorDecl *NewDD = | |||
8021 | CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(), | |||
8022 | NameInfo, R, TInfo, isInline, | |||
8023 | /*isImplicitlyDeclared=*/false); | |||
8024 | ||||
8025 | // If the destructor needs an implicit exception specification, set it | |||
8026 | // now. FIXME: It'd be nice to be able to create the right type to start | |||
8027 | // with, but the type needs to reference the destructor declaration. | |||
8028 | if (SemaRef.getLangOpts().CPlusPlus11) | |||
8029 | SemaRef.AdjustDestructorExceptionSpec(NewDD); | |||
8030 | ||||
8031 | IsVirtualOkay = true; | |||
8032 | return NewDD; | |||
8033 | ||||
8034 | } else { | |||
8035 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); | |||
8036 | D.setInvalidType(); | |||
8037 | ||||
8038 | // Create a FunctionDecl to satisfy the function definition parsing | |||
8039 | // code path. | |||
8040 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | |||
8041 | D.getIdentifierLoc(), Name, R, TInfo, SC, | |||
8042 | isInline, | |||
8043 | /*hasPrototype=*/true, isConstexpr); | |||
8044 | } | |||
8045 | ||||
8046 | } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | |||
8047 | if (!DC->isRecord()) { | |||
8048 | SemaRef.Diag(D.getIdentifierLoc(), | |||
8049 | diag::err_conv_function_not_member); | |||
8050 | return nullptr; | |||
8051 | } | |||
8052 | ||||
8053 | SemaRef.CheckConversionDeclarator(D, R, SC); | |||
8054 | IsVirtualOkay = true; | |||
8055 | return CXXConversionDecl::Create( | |||
8056 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | |||
8057 | TInfo, isInline, ExplicitSpecifier, isConstexpr, SourceLocation()); | |||
8058 | ||||
8059 | } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { | |||
8060 | SemaRef.CheckDeductionGuideDeclarator(D, R, SC); | |||
8061 | ||||
8062 | return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | |||
8063 | ExplicitSpecifier, NameInfo, R, TInfo, | |||
8064 | D.getEndLoc()); | |||
8065 | } else if (DC->isRecord()) { | |||
8066 | // If the name of the function is the same as the name of the record, | |||
8067 | // then this must be an invalid constructor that has a return type. | |||
8068 | // (The parser checks for a return type and makes the declarator a | |||
8069 | // constructor if it has no return type). | |||
8070 | if (Name.getAsIdentifierInfo() && | |||
8071 | Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ | |||
8072 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) | |||
8073 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | |||
8074 | << SourceRange(D.getIdentifierLoc()); | |||
8075 | return nullptr; | |||
8076 | } | |||
8077 | ||||
8078 | // This is a C++ method declaration. | |||
8079 | CXXMethodDecl *Ret = CXXMethodDecl::Create( | |||
8080 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | |||
8081 | TInfo, SC, isInline, isConstexpr, SourceLocation()); | |||
8082 | IsVirtualOkay = !Ret->isStatic(); | |||
8083 | return Ret; | |||
8084 | } else { | |||
8085 | bool isFriend = | |||
8086 | SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); | |||
8087 | if (!isFriend && SemaRef.CurContext->isRecord()) | |||
8088 | return nullptr; | |||
8089 | ||||
8090 | // Determine whether the function was written with a | |||
8091 | // prototype. This true when: | |||
8092 | // - we're in C++ (where every function has a prototype), | |||
8093 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, | |||
8094 | R, TInfo, SC, isInline, true /*HasPrototype*/, | |||
8095 | isConstexpr); | |||
8096 | } | |||
8097 | } | |||
8098 | ||||
8099 | enum OpenCLParamType { | |||
8100 | ValidKernelParam, | |||
8101 | PtrPtrKernelParam, | |||
8102 | PtrKernelParam, | |||
8103 | InvalidAddrSpacePtrKernelParam, | |||
8104 | InvalidKernelParam, | |||
8105 | RecordKernelParam | |||
8106 | }; | |||
8107 | ||||
8108 | static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { | |||
8109 | // Size dependent types are just typedefs to normal integer types | |||
8110 | // (e.g. unsigned long), so we cannot distinguish them from other typedefs to | |||
8111 | // integers other than by their names. | |||
8112 | StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; | |||
8113 | ||||
8114 | // Remove typedefs one by one until we reach a typedef | |||
8115 | // for a size dependent type. | |||
8116 | QualType DesugaredTy = Ty; | |||
8117 | do { | |||
8118 | ArrayRef<StringRef> Names(SizeTypeNames); | |||
8119 | auto Match = llvm::find(Names, DesugaredTy.getAsString()); | |||
8120 | if (Names.end() != Match) | |||
8121 | return true; | |||
8122 | ||||
8123 | Ty = DesugaredTy; | |||
8124 | DesugaredTy = Ty.getSingleStepDesugaredType(C); | |||
8125 | } while (DesugaredTy != Ty); | |||
8126 | ||||
8127 | return false; | |||
8128 | } | |||
8129 | ||||
8130 | static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { | |||
8131 | if (PT->isPointerType()) { | |||
8132 | QualType PointeeType = PT->getPointeeType(); | |||
8133 | if (PointeeType->isPointerType()) | |||
8134 | return PtrPtrKernelParam; | |||
8135 | if (PointeeType.getAddressSpace() == LangAS::opencl_generic || | |||
8136 | PointeeType.getAddressSpace() == LangAS::opencl_private || | |||
8137 | PointeeType.getAddressSpace() == LangAS::Default) | |||
8138 | return InvalidAddrSpacePtrKernelParam; | |||
8139 | return PtrKernelParam; | |||
8140 | } | |||
8141 | ||||
8142 | // OpenCL v1.2 s6.9.k: | |||
8143 | // Arguments to kernel functions in a program cannot be declared with the | |||
8144 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | |||
8145 | // uintptr_t or a struct and/or union that contain fields declared to be one | |||
8146 | // of these built-in scalar types. | |||
8147 | if (isOpenCLSizeDependentType(S.getASTContext(), PT)) | |||
8148 | return InvalidKernelParam; | |||
8149 | ||||
8150 | if (PT->isImageType()) | |||
8151 | return PtrKernelParam; | |||
8152 | ||||
8153 | if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) | |||
8154 | return InvalidKernelParam; | |||
8155 | ||||
8156 | // OpenCL extension spec v1.2 s9.5: | |||
8157 | // This extension adds support for half scalar and vector types as built-in | |||
8158 | // types that can be used for arithmetic operations, conversions etc. | |||
8159 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) | |||
8160 | return InvalidKernelParam; | |||
8161 | ||||
8162 | if (PT->isRecordType()) | |||
8163 | return RecordKernelParam; | |||
8164 | ||||
8165 | // Look into an array argument to check if it has a forbidden type. | |||
8166 | if (PT->isArrayType()) { | |||
8167 | const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); | |||
8168 | // Call ourself to check an underlying type of an array. Since the | |||
8169 | // getPointeeOrArrayElementType returns an innermost type which is not an | |||
8170 | // array, this recursive call only happens once. | |||
8171 | return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); | |||
8172 | } | |||
8173 | ||||
8174 | return ValidKernelParam; | |||
8175 | } | |||
8176 | ||||
8177 | static void checkIsValidOpenCLKernelParameter( | |||
8178 | Sema &S, | |||
8179 | Declarator &D, | |||
8180 | ParmVarDecl *Param, | |||
8181 | llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { | |||
8182 | QualType PT = Param->getType(); | |||
8183 | ||||
8184 | // Cache the valid types we encounter to avoid rechecking structs that are | |||
8185 | // used again | |||
8186 | if (ValidTypes.count(PT.getTypePtr())) | |||
8187 | return; | |||
8188 | ||||
8189 | switch (getOpenCLKernelParameterType(S, PT)) { | |||
8190 | case PtrPtrKernelParam: | |||
8191 | // OpenCL v1.2 s6.9.a: | |||
8192 | // A kernel function argument cannot be declared as a | |||
8193 | // pointer to a pointer type. | |||
8194 | S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); | |||
8195 | D.setInvalidType(); | |||
8196 | return; | |||
8197 | ||||
8198 | case InvalidAddrSpacePtrKernelParam: | |||
8199 | // OpenCL v1.0 s6.5: | |||
8200 | // __kernel function arguments declared to be a pointer of a type can point | |||
8201 | // to one of the following address spaces only : __global, __local or | |||
8202 | // __constant. | |||
8203 | S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); | |||
8204 | D.setInvalidType(); | |||
8205 | return; | |||
8206 | ||||
8207 | // OpenCL v1.2 s6.9.k: | |||
8208 | // Arguments to kernel functions in a program cannot be declared with the | |||
8209 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | |||
8210 | // uintptr_t or a struct and/or union that contain fields declared to be | |||
8211 | // one of these built-in scalar types. | |||
8212 | ||||
8213 | case InvalidKernelParam: | |||
8214 | // OpenCL v1.2 s6.8 n: | |||
8215 | // A kernel function argument cannot be declared | |||
8216 | // of event_t type. | |||
8217 | // Do not diagnose half type since it is diagnosed as invalid argument | |||
8218 | // type for any function elsewhere. | |||
8219 | if (!PT->isHalfType()) { | |||
8220 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | |||
8221 | ||||
8222 | // Explain what typedefs are involved. | |||
8223 | const TypedefType *Typedef = nullptr; | |||
8224 | while ((Typedef = PT->getAs<TypedefType>())) { | |||
8225 | SourceLocation Loc = Typedef->getDecl()->getLocation(); | |||
8226 | // SourceLocation may be invalid for a built-in type. | |||
8227 | if (Loc.isValid()) | |||
8228 | S.Diag(Loc, diag::note_entity_declared_at) << PT; | |||
8229 | PT = Typedef->desugar(); | |||
8230 | } | |||
8231 | } | |||
8232 | ||||
8233 | D.setInvalidType(); | |||
8234 | return; | |||
8235 | ||||
8236 | case PtrKernelParam: | |||
8237 | case ValidKernelParam: | |||
8238 | ValidTypes.insert(PT.getTypePtr()); | |||
8239 | return; | |||
8240 | ||||
8241 | case RecordKernelParam: | |||
8242 | break; | |||
8243 | } | |||
8244 | ||||
8245 | // Track nested structs we will inspect | |||
8246 | SmallVector<const Decl *, 4> VisitStack; | |||
8247 | ||||
8248 | // Track where we are in the nested structs. Items will migrate from | |||
8249 | // VisitStack to HistoryStack as we do the DFS for bad field. | |||
8250 | SmallVector<const FieldDecl *, 4> HistoryStack; | |||
8251 | HistoryStack.push_back(nullptr); | |||
8252 | ||||
8253 | // At this point we already handled everything except of a RecordType or | |||
8254 | // an ArrayType of a RecordType. | |||
8255 | assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(((PT->isArrayType() || PT->isRecordType()) && "Unexpected type." ) ? static_cast<void> (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8255, __PRETTY_FUNCTION__)); | |||
8256 | const RecordType *RecTy = | |||
8257 | PT->getPointeeOrArrayElementType()->getAs<RecordType>(); | |||
8258 | const RecordDecl *OrigRecDecl = RecTy->getDecl(); | |||
8259 | ||||
8260 | VisitStack.push_back(RecTy->getDecl()); | |||
8261 | assert(VisitStack.back() && "First decl null?")((VisitStack.back() && "First decl null?") ? static_cast <void> (0) : __assert_fail ("VisitStack.back() && \"First decl null?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8261, __PRETTY_FUNCTION__)); | |||
8262 | ||||
8263 | do { | |||
8264 | const Decl *Next = VisitStack.pop_back_val(); | |||
8265 | if (!Next) { | |||
8266 | assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail ("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8266, __PRETTY_FUNCTION__)); | |||
8267 | // Found a marker, we have gone up a level | |||
8268 | if (const FieldDecl *Hist = HistoryStack.pop_back_val()) | |||
8269 | ValidTypes.insert(Hist->getType().getTypePtr()); | |||
8270 | ||||
8271 | continue; | |||
8272 | } | |||
8273 | ||||
8274 | // Adds everything except the original parameter declaration (which is not a | |||
8275 | // field itself) to the history stack. | |||
8276 | const RecordDecl *RD; | |||
8277 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { | |||
8278 | HistoryStack.push_back(Field); | |||
8279 | ||||
8280 | QualType FieldTy = Field->getType(); | |||
8281 | // Other field types (known to be valid or invalid) are handled while we | |||
8282 | // walk around RecordDecl::fields(). | |||
8283 | assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8284, __PRETTY_FUNCTION__)) | |||
8284 | "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8284, __PRETTY_FUNCTION__)); | |||
8285 | const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); | |||
8286 | ||||
8287 | RD = FieldRecTy->castAs<RecordType>()->getDecl(); | |||
8288 | } else { | |||
8289 | RD = cast<RecordDecl>(Next); | |||
8290 | } | |||
8291 | ||||
8292 | // Add a null marker so we know when we've gone back up a level | |||
8293 | VisitStack.push_back(nullptr); | |||
8294 | ||||
8295 | for (const auto *FD : RD->fields()) { | |||
8296 | QualType QT = FD->getType(); | |||
8297 | ||||
8298 | if (ValidTypes.count(QT.getTypePtr())) | |||
8299 | continue; | |||
8300 | ||||
8301 | OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); | |||
8302 | if (ParamType == ValidKernelParam) | |||
8303 | continue; | |||
8304 | ||||
8305 | if (ParamType == RecordKernelParam) { | |||
8306 | VisitStack.push_back(FD); | |||
8307 | continue; | |||
8308 | } | |||
8309 | ||||
8310 | // OpenCL v1.2 s6.9.p: | |||
8311 | // Arguments to kernel functions that are declared to be a struct or union | |||
8312 | // do not allow OpenCL objects to be passed as elements of the struct or | |||
8313 | // union. | |||
8314 | if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || | |||
8315 | ParamType == InvalidAddrSpacePtrKernelParam) { | |||
8316 | S.Diag(Param->getLocation(), | |||
8317 | diag::err_record_with_pointers_kernel_param) | |||
8318 | << PT->isUnionType() | |||
8319 | << PT; | |||
8320 | } else { | |||
8321 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | |||
8322 | } | |||
8323 | ||||
8324 | S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) | |||
8325 | << OrigRecDecl->getDeclName(); | |||
8326 | ||||
8327 | // We have an error, now let's go back up through history and show where | |||
8328 | // the offending field came from | |||
8329 | for (ArrayRef<const FieldDecl *>::const_iterator | |||
8330 | I = HistoryStack.begin() + 1, | |||
8331 | E = HistoryStack.end(); | |||
8332 | I != E; ++I) { | |||
8333 | const FieldDecl *OuterField = *I; | |||
8334 | S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) | |||
8335 | << OuterField->getType(); | |||
8336 | } | |||
8337 | ||||
8338 | S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) | |||
8339 | << QT->isPointerType() | |||
8340 | << QT; | |||
8341 | D.setInvalidType(); | |||
8342 | return; | |||
8343 | } | |||
8344 | } while (!VisitStack.empty()); | |||
8345 | } | |||
8346 | ||||
8347 | /// Find the DeclContext in which a tag is implicitly declared if we see an | |||
8348 | /// elaborated type specifier in the specified context, and lookup finds | |||
8349 | /// nothing. | |||
8350 | static DeclContext *getTagInjectionContext(DeclContext *DC) { | |||
8351 | while (!DC->isFileContext() && !DC->isFunctionOrMethod()) | |||
8352 | DC = DC->getParent(); | |||
8353 | return DC; | |||
8354 | } | |||
8355 | ||||
8356 | /// Find the Scope in which a tag is implicitly declared if we see an | |||
8357 | /// elaborated type specifier in the specified context, and lookup finds | |||
8358 | /// nothing. | |||
8359 | static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { | |||
8360 | while (S->isClassScope() || | |||
8361 | (LangOpts.CPlusPlus && | |||
8362 | S->isFunctionPrototypeScope()) || | |||
8363 | ((S->getFlags() & Scope::DeclScope) == 0) || | |||
8364 | (S->getEntity() && S->getEntity()->isTransparentContext())) | |||
8365 | S = S->getParent(); | |||
8366 | return S; | |||
8367 | } | |||
8368 | ||||
8369 | NamedDecl* | |||
8370 | Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, | |||
8371 | TypeSourceInfo *TInfo, LookupResult &Previous, | |||
8372 | MultiTemplateParamsArg TemplateParamLists, | |||
8373 | bool &AddToScope) { | |||
8374 | QualType R = TInfo->getType(); | |||
8375 | ||||
8376 | assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("R->isFunctionType()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8376, __PRETTY_FUNCTION__)); | |||
8377 | ||||
8378 | // TODO: consider using NameInfo for diagnostic. | |||
8379 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | |||
8380 | DeclarationName Name = NameInfo.getName(); | |||
8381 | StorageClass SC = getFunctionStorageClass(*this, D); | |||
8382 | ||||
8383 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | |||
8384 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
8385 | diag::err_invalid_thread) | |||
8386 | << DeclSpec::getSpecifierName(TSCS); | |||
8387 | ||||
8388 | if (D.isFirstDeclarationOfMember()) | |||
8389 | adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), | |||
8390 | D.getIdentifierLoc()); | |||
8391 | ||||
8392 | bool isFriend = false; | |||
8393 | FunctionTemplateDecl *FunctionTemplate = nullptr; | |||
8394 | bool isMemberSpecialization = false; | |||
8395 | bool isFunctionTemplateSpecialization = false; | |||
8396 | ||||
8397 | bool isDependentClassScopeExplicitSpecialization = false; | |||
8398 | bool HasExplicitTemplateArgs = false; | |||
8399 | TemplateArgumentListInfo TemplateArgs; | |||
8400 | ||||
8401 | bool isVirtualOkay = false; | |||
8402 | ||||
8403 | DeclContext *OriginalDC = DC; | |||
8404 | bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); | |||
8405 | ||||
8406 | FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, | |||
8407 | isVirtualOkay); | |||
8408 | if (!NewFD) return nullptr; | |||
8409 | ||||
8410 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) | |||
8411 | NewFD->setTopLevelDeclInObjCContainer(); | |||
8412 | ||||
8413 | // Set the lexical context. If this is a function-scope declaration, or has a | |||
8414 | // C++ scope specifier, or is the object of a friend declaration, the lexical | |||
8415 | // context will be different from the semantic context. | |||
8416 | NewFD->setLexicalDeclContext(CurContext); | |||
8417 | ||||
8418 | if (IsLocalExternDecl) | |||
8419 | NewFD->setLocalExternDecl(); | |||
8420 | ||||
8421 | if (getLangOpts().CPlusPlus) { | |||
8422 | bool isInline = D.getDeclSpec().isInlineSpecified(); | |||
8423 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | |||
8424 | bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); | |||
8425 | bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); | |||
8426 | isFriend = D.getDeclSpec().isFriendSpecified(); | |||
8427 | if (isFriend && !isInline && D.isFunctionDefinition()) { | |||
8428 | // C++ [class.friend]p5 | |||
8429 | // A function can be defined in a friend declaration of a | |||
8430 | // class . . . . Such a function is implicitly inline. | |||
8431 | NewFD->setImplicitlyInline(); | |||
8432 | } | |||
8433 | ||||
8434 | // If this is a method defined in an __interface, and is not a constructor | |||
8435 | // or an overloaded operator, then set the pure flag (isVirtual will already | |||
8436 | // return true). | |||
8437 | if (const CXXRecordDecl *Parent = | |||
8438 | dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { | |||
8439 | if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) | |||
8440 | NewFD->setPure(true); | |||
8441 | ||||
8442 | // C++ [class.union]p2 | |||
8443 | // A union can have member functions, but not virtual functions. | |||
8444 | if (isVirtual && Parent->isUnion()) | |||
8445 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); | |||
8446 | } | |||
8447 | ||||
8448 | SetNestedNameSpecifier(*this, NewFD, D); | |||
8449 | isMemberSpecialization = false; | |||
8450 | isFunctionTemplateSpecialization = false; | |||
8451 | if (D.isInvalidType()) | |||
8452 | NewFD->setInvalidDecl(); | |||
8453 | ||||
8454 | // Match up the template parameter lists with the scope specifier, then | |||
8455 | // determine whether we have a template or a template specialization. | |||
8456 | bool Invalid = false; | |||
8457 | if (TemplateParameterList *TemplateParams = | |||
8458 | MatchTemplateParametersToScopeSpecifier( | |||
8459 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | |||
8460 | D.getCXXScopeSpec(), | |||
8461 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | |||
8462 | ? D.getName().TemplateId | |||
8463 | : nullptr, | |||
8464 | TemplateParamLists, isFriend, isMemberSpecialization, | |||
8465 | Invalid)) { | |||
8466 | if (TemplateParams->size() > 0) { | |||
8467 | // This is a function template | |||
8468 | ||||
8469 | // Check that we can declare a template here. | |||
8470 | if (CheckTemplateDeclScope(S, TemplateParams)) | |||
8471 | NewFD->setInvalidDecl(); | |||
8472 | ||||
8473 | // A destructor cannot be a template. | |||
8474 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | |||
8475 | Diag(NewFD->getLocation(), diag::err_destructor_template); | |||
8476 | NewFD->setInvalidDecl(); | |||
8477 | } | |||
8478 | ||||
8479 | // If we're adding a template to a dependent context, we may need to | |||
8480 | // rebuilding some of the types used within the template parameter list, | |||
8481 | // now that we know what the current instantiation is. | |||
8482 | if (DC->isDependentContext()) { | |||
8483 | ContextRAII SavedContext(*this, DC); | |||
8484 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) | |||
8485 | Invalid = true; | |||
8486 | } | |||
8487 | ||||
8488 | FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, | |||
8489 | NewFD->getLocation(), | |||
8490 | Name, TemplateParams, | |||
8491 | NewFD); | |||
8492 | FunctionTemplate->setLexicalDeclContext(CurContext); | |||
8493 | NewFD->setDescribedFunctionTemplate(FunctionTemplate); | |||
8494 | ||||
8495 | // For source fidelity, store the other template param lists. | |||
8496 | if (TemplateParamLists.size() > 1) { | |||
8497 | NewFD->setTemplateParameterListsInfo(Context, | |||
8498 | TemplateParamLists.drop_back(1)); | |||
8499 | } | |||
8500 | } else { | |||
8501 | // This is a function template specialization. | |||
8502 | isFunctionTemplateSpecialization = true; | |||
8503 | // For source fidelity, store all the template param lists. | |||
8504 | if (TemplateParamLists.size() > 0) | |||
8505 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | |||
8506 | ||||
8507 | // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". | |||
8508 | if (isFriend) { | |||
8509 | // We want to remove the "template<>", found here. | |||
8510 | SourceRange RemoveRange = TemplateParams->getSourceRange(); | |||
8511 | ||||
8512 | // If we remove the template<> and the name is not a | |||
8513 | // template-id, we're actually silently creating a problem: | |||
8514 | // the friend declaration will refer to an untemplated decl, | |||
8515 | // and clearly the user wants a template specialization. So | |||
8516 | // we need to insert '<>' after the name. | |||
8517 | SourceLocation InsertLoc; | |||
8518 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | |||
8519 | InsertLoc = D.getName().getSourceRange().getEnd(); | |||
8520 | InsertLoc = getLocForEndOfToken(InsertLoc); | |||
8521 | } | |||
8522 | ||||
8523 | Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) | |||
8524 | << Name << RemoveRange | |||
8525 | << FixItHint::CreateRemoval(RemoveRange) | |||
8526 | << FixItHint::CreateInsertion(InsertLoc, "<>"); | |||
8527 | } | |||
8528 | } | |||
8529 | } else { | |||
8530 | // All template param lists were matched against the scope specifier: | |||
8531 | // this is NOT (an explicit specialization of) a template. | |||
8532 | if (TemplateParamLists.size() > 0) | |||
8533 | // For source fidelity, store all the template param lists. | |||
8534 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | |||
8535 | } | |||
8536 | ||||
8537 | if (Invalid) { | |||
8538 | NewFD->setInvalidDecl(); | |||
8539 | if (FunctionTemplate) | |||
8540 | FunctionTemplate->setInvalidDecl(); | |||
8541 | } | |||
8542 | ||||
8543 | // C++ [dcl.fct.spec]p5: | |||
8544 | // The virtual specifier shall only be used in declarations of | |||
8545 | // nonstatic class member functions that appear within a | |||
8546 | // member-specification of a class declaration; see 10.3. | |||
8547 | // | |||
8548 | if (isVirtual && !NewFD->isInvalidDecl()) { | |||
8549 | if (!isVirtualOkay) { | |||
8550 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | |||
8551 | diag::err_virtual_non_function); | |||
8552 | } else if (!CurContext->isRecord()) { | |||
8553 | // 'virtual' was specified outside of the class. | |||
8554 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | |||
8555 | diag::err_virtual_out_of_class) | |||
8556 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | |||
8557 | } else if (NewFD->getDescribedFunctionTemplate()) { | |||
8558 | // C++ [temp.mem]p3: | |||
8559 | // A member function template shall not be virtual. | |||
8560 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | |||
8561 | diag::err_virtual_member_function_template) | |||
8562 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | |||
8563 | } else { | |||
8564 | // Okay: Add virtual to the method. | |||
8565 | NewFD->setVirtualAsWritten(true); | |||
8566 | } | |||
8567 | ||||
8568 | if (getLangOpts().CPlusPlus14 && | |||
8569 | NewFD->getReturnType()->isUndeducedType()) | |||
8570 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); | |||
8571 | } | |||
8572 | ||||
8573 | if (getLangOpts().CPlusPlus14 && | |||
8574 | (NewFD->isDependentContext() || | |||
8575 | (isFriend && CurContext->isDependentContext())) && | |||
8576 | NewFD->getReturnType()->isUndeducedType()) { | |||
8577 | // If the function template is referenced directly (for instance, as a | |||
8578 | // member of the current instantiation), pretend it has a dependent type. | |||
8579 | // This is not really justified by the standard, but is the only sane | |||
8580 | // thing to do. | |||
8581 | // FIXME: For a friend function, we have not marked the function as being | |||
8582 | // a friend yet, so 'isDependentContext' on the FD doesn't work. | |||
8583 | const FunctionProtoType *FPT = | |||
8584 | NewFD->getType()->castAs<FunctionProtoType>(); | |||
8585 | QualType Result = | |||
8586 | SubstAutoType(FPT->getReturnType(), Context.DependentTy); | |||
8587 | NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), | |||
8588 | FPT->getExtProtoInfo())); | |||
8589 | } | |||
8590 | ||||
8591 | // C++ [dcl.fct.spec]p3: | |||
8592 | // The inline specifier shall not appear on a block scope function | |||
8593 | // declaration. | |||
8594 | if (isInline && !NewFD->isInvalidDecl()) { | |||
8595 | if (CurContext->isFunctionOrMethod()) { | |||
8596 | // 'inline' is not allowed on block scope function declaration. | |||
8597 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
8598 | diag::err_inline_declaration_block_scope) << Name | |||
8599 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | |||
8600 | } | |||
8601 | } | |||
8602 | ||||
8603 | // C++ [dcl.fct.spec]p6: | |||
8604 | // The explicit specifier shall be used only in the declaration of a | |||
8605 | // constructor or conversion function within its class definition; | |||
8606 | // see 12.3.1 and 12.3.2. | |||
8607 | if (hasExplicit && !NewFD->isInvalidDecl() && | |||
8608 | !isa<CXXDeductionGuideDecl>(NewFD)) { | |||
8609 | if (!CurContext->isRecord()) { | |||
8610 | // 'explicit' was specified outside of the class. | |||
8611 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | |||
8612 | diag::err_explicit_out_of_class) | |||
8613 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | |||
8614 | } else if (!isa<CXXConstructorDecl>(NewFD) && | |||
8615 | !isa<CXXConversionDecl>(NewFD)) { | |||
8616 | // 'explicit' was specified on a function that wasn't a constructor | |||
8617 | // or conversion function. | |||
8618 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | |||
8619 | diag::err_explicit_non_ctor_or_conv_function) | |||
8620 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | |||
8621 | } | |||
8622 | } | |||
8623 | ||||
8624 | if (isConstexpr) { | |||
8625 | // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors | |||
8626 | // are implicitly inline. | |||
8627 | NewFD->setImplicitlyInline(); | |||
8628 | ||||
8629 | // C++11 [dcl.constexpr]p3: functions declared constexpr are required to | |||
8630 | // be either constructors or to return a literal type. Therefore, | |||
8631 | // destructors cannot be declared constexpr. | |||
8632 | if (isa<CXXDestructorDecl>(NewFD)) | |||
8633 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); | |||
8634 | } | |||
8635 | ||||
8636 | // If __module_private__ was specified, mark the function accordingly. | |||
8637 | if (D.getDeclSpec().isModulePrivateSpecified()) { | |||
8638 | if (isFunctionTemplateSpecialization) { | |||
8639 | SourceLocation ModulePrivateLoc | |||
8640 | = D.getDeclSpec().getModulePrivateSpecLoc(); | |||
8641 | Diag(ModulePrivateLoc, diag::err_module_private_specialization) | |||
8642 | << 0 | |||
8643 | << FixItHint::CreateRemoval(ModulePrivateLoc); | |||
8644 | } else { | |||
8645 | NewFD->setModulePrivate(); | |||
8646 | if (FunctionTemplate) | |||
8647 | FunctionTemplate->setModulePrivate(); | |||
8648 | } | |||
8649 | } | |||
8650 | ||||
8651 | if (isFriend) { | |||
8652 | if (FunctionTemplate) { | |||
8653 | FunctionTemplate->setObjectOfFriendDecl(); | |||
8654 | FunctionTemplate->setAccess(AS_public); | |||
8655 | } | |||
8656 | NewFD->setObjectOfFriendDecl(); | |||
8657 | NewFD->setAccess(AS_public); | |||
8658 | } | |||
8659 | ||||
8660 | // If a function is defined as defaulted or deleted, mark it as such now. | |||
8661 | // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function | |||
8662 | // definition kind to FDK_Definition. | |||
8663 | switch (D.getFunctionDefinitionKind()) { | |||
8664 | case FDK_Declaration: | |||
8665 | case FDK_Definition: | |||
8666 | break; | |||
8667 | ||||
8668 | case FDK_Defaulted: | |||
8669 | NewFD->setDefaulted(); | |||
8670 | break; | |||
8671 | ||||
8672 | case FDK_Deleted: | |||
8673 | NewFD->setDeletedAsWritten(); | |||
8674 | break; | |||
8675 | } | |||
8676 | ||||
8677 | if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && | |||
8678 | D.isFunctionDefinition()) { | |||
8679 | // C++ [class.mfct]p2: | |||
8680 | // A member function may be defined (8.4) in its class definition, in | |||
8681 | // which case it is an inline member function (7.1.2) | |||
8682 | NewFD->setImplicitlyInline(); | |||
8683 | } | |||
8684 | ||||
8685 | if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && | |||
8686 | !CurContext->isRecord()) { | |||
8687 | // C++ [class.static]p1: | |||
8688 | // A data or function member of a class may be declared static | |||
8689 | // in a class definition, in which case it is a static member of | |||
8690 | // the class. | |||
8691 | ||||
8692 | // Complain about the 'static' specifier if it's on an out-of-line | |||
8693 | // member function definition. | |||
8694 | ||||
8695 | // MSVC permits the use of a 'static' storage specifier on an out-of-line | |||
8696 | // member function template declaration and class member template | |||
8697 | // declaration (MSVC versions before 2015), warn about this. | |||
8698 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
8699 | ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | |||
8700 | cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || | |||
8701 | (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) | |||
8702 | ? diag::ext_static_out_of_line : diag::err_static_out_of_line) | |||
8703 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
8704 | } | |||
8705 | ||||
8706 | // C++11 [except.spec]p15: | |||
8707 | // A deallocation function with no exception-specification is treated | |||
8708 | // as if it were specified with noexcept(true). | |||
8709 | const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); | |||
8710 | if ((Name.getCXXOverloadedOperator() == OO_Delete || | |||
8711 | Name.getCXXOverloadedOperator() == OO_Array_Delete) && | |||
8712 | getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) | |||
8713 | NewFD->setType(Context.getFunctionType( | |||
8714 | FPT->getReturnType(), FPT->getParamTypes(), | |||
8715 | FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); | |||
8716 | } | |||
8717 | ||||
8718 | // Filter out previous declarations that don't match the scope. | |||
8719 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), | |||
8720 | D.getCXXScopeSpec().isNotEmpty() || | |||
8721 | isMemberSpecialization || | |||
8722 | isFunctionTemplateSpecialization); | |||
8723 | ||||
8724 | // Handle GNU asm-label extension (encoded as an attribute). | |||
8725 | if (Expr *E = (Expr*) D.getAsmLabel()) { | |||
8726 | // The parser guarantees this is a string. | |||
8727 | StringLiteral *SE = cast<StringLiteral>(E); | |||
8728 | NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, | |||
8729 | SE->getString(), 0)); | |||
8730 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | |||
8731 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | |||
8732 | ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); | |||
8733 | if (I != ExtnameUndeclaredIdentifiers.end()) { | |||
8734 | if (isDeclExternC(NewFD)) { | |||
8735 | NewFD->addAttr(I->second); | |||
8736 | ExtnameUndeclaredIdentifiers.erase(I); | |||
8737 | } else | |||
8738 | Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) | |||
8739 | << /*Variable*/0 << NewFD; | |||
8740 | } | |||
8741 | } | |||
8742 | ||||
8743 | // Copy the parameter declarations from the declarator D to the function | |||
8744 | // declaration NewFD, if they are available. First scavenge them into Params. | |||
8745 | SmallVector<ParmVarDecl*, 16> Params; | |||
8746 | unsigned FTIIdx; | |||
8747 | if (D.isFunctionDeclarator(FTIIdx)) { | |||
8748 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; | |||
8749 | ||||
8750 | // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs | |||
8751 | // function that takes no arguments, not a function that takes a | |||
8752 | // single void argument. | |||
8753 | // We let through "const void" here because Sema::GetTypeForDeclarator | |||
8754 | // already checks for that case. | |||
8755 | if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { | |||
8756 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | |||
8757 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
8758 | assert(Param->getDeclContext() != NewFD && "Was set before ?")((Param->getDeclContext() != NewFD && "Was set before ?" ) ? static_cast<void> (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8758, __PRETTY_FUNCTION__)); | |||
8759 | Param->setDeclContext(NewFD); | |||
8760 | Params.push_back(Param); | |||
8761 | ||||
8762 | if (Param->isInvalidDecl()) | |||
8763 | NewFD->setInvalidDecl(); | |||
8764 | } | |||
8765 | } | |||
8766 | ||||
8767 | if (!getLangOpts().CPlusPlus) { | |||
8768 | // In C, find all the tag declarations from the prototype and move them | |||
8769 | // into the function DeclContext. Remove them from the surrounding tag | |||
8770 | // injection context of the function, which is typically but not always | |||
8771 | // the TU. | |||
8772 | DeclContext *PrototypeTagContext = | |||
8773 | getTagInjectionContext(NewFD->getLexicalDeclContext()); | |||
8774 | for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { | |||
8775 | auto *TD = dyn_cast<TagDecl>(NonParmDecl); | |||
8776 | ||||
8777 | // We don't want to reparent enumerators. Look at their parent enum | |||
8778 | // instead. | |||
8779 | if (!TD) { | |||
8780 | if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) | |||
8781 | TD = cast<EnumDecl>(ECD->getDeclContext()); | |||
8782 | } | |||
8783 | if (!TD) | |||
8784 | continue; | |||
8785 | DeclContext *TagDC = TD->getLexicalDeclContext(); | |||
8786 | if (!TagDC->containsDecl(TD)) | |||
8787 | continue; | |||
8788 | TagDC->removeDecl(TD); | |||
8789 | TD->setDeclContext(NewFD); | |||
8790 | NewFD->addDecl(TD); | |||
8791 | ||||
8792 | // Preserve the lexical DeclContext if it is not the surrounding tag | |||
8793 | // injection context of the FD. In this example, the semantic context of | |||
8794 | // E will be f and the lexical context will be S, while both the | |||
8795 | // semantic and lexical contexts of S will be f: | |||
8796 | // void f(struct S { enum E { a } f; } s); | |||
8797 | if (TagDC != PrototypeTagContext) | |||
8798 | TD->setLexicalDeclContext(TagDC); | |||
8799 | } | |||
8800 | } | |||
8801 | } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { | |||
8802 | // When we're declaring a function with a typedef, typeof, etc as in the | |||
8803 | // following example, we'll need to synthesize (unnamed) | |||
8804 | // parameters for use in the declaration. | |||
8805 | // | |||
8806 | // @code | |||
8807 | // typedef void fn(int); | |||
8808 | // fn f; | |||
8809 | // @endcode | |||
8810 | ||||
8811 | // Synthesize a parameter for each argument type. | |||
8812 | for (const auto &AI : FT->param_types()) { | |||
8813 | ParmVarDecl *Param = | |||
8814 | BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); | |||
8815 | Param->setScopeInfo(0, Params.size()); | |||
8816 | Params.push_back(Param); | |||
8817 | } | |||
8818 | } else { | |||
8819 | assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&((R->isFunctionNoProtoType() && NewFD->getNumParams () == 0 && "Should not need args for typedef of non-prototype fn" ) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8820, __PRETTY_FUNCTION__)) | |||
8820 | "Should not need args for typedef of non-prototype fn")((R->isFunctionNoProtoType() && NewFD->getNumParams () == 0 && "Should not need args for typedef of non-prototype fn" ) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8820, __PRETTY_FUNCTION__)); | |||
8821 | } | |||
8822 | ||||
8823 | // Finally, we know we have the right number of parameters, install them. | |||
8824 | NewFD->setParams(Params); | |||
8825 | ||||
8826 | if (D.getDeclSpec().isNoreturnSpecified()) | |||
8827 | NewFD->addAttr( | |||
8828 | ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), | |||
8829 | Context, 0)); | |||
8830 | ||||
8831 | // Functions returning a variably modified type violate C99 6.7.5.2p2 | |||
8832 | // because all functions have linkage. | |||
8833 | if (!NewFD->isInvalidDecl() && | |||
8834 | NewFD->getReturnType()->isVariablyModifiedType()) { | |||
8835 | Diag(NewFD->getLocation(), diag::err_vm_func_decl); | |||
8836 | NewFD->setInvalidDecl(); | |||
8837 | } | |||
8838 | ||||
8839 | // Apply an implicit SectionAttr if '#pragma clang section text' is active | |||
8840 | if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && | |||
8841 | !NewFD->hasAttr<SectionAttr>()) { | |||
8842 | NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, | |||
8843 | PragmaClangTextSection.SectionName, | |||
8844 | PragmaClangTextSection.PragmaLocation)); | |||
8845 | } | |||
8846 | ||||
8847 | // Apply an implicit SectionAttr if #pragma code_seg is active. | |||
8848 | if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && | |||
8849 | !NewFD->hasAttr<SectionAttr>()) { | |||
8850 | NewFD->addAttr( | |||
8851 | SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, | |||
8852 | CodeSegStack.CurrentValue->getString(), | |||
8853 | CodeSegStack.CurrentPragmaLocation)); | |||
8854 | if (UnifySection(CodeSegStack.CurrentValue->getString(), | |||
8855 | ASTContext::PSF_Implicit | ASTContext::PSF_Execute | | |||
8856 | ASTContext::PSF_Read, | |||
8857 | NewFD)) | |||
8858 | NewFD->dropAttr<SectionAttr>(); | |||
8859 | } | |||
8860 | ||||
8861 | // Apply an implicit CodeSegAttr from class declspec or | |||
8862 | // apply an implicit SectionAttr from #pragma code_seg if active. | |||
8863 | if (!NewFD->hasAttr<CodeSegAttr>()) { | |||
8864 | if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, | |||
8865 | D.isFunctionDefinition())) { | |||
8866 | NewFD->addAttr(SAttr); | |||
8867 | } | |||
8868 | } | |||
8869 | ||||
8870 | // Handle attributes. | |||
8871 | ProcessDeclAttributes(S, NewFD, D); | |||
8872 | ||||
8873 | if (getLangOpts().OpenCL) { | |||
8874 | // OpenCL v1.1 s6.5: Using an address space qualifier in a function return | |||
8875 | // type declaration will generate a compilation error. | |||
8876 | LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); | |||
8877 | if (AddressSpace != LangAS::Default) { | |||
8878 | Diag(NewFD->getLocation(), | |||
8879 | diag::err_opencl_return_value_with_address_space); | |||
8880 | NewFD->setInvalidDecl(); | |||
8881 | } | |||
8882 | } | |||
8883 | ||||
8884 | if (!getLangOpts().CPlusPlus) { | |||
8885 | // Perform semantic checking on the function declaration. | |||
8886 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | |||
8887 | CheckMain(NewFD, D.getDeclSpec()); | |||
8888 | ||||
8889 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | |||
8890 | CheckMSVCRTEntryPoint(NewFD); | |||
8891 | ||||
8892 | if (!NewFD->isInvalidDecl()) | |||
8893 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | |||
8894 | isMemberSpecialization)); | |||
8895 | else if (!Previous.empty()) | |||
8896 | // Recover gracefully from an invalid redeclaration. | |||
8897 | D.setRedeclaration(true); | |||
8898 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8900, __PRETTY_FUNCTION__)) | |||
8899 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8900, __PRETTY_FUNCTION__)) | |||
8900 | "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8900, __PRETTY_FUNCTION__)); | |||
8901 | ||||
8902 | // Diagnose no-prototype function declarations with calling conventions that | |||
8903 | // don't support variadic calls. Only do this in C and do it after merging | |||
8904 | // possibly prototyped redeclarations. | |||
8905 | const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); | |||
8906 | if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { | |||
8907 | CallingConv CC = FT->getExtInfo().getCC(); | |||
8908 | if (!supportsVariadicCall(CC)) { | |||
8909 | // Windows system headers sometimes accidentally use stdcall without | |||
8910 | // (void) parameters, so we relax this to a warning. | |||
8911 | int DiagID = | |||
8912 | CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; | |||
8913 | Diag(NewFD->getLocation(), DiagID) | |||
8914 | << FunctionType::getNameForCallConv(CC); | |||
8915 | } | |||
8916 | } | |||
8917 | } else { | |||
8918 | // C++11 [replacement.functions]p3: | |||
8919 | // The program's definitions shall not be specified as inline. | |||
8920 | // | |||
8921 | // N.B. We diagnose declarations instead of definitions per LWG issue 2340. | |||
8922 | // | |||
8923 | // Suppress the diagnostic if the function is __attribute__((used)), since | |||
8924 | // that forces an external definition to be emitted. | |||
8925 | if (D.getDeclSpec().isInlineSpecified() && | |||
8926 | NewFD->isReplaceableGlobalAllocationFunction() && | |||
8927 | !NewFD->hasAttr<UsedAttr>()) | |||
8928 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
8929 | diag::ext_operator_new_delete_declared_inline) | |||
8930 | << NewFD->getDeclName(); | |||
8931 | ||||
8932 | // If the declarator is a template-id, translate the parser's template | |||
8933 | // argument list into our AST format. | |||
8934 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | |||
8935 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; | |||
8936 | TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); | |||
8937 | TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); | |||
8938 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
8939 | TemplateId->NumArgs); | |||
8940 | translateTemplateArguments(TemplateArgsPtr, | |||
8941 | TemplateArgs); | |||
8942 | ||||
8943 | HasExplicitTemplateArgs = true; | |||
8944 | ||||
8945 | if (NewFD->isInvalidDecl()) { | |||
8946 | HasExplicitTemplateArgs = false; | |||
8947 | } else if (FunctionTemplate) { | |||
8948 | // Function template with explicit template arguments. | |||
8949 | Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) | |||
8950 | << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); | |||
8951 | ||||
8952 | HasExplicitTemplateArgs = false; | |||
8953 | } else { | |||
8954 | assert((isFunctionTemplateSpecialization ||(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8956, __PRETTY_FUNCTION__)) | |||
8955 | D.getDeclSpec().isFriendSpecified()) &&(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8956, __PRETTY_FUNCTION__)) | |||
8956 | "should have a 'template<>' for this decl")(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8956, __PRETTY_FUNCTION__)); | |||
8957 | // "friend void foo<>(int);" is an implicit specialization decl. | |||
8958 | isFunctionTemplateSpecialization = true; | |||
8959 | } | |||
8960 | } else if (isFriend && isFunctionTemplateSpecialization) { | |||
8961 | // This combination is only possible in a recovery case; the user | |||
8962 | // wrote something like: | |||
8963 | // template <> friend void foo(int); | |||
8964 | // which we're recovering from as if the user had written: | |||
8965 | // friend void foo<>(int); | |||
8966 | // Go ahead and fake up a template id. | |||
8967 | HasExplicitTemplateArgs = true; | |||
8968 | TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); | |||
8969 | TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); | |||
8970 | } | |||
8971 | ||||
8972 | // We do not add HD attributes to specializations here because | |||
8973 | // they may have different constexpr-ness compared to their | |||
8974 | // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, | |||
8975 | // may end up with different effective targets. Instead, a | |||
8976 | // specialization inherits its target attributes from its template | |||
8977 | // in the CheckFunctionTemplateSpecialization() call below. | |||
8978 | if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) | |||
8979 | maybeAddCUDAHostDeviceAttrs(NewFD, Previous); | |||
8980 | ||||
8981 | // If it's a friend (and only if it's a friend), it's possible | |||
8982 | // that either the specialized function type or the specialized | |||
8983 | // template is dependent, and therefore matching will fail. In | |||
8984 | // this case, don't check the specialization yet. | |||
8985 | bool InstantiationDependent = false; | |||
8986 | if (isFunctionTemplateSpecialization && isFriend && | |||
8987 | (NewFD->getType()->isDependentType() || DC->isDependentContext() || | |||
8988 | TemplateSpecializationType::anyDependentTemplateArguments( | |||
8989 | TemplateArgs, | |||
8990 | InstantiationDependent))) { | |||
8991 | assert(HasExplicitTemplateArgs &&((HasExplicitTemplateArgs && "friend function specialization without template args" ) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8992, __PRETTY_FUNCTION__)) | |||
8992 | "friend function specialization without template args")((HasExplicitTemplateArgs && "friend function specialization without template args" ) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 8992, __PRETTY_FUNCTION__)); | |||
8993 | if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, | |||
8994 | Previous)) | |||
8995 | NewFD->setInvalidDecl(); | |||
8996 | } else if (isFunctionTemplateSpecialization) { | |||
8997 | if (CurContext->isDependentContext() && CurContext->isRecord() | |||
8998 | && !isFriend) { | |||
8999 | isDependentClassScopeExplicitSpecialization = true; | |||
9000 | } else if (!NewFD->isInvalidDecl() && | |||
9001 | CheckFunctionTemplateSpecialization( | |||
9002 | NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), | |||
9003 | Previous)) | |||
9004 | NewFD->setInvalidDecl(); | |||
9005 | ||||
9006 | // C++ [dcl.stc]p1: | |||
9007 | // A storage-class-specifier shall not be specified in an explicit | |||
9008 | // specialization (14.7.3) | |||
9009 | FunctionTemplateSpecializationInfo *Info = | |||
9010 | NewFD->getTemplateSpecializationInfo(); | |||
9011 | if (Info && SC != SC_None) { | |||
9012 | if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) | |||
9013 | Diag(NewFD->getLocation(), | |||
9014 | diag::err_explicit_specialization_inconsistent_storage_class) | |||
9015 | << SC | |||
9016 | << FixItHint::CreateRemoval( | |||
9017 | D.getDeclSpec().getStorageClassSpecLoc()); | |||
9018 | ||||
9019 | else | |||
9020 | Diag(NewFD->getLocation(), | |||
9021 | diag::ext_explicit_specialization_storage_class) | |||
9022 | << FixItHint::CreateRemoval( | |||
9023 | D.getDeclSpec().getStorageClassSpecLoc()); | |||
9024 | } | |||
9025 | } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { | |||
9026 | if (CheckMemberSpecialization(NewFD, Previous)) | |||
9027 | NewFD->setInvalidDecl(); | |||
9028 | } | |||
9029 | ||||
9030 | // Perform semantic checking on the function declaration. | |||
9031 | if (!isDependentClassScopeExplicitSpecialization) { | |||
9032 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | |||
9033 | CheckMain(NewFD, D.getDeclSpec()); | |||
9034 | ||||
9035 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | |||
9036 | CheckMSVCRTEntryPoint(NewFD); | |||
9037 | ||||
9038 | if (!NewFD->isInvalidDecl()) | |||
9039 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | |||
9040 | isMemberSpecialization)); | |||
9041 | else if (!Previous.empty()) | |||
9042 | // Recover gracefully from an invalid redeclaration. | |||
9043 | D.setRedeclaration(true); | |||
9044 | } | |||
9045 | ||||
9046 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 9048, __PRETTY_FUNCTION__)) | |||
9047 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 9048, __PRETTY_FUNCTION__)) | |||
9048 | "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 9048, __PRETTY_FUNCTION__)); | |||
9049 | ||||
9050 | NamedDecl *PrincipalDecl = (FunctionTemplate | |||
9051 | ? cast<NamedDecl>(FunctionTemplate) | |||
9052 | : NewFD); | |||
9053 | ||||
9054 | if (isFriend && NewFD->getPreviousDecl()) { | |||
9055 | AccessSpecifier Access = AS_public; | |||
9056 | if (!NewFD->isInvalidDecl()) | |||
9057 | Access = NewFD->getPreviousDecl()->getAccess(); | |||
9058 | ||||
9059 | NewFD->setAccess(Access); | |||
9060 | if (FunctionTemplate) FunctionTemplate->setAccess(Access); | |||
9061 | } | |||
9062 | ||||
9063 | if (NewFD->isOverloadedOperator() && !DC->isRecord() && | |||
9064 | PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) | |||
9065 | PrincipalDecl->setNonMemberOperator(); | |||
9066 | ||||
9067 | // If we have a function template, check the template parameter | |||
9068 | // list. This will check and merge default template arguments. | |||
9069 | if (FunctionTemplate) { | |||
9070 | FunctionTemplateDecl *PrevTemplate = | |||
9071 | FunctionTemplate->getPreviousDecl(); | |||
9072 | CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), | |||
9073 | PrevTemplate ? PrevTemplate->getTemplateParameters() | |||
9074 | : nullptr, | |||
9075 | D.getDeclSpec().isFriendSpecified() | |||
9076 | ? (D.isFunctionDefinition() | |||
9077 | ? TPC_FriendFunctionTemplateDefinition | |||
9078 | : TPC_FriendFunctionTemplate) | |||
9079 | : (D.getCXXScopeSpec().isSet() && | |||
9080 | DC && DC->isRecord() && | |||
9081 | DC->isDependentContext()) | |||
9082 | ? TPC_ClassTemplateMember | |||
9083 | : TPC_FunctionTemplate); | |||
9084 | } | |||
9085 | ||||
9086 | if (NewFD->isInvalidDecl()) { | |||
9087 | // Ignore all the rest of this. | |||
9088 | } else if (!D.isRedeclaration()) { | |||
9089 | struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, | |||
9090 | AddToScope }; | |||
9091 | // Fake up an access specifier if it's supposed to be a class member. | |||
9092 | if (isa<CXXRecordDecl>(NewFD->getDeclContext())) | |||
9093 | NewFD->setAccess(AS_public); | |||
9094 | ||||
9095 | // Qualified decls generally require a previous declaration. | |||
9096 | if (D.getCXXScopeSpec().isSet()) { | |||
9097 | // ...with the major exception of templated-scope or | |||
9098 | // dependent-scope friend declarations. | |||
9099 | ||||
9100 | // TODO: we currently also suppress this check in dependent | |||
9101 | // contexts because (1) the parameter depth will be off when | |||
9102 | // matching friend templates and (2) we might actually be | |||
9103 | // selecting a friend based on a dependent factor. But there | |||
9104 | // are situations where these conditions don't apply and we | |||
9105 | // can actually do this check immediately. | |||
9106 | // | |||
9107 | // Unless the scope is dependent, it's always an error if qualified | |||
9108 | // redeclaration lookup found nothing at all. Diagnose that now; | |||
9109 | // nothing will diagnose that error later. | |||
9110 | if (isFriend && | |||
9111 | (D.getCXXScopeSpec().getScopeRep()->isDependent() || | |||
9112 | (!Previous.empty() && CurContext->isDependentContext()))) { | |||
9113 | // ignore these | |||
9114 | } else { | |||
9115 | // The user tried to provide an out-of-line definition for a | |||
9116 | // function that is a member of a class or namespace, but there | |||
9117 | // was no such member function declared (C++ [class.mfct]p2, | |||
9118 | // C++ [namespace.memdef]p2). For example: | |||
9119 | // | |||
9120 | // class X { | |||
9121 | // void f() const; | |||
9122 | // }; | |||
9123 | // | |||
9124 | // void X::f() { } // ill-formed | |||
9125 | // | |||
9126 | // Complain about this problem, and attempt to suggest close | |||
9127 | // matches (e.g., those that differ only in cv-qualifiers and | |||
9128 | // whether the parameter types are references). | |||
9129 | ||||
9130 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | |||
9131 | *this, Previous, NewFD, ExtraArgs, false, nullptr)) { | |||
9132 | AddToScope = ExtraArgs.AddToScope; | |||
9133 | return Result; | |||
9134 | } | |||
9135 | } | |||
9136 | ||||
9137 | // Unqualified local friend declarations are required to resolve | |||
9138 | // to something. | |||
9139 | } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { | |||
9140 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | |||
9141 | *this, Previous, NewFD, ExtraArgs, true, S)) { | |||
9142 | AddToScope = ExtraArgs.AddToScope; | |||
9143 | return Result; | |||
9144 | } | |||
9145 | } | |||
9146 | } else if (!D.isFunctionDefinition() && | |||
9147 | isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && | |||
9148 | !isFriend && !isFunctionTemplateSpecialization && | |||
9149 | !isMemberSpecialization) { | |||
9150 | // An out-of-line member function declaration must also be a | |||
9151 | // definition (C++ [class.mfct]p2). | |||
9152 | // Note that this is not the case for explicit specializations of | |||
9153 | // function templates or member functions of class templates, per | |||
9154 | // C++ [temp.expl.spec]p2. We also allow these declarations as an | |||
9155 | // extension for compatibility with old SWIG code which likes to | |||
9156 | // generate them. | |||
9157 | Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) | |||
9158 | << D.getCXXScopeSpec().getRange(); | |||
9159 | } | |||
9160 | } | |||
9161 | ||||
9162 | ProcessPragmaWeak(S, NewFD); | |||
9163 | checkAttributesAfterMerging(*this, *NewFD); | |||
9164 | ||||
9165 | AddKnownFunctionAttributes(NewFD); | |||
9166 | ||||
9167 | if (NewFD->hasAttr<OverloadableAttr>() && | |||
9168 | !NewFD->getType()->getAs<FunctionProtoType>()) { | |||
9169 | Diag(NewFD->getLocation(), | |||
9170 | diag::err_attribute_overloadable_no_prototype) | |||
9171 | << NewFD; | |||
9172 | ||||
9173 | // Turn this into a variadic function with no parameters. | |||
9174 | const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); | |||
9175 | FunctionProtoType::ExtProtoInfo EPI( | |||
9176 | Context.getDefaultCallingConvention(true, false)); | |||
9177 | EPI.Variadic = true; | |||
9178 | EPI.ExtInfo = FT->getExtInfo(); | |||
9179 | ||||
9180 | QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); | |||
9181 | NewFD->setType(R); | |||
9182 | } | |||
9183 | ||||
9184 | // If there's a #pragma GCC visibility in scope, and this isn't a class | |||
9185 | // member, set the visibility of this function. | |||
9186 | if (!DC->isRecord() && NewFD->isExternallyVisible()) | |||
9187 | AddPushedVisibilityAttribute(NewFD); | |||
9188 | ||||
9189 | // If there's a #pragma clang arc_cf_code_audited in scope, consider | |||
9190 | // marking the function. | |||
9191 | AddCFAuditedAttribute(NewFD); | |||
9192 | ||||
9193 | // If this is a function definition, check if we have to apply optnone due to | |||
9194 | // a pragma. | |||
9195 | if(D.isFunctionDefinition()) | |||
9196 | AddRangeBasedOptnone(NewFD); | |||
9197 | ||||
9198 | // If this is the first declaration of an extern C variable, update | |||
9199 | // the map of such variables. | |||
9200 | if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && | |||
9201 | isIncompleteDeclExternC(*this, NewFD)) | |||
9202 | RegisterLocallyScopedExternCDecl(NewFD, S); | |||
9203 | ||||
9204 | // Set this FunctionDecl's range up to the right paren. | |||
9205 | NewFD->setRangeEnd(D.getSourceRange().getEnd()); | |||
9206 | ||||
9207 | if (D.isRedeclaration() && !Previous.empty()) { | |||
9208 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | |||
9209 | checkDLLAttributeRedeclaration(*this, Prev, NewFD, | |||
9210 | isMemberSpecialization || | |||
9211 | isFunctionTemplateSpecialization, | |||
9212 | D.isFunctionDefinition()); | |||
9213 | } | |||
9214 | ||||
9215 | if (getLangOpts().CUDA) { | |||
9216 | IdentifierInfo *II = NewFD->getIdentifier(); | |||
9217 | if (II && II->isStr(getCudaConfigureFuncName()) && | |||
9218 | !NewFD->isInvalidDecl() && | |||
9219 | NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | |||
9220 | if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) | |||
9221 | Diag(NewFD->getLocation(), diag::err_config_scalar_return) | |||
9222 | << getCudaConfigureFuncName(); | |||
9223 | Context.setcudaConfigureCallDecl(NewFD); | |||
9224 | } | |||
9225 | ||||
9226 | // Variadic functions, other than a *declaration* of printf, are not allowed | |||
9227 | // in device-side CUDA code, unless someone passed | |||
9228 | // -fcuda-allow-variadic-functions. | |||
9229 | if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && | |||
9230 | (NewFD->hasAttr<CUDADeviceAttr>() || | |||
9231 | NewFD->hasAttr<CUDAGlobalAttr>()) && | |||
9232 | !(II && II->isStr("printf") && NewFD->isExternC() && | |||
9233 | !D.isFunctionDefinition())) { | |||
9234 | Diag(NewFD->getLocation(), diag::err_variadic_device_fn); | |||
9235 | } | |||
9236 | } | |||
9237 | ||||
9238 | MarkUnusedFileScopedDecl(NewFD); | |||
9239 | ||||
9240 | ||||
9241 | ||||
9242 | if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { | |||
9243 | // OpenCL v1.2 s6.8 static is invalid for kernel functions. | |||
9244 | if ((getLangOpts().OpenCLVersion >= 120) | |||
9245 | && (SC == SC_Static)) { | |||
9246 | Diag(D.getIdentifierLoc(), diag::err_static_kernel); | |||
9247 | D.setInvalidType(); | |||
9248 | } | |||
9249 | ||||
9250 | // OpenCL v1.2, s6.9 -- Kernels can only have return type void. | |||
9251 | if (!NewFD->getReturnType()->isVoidType()) { | |||
9252 | SourceRange RTRange = NewFD->getReturnTypeSourceRange(); | |||
9253 | Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) | |||
9254 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") | |||
9255 | : FixItHint()); | |||
9256 | D.setInvalidType(); | |||
9257 | } | |||
9258 | ||||
9259 | llvm::SmallPtrSet<const Type *, 16> ValidTypes; | |||
9260 | for (auto Param : NewFD->parameters()) | |||
9261 | checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); | |||
9262 | ||||
9263 | if (getLangOpts().OpenCLCPlusPlus) { | |||
9264 | if (DC->isRecord()) { | |||
9265 | Diag(D.getIdentifierLoc(), diag::err_method_kernel); | |||
9266 | D.setInvalidType(); | |||
9267 | } | |||
9268 | if (FunctionTemplate) { | |||
9269 | Diag(D.getIdentifierLoc(), diag::err_template_kernel); | |||
9270 | D.setInvalidType(); | |||
9271 | } | |||
9272 | } | |||
9273 | } | |||
9274 | ||||
9275 | if (getLangOpts().CPlusPlus) { | |||
9276 | if (FunctionTemplate) { | |||
9277 | if (NewFD->isInvalidDecl()) | |||
9278 | FunctionTemplate->setInvalidDecl(); | |||
9279 | return FunctionTemplate; | |||
9280 | } | |||
9281 | ||||
9282 | if (isMemberSpecialization && !NewFD->isInvalidDecl()) | |||
9283 | CompleteMemberSpecialization(NewFD, Previous); | |||
9284 | } | |||
9285 | ||||
9286 | for (const ParmVarDecl *Param : NewFD->parameters()) { | |||
9287 | QualType PT = Param->getType(); | |||
9288 | ||||
9289 | // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value | |||
9290 | // types. | |||
9291 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { | |||
9292 | if(const PipeType *PipeTy = PT->getAs<PipeType>()) { | |||
9293 | QualType ElemTy = PipeTy->getElementType(); | |||
9294 | if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { | |||
9295 | Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); | |||
9296 | D.setInvalidType(); | |||
9297 | } | |||
9298 | } | |||
9299 | } | |||
9300 | } | |||
9301 | ||||
9302 | // Here we have an function template explicit specialization at class scope. | |||
9303 | // The actual specialization will be postponed to template instatiation | |||
9304 | // time via the ClassScopeFunctionSpecializationDecl node. | |||
9305 | if (isDependentClassScopeExplicitSpecialization) { | |||
9306 | ClassScopeFunctionSpecializationDecl *NewSpec = | |||
9307 | ClassScopeFunctionSpecializationDecl::Create( | |||
9308 | Context, CurContext, NewFD->getLocation(), | |||
9309 | cast<CXXMethodDecl>(NewFD), | |||
9310 | HasExplicitTemplateArgs, TemplateArgs); | |||
9311 | CurContext->addDecl(NewSpec); | |||
9312 | AddToScope = false; | |||
9313 | } | |||
9314 | ||||
9315 | // Diagnose availability attributes. Availability cannot be used on functions | |||
9316 | // that are run during load/unload. | |||
9317 | if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { | |||
9318 | if (NewFD->hasAttr<ConstructorAttr>()) { | |||
9319 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | |||
9320 | << 1; | |||
9321 | NewFD->dropAttr<AvailabilityAttr>(); | |||
9322 | } | |||
9323 | if (NewFD->hasAttr<DestructorAttr>()) { | |||
9324 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | |||
9325 | << 2; | |||
9326 | NewFD->dropAttr<AvailabilityAttr>(); | |||
9327 | } | |||
9328 | } | |||
9329 | ||||
9330 | return NewFD; | |||
9331 | } | |||
9332 | ||||
9333 | /// Return a CodeSegAttr from a containing class. The Microsoft docs say | |||
9334 | /// when __declspec(code_seg) "is applied to a class, all member functions of | |||
9335 | /// the class and nested classes -- this includes compiler-generated special | |||
9336 | /// member functions -- are put in the specified segment." | |||
9337 | /// The actual behavior is a little more complicated. The Microsoft compiler | |||
9338 | /// won't check outer classes if there is an active value from #pragma code_seg. | |||
9339 | /// The CodeSeg is always applied from the direct parent but only from outer | |||
9340 | /// classes when the #pragma code_seg stack is empty. See: | |||
9341 | /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer | |||
9342 | /// available since MS has removed the page. | |||
9343 | static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { | |||
9344 | const auto *Method = dyn_cast<CXXMethodDecl>(FD); | |||
9345 | if (!Method) | |||
9346 | return nullptr; | |||
9347 | const CXXRecordDecl *Parent = Method->getParent(); | |||
9348 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | |||
9349 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | |||
9350 | NewAttr->setImplicit(true); | |||
9351 | return NewAttr; | |||
9352 | } | |||
9353 | ||||
9354 | // The Microsoft compiler won't check outer classes for the CodeSeg | |||
9355 | // when the #pragma code_seg stack is active. | |||
9356 | if (S.CodeSegStack.CurrentValue) | |||
9357 | return nullptr; | |||
9358 | ||||
9359 | while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { | |||
9360 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | |||
9361 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | |||
9362 | NewAttr->setImplicit(true); | |||
9363 | return NewAttr; | |||
9364 | } | |||
9365 | } | |||
9366 | return nullptr; | |||
9367 | } | |||
9368 | ||||
9369 | /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a | |||
9370 | /// containing class. Otherwise it will return implicit SectionAttr if the | |||
9371 | /// function is a definition and there is an active value on CodeSegStack | |||
9372 | /// (from the current #pragma code-seg value). | |||
9373 | /// | |||
9374 | /// \param FD Function being declared. | |||
9375 | /// \param IsDefinition Whether it is a definition or just a declarartion. | |||
9376 | /// \returns A CodeSegAttr or SectionAttr to apply to the function or | |||
9377 | /// nullptr if no attribute should be added. | |||
9378 | Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, | |||
9379 | bool IsDefinition) { | |||
9380 | if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) | |||
9381 | return A; | |||
9382 | if (!FD->hasAttr<SectionAttr>() && IsDefinition && | |||
9383 | CodeSegStack.CurrentValue) { | |||
9384 | return SectionAttr::CreateImplicit(getASTContext(), | |||
9385 | SectionAttr::Declspec_allocate, | |||
9386 | CodeSegStack.CurrentValue->getString(), | |||
9387 | CodeSegStack.CurrentPragmaLocation); | |||
9388 | } | |||
9389 | return nullptr; | |||
9390 | } | |||
9391 | ||||
9392 | /// Determines if we can perform a correct type check for \p D as a | |||
9393 | /// redeclaration of \p PrevDecl. If not, we can generally still perform a | |||
9394 | /// best-effort check. | |||
9395 | /// | |||
9396 | /// \param NewD The new declaration. | |||
9397 | /// \param OldD The old declaration. | |||
9398 | /// \param NewT The portion of the type of the new declaration to check. | |||
9399 | /// \param OldT The portion of the type of the old declaration to check. | |||
9400 | bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, | |||
9401 | QualType NewT, QualType OldT) { | |||
9402 | if (!NewD->getLexicalDeclContext()->isDependentContext()) | |||
9403 | return true; | |||
9404 | ||||
9405 | // For dependently-typed local extern declarations and friends, we can't | |||
9406 | // perform a correct type check in general until instantiation: | |||
9407 | // | |||
9408 | // int f(); | |||
9409 | // template<typename T> void g() { T f(); } | |||
9410 | // | |||
9411 | // (valid if g() is only instantiated with T = int). | |||
9412 | if (NewT->isDependentType() && | |||
9413 | (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) | |||
9414 | return false; | |||
9415 | ||||
9416 | // Similarly, if the previous declaration was a dependent local extern | |||
9417 | // declaration, we don't really know its type yet. | |||
9418 | if (OldT->isDependentType() && OldD->isLocalExternDecl()) | |||
9419 | return false; | |||
9420 | ||||
9421 | return true; | |||
9422 | } | |||
9423 | ||||
9424 | /// Checks if the new declaration declared in dependent context must be | |||
9425 | /// put in the same redeclaration chain as the specified declaration. | |||
9426 | /// | |||
9427 | /// \param D Declaration that is checked. | |||
9428 | /// \param PrevDecl Previous declaration found with proper lookup method for the | |||
9429 | /// same declaration name. | |||
9430 | /// \returns True if D must be added to the redeclaration chain which PrevDecl | |||
9431 | /// belongs to. | |||
9432 | /// | |||
9433 | bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { | |||
9434 | if (!D->getLexicalDeclContext()->isDependentContext()) | |||
9435 | return true; | |||
9436 | ||||
9437 | // Don't chain dependent friend function definitions until instantiation, to | |||
9438 | // permit cases like | |||
9439 | // | |||
9440 | // void func(); | |||
9441 | // template<typename T> class C1 { friend void func() {} }; | |||
9442 | // template<typename T> class C2 { friend void func() {} }; | |||
9443 | // | |||
9444 | // ... which is valid if only one of C1 and C2 is ever instantiated. | |||
9445 | // | |||
9446 | // FIXME: This need only apply to function definitions. For now, we proxy | |||
9447 | // this by checking for a file-scope function. We do not want this to apply | |||
9448 | // to friend declarations nominating member functions, because that gets in | |||
9449 | // the way of access checks. | |||
9450 | if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) | |||
9451 | return false; | |||
9452 | ||||
9453 | auto *VD = dyn_cast<ValueDecl>(D); | |||
9454 | auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); | |||
9455 | return !VD || !PrevVD || | |||
9456 | canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), | |||
9457 | PrevVD->getType()); | |||
9458 | } | |||
9459 | ||||
9460 | /// Check the target attribute of the function for MultiVersion | |||
9461 | /// validity. | |||
9462 | /// | |||
9463 | /// Returns true if there was an error, false otherwise. | |||
9464 | static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { | |||
9465 | const auto *TA = FD->getAttr<TargetAttr>(); | |||
9466 | assert(TA && "MultiVersion Candidate requires a target attribute")((TA && "MultiVersion Candidate requires a target attribute" ) ? static_cast<void> (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 9466, __PRETTY_FUNCTION__)); | |||
9467 | TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); | |||
9468 | const TargetInfo &TargetInfo = S.Context.getTargetInfo(); | |||
9469 | enum ErrType { Feature = 0, Architecture = 1 }; | |||
9470 | ||||
9471 | if (!ParseInfo.Architecture.empty() && | |||
9472 | !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { | |||
9473 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | |||
9474 | << Architecture << ParseInfo.Architecture; | |||
9475 | return true; | |||
9476 | } | |||
9477 | ||||
9478 | for (const auto &Feat : ParseInfo.Features) { | |||
9479 | auto BareFeat = StringRef{Feat}.substr(1); | |||
9480 | if (Feat[0] == '-') { | |||
9481 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | |||
9482 | << Feature << ("no-" + BareFeat).str(); | |||
9483 | return true; | |||
9484 | } | |||
9485 | ||||
9486 | if (!TargetInfo.validateCpuSupports(BareFeat) || | |||
9487 | !TargetInfo.isValidFeatureName(BareFeat)) { | |||
9488 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | |||
9489 | << Feature << BareFeat; | |||
9490 | return true; | |||
9491 | } | |||
9492 | } | |||
9493 | return false; | |||
9494 | } | |||
9495 | ||||
9496 | static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, | |||
9497 | MultiVersionKind MVType) { | |||
9498 | for (const Attr *A : FD->attrs()) { | |||
9499 | switch (A->getKind()) { | |||
9500 | case attr::CPUDispatch: | |||
9501 | case attr::CPUSpecific: | |||
9502 | if (MVType != MultiVersionKind::CPUDispatch && | |||
9503 | MVType != MultiVersionKind::CPUSpecific) | |||
9504 | return true; | |||
9505 | break; | |||
9506 | case attr::Target: | |||
9507 | if (MVType != MultiVersionKind::Target) | |||
9508 | return true; | |||
9509 | break; | |||
9510 | default: | |||
9511 | return true; | |||
9512 | } | |||
9513 | } | |||
9514 | return false; | |||
9515 | } | |||
9516 | ||||
9517 | static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, | |||
9518 | const FunctionDecl *NewFD, | |||
9519 | bool CausesMV, | |||
9520 | MultiVersionKind MVType) { | |||
9521 | enum DoesntSupport { | |||
9522 | FuncTemplates = 0, | |||
9523 | VirtFuncs = 1, | |||
9524 | DeducedReturn = 2, | |||
9525 | Constructors = 3, | |||
9526 | Destructors = 4, | |||
9527 | DeletedFuncs = 5, | |||
9528 | DefaultedFuncs = 6, | |||
9529 | ConstexprFuncs = 7, | |||
9530 | }; | |||
9531 | enum Different { | |||
9532 | CallingConv = 0, | |||
9533 | ReturnType = 1, | |||
9534 | ConstexprSpec = 2, | |||
9535 | InlineSpec = 3, | |||
9536 | StorageClass = 4, | |||
9537 | Linkage = 5 | |||
9538 | }; | |||
9539 | ||||
9540 | bool IsCPUSpecificCPUDispatchMVType = | |||
9541 | MVType == MultiVersionKind::CPUDispatch || | |||
9542 | MVType == MultiVersionKind::CPUSpecific; | |||
9543 | ||||
9544 | if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { | |||
9545 | S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); | |||
9546 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
9547 | return true; | |||
9548 | } | |||
9549 | ||||
9550 | if (!NewFD->getType()->getAs<FunctionProtoType>()) | |||
9551 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); | |||
9552 | ||||
9553 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | |||
9554 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | |||
9555 | if (OldFD) | |||
9556 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
9557 | return true; | |||
9558 | } | |||
9559 | ||||
9560 | // For now, disallow all other attributes. These should be opt-in, but | |||
9561 | // an analysis of all of them is a future FIXME. | |||
9562 | if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { | |||
9563 | S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) | |||
9564 | << IsCPUSpecificCPUDispatchMVType; | |||
9565 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
9566 | return true; | |||
9567 | } | |||
9568 | ||||
9569 | if (HasNonMultiVersionAttributes(NewFD, MVType)) | |||
9570 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) | |||
9571 | << IsCPUSpecificCPUDispatchMVType; | |||
9572 | ||||
9573 | if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) | |||
9574 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) | |||
9575 | << IsCPUSpecificCPUDispatchMVType << FuncTemplates; | |||
9576 | ||||
9577 | if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { | |||
9578 | if (NewCXXFD->isVirtual()) | |||
9579 | return S.Diag(NewCXXFD->getLocation(), | |||
9580 | diag::err_multiversion_doesnt_support) | |||
9581 | << IsCPUSpecificCPUDispatchMVType << VirtFuncs; | |||
9582 | ||||
9583 | if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) | |||
9584 | return S.Diag(NewCXXCtor->getLocation(), | |||
9585 | diag::err_multiversion_doesnt_support) | |||
9586 | << IsCPUSpecificCPUDispatchMVType << Constructors; | |||
9587 | ||||
9588 | if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) | |||
9589 | return S.Diag(NewCXXDtor->getLocation(), | |||
9590 | diag::err_multiversion_doesnt_support) | |||
9591 | << IsCPUSpecificCPUDispatchMVType << Destructors; | |||
9592 | } | |||
9593 | ||||
9594 | if (NewFD->isDeleted()) | |||
9595 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) | |||
9596 | << IsCPUSpecificCPUDispatchMVType << DeletedFuncs; | |||
9597 | ||||
9598 | if (NewFD->isDefaulted()) | |||
9599 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) | |||
9600 | << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs; | |||
9601 | ||||
9602 | if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch || | |||
9603 | MVType == MultiVersionKind::CPUSpecific)) | |||
9604 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) | |||
9605 | << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs; | |||
9606 | ||||
9607 | QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); | |||
9608 | const auto *NewType = cast<FunctionType>(NewQType); | |||
9609 | QualType NewReturnType = NewType->getReturnType(); | |||
9610 | ||||
9611 | if (NewReturnType->isUndeducedType()) | |||
9612 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) | |||
9613 | << IsCPUSpecificCPUDispatchMVType << DeducedReturn; | |||
9614 | ||||
9615 | // Only allow transition to MultiVersion if it hasn't been used. | |||
9616 | if (OldFD && CausesMV && OldFD->isUsed(false)) | |||
9617 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); | |||
9618 | ||||
9619 | // Ensure the return type is identical. | |||
9620 | if (OldFD) { | |||
9621 | QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); | |||
9622 | const auto *OldType = cast<FunctionType>(OldQType); | |||
9623 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | |||
9624 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | |||
9625 | ||||
9626 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) | |||
9627 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9628 | << CallingConv; | |||
9629 | ||||
9630 | QualType OldReturnType = OldType->getReturnType(); | |||
9631 | ||||
9632 | if (OldReturnType != NewReturnType) | |||
9633 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9634 | << ReturnType; | |||
9635 | ||||
9636 | if (OldFD->isConstexpr() != NewFD->isConstexpr()) | |||
9637 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9638 | << ConstexprSpec; | |||
9639 | ||||
9640 | if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) | |||
9641 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9642 | << InlineSpec; | |||
9643 | ||||
9644 | if (OldFD->getStorageClass() != NewFD->getStorageClass()) | |||
9645 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9646 | << StorageClass; | |||
9647 | ||||
9648 | if (OldFD->isExternC() != NewFD->isExternC()) | |||
9649 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9650 | << Linkage; | |||
9651 | ||||
9652 | if (S.CheckEquivalentExceptionSpec( | |||
9653 | OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), | |||
9654 | NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) | |||
9655 | return true; | |||
9656 | } | |||
9657 | return false; | |||
9658 | } | |||
9659 | ||||
9660 | /// Check the validity of a multiversion function declaration that is the | |||
9661 | /// first of its kind. Also sets the multiversion'ness' of the function itself. | |||
9662 | /// | |||
9663 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | |||
9664 | /// | |||
9665 | /// Returns true if there was an error, false otherwise. | |||
9666 | static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, | |||
9667 | MultiVersionKind MVType, | |||
9668 | const TargetAttr *TA) { | |||
9669 | assert(MVType != MultiVersionKind::None &&((MVType != MultiVersionKind::None && "Function lacks multiversion attribute" ) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 9670, __PRETTY_FUNCTION__)) | |||
9670 | "Function lacks multiversion attribute")((MVType != MultiVersionKind::None && "Function lacks multiversion attribute" ) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 9670, __PRETTY_FUNCTION__)); | |||
9671 | ||||
9672 | // Target only causes MV if it is default, otherwise this is a normal | |||
9673 | // function. | |||
9674 | if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) | |||
9675 | return false; | |||
9676 | ||||
9677 | if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { | |||
9678 | FD->setInvalidDecl(); | |||
9679 | return true; | |||
9680 | } | |||
9681 | ||||
9682 | if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { | |||
9683 | FD->setInvalidDecl(); | |||
9684 | return true; | |||
9685 | } | |||
9686 | ||||
9687 | FD->setIsMultiVersion(); | |||
9688 | return false; | |||
9689 | } | |||
9690 | ||||
9691 | static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { | |||
9692 | for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { | |||
9693 | if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) | |||
9694 | return true; | |||
9695 | } | |||
9696 | ||||
9697 | return false; | |||
9698 | } | |||
9699 | ||||
9700 | static bool CheckTargetCausesMultiVersioning( | |||
9701 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, | |||
9702 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | |||
9703 | LookupResult &Previous) { | |||
9704 | const auto *OldTA = OldFD->getAttr<TargetAttr>(); | |||
9705 | TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); | |||
9706 | // Sort order doesn't matter, it just needs to be consistent. | |||
9707 | llvm::sort(NewParsed.Features); | |||
9708 | ||||
9709 | // If the old decl is NOT MultiVersioned yet, and we don't cause that | |||
9710 | // to change, this is a simple redeclaration. | |||
9711 | if (!NewTA->isDefaultVersion() && | |||
9712 | (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) | |||
9713 | return false; | |||
9714 | ||||
9715 | // Otherwise, this decl causes MultiVersioning. | |||
9716 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | |||
9717 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | |||
9718 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
9719 | NewFD->setInvalidDecl(); | |||
9720 | return true; | |||
9721 | } | |||
9722 | ||||
9723 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, | |||
9724 | MultiVersionKind::Target)) { | |||
9725 | NewFD->setInvalidDecl(); | |||
9726 | return true; | |||
9727 | } | |||
9728 | ||||
9729 | if (CheckMultiVersionValue(S, NewFD)) { | |||
9730 | NewFD->setInvalidDecl(); | |||
9731 | return true; | |||
9732 | } | |||
9733 | ||||
9734 | // If this is 'default', permit the forward declaration. | |||
9735 | if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { | |||
9736 | Redeclaration = true; | |||
9737 | OldDecl = OldFD; | |||
9738 | OldFD->setIsMultiVersion(); | |||
9739 | NewFD->setIsMultiVersion(); | |||
9740 | return false; | |||
9741 | } | |||
9742 | ||||
9743 | if (CheckMultiVersionValue(S, OldFD)) { | |||
9744 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
9745 | NewFD->setInvalidDecl(); | |||
9746 | return true; | |||
9747 | } | |||
9748 | ||||
9749 | TargetAttr::ParsedTargetAttr OldParsed = | |||
9750 | OldTA->parse(std::less<std::string>()); | |||
9751 | ||||
9752 | if (OldParsed == NewParsed) { | |||
9753 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | |||
9754 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
9755 | NewFD->setInvalidDecl(); | |||
9756 | return true; | |||
9757 | } | |||
9758 | ||||
9759 | for (const auto *FD : OldFD->redecls()) { | |||
9760 | const auto *CurTA = FD->getAttr<TargetAttr>(); | |||
9761 | // We allow forward declarations before ANY multiversioning attributes, but | |||
9762 | // nothing after the fact. | |||
9763 | if (PreviousDeclsHaveMultiVersionAttribute(FD) && | |||
9764 | (!CurTA || CurTA->isInherited())) { | |||
9765 | S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) | |||
9766 | << 0; | |||
9767 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
9768 | NewFD->setInvalidDecl(); | |||
9769 | return true; | |||
9770 | } | |||
9771 | } | |||
9772 | ||||
9773 | OldFD->setIsMultiVersion(); | |||
9774 | NewFD->setIsMultiVersion(); | |||
9775 | Redeclaration = false; | |||
9776 | MergeTypeWithPrevious = false; | |||
9777 | OldDecl = nullptr; | |||
9778 | Previous.clear(); | |||
9779 | return false; | |||
9780 | } | |||
9781 | ||||
9782 | /// Check the validity of a new function declaration being added to an existing | |||
9783 | /// multiversioned declaration collection. | |||
9784 | static bool CheckMultiVersionAdditionalDecl( | |||
9785 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, | |||
9786 | MultiVersionKind NewMVType, const TargetAttr *NewTA, | |||
9787 | const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, | |||
9788 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | |||
9789 | LookupResult &Previous) { | |||
9790 | ||||
9791 | MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); | |||
9792 | // Disallow mixing of multiversioning types. | |||
9793 | if ((OldMVType == MultiVersionKind::Target && | |||
9794 | NewMVType != MultiVersionKind::Target) || | |||
9795 | (NewMVType == MultiVersionKind::Target && | |||
9796 | OldMVType != MultiVersionKind::Target)) { | |||
9797 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | |||
9798 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
9799 | NewFD->setInvalidDecl(); | |||
9800 | return true; | |||
9801 | } | |||
9802 | ||||
9803 | TargetAttr::ParsedTargetAttr NewParsed; | |||
9804 | if (NewTA) { | |||
9805 | NewParsed = NewTA->parse(); | |||
9806 | llvm::sort(NewParsed.Features); | |||
9807 | } | |||
9808 | ||||
9809 | bool UseMemberUsingDeclRules = | |||
9810 | S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); | |||
9811 | ||||
9812 | // Next, check ALL non-overloads to see if this is a redeclaration of a | |||
9813 | // previous member of the MultiVersion set. | |||
9814 | for (NamedDecl *ND : Previous) { | |||
9815 | FunctionDecl *CurFD = ND->getAsFunction(); | |||
9816 | if (!CurFD) | |||
9817 | continue; | |||
9818 | if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) | |||
9819 | continue; | |||
9820 | ||||
9821 | if (NewMVType == MultiVersionKind::Target) { | |||
9822 | const auto *CurTA = CurFD->getAttr<TargetAttr>(); | |||
9823 | if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { | |||
9824 | NewFD->setIsMultiVersion(); | |||
9825 | Redeclaration = true; | |||
9826 | OldDecl = ND; | |||
9827 | return false; | |||
9828 | } | |||
9829 | ||||
9830 | TargetAttr::ParsedTargetAttr CurParsed = | |||
9831 | CurTA->parse(std::less<std::string>()); | |||
9832 | if (CurParsed == NewParsed) { | |||
9833 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | |||
9834 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | |||
9835 | NewFD->setInvalidDecl(); | |||
9836 | return true; | |||
9837 | } | |||
9838 | } else { | |||
9839 | const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); | |||
9840 | const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); | |||
9841 | // Handle CPUDispatch/CPUSpecific versions. | |||
9842 | // Only 1 CPUDispatch function is allowed, this will make it go through | |||
9843 | // the redeclaration errors. | |||
9844 | if (NewMVType == MultiVersionKind::CPUDispatch && | |||
9845 | CurFD->hasAttr<CPUDispatchAttr>()) { | |||
9846 | if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && | |||
9847 | std::equal( | |||
9848 | CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), | |||
9849 | NewCPUDisp->cpus_begin(), | |||
9850 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | |||
9851 | return Cur->getName() == New->getName(); | |||
9852 | })) { | |||
9853 | NewFD->setIsMultiVersion(); | |||
9854 | Redeclaration = true; | |||
9855 | OldDecl = ND; | |||
9856 | return false; | |||
9857 | } | |||
9858 | ||||
9859 | // If the declarations don't match, this is an error condition. | |||
9860 | S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); | |||
9861 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | |||
9862 | NewFD->setInvalidDecl(); | |||
9863 | return true; | |||
9864 | } | |||
9865 | if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { | |||
9866 | ||||
9867 | if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && | |||
9868 | std::equal( | |||
9869 | CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), | |||
9870 | NewCPUSpec->cpus_begin(), | |||
9871 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | |||
9872 | return Cur->getName() == New->getName(); | |||
9873 | })) { | |||
9874 | NewFD->setIsMultiVersion(); | |||
9875 | Redeclaration = true; | |||
9876 | OldDecl = ND; | |||
9877 | return false; | |||
9878 | } | |||
9879 | ||||
9880 | // Only 1 version of CPUSpecific is allowed for each CPU. | |||
9881 | for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { | |||
9882 | for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { | |||
9883 | if (CurII == NewII) { | |||
9884 | S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) | |||
9885 | << NewII; | |||
9886 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | |||
9887 | NewFD->setInvalidDecl(); | |||
9888 | return true; | |||
9889 | } | |||
9890 | } | |||
9891 | } | |||
9892 | } | |||
9893 | // If the two decls aren't the same MVType, there is no possible error | |||
9894 | // condition. | |||
9895 | } | |||
9896 | } | |||
9897 | ||||
9898 | // Else, this is simply a non-redecl case. Checking the 'value' is only | |||
9899 | // necessary in the Target case, since The CPUSpecific/Dispatch cases are | |||
9900 | // handled in the attribute adding step. | |||
9901 | if (NewMVType == MultiVersionKind::Target && | |||
9902 | CheckMultiVersionValue(S, NewFD)) { | |||
9903 | NewFD->setInvalidDecl(); | |||
9904 | return true; | |||
9905 | } | |||
9906 | ||||
9907 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, | |||
9908 | !OldFD->isMultiVersion(), NewMVType)) { | |||
9909 | NewFD->setInvalidDecl(); | |||
9910 | return true; | |||
9911 | } | |||
9912 | ||||
9913 | // Permit forward declarations in the case where these two are compatible. | |||
9914 | if (!OldFD->isMultiVersion()) { | |||
9915 | OldFD->setIsMultiVersion(); | |||
9916 | NewFD->setIsMultiVersion(); | |||
9917 | Redeclaration = true; | |||
9918 | OldDecl = OldFD; | |||
9919 | return false; | |||
9920 | } | |||
9921 | ||||
9922 | NewFD->setIsMultiVersion(); | |||
9923 | Redeclaration = false; | |||
9924 | MergeTypeWithPrevious = false; | |||
9925 | OldDecl = nullptr; | |||
9926 | Previous.clear(); | |||
9927 | return false; | |||
9928 | } | |||
9929 | ||||
9930 | ||||
9931 | /// Check the validity of a mulitversion function declaration. | |||
9932 | /// Also sets the multiversion'ness' of the function itself. | |||
9933 | /// | |||
9934 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | |||
9935 | /// | |||
9936 | /// Returns true if there was an error, false otherwise. | |||
9937 | static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, | |||
9938 | bool &Redeclaration, NamedDecl *&OldDecl, | |||
9939 | bool &MergeTypeWithPrevious, | |||
9940 | LookupResult &Previous) { | |||
9941 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); | |||
9942 | const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); | |||
9943 | const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); | |||
9944 | ||||
9945 | // Mixing Multiversioning types is prohibited. | |||
9946 | if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || | |||
9947 | (NewCPUDisp && NewCPUSpec)) { | |||
9948 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | |||
9949 | NewFD->setInvalidDecl(); | |||
9950 | return true; | |||
9951 | } | |||
9952 | ||||
9953 | MultiVersionKind MVType = NewFD->getMultiVersionKind(); | |||
9954 | ||||
9955 | // Main isn't allowed to become a multiversion function, however it IS | |||
9956 | // permitted to have 'main' be marked with the 'target' optimization hint. | |||
9957 | if (NewFD->isMain()) { | |||
9958 | if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || | |||
9959 | MVType == MultiVersionKind::CPUDispatch || | |||
9960 | MVType == MultiVersionKind::CPUSpecific) { | |||
9961 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); | |||
9962 | NewFD->setInvalidDecl(); | |||
9963 | return true; | |||
9964 | } | |||
9965 | return false; | |||
9966 | } | |||
9967 | ||||
9968 | if (!OldDecl || !OldDecl->getAsFunction() || | |||
9969 | OldDecl->getDeclContext()->getRedeclContext() != | |||
9970 | NewFD->getDeclContext()->getRedeclContext()) { | |||
9971 | // If there's no previous declaration, AND this isn't attempting to cause | |||
9972 | // multiversioning, this isn't an error condition. | |||
9973 | if (MVType == MultiVersionKind::None) | |||
9974 | return false; | |||
9975 | return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); | |||
9976 | } | |||
9977 | ||||
9978 | FunctionDecl *OldFD = OldDecl->getAsFunction(); | |||
9979 | ||||
9980 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) | |||
9981 | return false; | |||
9982 | ||||
9983 | if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { | |||
9984 | S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) | |||
9985 | << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); | |||
9986 | NewFD->setInvalidDecl(); | |||
9987 | return true; | |||
9988 | } | |||
9989 | ||||
9990 | // Handle the target potentially causes multiversioning case. | |||
9991 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) | |||
9992 | return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, | |||
9993 | Redeclaration, OldDecl, | |||
9994 | MergeTypeWithPrevious, Previous); | |||
9995 | ||||
9996 | // At this point, we have a multiversion function decl (in OldFD) AND an | |||
9997 | // appropriate attribute in the current function decl. Resolve that these are | |||
9998 | // still compatible with previous declarations. | |||
9999 | return CheckMultiVersionAdditionalDecl( | |||
10000 | S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, | |||
10001 | OldDecl, MergeTypeWithPrevious, Previous); | |||
10002 | } | |||
10003 | ||||
10004 | /// Perform semantic checking of a new function declaration. | |||
10005 | /// | |||
10006 | /// Performs semantic analysis of the new function declaration | |||
10007 | /// NewFD. This routine performs all semantic checking that does not | |||
10008 | /// require the actual declarator involved in the declaration, and is | |||
10009 | /// used both for the declaration of functions as they are parsed | |||
10010 | /// (called via ActOnDeclarator) and for the declaration of functions | |||
10011 | /// that have been instantiated via C++ template instantiation (called | |||
10012 | /// via InstantiateDecl). | |||
10013 | /// | |||
10014 | /// \param IsMemberSpecialization whether this new function declaration is | |||
10015 | /// a member specialization (that replaces any definition provided by the | |||
10016 | /// previous declaration). | |||
10017 | /// | |||
10018 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | |||
10019 | /// | |||
10020 | /// \returns true if the function declaration is a redeclaration. | |||
10021 | bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, | |||
10022 | LookupResult &Previous, | |||
10023 | bool IsMemberSpecialization) { | |||
10024 | assert(!NewFD->getReturnType()->isVariablyModifiedType() &&((!NewFD->getReturnType()->isVariablyModifiedType() && "Variably modified return types are not handled here") ? static_cast <void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10025, __PRETTY_FUNCTION__)) | |||
10025 | "Variably modified return types are not handled here")((!NewFD->getReturnType()->isVariablyModifiedType() && "Variably modified return types are not handled here") ? static_cast <void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10025, __PRETTY_FUNCTION__)); | |||
10026 | ||||
10027 | // Determine whether the type of this function should be merged with | |||
10028 | // a previous visible declaration. This never happens for functions in C++, | |||
10029 | // and always happens in C if the previous declaration was visible. | |||
10030 | bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && | |||
10031 | !Previous.isShadowed(); | |||
10032 | ||||
10033 | bool Redeclaration = false; | |||
10034 | NamedDecl *OldDecl = nullptr; | |||
10035 | bool MayNeedOverloadableChecks = false; | |||
10036 | ||||
10037 | // Merge or overload the declaration with an existing declaration of | |||
10038 | // the same name, if appropriate. | |||
10039 | if (!Previous.empty()) { | |||
10040 | // Determine whether NewFD is an overload of PrevDecl or | |||
10041 | // a declaration that requires merging. If it's an overload, | |||
10042 | // there's no more work to do here; we'll just add the new | |||
10043 | // function to the scope. | |||
10044 | if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { | |||
10045 | NamedDecl *Candidate = Previous.getRepresentativeDecl(); | |||
10046 | if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { | |||
10047 | Redeclaration = true; | |||
10048 | OldDecl = Candidate; | |||
10049 | } | |||
10050 | } else { | |||
10051 | MayNeedOverloadableChecks = true; | |||
10052 | switch (CheckOverload(S, NewFD, Previous, OldDecl, | |||
10053 | /*NewIsUsingDecl*/ false)) { | |||
10054 | case Ovl_Match: | |||
10055 | Redeclaration = true; | |||
10056 | break; | |||
10057 | ||||
10058 | case Ovl_NonFunction: | |||
10059 | Redeclaration = true; | |||
10060 | break; | |||
10061 | ||||
10062 | case Ovl_Overload: | |||
10063 | Redeclaration = false; | |||
10064 | break; | |||
10065 | } | |||
10066 | } | |||
10067 | } | |||
10068 | ||||
10069 | // Check for a previous extern "C" declaration with this name. | |||
10070 | if (!Redeclaration && | |||
10071 | checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { | |||
10072 | if (!Previous.empty()) { | |||
10073 | // This is an extern "C" declaration with the same name as a previous | |||
10074 | // declaration, and thus redeclares that entity... | |||
10075 | Redeclaration = true; | |||
10076 | OldDecl = Previous.getFoundDecl(); | |||
10077 | MergeTypeWithPrevious = false; | |||
10078 | ||||
10079 | // ... except in the presence of __attribute__((overloadable)). | |||
10080 | if (OldDecl->hasAttr<OverloadableAttr>() || | |||
10081 | NewFD->hasAttr<OverloadableAttr>()) { | |||
10082 | if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { | |||
10083 | MayNeedOverloadableChecks = true; | |||
10084 | Redeclaration = false; | |||
10085 | OldDecl = nullptr; | |||
10086 | } | |||
10087 | } | |||
10088 | } | |||
10089 | } | |||
10090 | ||||
10091 | if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, | |||
10092 | MergeTypeWithPrevious, Previous)) | |||
10093 | return Redeclaration; | |||
10094 | ||||
10095 | // C++11 [dcl.constexpr]p8: | |||
10096 | // A constexpr specifier for a non-static member function that is not | |||
10097 | // a constructor declares that member function to be const. | |||
10098 | // | |||
10099 | // This needs to be delayed until we know whether this is an out-of-line | |||
10100 | // definition of a static member function. | |||
10101 | // | |||
10102 | // This rule is not present in C++1y, so we produce a backwards | |||
10103 | // compatibility warning whenever it happens in C++11. | |||
10104 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | |||
10105 | if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && | |||
10106 | !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && | |||
10107 | !MD->getMethodQualifiers().hasConst()) { | |||
10108 | CXXMethodDecl *OldMD = nullptr; | |||
10109 | if (OldDecl) | |||
10110 | OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); | |||
10111 | if (!OldMD || !OldMD->isStatic()) { | |||
10112 | const FunctionProtoType *FPT = | |||
10113 | MD->getType()->castAs<FunctionProtoType>(); | |||
10114 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | |||
10115 | EPI.TypeQuals.addConst(); | |||
10116 | MD->setType(Context.getFunctionType(FPT->getReturnType(), | |||
10117 | FPT->getParamTypes(), EPI)); | |||
10118 | ||||
10119 | // Warn that we did this, if we're not performing template instantiation. | |||
10120 | // In that case, we'll have warned already when the template was defined. | |||
10121 | if (!inTemplateInstantiation()) { | |||
10122 | SourceLocation AddConstLoc; | |||
10123 | if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() | |||
10124 | .IgnoreParens().getAs<FunctionTypeLoc>()) | |||
10125 | AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); | |||
10126 | ||||
10127 | Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) | |||
10128 | << FixItHint::CreateInsertion(AddConstLoc, " const"); | |||
10129 | } | |||
10130 | } | |||
10131 | } | |||
10132 | ||||
10133 | if (Redeclaration) { | |||
10134 | // NewFD and OldDecl represent declarations that need to be | |||
10135 | // merged. | |||
10136 | if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { | |||
10137 | NewFD->setInvalidDecl(); | |||
10138 | return Redeclaration; | |||
10139 | } | |||
10140 | ||||
10141 | Previous.clear(); | |||
10142 | Previous.addDecl(OldDecl); | |||
10143 | ||||
10144 | if (FunctionTemplateDecl *OldTemplateDecl = | |||
10145 | dyn_cast<FunctionTemplateDecl>(OldDecl)) { | |||
10146 | auto *OldFD = OldTemplateDecl->getTemplatedDecl(); | |||
10147 | FunctionTemplateDecl *NewTemplateDecl | |||
10148 | = NewFD->getDescribedFunctionTemplate(); | |||
10149 | assert(NewTemplateDecl && "Template/non-template mismatch")((NewTemplateDecl && "Template/non-template mismatch" ) ? static_cast<void> (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10149, __PRETTY_FUNCTION__)); | |||
10150 | ||||
10151 | // The call to MergeFunctionDecl above may have created some state in | |||
10152 | // NewTemplateDecl that needs to be merged with OldTemplateDecl before we | |||
10153 | // can add it as a redeclaration. | |||
10154 | NewTemplateDecl->mergePrevDecl(OldTemplateDecl); | |||
10155 | ||||
10156 | NewFD->setPreviousDeclaration(OldFD); | |||
10157 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | |||
10158 | if (NewFD->isCXXClassMember()) { | |||
10159 | NewFD->setAccess(OldTemplateDecl->getAccess()); | |||
10160 | NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); | |||
10161 | } | |||
10162 | ||||
10163 | // If this is an explicit specialization of a member that is a function | |||
10164 | // template, mark it as a member specialization. | |||
10165 | if (IsMemberSpecialization && | |||
10166 | NewTemplateDecl->getInstantiatedFromMemberTemplate()) { | |||
10167 | NewTemplateDecl->setMemberSpecialization(); | |||
10168 | assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast <void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10168, __PRETTY_FUNCTION__)); | |||
10169 | // Explicit specializations of a member template do not inherit deleted | |||
10170 | // status from the parent member template that they are specializing. | |||
10171 | if (OldFD->isDeleted()) { | |||
10172 | // FIXME: This assert will not hold in the presence of modules. | |||
10173 | assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void > (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10173, __PRETTY_FUNCTION__)); | |||
10174 | // FIXME: We need an update record for this AST mutation. | |||
10175 | OldFD->setDeletedAsWritten(false); | |||
10176 | } | |||
10177 | } | |||
10178 | ||||
10179 | } else { | |||
10180 | if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { | |||
10181 | auto *OldFD = cast<FunctionDecl>(OldDecl); | |||
10182 | // This needs to happen first so that 'inline' propagates. | |||
10183 | NewFD->setPreviousDeclaration(OldFD); | |||
10184 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | |||
10185 | if (NewFD->isCXXClassMember()) | |||
10186 | NewFD->setAccess(OldFD->getAccess()); | |||
10187 | } | |||
10188 | } | |||
10189 | } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && | |||
10190 | !NewFD->getAttr<OverloadableAttr>()) { | |||
10191 | assert((Previous.empty() ||(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10196, __PRETTY_FUNCTION__)) | |||
10192 | llvm::any_of(Previous,(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10196, __PRETTY_FUNCTION__)) | |||
10193 | [](const NamedDecl *ND) {(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10196, __PRETTY_FUNCTION__)) | |||
10194 | return ND->hasAttr<OverloadableAttr>();(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10196, __PRETTY_FUNCTION__)) | |||
10195 | })) &&(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10196, __PRETTY_FUNCTION__)) | |||
10196 | "Non-redecls shouldn't happen without overloadable present")(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10196, __PRETTY_FUNCTION__)); | |||
10197 | ||||
10198 | auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { | |||
10199 | const auto *FD = dyn_cast<FunctionDecl>(ND); | |||
10200 | return FD && !FD->hasAttr<OverloadableAttr>(); | |||
10201 | }); | |||
10202 | ||||
10203 | if (OtherUnmarkedIter != Previous.end()) { | |||
10204 | Diag(NewFD->getLocation(), | |||
10205 | diag::err_attribute_overloadable_multiple_unmarked_overloads); | |||
10206 | Diag((*OtherUnmarkedIter)->getLocation(), | |||
10207 | diag::note_attribute_overloadable_prev_overload) | |||
10208 | << false; | |||
10209 | ||||
10210 | NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); | |||
10211 | } | |||
10212 | } | |||
10213 | ||||
10214 | // Semantic checking for this function declaration (in isolation). | |||
10215 | ||||
10216 | if (getLangOpts().CPlusPlus) { | |||
10217 | // C++-specific checks. | |||
10218 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { | |||
10219 | CheckConstructor(Constructor); | |||
10220 | } else if (CXXDestructorDecl *Destructor = | |||
10221 | dyn_cast<CXXDestructorDecl>(NewFD)) { | |||
10222 | CXXRecordDecl *Record = Destructor->getParent(); | |||
10223 | QualType ClassType = Context.getTypeDeclType(Record); | |||
10224 | ||||
10225 | // FIXME: Shouldn't we be able to perform this check even when the class | |||
10226 | // type is dependent? Both gcc and edg can handle that. | |||
10227 | if (!ClassType->isDependentType()) { | |||
10228 | DeclarationName Name | |||
10229 | = Context.DeclarationNames.getCXXDestructorName( | |||
10230 | Context.getCanonicalType(ClassType)); | |||
10231 | if (NewFD->getDeclName() != Name) { | |||
10232 | Diag(NewFD->getLocation(), diag::err_destructor_name); | |||
10233 | NewFD->setInvalidDecl(); | |||
10234 | return Redeclaration; | |||
10235 | } | |||
10236 | } | |||
10237 | } else if (CXXConversionDecl *Conversion | |||
10238 | = dyn_cast<CXXConversionDecl>(NewFD)) { | |||
10239 | ActOnConversionDeclarator(Conversion); | |||
10240 | } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { | |||
10241 | if (auto *TD = Guide->getDescribedFunctionTemplate()) | |||
10242 | CheckDeductionGuideTemplate(TD); | |||
10243 | ||||
10244 | // A deduction guide is not on the list of entities that can be | |||
10245 | // explicitly specialized. | |||
10246 | if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) | |||
10247 | Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) | |||
10248 | << /*explicit specialization*/ 1; | |||
10249 | } | |||
10250 | ||||
10251 | // Find any virtual functions that this function overrides. | |||
10252 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { | |||
10253 | if (!Method->isFunctionTemplateSpecialization() && | |||
10254 | !Method->getDescribedFunctionTemplate() && | |||
10255 | Method->isCanonicalDecl()) { | |||
10256 | if (AddOverriddenMethods(Method->getParent(), Method)) { | |||
10257 | // If the function was marked as "static", we have a problem. | |||
10258 | if (NewFD->getStorageClass() == SC_Static) { | |||
10259 | ReportOverrides(*this, diag::err_static_overrides_virtual, Method); | |||
10260 | } | |||
10261 | } | |||
10262 | } | |||
10263 | ||||
10264 | if (Method->isStatic()) | |||
10265 | checkThisInStaticMemberFunctionType(Method); | |||
10266 | } | |||
10267 | ||||
10268 | // Extra checking for C++ overloaded operators (C++ [over.oper]). | |||
10269 | if (NewFD->isOverloadedOperator() && | |||
10270 | CheckOverloadedOperatorDeclaration(NewFD)) { | |||
10271 | NewFD->setInvalidDecl(); | |||
10272 | return Redeclaration; | |||
10273 | } | |||
10274 | ||||
10275 | // Extra checking for C++0x literal operators (C++0x [over.literal]). | |||
10276 | if (NewFD->getLiteralIdentifier() && | |||
10277 | CheckLiteralOperatorDeclaration(NewFD)) { | |||
10278 | NewFD->setInvalidDecl(); | |||
10279 | return Redeclaration; | |||
10280 | } | |||
10281 | ||||
10282 | // In C++, check default arguments now that we have merged decls. Unless | |||
10283 | // the lexical context is the class, because in this case this is done | |||
10284 | // during delayed parsing anyway. | |||
10285 | if (!CurContext->isRecord()) | |||
10286 | CheckCXXDefaultArguments(NewFD); | |||
10287 | ||||
10288 | // If this function declares a builtin function, check the type of this | |||
10289 | // declaration against the expected type for the builtin. | |||
10290 | if (unsigned BuiltinID = NewFD->getBuiltinID()) { | |||
10291 | ASTContext::GetBuiltinTypeError Error; | |||
10292 | LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); | |||
10293 | QualType T = Context.GetBuiltinType(BuiltinID, Error); | |||
10294 | // If the type of the builtin differs only in its exception | |||
10295 | // specification, that's OK. | |||
10296 | // FIXME: If the types do differ in this way, it would be better to | |||
10297 | // retain the 'noexcept' form of the type. | |||
10298 | if (!T.isNull() && | |||
10299 | !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, | |||
10300 | NewFD->getType())) | |||
10301 | // The type of this function differs from the type of the builtin, | |||
10302 | // so forget about the builtin entirely. | |||
10303 | Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); | |||
10304 | } | |||
10305 | ||||
10306 | // If this function is declared as being extern "C", then check to see if | |||
10307 | // the function returns a UDT (class, struct, or union type) that is not C | |||
10308 | // compatible, and if it does, warn the user. | |||
10309 | // But, issue any diagnostic on the first declaration only. | |||
10310 | if (Previous.empty() && NewFD->isExternC()) { | |||
10311 | QualType R = NewFD->getReturnType(); | |||
10312 | if (R->isIncompleteType() && !R->isVoidType()) | |||
10313 | Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) | |||
10314 | << NewFD << R; | |||
10315 | else if (!R.isPODType(Context) && !R->isVoidType() && | |||
10316 | !R->isObjCObjectPointerType()) | |||
10317 | Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; | |||
10318 | } | |||
10319 | ||||
10320 | // C++1z [dcl.fct]p6: | |||
10321 | // [...] whether the function has a non-throwing exception-specification | |||
10322 | // [is] part of the function type | |||
10323 | // | |||
10324 | // This results in an ABI break between C++14 and C++17 for functions whose | |||
10325 | // declared type includes an exception-specification in a parameter or | |||
10326 | // return type. (Exception specifications on the function itself are OK in | |||
10327 | // most cases, and exception specifications are not permitted in most other | |||
10328 | // contexts where they could make it into a mangling.) | |||
10329 | if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { | |||
10330 | auto HasNoexcept = [&](QualType T) -> bool { | |||
10331 | // Strip off declarator chunks that could be between us and a function | |||
10332 | // type. We don't need to look far, exception specifications are very | |||
10333 | // restricted prior to C++17. | |||
10334 | if (auto *RT = T->getAs<ReferenceType>()) | |||
10335 | T = RT->getPointeeType(); | |||
10336 | else if (T->isAnyPointerType()) | |||
10337 | T = T->getPointeeType(); | |||
10338 | else if (auto *MPT = T->getAs<MemberPointerType>()) | |||
10339 | T = MPT->getPointeeType(); | |||
10340 | if (auto *FPT = T->getAs<FunctionProtoType>()) | |||
10341 | if (FPT->isNothrow()) | |||
10342 | return true; | |||
10343 | return false; | |||
10344 | }; | |||
10345 | ||||
10346 | auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); | |||
10347 | bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); | |||
10348 | for (QualType T : FPT->param_types()) | |||
10349 | AnyNoexcept |= HasNoexcept(T); | |||
10350 | if (AnyNoexcept) | |||
10351 | Diag(NewFD->getLocation(), | |||
10352 | diag::warn_cxx17_compat_exception_spec_in_signature) | |||
10353 | << NewFD; | |||
10354 | } | |||
10355 | ||||
10356 | if (!Redeclaration && LangOpts.CUDA) | |||
10357 | checkCUDATargetOverload(NewFD, Previous); | |||
10358 | } | |||
10359 | return Redeclaration; | |||
10360 | } | |||
10361 | ||||
10362 | void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { | |||
10363 | // C++11 [basic.start.main]p3: | |||
10364 | // A program that [...] declares main to be inline, static or | |||
10365 | // constexpr is ill-formed. | |||
10366 | // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall | |||
10367 | // appear in a declaration of main. | |||
10368 | // static main is not an error under C99, but we should warn about it. | |||
10369 | // We accept _Noreturn main as an extension. | |||
10370 | if (FD->getStorageClass() == SC_Static) | |||
10371 | Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus | |||
10372 | ? diag::err_static_main : diag::warn_static_main) | |||
10373 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | |||
10374 | if (FD->isInlineSpecified()) | |||
10375 | Diag(DS.getInlineSpecLoc(), diag::err_inline_main) | |||
10376 | << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); | |||
10377 | if (DS.isNoreturnSpecified()) { | |||
10378 | SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); | |||
10379 | SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); | |||
10380 | Diag(NoreturnLoc, diag::ext_noreturn_main); | |||
10381 | Diag(NoreturnLoc, diag::note_main_remove_noreturn) | |||
10382 | << FixItHint::CreateRemoval(NoreturnRange); | |||
10383 | } | |||
10384 | if (FD->isConstexpr()) { | |||
10385 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) | |||
10386 | << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); | |||
10387 | FD->setConstexpr(false); | |||
10388 | } | |||
10389 | ||||
10390 | if (getLangOpts().OpenCL) { | |||
10391 | Diag(FD->getLocation(), diag::err_opencl_no_main) | |||
10392 | << FD->hasAttr<OpenCLKernelAttr>(); | |||
10393 | FD->setInvalidDecl(); | |||
10394 | return; | |||
10395 | } | |||
10396 | ||||
10397 | QualType T = FD->getType(); | |||
10398 | assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10398, __PRETTY_FUNCTION__)); | |||
10399 | const FunctionType* FT = T->castAs<FunctionType>(); | |||
10400 | ||||
10401 | // Set default calling convention for main() | |||
10402 | if (FT->getCallConv() != CC_C) { | |||
10403 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); | |||
10404 | FD->setType(QualType(FT, 0)); | |||
10405 | T = Context.getCanonicalType(FD->getType()); | |||
10406 | } | |||
10407 | ||||
10408 | if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { | |||
10409 | // In C with GNU extensions we allow main() to have non-integer return | |||
10410 | // type, but we should warn about the extension, and we disable the | |||
10411 | // implicit-return-zero rule. | |||
10412 | ||||
10413 | // GCC in C mode accepts qualified 'int'. | |||
10414 | if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) | |||
10415 | FD->setHasImplicitReturnZero(true); | |||
10416 | else { | |||
10417 | Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); | |||
10418 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | |||
10419 | if (RTRange.isValid()) | |||
10420 | Diag(RTRange.getBegin(), diag::note_main_change_return_type) | |||
10421 | << FixItHint::CreateReplacement(RTRange, "int"); | |||
10422 | } | |||
10423 | } else { | |||
10424 | // In C and C++, main magically returns 0 if you fall off the end; | |||
10425 | // set the flag which tells us that. | |||
10426 | // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. | |||
10427 | ||||
10428 | // All the standards say that main() should return 'int'. | |||
10429 | if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) | |||
10430 | FD->setHasImplicitReturnZero(true); | |||
10431 | else { | |||
10432 | // Otherwise, this is just a flat-out error. | |||
10433 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | |||
10434 | Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) | |||
10435 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") | |||
10436 | : FixItHint()); | |||
10437 | FD->setInvalidDecl(true); | |||
10438 | } | |||
10439 | } | |||
10440 | ||||
10441 | // Treat protoless main() as nullary. | |||
10442 | if (isa<FunctionNoProtoType>(FT)) return; | |||
10443 | ||||
10444 | const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); | |||
10445 | unsigned nparams = FTP->getNumParams(); | |||
10446 | assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10446, __PRETTY_FUNCTION__)); | |||
10447 | ||||
10448 | bool HasExtraParameters = (nparams > 3); | |||
10449 | ||||
10450 | if (FTP->isVariadic()) { | |||
10451 | Diag(FD->getLocation(), diag::ext_variadic_main); | |||
10452 | // FIXME: if we had information about the location of the ellipsis, we | |||
10453 | // could add a FixIt hint to remove it as a parameter. | |||
10454 | } | |||
10455 | ||||
10456 | // Darwin passes an undocumented fourth argument of type char**. If | |||
10457 | // other platforms start sprouting these, the logic below will start | |||
10458 | // getting shifty. | |||
10459 | if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) | |||
10460 | HasExtraParameters = false; | |||
10461 | ||||
10462 | if (HasExtraParameters) { | |||
10463 | Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; | |||
10464 | FD->setInvalidDecl(true); | |||
10465 | nparams = 3; | |||
10466 | } | |||
10467 | ||||
10468 | // FIXME: a lot of the following diagnostics would be improved | |||
10469 | // if we had some location information about types. | |||
10470 | ||||
10471 | QualType CharPP = | |||
10472 | Context.getPointerType(Context.getPointerType(Context.CharTy)); | |||
10473 | QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; | |||
10474 | ||||
10475 | for (unsigned i = 0; i < nparams; ++i) { | |||
10476 | QualType AT = FTP->getParamType(i); | |||
10477 | ||||
10478 | bool mismatch = true; | |||
10479 | ||||
10480 | if (Context.hasSameUnqualifiedType(AT, Expected[i])) | |||
10481 | mismatch = false; | |||
10482 | else if (Expected[i] == CharPP) { | |||
10483 | // As an extension, the following forms are okay: | |||
10484 | // char const ** | |||
10485 | // char const * const * | |||
10486 | // char * const * | |||
10487 | ||||
10488 | QualifierCollector qs; | |||
10489 | const PointerType* PT; | |||
10490 | if ((PT = qs.strip(AT)->getAs<PointerType>()) && | |||
10491 | (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && | |||
10492 | Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), | |||
10493 | Context.CharTy)) { | |||
10494 | qs.removeConst(); | |||
10495 | mismatch = !qs.empty(); | |||
10496 | } | |||
10497 | } | |||
10498 | ||||
10499 | if (mismatch) { | |||
10500 | Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; | |||
10501 | // TODO: suggest replacing given type with expected type | |||
10502 | FD->setInvalidDecl(true); | |||
10503 | } | |||
10504 | } | |||
10505 | ||||
10506 | if (nparams == 1 && !FD->isInvalidDecl()) { | |||
10507 | Diag(FD->getLocation(), diag::warn_main_one_arg); | |||
10508 | } | |||
10509 | ||||
10510 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | |||
10511 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | |||
10512 | FD->setInvalidDecl(); | |||
10513 | } | |||
10514 | } | |||
10515 | ||||
10516 | void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { | |||
10517 | QualType T = FD->getType(); | |||
10518 | assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10518, __PRETTY_FUNCTION__)); | |||
10519 | const FunctionType *FT = T->castAs<FunctionType>(); | |||
10520 | ||||
10521 | // Set an implicit return of 'zero' if the function can return some integral, | |||
10522 | // enumeration, pointer or nullptr type. | |||
10523 | if (FT->getReturnType()->isIntegralOrEnumerationType() || | |||
10524 | FT->getReturnType()->isAnyPointerType() || | |||
10525 | FT->getReturnType()->isNullPtrType()) | |||
10526 | // DllMain is exempt because a return value of zero means it failed. | |||
10527 | if (FD->getName() != "DllMain") | |||
10528 | FD->setHasImplicitReturnZero(true); | |||
10529 | ||||
10530 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | |||
10531 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | |||
10532 | FD->setInvalidDecl(); | |||
10533 | } | |||
10534 | } | |||
10535 | ||||
10536 | bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { | |||
10537 | // FIXME: Need strict checking. In C89, we need to check for | |||
10538 | // any assignment, increment, decrement, function-calls, or | |||
10539 | // commas outside of a sizeof. In C99, it's the same list, | |||
10540 | // except that the aforementioned are allowed in unevaluated | |||
10541 | // expressions. Everything else falls under the | |||
10542 | // "may accept other forms of constant expressions" exception. | |||
10543 | // (We never end up here for C++, so the constant expression | |||
10544 | // rules there don't matter.) | |||
10545 | const Expr *Culprit; | |||
10546 | if (Init->isConstantInitializer(Context, false, &Culprit)) | |||
10547 | return false; | |||
10548 | Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) | |||
10549 | << Culprit->getSourceRange(); | |||
10550 | return true; | |||
10551 | } | |||
10552 | ||||
10553 | namespace { | |||
10554 | // Visits an initialization expression to see if OrigDecl is evaluated in | |||
10555 | // its own initialization and throws a warning if it does. | |||
10556 | class SelfReferenceChecker | |||
10557 | : public EvaluatedExprVisitor<SelfReferenceChecker> { | |||
10558 | Sema &S; | |||
10559 | Decl *OrigDecl; | |||
10560 | bool isRecordType; | |||
10561 | bool isPODType; | |||
10562 | bool isReferenceType; | |||
10563 | ||||
10564 | bool isInitList; | |||
10565 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | |||
10566 | ||||
10567 | public: | |||
10568 | typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; | |||
10569 | ||||
10570 | SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), | |||
10571 | S(S), OrigDecl(OrigDecl) { | |||
10572 | isPODType = false; | |||
10573 | isRecordType = false; | |||
10574 | isReferenceType = false; | |||
10575 | isInitList = false; | |||
10576 | if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { | |||
10577 | isPODType = VD->getType().isPODType(S.Context); | |||
10578 | isRecordType = VD->getType()->isRecordType(); | |||
10579 | isReferenceType = VD->getType()->isReferenceType(); | |||
10580 | } | |||
10581 | } | |||
10582 | ||||
10583 | // For most expressions, just call the visitor. For initializer lists, | |||
10584 | // track the index of the field being initialized since fields are | |||
10585 | // initialized in order allowing use of previously initialized fields. | |||
10586 | void CheckExpr(Expr *E) { | |||
10587 | InitListExpr *InitList = dyn_cast<InitListExpr>(E); | |||
10588 | if (!InitList) { | |||
10589 | Visit(E); | |||
10590 | return; | |||
10591 | } | |||
10592 | ||||
10593 | // Track and increment the index here. | |||
10594 | isInitList = true; | |||
10595 | InitFieldIndex.push_back(0); | |||
10596 | for (auto Child : InitList->children()) { | |||
10597 | CheckExpr(cast<Expr>(Child)); | |||
10598 | ++InitFieldIndex.back(); | |||
10599 | } | |||
10600 | InitFieldIndex.pop_back(); | |||
10601 | } | |||
10602 | ||||
10603 | // Returns true if MemberExpr is checked and no further checking is needed. | |||
10604 | // Returns false if additional checking is required. | |||
10605 | bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { | |||
10606 | llvm::SmallVector<FieldDecl*, 4> Fields; | |||
10607 | Expr *Base = E; | |||
10608 | bool ReferenceField = false; | |||
10609 | ||||
10610 | // Get the field members used. | |||
10611 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | |||
10612 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | |||
10613 | if (!FD) | |||
10614 | return false; | |||
10615 | Fields.push_back(FD); | |||
10616 | if (FD->getType()->isReferenceType()) | |||
10617 | ReferenceField = true; | |||
10618 | Base = ME->getBase()->IgnoreParenImpCasts(); | |||
10619 | } | |||
10620 | ||||
10621 | // Keep checking only if the base Decl is the same. | |||
10622 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); | |||
10623 | if (!DRE || DRE->getDecl() != OrigDecl) | |||
10624 | return false; | |||
10625 | ||||
10626 | // A reference field can be bound to an unininitialized field. | |||
10627 | if (CheckReference && !ReferenceField) | |||
10628 | return true; | |||
10629 | ||||
10630 | // Convert FieldDecls to their index number. | |||
10631 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | |||
10632 | for (const FieldDecl *I : llvm::reverse(Fields)) | |||
10633 | UsedFieldIndex.push_back(I->getFieldIndex()); | |||
10634 | ||||
10635 | // See if a warning is needed by checking the first difference in index | |||
10636 | // numbers. If field being used has index less than the field being | |||
10637 | // initialized, then the use is safe. | |||
10638 | for (auto UsedIter = UsedFieldIndex.begin(), | |||
10639 | UsedEnd = UsedFieldIndex.end(), | |||
10640 | OrigIter = InitFieldIndex.begin(), | |||
10641 | OrigEnd = InitFieldIndex.end(); | |||
10642 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | |||
10643 | if (*UsedIter < *OrigIter) | |||
10644 | return true; | |||
10645 | if (*UsedIter > *OrigIter) | |||
10646 | break; | |||
10647 | } | |||
10648 | ||||
10649 | // TODO: Add a different warning which will print the field names. | |||
10650 | HandleDeclRefExpr(DRE); | |||
10651 | return true; | |||
10652 | } | |||
10653 | ||||
10654 | // For most expressions, the cast is directly above the DeclRefExpr. | |||
10655 | // For conditional operators, the cast can be outside the conditional | |||
10656 | // operator if both expressions are DeclRefExpr's. | |||
10657 | void HandleValue(Expr *E) { | |||
10658 | E = E->IgnoreParens(); | |||
10659 | if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { | |||
10660 | HandleDeclRefExpr(DRE); | |||
10661 | return; | |||
10662 | } | |||
10663 | ||||
10664 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | |||
10665 | Visit(CO->getCond()); | |||
10666 | HandleValue(CO->getTrueExpr()); | |||
10667 | HandleValue(CO->getFalseExpr()); | |||
10668 | return; | |||
10669 | } | |||
10670 | ||||
10671 | if (BinaryConditionalOperator *BCO = | |||
10672 | dyn_cast<BinaryConditionalOperator>(E)) { | |||
10673 | Visit(BCO->getCond()); | |||
10674 | HandleValue(BCO->getFalseExpr()); | |||
10675 | return; | |||
10676 | } | |||
10677 | ||||
10678 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | |||
10679 | HandleValue(OVE->getSourceExpr()); | |||
10680 | return; | |||
10681 | } | |||
10682 | ||||
10683 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
10684 | if (BO->getOpcode() == BO_Comma) { | |||
10685 | Visit(BO->getLHS()); | |||
10686 | HandleValue(BO->getRHS()); | |||
10687 | return; | |||
10688 | } | |||
10689 | } | |||
10690 | ||||
10691 | if (isa<MemberExpr>(E)) { | |||
10692 | if (isInitList) { | |||
10693 | if (CheckInitListMemberExpr(cast<MemberExpr>(E), | |||
10694 | false /*CheckReference*/)) | |||
10695 | return; | |||
10696 | } | |||
10697 | ||||
10698 | Expr *Base = E->IgnoreParenImpCasts(); | |||
10699 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | |||
10700 | // Check for static member variables and don't warn on them. | |||
10701 | if (!isa<FieldDecl>(ME->getMemberDecl())) | |||
10702 | return; | |||
10703 | Base = ME->getBase()->IgnoreParenImpCasts(); | |||
10704 | } | |||
10705 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) | |||
10706 | HandleDeclRefExpr(DRE); | |||
10707 | return; | |||
10708 | } | |||
10709 | ||||
10710 | Visit(E); | |||
10711 | } | |||
10712 | ||||
10713 | // Reference types not handled in HandleValue are handled here since all | |||
10714 | // uses of references are bad, not just r-value uses. | |||
10715 | void VisitDeclRefExpr(DeclRefExpr *E) { | |||
10716 | if (isReferenceType) | |||
10717 | HandleDeclRefExpr(E); | |||
10718 | } | |||
10719 | ||||
10720 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
10721 | if (E->getCastKind() == CK_LValueToRValue) { | |||
10722 | HandleValue(E->getSubExpr()); | |||
10723 | return; | |||
10724 | } | |||
10725 | ||||
10726 | Inherited::VisitImplicitCastExpr(E); | |||
10727 | } | |||
10728 | ||||
10729 | void VisitMemberExpr(MemberExpr *E) { | |||
10730 | if (isInitList) { | |||
10731 | if (CheckInitListMemberExpr(E, true /*CheckReference*/)) | |||
10732 | return; | |||
10733 | } | |||
10734 | ||||
10735 | // Don't warn on arrays since they can be treated as pointers. | |||
10736 | if (E->getType()->canDecayToPointerType()) return; | |||
10737 | ||||
10738 | // Warn when a non-static method call is followed by non-static member | |||
10739 | // field accesses, which is followed by a DeclRefExpr. | |||
10740 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); | |||
10741 | bool Warn = (MD && !MD->isStatic()); | |||
10742 | Expr *Base = E->getBase()->IgnoreParenImpCasts(); | |||
10743 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | |||
10744 | if (!isa<FieldDecl>(ME->getMemberDecl())) | |||
10745 | Warn = false; | |||
10746 | Base = ME->getBase()->IgnoreParenImpCasts(); | |||
10747 | } | |||
10748 | ||||
10749 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { | |||
10750 | if (Warn) | |||
10751 | HandleDeclRefExpr(DRE); | |||
10752 | return; | |||
10753 | } | |||
10754 | ||||
10755 | // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. | |||
10756 | // Visit that expression. | |||
10757 | Visit(Base); | |||
10758 | } | |||
10759 | ||||
10760 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | |||
10761 | Expr *Callee = E->getCallee(); | |||
10762 | ||||
10763 | if (isa<UnresolvedLookupExpr>(Callee)) | |||
10764 | return Inherited::VisitCXXOperatorCallExpr(E); | |||
10765 | ||||
10766 | Visit(Callee); | |||
10767 | for (auto Arg: E->arguments()) | |||
10768 | HandleValue(Arg->IgnoreParenImpCasts()); | |||
10769 | } | |||
10770 | ||||
10771 | void VisitUnaryOperator(UnaryOperator *E) { | |||
10772 | // For POD record types, addresses of its own members are well-defined. | |||
10773 | if (E->getOpcode() == UO_AddrOf && isRecordType && | |||
10774 | isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { | |||
10775 | if (!isPODType) | |||
10776 | HandleValue(E->getSubExpr()); | |||
10777 | return; | |||
10778 | } | |||
10779 | ||||
10780 | if (E->isIncrementDecrementOp()) { | |||
10781 | HandleValue(E->getSubExpr()); | |||
10782 | return; | |||
10783 | } | |||
10784 | ||||
10785 | Inherited::VisitUnaryOperator(E); | |||
10786 | } | |||
10787 | ||||
10788 | void VisitObjCMessageExpr(ObjCMessageExpr *E) {} | |||
10789 | ||||
10790 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | |||
10791 | if (E->getConstructor()->isCopyConstructor()) { | |||
10792 | Expr *ArgExpr = E->getArg(0); | |||
10793 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | |||
10794 | if (ILE->getNumInits() == 1) | |||
10795 | ArgExpr = ILE->getInit(0); | |||
10796 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | |||
10797 | if (ICE->getCastKind() == CK_NoOp) | |||
10798 | ArgExpr = ICE->getSubExpr(); | |||
10799 | HandleValue(ArgExpr); | |||
10800 | return; | |||
10801 | } | |||
10802 | Inherited::VisitCXXConstructExpr(E); | |||
10803 | } | |||
10804 | ||||
10805 | void VisitCallExpr(CallExpr *E) { | |||
10806 | // Treat std::move as a use. | |||
10807 | if (E->isCallToStdMove()) { | |||
10808 | HandleValue(E->getArg(0)); | |||
10809 | return; | |||
10810 | } | |||
10811 | ||||
10812 | Inherited::VisitCallExpr(E); | |||
10813 | } | |||
10814 | ||||
10815 | void VisitBinaryOperator(BinaryOperator *E) { | |||
10816 | if (E->isCompoundAssignmentOp()) { | |||
10817 | HandleValue(E->getLHS()); | |||
10818 | Visit(E->getRHS()); | |||
10819 | return; | |||
10820 | } | |||
10821 | ||||
10822 | Inherited::VisitBinaryOperator(E); | |||
10823 | } | |||
10824 | ||||
10825 | // A custom visitor for BinaryConditionalOperator is needed because the | |||
10826 | // regular visitor would check the condition and true expression separately | |||
10827 | // but both point to the same place giving duplicate diagnostics. | |||
10828 | void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { | |||
10829 | Visit(E->getCond()); | |||
10830 | Visit(E->getFalseExpr()); | |||
10831 | } | |||
10832 | ||||
10833 | void HandleDeclRefExpr(DeclRefExpr *DRE) { | |||
10834 | Decl* ReferenceDecl = DRE->getDecl(); | |||
10835 | if (OrigDecl != ReferenceDecl) return; | |||
10836 | unsigned diag; | |||
10837 | if (isReferenceType) { | |||
10838 | diag = diag::warn_uninit_self_reference_in_reference_init; | |||
10839 | } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { | |||
10840 | diag = diag::warn_static_self_reference_in_init; | |||
10841 | } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || | |||
10842 | isa<NamespaceDecl>(OrigDecl->getDeclContext()) || | |||
10843 | DRE->getDecl()->getType()->isRecordType()) { | |||
10844 | diag = diag::warn_uninit_self_reference_in_init; | |||
10845 | } else { | |||
10846 | // Local variables will be handled by the CFG analysis. | |||
10847 | return; | |||
10848 | } | |||
10849 | ||||
10850 | S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, | |||
10851 | S.PDiag(diag) | |||
10852 | << DRE->getDecl() << OrigDecl->getLocation() | |||
10853 | << DRE->getSourceRange()); | |||
10854 | } | |||
10855 | }; | |||
10856 | ||||
10857 | /// CheckSelfReference - Warns if OrigDecl is used in expression E. | |||
10858 | static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, | |||
10859 | bool DirectInit) { | |||
10860 | // Parameters arguments are occassionially constructed with itself, | |||
10861 | // for instance, in recursive functions. Skip them. | |||
10862 | if (isa<ParmVarDecl>(OrigDecl)) | |||
10863 | return; | |||
10864 | ||||
10865 | E = E->IgnoreParens(); | |||
10866 | ||||
10867 | // Skip checking T a = a where T is not a record or reference type. | |||
10868 | // Doing so is a way to silence uninitialized warnings. | |||
10869 | if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) | |||
10870 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) | |||
10871 | if (ICE->getCastKind() == CK_LValueToRValue) | |||
10872 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) | |||
10873 | if (DRE->getDecl() == OrigDecl) | |||
10874 | return; | |||
10875 | ||||
10876 | SelfReferenceChecker(S, OrigDecl).CheckExpr(E); | |||
10877 | } | |||
10878 | } // end anonymous namespace | |||
10879 | ||||
10880 | namespace { | |||
10881 | // Simple wrapper to add the name of a variable or (if no variable is | |||
10882 | // available) a DeclarationName into a diagnostic. | |||
10883 | struct VarDeclOrName { | |||
10884 | VarDecl *VDecl; | |||
10885 | DeclarationName Name; | |||
10886 | ||||
10887 | friend const Sema::SemaDiagnosticBuilder & | |||
10888 | operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { | |||
10889 | return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; | |||
10890 | } | |||
10891 | }; | |||
10892 | } // end anonymous namespace | |||
10893 | ||||
10894 | QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, | |||
10895 | DeclarationName Name, QualType Type, | |||
10896 | TypeSourceInfo *TSI, | |||
10897 | SourceRange Range, bool DirectInit, | |||
10898 | Expr *Init) { | |||
10899 | bool IsInitCapture = !VDecl; | |||
10900 | assert((!VDecl || !VDecl->isInitCapture()) &&(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization" ) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10901, __PRETTY_FUNCTION__)) | |||
10901 | "init captures are expected to be deduced prior to initialization")(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization" ) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10901, __PRETTY_FUNCTION__)); | |||
10902 | ||||
10903 | VarDeclOrName VN{VDecl, Name}; | |||
10904 | ||||
10905 | DeducedType *Deduced = Type->getContainedDeducedType(); | |||
10906 | assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")((Deduced && "deduceVarTypeFromInitializer for non-deduced type" ) ? static_cast<void> (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10906, __PRETTY_FUNCTION__)); | |||
10907 | ||||
10908 | // C++11 [dcl.spec.auto]p3 | |||
10909 | if (!Init) { | |||
10910 | assert(VDecl && "no init for init capture deduction?")((VDecl && "no init for init capture deduction?") ? static_cast <void> (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10910, __PRETTY_FUNCTION__)); | |||
10911 | ||||
10912 | // Except for class argument deduction, and then for an initializing | |||
10913 | // declaration only, i.e. no static at class scope or extern. | |||
10914 | if (!isa<DeducedTemplateSpecializationType>(Deduced) || | |||
10915 | VDecl->hasExternalStorage() || | |||
10916 | VDecl->isStaticDataMember()) { | |||
10917 | Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) | |||
10918 | << VDecl->getDeclName() << Type; | |||
10919 | return QualType(); | |||
10920 | } | |||
10921 | } | |||
10922 | ||||
10923 | ArrayRef<Expr*> DeduceInits; | |||
10924 | if (Init) | |||
10925 | DeduceInits = Init; | |||
10926 | ||||
10927 | if (DirectInit) { | |||
10928 | if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) | |||
10929 | DeduceInits = PL->exprs(); | |||
10930 | } | |||
10931 | ||||
10932 | if (isa<DeducedTemplateSpecializationType>(Deduced)) { | |||
10933 | assert(VDecl && "non-auto type for init capture deduction?")((VDecl && "non-auto type for init capture deduction?" ) ? static_cast<void> (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 10933, __PRETTY_FUNCTION__)); | |||
10934 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | |||
10935 | InitializationKind Kind = InitializationKind::CreateForInit( | |||
10936 | VDecl->getLocation(), DirectInit, Init); | |||
10937 | // FIXME: Initialization should not be taking a mutable list of inits. | |||
10938 | SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); | |||
10939 | return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, | |||
10940 | InitsCopy); | |||
10941 | } | |||
10942 | ||||
10943 | if (DirectInit) { | |||
10944 | if (auto *IL = dyn_cast<InitListExpr>(Init)) | |||
10945 | DeduceInits = IL->inits(); | |||
10946 | } | |||
10947 | ||||
10948 | // Deduction only works if we have exactly one source expression. | |||
10949 | if (DeduceInits.empty()) { | |||
10950 | // It isn't possible to write this directly, but it is possible to | |||
10951 | // end up in this situation with "auto x(some_pack...);" | |||
10952 | Diag(Init->getBeginLoc(), IsInitCapture | |||
10953 | ? diag::err_init_capture_no_expression | |||
10954 | : diag::err_auto_var_init_no_expression) | |||
10955 | << VN << Type << Range; | |||
10956 | return QualType(); | |||
10957 | } | |||
10958 | ||||
10959 | if (DeduceInits.size() > 1) { | |||
10960 | Diag(DeduceInits[1]->getBeginLoc(), | |||
10961 | IsInitCapture ? diag::err_init_capture_multiple_expressions | |||
10962 | : diag::err_auto_var_init_multiple_expressions) | |||
10963 | << VN << Type << Range; | |||
10964 | return QualType(); | |||
10965 | } | |||
10966 | ||||
10967 | Expr *DeduceInit = DeduceInits[0]; | |||
10968 | if (DirectInit && isa<InitListExpr>(DeduceInit)) { | |||
10969 | Diag(Init->getBeginLoc(), IsInitCapture | |||
10970 | ? diag::err_init_capture_paren_braces | |||
10971 | : diag::err_auto_var_init_paren_braces) | |||
10972 | << isa<InitListExpr>(Init) << VN << Type << Range; | |||
10973 | return QualType(); | |||
10974 | } | |||
10975 | ||||
10976 | // Expressions default to 'id' when we're in a debugger. | |||
10977 | bool DefaultedAnyToId = false; | |||
10978 | if (getLangOpts().DebuggerCastResultToId && | |||
10979 | Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { | |||
10980 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | |||
10981 | if (Result.isInvalid()) { | |||
10982 | return QualType(); | |||
10983 | } | |||
10984 | Init = Result.get(); | |||
10985 | DefaultedAnyToId = true; | |||
10986 | } | |||
10987 | ||||
10988 | // C++ [dcl.decomp]p1: | |||
10989 | // If the assignment-expression [...] has array type A and no ref-qualifier | |||
10990 | // is present, e has type cv A | |||
10991 | if (VDecl && isa<DecompositionDecl>(VDecl) && | |||
10992 | Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && | |||
10993 | DeduceInit->getType()->isConstantArrayType()) | |||
10994 | return Context.getQualifiedType(DeduceInit->getType(), | |||
10995 | Type.getQualifiers()); | |||
10996 | ||||
10997 | QualType DeducedType; | |||
10998 | if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { | |||
10999 | if (!IsInitCapture) | |||
11000 | DiagnoseAutoDeductionFailure(VDecl, DeduceInit); | |||
11001 | else if (isa<InitListExpr>(Init)) | |||
11002 | Diag(Range.getBegin(), | |||
11003 | diag::err_init_capture_deduction_failure_from_init_list) | |||
11004 | << VN | |||
11005 | << (DeduceInit->getType().isNull() ? TSI->getType() | |||
11006 | : DeduceInit->getType()) | |||
11007 | << DeduceInit->getSourceRange(); | |||
11008 | else | |||
11009 | Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) | |||
11010 | << VN << TSI->getType() | |||
11011 | << (DeduceInit->getType().isNull() ? TSI->getType() | |||
11012 | : DeduceInit->getType()) | |||
11013 | << DeduceInit->getSourceRange(); | |||
11014 | } | |||
11015 | ||||
11016 | // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using | |||
11017 | // 'id' instead of a specific object type prevents most of our usual | |||
11018 | // checks. | |||
11019 | // We only want to warn outside of template instantiations, though: | |||
11020 | // inside a template, the 'id' could have come from a parameter. | |||
11021 | if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && | |||
11022 | !DeducedType.isNull() && DeducedType->isObjCIdType()) { | |||
11023 | SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); | |||
11024 | Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; | |||
11025 | } | |||
11026 | ||||
11027 | return DeducedType; | |||
11028 | } | |||
11029 | ||||
11030 | bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, | |||
11031 | Expr *Init) { | |||
11032 | QualType DeducedType = deduceVarTypeFromInitializer( | |||
11033 | VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), | |||
11034 | VDecl->getSourceRange(), DirectInit, Init); | |||
11035 | if (DeducedType.isNull()) { | |||
11036 | VDecl->setInvalidDecl(); | |||
11037 | return true; | |||
11038 | } | |||
11039 | ||||
11040 | VDecl->setType(DeducedType); | |||
11041 | assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) : __assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 11041, __PRETTY_FUNCTION__)); | |||
11042 | ||||
11043 | // In ARC, infer lifetime. | |||
11044 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) | |||
11045 | VDecl->setInvalidDecl(); | |||
11046 | ||||
11047 | // If this is a redeclaration, check that the type we just deduced matches | |||
11048 | // the previously declared type. | |||
11049 | if (VarDecl *Old = VDecl->getPreviousDecl()) { | |||
11050 | // We never need to merge the type, because we cannot form an incomplete | |||
11051 | // array of auto, nor deduce such a type. | |||
11052 | MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); | |||
11053 | } | |||
11054 | ||||
11055 | // Check the deduced type is valid for a variable declaration. | |||
11056 | CheckVariableDeclarationType(VDecl); | |||
11057 | return VDecl->isInvalidDecl(); | |||
11058 | } | |||
11059 | ||||
11060 | /// AddInitializerToDecl - Adds the initializer Init to the | |||
11061 | /// declaration dcl. If DirectInit is true, this is C++ direct | |||
11062 | /// initialization rather than copy initialization. | |||
11063 | void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { | |||
11064 | // If there is no declaration, there was an error parsing it. Just ignore | |||
11065 | // the initializer. | |||
11066 | if (!RealDecl || RealDecl->isInvalidDecl()) { | |||
11067 | CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); | |||
11068 | return; | |||
11069 | } | |||
11070 | ||||
11071 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { | |||
11072 | // Pure-specifiers are handled in ActOnPureSpecifier. | |||
11073 | Diag(Method->getLocation(), diag::err_member_function_initialization) | |||
11074 | << Method->getDeclName() << Init->getSourceRange(); | |||
11075 | Method->setInvalidDecl(); | |||
11076 | return; | |||
11077 | } | |||
11078 | ||||
11079 | VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); | |||
11080 | if (!VDecl) { | |||
11081 | assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")((!isa<FieldDecl>(RealDecl) && "field init shouldn't get here" ) ? static_cast<void> (0) : __assert_fail ("!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 11081, __PRETTY_FUNCTION__)); | |||
11082 | Diag(RealDecl->getLocation(), diag::err_illegal_initializer); | |||
11083 | RealDecl->setInvalidDecl(); | |||
11084 | return; | |||
11085 | } | |||
11086 | ||||
11087 | // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. | |||
11088 | if (VDecl->getType()->isUndeducedType()) { | |||
11089 | // Attempt typo correction early so that the type of the init expression can | |||
11090 | // be deduced based on the chosen correction if the original init contains a | |||
11091 | // TypoExpr. | |||
11092 | ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); | |||
11093 | if (!Res.isUsable()) { | |||
11094 | RealDecl->setInvalidDecl(); | |||
11095 | return; | |||
11096 | } | |||
11097 | Init = Res.get(); | |||
11098 | ||||
11099 | if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) | |||
11100 | return; | |||
11101 | } | |||
11102 | ||||
11103 | // dllimport cannot be used on variable definitions. | |||
11104 | if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { | |||
11105 | Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); | |||
11106 | VDecl->setInvalidDecl(); | |||
11107 | return; | |||
11108 | } | |||
11109 | ||||
11110 | if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { | |||
11111 | // C99 6.7.8p5. C++ has no such restriction, but that is a defect. | |||
11112 | Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); | |||
11113 | VDecl->setInvalidDecl(); | |||
11114 | return; | |||
11115 | } | |||
11116 | ||||
11117 | if (!VDecl->getType()->isDependentType()) { | |||
11118 | // A definition must end up with a complete type, which means it must be | |||
11119 | // complete with the restriction that an array type might be completed by | |||
11120 | // the initializer; note that later code assumes this restriction. | |||
11121 | QualType BaseDeclType = VDecl->getType(); | |||
11122 | if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) | |||
11123 | BaseDeclType = Array->getElementType(); | |||
11124 | if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, | |||
11125 | diag::err_typecheck_decl_incomplete_type)) { | |||
11126 | RealDecl->setInvalidDecl(); | |||
11127 | return; | |||
11128 | } | |||
11129 | ||||
11130 | // The variable can not have an abstract class type. | |||
11131 | if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), | |||
11132 | diag::err_abstract_type_in_decl, | |||
11133 | AbstractVariableType)) | |||
11134 | VDecl->setInvalidDecl(); | |||
11135 | } | |||
11136 | ||||
11137 | // If adding the initializer will turn this declaration into a definition, | |||
11138 | // and we already have a definition for this variable, diagnose or otherwise | |||
11139 | // handle the situation. | |||
11140 | VarDecl *Def; | |||
11141 | if ((Def = VDecl->getDefinition()) && Def != VDecl && | |||
11142 | (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && | |||
11143 | !VDecl->isThisDeclarationADemotedDefinition() && | |||
11144 | checkVarDeclRedefinition(Def, VDecl)) | |||
11145 | return; | |||
11146 | ||||
11147 | if (getLangOpts().CPlusPlus) { | |||
11148 | // C++ [class.static.data]p4 | |||
11149 | // If a static data member is of const integral or const | |||
11150 | // enumeration type, its declaration in the class definition can | |||
11151 | // specify a constant-initializer which shall be an integral | |||
11152 | // constant expression (5.19). In that case, the member can appear | |||
11153 | // in integral constant expressions. The member shall still be | |||
11154 | // defined in a namespace scope if it is used in the program and the | |||
11155 | // namespace scope definition shall not contain an initializer. | |||
11156 | // | |||
11157 | // We already performed a redefinition check above, but for static | |||
11158 | // data members we also need to check whether there was an in-class | |||
11159 | // declaration with an initializer. | |||
11160 | if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { | |||
11161 | Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) | |||
11162 | << VDecl->getDeclName(); | |||
11163 | Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), | |||
11164 | diag::note_previous_initializer) | |||
11165 | << 0; | |||
11166 | return; | |||
11167 | } | |||
11168 | ||||
11169 | if (VDecl->hasLocalStorage()) | |||
11170 | setFunctionHasBranchProtectedScope(); | |||
11171 | ||||
11172 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { | |||
11173 | VDecl->setInvalidDecl(); | |||
11174 | return; | |||
11175 | } | |||
11176 | } | |||
11177 | ||||
11178 | // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside | |||
11179 | // a kernel function cannot be initialized." | |||
11180 | if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { | |||
11181 | Diag(VDecl->getLocation(), diag::err_local_cant_init); | |||
11182 | VDecl->setInvalidDecl(); | |||
11183 | return; | |||
11184 | } | |||
11185 | ||||
11186 | // Get the decls type and save a reference for later, since | |||
11187 | // CheckInitializerTypes may change it. | |||
11188 | QualType DclT = VDecl->getType(), SavT = DclT; | |||
11189 | ||||
11190 | // Expressions default to 'id' when we're in a debugger | |||
11191 | // and we are assigning it to a variable of Objective-C pointer type. | |||
11192 | if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && | |||
11193 | Init->getType() == Context.UnknownAnyTy) { | |||
11194 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | |||
11195 | if (Result.isInvalid()) { | |||
11196 | VDecl->setInvalidDecl(); | |||
11197 | return; | |||
11198 | } | |||
11199 | Init = Result.get(); | |||
11200 | } | |||
11201 | ||||
11202 | // Perform the initialization. | |||
11203 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); | |||
11204 | if (!VDecl->isInvalidDecl()) { | |||
11205 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | |||
11206 | InitializationKind Kind = InitializationKind::CreateForInit( | |||
11207 | VDecl->getLocation(), DirectInit, Init); | |||
11208 | ||||
11209 | MultiExprArg Args = Init; | |||
11210 | if (CXXDirectInit) | |||
11211 | Args = MultiExprArg(CXXDirectInit->getExprs(), | |||
11212 | CXXDirectInit->getNumExprs()); | |||
11213 | ||||
11214 | // Try to correct any TypoExprs in the initialization arguments. | |||
11215 | for (size_t Idx = 0; Idx < Args.size(); ++Idx) { | |||
11216 | ExprResult Res = CorrectDelayedTyposInExpr( | |||
11217 | Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { | |||
11218 | InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); | |||
11219 | return Init.Failed() ? ExprError() : E; | |||
11220 | }); | |||
11221 | if (Res.isInvalid()) { | |||
11222 | VDecl->setInvalidDecl(); | |||
11223 | } else if (Res.get() != Args[Idx]) { | |||
11224 | Args[Idx] = Res.get(); | |||
11225 | } | |||
11226 | } | |||
11227 | if (VDecl->isInvalidDecl()) | |||
11228 | return; | |||
11229 | ||||
11230 | InitializationSequence InitSeq(*this, Entity, Kind, Args, | |||
11231 | /*TopLevelOfInitList=*/false, | |||
11232 | /*TreatUnavailableAsInvalid=*/false); | |||
11233 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); | |||
11234 | if (Result.isInvalid()) { | |||
11235 | VDecl->setInvalidDecl(); | |||
11236 | return; | |||
11237 | } | |||
11238 | ||||
11239 | Init = Result.getAs<Expr>(); | |||
11240 | } | |||
11241 | ||||
11242 | // Check for self-references within variable initializers. | |||
11243 | // Variables declared within a function/method body (except for references) | |||
11244 | // are handled by a dataflow analysis. | |||
11245 | if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || | |||
11246 | VDecl->getType()->isReferenceType()) { | |||
11247 | CheckSelfReference(*this, RealDecl, Init, DirectInit); | |||
11248 | } | |||
11249 | ||||
11250 | // If the type changed, it means we had an incomplete type that was | |||
11251 | // completed by the initializer. For example: | |||
11252 | // int ary[] = { 1, 3, 5 }; | |||
11253 | // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. | |||
11254 | if (!VDecl->isInvalidDecl() && (DclT != SavT)) | |||
11255 | VDecl->setType(DclT); | |||
11256 | ||||
11257 | if (!VDecl->isInvalidDecl()) { | |||
11258 | checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); | |||
11259 | ||||
11260 | if (VDecl->hasAttr<BlocksAttr>()) | |||
11261 | checkRetainCycles(VDecl, Init); | |||
11262 | ||||
11263 | // It is safe to assign a weak reference into a strong variable. | |||
11264 | // Although this code can still have problems: | |||
11265 | // id x = self.weakProp; | |||
11266 | // id y = self.weakProp; | |||
11267 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | |||
11268 | // paths through the function. This should be revisited if | |||
11269 | // -Wrepeated-use-of-weak is made flow-sensitive. | |||
11270 | if (FunctionScopeInfo *FSI = getCurFunction()) | |||
11271 | if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || | |||
11272 | VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && | |||
11273 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | |||
11274 | Init->getBeginLoc())) | |||
11275 | FSI->markSafeWeakUse(Init); | |||
11276 | } | |||
11277 | ||||
11278 | // The initialization is usually a full-expression. | |||
11279 | // | |||
11280 | // FIXME: If this is a braced initialization of an aggregate, it is not | |||
11281 | // an expression, and each individual field initializer is a separate | |||
11282 | // full-expression. For instance, in: | |||
11283 | // | |||
11284 | // struct Temp { ~Temp(); }; | |||
11285 | // struct S { S(Temp); }; | |||
11286 | // struct T { S a, b; } t = { Temp(), Temp() } | |||
11287 | // | |||
11288 | // we should destroy the first Temp before constructing the second. | |||
11289 | ExprResult Result = | |||
11290 | ActOnFinishFullExpr(Init, VDecl->getLocation(), | |||
11291 | /*DiscardedValue*/ false, VDecl->isConstexpr()); | |||
11292 | if (Result.isInvalid()) { | |||
11293 | VDecl->setInvalidDecl(); | |||
11294 | return; | |||
11295 | } | |||
11296 | Init = Result.get(); | |||
11297 | ||||
11298 | // Attach the initializer to the decl. | |||
11299 | VDecl->setInit(Init); | |||
11300 | ||||
11301 | if (VDecl->isLocalVarDecl()) { | |||
11302 | // Don't check the initializer if the declaration is malformed. | |||
11303 | if (VDecl->isInvalidDecl()) { | |||
11304 | // do nothing | |||
11305 | ||||
11306 | // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. | |||
11307 | // This is true even in OpenCL C++. | |||
11308 | } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { | |||
11309 | CheckForConstantInitializer(Init, DclT); | |||
11310 | ||||
11311 | // Otherwise, C++ does not restrict the initializer. | |||
11312 | } else if (getLangOpts().CPlusPlus) { | |||
11313 | // do nothing | |||
11314 | ||||
11315 | // C99 6.7.8p4: All the expressions in an initializer for an object that has | |||
11316 | // static storage duration shall be constant expressions or string literals. | |||
11317 | } else if (VDecl->getStorageClass() == SC_Static) { | |||
11318 | CheckForConstantInitializer(Init, DclT); | |||
11319 | ||||
11320 | // C89 is stricter than C99 for aggregate initializers. | |||
11321 | // C89 6.5.7p3: All the expressions [...] in an initializer list | |||
11322 | // for an object that has aggregate or union type shall be | |||
11323 | // constant expressions. | |||
11324 | } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && | |||
11325 | isa<InitListExpr>(Init)) { | |||
11326 | const Expr *Culprit; | |||
11327 | if (!Init->isConstantInitializer(Context, false, &Culprit)) { | |||
11328 | Diag(Culprit->getExprLoc(), | |||
11329 | diag::ext_aggregate_init_not_constant) | |||
11330 | << Culprit->getSourceRange(); | |||
11331 | } | |||
11332 | } | |||
11333 | ||||
11334 | if (auto *E = dyn_cast<ExprWithCleanups>(Init)) | |||
11335 | if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) | |||
11336 | if (VDecl->hasLocalStorage()) | |||
11337 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | |||
11338 | } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && | |||
11339 | VDecl->getLexicalDeclContext()->isRecord()) { | |||
11340 | // This is an in-class initialization for a static data member, e.g., | |||
11341 | // | |||
11342 | // struct S { | |||
11343 | // static const int value = 17; | |||
11344 | // }; | |||
11345 | ||||
11346 | // C++ [class.mem]p4: | |||
11347 | // A member-declarator can contain a constant-initializer only | |||
11348 | // if it declares a static member (9.4) of const integral or | |||
11349 | // const enumeration type, see 9.4.2. | |||
11350 | // | |||
11351 | // C++11 [class.static.data]p3: | |||
11352 | // If a non-volatile non-inline const static data member is of integral | |||
11353 | // or enumeration type, its declaration in the class definition can | |||
11354 | // specify a brace-or-equal-initializer in which every initializer-clause | |||
11355 | // that is an assignment-expression is a constant expression. A static | |||
11356 | // data member of literal type can be declared in the class definition | |||
11357 | // with the constexpr specifier; if so, its declaration shall specify a | |||
11358 | // brace-or-equal-initializer in which every initializer-clause that is | |||
11359 | // an assignment-expression is a constant expression. | |||
11360 | ||||
11361 | // Do nothing on dependent types. | |||
11362 | if (DclT->isDependentType()) { | |||
11363 | ||||
11364 | // Allow any 'static constexpr' members, whether or not they are of literal | |||
11365 | // type. We separately check that every constexpr variable is of literal | |||
11366 | // type. | |||
11367 | } else if (VDecl->isConstexpr()) { | |||
11368 | ||||
11369 | // Require constness. | |||
11370 | } else if (!DclT.isConstQualified()) { | |||
11371 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) | |||
11372 | << Init->getSourceRange(); | |||
11373 | VDecl->setInvalidDecl(); | |||
11374 | ||||
11375 | // We allow integer constant expressions in all cases. | |||
11376 | } else if (DclT->isIntegralOrEnumerationType()) { | |||
11377 | // Check whether the expression is a constant expression. | |||
11378 | SourceLocation Loc; | |||
11379 | if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) | |||
11380 | // In C++11, a non-constexpr const static data member with an | |||
11381 | // in-class initializer cannot be volatile. | |||
11382 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); | |||
11383 | else if (Init->isValueDependent()) | |||
11384 | ; // Nothing to check. | |||
11385 | else if (Init->isIntegerConstantExpr(Context, &Loc)) | |||
11386 | ; // Ok, it's an ICE! | |||
11387 | else if (Init->getType()->isScopedEnumeralType() && | |||
11388 | Init->isCXX11ConstantExpr(Context)) | |||
11389 | ; // Ok, it is a scoped-enum constant expression. | |||
11390 | else if (Init->isEvaluatable(Context)) { | |||
11391 | // If we can constant fold the initializer through heroics, accept it, | |||
11392 | // but report this as a use of an extension for -pedantic. | |||
11393 | Diag(Loc, diag::ext_in_class_initializer_non_constant) | |||
11394 | << Init->getSourceRange(); | |||
11395 | } else { | |||
11396 | // Otherwise, this is some crazy unknown case. Report the issue at the | |||
11397 | // location provided by the isIntegerConstantExpr failed check. | |||
11398 | Diag(Loc, diag::err_in_class_initializer_non_constant) | |||
11399 | << Init->getSourceRange(); | |||
11400 | VDecl->setInvalidDecl(); | |||
11401 | } | |||
11402 | ||||
11403 | // We allow foldable floating-point constants as an extension. | |||
11404 | } else if (DclT->isFloatingType()) { // also permits complex, which is ok | |||
11405 | // In C++98, this is a GNU extension. In C++11, it is not, but we support | |||
11406 | // it anyway and provide a fixit to add the 'constexpr'. | |||
11407 | if (getLangOpts().CPlusPlus11) { | |||
11408 | Diag(VDecl->getLocation(), | |||
11409 | diag::ext_in_class_initializer_float_type_cxx11) | |||
11410 | << DclT << Init->getSourceRange(); | |||
11411 | Diag(VDecl->getBeginLoc(), | |||
11412 | diag::note_in_class_initializer_float_type_cxx11) | |||
11413 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | |||
11414 | } else { | |||
11415 | Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) | |||
11416 | << DclT << Init->getSourceRange(); | |||
11417 | ||||
11418 | if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { | |||
11419 | Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) | |||
11420 | << Init->getSourceRange(); | |||
11421 | VDecl->setInvalidDecl(); | |||
11422 | } | |||
11423 | } | |||
11424 | ||||
11425 | // Suggest adding 'constexpr' in C++11 for literal types. | |||
11426 | } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { | |||
11427 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) | |||
11428 | << DclT << Init->getSourceRange() | |||
11429 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | |||
11430 | VDecl->setConstexpr(true); | |||
11431 | ||||
11432 | } else { | |||
11433 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) | |||
11434 | << DclT << Init->getSourceRange(); | |||
11435 | VDecl->setInvalidDecl(); | |||
11436 | } | |||
11437 | } else if (VDecl->isFileVarDecl()) { | |||
11438 | // In C, extern is typically used to avoid tentative definitions when | |||
11439 | // declaring variables in headers, but adding an intializer makes it a | |||
11440 | // definition. This is somewhat confusing, so GCC and Clang both warn on it. | |||
11441 | // In C++, extern is often used to give implictly static const variables | |||
11442 | // external linkage, so don't warn in that case. If selectany is present, | |||
11443 | // this might be header code intended for C and C++ inclusion, so apply the | |||
11444 | // C++ rules. | |||
11445 | if (VDecl->getStorageClass() == SC_Extern && | |||
11446 | ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || | |||
11447 | !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && | |||
11448 | !(getLangOpts().CPlusPlus && VDecl->isExternC()) && | |||
11449 | !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) | |||
11450 | Diag(VDecl->getLocation(), diag::warn_extern_init); | |||
11451 | ||||
11452 | // In Microsoft C++ mode, a const variable defined in namespace scope has | |||
11453 | // external linkage by default if the variable is declared with | |||
11454 | // __declspec(dllexport). | |||
11455 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
11456 | getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && | |||
11457 | VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) | |||
11458 | VDecl->setStorageClass(SC_Extern); | |||
11459 | ||||
11460 | // C99 6.7.8p4. All file scoped initializers need to be constant. | |||
11461 | if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) | |||
11462 | CheckForConstantInitializer(Init, DclT); | |||
11463 | } | |||
11464 | ||||
11465 | // We will represent direct-initialization similarly to copy-initialization: | |||
11466 | // int x(1); -as-> int x = 1; | |||
11467 | // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); | |||
11468 | // | |||
11469 | // Clients that want to distinguish between the two forms, can check for | |||
11470 | // direct initializer using VarDecl::getInitStyle(). | |||
11471 | // A major benefit is that clients that don't particularly care about which | |||
11472 | // exactly form was it (like the CodeGen) can handle both cases without | |||
11473 | // special case code. | |||
11474 | ||||
11475 | // C++ 8.5p11: | |||
11476 | // The form of initialization (using parentheses or '=') is generally | |||
11477 | // insignificant, but does matter when the entity being initialized has a | |||
11478 | // class type. | |||
11479 | if (CXXDirectInit) { | |||
11480 | assert(DirectInit && "Call-style initializer must be direct init.")((DirectInit && "Call-style initializer must be direct init." ) ? static_cast<void> (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 11480, __PRETTY_FUNCTION__)); | |||
11481 | VDecl->setInitStyle(VarDecl::CallInit); | |||
11482 | } else if (DirectInit) { | |||
11483 | // This must be list-initialization. No other way is direct-initialization. | |||
11484 | VDecl->setInitStyle(VarDecl::ListInit); | |||
11485 | } | |||
11486 | ||||
11487 | CheckCompleteVariableDeclaration(VDecl); | |||
11488 | } | |||
11489 | ||||
11490 | /// ActOnInitializerError - Given that there was an error parsing an | |||
11491 | /// initializer for the given declaration, try to return to some form | |||
11492 | /// of sanity. | |||
11493 | void Sema::ActOnInitializerError(Decl *D) { | |||
11494 | // Our main concern here is re-establishing invariants like "a | |||
11495 | // variable's type is either dependent or complete". | |||
11496 | if (!D || D->isInvalidDecl()) return; | |||
11497 | ||||
11498 | VarDecl *VD = dyn_cast<VarDecl>(D); | |||
11499 | if (!VD) return; | |||
11500 | ||||
11501 | // Bindings are not usable if we can't make sense of the initializer. | |||
11502 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) | |||
11503 | for (auto *BD : DD->bindings()) | |||
11504 | BD->setInvalidDecl(); | |||
11505 | ||||
11506 | // Auto types are meaningless if we can't make sense of the initializer. | |||
11507 | if (ParsingInitForAutoVars.count(D)) { | |||
11508 | D->setInvalidDecl(); | |||
11509 | return; | |||
11510 | } | |||
11511 | ||||
11512 | QualType Ty = VD->getType(); | |||
11513 | if (Ty->isDependentType()) return; | |||
11514 | ||||
11515 | // Require a complete type. | |||
11516 | if (RequireCompleteType(VD->getLocation(), | |||
11517 | Context.getBaseElementType(Ty), | |||
11518 | diag::err_typecheck_decl_incomplete_type)) { | |||
11519 | VD->setInvalidDecl(); | |||
11520 | return; | |||
11521 | } | |||
11522 | ||||
11523 | // Require a non-abstract type. | |||
11524 | if (RequireNonAbstractType(VD->getLocation(), Ty, | |||
11525 | diag::err_abstract_type_in_decl, | |||
11526 | AbstractVariableType)) { | |||
11527 | VD->setInvalidDecl(); | |||
11528 | return; | |||
11529 | } | |||
11530 | ||||
11531 | // Don't bother complaining about constructors or destructors, | |||
11532 | // though. | |||
11533 | } | |||
11534 | ||||
11535 | void Sema::ActOnUninitializedDecl(Decl *RealDecl) { | |||
11536 | // If there is no declaration, there was an error parsing it. Just ignore it. | |||
11537 | if (!RealDecl) | |||
11538 | return; | |||
11539 | ||||
11540 | if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { | |||
11541 | QualType Type = Var->getType(); | |||
11542 | ||||
11543 | // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. | |||
11544 | if (isa<DecompositionDecl>(RealDecl)) { | |||
11545 | Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; | |||
11546 | Var->setInvalidDecl(); | |||
11547 | return; | |||
11548 | } | |||
11549 | ||||
11550 | if (Type->isUndeducedType() && | |||
11551 | DeduceVariableDeclarationType(Var, false, nullptr)) | |||
11552 | return; | |||
11553 | ||||
11554 | // C++11 [class.static.data]p3: A static data member can be declared with | |||
11555 | // the constexpr specifier; if so, its declaration shall specify | |||
11556 | // a brace-or-equal-initializer. | |||
11557 | // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to | |||
11558 | // the definition of a variable [...] or the declaration of a static data | |||
11559 | // member. | |||
11560 | if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && | |||
11561 | !Var->isThisDeclarationADemotedDefinition()) { | |||
11562 | if (Var->isStaticDataMember()) { | |||
11563 | // C++1z removes the relevant rule; the in-class declaration is always | |||
11564 | // a definition there. | |||
11565 | if (!getLangOpts().CPlusPlus17) { | |||
11566 | Diag(Var->getLocation(), | |||
11567 | diag::err_constexpr_static_mem_var_requires_init) | |||
11568 | << Var->getDeclName(); | |||
11569 | Var->setInvalidDecl(); | |||
11570 | return; | |||
11571 | } | |||
11572 | } else { | |||
11573 | Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); | |||
11574 | Var->setInvalidDecl(); | |||
11575 | return; | |||
11576 | } | |||
11577 | } | |||
11578 | ||||
11579 | // OpenCL v1.1 s6.5.3: variables declared in the constant address space must | |||
11580 | // be initialized. | |||
11581 | if (!Var->isInvalidDecl() && | |||
11582 | Var->getType().getAddressSpace() == LangAS::opencl_constant && | |||
11583 | Var->getStorageClass() != SC_Extern && !Var->getInit()) { | |||
11584 | Diag(Var->getLocation(), diag::err_opencl_constant_no_init); | |||
11585 | Var->setInvalidDecl(); | |||
11586 | return; | |||
11587 | } | |||
11588 | ||||
11589 | switch (Var->isThisDeclarationADefinition()) { | |||
11590 | case VarDecl::Definition: | |||
11591 | if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) | |||
11592 | break; | |||
11593 | ||||
11594 | // We have an out-of-line definition of a static data member | |||
11595 | // that has an in-class initializer, so we type-check this like | |||
11596 | // a declaration. | |||
11597 | // | |||
11598 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
11599 | ||||
11600 | case VarDecl::DeclarationOnly: | |||
11601 | // It's only a declaration. | |||
11602 | ||||
11603 | // Block scope. C99 6.7p7: If an identifier for an object is | |||
11604 | // declared with no linkage (C99 6.2.2p6), the type for the | |||
11605 | // object shall be complete. | |||
11606 | if (!Type->isDependentType() && Var->isLocalVarDecl() && | |||
11607 | !Var->hasLinkage() && !Var->isInvalidDecl() && | |||
11608 | RequireCompleteType(Var->getLocation(), Type, | |||
11609 | diag::err_typecheck_decl_incomplete_type)) | |||
11610 | Var->setInvalidDecl(); | |||
11611 | ||||
11612 | // Make sure that the type is not abstract. | |||
11613 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | |||
11614 | RequireNonAbstractType(Var->getLocation(), Type, | |||
11615 | diag::err_abstract_type_in_decl, | |||
11616 | AbstractVariableType)) | |||
11617 | Var->setInvalidDecl(); | |||
11618 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | |||
11619 | Var->getStorageClass() == SC_PrivateExtern) { | |||
11620 | Diag(Var->getLocation(), diag::warn_private_extern); | |||
11621 | Diag(Var->getLocation(), diag::note_private_extern); | |||
11622 | } | |||
11623 | ||||
11624 | return; | |||
11625 | ||||
11626 | case VarDecl::TentativeDefinition: | |||
11627 | // File scope. C99 6.9.2p2: A declaration of an identifier for an | |||
11628 | // object that has file scope without an initializer, and without a | |||
11629 | // storage-class specifier or with the storage-class specifier "static", | |||
11630 | // constitutes a tentative definition. Note: A tentative definition with | |||
11631 | // external linkage is valid (C99 6.2.2p5). | |||
11632 | if (!Var->isInvalidDecl()) { | |||
11633 | if (const IncompleteArrayType *ArrayT | |||
11634 | = Context.getAsIncompleteArrayType(Type)) { | |||
11635 | if (RequireCompleteType(Var->getLocation(), | |||
11636 | ArrayT->getElementType(), | |||
11637 | diag::err_illegal_decl_array_incomplete_type)) | |||
11638 | Var->setInvalidDecl(); | |||
11639 | } else if (Var->getStorageClass() == SC_Static) { | |||
11640 | // C99 6.9.2p3: If the declaration of an identifier for an object is | |||
11641 | // a tentative definition and has internal linkage (C99 6.2.2p3), the | |||
11642 | // declared type shall not be an incomplete type. | |||
11643 | // NOTE: code such as the following | |||
11644 | // static struct s; | |||
11645 | // struct s { int a; }; | |||
11646 | // is accepted by gcc. Hence here we issue a warning instead of | |||
11647 | // an error and we do not invalidate the static declaration. | |||
11648 | // NOTE: to avoid multiple warnings, only check the first declaration. | |||
11649 | if (Var->isFirstDecl()) | |||
11650 | RequireCompleteType(Var->getLocation(), Type, | |||
11651 | diag::ext_typecheck_decl_incomplete_type); | |||
11652 | } | |||
11653 | } | |||
11654 | ||||
11655 | // Record the tentative definition; we're done. | |||
11656 | if (!Var->isInvalidDecl()) | |||
11657 | TentativeDefinitions.push_back(Var); | |||
11658 | return; | |||
11659 | } | |||
11660 | ||||
11661 | // Provide a specific diagnostic for uninitialized variable | |||
11662 | // definitions with incomplete array type. | |||
11663 | if (Type->isIncompleteArrayType()) { | |||
11664 | Diag(Var->getLocation(), | |||
11665 | diag::err_typecheck_incomplete_array_needs_initializer); | |||
11666 | Var->setInvalidDecl(); | |||
11667 | return; | |||
11668 | } | |||
11669 | ||||
11670 | // Provide a specific diagnostic for uninitialized variable | |||
11671 | // definitions with reference type. | |||
11672 | if (Type->isReferenceType()) { | |||
11673 | Diag(Var->getLocation(), diag::err_reference_var_requires_init) | |||
11674 | << Var->getDeclName() | |||
11675 | << SourceRange(Var->getLocation(), Var->getLocation()); | |||
11676 | Var->setInvalidDecl(); | |||
11677 | return; | |||
11678 | } | |||
11679 | ||||
11680 | // Do not attempt to type-check the default initializer for a | |||
11681 | // variable with dependent type. | |||
11682 | if (Type->isDependentType()) | |||
11683 | return; | |||
11684 | ||||
11685 | if (Var->isInvalidDecl()) | |||
11686 | return; | |||
11687 | ||||
11688 | if (!Var->hasAttr<AliasAttr>()) { | |||
11689 | if (RequireCompleteType(Var->getLocation(), | |||
11690 | Context.getBaseElementType(Type), | |||
11691 | diag::err_typecheck_decl_incomplete_type)) { | |||
11692 | Var->setInvalidDecl(); | |||
11693 | return; | |||
11694 | } | |||
11695 | } else { | |||
11696 | return; | |||
11697 | } | |||
11698 | ||||
11699 | // The variable can not have an abstract class type. | |||
11700 | if (RequireNonAbstractType(Var->getLocation(), Type, | |||
11701 | diag::err_abstract_type_in_decl, | |||
11702 | AbstractVariableType)) { | |||
11703 | Var->setInvalidDecl(); | |||
11704 | return; | |||
11705 | } | |||
11706 | ||||
11707 | // Check for jumps past the implicit initializer. C++0x | |||
11708 | // clarifies that this applies to a "variable with automatic | |||
11709 | // storage duration", not a "local variable". | |||
11710 | // C++11 [stmt.dcl]p3 | |||
11711 | // A program that jumps from a point where a variable with automatic | |||
11712 | // storage duration is not in scope to a point where it is in scope is | |||
11713 | // ill-formed unless the variable has scalar type, class type with a | |||
11714 | // trivial default constructor and a trivial destructor, a cv-qualified | |||
11715 | // version of one of these types, or an array of one of the preceding | |||
11716 | // types and is declared without an initializer. | |||
11717 | if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { | |||
11718 | if (const RecordType *Record | |||
11719 | = Context.getBaseElementType(Type)->getAs<RecordType>()) { | |||
11720 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); | |||
11721 | // Mark the function (if we're in one) for further checking even if the | |||
11722 | // looser rules of C++11 do not require such checks, so that we can | |||
11723 | // diagnose incompatibilities with C++98. | |||
11724 | if (!CXXRecord->isPOD()) | |||
11725 | setFunctionHasBranchProtectedScope(); | |||
11726 | } | |||
11727 | } | |||
11728 | // In OpenCL, we can't initialize objects in the __local address space, | |||
11729 | // even implicitly, so don't synthesize an implicit initializer. | |||
11730 | if (getLangOpts().OpenCL && | |||
11731 | Var->getType().getAddressSpace() == LangAS::opencl_local) | |||
11732 | return; | |||
11733 | // C++03 [dcl.init]p9: | |||
11734 | // If no initializer is specified for an object, and the | |||
11735 | // object is of (possibly cv-qualified) non-POD class type (or | |||
11736 | // array thereof), the object shall be default-initialized; if | |||
11737 | // the object is of const-qualified type, the underlying class | |||
11738 | // type shall have a user-declared default | |||
11739 | // constructor. Otherwise, if no initializer is specified for | |||
11740 | // a non- static object, the object and its subobjects, if | |||
11741 | // any, have an indeterminate initial value); if the object | |||
11742 | // or any of its subobjects are of const-qualified type, the | |||
11743 | // program is ill-formed. | |||
11744 | // C++0x [dcl.init]p11: | |||
11745 | // If no initializer is specified for an object, the object is | |||
11746 | // default-initialized; [...]. | |||
11747 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); | |||
11748 | InitializationKind Kind | |||
11749 | = InitializationKind::CreateDefault(Var->getLocation()); | |||
11750 | ||||
11751 | InitializationSequence InitSeq(*this, Entity, Kind, None); | |||
11752 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); | |||
11753 | if (Init.isInvalid()) | |||
11754 | Var->setInvalidDecl(); | |||
11755 | else if (Init.get()) { | |||
11756 | Var->setInit(MaybeCreateExprWithCleanups(Init.get())); | |||
11757 | // This is important for template substitution. | |||
11758 | Var->setInitStyle(VarDecl::CallInit); | |||
11759 | } | |||
11760 | ||||
11761 | CheckCompleteVariableDeclaration(Var); | |||
11762 | } | |||
11763 | } | |||
11764 | ||||
11765 | void Sema::ActOnCXXForRangeDecl(Decl *D) { | |||
11766 | // If there is no declaration, there was an error parsing it. Ignore it. | |||
11767 | if (!D) | |||
11768 | return; | |||
11769 | ||||
11770 | VarDecl *VD = dyn_cast<VarDecl>(D); | |||
11771 | if (!VD) { | |||
11772 | Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); | |||
11773 | D->setInvalidDecl(); | |||
11774 | return; | |||
11775 | } | |||
11776 | ||||
11777 | VD->setCXXForRangeDecl(true); | |||
11778 | ||||
11779 | // for-range-declaration cannot be given a storage class specifier. | |||
11780 | int Error = -1; | |||
11781 | switch (VD->getStorageClass()) { | |||
11782 | case SC_None: | |||
11783 | break; | |||
11784 | case SC_Extern: | |||
11785 | Error = 0; | |||
11786 | break; | |||
11787 | case SC_Static: | |||
11788 | Error = 1; | |||
11789 | break; | |||
11790 | case SC_PrivateExtern: | |||
11791 | Error = 2; | |||
11792 | break; | |||
11793 | case SC_Auto: | |||
11794 | Error = 3; | |||
11795 | break; | |||
11796 | case SC_Register: | |||
11797 | Error = 4; | |||
11798 | break; | |||
11799 | } | |||
11800 | if (Error != -1) { | |||
11801 | Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) | |||
11802 | << VD->getDeclName() << Error; | |||
11803 | D->setInvalidDecl(); | |||
11804 | } | |||
11805 | } | |||
11806 | ||||
11807 | StmtResult | |||
11808 | Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, | |||
11809 | IdentifierInfo *Ident, | |||
11810 | ParsedAttributes &Attrs, | |||
11811 | SourceLocation AttrEnd) { | |||
11812 | // C++1y [stmt.iter]p1: | |||
11813 | // A range-based for statement of the form | |||
11814 | // for ( for-range-identifier : for-range-initializer ) statement | |||
11815 | // is equivalent to | |||
11816 | // for ( auto&& for-range-identifier : for-range-initializer ) statement | |||
11817 | DeclSpec DS(Attrs.getPool().getFactory()); | |||
11818 | ||||
11819 | const char *PrevSpec; | |||
11820 | unsigned DiagID; | |||
11821 | DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, | |||
11822 | getPrintingPolicy()); | |||
11823 | ||||
11824 | Declarator D(DS, DeclaratorContext::ForContext); | |||
11825 | D.SetIdentifier(Ident, IdentLoc); | |||
11826 | D.takeAttributes(Attrs, AttrEnd); | |||
11827 | ||||
11828 | D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), | |||
11829 | IdentLoc); | |||
11830 | Decl *Var = ActOnDeclarator(S, D); | |||
11831 | cast<VarDecl>(Var)->setCXXForRangeDecl(true); | |||
11832 | FinalizeDeclaration(Var); | |||
11833 | return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, | |||
11834 | AttrEnd.isValid() ? AttrEnd : IdentLoc); | |||
11835 | } | |||
11836 | ||||
11837 | void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { | |||
11838 | if (var->isInvalidDecl()) return; | |||
| ||||
11839 | ||||
11840 | if (getLangOpts().OpenCL) { | |||
11841 | // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an | |||
11842 | // initialiser | |||
11843 | if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && | |||
11844 | !var->hasInit()) { | |||
11845 | Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) | |||
11846 | << 1 /*Init*/; | |||
11847 | var->setInvalidDecl(); | |||
11848 | return; | |||
11849 | } | |||
11850 | } | |||
11851 | ||||
11852 | // In Objective-C, don't allow jumps past the implicit initialization of a | |||
11853 | // local retaining variable. | |||
11854 | if (getLangOpts().ObjC && | |||
11855 | var->hasLocalStorage()) { | |||
11856 | switch (var->getType().getObjCLifetime()) { | |||
11857 | case Qualifiers::OCL_None: | |||
11858 | case Qualifiers::OCL_ExplicitNone: | |||
11859 | case Qualifiers::OCL_Autoreleasing: | |||
11860 | break; | |||
11861 | ||||
11862 | case Qualifiers::OCL_Weak: | |||
11863 | case Qualifiers::OCL_Strong: | |||
11864 | setFunctionHasBranchProtectedScope(); | |||
11865 | break; | |||
11866 | } | |||
11867 | } | |||
11868 | ||||
11869 | if (var->hasLocalStorage() && | |||
11870 | var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
11871 | setFunctionHasBranchProtectedScope(); | |||
11872 | ||||
11873 | // Warn about externally-visible variables being defined without a | |||
11874 | // prior declaration. We only want to do this for global | |||
11875 | // declarations, but we also specifically need to avoid doing it for | |||
11876 | // class members because the linkage of an anonymous class can | |||
11877 | // change if it's later given a typedef name. | |||
11878 | if (var->isThisDeclarationADefinition() && | |||
11879 | var->getDeclContext()->getRedeclContext()->isFileContext() && | |||
11880 | var->isExternallyVisible() && var->hasLinkage() && | |||
11881 | !var->isInline() && !var->getDescribedVarTemplate() && | |||
11882 | !isTemplateInstantiation(var->getTemplateSpecializationKind()) && | |||
11883 | !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, | |||
11884 | var->getLocation())) { | |||
11885 | // Find a previous declaration that's not a definition. | |||
11886 | VarDecl *prev = var->getPreviousDecl(); | |||
11887 | while (prev && prev->isThisDeclarationADefinition()) | |||
11888 | prev = prev->getPreviousDecl(); | |||
11889 | ||||
11890 | if (!prev) | |||
11891 | Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; | |||
11892 | } | |||
11893 | ||||
11894 | // Cache the result of checking for constant initialization. | |||
11895 | Optional<bool> CacheHasConstInit; | |||
11896 | const Expr *CacheCulprit; | |||
11897 | auto checkConstInit = [&]() mutable { | |||
11898 | if (!CacheHasConstInit) | |||
11899 | CacheHasConstInit = var->getInit()->isConstantInitializer( | |||
11900 | Context, var->getType()->isReferenceType(), &CacheCulprit); | |||
11901 | return *CacheHasConstInit; | |||
11902 | }; | |||
11903 | ||||
11904 | if (var->getTLSKind() == VarDecl::TLS_Static) { | |||
11905 | if (var->getType().isDestructedType()) { | |||
11906 | // GNU C++98 edits for __thread, [basic.start.term]p3: | |||
11907 | // The type of an object with thread storage duration shall not | |||
11908 | // have a non-trivial destructor. | |||
11909 | Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); | |||
11910 | if (getLangOpts().CPlusPlus11) | |||
11911 | Diag(var->getLocation(), diag::note_use_thread_local); | |||
11912 | } else if (getLangOpts().CPlusPlus && var->hasInit()) { | |||
11913 | if (!checkConstInit()) { | |||
11914 | // GNU C++98 edits for __thread, [basic.start.init]p4: | |||
11915 | // An object of thread storage duration shall not require dynamic | |||
11916 | // initialization. | |||
11917 | // FIXME: Need strict checking here. | |||
11918 | Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) | |||
11919 | << CacheCulprit->getSourceRange(); | |||
11920 | if (getLangOpts().CPlusPlus11) | |||
11921 | Diag(var->getLocation(), diag::note_use_thread_local); | |||
11922 | } | |||
11923 | } | |||
11924 | } | |||
11925 | ||||
11926 | // Apply section attributes and pragmas to global variables. | |||
11927 | bool GlobalStorage = var->hasGlobalStorage(); | |||
11928 | if (GlobalStorage && var->isThisDeclarationADefinition() && | |||
11929 | !inTemplateInstantiation()) { | |||
11930 | PragmaStack<StringLiteral *> *Stack = nullptr; | |||
11931 | int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; | |||
11932 | if (var->getType().isConstQualified()) | |||
11933 | Stack = &ConstSegStack; | |||
11934 | else if (!var->getInit()) { | |||
11935 | Stack = &BSSSegStack; | |||
11936 | SectionFlags |= ASTContext::PSF_Write; | |||
11937 | } else { | |||
11938 | Stack = &DataSegStack; | |||
11939 | SectionFlags |= ASTContext::PSF_Write; | |||
11940 | } | |||
11941 | if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { | |||
11942 | var->addAttr(SectionAttr::CreateImplicit( | |||
11943 | Context, SectionAttr::Declspec_allocate, | |||
11944 | Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); | |||
11945 | } | |||
11946 | if (const SectionAttr *SA = var->getAttr<SectionAttr>()) | |||
11947 | if (UnifySection(SA->getName(), SectionFlags, var)) | |||
11948 | var->dropAttr<SectionAttr>(); | |||
11949 | ||||
11950 | // Apply the init_seg attribute if this has an initializer. If the | |||
11951 | // initializer turns out to not be dynamic, we'll end up ignoring this | |||
11952 | // attribute. | |||
11953 | if (CurInitSeg && var->getInit()) | |||
11954 | var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), | |||
11955 | CurInitSegLoc)); | |||
11956 | } | |||
11957 | ||||
11958 | // All the following checks are C++ only. | |||
11959 | if (!getLangOpts().CPlusPlus) { | |||
11960 | // If this variable must be emitted, add it as an initializer for the | |||
11961 | // current module. | |||
11962 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | |||
11963 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | |||
11964 | return; | |||
11965 | } | |||
11966 | ||||
11967 | if (auto *DD = dyn_cast<DecompositionDecl>(var)) | |||
11968 | CheckCompleteDecompositionDeclaration(DD); | |||
11969 | ||||
11970 | QualType type = var->getType(); | |||
11971 | if (type->isDependentType()) return; | |||
11972 | ||||
11973 | if (var->hasAttr<BlocksAttr>()) | |||
11974 | getCurFunction()->addByrefBlockVar(var); | |||
11975 | ||||
11976 | Expr *Init = var->getInit(); | |||
11977 | bool IsGlobal = GlobalStorage && !var->isStaticLocal(); | |||
11978 | QualType baseType = Context.getBaseElementType(type); | |||
11979 | ||||
11980 | if (Init && !Init->isValueDependent()) { | |||
11981 | if (var->isConstexpr()) { | |||
11982 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
11983 | if (!var->evaluateValue(Notes) || !var->isInitICE()) { | |||
11984 | SourceLocation DiagLoc = var->getLocation(); | |||
11985 | // If the note doesn't add any useful information other than a source | |||
11986 | // location, fold it into the primary diagnostic. | |||
11987 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | |||
11988 | diag::note_invalid_subexpr_in_const_expr) { | |||
11989 | DiagLoc = Notes[0].first; | |||
11990 | Notes.clear(); | |||
11991 | } | |||
11992 | Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) | |||
11993 | << var << Init->getSourceRange(); | |||
11994 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) | |||
11995 | Diag(Notes[I].first, Notes[I].second); | |||
11996 | } | |||
11997 | } else if (var->isUsableInConstantExpressions(Context)) { | |||
11998 | // Check whether the initializer of a const variable of integral or | |||
11999 | // enumeration type is an ICE now, since we can't tell whether it was | |||
12000 | // initialized by a constant expression if we check later. | |||
12001 | var->checkInitIsICE(); | |||
12002 | } | |||
12003 | ||||
12004 | // Don't emit further diagnostics about constexpr globals since they | |||
12005 | // were just diagnosed. | |||
12006 | if (!var->isConstexpr() && GlobalStorage && | |||
12007 | var->hasAttr<RequireConstantInitAttr>()) { | |||
12008 | // FIXME: Need strict checking in C++03 here. | |||
12009 | bool DiagErr = getLangOpts().CPlusPlus11 | |||
12010 | ? !var->checkInitIsICE() : !checkConstInit(); | |||
12011 | if (DiagErr) { | |||
12012 | auto attr = var->getAttr<RequireConstantInitAttr>(); | |||
12013 | Diag(var->getLocation(), diag::err_require_constant_init_failed) | |||
12014 | << Init->getSourceRange(); | |||
12015 | Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) | |||
12016 | << attr->getRange(); | |||
12017 | if (getLangOpts().CPlusPlus11) { | |||
12018 | APValue Value; | |||
12019 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
12020 | Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); | |||
12021 | for (auto &it : Notes) | |||
12022 | Diag(it.first, it.second); | |||
12023 | } else { | |||
12024 | Diag(CacheCulprit->getExprLoc(), | |||
| ||||
12025 | diag::note_invalid_subexpr_in_const_expr) | |||
12026 | << CacheCulprit->getSourceRange(); | |||
12027 | } | |||
12028 | } | |||
12029 | } | |||
12030 | else if (!var->isConstexpr() && IsGlobal && | |||
12031 | !getDiagnostics().isIgnored(diag::warn_global_constructor, | |||
12032 | var->getLocation())) { | |||
12033 | // Warn about globals which don't have a constant initializer. Don't | |||
12034 | // warn about globals with a non-trivial destructor because we already | |||
12035 | // warned about them. | |||
12036 | CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); | |||
12037 | if (!(RD && !RD->hasTrivialDestructor())) { | |||
12038 | if (!checkConstInit()) | |||
12039 | Diag(var->getLocation(), diag::warn_global_constructor) | |||
12040 | << Init->getSourceRange(); | |||
12041 | } | |||
12042 | } | |||
12043 | } | |||
12044 | ||||
12045 | // Require the destructor. | |||
12046 | if (const RecordType *recordType = baseType->getAs<RecordType>()) | |||
12047 | FinalizeVarWithDestructor(var, recordType); | |||
12048 | ||||
12049 | // If this variable must be emitted, add it as an initializer for the current | |||
12050 | // module. | |||
12051 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | |||
12052 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | |||
12053 | } | |||
12054 | ||||
12055 | /// Determines if a variable's alignment is dependent. | |||
12056 | static bool hasDependentAlignment(VarDecl *VD) { | |||
12057 | if (VD->getType()->isDependentType()) | |||
12058 | return true; | |||
12059 | for (auto *I : VD->specific_attrs<AlignedAttr>()) | |||
12060 | if (I->isAlignmentDependent()) | |||
12061 | return true; | |||
12062 | return false; | |||
12063 | } | |||
12064 | ||||
12065 | /// Check if VD needs to be dllexport/dllimport due to being in a | |||
12066 | /// dllexport/import function. | |||
12067 | void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { | |||
12068 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 12068, __PRETTY_FUNCTION__)); | |||
12069 | ||||
12070 | auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | |||
12071 | ||||
12072 | // Find outermost function when VD is in lambda function. | |||
12073 | while (FD && !getDLLAttr(FD) && | |||
12074 | !FD->hasAttr<DLLExportStaticLocalAttr>() && | |||
12075 | !FD->hasAttr<DLLImportStaticLocalAttr>()) { | |||
12076 | FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); | |||
12077 | } | |||
12078 | ||||
12079 | if (!FD) | |||
12080 | return; | |||
12081 | ||||
12082 | // Static locals inherit dll attributes from their function. | |||
12083 | if (Attr *A = getDLLAttr(FD)) { | |||
12084 | auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); | |||
12085 | NewAttr->setInherited(true); | |||
12086 | VD->addAttr(NewAttr); | |||
12087 | } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { | |||
12088 | auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(), | |||
12089 | getASTContext(), | |||
12090 | A->getSpellingListIndex()); | |||
12091 | NewAttr->setInherited(true); | |||
12092 | VD->addAttr(NewAttr); | |||
12093 | ||||
12094 | // Export this function to enforce exporting this static variable even | |||
12095 | // if it is not used in this compilation unit. | |||
12096 | if (!FD->hasAttr<DLLExportAttr>()) | |||
12097 | FD->addAttr(NewAttr); | |||
12098 | ||||
12099 | } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { | |||
12100 | auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(), | |||
12101 | getASTContext(), | |||
12102 | A->getSpellingListIndex()); | |||
12103 | NewAttr->setInherited(true); | |||
12104 | VD->addAttr(NewAttr); | |||
12105 | } | |||
12106 | } | |||
12107 | ||||
12108 | /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform | |||
12109 | /// any semantic actions necessary after any initializer has been attached. | |||
12110 | void Sema::FinalizeDeclaration(Decl *ThisDecl) { | |||
12111 | // Note that we are no longer parsing the initializer for this declaration. | |||
12112 | ParsingInitForAutoVars.erase(ThisDecl); | |||
12113 | ||||
12114 | VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); | |||
12115 | if (!VD) | |||
12116 | return; | |||
12117 | ||||
12118 | // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active | |||
12119 | if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && | |||
12120 | !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { | |||
12121 | if (PragmaClangBSSSection.Valid) | |||
12122 | VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, | |||
12123 | PragmaClangBSSSection.SectionName, | |||
12124 | PragmaClangBSSSection.PragmaLocation)); | |||
12125 | if (PragmaClangDataSection.Valid) | |||
12126 | VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, | |||
12127 | PragmaClangDataSection.SectionName, | |||
12128 | PragmaClangDataSection.PragmaLocation)); | |||
12129 | if (PragmaClangRodataSection.Valid) | |||
12130 | VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, | |||
12131 | PragmaClangRodataSection.SectionName, | |||
12132 | PragmaClangRodataSection.PragmaLocation)); | |||
12133 | } | |||
12134 | ||||
12135 | if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { | |||
12136 | for (auto *BD : DD->bindings()) { | |||
12137 | FinalizeDeclaration(BD); | |||
12138 | } | |||
12139 | } | |||
12140 | ||||
12141 | checkAttributesAfterMerging(*this, *VD); | |||
12142 | ||||
12143 | // Perform TLS alignment check here after attributes attached to the variable | |||
12144 | // which may affect the alignment have been processed. Only perform the check | |||
12145 | // if the target has a maximum TLS alignment (zero means no constraints). | |||
12146 | if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { | |||
12147 | // Protect the check so that it's not performed on dependent types and | |||
12148 | // dependent alignments (we can't determine the alignment in that case). | |||
12149 | if (VD->getTLSKind() && !hasDependentAlignment(VD) && | |||
12150 | !VD->isInvalidDecl()) { | |||
12151 | CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); | |||
12152 | if (Context.getDeclAlign(VD) > MaxAlignChars) { | |||
12153 | Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) | |||
12154 | << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD | |||
12155 | << (unsigned)MaxAlignChars.getQuantity(); | |||
12156 | } | |||
12157 | } | |||
12158 | } | |||
12159 | ||||
12160 | if (VD->isStaticLocal()) { | |||
12161 | CheckStaticLocalForDllExport(VD); | |||
12162 | ||||
12163 | if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { | |||
12164 | // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ | |||
12165 | // function, only __shared__ variables or variables without any device | |||
12166 | // memory qualifiers may be declared with static storage class. | |||
12167 | // Note: It is unclear how a function-scope non-const static variable | |||
12168 | // without device memory qualifier is implemented, therefore only static | |||
12169 | // const variable without device memory qualifier is allowed. | |||
12170 | [&]() { | |||
12171 | if (!getLangOpts().CUDA) | |||
12172 | return; | |||
12173 | if (VD->hasAttr<CUDASharedAttr>()) | |||
12174 | return; | |||
12175 | if (VD->getType().isConstQualified() && | |||
12176 | !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) | |||
12177 | return; | |||
12178 | if (CUDADiagIfDeviceCode(VD->getLocation(), | |||
12179 | diag::err_device_static_local_var) | |||
12180 | << CurrentCUDATarget()) | |||
12181 | VD->setInvalidDecl(); | |||
12182 | }(); | |||
12183 | } | |||
12184 | } | |||
12185 | ||||
12186 | // Perform check for initializers of device-side global variables. | |||
12187 | // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA | |||
12188 | // 7.5). We must also apply the same checks to all __shared__ | |||
12189 | // variables whether they are local or not. CUDA also allows | |||
12190 | // constant initializers for __constant__ and __device__ variables. | |||
12191 | if (getLangOpts().CUDA) | |||
12192 | checkAllowedCUDAInitializer(VD); | |||
12193 | ||||
12194 | // Grab the dllimport or dllexport attribute off of the VarDecl. | |||
12195 | const InheritableAttr *DLLAttr = getDLLAttr(VD); | |||
12196 | ||||
12197 | // Imported static data members cannot be defined out-of-line. | |||
12198 | if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { | |||
12199 | if (VD->isStaticDataMember() && VD->isOutOfLine() && | |||
12200 | VD->isThisDeclarationADefinition()) { | |||
12201 | // We allow definitions of dllimport class template static data members | |||
12202 | // with a warning. | |||
12203 | CXXRecordDecl *Context = | |||
12204 | cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); | |||
12205 | bool IsClassTemplateMember = | |||
12206 | isa<ClassTemplatePartialSpecializationDecl>(Context) || | |||
12207 | Context->getDescribedClassTemplate(); | |||
12208 | ||||
12209 | Diag(VD->getLocation(), | |||
12210 | IsClassTemplateMember | |||
12211 | ? diag::warn_attribute_dllimport_static_field_definition | |||
12212 | : diag::err_attribute_dllimport_static_field_definition); | |||
12213 | Diag(IA->getLocation(), diag::note_attribute); | |||
12214 | if (!IsClassTemplateMember) | |||
12215 | VD->setInvalidDecl(); | |||
12216 | } | |||
12217 | } | |||
12218 | ||||
12219 | // dllimport/dllexport variables cannot be thread local, their TLS index | |||
12220 | // isn't exported with the variable. | |||
12221 | if (DLLAttr && VD->getTLSKind()) { | |||
12222 | auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | |||
12223 | if (F && getDLLAttr(F)) { | |||
12224 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 12224, __PRETTY_FUNCTION__)); | |||
12225 | // But if this is a static local in a dlimport/dllexport function, the | |||
12226 | // function will never be inlined, which means the var would never be | |||
12227 | // imported, so having it marked import/export is safe. | |||
12228 | } else { | |||
12229 | Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD | |||
12230 | << DLLAttr; | |||
12231 | VD->setInvalidDecl(); | |||
12232 | } | |||
12233 | } | |||
12234 | ||||
12235 | if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { | |||
12236 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { | |||
12237 | Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; | |||
12238 | VD->dropAttr<UsedAttr>(); | |||
12239 | } | |||
12240 | } | |||
12241 | ||||
12242 | const DeclContext *DC = VD->getDeclContext(); | |||
12243 | // If there's a #pragma GCC visibility in scope, and this isn't a class | |||
12244 | // member, set the visibility of this variable. | |||
12245 | if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) | |||
12246 | AddPushedVisibilityAttribute(VD); | |||
12247 | ||||
12248 | // FIXME: Warn on unused var template partial specializations. | |||
12249 | if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) | |||
12250 | MarkUnusedFileScopedDecl(VD); | |||
12251 | ||||
12252 | // Now we have parsed the initializer and can update the table of magic | |||
12253 | // tag values. | |||
12254 | if (!VD->hasAttr<TypeTagForDatatypeAttr>() || | |||
12255 | !VD->getType()->isIntegralOrEnumerationType()) | |||
12256 | return; | |||
12257 | ||||
12258 | for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { | |||
12259 | const Expr *MagicValueExpr = VD->getInit(); | |||
12260 | if (!MagicValueExpr) { | |||
12261 | continue; | |||
12262 | } | |||
12263 | llvm::APSInt MagicValueInt; | |||
12264 | if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { | |||
12265 | Diag(I->getRange().getBegin(), | |||
12266 | diag::err_type_tag_for_datatype_not_ice) | |||
12267 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | |||
12268 | continue; | |||
12269 | } | |||
12270 | if (MagicValueInt.getActiveBits() > 64) { | |||
12271 | Diag(I->getRange().getBegin(), | |||
12272 | diag::err_type_tag_for_datatype_too_large) | |||
12273 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | |||
12274 | continue; | |||
12275 | } | |||
12276 | uint64_t MagicValue = MagicValueInt.getZExtValue(); | |||
12277 | RegisterTypeTagForDatatype(I->getArgumentKind(), | |||
12278 | MagicValue, | |||
12279 | I->getMatchingCType(), | |||
12280 | I->getLayoutCompatible(), | |||
12281 | I->getMustBeNull()); | |||
12282 | } | |||
12283 | } | |||
12284 | ||||
12285 | static bool hasDeducedAuto(DeclaratorDecl *DD) { | |||
12286 | auto *VD = dyn_cast<VarDecl>(DD); | |||
12287 | return VD && !VD->getType()->hasAutoForTrailingReturnType(); | |||
12288 | } | |||
12289 | ||||
12290 | Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, | |||
12291 | ArrayRef<Decl *> Group) { | |||
12292 | SmallVector<Decl*, 8> Decls; | |||
12293 | ||||
12294 | if (DS.isTypeSpecOwned()) | |||
12295 | Decls.push_back(DS.getRepAsDecl()); | |||
12296 | ||||
12297 | DeclaratorDecl *FirstDeclaratorInGroup = nullptr; | |||
12298 | DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; | |||
12299 | bool DiagnosedMultipleDecomps = false; | |||
12300 | DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; | |||
12301 | bool DiagnosedNonDeducedAuto = false; | |||
12302 | ||||
12303 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | |||
12304 | if (Decl *D = Group[i]) { | |||
12305 | // For declarators, there are some additional syntactic-ish checks we need | |||
12306 | // to perform. | |||
12307 | if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { | |||
12308 | if (!FirstDeclaratorInGroup) | |||
12309 | FirstDeclaratorInGroup = DD; | |||
12310 | if (!FirstDecompDeclaratorInGroup) | |||
12311 | FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); | |||
12312 | if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && | |||
12313 | !hasDeducedAuto(DD)) | |||
12314 | FirstNonDeducedAutoInGroup = DD; | |||
12315 | ||||
12316 | if (FirstDeclaratorInGroup != DD) { | |||
12317 | // A decomposition declaration cannot be combined with any other | |||
12318 | // declaration in the same group. | |||
12319 | if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { | |||
12320 | Diag(FirstDecompDeclaratorInGroup->getLocation(), | |||
12321 | diag::err_decomp_decl_not_alone) | |||
12322 | << FirstDeclaratorInGroup->getSourceRange() | |||
12323 | << DD->getSourceRange(); | |||
12324 | DiagnosedMultipleDecomps = true; | |||
12325 | } | |||
12326 | ||||
12327 | // A declarator that uses 'auto' in any way other than to declare a | |||
12328 | // variable with a deduced type cannot be combined with any other | |||
12329 | // declarator in the same group. | |||
12330 | if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { | |||
12331 | Diag(FirstNonDeducedAutoInGroup->getLocation(), | |||
12332 | diag::err_auto_non_deduced_not_alone) | |||
12333 | << FirstNonDeducedAutoInGroup->getType() | |||
12334 | ->hasAutoForTrailingReturnType() | |||
12335 | << FirstDeclaratorInGroup->getSourceRange() | |||
12336 | << DD->getSourceRange(); | |||
12337 | DiagnosedNonDeducedAuto = true; | |||
12338 | } | |||
12339 | } | |||
12340 | } | |||
12341 | ||||
12342 | Decls.push_back(D); | |||
12343 | } | |||
12344 | } | |||
12345 | ||||
12346 | if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { | |||
12347 | if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { | |||
12348 | handleTagNumbering(Tag, S); | |||
12349 | if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && | |||
12350 | getLangOpts().CPlusPlus) | |||
12351 | Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); | |||
12352 | } | |||
12353 | } | |||
12354 | ||||
12355 | return BuildDeclaratorGroup(Decls); | |||
12356 | } | |||
12357 | ||||
12358 | /// BuildDeclaratorGroup - convert a list of declarations into a declaration | |||
12359 | /// group, performing any necessary semantic checking. | |||
12360 | Sema::DeclGroupPtrTy | |||
12361 | Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { | |||
12362 | // C++14 [dcl.spec.auto]p7: (DR1347) | |||
12363 | // If the type that replaces the placeholder type is not the same in each | |||
12364 | // deduction, the program is ill-formed. | |||
12365 | if (Group.size() > 1) { | |||
12366 | QualType Deduced; | |||
12367 | VarDecl *DeducedDecl = nullptr; | |||
12368 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | |||
12369 | VarDecl *D = dyn_cast<VarDecl>(Group[i]); | |||
12370 | if (!D || D->isInvalidDecl()) | |||
12371 | break; | |||
12372 | DeducedType *DT = D->getType()->getContainedDeducedType(); | |||
12373 | if (!DT || DT->getDeducedType().isNull()) | |||
12374 | continue; | |||
12375 | if (Deduced.isNull()) { | |||
12376 | Deduced = DT->getDeducedType(); | |||
12377 | DeducedDecl = D; | |||
12378 | } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { | |||
12379 | auto *AT = dyn_cast<AutoType>(DT); | |||
12380 | Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), | |||
12381 | diag::err_auto_different_deductions) | |||
12382 | << (AT ? (unsigned)AT->getKeyword() : 3) | |||
12383 | << Deduced << DeducedDecl->getDeclName() | |||
12384 | << DT->getDeducedType() << D->getDeclName() | |||
12385 | << DeducedDecl->getInit()->getSourceRange() | |||
12386 | << D->getInit()->getSourceRange(); | |||
12387 | D->setInvalidDecl(); | |||
12388 | break; | |||
12389 | } | |||
12390 | } | |||
12391 | } | |||
12392 | ||||
12393 | ActOnDocumentableDecls(Group); | |||
12394 | ||||
12395 | return DeclGroupPtrTy::make( | |||
12396 | DeclGroupRef::Create(Context, Group.data(), Group.size())); | |||
12397 | } | |||
12398 | ||||
12399 | void Sema::ActOnDocumentableDecl(Decl *D) { | |||
12400 | ActOnDocumentableDecls(D); | |||
12401 | } | |||
12402 | ||||
12403 | void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { | |||
12404 | // Don't parse the comment if Doxygen diagnostics are ignored. | |||
12405 | if (Group.empty() || !Group[0]) | |||
12406 | return; | |||
12407 | ||||
12408 | if (Diags.isIgnored(diag::warn_doc_param_not_found, | |||
12409 | Group[0]->getLocation()) && | |||
12410 | Diags.isIgnored(diag::warn_unknown_comment_command_name, | |||
12411 | Group[0]->getLocation())) | |||
12412 | return; | |||
12413 | ||||
12414 | if (Group.size() >= 2) { | |||
12415 | // This is a decl group. Normally it will contain only declarations | |||
12416 | // produced from declarator list. But in case we have any definitions or | |||
12417 | // additional declaration references: | |||
12418 | // 'typedef struct S {} S;' | |||
12419 | // 'typedef struct S *S;' | |||
12420 | // 'struct S *pS;' | |||
12421 | // FinalizeDeclaratorGroup adds these as separate declarations. | |||
12422 | Decl *MaybeTagDecl = Group[0]; | |||
12423 | if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { | |||
12424 | Group = Group.slice(1); | |||
12425 | } | |||
12426 | } | |||
12427 | ||||
12428 | // See if there are any new comments that are not attached to a decl. | |||
12429 | ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); | |||
12430 | if (!Comments.empty() && | |||
12431 | !Comments.back()->isAttached()) { | |||
12432 | // There is at least one comment that not attached to a decl. | |||
12433 | // Maybe it should be attached to one of these decls? | |||
12434 | // | |||
12435 | // Note that this way we pick up not only comments that precede the | |||
12436 | // declaration, but also comments that *follow* the declaration -- thanks to | |||
12437 | // the lookahead in the lexer: we've consumed the semicolon and looked | |||
12438 | // ahead through comments. | |||
12439 | for (unsigned i = 0, e = Group.size(); i != e; ++i) | |||
12440 | Context.getCommentForDecl(Group[i], &PP); | |||
12441 | } | |||
12442 | } | |||
12443 | ||||
12444 | /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() | |||
12445 | /// to introduce parameters into function prototype scope. | |||
12446 | Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { | |||
12447 | const DeclSpec &DS = D.getDeclSpec(); | |||
12448 | ||||
12449 | // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. | |||
12450 | ||||
12451 | // C++03 [dcl.stc]p2 also permits 'auto'. | |||
12452 | StorageClass SC = SC_None; | |||
12453 | if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { | |||
12454 | SC = SC_Register; | |||
12455 | // In C++11, the 'register' storage class specifier is deprecated. | |||
12456 | // In C++17, it is not allowed, but we tolerate it as an extension. | |||
12457 | if (getLangOpts().CPlusPlus11) { | |||
12458 | Diag(DS.getStorageClassSpecLoc(), | |||
12459 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | |||
12460 | : diag::warn_deprecated_register) | |||
12461 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | |||
12462 | } | |||
12463 | } else if (getLangOpts().CPlusPlus && | |||
12464 | DS.getStorageClassSpec() == DeclSpec::SCS_auto) { | |||
12465 | SC = SC_Auto; | |||
12466 | } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { | |||
12467 | Diag(DS.getStorageClassSpecLoc(), | |||
12468 | diag::err_invalid_storage_class_in_func_decl); | |||
12469 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | |||
12470 | } | |||
12471 | ||||
12472 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | |||
12473 | Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) | |||
12474 | << DeclSpec::getSpecifierName(TSCS); | |||
12475 | if (DS.isInlineSpecified()) | |||
12476 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | |||
12477 | << getLangOpts().CPlusPlus17; | |||
12478 | if (DS.isConstexprSpecified()) | |||
12479 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) | |||
12480 | << 0; | |||
12481 | ||||
12482 | DiagnoseFunctionSpecifiers(DS); | |||
12483 | ||||
12484 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
12485 | QualType parmDeclType = TInfo->getType(); | |||
12486 | ||||
12487 | if (getLangOpts().CPlusPlus) { | |||
12488 | // Check that there are no default arguments inside the type of this | |||
12489 | // parameter. | |||
12490 | CheckExtraCXXDefaultArguments(D); | |||
12491 | ||||
12492 | // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). | |||
12493 | if (D.getCXXScopeSpec().isSet()) { | |||
12494 | Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) | |||
12495 | << D.getCXXScopeSpec().getRange(); | |||
12496 | D.getCXXScopeSpec().clear(); | |||
12497 | } | |||
12498 | } | |||
12499 | ||||
12500 | // Ensure we have a valid name | |||
12501 | IdentifierInfo *II = nullptr; | |||
12502 | if (D.hasName()) { | |||
12503 | II = D.getIdentifier(); | |||
12504 | if (!II) { | |||
12505 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) | |||
12506 | << GetNameForDeclarator(D).getName(); | |||
12507 | D.setInvalidType(true); | |||
12508 | } | |||
12509 | } | |||
12510 | ||||
12511 | // Check for redeclaration of parameters, e.g. int foo(int x, int x); | |||
12512 | if (II) { | |||
12513 | LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, | |||
12514 | ForVisibleRedeclaration); | |||
12515 | LookupName(R, S); | |||
12516 | if (R.isSingleResult()) { | |||
12517 | NamedDecl *PrevDecl = R.getFoundDecl(); | |||
12518 | if (PrevDecl->isTemplateParameter()) { | |||
12519 | // Maybe we will complain about the shadowed template parameter. | |||
12520 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | |||
12521 | // Just pretend that we didn't see the previous declaration. | |||
12522 | PrevDecl = nullptr; | |||
12523 | } else if (S->isDeclScope(PrevDecl)) { | |||
12524 | Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; | |||
12525 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
12526 | ||||
12527 | // Recover by removing the name | |||
12528 | II = nullptr; | |||
12529 | D.SetIdentifier(nullptr, D.getIdentifierLoc()); | |||
12530 | D.setInvalidType(true); | |||
12531 | } | |||
12532 | } | |||
12533 | } | |||
12534 | ||||
12535 | // Temporarily put parameter variables in the translation unit, not | |||
12536 | // the enclosing context. This prevents them from accidentally | |||
12537 | // looking like class members in C++. | |||
12538 | ParmVarDecl *New = | |||
12539 | CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), | |||
12540 | D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); | |||
12541 | ||||
12542 | if (D.isInvalidType()) | |||
12543 | New->setInvalidDecl(); | |||
12544 | ||||
12545 | assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void> (0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 12545, __PRETTY_FUNCTION__)); | |||
12546 | assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast< void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 12546, __PRETTY_FUNCTION__)); | |||
12547 | New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, | |||
12548 | S->getNextFunctionPrototypeIndex()); | |||
12549 | ||||
12550 | // Add the parameter declaration into this scope. | |||
12551 | S->AddDecl(New); | |||
12552 | if (II) | |||
12553 | IdResolver.AddDecl(New); | |||
12554 | ||||
12555 | ProcessDeclAttributes(S, New, D); | |||
12556 | ||||
12557 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
12558 | Diag(New->getLocation(), diag::err_module_private_local) | |||
12559 | << 1 << New->getDeclName() | |||
12560 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | |||
12561 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | |||
12562 | ||||
12563 | if (New->hasAttr<BlocksAttr>()) { | |||
12564 | Diag(New->getLocation(), diag::err_block_on_nonlocal); | |||
12565 | } | |||
12566 | return New; | |||
12567 | } | |||
12568 | ||||
12569 | /// Synthesizes a variable for a parameter arising from a | |||
12570 | /// typedef. | |||
12571 | ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, | |||
12572 | SourceLocation Loc, | |||
12573 | QualType T) { | |||
12574 | /* FIXME: setting StartLoc == Loc. | |||
12575 | Would it be worth to modify callers so as to provide proper source | |||
12576 | location for the unnamed parameters, embedding the parameter's type? */ | |||
12577 | ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, | |||
12578 | T, Context.getTrivialTypeSourceInfo(T, Loc), | |||
12579 | SC_None, nullptr); | |||
12580 | Param->setImplicit(); | |||
12581 | return Param; | |||
12582 | } | |||
12583 | ||||
12584 | void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { | |||
12585 | // Don't diagnose unused-parameter errors in template instantiations; we | |||
12586 | // will already have done so in the template itself. | |||
12587 | if (inTemplateInstantiation()) | |||
12588 | return; | |||
12589 | ||||
12590 | for (const ParmVarDecl *Parameter : Parameters) { | |||
12591 | if (!Parameter->isReferenced() && Parameter->getDeclName() && | |||
12592 | !Parameter->hasAttr<UnusedAttr>()) { | |||
12593 | Diag(Parameter->getLocation(), diag::warn_unused_parameter) | |||
12594 | << Parameter->getDeclName(); | |||
12595 | } | |||
12596 | } | |||
12597 | } | |||
12598 | ||||
12599 | void Sema::DiagnoseSizeOfParametersAndReturnValue( | |||
12600 | ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { | |||
12601 | if (LangOpts.NumLargeByValueCopy == 0) // No check. | |||
12602 | return; | |||
12603 | ||||
12604 | // Warn if the return value is pass-by-value and larger than the specified | |||
12605 | // threshold. | |||
12606 | if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { | |||
12607 | unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); | |||
12608 | if (Size > LangOpts.NumLargeByValueCopy) | |||
12609 | Diag(D->getLocation(), diag::warn_return_value_size) | |||
12610 | << D->getDeclName() << Size; | |||
12611 | } | |||
12612 | ||||
12613 | // Warn if any parameter is pass-by-value and larger than the specified | |||
12614 | // threshold. | |||
12615 | for (const ParmVarDecl *Parameter : Parameters) { | |||
12616 | QualType T = Parameter->getType(); | |||
12617 | if (T->isDependentType() || !T.isPODType(Context)) | |||
12618 | continue; | |||
12619 | unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); | |||
12620 | if (Size > LangOpts.NumLargeByValueCopy) | |||
12621 | Diag(Parameter->getLocation(), diag::warn_parameter_size) | |||
12622 | << Parameter->getDeclName() << Size; | |||
12623 | } | |||
12624 | } | |||
12625 | ||||
12626 | ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, | |||
12627 | SourceLocation NameLoc, IdentifierInfo *Name, | |||
12628 | QualType T, TypeSourceInfo *TSInfo, | |||
12629 | StorageClass SC) { | |||
12630 | // In ARC, infer a lifetime qualifier for appropriate parameter types. | |||
12631 | if (getLangOpts().ObjCAutoRefCount && | |||
12632 | T.getObjCLifetime() == Qualifiers::OCL_None && | |||
12633 | T->isObjCLifetimeType()) { | |||
12634 | ||||
12635 | Qualifiers::ObjCLifetime lifetime; | |||
12636 | ||||
12637 | // Special cases for arrays: | |||
12638 | // - if it's const, use __unsafe_unretained | |||
12639 | // - otherwise, it's an error | |||
12640 | if (T->isArrayType()) { | |||
12641 | if (!T.isConstQualified()) { | |||
12642 | if (DelayedDiagnostics.shouldDelayDiagnostics()) | |||
12643 | DelayedDiagnostics.add( | |||
12644 | sema::DelayedDiagnostic::makeForbiddenType( | |||
12645 | NameLoc, diag::err_arc_array_param_no_ownership, T, false)); | |||
12646 | else | |||
12647 | Diag(NameLoc, diag::err_arc_array_param_no_ownership) | |||
12648 | << TSInfo->getTypeLoc().getSourceRange(); | |||
12649 | } | |||
12650 | lifetime = Qualifiers::OCL_ExplicitNone; | |||
12651 | } else { | |||
12652 | lifetime = T->getObjCARCImplicitLifetime(); | |||
12653 | } | |||
12654 | T = Context.getLifetimeQualifiedType(T, lifetime); | |||
12655 | } | |||
12656 | ||||
12657 | ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, | |||
12658 | Context.getAdjustedParameterType(T), | |||
12659 | TSInfo, SC, nullptr); | |||
12660 | ||||
12661 | // Parameters can not be abstract class types. | |||
12662 | // For record types, this is done by the AbstractClassUsageDiagnoser once | |||
12663 | // the class has been completely parsed. | |||
12664 | if (!CurContext->isRecord() && | |||
12665 | RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, | |||
12666 | AbstractParamType)) | |||
12667 | New->setInvalidDecl(); | |||
12668 | ||||
12669 | // Parameter declarators cannot be interface types. All ObjC objects are | |||
12670 | // passed by reference. | |||
12671 | if (T->isObjCObjectType()) { | |||
12672 | SourceLocation TypeEndLoc = | |||
12673 | getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); | |||
12674 | Diag(NameLoc, | |||
12675 | diag::err_object_cannot_be_passed_returned_by_value) << 1 << T | |||
12676 | << FixItHint::CreateInsertion(TypeEndLoc, "*"); | |||
12677 | T = Context.getObjCObjectPointerType(T); | |||
12678 | New->setType(T); | |||
12679 | } | |||
12680 | ||||
12681 | // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage | |||
12682 | // duration shall not be qualified by an address-space qualifier." | |||
12683 | // Since all parameters have automatic store duration, they can not have | |||
12684 | // an address space. | |||
12685 | if (T.getAddressSpace() != LangAS::Default && | |||
12686 | // OpenCL allows function arguments declared to be an array of a type | |||
12687 | // to be qualified with an address space. | |||
12688 | !(getLangOpts().OpenCL && | |||
12689 | (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { | |||
12690 | Diag(NameLoc, diag::err_arg_with_address_space); | |||
12691 | New->setInvalidDecl(); | |||
12692 | } | |||
12693 | ||||
12694 | return New; | |||
12695 | } | |||
12696 | ||||
12697 | void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, | |||
12698 | SourceLocation LocAfterDecls) { | |||
12699 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | |||
12700 | ||||
12701 | // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' | |||
12702 | // for a K&R function. | |||
12703 | if (!FTI.hasPrototype) { | |||
12704 | for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { | |||
12705 | --i; | |||
12706 | if (FTI.Params[i].Param == nullptr) { | |||
12707 | SmallString<256> Code; | |||
12708 | llvm::raw_svector_ostream(Code) | |||
12709 | << " int " << FTI.Params[i].Ident->getName() << ";\n"; | |||
12710 | Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) | |||
12711 | << FTI.Params[i].Ident | |||
12712 | << FixItHint::CreateInsertion(LocAfterDecls, Code); | |||
12713 | ||||
12714 | // Implicitly declare the argument as type 'int' for lack of a better | |||
12715 | // type. | |||
12716 | AttributeFactory attrs; | |||
12717 | DeclSpec DS(attrs); | |||
12718 | const char* PrevSpec; // unused | |||
12719 | unsigned DiagID; // unused | |||
12720 | DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, | |||
12721 | DiagID, Context.getPrintingPolicy()); | |||
12722 | // Use the identifier location for the type source range. | |||
12723 | DS.SetRangeStart(FTI.Params[i].IdentLoc); | |||
12724 | DS.SetRangeEnd(FTI.Params[i].IdentLoc); | |||
12725 | Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); | |||
12726 | ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); | |||
12727 | FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); | |||
12728 | } | |||
12729 | } | |||
12730 | } | |||
12731 | } | |||
12732 | ||||
12733 | Decl * | |||
12734 | Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, | |||
12735 | MultiTemplateParamsArg TemplateParameterLists, | |||
12736 | SkipBodyInfo *SkipBody) { | |||
12737 | assert(getCurFunctionDecl() == nullptr && "Function parsing confused")((getCurFunctionDecl() == nullptr && "Function parsing confused" ) ? static_cast<void> (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 12737, __PRETTY_FUNCTION__)); | |||
12738 | assert(D.isFunctionDeclarator() && "Not a function declarator!")((D.isFunctionDeclarator() && "Not a function declarator!" ) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 12738, __PRETTY_FUNCTION__)); | |||
12739 | Scope *ParentScope = FnBodyScope->getParent(); | |||
12740 | ||||
12741 | D.setFunctionDefinitionKind(FDK_Definition); | |||
12742 | Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); | |||
12743 | return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); | |||
12744 | } | |||
12745 | ||||
12746 | void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { | |||
12747 | Consumer.HandleInlineFunctionDefinition(D); | |||
12748 | } | |||
12749 | ||||
12750 | static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, | |||
12751 | const FunctionDecl*& PossibleZeroParamPrototype) { | |||
12752 | // Don't warn about invalid declarations. | |||
12753 | if (FD->isInvalidDecl()) | |||
12754 | return false; | |||
12755 | ||||
12756 | // Or declarations that aren't global. | |||
12757 | if (!FD->isGlobal()) | |||
12758 | return false; | |||
12759 | ||||
12760 | // Don't warn about C++ member functions. | |||
12761 | if (isa<CXXMethodDecl>(FD)) | |||
12762 | return false; | |||
12763 | ||||
12764 | // Don't warn about 'main'. | |||
12765 | if (FD->isMain()) | |||
12766 | return false; | |||
12767 | ||||
12768 | // Don't warn about inline functions. | |||
12769 | if (FD->isInlined()) | |||
12770 | return false; | |||
12771 | ||||
12772 | // Don't warn about function templates. | |||
12773 | if (FD->getDescribedFunctionTemplate()) | |||
12774 | return false; | |||
12775 | ||||
12776 | // Don't warn about function template specializations. | |||
12777 | if (FD->isFunctionTemplateSpecialization()) | |||
12778 | return false; | |||
12779 | ||||
12780 | // Don't warn for OpenCL kernels. | |||
12781 | if (FD->hasAttr<OpenCLKernelAttr>()) | |||
12782 | return false; | |||
12783 | ||||
12784 | // Don't warn on explicitly deleted functions. | |||
12785 | if (FD->isDeleted()) | |||
12786 | return false; | |||
12787 | ||||
12788 | bool MissingPrototype = true; | |||
12789 | for (const FunctionDecl *Prev = FD->getPreviousDecl(); | |||
12790 | Prev; Prev = Prev->getPreviousDecl()) { | |||
12791 | // Ignore any declarations that occur in function or method | |||
12792 | // scope, because they aren't visible from the header. | |||
12793 | if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) | |||
12794 | continue; | |||
12795 | ||||
12796 | MissingPrototype = !Prev->getType()->isFunctionProtoType(); | |||
12797 | if (FD->getNumParams() == 0) | |||
12798 | PossibleZeroParamPrototype = Prev; | |||
12799 | break; | |||
12800 | } | |||
12801 | ||||
12802 | return MissingPrototype; | |||
12803 | } | |||
12804 | ||||
12805 | void | |||
12806 | Sema::CheckForFunctionRedefinition(FunctionDecl *FD, | |||
12807 | const FunctionDecl *EffectiveDefinition, | |||
12808 | SkipBodyInfo *SkipBody) { | |||
12809 | const FunctionDecl *Definition = EffectiveDefinition; | |||
12810 | if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { | |||
12811 | // If this is a friend function defined in a class template, it does not | |||
12812 | // have a body until it is used, nevertheless it is a definition, see | |||
12813 | // [temp.inst]p2: | |||
12814 | // | |||
12815 | // ... for the purpose of determining whether an instantiated redeclaration | |||
12816 | // is valid according to [basic.def.odr] and [class.mem], a declaration that | |||
12817 | // corresponds to a definition in the template is considered to be a | |||
12818 | // definition. | |||
12819 | // | |||
12820 | // The following code must produce redefinition error: | |||
12821 | // | |||
12822 | // template<typename T> struct C20 { friend void func_20() {} }; | |||
12823 | // C20<int> c20i; | |||
12824 | // void func_20() {} | |||
12825 | // | |||
12826 | for (auto I : FD->redecls()) { | |||
12827 | if (I != FD && !I->isInvalidDecl() && | |||
12828 | I->getFriendObjectKind() != Decl::FOK_None) { | |||
12829 | if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { | |||
12830 | if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { | |||
12831 | // A merged copy of the same function, instantiated as a member of | |||
12832 | // the same class, is OK. | |||
12833 | if (declaresSameEntity(OrigFD, Original) && | |||
12834 | declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), | |||
12835 | cast<Decl>(FD->getLexicalDeclContext()))) | |||
12836 | continue; | |||
12837 | } | |||
12838 | ||||
12839 | if (Original->isThisDeclarationADefinition()) { | |||
12840 | Definition = I; | |||
12841 | break; | |||
12842 | } | |||
12843 | } | |||
12844 | } | |||
12845 | } | |||
12846 | } | |||
12847 | ||||
12848 | if (!Definition) | |||
12849 | // Similar to friend functions a friend function template may be a | |||
12850 | // definition and do not have a body if it is instantiated in a class | |||
12851 | // template. | |||
12852 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { | |||
12853 | for (auto I : FTD->redecls()) { | |||
12854 | auto D = cast<FunctionTemplateDecl>(I); | |||
12855 | if (D != FTD) { | |||
12856 | assert(!D->isThisDeclarationADefinition() &&((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 12857, __PRETTY_FUNCTION__)) | |||
12857 | "More than one definition in redeclaration chain")((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 12857, __PRETTY_FUNCTION__)); | |||
12858 | if (D->getFriendObjectKind() != Decl::FOK_None) | |||
12859 | if (FunctionTemplateDecl *FT = | |||
12860 | D->getInstantiatedFromMemberTemplate()) { | |||
12861 | if (FT->isThisDeclarationADefinition()) { | |||
12862 | Definition = D->getTemplatedDecl(); | |||
12863 | break; | |||
12864 | } | |||
12865 | } | |||
12866 | } | |||
12867 | } | |||
12868 | } | |||
12869 | ||||
12870 | if (!Definition) | |||
12871 | return; | |||
12872 | ||||
12873 | if (canRedefineFunction(Definition, getLangOpts())) | |||
12874 | return; | |||
12875 | ||||
12876 | // Don't emit an error when this is redefinition of a typo-corrected | |||
12877 | // definition. | |||
12878 | if (TypoCorrectedFunctionDefinitions.count(Definition)) | |||
12879 | return; | |||
12880 | ||||
12881 | // If we don't have a visible definition of the function, and it's inline or | |||
12882 | // a template, skip the new definition. | |||
12883 | if (SkipBody && !hasVisibleDefinition(Definition) && | |||
12884 | (Definition->getFormalLinkage() == InternalLinkage || | |||
12885 | Definition->isInlined() || | |||
12886 | Definition->getDescribedFunctionTemplate() || | |||
12887 | Definition->getNumTemplateParameterLists())) { | |||
12888 | SkipBody->ShouldSkip = true; | |||
12889 | SkipBody->Previous = const_cast<FunctionDecl*>(Definition); | |||
12890 | if (auto *TD = Definition->getDescribedFunctionTemplate()) | |||
12891 | makeMergedDefinitionVisible(TD); | |||
12892 | makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); | |||
12893 | return; | |||
12894 | } | |||
12895 | ||||
12896 | if (getLangOpts().GNUMode && Definition->isInlineSpecified() && | |||
12897 | Definition->getStorageClass() == SC_Extern) | |||
12898 | Diag(FD->getLocation(), diag::err_redefinition_extern_inline) | |||
12899 | << FD->getDeclName() << getLangOpts().CPlusPlus; | |||
12900 | else | |||
12901 | Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); | |||
12902 | ||||
12903 | Diag(Definition->getLocation(), diag::note_previous_definition); | |||
12904 | FD->setInvalidDecl(); | |||
12905 | } | |||
12906 | ||||
12907 | static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, | |||
12908 | Sema &S) { | |||
12909 | CXXRecordDecl *const LambdaClass = CallOperator->getParent(); | |||
12910 | ||||
12911 | LambdaScopeInfo *LSI = S.PushLambdaScope(); | |||
12912 | LSI->CallOperator = CallOperator; | |||
12913 | LSI->Lambda = LambdaClass; | |||
12914 | LSI->ReturnType = CallOperator->getReturnType(); | |||
12915 | const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); | |||
12916 | ||||
12917 | if (LCD == LCD_None) | |||
12918 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; | |||
12919 | else if (LCD == LCD_ByCopy) | |||
12920 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; | |||
12921 | else if (LCD == LCD_ByRef) | |||
12922 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; | |||
12923 | DeclarationNameInfo DNI = CallOperator->getNameInfo(); | |||
12924 | ||||
12925 | LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); | |||
12926 | LSI->Mutable = !CallOperator->isConst(); | |||
12927 | ||||
12928 | // Add the captures to the LSI so they can be noted as already | |||
12929 | // captured within tryCaptureVar. | |||
12930 | auto I = LambdaClass->field_begin(); | |||
12931 | for (const auto &C : LambdaClass->captures()) { | |||
12932 | if (C.capturesVariable()) { | |||
12933 | VarDecl *VD = C.getCapturedVar(); | |||
12934 | if (VD->isInitCapture()) | |||
12935 | S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); | |||
12936 | QualType CaptureType = VD->getType(); | |||
12937 | const bool ByRef = C.getCaptureKind() == LCK_ByRef; | |||
12938 | LSI->addCapture(VD, /*IsBlock*/false, ByRef, | |||
12939 | /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), | |||
12940 | /*EllipsisLoc*/C.isPackExpansion() | |||
12941 | ? C.getEllipsisLoc() : SourceLocation(), | |||
12942 | CaptureType, /*Invalid*/false); | |||
12943 | ||||
12944 | } else if (C.capturesThis()) { | |||
12945 | LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), | |||
12946 | C.getCaptureKind() == LCK_StarThis); | |||
12947 | } else { | |||
12948 | LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), | |||
12949 | I->getType()); | |||
12950 | } | |||
12951 | ++I; | |||
12952 | } | |||
12953 | } | |||
12954 | ||||
12955 | Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, | |||
12956 | SkipBodyInfo *SkipBody) { | |||
12957 | if (!D) { | |||
12958 | // Parsing the function declaration failed in some way. Push on a fake scope | |||
12959 | // anyway so we can try to parse the function body. | |||
12960 | PushFunctionScope(); | |||
12961 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | |||
12962 | return D; | |||
12963 | } | |||
12964 | ||||
12965 | FunctionDecl *FD = nullptr; | |||
12966 | ||||
12967 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) | |||
12968 | FD = FunTmpl->getTemplatedDecl(); | |||
12969 | else | |||
12970 | FD = cast<FunctionDecl>(D); | |||
12971 | ||||
12972 | // Do not push if it is a lambda because one is already pushed when building | |||
12973 | // the lambda in ActOnStartOfLambdaDefinition(). | |||
12974 | if (!isLambdaCallOperator(FD)) | |||
12975 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | |||
12976 | ||||
12977 | // Check for defining attributes before the check for redefinition. | |||
12978 | if (const auto *Attr = FD->getAttr<AliasAttr>()) { | |||
12979 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; | |||
12980 | FD->dropAttr<AliasAttr>(); | |||
12981 | FD->setInvalidDecl(); | |||
12982 | } | |||
12983 | if (const auto *Attr = FD->getAttr<IFuncAttr>()) { | |||
12984 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; | |||
12985 | FD->dropAttr<IFuncAttr>(); | |||
12986 | FD->setInvalidDecl(); | |||
12987 | } | |||
12988 | ||||
12989 | // See if this is a redefinition. If 'will have body' is already set, then | |||
12990 | // these checks were already performed when it was set. | |||
12991 | if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { | |||
12992 | CheckForFunctionRedefinition(FD, nullptr, SkipBody); | |||
12993 | ||||
12994 | // If we're skipping the body, we're done. Don't enter the scope. | |||
12995 | if (SkipBody && SkipBody->ShouldSkip) | |||
12996 | return D; | |||
12997 | } | |||
12998 | ||||
12999 | // Mark this function as "will have a body eventually". This lets users to | |||
13000 | // call e.g. isInlineDefinitionExternallyVisible while we're still parsing | |||
13001 | // this function. | |||
13002 | FD->setWillHaveBody(); | |||
13003 | ||||
13004 | // If we are instantiating a generic lambda call operator, push | |||
13005 | // a LambdaScopeInfo onto the function stack. But use the information | |||
13006 | // that's already been calculated (ActOnLambdaExpr) to prime the current | |||
13007 | // LambdaScopeInfo. | |||
13008 | // When the template operator is being specialized, the LambdaScopeInfo, | |||
13009 | // has to be properly restored so that tryCaptureVariable doesn't try | |||
13010 | // and capture any new variables. In addition when calculating potential | |||
13011 | // captures during transformation of nested lambdas, it is necessary to | |||
13012 | // have the LSI properly restored. | |||
13013 | if (isGenericLambdaCallOperatorSpecialization(FD)) { | |||
13014 | assert(inTemplateInstantiation() &&((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13016, __PRETTY_FUNCTION__)) | |||
13015 | "There should be an active template instantiation on the stack "((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13016, __PRETTY_FUNCTION__)) | |||
13016 | "when instantiating a generic lambda!")((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13016, __PRETTY_FUNCTION__)); | |||
13017 | RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); | |||
13018 | } else { | |||
13019 | // Enter a new function scope | |||
13020 | PushFunctionScope(); | |||
13021 | } | |||
13022 | ||||
13023 | // Builtin functions cannot be defined. | |||
13024 | if (unsigned BuiltinID = FD->getBuiltinID()) { | |||
13025 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && | |||
13026 | !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { | |||
13027 | Diag(FD->getLocation(), diag::err_builtin_definition) << FD; | |||
13028 | FD->setInvalidDecl(); | |||
13029 | } | |||
13030 | } | |||
13031 | ||||
13032 | // The return type of a function definition must be complete | |||
13033 | // (C99 6.9.1p3, C++ [dcl.fct]p6). | |||
13034 | QualType ResultType = FD->getReturnType(); | |||
13035 | if (!ResultType->isDependentType() && !ResultType->isVoidType() && | |||
13036 | !FD->isInvalidDecl() && | |||
13037 | RequireCompleteType(FD->getLocation(), ResultType, | |||
13038 | diag::err_func_def_incomplete_result)) | |||
13039 | FD->setInvalidDecl(); | |||
13040 | ||||
13041 | if (FnBodyScope) | |||
13042 | PushDeclContext(FnBodyScope, FD); | |||
13043 | ||||
13044 | // Check the validity of our function parameters | |||
13045 | CheckParmsForFunctionDef(FD->parameters(), | |||
13046 | /*CheckParameterNames=*/true); | |||
13047 | ||||
13048 | // Add non-parameter declarations already in the function to the current | |||
13049 | // scope. | |||
13050 | if (FnBodyScope) { | |||
13051 | for (Decl *NPD : FD->decls()) { | |||
13052 | auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); | |||
13053 | if (!NonParmDecl) | |||
13054 | continue; | |||
13055 | assert(!isa<ParmVarDecl>(NonParmDecl) &&((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13056, __PRETTY_FUNCTION__)) | |||
13056 | "parameters should not be in newly created FD yet")((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13056, __PRETTY_FUNCTION__)); | |||
13057 | ||||
13058 | // If the decl has a name, make it accessible in the current scope. | |||
13059 | if (NonParmDecl->getDeclName()) | |||
13060 | PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); | |||
13061 | ||||
13062 | // Similarly, dive into enums and fish their constants out, making them | |||
13063 | // accessible in this scope. | |||
13064 | if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { | |||
13065 | for (auto *EI : ED->enumerators()) | |||
13066 | PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); | |||
13067 | } | |||
13068 | } | |||
13069 | } | |||
13070 | ||||
13071 | // Introduce our parameters into the function scope | |||
13072 | for (auto Param : FD->parameters()) { | |||
13073 | Param->setOwningFunction(FD); | |||
13074 | ||||
13075 | // If this has an identifier, add it to the scope stack. | |||
13076 | if (Param->getIdentifier() && FnBodyScope) { | |||
13077 | CheckShadow(FnBodyScope, Param); | |||
13078 | ||||
13079 | PushOnScopeChains(Param, FnBodyScope); | |||
13080 | } | |||
13081 | } | |||
13082 | ||||
13083 | // Ensure that the function's exception specification is instantiated. | |||
13084 | if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) | |||
13085 | ResolveExceptionSpec(D->getLocation(), FPT); | |||
13086 | ||||
13087 | // dllimport cannot be applied to non-inline function definitions. | |||
13088 | if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && | |||
13089 | !FD->isTemplateInstantiation()) { | |||
13090 | assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void > (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13090, __PRETTY_FUNCTION__)); | |||
13091 | Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); | |||
13092 | FD->setInvalidDecl(); | |||
13093 | return D; | |||
13094 | } | |||
13095 | // We want to attach documentation to original Decl (which might be | |||
13096 | // a function template). | |||
13097 | ActOnDocumentableDecl(D); | |||
13098 | if (getCurLexicalContext()->isObjCContainer() && | |||
13099 | getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && | |||
13100 | getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) | |||
13101 | Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); | |||
13102 | ||||
13103 | return D; | |||
13104 | } | |||
13105 | ||||
13106 | /// Given the set of return statements within a function body, | |||
13107 | /// compute the variables that are subject to the named return value | |||
13108 | /// optimization. | |||
13109 | /// | |||
13110 | /// Each of the variables that is subject to the named return value | |||
13111 | /// optimization will be marked as NRVO variables in the AST, and any | |||
13112 | /// return statement that has a marked NRVO variable as its NRVO candidate can | |||
13113 | /// use the named return value optimization. | |||
13114 | /// | |||
13115 | /// This function applies a very simplistic algorithm for NRVO: if every return | |||
13116 | /// statement in the scope of a variable has the same NRVO candidate, that | |||
13117 | /// candidate is an NRVO variable. | |||
13118 | void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { | |||
13119 | ReturnStmt **Returns = Scope->Returns.data(); | |||
13120 | ||||
13121 | for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { | |||
13122 | if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { | |||
13123 | if (!NRVOCandidate->isNRVOVariable()) | |||
13124 | Returns[I]->setNRVOCandidate(nullptr); | |||
13125 | } | |||
13126 | } | |||
13127 | } | |||
13128 | ||||
13129 | bool Sema::canDelayFunctionBody(const Declarator &D) { | |||
13130 | // We can't delay parsing the body of a constexpr function template (yet). | |||
13131 | if (D.getDeclSpec().isConstexprSpecified()) | |||
13132 | return false; | |||
13133 | ||||
13134 | // We can't delay parsing the body of a function template with a deduced | |||
13135 | // return type (yet). | |||
13136 | if (D.getDeclSpec().hasAutoTypeSpec()) { | |||
13137 | // If the placeholder introduces a non-deduced trailing return type, | |||
13138 | // we can still delay parsing it. | |||
13139 | if (D.getNumTypeObjects()) { | |||
13140 | const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); | |||
13141 | if (Outer.Kind == DeclaratorChunk::Function && | |||
13142 | Outer.Fun.hasTrailingReturnType()) { | |||
13143 | QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); | |||
13144 | return Ty.isNull() || !Ty->isUndeducedType(); | |||
13145 | } | |||
13146 | } | |||
13147 | return false; | |||
13148 | } | |||
13149 | ||||
13150 | return true; | |||
13151 | } | |||
13152 | ||||
13153 | bool Sema::canSkipFunctionBody(Decl *D) { | |||
13154 | // We cannot skip the body of a function (or function template) which is | |||
13155 | // constexpr, since we may need to evaluate its body in order to parse the | |||
13156 | // rest of the file. | |||
13157 | // We cannot skip the body of a function with an undeduced return type, | |||
13158 | // because any callers of that function need to know the type. | |||
13159 | if (const FunctionDecl *FD = D->getAsFunction()) { | |||
13160 | if (FD->isConstexpr()) | |||
13161 | return false; | |||
13162 | // We can't simply call Type::isUndeducedType here, because inside template | |||
13163 | // auto can be deduced to a dependent type, which is not considered | |||
13164 | // "undeduced". | |||
13165 | if (FD->getReturnType()->getContainedDeducedType()) | |||
13166 | return false; | |||
13167 | } | |||
13168 | return Consumer.shouldSkipFunctionBody(D); | |||
13169 | } | |||
13170 | ||||
13171 | Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { | |||
13172 | if (!Decl) | |||
13173 | return nullptr; | |||
13174 | if (FunctionDecl *FD = Decl->getAsFunction()) | |||
13175 | FD->setHasSkippedBody(); | |||
13176 | else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) | |||
13177 | MD->setHasSkippedBody(); | |||
13178 | return Decl; | |||
13179 | } | |||
13180 | ||||
13181 | Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { | |||
13182 | return ActOnFinishFunctionBody(D, BodyArg, false); | |||
13183 | } | |||
13184 | ||||
13185 | /// RAII object that pops an ExpressionEvaluationContext when exiting a function | |||
13186 | /// body. | |||
13187 | class ExitFunctionBodyRAII { | |||
13188 | public: | |||
13189 | ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} | |||
13190 | ~ExitFunctionBodyRAII() { | |||
13191 | if (!IsLambda) | |||
13192 | S.PopExpressionEvaluationContext(); | |||
13193 | } | |||
13194 | ||||
13195 | private: | |||
13196 | Sema &S; | |||
13197 | bool IsLambda = false; | |||
13198 | }; | |||
13199 | ||||
13200 | static void diagnoseImplicitlyRetainedSelf(Sema &S) { | |||
13201 | llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; | |||
13202 | ||||
13203 | auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { | |||
13204 | if (EscapeInfo.count(BD)) | |||
13205 | return EscapeInfo[BD]; | |||
13206 | ||||
13207 | bool R = false; | |||
13208 | const BlockDecl *CurBD = BD; | |||
13209 | ||||
13210 | do { | |||
13211 | R = !CurBD->doesNotEscape(); | |||
13212 | if (R) | |||
13213 | break; | |||
13214 | CurBD = CurBD->getParent()->getInnermostBlockDecl(); | |||
13215 | } while (CurBD); | |||
13216 | ||||
13217 | return EscapeInfo[BD] = R; | |||
13218 | }; | |||
13219 | ||||
13220 | // If the location where 'self' is implicitly retained is inside a escaping | |||
13221 | // block, emit a diagnostic. | |||
13222 | for (const std::pair<SourceLocation, const BlockDecl *> &P : | |||
13223 | S.ImplicitlyRetainedSelfLocs) | |||
13224 | if (IsOrNestedInEscapingBlock(P.second)) | |||
13225 | S.Diag(P.first, diag::warn_implicitly_retains_self) | |||
13226 | << FixItHint::CreateInsertion(P.first, "self->"); | |||
13227 | } | |||
13228 | ||||
13229 | Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, | |||
13230 | bool IsInstantiation) { | |||
13231 | FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; | |||
13232 | ||||
13233 | sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | |||
13234 | sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; | |||
13235 | ||||
13236 | if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) | |||
13237 | CheckCompletedCoroutineBody(FD, Body); | |||
13238 | ||||
13239 | // Do not call PopExpressionEvaluationContext() if it is a lambda because one | |||
13240 | // is already popped when finishing the lambda in BuildLambdaExpr(). This is | |||
13241 | // meant to pop the context added in ActOnStartOfFunctionDef(). | |||
13242 | ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); | |||
13243 | ||||
13244 | if (FD) { | |||
13245 | FD->setBody(Body); | |||
13246 | FD->setWillHaveBody(false); | |||
13247 | ||||
13248 | if (getLangOpts().CPlusPlus14) { | |||
13249 | if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && | |||
13250 | FD->getReturnType()->isUndeducedType()) { | |||
13251 | // If the function has a deduced result type but contains no 'return' | |||
13252 | // statements, the result type as written must be exactly 'auto', and | |||
13253 | // the deduced result type is 'void'. | |||
13254 | if (!FD->getReturnType()->getAs<AutoType>()) { | |||
13255 | Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) | |||
13256 | << FD->getReturnType(); | |||
13257 | FD->setInvalidDecl(); | |||
13258 | } else { | |||
13259 | // Substitute 'void' for the 'auto' in the type. | |||
13260 | TypeLoc ResultType = getReturnTypeLoc(FD); | |||
13261 | Context.adjustDeducedFunctionResultType( | |||
13262 | FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); | |||
13263 | } | |||
13264 | } | |||
13265 | } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { | |||
13266 | // In C++11, we don't use 'auto' deduction rules for lambda call | |||
13267 | // operators because we don't support return type deduction. | |||
13268 | auto *LSI = getCurLambda(); | |||
13269 | if (LSI->HasImplicitReturnType) { | |||
13270 | deduceClosureReturnType(*LSI); | |||
13271 | ||||
13272 | // C++11 [expr.prim.lambda]p4: | |||
13273 | // [...] if there are no return statements in the compound-statement | |||
13274 | // [the deduced type is] the type void | |||
13275 | QualType RetType = | |||
13276 | LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; | |||
13277 | ||||
13278 | // Update the return type to the deduced type. | |||
13279 | const FunctionProtoType *Proto = | |||
13280 | FD->getType()->getAs<FunctionProtoType>(); | |||
13281 | FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), | |||
13282 | Proto->getExtProtoInfo())); | |||
13283 | } | |||
13284 | } | |||
13285 | ||||
13286 | // If the function implicitly returns zero (like 'main') or is naked, | |||
13287 | // don't complain about missing return statements. | |||
13288 | if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) | |||
13289 | WP.disableCheckFallThrough(); | |||
13290 | ||||
13291 | // MSVC permits the use of pure specifier (=0) on function definition, | |||
13292 | // defined at class scope, warn about this non-standard construct. | |||
13293 | if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) | |||
13294 | Diag(FD->getLocation(), diag::ext_pure_function_definition); | |||
13295 | ||||
13296 | if (!FD->isInvalidDecl()) { | |||
13297 | // Don't diagnose unused parameters of defaulted or deleted functions. | |||
13298 | if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) | |||
13299 | DiagnoseUnusedParameters(FD->parameters()); | |||
13300 | DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), | |||
13301 | FD->getReturnType(), FD); | |||
13302 | ||||
13303 | // If this is a structor, we need a vtable. | |||
13304 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) | |||
13305 | MarkVTableUsed(FD->getLocation(), Constructor->getParent()); | |||
13306 | else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) | |||
13307 | MarkVTableUsed(FD->getLocation(), Destructor->getParent()); | |||
13308 | ||||
13309 | // Try to apply the named return value optimization. We have to check | |||
13310 | // if we can do this here because lambdas keep return statements around | |||
13311 | // to deduce an implicit return type. | |||
13312 | if (FD->getReturnType()->isRecordType() && | |||
13313 | (!getLangOpts().CPlusPlus || !FD->isDependentContext())) | |||
13314 | computeNRVO(Body, getCurFunction()); | |||
13315 | } | |||
13316 | ||||
13317 | // GNU warning -Wmissing-prototypes: | |||
13318 | // Warn if a global function is defined without a previous | |||
13319 | // prototype declaration. This warning is issued even if the | |||
13320 | // definition itself provides a prototype. The aim is to detect | |||
13321 | // global functions that fail to be declared in header files. | |||
13322 | const FunctionDecl *PossibleZeroParamPrototype = nullptr; | |||
13323 | if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { | |||
13324 | Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; | |||
13325 | ||||
13326 | if (PossibleZeroParamPrototype) { | |||
13327 | // We found a declaration that is not a prototype, | |||
13328 | // but that could be a zero-parameter prototype | |||
13329 | if (TypeSourceInfo *TI = | |||
13330 | PossibleZeroParamPrototype->getTypeSourceInfo()) { | |||
13331 | TypeLoc TL = TI->getTypeLoc(); | |||
13332 | if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) | |||
13333 | Diag(PossibleZeroParamPrototype->getLocation(), | |||
13334 | diag::note_declaration_not_a_prototype) | |||
13335 | << PossibleZeroParamPrototype | |||
13336 | << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); | |||
13337 | } | |||
13338 | } | |||
13339 | ||||
13340 | // GNU warning -Wstrict-prototypes | |||
13341 | // Warn if K&R function is defined without a previous declaration. | |||
13342 | // This warning is issued only if the definition itself does not provide | |||
13343 | // a prototype. Only K&R definitions do not provide a prototype. | |||
13344 | // An empty list in a function declarator that is part of a definition | |||
13345 | // of that function specifies that the function has no parameters | |||
13346 | // (C99 6.7.5.3p14) | |||
13347 | if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && | |||
13348 | !LangOpts.CPlusPlus) { | |||
13349 | TypeSourceInfo *TI = FD->getTypeSourceInfo(); | |||
13350 | TypeLoc TL = TI->getTypeLoc(); | |||
13351 | FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); | |||
13352 | Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; | |||
13353 | } | |||
13354 | } | |||
13355 | ||||
13356 | // Warn on CPUDispatch with an actual body. | |||
13357 | if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) | |||
13358 | if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) | |||
13359 | if (!CmpndBody->body_empty()) | |||
13360 | Diag(CmpndBody->body_front()->getBeginLoc(), | |||
13361 | diag::warn_dispatch_body_ignored); | |||
13362 | ||||
13363 | if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { | |||
13364 | const CXXMethodDecl *KeyFunction; | |||
13365 | if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && | |||
13366 | MD->isVirtual() && | |||
13367 | (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && | |||
13368 | MD == KeyFunction->getCanonicalDecl()) { | |||
13369 | // Update the key-function state if necessary for this ABI. | |||
13370 | if (FD->isInlined() && | |||
13371 | !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { | |||
13372 | Context.setNonKeyFunction(MD); | |||
13373 | ||||
13374 | // If the newly-chosen key function is already defined, then we | |||
13375 | // need to mark the vtable as used retroactively. | |||
13376 | KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); | |||
13377 | const FunctionDecl *Definition; | |||
13378 | if (KeyFunction && KeyFunction->isDefined(Definition)) | |||
13379 | MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); | |||
13380 | } else { | |||
13381 | // We just defined they key function; mark the vtable as used. | |||
13382 | MarkVTableUsed(FD->getLocation(), MD->getParent(), true); | |||
13383 | } | |||
13384 | } | |||
13385 | } | |||
13386 | ||||
13387 | assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && "Function parsing confused") ? static_cast <void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13388, __PRETTY_FUNCTION__)) | |||
13388 | "Function parsing confused")(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && "Function parsing confused") ? static_cast <void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13388, __PRETTY_FUNCTION__)); | |||
13389 | } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { | |||
13390 | assert(MD == getCurMethodDecl() && "Method parsing confused")((MD == getCurMethodDecl() && "Method parsing confused" ) ? static_cast<void> (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13390, __PRETTY_FUNCTION__)); | |||
13391 | MD->setBody(Body); | |||
13392 | if (!MD->isInvalidDecl()) { | |||
13393 | DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), | |||
13394 | MD->getReturnType(), MD); | |||
13395 | ||||
13396 | if (Body) | |||
13397 | computeNRVO(Body, getCurFunction()); | |||
13398 | } | |||
13399 | if (getCurFunction()->ObjCShouldCallSuper) { | |||
13400 | Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) | |||
13401 | << MD->getSelector().getAsString(); | |||
13402 | getCurFunction()->ObjCShouldCallSuper = false; | |||
13403 | } | |||
13404 | if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { | |||
13405 | const ObjCMethodDecl *InitMethod = nullptr; | |||
13406 | bool isDesignated = | |||
13407 | MD->isDesignatedInitializerForTheInterface(&InitMethod); | |||
13408 | assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void> (0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13408, __PRETTY_FUNCTION__)); | |||
13409 | (void)isDesignated; | |||
13410 | ||||
13411 | auto superIsNSObject = [&](const ObjCMethodDecl *MD) { | |||
13412 | auto IFace = MD->getClassInterface(); | |||
13413 | if (!IFace) | |||
13414 | return false; | |||
13415 | auto SuperD = IFace->getSuperClass(); | |||
13416 | if (!SuperD) | |||
13417 | return false; | |||
13418 | return SuperD->getIdentifier() == | |||
13419 | NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); | |||
13420 | }; | |||
13421 | // Don't issue this warning for unavailable inits or direct subclasses | |||
13422 | // of NSObject. | |||
13423 | if (!MD->isUnavailable() && !superIsNSObject(MD)) { | |||
13424 | Diag(MD->getLocation(), | |||
13425 | diag::warn_objc_designated_init_missing_super_call); | |||
13426 | Diag(InitMethod->getLocation(), | |||
13427 | diag::note_objc_designated_init_marked_here); | |||
13428 | } | |||
13429 | getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; | |||
13430 | } | |||
13431 | if (getCurFunction()->ObjCWarnForNoInitDelegation) { | |||
13432 | // Don't issue this warning for unavaialable inits. | |||
13433 | if (!MD->isUnavailable()) | |||
13434 | Diag(MD->getLocation(), | |||
13435 | diag::warn_objc_secondary_init_missing_init_call); | |||
13436 | getCurFunction()->ObjCWarnForNoInitDelegation = false; | |||
13437 | } | |||
13438 | ||||
13439 | diagnoseImplicitlyRetainedSelf(*this); | |||
13440 | } else { | |||
13441 | // Parsing the function declaration failed in some way. Pop the fake scope | |||
13442 | // we pushed on. | |||
13443 | PopFunctionScopeInfo(ActivePolicy, dcl); | |||
13444 | return nullptr; | |||
13445 | } | |||
13446 | ||||
13447 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | |||
13448 | DiagnoseUnguardedAvailabilityViolations(dcl); | |||
13449 | ||||
13450 | assert(!getCurFunction()->ObjCShouldCallSuper &&((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13452, __PRETTY_FUNCTION__)) | |||
13451 | "This should only be set for ObjC methods, which should have been "((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13452, __PRETTY_FUNCTION__)) | |||
13452 | "handled in the block above.")((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13452, __PRETTY_FUNCTION__)); | |||
13453 | ||||
13454 | // Verify and clean out per-function state. | |||
13455 | if (Body && (!FD || !FD->isDefaulted())) { | |||
13456 | // C++ constructors that have function-try-blocks can't have return | |||
13457 | // statements in the handlers of that block. (C++ [except.handle]p14) | |||
13458 | // Verify this. | |||
13459 | if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) | |||
13460 | DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); | |||
13461 | ||||
13462 | // Verify that gotos and switch cases don't jump into scopes illegally. | |||
13463 | if (getCurFunction()->NeedsScopeChecking() && | |||
13464 | !PP.isCodeCompletionEnabled()) | |||
13465 | DiagnoseInvalidJumps(Body); | |||
13466 | ||||
13467 | if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { | |||
13468 | if (!Destructor->getParent()->isDependentType()) | |||
13469 | CheckDestructor(Destructor); | |||
13470 | ||||
13471 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | |||
13472 | Destructor->getParent()); | |||
13473 | } | |||
13474 | ||||
13475 | // If any errors have occurred, clear out any temporaries that may have | |||
13476 | // been leftover. This ensures that these temporaries won't be picked up for | |||
13477 | // deletion in some later function. | |||
13478 | if (getDiagnostics().hasErrorOccurred() || | |||
13479 | getDiagnostics().getSuppressAllDiagnostics()) { | |||
13480 | DiscardCleanupsInEvaluationContext(); | |||
13481 | } | |||
13482 | if (!getDiagnostics().hasUncompilableErrorOccurred() && | |||
13483 | !isa<FunctionTemplateDecl>(dcl)) { | |||
13484 | // Since the body is valid, issue any analysis-based warnings that are | |||
13485 | // enabled. | |||
13486 | ActivePolicy = &WP; | |||
13487 | } | |||
13488 | ||||
13489 | if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && | |||
13490 | (!CheckConstexprFunctionDecl(FD) || | |||
13491 | !CheckConstexprFunctionBody(FD, Body))) | |||
13492 | FD->setInvalidDecl(); | |||
13493 | ||||
13494 | if (FD && FD->hasAttr<NakedAttr>()) { | |||
13495 | for (const Stmt *S : Body->children()) { | |||
13496 | // Allow local register variables without initializer as they don't | |||
13497 | // require prologue. | |||
13498 | bool RegisterVariables = false; | |||
13499 | if (auto *DS = dyn_cast<DeclStmt>(S)) { | |||
13500 | for (const auto *Decl : DS->decls()) { | |||
13501 | if (const auto *Var = dyn_cast<VarDecl>(Decl)) { | |||
13502 | RegisterVariables = | |||
13503 | Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); | |||
13504 | if (!RegisterVariables) | |||
13505 | break; | |||
13506 | } | |||
13507 | } | |||
13508 | } | |||
13509 | if (RegisterVariables) | |||
13510 | continue; | |||
13511 | if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { | |||
13512 | Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); | |||
13513 | Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); | |||
13514 | FD->setInvalidDecl(); | |||
13515 | break; | |||
13516 | } | |||
13517 | } | |||
13518 | } | |||
13519 | ||||
13520 | assert(ExprCleanupObjects.size() ==((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13522, __PRETTY_FUNCTION__)) | |||
13521 | ExprEvalContexts.back().NumCleanupObjects &&((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13522, __PRETTY_FUNCTION__)) | |||
13522 | "Leftover temporaries in function")((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13522, __PRETTY_FUNCTION__)); | |||
13523 | assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")((!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13523, __PRETTY_FUNCTION__)); | |||
13524 | assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13525, __PRETTY_FUNCTION__)) | |||
13525 | "Leftover expressions for odr-use checking")((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13525, __PRETTY_FUNCTION__)); | |||
13526 | } | |||
13527 | ||||
13528 | if (!IsInstantiation) | |||
13529 | PopDeclContext(); | |||
13530 | ||||
13531 | PopFunctionScopeInfo(ActivePolicy, dcl); | |||
13532 | // If any errors have occurred, clear out any temporaries that may have | |||
13533 | // been leftover. This ensures that these temporaries won't be picked up for | |||
13534 | // deletion in some later function. | |||
13535 | if (getDiagnostics().hasErrorOccurred()) { | |||
13536 | DiscardCleanupsInEvaluationContext(); | |||
13537 | } | |||
13538 | ||||
13539 | return dcl; | |||
13540 | } | |||
13541 | ||||
13542 | /// When we finish delayed parsing of an attribute, we must attach it to the | |||
13543 | /// relevant Decl. | |||
13544 | void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, | |||
13545 | ParsedAttributes &Attrs) { | |||
13546 | // Always attach attributes to the underlying decl. | |||
13547 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | |||
13548 | D = TD->getTemplatedDecl(); | |||
13549 | ProcessDeclAttributeList(S, D, Attrs); | |||
13550 | ||||
13551 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) | |||
13552 | if (Method->isStatic()) | |||
13553 | checkThisInStaticMemberFunctionAttributes(Method); | |||
13554 | } | |||
13555 | ||||
13556 | /// ImplicitlyDefineFunction - An undeclared identifier was used in a function | |||
13557 | /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). | |||
13558 | NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, | |||
13559 | IdentifierInfo &II, Scope *S) { | |||
13560 | // Find the scope in which the identifier is injected and the corresponding | |||
13561 | // DeclContext. | |||
13562 | // FIXME: C89 does not say what happens if there is no enclosing block scope. | |||
13563 | // In that case, we inject the declaration into the translation unit scope | |||
13564 | // instead. | |||
13565 | Scope *BlockScope = S; | |||
13566 | while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) | |||
13567 | BlockScope = BlockScope->getParent(); | |||
13568 | ||||
13569 | Scope *ContextScope = BlockScope; | |||
13570 | while (!ContextScope->getEntity()) | |||
13571 | ContextScope = ContextScope->getParent(); | |||
13572 | ContextRAII SavedContext(*this, ContextScope->getEntity()); | |||
13573 | ||||
13574 | // Before we produce a declaration for an implicitly defined | |||
13575 | // function, see whether there was a locally-scoped declaration of | |||
13576 | // this name as a function or variable. If so, use that | |||
13577 | // (non-visible) declaration, and complain about it. | |||
13578 | NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); | |||
13579 | if (ExternCPrev) { | |||
13580 | // We still need to inject the function into the enclosing block scope so | |||
13581 | // that later (non-call) uses can see it. | |||
13582 | PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); | |||
13583 | ||||
13584 | // C89 footnote 38: | |||
13585 | // If in fact it is not defined as having type "function returning int", | |||
13586 | // the behavior is undefined. | |||
13587 | if (!isa<FunctionDecl>(ExternCPrev) || | |||
13588 | !Context.typesAreCompatible( | |||
13589 | cast<FunctionDecl>(ExternCPrev)->getType(), | |||
13590 | Context.getFunctionNoProtoType(Context.IntTy))) { | |||
13591 | Diag(Loc, diag::ext_use_out_of_scope_declaration) | |||
13592 | << ExternCPrev << !getLangOpts().C99; | |||
13593 | Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); | |||
13594 | return ExternCPrev; | |||
13595 | } | |||
13596 | } | |||
13597 | ||||
13598 | // Extension in C99. Legal in C90, but warn about it. | |||
13599 | unsigned diag_id; | |||
13600 | if (II.getName().startswith("__builtin_")) | |||
13601 | diag_id = diag::warn_builtin_unknown; | |||
13602 | // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. | |||
13603 | else if (getLangOpts().OpenCL) | |||
13604 | diag_id = diag::err_opencl_implicit_function_decl; | |||
13605 | else if (getLangOpts().C99) | |||
13606 | diag_id = diag::ext_implicit_function_decl; | |||
13607 | else | |||
13608 | diag_id = diag::warn_implicit_function_decl; | |||
13609 | Diag(Loc, diag_id) << &II; | |||
13610 | ||||
13611 | // If we found a prior declaration of this function, don't bother building | |||
13612 | // another one. We've already pushed that one into scope, so there's nothing | |||
13613 | // more to do. | |||
13614 | if (ExternCPrev) | |||
13615 | return ExternCPrev; | |||
13616 | ||||
13617 | // Because typo correction is expensive, only do it if the implicit | |||
13618 | // function declaration is going to be treated as an error. | |||
13619 | if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { | |||
13620 | TypoCorrection Corrected; | |||
13621 | DeclFilterCCC<FunctionDecl> CCC{}; | |||
13622 | if (S && (Corrected = | |||
13623 | CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, | |||
13624 | S, nullptr, CCC, CTK_NonError))) | |||
13625 | diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), | |||
13626 | /*ErrorRecovery*/false); | |||
13627 | } | |||
13628 | ||||
13629 | // Set a Declarator for the implicit definition: int foo(); | |||
13630 | const char *Dummy; | |||
13631 | AttributeFactory attrFactory; | |||
13632 | DeclSpec DS(attrFactory); | |||
13633 | unsigned DiagID; | |||
13634 | bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, | |||
13635 | Context.getPrintingPolicy()); | |||
13636 | (void)Error; // Silence warning. | |||
13637 | assert(!Error && "Error setting up implicit decl!")((!Error && "Error setting up implicit decl!") ? static_cast <void> (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13637, __PRETTY_FUNCTION__)); | |||
13638 | SourceLocation NoLoc; | |||
13639 | Declarator D(DS, DeclaratorContext::BlockContext); | |||
13640 | D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, | |||
13641 | /*IsAmbiguous=*/false, | |||
13642 | /*LParenLoc=*/NoLoc, | |||
13643 | /*Params=*/nullptr, | |||
13644 | /*NumParams=*/0, | |||
13645 | /*EllipsisLoc=*/NoLoc, | |||
13646 | /*RParenLoc=*/NoLoc, | |||
13647 | /*RefQualifierIsLvalueRef=*/true, | |||
13648 | /*RefQualifierLoc=*/NoLoc, | |||
13649 | /*MutableLoc=*/NoLoc, EST_None, | |||
13650 | /*ESpecRange=*/SourceRange(), | |||
13651 | /*Exceptions=*/nullptr, | |||
13652 | /*ExceptionRanges=*/nullptr, | |||
13653 | /*NumExceptions=*/0, | |||
13654 | /*NoexceptExpr=*/nullptr, | |||
13655 | /*ExceptionSpecTokens=*/nullptr, | |||
13656 | /*DeclsInPrototype=*/None, Loc, | |||
13657 | Loc, D), | |||
13658 | std::move(DS.getAttributes()), SourceLocation()); | |||
13659 | D.SetIdentifier(&II, Loc); | |||
13660 | ||||
13661 | // Insert this function into the enclosing block scope. | |||
13662 | FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); | |||
13663 | FD->setImplicit(); | |||
13664 | ||||
13665 | AddKnownFunctionAttributes(FD); | |||
13666 | ||||
13667 | return FD; | |||
13668 | } | |||
13669 | ||||
13670 | /// Adds any function attributes that we know a priori based on | |||
13671 | /// the declaration of this function. | |||
13672 | /// | |||
13673 | /// These attributes can apply both to implicitly-declared builtins | |||
13674 | /// (like __builtin___printf_chk) or to library-declared functions | |||
13675 | /// like NSLog or printf. | |||
13676 | /// | |||
13677 | /// We need to check for duplicate attributes both here and where user-written | |||
13678 | /// attributes are applied to declarations. | |||
13679 | void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { | |||
13680 | if (FD->isInvalidDecl()) | |||
13681 | return; | |||
13682 | ||||
13683 | // If this is a built-in function, map its builtin attributes to | |||
13684 | // actual attributes. | |||
13685 | if (unsigned BuiltinID = FD->getBuiltinID()) { | |||
13686 | // Handle printf-formatting attributes. | |||
13687 | unsigned FormatIdx; | |||
13688 | bool HasVAListArg; | |||
13689 | if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { | |||
13690 | if (!FD->hasAttr<FormatAttr>()) { | |||
13691 | const char *fmt = "printf"; | |||
13692 | unsigned int NumParams = FD->getNumParams(); | |||
13693 | if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) | |||
13694 | FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) | |||
13695 | fmt = "NSString"; | |||
13696 | FD->addAttr(FormatAttr::CreateImplicit(Context, | |||
13697 | &Context.Idents.get(fmt), | |||
13698 | FormatIdx+1, | |||
13699 | HasVAListArg ? 0 : FormatIdx+2, | |||
13700 | FD->getLocation())); | |||
13701 | } | |||
13702 | } | |||
13703 | if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, | |||
13704 | HasVAListArg)) { | |||
13705 | if (!FD->hasAttr<FormatAttr>()) | |||
13706 | FD->addAttr(FormatAttr::CreateImplicit(Context, | |||
13707 | &Context.Idents.get("scanf"), | |||
13708 | FormatIdx+1, | |||
13709 | HasVAListArg ? 0 : FormatIdx+2, | |||
13710 | FD->getLocation())); | |||
13711 | } | |||
13712 | ||||
13713 | // Handle automatically recognized callbacks. | |||
13714 | SmallVector<int, 4> Encoding; | |||
13715 | if (!FD->hasAttr<CallbackAttr>() && | |||
13716 | Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) | |||
13717 | FD->addAttr(CallbackAttr::CreateImplicit( | |||
13718 | Context, Encoding.data(), Encoding.size(), FD->getLocation())); | |||
13719 | ||||
13720 | // Mark const if we don't care about errno and that is the only thing | |||
13721 | // preventing the function from being const. This allows IRgen to use LLVM | |||
13722 | // intrinsics for such functions. | |||
13723 | if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && | |||
13724 | Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) | |||
13725 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | |||
13726 | ||||
13727 | // We make "fma" on some platforms const because we know it does not set | |||
13728 | // errno in those environments even though it could set errno based on the | |||
13729 | // C standard. | |||
13730 | const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); | |||
13731 | if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && | |||
13732 | !FD->hasAttr<ConstAttr>()) { | |||
13733 | switch (BuiltinID) { | |||
13734 | case Builtin::BI__builtin_fma: | |||
13735 | case Builtin::BI__builtin_fmaf: | |||
13736 | case Builtin::BI__builtin_fmal: | |||
13737 | case Builtin::BIfma: | |||
13738 | case Builtin::BIfmaf: | |||
13739 | case Builtin::BIfmal: | |||
13740 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | |||
13741 | break; | |||
13742 | default: | |||
13743 | break; | |||
13744 | } | |||
13745 | } | |||
13746 | ||||
13747 | if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && | |||
13748 | !FD->hasAttr<ReturnsTwiceAttr>()) | |||
13749 | FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, | |||
13750 | FD->getLocation())); | |||
13751 | if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) | |||
13752 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | |||
13753 | if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) | |||
13754 | FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); | |||
13755 | if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) | |||
13756 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | |||
13757 | if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && | |||
13758 | !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { | |||
13759 | // Add the appropriate attribute, depending on the CUDA compilation mode | |||
13760 | // and which target the builtin belongs to. For example, during host | |||
13761 | // compilation, aux builtins are __device__, while the rest are __host__. | |||
13762 | if (getLangOpts().CUDAIsDevice != | |||
13763 | Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) | |||
13764 | FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); | |||
13765 | else | |||
13766 | FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); | |||
13767 | } | |||
13768 | } | |||
13769 | ||||
13770 | // If C++ exceptions are enabled but we are told extern "C" functions cannot | |||
13771 | // throw, add an implicit nothrow attribute to any extern "C" function we come | |||
13772 | // across. | |||
13773 | if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && | |||
13774 | FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { | |||
13775 | const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); | |||
13776 | if (!FPT || FPT->getExceptionSpecType() == EST_None) | |||
13777 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | |||
13778 | } | |||
13779 | ||||
13780 | IdentifierInfo *Name = FD->getIdentifier(); | |||
13781 | if (!Name) | |||
13782 | return; | |||
13783 | if ((!getLangOpts().CPlusPlus && | |||
13784 | FD->getDeclContext()->isTranslationUnit()) || | |||
13785 | (isa<LinkageSpecDecl>(FD->getDeclContext()) && | |||
13786 | cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == | |||
13787 | LinkageSpecDecl::lang_c)) { | |||
13788 | // Okay: this could be a libc/libm/Objective-C function we know | |||
13789 | // about. | |||
13790 | } else | |||
13791 | return; | |||
13792 | ||||
13793 | if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { | |||
13794 | // FIXME: asprintf and vasprintf aren't C99 functions. Should they be | |||
13795 | // target-specific builtins, perhaps? | |||
13796 | if (!FD->hasAttr<FormatAttr>()) | |||
13797 | FD->addAttr(FormatAttr::CreateImplicit(Context, | |||
13798 | &Context.Idents.get("printf"), 2, | |||
13799 | Name->isStr("vasprintf") ? 0 : 3, | |||
13800 | FD->getLocation())); | |||
13801 | } | |||
13802 | ||||
13803 | if (Name->isStr("__CFStringMakeConstantString")) { | |||
13804 | // We already have a __builtin___CFStringMakeConstantString, | |||
13805 | // but builds that use -fno-constant-cfstrings don't go through that. | |||
13806 | if (!FD->hasAttr<FormatArgAttr>()) | |||
13807 | FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), | |||
13808 | FD->getLocation())); | |||
13809 | } | |||
13810 | } | |||
13811 | ||||
13812 | TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, | |||
13813 | TypeSourceInfo *TInfo) { | |||
13814 | assert(D.getIdentifier() && "Wrong callback for declspec without declarator")((D.getIdentifier() && "Wrong callback for declspec without declarator" ) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13814, __PRETTY_FUNCTION__)); | |||
13815 | assert(!T.isNull() && "GetTypeForDeclarator() returned null type")((!T.isNull() && "GetTypeForDeclarator() returned null type" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13815, __PRETTY_FUNCTION__)); | |||
13816 | ||||
13817 | if (!TInfo) { | |||
13818 | assert(D.isInvalidType() && "no declarator info for valid type")((D.isInvalidType() && "no declarator info for valid type" ) ? static_cast<void> (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13818, __PRETTY_FUNCTION__)); | |||
13819 | TInfo = Context.getTrivialTypeSourceInfo(T); | |||
13820 | } | |||
13821 | ||||
13822 | // Scope manipulation handled by caller. | |||
13823 | TypedefDecl *NewTD = | |||
13824 | TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), | |||
13825 | D.getIdentifierLoc(), D.getIdentifier(), TInfo); | |||
13826 | ||||
13827 | // Bail out immediately if we have an invalid declaration. | |||
13828 | if (D.isInvalidType()) { | |||
13829 | NewTD->setInvalidDecl(); | |||
13830 | return NewTD; | |||
13831 | } | |||
13832 | ||||
13833 | if (D.getDeclSpec().isModulePrivateSpecified()) { | |||
13834 | if (CurContext->isFunctionOrMethod()) | |||
13835 | Diag(NewTD->getLocation(), diag::err_module_private_local) | |||
13836 | << 2 << NewTD->getDeclName() | |||
13837 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | |||
13838 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | |||
13839 | else | |||
13840 | NewTD->setModulePrivate(); | |||
13841 | } | |||
13842 | ||||
13843 | // C++ [dcl.typedef]p8: | |||
13844 | // If the typedef declaration defines an unnamed class (or | |||
13845 | // enum), the first typedef-name declared by the declaration | |||
13846 | // to be that class type (or enum type) is used to denote the | |||
13847 | // class type (or enum type) for linkage purposes only. | |||
13848 | // We need to check whether the type was declared in the declaration. | |||
13849 | switch (D.getDeclSpec().getTypeSpecType()) { | |||
13850 | case TST_enum: | |||
13851 | case TST_struct: | |||
13852 | case TST_interface: | |||
13853 | case TST_union: | |||
13854 | case TST_class: { | |||
13855 | TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
13856 | setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); | |||
13857 | break; | |||
13858 | } | |||
13859 | ||||
13860 | default: | |||
13861 | break; | |||
13862 | } | |||
13863 | ||||
13864 | return NewTD; | |||
13865 | } | |||
13866 | ||||
13867 | /// Check that this is a valid underlying type for an enum declaration. | |||
13868 | bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { | |||
13869 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); | |||
13870 | QualType T = TI->getType(); | |||
13871 | ||||
13872 | if (T->isDependentType()) | |||
13873 | return false; | |||
13874 | ||||
13875 | if (const BuiltinType *BT = T->getAs<BuiltinType>()) | |||
13876 | if (BT->isInteger()) | |||
13877 | return false; | |||
13878 | ||||
13879 | Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; | |||
13880 | return true; | |||
13881 | } | |||
13882 | ||||
13883 | /// Check whether this is a valid redeclaration of a previous enumeration. | |||
13884 | /// \return true if the redeclaration was invalid. | |||
13885 | bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, | |||
13886 | QualType EnumUnderlyingTy, bool IsFixed, | |||
13887 | const EnumDecl *Prev) { | |||
13888 | if (IsScoped != Prev->isScoped()) { | |||
13889 | Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) | |||
13890 | << Prev->isScoped(); | |||
13891 | Diag(Prev->getLocation(), diag::note_previous_declaration); | |||
13892 | return true; | |||
13893 | } | |||
13894 | ||||
13895 | if (IsFixed && Prev->isFixed()) { | |||
13896 | if (!EnumUnderlyingTy->isDependentType() && | |||
13897 | !Prev->getIntegerType()->isDependentType() && | |||
13898 | !Context.hasSameUnqualifiedType(EnumUnderlyingTy, | |||
13899 | Prev->getIntegerType())) { | |||
13900 | // TODO: Highlight the underlying type of the redeclaration. | |||
13901 | Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) | |||
13902 | << EnumUnderlyingTy << Prev->getIntegerType(); | |||
13903 | Diag(Prev->getLocation(), diag::note_previous_declaration) | |||
13904 | << Prev->getIntegerTypeRange(); | |||
13905 | return true; | |||
13906 | } | |||
13907 | } else if (IsFixed != Prev->isFixed()) { | |||
13908 | Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) | |||
13909 | << Prev->isFixed(); | |||
13910 | Diag(Prev->getLocation(), diag::note_previous_declaration); | |||
13911 | return true; | |||
13912 | } | |||
13913 | ||||
13914 | return false; | |||
13915 | } | |||
13916 | ||||
13917 | /// Get diagnostic %select index for tag kind for | |||
13918 | /// redeclaration diagnostic message. | |||
13919 | /// WARNING: Indexes apply to particular diagnostics only! | |||
13920 | /// | |||
13921 | /// \returns diagnostic %select index. | |||
13922 | static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { | |||
13923 | switch (Tag) { | |||
13924 | case TTK_Struct: return 0; | |||
13925 | case TTK_Interface: return 1; | |||
13926 | case TTK_Class: return 2; | |||
13927 | default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13927); | |||
13928 | } | |||
13929 | } | |||
13930 | ||||
13931 | /// Determine if tag kind is a class-key compatible with | |||
13932 | /// class for redeclaration (class, struct, or __interface). | |||
13933 | /// | |||
13934 | /// \returns true iff the tag kind is compatible. | |||
13935 | static bool isClassCompatTagKind(TagTypeKind Tag) | |||
13936 | { | |||
13937 | return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; | |||
13938 | } | |||
13939 | ||||
13940 | Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, | |||
13941 | TagTypeKind TTK) { | |||
13942 | if (isa<TypedefDecl>(PrevDecl)) | |||
13943 | return NTK_Typedef; | |||
13944 | else if (isa<TypeAliasDecl>(PrevDecl)) | |||
13945 | return NTK_TypeAlias; | |||
13946 | else if (isa<ClassTemplateDecl>(PrevDecl)) | |||
13947 | return NTK_Template; | |||
13948 | else if (isa<TypeAliasTemplateDecl>(PrevDecl)) | |||
13949 | return NTK_TypeAliasTemplate; | |||
13950 | else if (isa<TemplateTemplateParmDecl>(PrevDecl)) | |||
13951 | return NTK_TemplateTemplateArgument; | |||
13952 | switch (TTK) { | |||
13953 | case TTK_Struct: | |||
13954 | case TTK_Interface: | |||
13955 | case TTK_Class: | |||
13956 | return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; | |||
13957 | case TTK_Union: | |||
13958 | return NTK_NonUnion; | |||
13959 | case TTK_Enum: | |||
13960 | return NTK_NonEnum; | |||
13961 | } | |||
13962 | llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 13962); | |||
13963 | } | |||
13964 | ||||
13965 | /// Determine whether a tag with a given kind is acceptable | |||
13966 | /// as a redeclaration of the given tag declaration. | |||
13967 | /// | |||
13968 | /// \returns true if the new tag kind is acceptable, false otherwise. | |||
13969 | bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, | |||
13970 | TagTypeKind NewTag, bool isDefinition, | |||
13971 | SourceLocation NewTagLoc, | |||
13972 | const IdentifierInfo *Name) { | |||
13973 | // C++ [dcl.type.elab]p3: | |||
13974 | // The class-key or enum keyword present in the | |||
13975 | // elaborated-type-specifier shall agree in kind with the | |||
13976 | // declaration to which the name in the elaborated-type-specifier | |||
13977 | // refers. This rule also applies to the form of | |||
13978 | // elaborated-type-specifier that declares a class-name or | |||
13979 | // friend class since it can be construed as referring to the | |||
13980 | // definition of the class. Thus, in any | |||
13981 | // elaborated-type-specifier, the enum keyword shall be used to | |||
13982 | // refer to an enumeration (7.2), the union class-key shall be | |||
13983 | // used to refer to a union (clause 9), and either the class or | |||
13984 | // struct class-key shall be used to refer to a class (clause 9) | |||
13985 | // declared using the class or struct class-key. | |||
13986 | TagTypeKind OldTag = Previous->getTagKind(); | |||
13987 | if (OldTag != NewTag && | |||
13988 | !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) | |||
13989 | return false; | |||
13990 | ||||
13991 | // Tags are compatible, but we might still want to warn on mismatched tags. | |||
13992 | // Non-class tags can't be mismatched at this point. | |||
13993 | if (!isClassCompatTagKind(NewTag)) | |||
13994 | return true; | |||
13995 | ||||
13996 | // Declarations for which -Wmismatched-tags is disabled are entirely ignored | |||
13997 | // by our warning analysis. We don't want to warn about mismatches with (eg) | |||
13998 | // declarations in system headers that are designed to be specialized, but if | |||
13999 | // a user asks us to warn, we should warn if their code contains mismatched | |||
14000 | // declarations. | |||
14001 | auto IsIgnoredLoc = [&](SourceLocation Loc) { | |||
14002 | return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, | |||
14003 | Loc); | |||
14004 | }; | |||
14005 | if (IsIgnoredLoc(NewTagLoc)) | |||
14006 | return true; | |||
14007 | ||||
14008 | auto IsIgnored = [&](const TagDecl *Tag) { | |||
14009 | return IsIgnoredLoc(Tag->getLocation()); | |||
14010 | }; | |||
14011 | while (IsIgnored(Previous)) { | |||
14012 | Previous = Previous->getPreviousDecl(); | |||
14013 | if (!Previous) | |||
14014 | return true; | |||
14015 | OldTag = Previous->getTagKind(); | |||
14016 | } | |||
14017 | ||||
14018 | bool isTemplate = false; | |||
14019 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) | |||
14020 | isTemplate = Record->getDescribedClassTemplate(); | |||
14021 | ||||
14022 | if (inTemplateInstantiation()) { | |||
14023 | if (OldTag != NewTag) { | |||
14024 | // In a template instantiation, do not offer fix-its for tag mismatches | |||
14025 | // since they usually mess up the template instead of fixing the problem. | |||
14026 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | |||
14027 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | |||
14028 | << getRedeclDiagFromTagKind(OldTag); | |||
14029 | // FIXME: Note previous location? | |||
14030 | } | |||
14031 | return true; | |||
14032 | } | |||
14033 | ||||
14034 | if (isDefinition) { | |||
14035 | // On definitions, check all previous tags and issue a fix-it for each | |||
14036 | // one that doesn't match the current tag. | |||
14037 | if (Previous->getDefinition()) { | |||
14038 | // Don't suggest fix-its for redefinitions. | |||
14039 | return true; | |||
14040 | } | |||
14041 | ||||
14042 | bool previousMismatch = false; | |||
14043 | for (const TagDecl *I : Previous->redecls()) { | |||
14044 | if (I->getTagKind() != NewTag) { | |||
14045 | // Ignore previous declarations for which the warning was disabled. | |||
14046 | if (IsIgnored(I)) | |||
14047 | continue; | |||
14048 | ||||
14049 | if (!previousMismatch) { | |||
14050 | previousMismatch = true; | |||
14051 | Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) | |||
14052 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | |||
14053 | << getRedeclDiagFromTagKind(I->getTagKind()); | |||
14054 | } | |||
14055 | Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) | |||
14056 | << getRedeclDiagFromTagKind(NewTag) | |||
14057 | << FixItHint::CreateReplacement(I->getInnerLocStart(), | |||
14058 | TypeWithKeyword::getTagTypeKindName(NewTag)); | |||
14059 | } | |||
14060 | } | |||
14061 | return true; | |||
14062 | } | |||
14063 | ||||
14064 | // Identify the prevailing tag kind: this is the kind of the definition (if | |||
14065 | // there is a non-ignored definition), or otherwise the kind of the prior | |||
14066 | // (non-ignored) declaration. | |||
14067 | const TagDecl *PrevDef = Previous->getDefinition(); | |||
14068 | if (PrevDef && IsIgnored(PrevDef)) | |||
14069 | PrevDef = nullptr; | |||
14070 | const TagDecl *Redecl = PrevDef ? PrevDef : Previous; | |||
14071 | if (Redecl->getTagKind() != NewTag) { | |||
14072 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | |||
14073 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | |||
14074 | << getRedeclDiagFromTagKind(OldTag); | |||
14075 | Diag(Redecl->getLocation(), diag::note_previous_use); | |||
14076 | ||||
14077 | // If there is a previous definition, suggest a fix-it. | |||
14078 | if (PrevDef) { | |||
14079 | Diag(NewTagLoc, diag::note_struct_class_suggestion) | |||
14080 | << getRedeclDiagFromTagKind(Redecl->getTagKind()) | |||
14081 | << FixItHint::CreateReplacement(SourceRange(NewTagLoc), | |||
14082 | TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); | |||
14083 | } | |||
14084 | } | |||
14085 | ||||
14086 | return true; | |||
14087 | } | |||
14088 | ||||
14089 | /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name | |||
14090 | /// from an outer enclosing namespace or file scope inside a friend declaration. | |||
14091 | /// This should provide the commented out code in the following snippet: | |||
14092 | /// namespace N { | |||
14093 | /// struct X; | |||
14094 | /// namespace M { | |||
14095 | /// struct Y { friend struct /*N::*/ X; }; | |||
14096 | /// } | |||
14097 | /// } | |||
14098 | static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, | |||
14099 | SourceLocation NameLoc) { | |||
14100 | // While the decl is in a namespace, do repeated lookup of that name and see | |||
14101 | // if we get the same namespace back. If we do not, continue until | |||
14102 | // translation unit scope, at which point we have a fully qualified NNS. | |||
14103 | SmallVector<IdentifierInfo *, 4> Namespaces; | |||
14104 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | |||
14105 | for (; !DC->isTranslationUnit(); DC = DC->getParent()) { | |||
14106 | // This tag should be declared in a namespace, which can only be enclosed by | |||
14107 | // other namespaces. Bail if there's an anonymous namespace in the chain. | |||
14108 | NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); | |||
14109 | if (!Namespace || Namespace->isAnonymousNamespace()) | |||
14110 | return FixItHint(); | |||
14111 | IdentifierInfo *II = Namespace->getIdentifier(); | |||
14112 | Namespaces.push_back(II); | |||
14113 | NamedDecl *Lookup = SemaRef.LookupSingleName( | |||
14114 | S, II, NameLoc, Sema::LookupNestedNameSpecifierName); | |||
14115 | if (Lookup == Namespace) | |||
14116 | break; | |||
14117 | } | |||
14118 | ||||
14119 | // Once we have all the namespaces, reverse them to go outermost first, and | |||
14120 | // build an NNS. | |||
14121 | SmallString<64> Insertion; | |||
14122 | llvm::raw_svector_ostream OS(Insertion); | |||
14123 | if (DC->isTranslationUnit()) | |||
14124 | OS << "::"; | |||
14125 | std::reverse(Namespaces.begin(), Namespaces.end()); | |||
14126 | for (auto *II : Namespaces) | |||
14127 | OS << II->getName() << "::"; | |||
14128 | return FixItHint::CreateInsertion(NameLoc, Insertion); | |||
14129 | } | |||
14130 | ||||
14131 | /// Determine whether a tag originally declared in context \p OldDC can | |||
14132 | /// be redeclared with an unqualified name in \p NewDC (assuming name lookup | |||
14133 | /// found a declaration in \p OldDC as a previous decl, perhaps through a | |||
14134 | /// using-declaration). | |||
14135 | static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, | |||
14136 | DeclContext *NewDC) { | |||
14137 | OldDC = OldDC->getRedeclContext(); | |||
14138 | NewDC = NewDC->getRedeclContext(); | |||
14139 | ||||
14140 | if (OldDC->Equals(NewDC)) | |||
14141 | return true; | |||
14142 | ||||
14143 | // In MSVC mode, we allow a redeclaration if the contexts are related (either | |||
14144 | // encloses the other). | |||
14145 | if (S.getLangOpts().MSVCCompat && | |||
14146 | (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) | |||
14147 | return true; | |||
14148 | ||||
14149 | return false; | |||
14150 | } | |||
14151 | ||||
14152 | /// This is invoked when we see 'struct foo' or 'struct {'. In the | |||
14153 | /// former case, Name will be non-null. In the later case, Name will be null. | |||
14154 | /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a | |||
14155 | /// reference/declaration/definition of a tag. | |||
14156 | /// | |||
14157 | /// \param IsTypeSpecifier \c true if this is a type-specifier (or | |||
14158 | /// trailing-type-specifier) other than one in an alias-declaration. | |||
14159 | /// | |||
14160 | /// \param SkipBody If non-null, will be set to indicate if the caller should | |||
14161 | /// skip the definition of this tag and treat it as if it were a declaration. | |||
14162 | Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, | |||
14163 | SourceLocation KWLoc, CXXScopeSpec &SS, | |||
14164 | IdentifierInfo *Name, SourceLocation NameLoc, | |||
14165 | const ParsedAttributesView &Attrs, AccessSpecifier AS, | |||
14166 | SourceLocation ModulePrivateLoc, | |||
14167 | MultiTemplateParamsArg TemplateParameterLists, | |||
14168 | bool &OwnedDecl, bool &IsDependent, | |||
14169 | SourceLocation ScopedEnumKWLoc, | |||
14170 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, | |||
14171 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, | |||
14172 | SkipBodyInfo *SkipBody) { | |||
14173 | // If this is not a definition, it must have a name. | |||
14174 | IdentifierInfo *OrigName = Name; | |||
14175 | assert((Name != nullptr || TUK == TUK_Definition) &&(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!" ) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 14176, __PRETTY_FUNCTION__)) | |||
14176 | "Nameless record must be a definition!")(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!" ) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 14176, __PRETTY_FUNCTION__)); | |||
14177 | assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)((TemplateParameterLists.size() == 0 || TUK != TUK_Reference) ? static_cast<void> (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 14177, __PRETTY_FUNCTION__)); | |||
14178 | ||||
14179 | OwnedDecl = false; | |||
14180 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); | |||
14181 | bool ScopedEnum = ScopedEnumKWLoc.isValid(); | |||
14182 | ||||
14183 | // FIXME: Check member specializations more carefully. | |||
14184 | bool isMemberSpecialization = false; | |||
14185 | bool Invalid = false; | |||
14186 | ||||
14187 | // We only need to do this matching if we have template parameters | |||
14188 | // or a scope specifier, which also conveniently avoids this work | |||
14189 | // for non-C++ cases. | |||
14190 | if (TemplateParameterLists.size() > 0 || | |||
14191 | (SS.isNotEmpty() && TUK != TUK_Reference)) { | |||
14192 | if (TemplateParameterList *TemplateParams = | |||
14193 | MatchTemplateParametersToScopeSpecifier( | |||
14194 | KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, | |||
14195 | TUK == TUK_Friend, isMemberSpecialization, Invalid)) { | |||
14196 | if (Kind == TTK_Enum) { | |||
14197 | Diag(KWLoc, diag::err_enum_template); | |||
14198 | return nullptr; | |||
14199 | } | |||
14200 | ||||
14201 | if (TemplateParams->size() > 0) { | |||
14202 | // This is a declaration or definition of a class template (which may | |||
14203 | // be a member of another template). | |||
14204 | ||||
14205 | if (Invalid) | |||
14206 | return nullptr; | |||
14207 | ||||
14208 | OwnedDecl = false; | |||
14209 | DeclResult Result = CheckClassTemplate( | |||
14210 | S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, | |||
14211 | AS, ModulePrivateLoc, | |||
14212 | /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, | |||
14213 | TemplateParameterLists.data(), SkipBody); | |||
14214 | return Result.get(); | |||
14215 | } else { | |||
14216 | // The "template<>" header is extraneous. | |||
14217 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) | |||
14218 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; | |||
14219 | isMemberSpecialization = true; | |||
14220 | } | |||
14221 | } | |||
14222 | } | |||
14223 | ||||
14224 | // Figure out the underlying type if this a enum declaration. We need to do | |||
14225 | // this early, because it's needed to detect if this is an incompatible | |||
14226 | // redeclaration. | |||
14227 | llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; | |||
14228 | bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; | |||
14229 | ||||
14230 | if (Kind == TTK_Enum) { | |||
14231 | if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { | |||
14232 | // No underlying type explicitly specified, or we failed to parse the | |||
14233 | // type, default to int. | |||
14234 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
14235 | } else if (UnderlyingType.get()) { | |||
14236 | // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an | |||
14237 | // integral type; any cv-qualification is ignored. | |||
14238 | TypeSourceInfo *TI = nullptr; | |||
14239 | GetTypeFromParser(UnderlyingType.get(), &TI); | |||
14240 | EnumUnderlying = TI; | |||
14241 | ||||
14242 | if (CheckEnumUnderlyingType(TI)) | |||
14243 | // Recover by falling back to int. | |||
14244 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
14245 | ||||
14246 | if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, | |||
14247 | UPPC_FixedUnderlyingType)) | |||
14248 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
14249 | ||||
14250 | } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
14251 | // For MSVC ABI compatibility, unfixed enums must use an underlying type | |||
14252 | // of 'int'. However, if this is an unfixed forward declaration, don't set | |||
14253 | // the underlying type unless the user enables -fms-compatibility. This | |||
14254 | // makes unfixed forward declared enums incomplete and is more conforming. | |||
14255 | if (TUK == TUK_Definition || getLangOpts().MSVCCompat) | |||
14256 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
14257 | } | |||
14258 | } | |||
14259 | ||||
14260 | DeclContext *SearchDC = CurContext; | |||
14261 | DeclContext *DC = CurContext; | |||
14262 | bool isStdBadAlloc = false; | |||
14263 | bool isStdAlignValT = false; | |||
14264 | ||||
14265 | RedeclarationKind Redecl = forRedeclarationInCurContext(); | |||
14266 | if (TUK == TUK_Friend || TUK == TUK_Reference) | |||
14267 | Redecl = NotForRedeclaration; | |||
14268 | ||||
14269 | /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C | |||
14270 | /// implemented asks for structural equivalence checking, the returned decl | |||
14271 | /// here is passed back to the parser, allowing the tag body to be parsed. | |||
14272 | auto createTagFromNewDecl = [&]() -> TagDecl * { | |||
14273 | assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")((!getLangOpts().CPlusPlus && "not meant for C++ usage" ) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 14273, __PRETTY_FUNCTION__)); | |||
14274 | // If there is an identifier, use the location of the identifier as the | |||
14275 | // location of the decl, otherwise use the location of the struct/union | |||
14276 | // keyword. | |||
14277 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | |||
14278 | TagDecl *New = nullptr; | |||
14279 | ||||
14280 | if (Kind == TTK_Enum) { | |||
14281 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, | |||
14282 | ScopedEnum, ScopedEnumUsesClassTag, IsFixed); | |||
14283 | // If this is an undefined enum, bail. | |||
14284 | if (TUK != TUK_Definition && !Invalid) | |||
14285 | return nullptr; | |||
14286 | if (EnumUnderlying) { | |||
14287 | EnumDecl *ED = cast<EnumDecl>(New); | |||
14288 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) | |||
14289 | ED->setIntegerTypeSourceInfo(TI); | |||
14290 | else | |||
14291 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); | |||
14292 | ED->setPromotionType(ED->getIntegerType()); | |||
14293 | } | |||
14294 | } else { // struct/union | |||
14295 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | |||
14296 | nullptr); | |||
14297 | } | |||
14298 | ||||
14299 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | |||
14300 | // Add alignment attributes if necessary; these attributes are checked | |||
14301 | // when the ASTContext lays out the structure. | |||
14302 | // | |||
14303 | // It is important for implementing the correct semantics that this | |||
14304 | // happen here (in ActOnTag). The #pragma pack stack is | |||
14305 | // maintained as a result of parser callbacks which can occur at | |||
14306 | // many points during the parsing of a struct declaration (because | |||
14307 | // the #pragma tokens are effectively skipped over during the | |||
14308 | // parsing of the struct). | |||
14309 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | |||
14310 | AddAlignmentAttributesForRecord(RD); | |||
14311 | AddMsStructLayoutForRecord(RD); | |||
14312 | } | |||
14313 | } | |||
14314 | New->setLexicalDeclContext(CurContext); | |||
14315 | return New; | |||
14316 | }; | |||
14317 | ||||
14318 | LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); | |||
14319 | if (Name && SS.isNotEmpty()) { | |||
14320 | // We have a nested-name tag ('struct foo::bar'). | |||
14321 | ||||
14322 | // Check for invalid 'foo::'. | |||
14323 | if (SS.isInvalid()) { | |||
14324 | Name = nullptr; | |||
14325 | goto CreateNewDecl; | |||
14326 | } | |||
14327 | ||||
14328 | // If this is a friend or a reference to a class in a dependent | |||
14329 | // context, don't try to make a decl for it. | |||
14330 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | |||
14331 | DC = computeDeclContext(SS, false); | |||
14332 | if (!DC) { | |||
14333 | IsDependent = true; | |||
14334 | return nullptr; | |||
14335 | } | |||
14336 | } else { | |||
14337 | DC = computeDeclContext(SS, true); | |||
14338 | if (!DC) { | |||
14339 | Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) | |||
14340 | << SS.getRange(); | |||
14341 | return nullptr; | |||
14342 | } | |||
14343 | } | |||
14344 | ||||
14345 | if (RequireCompleteDeclContext(SS, DC)) | |||
14346 | return nullptr; | |||
14347 | ||||
14348 | SearchDC = DC; | |||
14349 | // Look-up name inside 'foo::'. | |||
14350 | LookupQualifiedName(Previous, DC); | |||
14351 | ||||
14352 | if (Previous.isAmbiguous()) | |||
14353 | return nullptr; | |||
14354 | ||||
14355 | if (Previous.empty()) { | |||
14356 | // Name lookup did not find anything. However, if the | |||
14357 | // nested-name-specifier refers to the current instantiation, | |||
14358 | // and that current instantiation has any dependent base | |||
14359 | // classes, we might find something at instantiation time: treat | |||
14360 | // this as a dependent elaborated-type-specifier. | |||
14361 | // But this only makes any sense for reference-like lookups. | |||
14362 | if (Previous.wasNotFoundInCurrentInstantiation() && | |||
14363 | (TUK == TUK_Reference || TUK == TUK_Friend)) { | |||
14364 | IsDependent = true; | |||
14365 | return nullptr; | |||
14366 | } | |||
14367 | ||||
14368 | // A tag 'foo::bar' must already exist. | |||
14369 | Diag(NameLoc, diag::err_not_tag_in_scope) | |||
14370 | << Kind << Name << DC << SS.getRange(); | |||
14371 | Name = nullptr; | |||
14372 | Invalid = true; | |||
14373 | goto CreateNewDecl; | |||
14374 | } | |||
14375 | } else if (Name) { | |||
14376 | // C++14 [class.mem]p14: | |||
14377 | // If T is the name of a class, then each of the following shall have a | |||
14378 | // name different from T: | |||
14379 | // -- every member of class T that is itself a type | |||
14380 | if (TUK != TUK_Reference && TUK != TUK_Friend && | |||
14381 | DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) | |||
14382 | return nullptr; | |||
14383 | ||||
14384 | // If this is a named struct, check to see if there was a previous forward | |||
14385 | // declaration or definition. | |||
14386 | // FIXME: We're looking into outer scopes here, even when we | |||
14387 | // shouldn't be. Doing so can result in ambiguities that we | |||
14388 | // shouldn't be diagnosing. | |||
14389 | LookupName(Previous, S); | |||
14390 | ||||
14391 | // When declaring or defining a tag, ignore ambiguities introduced | |||
14392 | // by types using'ed into this scope. | |||
14393 | if (Previous.isAmbiguous() && | |||
14394 | (TUK == TUK_Definition || TUK == TUK_Declaration)) { | |||
14395 | LookupResult::Filter F = Previous.makeFilter(); | |||
14396 | while (F.hasNext()) { | |||
14397 | NamedDecl *ND = F.next(); | |||
14398 | if (!ND->getDeclContext()->getRedeclContext()->Equals( | |||
14399 | SearchDC->getRedeclContext())) | |||
14400 | F.erase(); | |||
14401 | } | |||
14402 | F.done(); | |||
14403 | } | |||
14404 | ||||
14405 | // C++11 [namespace.memdef]p3: | |||
14406 | // If the name in a friend declaration is neither qualified nor | |||
14407 | // a template-id and the declaration is a function or an | |||
14408 | // elaborated-type-specifier, the lookup to determine whether | |||
14409 | // the entity has been previously declared shall not consider | |||
14410 | // any scopes outside the innermost enclosing namespace. | |||
14411 | // | |||
14412 | // MSVC doesn't implement the above rule for types, so a friend tag | |||
14413 | // declaration may be a redeclaration of a type declared in an enclosing | |||
14414 | // scope. They do implement this rule for friend functions. | |||
14415 | // | |||
14416 | // Does it matter that this should be by scope instead of by | |||
14417 | // semantic context? | |||
14418 | if (!Previous.empty() && TUK == TUK_Friend) { | |||
14419 | DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); | |||
14420 | LookupResult::Filter F = Previous.makeFilter(); | |||
14421 | bool FriendSawTagOutsideEnclosingNamespace = false; | |||
14422 | while (F.hasNext()) { | |||
14423 | NamedDecl *ND = F.next(); | |||
14424 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | |||
14425 | if (DC->isFileContext() && | |||
14426 | !EnclosingNS->Encloses(ND->getDeclContext())) { | |||
14427 | if (getLangOpts().MSVCCompat) | |||
14428 | FriendSawTagOutsideEnclosingNamespace = true; | |||
14429 | else | |||
14430 | F.erase(); | |||
14431 | } | |||
14432 | } | |||
14433 | F.done(); | |||
14434 | ||||
14435 | // Diagnose this MSVC extension in the easy case where lookup would have | |||
14436 | // unambiguously found something outside the enclosing namespace. | |||
14437 | if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { | |||
14438 | NamedDecl *ND = Previous.getFoundDecl(); | |||
14439 | Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) | |||
14440 | << createFriendTagNNSFixIt(*this, ND, S, NameLoc); | |||
14441 | } | |||
14442 | } | |||
14443 | ||||
14444 | // Note: there used to be some attempt at recovery here. | |||
14445 | if (Previous.isAmbiguous()) | |||
14446 | return nullptr; | |||
14447 | ||||
14448 | if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { | |||
14449 | // FIXME: This makes sure that we ignore the contexts associated | |||
14450 | // with C structs, unions, and enums when looking for a matching | |||
14451 | // tag declaration or definition. See the similar lookup tweak | |||
14452 | // in Sema::LookupName; is there a better way to deal with this? | |||
14453 | while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) | |||
14454 | SearchDC = SearchDC->getParent(); | |||
14455 | } | |||
14456 | } | |||
14457 | ||||
14458 | if (Previous.isSingleResult() && | |||
14459 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
14460 | // Maybe we will complain about the shadowed template parameter. | |||
14461 | DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); | |||
14462 | // Just pretend that we didn't see the previous declaration. | |||
14463 | Previous.clear(); | |||
14464 | } | |||
14465 | ||||
14466 | if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && | |||
14467 | DC->Equals(getStdNamespace())) { | |||
14468 | if (Name->isStr("bad_alloc")) { | |||
14469 | // This is a declaration of or a reference to "std::bad_alloc". | |||
14470 | isStdBadAlloc = true; | |||
14471 | ||||
14472 | // If std::bad_alloc has been implicitly declared (but made invisible to | |||
14473 | // name lookup), fill in this implicit declaration as the previous | |||
14474 | // declaration, so that the declarations get chained appropriately. | |||
14475 | if (Previous.empty() && StdBadAlloc) | |||
14476 | Previous.addDecl(getStdBadAlloc()); | |||
14477 | } else if (Name->isStr("align_val_t")) { | |||
14478 | isStdAlignValT = true; | |||
14479 | if (Previous.empty() && StdAlignValT) | |||
14480 | Previous.addDecl(getStdAlignValT()); | |||
14481 | } | |||
14482 | } | |||
14483 | ||||
14484 | // If we didn't find a previous declaration, and this is a reference | |||
14485 | // (or friend reference), move to the correct scope. In C++, we | |||
14486 | // also need to do a redeclaration lookup there, just in case | |||
14487 | // there's a shadow friend decl. | |||
14488 | if (Name && Previous.empty() && | |||
14489 | (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { | |||
14490 | if (Invalid) goto CreateNewDecl; | |||
14491 | assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 14491, __PRETTY_FUNCTION__)); | |||
14492 | ||||
14493 | if (TUK == TUK_Reference || IsTemplateParamOrArg) { | |||
14494 | // C++ [basic.scope.pdecl]p5: | |||
14495 | // -- for an elaborated-type-specifier of the form | |||
14496 | // | |||
14497 | // class-key identifier | |||
14498 | // | |||
14499 | // if the elaborated-type-specifier is used in the | |||
14500 | // decl-specifier-seq or parameter-declaration-clause of a | |||
14501 | // function defined in namespace scope, the identifier is | |||
14502 | // declared as a class-name in the namespace that contains | |||
14503 | // the declaration; otherwise, except as a friend | |||
14504 | // declaration, the identifier is declared in the smallest | |||
14505 | // non-class, non-function-prototype scope that contains the | |||
14506 | // declaration. | |||
14507 | // | |||
14508 | // C99 6.7.2.3p8 has a similar (but not identical!) provision for | |||
14509 | // C structs and unions. | |||
14510 | // | |||
14511 | // It is an error in C++ to declare (rather than define) an enum | |||
14512 | // type, including via an elaborated type specifier. We'll | |||
14513 | // diagnose that later; for now, declare the enum in the same | |||
14514 | // scope as we would have picked for any other tag type. | |||
14515 | // | |||
14516 | // GNU C also supports this behavior as part of its incomplete | |||
14517 | // enum types extension, while GNU C++ does not. | |||
14518 | // | |||
14519 | // Find the context where we'll be declaring the tag. | |||
14520 | // FIXME: We would like to maintain the current DeclContext as the | |||
14521 | // lexical context, | |||
14522 | SearchDC = getTagInjectionContext(SearchDC); | |||
14523 | ||||
14524 | // Find the scope where we'll be declaring the tag. | |||
14525 | S = getTagInjectionScope(S, getLangOpts()); | |||
14526 | } else { | |||
14527 | assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail ("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 14527, __PRETTY_FUNCTION__)); | |||
14528 | // C++ [namespace.memdef]p3: | |||
14529 | // If a friend declaration in a non-local class first declares a | |||
14530 | // class or function, the friend class or function is a member of | |||
14531 | // the innermost enclosing namespace. | |||
14532 | SearchDC = SearchDC->getEnclosingNamespaceContext(); | |||
14533 | } | |||
14534 | ||||
14535 | // In C++, we need to do a redeclaration lookup to properly | |||
14536 | // diagnose some problems. | |||
14537 | // FIXME: redeclaration lookup is also used (with and without C++) to find a | |||
14538 | // hidden declaration so that we don't get ambiguity errors when using a | |||
14539 | // type declared by an elaborated-type-specifier. In C that is not correct | |||
14540 | // and we should instead merge compatible types found by lookup. | |||
14541 | if (getLangOpts().CPlusPlus) { | |||
14542 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | |||
14543 | LookupQualifiedName(Previous, SearchDC); | |||
14544 | } else { | |||
14545 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | |||
14546 | LookupName(Previous, S); | |||
14547 | } | |||
14548 | } | |||
14549 | ||||
14550 | // If we have a known previous declaration to use, then use it. | |||
14551 | if (Previous.empty() && SkipBody && SkipBody->Previous) | |||
14552 | Previous.addDecl(SkipBody->Previous); | |||
14553 | ||||
14554 | if (!Previous.empty()) { | |||
14555 | NamedDecl *PrevDecl = Previous.getFoundDecl(); | |||
14556 | NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); | |||
14557 | ||||
14558 | // It's okay to have a tag decl in the same scope as a typedef | |||
14559 | // which hides a tag decl in the same scope. Finding this | |||
14560 | // insanity with a redeclaration lookup can only actually happen | |||
14561 | // in C++. | |||
14562 | // | |||
14563 | // This is also okay for elaborated-type-specifiers, which is | |||
14564 | // technically forbidden by the current standard but which is | |||
14565 | // okay according to the likely resolution of an open issue; | |||
14566 | // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 | |||
14567 | if (getLangOpts().CPlusPlus) { | |||
14568 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { | |||
14569 | if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { | |||
14570 | TagDecl *Tag = TT->getDecl(); | |||
14571 | if (Tag->getDeclName() == Name && | |||
14572 | Tag->getDeclContext()->getRedeclContext() | |||
14573 | ->Equals(TD->getDeclContext()->getRedeclContext())) { | |||
14574 | PrevDecl = Tag; | |||
14575 | Previous.clear(); | |||
14576 | Previous.addDecl(Tag); | |||
14577 | Previous.resolveKind(); | |||
14578 | } | |||
14579 | } | |||
14580 | } | |||
14581 | } | |||
14582 | ||||
14583 | // If this is a redeclaration of a using shadow declaration, it must | |||
14584 | // declare a tag in the same context. In MSVC mode, we allow a | |||
14585 | // redefinition if either context is within the other. | |||
14586 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { | |||
14587 | auto *OldTag = dyn_cast<TagDecl>(PrevDecl); | |||
14588 | if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && | |||
14589 | isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && | |||
14590 | !(OldTag && isAcceptableTagRedeclContext( | |||
14591 | *this, OldTag->getDeclContext(), SearchDC))) { | |||
14592 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); | |||
14593 | Diag(Shadow->getTargetDecl()->getLocation(), | |||
14594 | diag::note_using_decl_target); | |||
14595 | Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) | |||
14596 | << 0; | |||
14597 | // Recover by ignoring the old declaration. | |||
14598 | Previous.clear(); | |||
14599 | goto CreateNewDecl; | |||
14600 | } | |||
14601 | } | |||
14602 | ||||
14603 | if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { | |||
14604 | // If this is a use of a previous tag, or if the tag is already declared | |||
14605 | // in the same scope (so that the definition/declaration completes or | |||
14606 | // rementions the tag), reuse the decl. | |||
14607 | if (TUK == TUK_Reference || TUK == TUK_Friend || | |||
14608 | isDeclInScope(DirectPrevDecl, SearchDC, S, | |||
14609 | SS.isNotEmpty() || isMemberSpecialization)) { | |||
14610 | // Make sure that this wasn't declared as an enum and now used as a | |||
14611 | // struct or something similar. | |||
14612 | if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, | |||
14613 | TUK == TUK_Definition, KWLoc, | |||
14614 | Name)) { | |||
14615 | bool SafeToContinue | |||
14616 | = (PrevTagDecl->getTagKind() != TTK_Enum && | |||
14617 | Kind != TTK_Enum); | |||
14618 | if (SafeToContinue) | |||
14619 | Diag(KWLoc, diag::err_use_with_wrong_tag) | |||
14620 | << Name | |||
14621 | << FixItHint::CreateReplacement(SourceRange(KWLoc), | |||
14622 | PrevTagDecl->getKindName()); | |||
14623 | else | |||
14624 | Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; | |||
14625 | Diag(PrevTagDecl->getLocation(), diag::note_previous_use); | |||
14626 | ||||
14627 | if (SafeToContinue) | |||
14628 | Kind = PrevTagDecl->getTagKind(); | |||
14629 | else { | |||
14630 | // Recover by making this an anonymous redefinition. | |||
14631 | Name = nullptr; | |||
14632 | Previous.clear(); | |||
14633 | Invalid = true; | |||
14634 | } | |||
14635 | } | |||
14636 | ||||
14637 | if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { | |||
14638 | const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); | |||
14639 | ||||
14640 | // If this is an elaborated-type-specifier for a scoped enumeration, | |||
14641 | // the 'class' keyword is not necessary and not permitted. | |||
14642 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | |||
14643 | if (ScopedEnum) | |||
14644 | Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) | |||
14645 | << PrevEnum->isScoped() | |||
14646 | << FixItHint::CreateRemoval(ScopedEnumKWLoc); | |||
14647 | return PrevTagDecl; | |||
14648 | } | |||
14649 | ||||
14650 | QualType EnumUnderlyingTy; | |||
14651 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | |||
14652 | EnumUnderlyingTy = TI->getType().getUnqualifiedType(); | |||
14653 | else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) | |||
14654 | EnumUnderlyingTy = QualType(T, 0); | |||
14655 | ||||
14656 | // All conflicts with previous declarations are recovered by | |||
14657 | // returning the previous declaration, unless this is a definition, | |||
14658 | // in which case we want the caller to bail out. | |||
14659 | if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, | |||
14660 | ScopedEnum, EnumUnderlyingTy, | |||
14661 | IsFixed, PrevEnum)) | |||
14662 | return TUK == TUK_Declaration ? PrevTagDecl : nullptr; | |||
14663 | } | |||
14664 | ||||
14665 | // C++11 [class.mem]p1: | |||
14666 | // A member shall not be declared twice in the member-specification, | |||
14667 | // except that a nested class or member class template can be declared | |||
14668 | // and then later defined. | |||
14669 | if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && | |||
14670 | S->isDeclScope(PrevDecl)) { | |||
14671 | Diag(NameLoc, diag::ext_member_redeclared); | |||
14672 | Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); | |||
14673 | } | |||
14674 | ||||
14675 | if (!Invalid) { | |||
14676 | // If this is a use, just return the declaration we found, unless | |||
14677 | // we have attributes. | |||
14678 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | |||
14679 | if (!Attrs.empty()) { | |||
14680 | // FIXME: Diagnose these attributes. For now, we create a new | |||
14681 | // declaration to hold them. | |||
14682 | } else if (TUK == TUK_Reference && | |||
14683 | (PrevTagDecl->getFriendObjectKind() == | |||
14684 | Decl::FOK_Undeclared || | |||
14685 | PrevDecl->getOwningModule() != getCurrentModule()) && | |||
14686 | SS.isEmpty()) { | |||
14687 | // This declaration is a reference to an existing entity, but | |||
14688 | // has different visibility from that entity: it either makes | |||
14689 | // a friend visible or it makes a type visible in a new module. | |||
14690 | // In either case, create a new declaration. We only do this if | |||
14691 | // the declaration would have meant the same thing if no prior | |||
14692 | // declaration were found, that is, if it was found in the same | |||
14693 | // scope where we would have injected a declaration. | |||
14694 | if (!getTagInjectionContext(CurContext)->getRedeclContext() | |||
14695 | ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) | |||
14696 | return PrevTagDecl; | |||
14697 | // This is in the injected scope, create a new declaration in | |||
14698 | // that scope. | |||
14699 | S = getTagInjectionScope(S, getLangOpts()); | |||
14700 | } else { | |||
14701 | return PrevTagDecl; | |||
14702 | } | |||
14703 | } | |||
14704 | ||||
14705 | // Diagnose attempts to redefine a tag. | |||
14706 | if (TUK == TUK_Definition) { | |||
14707 | if (NamedDecl *Def = PrevTagDecl->getDefinition()) { | |||
14708 | // If we're defining a specialization and the previous definition | |||
14709 | // is from an implicit instantiation, don't emit an error | |||
14710 | // here; we'll catch this in the general case below. | |||
14711 | bool IsExplicitSpecializationAfterInstantiation = false; | |||
14712 | if (isMemberSpecialization) { | |||
14713 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) | |||
14714 | IsExplicitSpecializationAfterInstantiation = | |||
14715 | RD->getTemplateSpecializationKind() != | |||
14716 | TSK_ExplicitSpecialization; | |||
14717 | else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) | |||
14718 | IsExplicitSpecializationAfterInstantiation = | |||
14719 | ED->getTemplateSpecializationKind() != | |||
14720 | TSK_ExplicitSpecialization; | |||
14721 | } | |||
14722 | ||||
14723 | // Note that clang allows ODR-like semantics for ObjC/C, i.e., do | |||
14724 | // not keep more that one definition around (merge them). However, | |||
14725 | // ensure the decl passes the structural compatibility check in | |||
14726 | // C11 6.2.7/1 (or 6.1.2.6/1 in C89). | |||
14727 | NamedDecl *Hidden = nullptr; | |||
14728 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { | |||
14729 | // There is a definition of this tag, but it is not visible. We | |||
14730 | // explicitly make use of C++'s one definition rule here, and | |||
14731 | // assume that this definition is identical to the hidden one | |||
14732 | // we already have. Make the existing definition visible and | |||
14733 | // use it in place of this one. | |||
14734 | if (!getLangOpts().CPlusPlus) { | |||
14735 | // Postpone making the old definition visible until after we | |||
14736 | // complete parsing the new one and do the structural | |||
14737 | // comparison. | |||
14738 | SkipBody->CheckSameAsPrevious = true; | |||
14739 | SkipBody->New = createTagFromNewDecl(); | |||
14740 | SkipBody->Previous = Def; | |||
14741 | return Def; | |||
14742 | } else { | |||
14743 | SkipBody->ShouldSkip = true; | |||
14744 | SkipBody->Previous = Def; | |||
14745 | makeMergedDefinitionVisible(Hidden); | |||
14746 | // Carry on and handle it like a normal definition. We'll | |||
14747 | // skip starting the definitiion later. | |||
14748 | } | |||
14749 | } else if (!IsExplicitSpecializationAfterInstantiation) { | |||
14750 | // A redeclaration in function prototype scope in C isn't | |||
14751 | // visible elsewhere, so merely issue a warning. | |||
14752 | if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) | |||
14753 | Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; | |||
14754 | else | |||
14755 | Diag(NameLoc, diag::err_redefinition) << Name; | |||
14756 | notePreviousDefinition(Def, | |||
14757 | NameLoc.isValid() ? NameLoc : KWLoc); | |||
14758 | // If this is a redefinition, recover by making this | |||
14759 | // struct be anonymous, which will make any later | |||
14760 | // references get the previous definition. | |||
14761 | Name = nullptr; | |||
14762 | Previous.clear(); | |||
14763 | Invalid = true; | |||
14764 | } | |||
14765 | } else { | |||
14766 | // If the type is currently being defined, complain | |||
14767 | // about a nested redefinition. | |||
14768 | auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); | |||
14769 | if (TD->isBeingDefined()) { | |||
14770 | Diag(NameLoc, diag::err_nested_redefinition) << Name; | |||
14771 | Diag(PrevTagDecl->getLocation(), | |||
14772 | diag::note_previous_definition); | |||
14773 | Name = nullptr; | |||
14774 | Previous.clear(); | |||
14775 | Invalid = true; | |||
14776 | } | |||
14777 | } | |||
14778 | ||||
14779 | // Okay, this is definition of a previously declared or referenced | |||
14780 | // tag. We're going to create a new Decl for it. | |||
14781 | } | |||
14782 | ||||
14783 | // Okay, we're going to make a redeclaration. If this is some kind | |||
14784 | // of reference, make sure we build the redeclaration in the same DC | |||
14785 | // as the original, and ignore the current access specifier. | |||
14786 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | |||
14787 | SearchDC = PrevTagDecl->getDeclContext(); | |||
14788 | AS = AS_none; | |||
14789 | } | |||
14790 | } | |||
14791 | // If we get here we have (another) forward declaration or we | |||
14792 | // have a definition. Just create a new decl. | |||
14793 | ||||
14794 | } else { | |||
14795 | // If we get here, this is a definition of a new tag type in a nested | |||
14796 | // scope, e.g. "struct foo; void bar() { struct foo; }", just create a | |||
14797 | // new decl/type. We set PrevDecl to NULL so that the entities | |||
14798 | // have distinct types. | |||
14799 | Previous.clear(); | |||
14800 | } | |||
14801 | // If we get here, we're going to create a new Decl. If PrevDecl | |||
14802 | // is non-NULL, it's a definition of the tag declared by | |||
14803 | // PrevDecl. If it's NULL, we have a new definition. | |||
14804 | ||||
14805 | // Otherwise, PrevDecl is not a tag, but was found with tag | |||
14806 | // lookup. This is only actually possible in C++, where a few | |||
14807 | // things like templates still live in the tag namespace. | |||
14808 | } else { | |||
14809 | // Use a better diagnostic if an elaborated-type-specifier | |||
14810 | // found the wrong kind of type on the first | |||
14811 | // (non-redeclaration) lookup. | |||
14812 | if ((TUK == TUK_Reference || TUK == TUK_Friend) && | |||
14813 | !Previous.isForRedeclaration()) { | |||
14814 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | |||
14815 | Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK | |||
14816 | << Kind; | |||
14817 | Diag(PrevDecl->getLocation(), diag::note_declared_at); | |||
14818 | Invalid = true; | |||
14819 | ||||
14820 | // Otherwise, only diagnose if the declaration is in scope. | |||
14821 | } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, | |||
14822 | SS.isNotEmpty() || isMemberSpecialization)) { | |||
14823 | // do nothing | |||
14824 | ||||
14825 | // Diagnose implicit declarations introduced by elaborated types. | |||
14826 | } else if (TUK == TUK_Reference || TUK == TUK_Friend) { | |||
14827 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | |||
14828 | Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; | |||
14829 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | |||
14830 | Invalid = true; | |||
14831 | ||||
14832 | // Otherwise it's a declaration. Call out a particularly common | |||
14833 | // case here. | |||
14834 | } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { | |||
14835 | unsigned Kind = 0; | |||
14836 | if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; | |||
14837 | Diag(NameLoc, diag::err_tag_definition_of_typedef) | |||
14838 | << Name << Kind << TND->getUnderlyingType(); | |||
14839 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | |||
14840 | Invalid = true; | |||
14841 | ||||
14842 | // Otherwise, diagnose. | |||
14843 | } else { | |||
14844 | // The tag name clashes with something else in the target scope, | |||
14845 | // issue an error and recover by making this tag be anonymous. | |||
14846 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; | |||
14847 | notePreviousDefinition(PrevDecl, NameLoc); | |||
14848 | Name = nullptr; | |||
14849 | Invalid = true; | |||
14850 | } | |||
14851 | ||||
14852 | // The existing declaration isn't relevant to us; we're in a | |||
14853 | // new scope, so clear out the previous declaration. | |||
14854 | Previous.clear(); | |||
14855 | } | |||
14856 | } | |||
14857 | ||||
14858 | CreateNewDecl: | |||
14859 | ||||
14860 | TagDecl *PrevDecl = nullptr; | |||
14861 | if (Previous.isSingleResult()) | |||
14862 | PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); | |||
14863 | ||||
14864 | // If there is an identifier, use the location of the identifier as the | |||
14865 | // location of the decl, otherwise use the location of the struct/union | |||
14866 | // keyword. | |||
14867 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | |||
14868 | ||||
14869 | // Otherwise, create a new declaration. If there is a previous | |||
14870 | // declaration of the same entity, the two will be linked via | |||
14871 | // PrevDecl. | |||
14872 | TagDecl *New; | |||
14873 | ||||
14874 | if (Kind == TTK_Enum) { | |||
14875 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | |||
14876 | // enum X { A, B, C } D; D should chain to X. | |||
14877 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, | |||
14878 | cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, | |||
14879 | ScopedEnumUsesClassTag, IsFixed); | |||
14880 | ||||
14881 | if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) | |||
14882 | StdAlignValT = cast<EnumDecl>(New); | |||
14883 | ||||
14884 | // If this is an undefined enum, warn. | |||
14885 | if (TUK != TUK_Definition && !Invalid) { | |||
14886 | TagDecl *Def; | |||
14887 | if (IsFixed && cast<EnumDecl>(New)->isFixed()) { | |||
14888 | // C++0x: 7.2p2: opaque-enum-declaration. | |||
14889 | // Conflicts are diagnosed above. Do nothing. | |||
14890 | } | |||
14891 | else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { | |||
14892 | Diag(Loc, diag::ext_forward_ref_enum_def) | |||
14893 | << New; | |||
14894 | Diag(Def->getLocation(), diag::note_previous_definition); | |||
14895 | } else { | |||
14896 | unsigned DiagID = diag::ext_forward_ref_enum; | |||
14897 | if (getLangOpts().MSVCCompat) | |||
14898 | DiagID = diag::ext_ms_forward_ref_enum; | |||
14899 | else if (getLangOpts().CPlusPlus) | |||
14900 | DiagID = diag::err_forward_ref_enum; | |||
14901 | Diag(Loc, DiagID); | |||
14902 | } | |||
14903 | } | |||
14904 | ||||
14905 | if (EnumUnderlying) { | |||
14906 | EnumDecl *ED = cast<EnumDecl>(New); | |||
14907 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | |||
14908 | ED->setIntegerTypeSourceInfo(TI); | |||
14909 | else | |||
14910 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); | |||
14911 | ED->setPromotionType(ED->getIntegerType()); | |||
14912 | assert(ED->isComplete() && "enum with type should be complete")((ED->isComplete() && "enum with type should be complete" ) ? static_cast<void> (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 14912, __PRETTY_FUNCTION__)); | |||
14913 | } | |||
14914 | } else { | |||
14915 | // struct/union/class | |||
14916 | ||||
14917 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | |||
14918 | // struct X { int A; } D; D should chain to X. | |||
14919 | if (getLangOpts().CPlusPlus) { | |||
14920 | // FIXME: Look for a way to use RecordDecl for simple structs. | |||
14921 | New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | |||
14922 | cast_or_null<CXXRecordDecl>(PrevDecl)); | |||
14923 | ||||
14924 | if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) | |||
14925 | StdBadAlloc = cast<CXXRecordDecl>(New); | |||
14926 | } else | |||
14927 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | |||
14928 | cast_or_null<RecordDecl>(PrevDecl)); | |||
14929 | } | |||
14930 | ||||
14931 | // C++11 [dcl.type]p3: | |||
14932 | // A type-specifier-seq shall not define a class or enumeration [...]. | |||
14933 | if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && | |||
14934 | TUK == TUK_Definition) { | |||
14935 | Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) | |||
14936 | << Context.getTagDeclType(New); | |||
14937 | Invalid = true; | |||
14938 | } | |||
14939 | ||||
14940 | if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && | |||
14941 | DC->getDeclKind() == Decl::Enum) { | |||
14942 | Diag(New->getLocation(), diag::err_type_defined_in_enum) | |||
14943 | << Context.getTagDeclType(New); | |||
14944 | Invalid = true; | |||
14945 | } | |||
14946 | ||||
14947 | // Maybe add qualifier info. | |||
14948 | if (SS.isNotEmpty()) { | |||
14949 | if (SS.isSet()) { | |||
14950 | // If this is either a declaration or a definition, check the | |||
14951 | // nested-name-specifier against the current context. | |||
14952 | if ((TUK == TUK_Definition || TUK == TUK_Declaration) && | |||
14953 | diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, | |||
14954 | isMemberSpecialization)) | |||
14955 | Invalid = true; | |||
14956 | ||||
14957 | New->setQualifierInfo(SS.getWithLocInContext(Context)); | |||
14958 | if (TemplateParameterLists.size() > 0) { | |||
14959 | New->setTemplateParameterListsInfo(Context, TemplateParameterLists); | |||
14960 | } | |||
14961 | } | |||
14962 | else | |||
14963 | Invalid = true; | |||
14964 | } | |||
14965 | ||||
14966 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | |||
14967 | // Add alignment attributes if necessary; these attributes are checked when | |||
14968 | // the ASTContext lays out the structure. | |||
14969 | // | |||
14970 | // It is important for implementing the correct semantics that this | |||
14971 | // happen here (in ActOnTag). The #pragma pack stack is | |||
14972 | // maintained as a result of parser callbacks which can occur at | |||
14973 | // many points during the parsing of a struct declaration (because | |||
14974 | // the #pragma tokens are effectively skipped over during the | |||
14975 | // parsing of the struct). | |||
14976 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | |||
14977 | AddAlignmentAttributesForRecord(RD); | |||
14978 | AddMsStructLayoutForRecord(RD); | |||
14979 | } | |||
14980 | } | |||
14981 | ||||
14982 | if (ModulePrivateLoc.isValid()) { | |||
14983 | if (isMemberSpecialization) | |||
14984 | Diag(New->getLocation(), diag::err_module_private_specialization) | |||
14985 | << 2 | |||
14986 | << FixItHint::CreateRemoval(ModulePrivateLoc); | |||
14987 | // __module_private__ does not apply to local classes. However, we only | |||
14988 | // diagnose this as an error when the declaration specifiers are | |||
14989 | // freestanding. Here, we just ignore the __module_private__. | |||
14990 | else if (!SearchDC->isFunctionOrMethod()) | |||
14991 | New->setModulePrivate(); | |||
14992 | } | |||
14993 | ||||
14994 | // If this is a specialization of a member class (of a class template), | |||
14995 | // check the specialization. | |||
14996 | if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) | |||
14997 | Invalid = true; | |||
14998 | ||||
14999 | // If we're declaring or defining a tag in function prototype scope in C, | |||
15000 | // note that this type can only be used within the function and add it to | |||
15001 | // the list of decls to inject into the function definition scope. | |||
15002 | if ((Name || Kind == TTK_Enum) && | |||
15003 | getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { | |||
15004 | if (getLangOpts().CPlusPlus) { | |||
15005 | // C++ [dcl.fct]p6: | |||
15006 | // Types shall not be defined in return or parameter types. | |||
15007 | if (TUK == TUK_Definition && !IsTypeSpecifier) { | |||
15008 | Diag(Loc, diag::err_type_defined_in_param_type) | |||
15009 | << Name; | |||
15010 | Invalid = true; | |||
15011 | } | |||
15012 | } else if (!PrevDecl) { | |||
15013 | Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); | |||
15014 | } | |||
15015 | } | |||
15016 | ||||
15017 | if (Invalid) | |||
15018 | New->setInvalidDecl(); | |||
15019 | ||||
15020 | // Set the lexical context. If the tag has a C++ scope specifier, the | |||
15021 | // lexical context will be different from the semantic context. | |||
15022 | New->setLexicalDeclContext(CurContext); | |||
15023 | ||||
15024 | // Mark this as a friend decl if applicable. | |||
15025 | // In Microsoft mode, a friend declaration also acts as a forward | |||
15026 | // declaration so we always pass true to setObjectOfFriendDecl to make | |||
15027 | // the tag name visible. | |||
15028 | if (TUK == TUK_Friend) | |||
15029 | New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); | |||
15030 | ||||
15031 | // Set the access specifier. | |||
15032 | if (!Invalid && SearchDC->isRecord()) | |||
15033 | SetMemberAccessSpecifier(New, PrevDecl, AS); | |||
15034 | ||||
15035 | if (PrevDecl) | |||
15036 | CheckRedeclarationModuleOwnership(New, PrevDecl); | |||
15037 | ||||
15038 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) | |||
15039 | New->startDefinition(); | |||
15040 | ||||
15041 | ProcessDeclAttributeList(S, New, Attrs); | |||
15042 | AddPragmaAttributes(S, New); | |||
15043 | ||||
15044 | // If this has an identifier, add it to the scope stack. | |||
15045 | if (TUK == TUK_Friend) { | |||
15046 | // We might be replacing an existing declaration in the lookup tables; | |||
15047 | // if so, borrow its access specifier. | |||
15048 | if (PrevDecl) | |||
15049 | New->setAccess(PrevDecl->getAccess()); | |||
15050 | ||||
15051 | DeclContext *DC = New->getDeclContext()->getRedeclContext(); | |||
15052 | DC->makeDeclVisibleInContext(New); | |||
15053 | if (Name) // can be null along some error paths | |||
15054 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) | |||
15055 | PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); | |||
15056 | } else if (Name) { | |||
15057 | S = getNonFieldDeclScope(S); | |||
15058 | PushOnScopeChains(New, S, true); | |||
15059 | } else { | |||
15060 | CurContext->addDecl(New); | |||
15061 | } | |||
15062 | ||||
15063 | // If this is the C FILE type, notify the AST context. | |||
15064 | if (IdentifierInfo *II = New->getIdentifier()) | |||
15065 | if (!New->isInvalidDecl() && | |||
15066 | New->getDeclContext()->getRedeclContext()->isTranslationUnit() && | |||
15067 | II->isStr("FILE")) | |||
15068 | Context.setFILEDecl(New); | |||
15069 | ||||
15070 | if (PrevDecl) | |||
15071 | mergeDeclAttributes(New, PrevDecl); | |||
15072 | ||||
15073 | // If there's a #pragma GCC visibility in scope, set the visibility of this | |||
15074 | // record. | |||
15075 | AddPushedVisibilityAttribute(New); | |||
15076 | ||||
15077 | if (isMemberSpecialization && !New->isInvalidDecl()) | |||
15078 | CompleteMemberSpecialization(New, Previous); | |||
15079 | ||||
15080 | OwnedDecl = true; | |||
15081 | // In C++, don't return an invalid declaration. We can't recover well from | |||
15082 | // the cases where we make the type anonymous. | |||
15083 | if (Invalid && getLangOpts().CPlusPlus) { | |||
15084 | if (New->isBeingDefined()) | |||
15085 | if (auto RD = dyn_cast<RecordDecl>(New)) | |||
15086 | RD->completeDefinition(); | |||
15087 | return nullptr; | |||
15088 | } else if (SkipBody && SkipBody->ShouldSkip) { | |||
15089 | return SkipBody->Previous; | |||
15090 | } else { | |||
15091 | return New; | |||
15092 | } | |||
15093 | } | |||
15094 | ||||
15095 | void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { | |||
15096 | AdjustDeclIfTemplate(TagD); | |||
15097 | TagDecl *Tag = cast<TagDecl>(TagD); | |||
15098 | ||||
15099 | // Enter the tag context. | |||
15100 | PushDeclContext(S, Tag); | |||
15101 | ||||
15102 | ActOnDocumentableDecl(TagD); | |||
15103 | ||||
15104 | // If there's a #pragma GCC visibility in scope, set the visibility of this | |||
15105 | // record. | |||
15106 | AddPushedVisibilityAttribute(Tag); | |||
15107 | } | |||
15108 | ||||
15109 | bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, | |||
15110 | SkipBodyInfo &SkipBody) { | |||
15111 | if (!hasStructuralCompatLayout(Prev, SkipBody.New)) | |||
15112 | return false; | |||
15113 | ||||
15114 | // Make the previous decl visible. | |||
15115 | makeMergedDefinitionVisible(SkipBody.Previous); | |||
15116 | return true; | |||
15117 | } | |||
15118 | ||||
15119 | Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { | |||
15120 | assert(isa<ObjCContainerDecl>(IDecl) &&((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15121, __PRETTY_FUNCTION__)) | |||
15121 | "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15121, __PRETTY_FUNCTION__)); | |||
15122 | DeclContext *OCD = cast<DeclContext>(IDecl); | |||
15123 | assert(getContainingDC(OCD) == CurContext &&((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15124, __PRETTY_FUNCTION__)) | |||
15124 | "The next DeclContext should be lexically contained in the current one.")((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15124, __PRETTY_FUNCTION__)); | |||
15125 | CurContext = OCD; | |||
15126 | return IDecl; | |||
15127 | } | |||
15128 | ||||
15129 | void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, | |||
15130 | SourceLocation FinalLoc, | |||
15131 | bool IsFinalSpelledSealed, | |||
15132 | SourceLocation LBraceLoc) { | |||
15133 | AdjustDeclIfTemplate(TagD); | |||
15134 | CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); | |||
15135 | ||||
15136 | FieldCollector->StartClass(); | |||
15137 | ||||
15138 | if (!Record->getIdentifier()) | |||
15139 | return; | |||
15140 | ||||
15141 | if (FinalLoc.isValid()) | |||
15142 | Record->addAttr(new (Context) | |||
15143 | FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); | |||
15144 | ||||
15145 | // C++ [class]p2: | |||
15146 | // [...] The class-name is also inserted into the scope of the | |||
15147 | // class itself; this is known as the injected-class-name. For | |||
15148 | // purposes of access checking, the injected-class-name is treated | |||
15149 | // as if it were a public member name. | |||
15150 | CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( | |||
15151 | Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), | |||
15152 | Record->getLocation(), Record->getIdentifier(), | |||
15153 | /*PrevDecl=*/nullptr, | |||
15154 | /*DelayTypeCreation=*/true); | |||
15155 | Context.getTypeDeclType(InjectedClassName, Record); | |||
15156 | InjectedClassName->setImplicit(); | |||
15157 | InjectedClassName->setAccess(AS_public); | |||
15158 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) | |||
15159 | InjectedClassName->setDescribedClassTemplate(Template); | |||
15160 | PushOnScopeChains(InjectedClassName, S); | |||
15161 | assert(InjectedClassName->isInjectedClassName() &&((InjectedClassName->isInjectedClassName() && "Broken injected-class-name" ) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15162, __PRETTY_FUNCTION__)) | |||
15162 | "Broken injected-class-name")((InjectedClassName->isInjectedClassName() && "Broken injected-class-name" ) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15162, __PRETTY_FUNCTION__)); | |||
15163 | } | |||
15164 | ||||
15165 | void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, | |||
15166 | SourceRange BraceRange) { | |||
15167 | AdjustDeclIfTemplate(TagD); | |||
15168 | TagDecl *Tag = cast<TagDecl>(TagD); | |||
15169 | Tag->setBraceRange(BraceRange); | |||
15170 | ||||
15171 | // Make sure we "complete" the definition even it is invalid. | |||
15172 | if (Tag->isBeingDefined()) { | |||
15173 | assert(Tag->isInvalidDecl() && "We should already have completed it")((Tag->isInvalidDecl() && "We should already have completed it" ) ? static_cast<void> (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15173, __PRETTY_FUNCTION__)); | |||
15174 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | |||
15175 | RD->completeDefinition(); | |||
15176 | } | |||
15177 | ||||
15178 | if (isa<CXXRecordDecl>(Tag)) { | |||
15179 | FieldCollector->FinishClass(); | |||
15180 | } | |||
15181 | ||||
15182 | // Exit this scope of this tag's definition. | |||
15183 | PopDeclContext(); | |||
15184 | ||||
15185 | if (getCurLexicalContext()->isObjCContainer() && | |||
15186 | Tag->getDeclContext()->isFileContext()) | |||
15187 | Tag->setTopLevelDeclInObjCContainer(); | |||
15188 | ||||
15189 | // Notify the consumer that we've defined a tag. | |||
15190 | if (!Tag->isInvalidDecl()) | |||
15191 | Consumer.HandleTagDeclDefinition(Tag); | |||
15192 | } | |||
15193 | ||||
15194 | void Sema::ActOnObjCContainerFinishDefinition() { | |||
15195 | // Exit this scope of this interface definition. | |||
15196 | PopDeclContext(); | |||
15197 | } | |||
15198 | ||||
15199 | void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { | |||
15200 | assert(DC == CurContext && "Mismatch of container contexts")((DC == CurContext && "Mismatch of container contexts" ) ? static_cast<void> (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15200, __PRETTY_FUNCTION__)); | |||
15201 | OriginalLexicalContext = DC; | |||
15202 | ActOnObjCContainerFinishDefinition(); | |||
15203 | } | |||
15204 | ||||
15205 | void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { | |||
15206 | ActOnObjCContainerStartDefinition(cast<Decl>(DC)); | |||
15207 | OriginalLexicalContext = nullptr; | |||
15208 | } | |||
15209 | ||||
15210 | void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { | |||
15211 | AdjustDeclIfTemplate(TagD); | |||
15212 | TagDecl *Tag = cast<TagDecl>(TagD); | |||
15213 | Tag->setInvalidDecl(); | |||
15214 | ||||
15215 | // Make sure we "complete" the definition even it is invalid. | |||
15216 | if (Tag->isBeingDefined()) { | |||
15217 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | |||
15218 | RD->completeDefinition(); | |||
15219 | } | |||
15220 | ||||
15221 | // We're undoing ActOnTagStartDefinition here, not | |||
15222 | // ActOnStartCXXMemberDeclarations, so we don't have to mess with | |||
15223 | // the FieldCollector. | |||
15224 | ||||
15225 | PopDeclContext(); | |||
15226 | } | |||
15227 | ||||
15228 | // Note that FieldName may be null for anonymous bitfields. | |||
15229 | ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, | |||
15230 | IdentifierInfo *FieldName, | |||
15231 | QualType FieldTy, bool IsMsStruct, | |||
15232 | Expr *BitWidth, bool *ZeroWidth) { | |||
15233 | // Default to true; that shouldn't confuse checks for emptiness | |||
15234 | if (ZeroWidth) | |||
15235 | *ZeroWidth = true; | |||
15236 | ||||
15237 | // C99 6.7.2.1p4 - verify the field type. | |||
15238 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | |||
15239 | if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { | |||
15240 | // Handle incomplete types with specific error. | |||
15241 | if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) | |||
15242 | return ExprError(); | |||
15243 | if (FieldName) | |||
15244 | return Diag(FieldLoc, diag::err_not_integral_type_bitfield) | |||
15245 | << FieldName << FieldTy << BitWidth->getSourceRange(); | |||
15246 | return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) | |||
15247 | << FieldTy << BitWidth->getSourceRange(); | |||
15248 | } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), | |||
15249 | UPPC_BitFieldWidth)) | |||
15250 | return ExprError(); | |||
15251 | ||||
15252 | // If the bit-width is type- or value-dependent, don't try to check | |||
15253 | // it now. | |||
15254 | if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) | |||
15255 | return BitWidth; | |||
15256 | ||||
15257 | llvm::APSInt Value; | |||
15258 | ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); | |||
15259 | if (ICE.isInvalid()) | |||
15260 | return ICE; | |||
15261 | BitWidth = ICE.get(); | |||
15262 | ||||
15263 | if (Value != 0 && ZeroWidth) | |||
15264 | *ZeroWidth = false; | |||
15265 | ||||
15266 | // Zero-width bitfield is ok for anonymous field. | |||
15267 | if (Value == 0 && FieldName) | |||
15268 | return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; | |||
15269 | ||||
15270 | if (Value.isSigned() && Value.isNegative()) { | |||
15271 | if (FieldName) | |||
15272 | return Diag(FieldLoc, diag::err_bitfield_has_negative_width) | |||
15273 | << FieldName << Value.toString(10); | |||
15274 | return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) | |||
15275 | << Value.toString(10); | |||
15276 | } | |||
15277 | ||||
15278 | if (!FieldTy->isDependentType()) { | |||
15279 | uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); | |||
15280 | uint64_t TypeWidth = Context.getIntWidth(FieldTy); | |||
15281 | bool BitfieldIsOverwide = Value.ugt(TypeWidth); | |||
15282 | ||||
15283 | // Over-wide bitfields are an error in C or when using the MSVC bitfield | |||
15284 | // ABI. | |||
15285 | bool CStdConstraintViolation = | |||
15286 | BitfieldIsOverwide && !getLangOpts().CPlusPlus; | |||
15287 | bool MSBitfieldViolation = | |||
15288 | Value.ugt(TypeStorageSize) && | |||
15289 | (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); | |||
15290 | if (CStdConstraintViolation || MSBitfieldViolation) { | |||
15291 | unsigned DiagWidth = | |||
15292 | CStdConstraintViolation ? TypeWidth : TypeStorageSize; | |||
15293 | if (FieldName) | |||
15294 | return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) | |||
15295 | << FieldName << (unsigned)Value.getZExtValue() | |||
15296 | << !CStdConstraintViolation << DiagWidth; | |||
15297 | ||||
15298 | return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) | |||
15299 | << (unsigned)Value.getZExtValue() << !CStdConstraintViolation | |||
15300 | << DiagWidth; | |||
15301 | } | |||
15302 | ||||
15303 | // Warn on types where the user might conceivably expect to get all | |||
15304 | // specified bits as value bits: that's all integral types other than | |||
15305 | // 'bool'. | |||
15306 | if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { | |||
15307 | if (FieldName) | |||
15308 | Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) | |||
15309 | << FieldName << (unsigned)Value.getZExtValue() | |||
15310 | << (unsigned)TypeWidth; | |||
15311 | else | |||
15312 | Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) | |||
15313 | << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; | |||
15314 | } | |||
15315 | } | |||
15316 | ||||
15317 | return BitWidth; | |||
15318 | } | |||
15319 | ||||
15320 | /// ActOnField - Each field of a C struct/union is passed into this in order | |||
15321 | /// to create a FieldDecl object for it. | |||
15322 | Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, | |||
15323 | Declarator &D, Expr *BitfieldWidth) { | |||
15324 | FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), | |||
15325 | DeclStart, D, static_cast<Expr*>(BitfieldWidth), | |||
15326 | /*InitStyle=*/ICIS_NoInit, AS_public); | |||
15327 | return Res; | |||
15328 | } | |||
15329 | ||||
15330 | /// HandleField - Analyze a field of a C struct or a C++ data member. | |||
15331 | /// | |||
15332 | FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, | |||
15333 | SourceLocation DeclStart, | |||
15334 | Declarator &D, Expr *BitWidth, | |||
15335 | InClassInitStyle InitStyle, | |||
15336 | AccessSpecifier AS) { | |||
15337 | if (D.isDecompositionDeclarator()) { | |||
15338 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); | |||
15339 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) | |||
15340 | << Decomp.getSourceRange(); | |||
15341 | return nullptr; | |||
15342 | } | |||
15343 | ||||
15344 | IdentifierInfo *II = D.getIdentifier(); | |||
15345 | SourceLocation Loc = DeclStart; | |||
15346 | if (II) Loc = D.getIdentifierLoc(); | |||
15347 | ||||
15348 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
15349 | QualType T = TInfo->getType(); | |||
15350 | if (getLangOpts().CPlusPlus) { | |||
15351 | CheckExtraCXXDefaultArguments(D); | |||
15352 | ||||
15353 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
15354 | UPPC_DataMemberType)) { | |||
15355 | D.setInvalidType(); | |||
15356 | T = Context.IntTy; | |||
15357 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
15358 | } | |||
15359 | } | |||
15360 | ||||
15361 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
15362 | ||||
15363 | if (D.getDeclSpec().isInlineSpecified()) | |||
15364 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
15365 | << getLangOpts().CPlusPlus17; | |||
15366 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | |||
15367 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
15368 | diag::err_invalid_thread) | |||
15369 | << DeclSpec::getSpecifierName(TSCS); | |||
15370 | ||||
15371 | // Check to see if this name was declared as a member previously | |||
15372 | NamedDecl *PrevDecl = nullptr; | |||
15373 | LookupResult Previous(*this, II, Loc, LookupMemberName, | |||
15374 | ForVisibleRedeclaration); | |||
15375 | LookupName(Previous, S); | |||
15376 | switch (Previous.getResultKind()) { | |||
15377 | case LookupResult::Found: | |||
15378 | case LookupResult::FoundUnresolvedValue: | |||
15379 | PrevDecl = Previous.getAsSingle<NamedDecl>(); | |||
15380 | break; | |||
15381 | ||||
15382 | case LookupResult::FoundOverloaded: | |||
15383 | PrevDecl = Previous.getRepresentativeDecl(); | |||
15384 | break; | |||
15385 | ||||
15386 | case LookupResult::NotFound: | |||
15387 | case LookupResult::NotFoundInCurrentInstantiation: | |||
15388 | case LookupResult::Ambiguous: | |||
15389 | break; | |||
15390 | } | |||
15391 | Previous.suppressDiagnostics(); | |||
15392 | ||||
15393 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | |||
15394 | // Maybe we will complain about the shadowed template parameter. | |||
15395 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | |||
15396 | // Just pretend that we didn't see the previous declaration. | |||
15397 | PrevDecl = nullptr; | |||
15398 | } | |||
15399 | ||||
15400 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) | |||
15401 | PrevDecl = nullptr; | |||
15402 | ||||
15403 | bool Mutable | |||
15404 | = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); | |||
15405 | SourceLocation TSSL = D.getBeginLoc(); | |||
15406 | FieldDecl *NewFD | |||
15407 | = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, | |||
15408 | TSSL, AS, PrevDecl, &D); | |||
15409 | ||||
15410 | if (NewFD->isInvalidDecl()) | |||
15411 | Record->setInvalidDecl(); | |||
15412 | ||||
15413 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
15414 | NewFD->setModulePrivate(); | |||
15415 | ||||
15416 | if (NewFD->isInvalidDecl() && PrevDecl) { | |||
15417 | // Don't introduce NewFD into scope; there's already something | |||
15418 | // with the same name in the same scope. | |||
15419 | } else if (II) { | |||
15420 | PushOnScopeChains(NewFD, S); | |||
15421 | } else | |||
15422 | Record->addDecl(NewFD); | |||
15423 | ||||
15424 | return NewFD; | |||
15425 | } | |||
15426 | ||||
15427 | /// Build a new FieldDecl and check its well-formedness. | |||
15428 | /// | |||
15429 | /// This routine builds a new FieldDecl given the fields name, type, | |||
15430 | /// record, etc. \p PrevDecl should refer to any previous declaration | |||
15431 | /// with the same name and in the same scope as the field to be | |||
15432 | /// created. | |||
15433 | /// | |||
15434 | /// \returns a new FieldDecl. | |||
15435 | /// | |||
15436 | /// \todo The Declarator argument is a hack. It will be removed once | |||
15437 | FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, | |||
15438 | TypeSourceInfo *TInfo, | |||
15439 | RecordDecl *Record, SourceLocation Loc, | |||
15440 | bool Mutable, Expr *BitWidth, | |||
15441 | InClassInitStyle InitStyle, | |||
15442 | SourceLocation TSSL, | |||
15443 | AccessSpecifier AS, NamedDecl *PrevDecl, | |||
15444 | Declarator *D) { | |||
15445 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
15446 | bool InvalidDecl = false; | |||
15447 | if (D) InvalidDecl = D->isInvalidType(); | |||
15448 | ||||
15449 | // If we receive a broken type, recover by assuming 'int' and | |||
15450 | // marking this declaration as invalid. | |||
15451 | if (T.isNull()) { | |||
15452 | InvalidDecl = true; | |||
15453 | T = Context.IntTy; | |||
15454 | } | |||
15455 | ||||
15456 | QualType EltTy = Context.getBaseElementType(T); | |||
15457 | if (!EltTy->isDependentType()) { | |||
15458 | if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { | |||
15459 | // Fields of incomplete type force their record to be invalid. | |||
15460 | Record->setInvalidDecl(); | |||
15461 | InvalidDecl = true; | |||
15462 | } else { | |||
15463 | NamedDecl *Def; | |||
15464 | EltTy->isIncompleteType(&Def); | |||
15465 | if (Def && Def->isInvalidDecl()) { | |||
15466 | Record->setInvalidDecl(); | |||
15467 | InvalidDecl = true; | |||
15468 | } | |||
15469 | } | |||
15470 | } | |||
15471 | ||||
15472 | // TR 18037 does not allow fields to be declared with address space | |||
15473 | if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() || | |||
15474 | T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { | |||
15475 | Diag(Loc, diag::err_field_with_address_space); | |||
15476 | Record->setInvalidDecl(); | |||
15477 | InvalidDecl = true; | |||
15478 | } | |||
15479 | ||||
15480 | if (LangOpts.OpenCL) { | |||
15481 | // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be | |||
15482 | // used as structure or union field: image, sampler, event or block types. | |||
15483 | if (T->isEventT() || T->isImageType() || T->isSamplerT() || | |||
15484 | T->isBlockPointerType()) { | |||
15485 | Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; | |||
15486 | Record->setInvalidDecl(); | |||
15487 | InvalidDecl = true; | |||
15488 | } | |||
15489 | // OpenCL v1.2 s6.9.c: bitfields are not supported. | |||
15490 | if (BitWidth) { | |||
15491 | Diag(Loc, diag::err_opencl_bitfields); | |||
15492 | InvalidDecl = true; | |||
15493 | } | |||
15494 | } | |||
15495 | ||||
15496 | // Anonymous bit-fields cannot be cv-qualified (CWG 2229). | |||
15497 | if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && | |||
15498 | T.hasQualifiers()) { | |||
15499 | InvalidDecl = true; | |||
15500 | Diag(Loc, diag::err_anon_bitfield_qualifiers); | |||
15501 | } | |||
15502 | ||||
15503 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | |||
15504 | // than a variably modified type. | |||
15505 | if (!InvalidDecl && T->isVariablyModifiedType()) { | |||
15506 | bool SizeIsNegative; | |||
15507 | llvm::APSInt Oversized; | |||
15508 | ||||
15509 | TypeSourceInfo *FixedTInfo = | |||
15510 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | |||
15511 | SizeIsNegative, | |||
15512 | Oversized); | |||
15513 | if (FixedTInfo) { | |||
15514 | Diag(Loc, diag::warn_illegal_constant_array_size); | |||
15515 | TInfo = FixedTInfo; | |||
15516 | T = FixedTInfo->getType(); | |||
15517 | } else { | |||
15518 | if (SizeIsNegative) | |||
15519 | Diag(Loc, diag::err_typecheck_negative_array_size); | |||
15520 | else if (Oversized.getBoolValue()) | |||
15521 | Diag(Loc, diag::err_array_too_large) | |||
15522 | << Oversized.toString(10); | |||
15523 | else | |||
15524 | Diag(Loc, diag::err_typecheck_field_variable_size); | |||
15525 | InvalidDecl = true; | |||
15526 | } | |||
15527 | } | |||
15528 | ||||
15529 | // Fields can not have abstract class types | |||
15530 | if (!InvalidDecl && RequireNonAbstractType(Loc, T, | |||
15531 | diag::err_abstract_type_in_decl, | |||
15532 | AbstractFieldType)) | |||
15533 | InvalidDecl = true; | |||
15534 | ||||
15535 | bool ZeroWidth = false; | |||
15536 | if (InvalidDecl) | |||
15537 | BitWidth = nullptr; | |||
15538 | // If this is declared as a bit-field, check the bit-field. | |||
15539 | if (BitWidth) { | |||
15540 | BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, | |||
15541 | &ZeroWidth).get(); | |||
15542 | if (!BitWidth) { | |||
15543 | InvalidDecl = true; | |||
15544 | BitWidth = nullptr; | |||
15545 | ZeroWidth = false; | |||
15546 | } | |||
15547 | } | |||
15548 | ||||
15549 | // Check that 'mutable' is consistent with the type of the declaration. | |||
15550 | if (!InvalidDecl && Mutable) { | |||
15551 | unsigned DiagID = 0; | |||
15552 | if (T->isReferenceType()) | |||
15553 | DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference | |||
15554 | : diag::err_mutable_reference; | |||
15555 | else if (T.isConstQualified()) | |||
15556 | DiagID = diag::err_mutable_const; | |||
15557 | ||||
15558 | if (DiagID) { | |||
15559 | SourceLocation ErrLoc = Loc; | |||
15560 | if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) | |||
15561 | ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); | |||
15562 | Diag(ErrLoc, DiagID); | |||
15563 | if (DiagID != diag::ext_mutable_reference) { | |||
15564 | Mutable = false; | |||
15565 | InvalidDecl = true; | |||
15566 | } | |||
15567 | } | |||
15568 | } | |||
15569 | ||||
15570 | // C++11 [class.union]p8 (DR1460): | |||
15571 | // At most one variant member of a union may have a | |||
15572 | // brace-or-equal-initializer. | |||
15573 | if (InitStyle != ICIS_NoInit) | |||
15574 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); | |||
15575 | ||||
15576 | FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, | |||
15577 | BitWidth, Mutable, InitStyle); | |||
15578 | if (InvalidDecl) | |||
15579 | NewFD->setInvalidDecl(); | |||
15580 | ||||
15581 | if (PrevDecl && !isa<TagDecl>(PrevDecl)) { | |||
15582 | Diag(Loc, diag::err_duplicate_member) << II; | |||
15583 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
15584 | NewFD->setInvalidDecl(); | |||
15585 | } | |||
15586 | ||||
15587 | if (!InvalidDecl && getLangOpts().CPlusPlus) { | |||
15588 | if (Record->isUnion()) { | |||
15589 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | |||
15590 | CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
15591 | if (RDecl->getDefinition()) { | |||
15592 | // C++ [class.union]p1: An object of a class with a non-trivial | |||
15593 | // constructor, a non-trivial copy constructor, a non-trivial | |||
15594 | // destructor, or a non-trivial copy assignment operator | |||
15595 | // cannot be a member of a union, nor can an array of such | |||
15596 | // objects. | |||
15597 | if (CheckNontrivialField(NewFD)) | |||
15598 | NewFD->setInvalidDecl(); | |||
15599 | } | |||
15600 | } | |||
15601 | ||||
15602 | // C++ [class.union]p1: If a union contains a member of reference type, | |||
15603 | // the program is ill-formed, except when compiling with MSVC extensions | |||
15604 | // enabled. | |||
15605 | if (EltTy->isReferenceType()) { | |||
15606 | Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? | |||
15607 | diag::ext_union_member_of_reference_type : | |||
15608 | diag::err_union_member_of_reference_type) | |||
15609 | << NewFD->getDeclName() << EltTy; | |||
15610 | if (!getLangOpts().MicrosoftExt) | |||
15611 | NewFD->setInvalidDecl(); | |||
15612 | } | |||
15613 | } | |||
15614 | } | |||
15615 | ||||
15616 | // FIXME: We need to pass in the attributes given an AST | |||
15617 | // representation, not a parser representation. | |||
15618 | if (D) { | |||
15619 | // FIXME: The current scope is almost... but not entirely... correct here. | |||
15620 | ProcessDeclAttributes(getCurScope(), NewFD, *D); | |||
15621 | ||||
15622 | if (NewFD->hasAttrs()) | |||
15623 | CheckAlignasUnderalignment(NewFD); | |||
15624 | } | |||
15625 | ||||
15626 | // In auto-retain/release, infer strong retension for fields of | |||
15627 | // retainable type. | |||
15628 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) | |||
15629 | NewFD->setInvalidDecl(); | |||
15630 | ||||
15631 | if (T.isObjCGCWeak()) | |||
15632 | Diag(Loc, diag::warn_attribute_weak_on_field); | |||
15633 | ||||
15634 | NewFD->setAccess(AS); | |||
15635 | return NewFD; | |||
15636 | } | |||
15637 | ||||
15638 | bool Sema::CheckNontrivialField(FieldDecl *FD) { | |||
15639 | assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15639, __PRETTY_FUNCTION__)); | |||
15640 | assert(getLangOpts().CPlusPlus && "valid check only for C++")((getLangOpts().CPlusPlus && "valid check only for C++" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15640, __PRETTY_FUNCTION__)); | |||
15641 | ||||
15642 | if (FD->isInvalidDecl() || FD->getType()->isDependentType()) | |||
15643 | return false; | |||
15644 | ||||
15645 | QualType EltTy = Context.getBaseElementType(FD->getType()); | |||
15646 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | |||
15647 | CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
15648 | if (RDecl->getDefinition()) { | |||
15649 | // We check for copy constructors before constructors | |||
15650 | // because otherwise we'll never get complaints about | |||
15651 | // copy constructors. | |||
15652 | ||||
15653 | CXXSpecialMember member = CXXInvalid; | |||
15654 | // We're required to check for any non-trivial constructors. Since the | |||
15655 | // implicit default constructor is suppressed if there are any | |||
15656 | // user-declared constructors, we just need to check that there is a | |||
15657 | // trivial default constructor and a trivial copy constructor. (We don't | |||
15658 | // worry about move constructors here, since this is a C++98 check.) | |||
15659 | if (RDecl->hasNonTrivialCopyConstructor()) | |||
15660 | member = CXXCopyConstructor; | |||
15661 | else if (!RDecl->hasTrivialDefaultConstructor()) | |||
15662 | member = CXXDefaultConstructor; | |||
15663 | else if (RDecl->hasNonTrivialCopyAssignment()) | |||
15664 | member = CXXCopyAssignment; | |||
15665 | else if (RDecl->hasNonTrivialDestructor()) | |||
15666 | member = CXXDestructor; | |||
15667 | ||||
15668 | if (member != CXXInvalid) { | |||
15669 | if (!getLangOpts().CPlusPlus11 && | |||
15670 | getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { | |||
15671 | // Objective-C++ ARC: it is an error to have a non-trivial field of | |||
15672 | // a union. However, system headers in Objective-C programs | |||
15673 | // occasionally have Objective-C lifetime objects within unions, | |||
15674 | // and rather than cause the program to fail, we make those | |||
15675 | // members unavailable. | |||
15676 | SourceLocation Loc = FD->getLocation(); | |||
15677 | if (getSourceManager().isInSystemHeader(Loc)) { | |||
15678 | if (!FD->hasAttr<UnavailableAttr>()) | |||
15679 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", | |||
15680 | UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); | |||
15681 | return false; | |||
15682 | } | |||
15683 | } | |||
15684 | ||||
15685 | Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? | |||
15686 | diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : | |||
15687 | diag::err_illegal_union_or_anon_struct_member) | |||
15688 | << FD->getParent()->isUnion() << FD->getDeclName() << member; | |||
15689 | DiagnoseNontrivial(RDecl, member); | |||
15690 | return !getLangOpts().CPlusPlus11; | |||
15691 | } | |||
15692 | } | |||
15693 | } | |||
15694 | ||||
15695 | return false; | |||
15696 | } | |||
15697 | ||||
15698 | /// TranslateIvarVisibility - Translate visibility from a token ID to an | |||
15699 | /// AST enum value. | |||
15700 | static ObjCIvarDecl::AccessControl | |||
15701 | TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { | |||
15702 | switch (ivarVisibility) { | |||
15703 | default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15703); | |||
15704 | case tok::objc_private: return ObjCIvarDecl::Private; | |||
15705 | case tok::objc_public: return ObjCIvarDecl::Public; | |||
15706 | case tok::objc_protected: return ObjCIvarDecl::Protected; | |||
15707 | case tok::objc_package: return ObjCIvarDecl::Package; | |||
15708 | } | |||
15709 | } | |||
15710 | ||||
15711 | /// ActOnIvar - Each ivar field of an objective-c class is passed into this | |||
15712 | /// in order to create an IvarDecl object for it. | |||
15713 | Decl *Sema::ActOnIvar(Scope *S, | |||
15714 | SourceLocation DeclStart, | |||
15715 | Declarator &D, Expr *BitfieldWidth, | |||
15716 | tok::ObjCKeywordKind Visibility) { | |||
15717 | ||||
15718 | IdentifierInfo *II = D.getIdentifier(); | |||
15719 | Expr *BitWidth = (Expr*)BitfieldWidth; | |||
15720 | SourceLocation Loc = DeclStart; | |||
15721 | if (II) Loc = D.getIdentifierLoc(); | |||
15722 | ||||
15723 | // FIXME: Unnamed fields can be handled in various different ways, for | |||
15724 | // example, unnamed unions inject all members into the struct namespace! | |||
15725 | ||||
15726 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
15727 | QualType T = TInfo->getType(); | |||
15728 | ||||
15729 | if (BitWidth) { | |||
15730 | // 6.7.2.1p3, 6.7.2.1p4 | |||
15731 | BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); | |||
15732 | if (!BitWidth) | |||
15733 | D.setInvalidType(); | |||
15734 | } else { | |||
15735 | // Not a bitfield. | |||
15736 | ||||
15737 | // validate II. | |||
15738 | ||||
15739 | } | |||
15740 | if (T->isReferenceType()) { | |||
15741 | Diag(Loc, diag::err_ivar_reference_type); | |||
15742 | D.setInvalidType(); | |||
15743 | } | |||
15744 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | |||
15745 | // than a variably modified type. | |||
15746 | else if (T->isVariablyModifiedType()) { | |||
15747 | Diag(Loc, diag::err_typecheck_ivar_variable_size); | |||
15748 | D.setInvalidType(); | |||
15749 | } | |||
15750 | ||||
15751 | // Get the visibility (access control) for this ivar. | |||
15752 | ObjCIvarDecl::AccessControl ac = | |||
15753 | Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) | |||
15754 | : ObjCIvarDecl::None; | |||
15755 | // Must set ivar's DeclContext to its enclosing interface. | |||
15756 | ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); | |||
15757 | if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) | |||
15758 | return nullptr; | |||
15759 | ObjCContainerDecl *EnclosingContext; | |||
15760 | if (ObjCImplementationDecl *IMPDecl = | |||
15761 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | |||
15762 | if (LangOpts.ObjCRuntime.isFragile()) { | |||
15763 | // Case of ivar declared in an implementation. Context is that of its class. | |||
15764 | EnclosingContext = IMPDecl->getClassInterface(); | |||
15765 | assert(EnclosingContext && "Implementation has no class interface!")((EnclosingContext && "Implementation has no class interface!" ) ? static_cast<void> (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15765, __PRETTY_FUNCTION__)); | |||
15766 | } | |||
15767 | else | |||
15768 | EnclosingContext = EnclosingDecl; | |||
15769 | } else { | |||
15770 | if (ObjCCategoryDecl *CDecl = | |||
15771 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | |||
15772 | if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { | |||
15773 | Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); | |||
15774 | return nullptr; | |||
15775 | } | |||
15776 | } | |||
15777 | EnclosingContext = EnclosingDecl; | |||
15778 | } | |||
15779 | ||||
15780 | // Construct the decl. | |||
15781 | ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, | |||
15782 | DeclStart, Loc, II, T, | |||
15783 | TInfo, ac, (Expr *)BitfieldWidth); | |||
15784 | ||||
15785 | if (II) { | |||
15786 | NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, | |||
15787 | ForVisibleRedeclaration); | |||
15788 | if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) | |||
15789 | && !isa<TagDecl>(PrevDecl)) { | |||
15790 | Diag(Loc, diag::err_duplicate_member) << II; | |||
15791 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
15792 | NewID->setInvalidDecl(); | |||
15793 | } | |||
15794 | } | |||
15795 | ||||
15796 | // Process attributes attached to the ivar. | |||
15797 | ProcessDeclAttributes(S, NewID, D); | |||
15798 | ||||
15799 | if (D.isInvalidType()) | |||
15800 | NewID->setInvalidDecl(); | |||
15801 | ||||
15802 | // In ARC, infer 'retaining' for ivars of retainable type. | |||
15803 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) | |||
15804 | NewID->setInvalidDecl(); | |||
15805 | ||||
15806 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
15807 | NewID->setModulePrivate(); | |||
15808 | ||||
15809 | if (II) { | |||
15810 | // FIXME: When interfaces are DeclContexts, we'll need to add | |||
15811 | // these to the interface. | |||
15812 | S->AddDecl(NewID); | |||
15813 | IdResolver.AddDecl(NewID); | |||
15814 | } | |||
15815 | ||||
15816 | if (LangOpts.ObjCRuntime.isNonFragile() && | |||
15817 | !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) | |||
15818 | Diag(Loc, diag::warn_ivars_in_interface); | |||
15819 | ||||
15820 | return NewID; | |||
15821 | } | |||
15822 | ||||
15823 | /// ActOnLastBitfield - This routine handles synthesized bitfields rules for | |||
15824 | /// class and class extensions. For every class \@interface and class | |||
15825 | /// extension \@interface, if the last ivar is a bitfield of any type, | |||
15826 | /// then add an implicit `char :0` ivar to the end of that interface. | |||
15827 | void Sema::ActOnLastBitfield(SourceLocation DeclLoc, | |||
15828 | SmallVectorImpl<Decl *> &AllIvarDecls) { | |||
15829 | if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) | |||
15830 | return; | |||
15831 | ||||
15832 | Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; | |||
15833 | ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); | |||
15834 | ||||
15835 | if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) | |||
15836 | return; | |||
15837 | ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); | |||
15838 | if (!ID) { | |||
15839 | if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { | |||
15840 | if (!CD->IsClassExtension()) | |||
15841 | return; | |||
15842 | } | |||
15843 | // No need to add this to end of @implementation. | |||
15844 | else | |||
15845 | return; | |||
15846 | } | |||
15847 | // All conditions are met. Add a new bitfield to the tail end of ivars. | |||
15848 | llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); | |||
15849 | Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); | |||
15850 | ||||
15851 | Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), | |||
15852 | DeclLoc, DeclLoc, nullptr, | |||
15853 | Context.CharTy, | |||
15854 | Context.getTrivialTypeSourceInfo(Context.CharTy, | |||
15855 | DeclLoc), | |||
15856 | ObjCIvarDecl::Private, BW, | |||
15857 | true); | |||
15858 | AllIvarDecls.push_back(Ivar); | |||
15859 | } | |||
15860 | ||||
15861 | void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, | |||
15862 | ArrayRef<Decl *> Fields, SourceLocation LBrac, | |||
15863 | SourceLocation RBrac, | |||
15864 | const ParsedAttributesView &Attrs) { | |||
15865 | assert(EnclosingDecl && "missing record or interface decl")((EnclosingDecl && "missing record or interface decl" ) ? static_cast<void> (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 15865, __PRETTY_FUNCTION__)); | |||
15866 | ||||
15867 | // If this is an Objective-C @implementation or category and we have | |||
15868 | // new fields here we should reset the layout of the interface since | |||
15869 | // it will now change. | |||
15870 | if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { | |||
15871 | ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); | |||
15872 | switch (DC->getKind()) { | |||
15873 | default: break; | |||
15874 | case Decl::ObjCCategory: | |||
15875 | Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); | |||
15876 | break; | |||
15877 | case Decl::ObjCImplementation: | |||
15878 | Context. | |||
15879 | ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); | |||
15880 | break; | |||
15881 | } | |||
15882 | } | |||
15883 | ||||
15884 | RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); | |||
15885 | CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); | |||
15886 | ||||
15887 | // Start counting up the number of named members; make sure to include | |||
15888 | // members of anonymous structs and unions in the total. | |||
15889 | unsigned NumNamedMembers = 0; | |||
15890 | if (Record) { | |||
15891 | for (const auto *I : Record->decls()) { | |||
15892 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | |||
15893 | if (IFD->getDeclName()) | |||
15894 | ++NumNamedMembers; | |||
15895 | } | |||
15896 | } | |||
15897 | ||||
15898 | // Verify that all the fields are okay. | |||
15899 | SmallVector<FieldDecl*, 32> RecFields; | |||
15900 | ||||
15901 | bool ObjCFieldLifetimeErrReported = false; | |||
15902 | for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); | |||
15903 | i != end; ++i) { | |||
15904 | FieldDecl *FD = cast<FieldDecl>(*i); | |||
15905 | ||||
15906 | // Get the type for the field. | |||
15907 | const Type *FDTy = FD->getType().getTypePtr(); | |||
15908 | ||||
15909 | if (!FD->isAnonymousStructOrUnion()) { | |||
15910 | // Remember all fields written by the user. | |||
15911 | RecFields.push_back(FD); | |||
15912 | } | |||
15913 | ||||
15914 | // If the field is already invalid for some reason, don't emit more | |||
15915 | // diagnostics about it. | |||
15916 | if (FD->isInvalidDecl()) { | |||
15917 | EnclosingDecl->setInvalidDecl(); | |||
15918 | continue; | |||
15919 | } | |||
15920 | ||||
15921 | // C99 6.7.2.1p2: | |||
15922 | // A structure or union shall not contain a member with | |||
15923 | // incomplete or function type (hence, a structure shall not | |||
15924 | // contain an instance of itself, but may contain a pointer to | |||
15925 | // an instance of itself), except that the last member of a | |||
15926 | // structure with more than one named member may have incomplete | |||
15927 | // array type; such a structure (and any union containing, | |||
15928 | // possibly recursively, a member that is such a structure) | |||
15929 | // shall not be a member of a structure or an element of an | |||
15930 | // array. | |||
15931 | bool IsLastField = (i + 1 == Fields.end()); | |||
15932 | if (FDTy->isFunctionType()) { | |||
15933 | // Field declared as a function. | |||
15934 | Diag(FD->getLocation(), diag::err_field_declared_as_function) | |||
15935 | << FD->getDeclName(); | |||
15936 | FD->setInvalidDecl(); | |||
15937 | EnclosingDecl->setInvalidDecl(); | |||
15938 | continue; | |||
15939 | } else if (FDTy->isIncompleteArrayType() && | |||
15940 | (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { | |||
15941 | if (Record) { | |||
15942 | // Flexible array member. | |||
15943 | // Microsoft and g++ is more permissive regarding flexible array. | |||
15944 | // It will accept flexible array in union and also | |||
15945 | // as the sole element of a struct/class. | |||
15946 | unsigned DiagID = 0; | |||
15947 | if (!Record->isUnion() && !IsLastField) { | |||
15948 | Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) | |||
15949 | << FD->getDeclName() << FD->getType() << Record->getTagKind(); | |||
15950 | Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); | |||
15951 | FD->setInvalidDecl(); | |||
15952 | EnclosingDecl->setInvalidDecl(); | |||
15953 | continue; | |||
15954 | } else if (Record->isUnion()) | |||
15955 | DiagID = getLangOpts().MicrosoftExt | |||
15956 | ? diag::ext_flexible_array_union_ms | |||
15957 | : getLangOpts().CPlusPlus | |||
15958 | ? diag::ext_flexible_array_union_gnu | |||
15959 | : diag::err_flexible_array_union; | |||
15960 | else if (NumNamedMembers < 1) | |||
15961 | DiagID = getLangOpts().MicrosoftExt | |||
15962 | ? diag::ext_flexible_array_empty_aggregate_ms | |||
15963 | : getLangOpts().CPlusPlus | |||
15964 | ? diag::ext_flexible_array_empty_aggregate_gnu | |||
15965 | : diag::err_flexible_array_empty_aggregate; | |||
15966 | ||||
15967 | if (DiagID) | |||
15968 | Diag(FD->getLocation(), DiagID) << FD->getDeclName() | |||
15969 | << Record->getTagKind(); | |||
15970 | // While the layout of types that contain virtual bases is not specified | |||
15971 | // by the C++ standard, both the Itanium and Microsoft C++ ABIs place | |||
15972 | // virtual bases after the derived members. This would make a flexible | |||
15973 | // array member declared at the end of an object not adjacent to the end | |||
15974 | // of the type. | |||
15975 | if (CXXRecord && CXXRecord->getNumVBases() != 0) | |||
15976 | Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) | |||
15977 | << FD->getDeclName() << Record->getTagKind(); | |||
15978 | if (!getLangOpts().C99) | |||
15979 | Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) | |||
15980 | << FD->getDeclName() << Record->getTagKind(); | |||
15981 | ||||
15982 | // If the element type has a non-trivial destructor, we would not | |||
15983 | // implicitly destroy the elements, so disallow it for now. | |||
15984 | // | |||
15985 | // FIXME: GCC allows this. We should probably either implicitly delete | |||
15986 | // the destructor of the containing class, or just allow this. | |||
15987 | QualType BaseElem = Context.getBaseElementType(FD->getType()); | |||
15988 | if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { | |||
15989 | Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) | |||
15990 | << FD->getDeclName() << FD->getType(); | |||
15991 | FD->setInvalidDecl(); | |||
15992 | EnclosingDecl->setInvalidDecl(); | |||
15993 | continue; | |||
15994 | } | |||
15995 | // Okay, we have a legal flexible array member at the end of the struct. | |||
15996 | Record->setHasFlexibleArrayMember(true); | |||
15997 | } else { | |||
15998 | // In ObjCContainerDecl ivars with incomplete array type are accepted, | |||
15999 | // unless they are followed by another ivar. That check is done | |||
16000 | // elsewhere, after synthesized ivars are known. | |||
16001 | } | |||
16002 | } else if (!FDTy->isDependentType() && | |||
16003 | RequireCompleteType(FD->getLocation(), FD->getType(), | |||
16004 | diag::err_field_incomplete)) { | |||
16005 | // Incomplete type | |||
16006 | FD->setInvalidDecl(); | |||
16007 | EnclosingDecl->setInvalidDecl(); | |||
16008 | continue; | |||
16009 | } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { | |||
16010 | if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { | |||
16011 | // A type which contains a flexible array member is considered to be a | |||
16012 | // flexible array member. | |||
16013 | Record->setHasFlexibleArrayMember(true); | |||
16014 | if (!Record->isUnion()) { | |||
16015 | // If this is a struct/class and this is not the last element, reject | |||
16016 | // it. Note that GCC supports variable sized arrays in the middle of | |||
16017 | // structures. | |||
16018 | if (!IsLastField) | |||
16019 | Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) | |||
16020 | << FD->getDeclName() << FD->getType(); | |||
16021 | else { | |||
16022 | // We support flexible arrays at the end of structs in | |||
16023 | // other structs as an extension. | |||
16024 | Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) | |||
16025 | << FD->getDeclName(); | |||
16026 | } | |||
16027 | } | |||
16028 | } | |||
16029 | if (isa<ObjCContainerDecl>(EnclosingDecl) && | |||
16030 | RequireNonAbstractType(FD->getLocation(), FD->getType(), | |||
16031 | diag::err_abstract_type_in_decl, | |||
16032 | AbstractIvarType)) { | |||
16033 | // Ivars can not have abstract class types | |||
16034 | FD->setInvalidDecl(); | |||
16035 | } | |||
16036 | if (Record && FDTTy->getDecl()->hasObjectMember()) | |||
16037 | Record->setHasObjectMember(true); | |||
16038 | if (Record && FDTTy->getDecl()->hasVolatileMember()) | |||
16039 | Record->setHasVolatileMember(true); | |||
16040 | if (Record && Record->isUnion() && | |||
16041 | FD->getType().isNonTrivialPrimitiveCType(Context)) | |||
16042 | Diag(FD->getLocation(), | |||
16043 | diag::err_nontrivial_primitive_type_in_union); | |||
16044 | } else if (FDTy->isObjCObjectType()) { | |||
16045 | /// A field cannot be an Objective-c object | |||
16046 | Diag(FD->getLocation(), diag::err_statically_allocated_object) | |||
16047 | << FixItHint::CreateInsertion(FD->getLocation(), "*"); | |||
16048 | QualType T = Context.getObjCObjectPointerType(FD->getType()); | |||
16049 | FD->setType(T); | |||
16050 | } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
16051 | Record && !ObjCFieldLifetimeErrReported && Record->isUnion() && | |||
16052 | !getLangOpts().CPlusPlus) { | |||
16053 | // It's an error in ARC or Weak if a field has lifetime. | |||
16054 | // We don't want to report this in a system header, though, | |||
16055 | // so we just make the field unavailable. | |||
16056 | // FIXME: that's really not sufficient; we need to make the type | |||
16057 | // itself invalid to, say, initialize or copy. | |||
16058 | QualType T = FD->getType(); | |||
16059 | if (T.hasNonTrivialObjCLifetime()) { | |||
16060 | SourceLocation loc = FD->getLocation(); | |||
16061 | if (getSourceManager().isInSystemHeader(loc)) { | |||
16062 | if (!FD->hasAttr<UnavailableAttr>()) { | |||
16063 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", | |||
16064 | UnavailableAttr::IR_ARCFieldWithOwnership, loc)); | |||
16065 | } | |||
16066 | } else { | |||
16067 | Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) | |||
16068 | << T->isBlockPointerType() << Record->getTagKind(); | |||
16069 | } | |||
16070 | ObjCFieldLifetimeErrReported = true; | |||
16071 | } | |||
16072 | } else if (getLangOpts().ObjC && | |||
16073 | getLangOpts().getGC() != LangOptions::NonGC && | |||
16074 | Record && !Record->hasObjectMember()) { | |||
16075 | if (FD->getType()->isObjCObjectPointerType() || | |||
16076 | FD->getType().isObjCGCStrong()) | |||
16077 | Record->setHasObjectMember(true); | |||
16078 | else if (Context.getAsArrayType(FD->getType())) { | |||
16079 | QualType BaseType = Context.getBaseElementType(FD->getType()); | |||
16080 | if (BaseType->isRecordType() && | |||
16081 | BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) | |||
16082 | Record->setHasObjectMember(true); | |||
16083 | else if (BaseType->isObjCObjectPointerType() || | |||
16084 | BaseType.isObjCGCStrong()) | |||
16085 | Record->setHasObjectMember(true); | |||
16086 | } | |||
16087 | } | |||
16088 | ||||
16089 | if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { | |||
16090 | QualType FT = FD->getType(); | |||
16091 | if (FT.isNonTrivialToPrimitiveDefaultInitialize()) | |||
16092 | Record->setNonTrivialToPrimitiveDefaultInitialize(true); | |||
16093 | QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); | |||
16094 | if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) | |||
16095 | Record->setNonTrivialToPrimitiveCopy(true); | |||
16096 | if (FT.isDestructedType()) { | |||
16097 | Record->setNonTrivialToPrimitiveDestroy(true); | |||
16098 | Record->setParamDestroyedInCallee(true); | |||
16099 | } | |||
16100 | ||||
16101 | if (const auto *RT = FT->getAs<RecordType>()) { | |||
16102 | if (RT->getDecl()->getArgPassingRestrictions() == | |||
16103 | RecordDecl::APK_CanNeverPassInRegs) | |||
16104 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | |||
16105 | } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) | |||
16106 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | |||
16107 | } | |||
16108 | ||||
16109 | if (Record && FD->getType().isVolatileQualified()) | |||
16110 | Record->setHasVolatileMember(true); | |||
16111 | // Keep track of the number of named members. | |||
16112 | if (FD->getIdentifier()) | |||
16113 | ++NumNamedMembers; | |||
16114 | } | |||
16115 | ||||
16116 | // Okay, we successfully defined 'Record'. | |||
16117 | if (Record) { | |||
16118 | bool Completed = false; | |||
16119 | if (CXXRecord) { | |||
16120 | if (!CXXRecord->isInvalidDecl()) { | |||
16121 | // Set access bits correctly on the directly-declared conversions. | |||
16122 | for (CXXRecordDecl::conversion_iterator | |||
16123 | I = CXXRecord->conversion_begin(), | |||
16124 | E = CXXRecord->conversion_end(); I != E; ++I) | |||
16125 | I.setAccess((*I)->getAccess()); | |||
16126 | } | |||
16127 | ||||
16128 | if (!CXXRecord->isDependentType()) { | |||
16129 | // Add any implicitly-declared members to this class. | |||
16130 | AddImplicitlyDeclaredMembersToClass(CXXRecord); | |||
16131 | ||||
16132 | if (!CXXRecord->isInvalidDecl()) { | |||
16133 | // If we have virtual base classes, we may end up finding multiple | |||
16134 | // final overriders for a given virtual function. Check for this | |||
16135 | // problem now. | |||
16136 | if (CXXRecord->getNumVBases()) { | |||
16137 | CXXFinalOverriderMap FinalOverriders; | |||
16138 | CXXRecord->getFinalOverriders(FinalOverriders); | |||
16139 | ||||
16140 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | |||
16141 | MEnd = FinalOverriders.end(); | |||
16142 | M != MEnd; ++M) { | |||
16143 | for (OverridingMethods::iterator SO = M->second.begin(), | |||
16144 | SOEnd = M->second.end(); | |||
16145 | SO != SOEnd; ++SO) { | |||
16146 | assert(SO->second.size() > 0 &&((SO->second.size() > 0 && "Virtual function without overriding functions?" ) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16147, __PRETTY_FUNCTION__)) | |||
16147 | "Virtual function without overriding functions?")((SO->second.size() > 0 && "Virtual function without overriding functions?" ) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16147, __PRETTY_FUNCTION__)); | |||
16148 | if (SO->second.size() == 1) | |||
16149 | continue; | |||
16150 | ||||
16151 | // C++ [class.virtual]p2: | |||
16152 | // In a derived class, if a virtual member function of a base | |||
16153 | // class subobject has more than one final overrider the | |||
16154 | // program is ill-formed. | |||
16155 | Diag(Record->getLocation(), diag::err_multiple_final_overriders) | |||
16156 | << (const NamedDecl *)M->first << Record; | |||
16157 | Diag(M->first->getLocation(), | |||
16158 | diag::note_overridden_virtual_function); | |||
16159 | for (OverridingMethods::overriding_iterator | |||
16160 | OM = SO->second.begin(), | |||
16161 | OMEnd = SO->second.end(); | |||
16162 | OM != OMEnd; ++OM) | |||
16163 | Diag(OM->Method->getLocation(), diag::note_final_overrider) | |||
16164 | << (const NamedDecl *)M->first << OM->Method->getParent(); | |||
16165 | ||||
16166 | Record->setInvalidDecl(); | |||
16167 | } | |||
16168 | } | |||
16169 | CXXRecord->completeDefinition(&FinalOverriders); | |||
16170 | Completed = true; | |||
16171 | } | |||
16172 | } | |||
16173 | } | |||
16174 | } | |||
16175 | ||||
16176 | if (!Completed) | |||
16177 | Record->completeDefinition(); | |||
16178 | ||||
16179 | // Handle attributes before checking the layout. | |||
16180 | ProcessDeclAttributeList(S, Record, Attrs); | |||
16181 | ||||
16182 | // We may have deferred checking for a deleted destructor. Check now. | |||
16183 | if (CXXRecord) { | |||
16184 | auto *Dtor = CXXRecord->getDestructor(); | |||
16185 | if (Dtor && Dtor->isImplicit() && | |||
16186 | ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { | |||
16187 | CXXRecord->setImplicitDestructorIsDeleted(); | |||
16188 | SetDeclDeleted(Dtor, CXXRecord->getLocation()); | |||
16189 | } | |||
16190 | } | |||
16191 | ||||
16192 | if (Record->hasAttrs()) { | |||
16193 | CheckAlignasUnderalignment(Record); | |||
16194 | ||||
16195 | if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) | |||
16196 | checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), | |||
16197 | IA->getRange(), IA->getBestCase(), | |||
16198 | IA->getSemanticSpelling()); | |||
16199 | } | |||
16200 | ||||
16201 | // Check if the structure/union declaration is a type that can have zero | |||
16202 | // size in C. For C this is a language extension, for C++ it may cause | |||
16203 | // compatibility problems. | |||
16204 | bool CheckForZeroSize; | |||
16205 | if (!getLangOpts().CPlusPlus) { | |||
16206 | CheckForZeroSize = true; | |||
16207 | } else { | |||
16208 | // For C++ filter out types that cannot be referenced in C code. | |||
16209 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); | |||
16210 | CheckForZeroSize = | |||
16211 | CXXRecord->getLexicalDeclContext()->isExternCContext() && | |||
16212 | !CXXRecord->isDependentType() && | |||
16213 | CXXRecord->isCLike(); | |||
16214 | } | |||
16215 | if (CheckForZeroSize) { | |||
16216 | bool ZeroSize = true; | |||
16217 | bool IsEmpty = true; | |||
16218 | unsigned NonBitFields = 0; | |||
16219 | for (RecordDecl::field_iterator I = Record->field_begin(), | |||
16220 | E = Record->field_end(); | |||
16221 | (NonBitFields == 0 || ZeroSize) && I != E; ++I) { | |||
16222 | IsEmpty = false; | |||
16223 | if (I->isUnnamedBitfield()) { | |||
16224 | if (!I->isZeroLengthBitField(Context)) | |||
16225 | ZeroSize = false; | |||
16226 | } else { | |||
16227 | ++NonBitFields; | |||
16228 | QualType FieldType = I->getType(); | |||
16229 | if (FieldType->isIncompleteType() || | |||
16230 | !Context.getTypeSizeInChars(FieldType).isZero()) | |||
16231 | ZeroSize = false; | |||
16232 | } | |||
16233 | } | |||
16234 | ||||
16235 | // Empty structs are an extension in C (C99 6.7.2.1p7). They are | |||
16236 | // allowed in C++, but warn if its declaration is inside | |||
16237 | // extern "C" block. | |||
16238 | if (ZeroSize) { | |||
16239 | Diag(RecLoc, getLangOpts().CPlusPlus ? | |||
16240 | diag::warn_zero_size_struct_union_in_extern_c : | |||
16241 | diag::warn_zero_size_struct_union_compat) | |||
16242 | << IsEmpty << Record->isUnion() << (NonBitFields > 1); | |||
16243 | } | |||
16244 | ||||
16245 | // Structs without named members are extension in C (C99 6.7.2.1p7), | |||
16246 | // but are accepted by GCC. | |||
16247 | if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { | |||
16248 | Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : | |||
16249 | diag::ext_no_named_members_in_struct_union) | |||
16250 | << Record->isUnion(); | |||
16251 | } | |||
16252 | } | |||
16253 | } else { | |||
16254 | ObjCIvarDecl **ClsFields = | |||
16255 | reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); | |||
16256 | if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { | |||
16257 | ID->setEndOfDefinitionLoc(RBrac); | |||
16258 | // Add ivar's to class's DeclContext. | |||
16259 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | |||
16260 | ClsFields[i]->setLexicalDeclContext(ID); | |||
16261 | ID->addDecl(ClsFields[i]); | |||
16262 | } | |||
16263 | // Must enforce the rule that ivars in the base classes may not be | |||
16264 | // duplicates. | |||
16265 | if (ID->getSuperClass()) | |||
16266 | DiagnoseDuplicateIvars(ID, ID->getSuperClass()); | |||
16267 | } else if (ObjCImplementationDecl *IMPDecl = | |||
16268 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | |||
16269 | assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl" ) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16269, __PRETTY_FUNCTION__)); | |||
16270 | for (unsigned I = 0, N = RecFields.size(); I != N; ++I) | |||
16271 | // Ivar declared in @implementation never belongs to the implementation. | |||
16272 | // Only it is in implementation's lexical context. | |||
16273 | ClsFields[I]->setLexicalDeclContext(IMPDecl); | |||
16274 | CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); | |||
16275 | IMPDecl->setIvarLBraceLoc(LBrac); | |||
16276 | IMPDecl->setIvarRBraceLoc(RBrac); | |||
16277 | } else if (ObjCCategoryDecl *CDecl = | |||
16278 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | |||
16279 | // case of ivars in class extension; all other cases have been | |||
16280 | // reported as errors elsewhere. | |||
16281 | // FIXME. Class extension does not have a LocEnd field. | |||
16282 | // CDecl->setLocEnd(RBrac); | |||
16283 | // Add ivar's to class extension's DeclContext. | |||
16284 | // Diagnose redeclaration of private ivars. | |||
16285 | ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); | |||
16286 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | |||
16287 | if (IDecl) { | |||
16288 | if (const ObjCIvarDecl *ClsIvar = | |||
16289 | IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { | |||
16290 | Diag(ClsFields[i]->getLocation(), | |||
16291 | diag::err_duplicate_ivar_declaration); | |||
16292 | Diag(ClsIvar->getLocation(), diag::note_previous_definition); | |||
16293 | continue; | |||
16294 | } | |||
16295 | for (const auto *Ext : IDecl->known_extensions()) { | |||
16296 | if (const ObjCIvarDecl *ClsExtIvar | |||
16297 | = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { | |||
16298 | Diag(ClsFields[i]->getLocation(), | |||
16299 | diag::err_duplicate_ivar_declaration); | |||
16300 | Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); | |||
16301 | continue; | |||
16302 | } | |||
16303 | } | |||
16304 | } | |||
16305 | ClsFields[i]->setLexicalDeclContext(CDecl); | |||
16306 | CDecl->addDecl(ClsFields[i]); | |||
16307 | } | |||
16308 | CDecl->setIvarLBraceLoc(LBrac); | |||
16309 | CDecl->setIvarRBraceLoc(RBrac); | |||
16310 | } | |||
16311 | } | |||
16312 | } | |||
16313 | ||||
16314 | /// Determine whether the given integral value is representable within | |||
16315 | /// the given type T. | |||
16316 | static bool isRepresentableIntegerValue(ASTContext &Context, | |||
16317 | llvm::APSInt &Value, | |||
16318 | QualType T) { | |||
16319 | assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16320, __PRETTY_FUNCTION__)) | |||
16320 | "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16320, __PRETTY_FUNCTION__)); | |||
16321 | unsigned BitWidth = Context.getIntWidth(T); | |||
16322 | ||||
16323 | if (Value.isUnsigned() || Value.isNonNegative()) { | |||
16324 | if (T->isSignedIntegerOrEnumerationType()) | |||
16325 | --BitWidth; | |||
16326 | return Value.getActiveBits() <= BitWidth; | |||
16327 | } | |||
16328 | return Value.getMinSignedBits() <= BitWidth; | |||
16329 | } | |||
16330 | ||||
16331 | // Given an integral type, return the next larger integral type | |||
16332 | // (or a NULL type of no such type exists). | |||
16333 | static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { | |||
16334 | // FIXME: Int128/UInt128 support, which also needs to be introduced into | |||
16335 | // enum checking below. | |||
16336 | assert((T->isIntegralType(Context) ||(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16337, __PRETTY_FUNCTION__)) | |||
16337 | T->isEnumeralType()) && "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16337, __PRETTY_FUNCTION__)); | |||
16338 | const unsigned NumTypes = 4; | |||
16339 | QualType SignedIntegralTypes[NumTypes] = { | |||
16340 | Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy | |||
16341 | }; | |||
16342 | QualType UnsignedIntegralTypes[NumTypes] = { | |||
16343 | Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, | |||
16344 | Context.UnsignedLongLongTy | |||
16345 | }; | |||
16346 | ||||
16347 | unsigned BitWidth = Context.getTypeSize(T); | |||
16348 | QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes | |||
16349 | : UnsignedIntegralTypes; | |||
16350 | for (unsigned I = 0; I != NumTypes; ++I) | |||
16351 | if (Context.getTypeSize(Types[I]) > BitWidth) | |||
16352 | return Types[I]; | |||
16353 | ||||
16354 | return QualType(); | |||
16355 | } | |||
16356 | ||||
16357 | EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, | |||
16358 | EnumConstantDecl *LastEnumConst, | |||
16359 | SourceLocation IdLoc, | |||
16360 | IdentifierInfo *Id, | |||
16361 | Expr *Val) { | |||
16362 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | |||
16363 | llvm::APSInt EnumVal(IntWidth); | |||
16364 | QualType EltTy; | |||
16365 | ||||
16366 | if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) | |||
16367 | Val = nullptr; | |||
16368 | ||||
16369 | if (Val) | |||
16370 | Val = DefaultLvalueConversion(Val).get(); | |||
16371 | ||||
16372 | if (Val) { | |||
16373 | if (Enum->isDependentType() || Val->isTypeDependent()) | |||
16374 | EltTy = Context.DependentTy; | |||
16375 | else { | |||
16376 | if (getLangOpts().CPlusPlus11 && Enum->isFixed() && | |||
16377 | !getLangOpts().MSVCCompat) { | |||
16378 | // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the | |||
16379 | // constant-expression in the enumerator-definition shall be a converted | |||
16380 | // constant expression of the underlying type. | |||
16381 | EltTy = Enum->getIntegerType(); | |||
16382 | ExprResult Converted = | |||
16383 | CheckConvertedConstantExpression(Val, EltTy, EnumVal, | |||
16384 | CCEK_Enumerator); | |||
16385 | if (Converted.isInvalid()) | |||
16386 | Val = nullptr; | |||
16387 | else | |||
16388 | Val = Converted.get(); | |||
16389 | } else if (!Val->isValueDependent() && | |||
16390 | !(Val = VerifyIntegerConstantExpression(Val, | |||
16391 | &EnumVal).get())) { | |||
16392 | // C99 6.7.2.2p2: Make sure we have an integer constant expression. | |||
16393 | } else { | |||
16394 | if (Enum->isComplete()) { | |||
16395 | EltTy = Enum->getIntegerType(); | |||
16396 | ||||
16397 | // In Obj-C and Microsoft mode, require the enumeration value to be | |||
16398 | // representable in the underlying type of the enumeration. In C++11, | |||
16399 | // we perform a non-narrowing conversion as part of converted constant | |||
16400 | // expression checking. | |||
16401 | if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | |||
16402 | if (getLangOpts().MSVCCompat) { | |||
16403 | Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; | |||
16404 | Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); | |||
16405 | } else | |||
16406 | Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; | |||
16407 | } else | |||
16408 | Val = ImpCastExprToType(Val, EltTy, | |||
16409 | EltTy->isBooleanType() ? | |||
16410 | CK_IntegralToBoolean : CK_IntegralCast) | |||
16411 | .get(); | |||
16412 | } else if (getLangOpts().CPlusPlus) { | |||
16413 | // C++11 [dcl.enum]p5: | |||
16414 | // If the underlying type is not fixed, the type of each enumerator | |||
16415 | // is the type of its initializing value: | |||
16416 | // - If an initializer is specified for an enumerator, the | |||
16417 | // initializing value has the same type as the expression. | |||
16418 | EltTy = Val->getType(); | |||
16419 | } else { | |||
16420 | // C99 6.7.2.2p2: | |||
16421 | // The expression that defines the value of an enumeration constant | |||
16422 | // shall be an integer constant expression that has a value | |||
16423 | // representable as an int. | |||
16424 | ||||
16425 | // Complain if the value is not representable in an int. | |||
16426 | if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) | |||
16427 | Diag(IdLoc, diag::ext_enum_value_not_int) | |||
16428 | << EnumVal.toString(10) << Val->getSourceRange() | |||
16429 | << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); | |||
16430 | else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { | |||
16431 | // Force the type of the expression to 'int'. | |||
16432 | Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); | |||
16433 | } | |||
16434 | EltTy = Val->getType(); | |||
16435 | } | |||
16436 | } | |||
16437 | } | |||
16438 | } | |||
16439 | ||||
16440 | if (!Val) { | |||
16441 | if (Enum->isDependentType()) | |||
16442 | EltTy = Context.DependentTy; | |||
16443 | else if (!LastEnumConst) { | |||
16444 | // C++0x [dcl.enum]p5: | |||
16445 | // If the underlying type is not fixed, the type of each enumerator | |||
16446 | // is the type of its initializing value: | |||
16447 | // - If no initializer is specified for the first enumerator, the | |||
16448 | // initializing value has an unspecified integral type. | |||
16449 | // | |||
16450 | // GCC uses 'int' for its unspecified integral type, as does | |||
16451 | // C99 6.7.2.2p3. | |||
16452 | if (Enum->isFixed()) { | |||
16453 | EltTy = Enum->getIntegerType(); | |||
16454 | } | |||
16455 | else { | |||
16456 | EltTy = Context.IntTy; | |||
16457 | } | |||
16458 | } else { | |||
16459 | // Assign the last value + 1. | |||
16460 | EnumVal = LastEnumConst->getInitVal(); | |||
16461 | ++EnumVal; | |||
16462 | EltTy = LastEnumConst->getType(); | |||
16463 | ||||
16464 | // Check for overflow on increment. | |||
16465 | if (EnumVal < LastEnumConst->getInitVal()) { | |||
16466 | // C++0x [dcl.enum]p5: | |||
16467 | // If the underlying type is not fixed, the type of each enumerator | |||
16468 | // is the type of its initializing value: | |||
16469 | // | |||
16470 | // - Otherwise the type of the initializing value is the same as | |||
16471 | // the type of the initializing value of the preceding enumerator | |||
16472 | // unless the incremented value is not representable in that type, | |||
16473 | // in which case the type is an unspecified integral type | |||
16474 | // sufficient to contain the incremented value. If no such type | |||
16475 | // exists, the program is ill-formed. | |||
16476 | QualType T = getNextLargerIntegralType(Context, EltTy); | |||
16477 | if (T.isNull() || Enum->isFixed()) { | |||
16478 | // There is no integral type larger enough to represent this | |||
16479 | // value. Complain, then allow the value to wrap around. | |||
16480 | EnumVal = LastEnumConst->getInitVal(); | |||
16481 | EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); | |||
16482 | ++EnumVal; | |||
16483 | if (Enum->isFixed()) | |||
16484 | // When the underlying type is fixed, this is ill-formed. | |||
16485 | Diag(IdLoc, diag::err_enumerator_wrapped) | |||
16486 | << EnumVal.toString(10) | |||
16487 | << EltTy; | |||
16488 | else | |||
16489 | Diag(IdLoc, diag::ext_enumerator_increment_too_large) | |||
16490 | << EnumVal.toString(10); | |||
16491 | } else { | |||
16492 | EltTy = T; | |||
16493 | } | |||
16494 | ||||
16495 | // Retrieve the last enumerator's value, extent that type to the | |||
16496 | // type that is supposed to be large enough to represent the incremented | |||
16497 | // value, then increment. | |||
16498 | EnumVal = LastEnumConst->getInitVal(); | |||
16499 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | |||
16500 | EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); | |||
16501 | ++EnumVal; | |||
16502 | ||||
16503 | // If we're not in C++, diagnose the overflow of enumerator values, | |||
16504 | // which in C99 means that the enumerator value is not representable in | |||
16505 | // an int (C99 6.7.2.2p2). However, we support GCC's extension that | |||
16506 | // permits enumerator values that are representable in some larger | |||
16507 | // integral type. | |||
16508 | if (!getLangOpts().CPlusPlus && !T.isNull()) | |||
16509 | Diag(IdLoc, diag::warn_enum_value_overflow); | |||
16510 | } else if (!getLangOpts().CPlusPlus && | |||
16511 | !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | |||
16512 | // Enforce C99 6.7.2.2p2 even when we compute the next value. | |||
16513 | Diag(IdLoc, diag::ext_enum_value_not_int) | |||
16514 | << EnumVal.toString(10) << 1; | |||
16515 | } | |||
16516 | } | |||
16517 | } | |||
16518 | ||||
16519 | if (!EltTy->isDependentType()) { | |||
16520 | // Make the enumerator value match the signedness and size of the | |||
16521 | // enumerator's type. | |||
16522 | EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); | |||
16523 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | |||
16524 | } | |||
16525 | ||||
16526 | return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, | |||
16527 | Val, EnumVal); | |||
16528 | } | |||
16529 | ||||
16530 | Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, | |||
16531 | SourceLocation IILoc) { | |||
16532 | if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || | |||
16533 | !getLangOpts().CPlusPlus) | |||
16534 | return SkipBodyInfo(); | |||
16535 | ||||
16536 | // We have an anonymous enum definition. Look up the first enumerator to | |||
16537 | // determine if we should merge the definition with an existing one and | |||
16538 | // skip the body. | |||
16539 | NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, | |||
16540 | forRedeclarationInCurContext()); | |||
16541 | auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); | |||
16542 | if (!PrevECD) | |||
16543 | return SkipBodyInfo(); | |||
16544 | ||||
16545 | EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); | |||
16546 | NamedDecl *Hidden; | |||
16547 | if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { | |||
16548 | SkipBodyInfo Skip; | |||
16549 | Skip.Previous = Hidden; | |||
16550 | return Skip; | |||
16551 | } | |||
16552 | ||||
16553 | return SkipBodyInfo(); | |||
16554 | } | |||
16555 | ||||
16556 | Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, | |||
16557 | SourceLocation IdLoc, IdentifierInfo *Id, | |||
16558 | const ParsedAttributesView &Attrs, | |||
16559 | SourceLocation EqualLoc, Expr *Val) { | |||
16560 | EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); | |||
16561 | EnumConstantDecl *LastEnumConst = | |||
16562 | cast_or_null<EnumConstantDecl>(lastEnumConst); | |||
16563 | ||||
16564 | // The scope passed in may not be a decl scope. Zip up the scope tree until | |||
16565 | // we find one that is. | |||
16566 | S = getNonFieldDeclScope(S); | |||
16567 | ||||
16568 | // Verify that there isn't already something declared with this name in this | |||
16569 | // scope. | |||
16570 | LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); | |||
16571 | LookupName(R, S); | |||
16572 | NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); | |||
16573 | ||||
16574 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | |||
16575 | // Maybe we will complain about the shadowed template parameter. | |||
16576 | DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); | |||
16577 | // Just pretend that we didn't see the previous declaration. | |||
16578 | PrevDecl = nullptr; | |||
16579 | } | |||
16580 | ||||
16581 | // C++ [class.mem]p15: | |||
16582 | // If T is the name of a class, then each of the following shall have a name | |||
16583 | // different from T: | |||
16584 | // - every enumerator of every member of class T that is an unscoped | |||
16585 | // enumerated type | |||
16586 | if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) | |||
16587 | DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), | |||
16588 | DeclarationNameInfo(Id, IdLoc)); | |||
16589 | ||||
16590 | EnumConstantDecl *New = | |||
16591 | CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); | |||
16592 | if (!New) | |||
16593 | return nullptr; | |||
16594 | ||||
16595 | if (PrevDecl) { | |||
16596 | if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { | |||
16597 | // Check for other kinds of shadowing not already handled. | |||
16598 | CheckShadow(New, PrevDecl, R); | |||
16599 | } | |||
16600 | ||||
16601 | // When in C++, we may get a TagDecl with the same name; in this case the | |||
16602 | // enum constant will 'hide' the tag. | |||
16603 | assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!") ? static_cast<void> (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16604, __PRETTY_FUNCTION__)) | |||
16604 | "Received TagDecl when not in C++!")(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!") ? static_cast<void> (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16604, __PRETTY_FUNCTION__)); | |||
16605 | if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { | |||
16606 | if (isa<EnumConstantDecl>(PrevDecl)) | |||
16607 | Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; | |||
16608 | else | |||
16609 | Diag(IdLoc, diag::err_redefinition) << Id; | |||
16610 | notePreviousDefinition(PrevDecl, IdLoc); | |||
16611 | return nullptr; | |||
16612 | } | |||
16613 | } | |||
16614 | ||||
16615 | // Process attributes. | |||
16616 | ProcessDeclAttributeList(S, New, Attrs); | |||
16617 | AddPragmaAttributes(S, New); | |||
16618 | ||||
16619 | // Register this decl in the current scope stack. | |||
16620 | New->setAccess(TheEnumDecl->getAccess()); | |||
16621 | PushOnScopeChains(New, S); | |||
16622 | ||||
16623 | ActOnDocumentableDecl(New); | |||
16624 | ||||
16625 | return New; | |||
16626 | } | |||
16627 | ||||
16628 | // Returns true when the enum initial expression does not trigger the | |||
16629 | // duplicate enum warning. A few common cases are exempted as follows: | |||
16630 | // Element2 = Element1 | |||
16631 | // Element2 = Element1 + 1 | |||
16632 | // Element2 = Element1 - 1 | |||
16633 | // Where Element2 and Element1 are from the same enum. | |||
16634 | static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { | |||
16635 | Expr *InitExpr = ECD->getInitExpr(); | |||
16636 | if (!InitExpr) | |||
16637 | return true; | |||
16638 | InitExpr = InitExpr->IgnoreImpCasts(); | |||
16639 | ||||
16640 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { | |||
16641 | if (!BO->isAdditiveOp()) | |||
16642 | return true; | |||
16643 | IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); | |||
16644 | if (!IL) | |||
16645 | return true; | |||
16646 | if (IL->getValue() != 1) | |||
16647 | return true; | |||
16648 | ||||
16649 | InitExpr = BO->getLHS(); | |||
16650 | } | |||
16651 | ||||
16652 | // This checks if the elements are from the same enum. | |||
16653 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); | |||
16654 | if (!DRE) | |||
16655 | return true; | |||
16656 | ||||
16657 | EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); | |||
16658 | if (!EnumConstant) | |||
16659 | return true; | |||
16660 | ||||
16661 | if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != | |||
16662 | Enum) | |||
16663 | return true; | |||
16664 | ||||
16665 | return false; | |||
16666 | } | |||
16667 | ||||
16668 | // Emits a warning when an element is implicitly set a value that | |||
16669 | // a previous element has already been set to. | |||
16670 | static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, | |||
16671 | EnumDecl *Enum, QualType EnumType) { | |||
16672 | // Avoid anonymous enums | |||
16673 | if (!Enum->getIdentifier()) | |||
16674 | return; | |||
16675 | ||||
16676 | // Only check for small enums. | |||
16677 | if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) | |||
16678 | return; | |||
16679 | ||||
16680 | if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) | |||
16681 | return; | |||
16682 | ||||
16683 | typedef SmallVector<EnumConstantDecl *, 3> ECDVector; | |||
16684 | typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; | |||
16685 | ||||
16686 | typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; | |||
16687 | typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; | |||
16688 | ||||
16689 | // Use int64_t as a key to avoid needing special handling for DenseMap keys. | |||
16690 | auto EnumConstantToKey = [](const EnumConstantDecl *D) { | |||
16691 | llvm::APSInt Val = D->getInitVal(); | |||
16692 | return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); | |||
16693 | }; | |||
16694 | ||||
16695 | DuplicatesVector DupVector; | |||
16696 | ValueToVectorMap EnumMap; | |||
16697 | ||||
16698 | // Populate the EnumMap with all values represented by enum constants without | |||
16699 | // an initializer. | |||
16700 | for (auto *Element : Elements) { | |||
16701 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); | |||
16702 | ||||
16703 | // Null EnumConstantDecl means a previous diagnostic has been emitted for | |||
16704 | // this constant. Skip this enum since it may be ill-formed. | |||
16705 | if (!ECD) { | |||
16706 | return; | |||
16707 | } | |||
16708 | ||||
16709 | // Constants with initalizers are handled in the next loop. | |||
16710 | if (ECD->getInitExpr()) | |||
16711 | continue; | |||
16712 | ||||
16713 | // Duplicate values are handled in the next loop. | |||
16714 | EnumMap.insert({EnumConstantToKey(ECD), ECD}); | |||
16715 | } | |||
16716 | ||||
16717 | if (EnumMap.size() == 0) | |||
16718 | return; | |||
16719 | ||||
16720 | // Create vectors for any values that has duplicates. | |||
16721 | for (auto *Element : Elements) { | |||
16722 | // The last loop returned if any constant was null. | |||
16723 | EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); | |||
16724 | if (!ValidDuplicateEnum(ECD, Enum)) | |||
16725 | continue; | |||
16726 | ||||
16727 | auto Iter = EnumMap.find(EnumConstantToKey(ECD)); | |||
16728 | if (Iter == EnumMap.end()) | |||
16729 | continue; | |||
16730 | ||||
16731 | DeclOrVector& Entry = Iter->second; | |||
16732 | if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { | |||
16733 | // Ensure constants are different. | |||
16734 | if (D == ECD) | |||
16735 | continue; | |||
16736 | ||||
16737 | // Create new vector and push values onto it. | |||
16738 | auto Vec = llvm::make_unique<ECDVector>(); | |||
16739 | Vec->push_back(D); | |||
16740 | Vec->push_back(ECD); | |||
16741 | ||||
16742 | // Update entry to point to the duplicates vector. | |||
16743 | Entry = Vec.get(); | |||
16744 | ||||
16745 | // Store the vector somewhere we can consult later for quick emission of | |||
16746 | // diagnostics. | |||
16747 | DupVector.emplace_back(std::move(Vec)); | |||
16748 | continue; | |||
16749 | } | |||
16750 | ||||
16751 | ECDVector *Vec = Entry.get<ECDVector*>(); | |||
16752 | // Make sure constants are not added more than once. | |||
16753 | if (*Vec->begin() == ECD) | |||
16754 | continue; | |||
16755 | ||||
16756 | Vec->push_back(ECD); | |||
16757 | } | |||
16758 | ||||
16759 | // Emit diagnostics. | |||
16760 | for (const auto &Vec : DupVector) { | |||
16761 | assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")((Vec->size() > 1 && "ECDVector should have at least 2 elements." ) ? static_cast<void> (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16761, __PRETTY_FUNCTION__)); | |||
16762 | ||||
16763 | // Emit warning for one enum constant. | |||
16764 | auto *FirstECD = Vec->front(); | |||
16765 | S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) | |||
16766 | << FirstECD << FirstECD->getInitVal().toString(10) | |||
16767 | << FirstECD->getSourceRange(); | |||
16768 | ||||
16769 | // Emit one note for each of the remaining enum constants with | |||
16770 | // the same value. | |||
16771 | for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) | |||
16772 | S.Diag(ECD->getLocation(), diag::note_duplicate_element) | |||
16773 | << ECD << ECD->getInitVal().toString(10) | |||
16774 | << ECD->getSourceRange(); | |||
16775 | } | |||
16776 | } | |||
16777 | ||||
16778 | bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, | |||
16779 | bool AllowMask) const { | |||
16780 | assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")((ED->isClosedFlag() && "looking for value in non-flag or open enum" ) ? static_cast<void> (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16780, __PRETTY_FUNCTION__)); | |||
16781 | assert(ED->isCompleteDefinition() && "expected enum definition")((ED->isCompleteDefinition() && "expected enum definition" ) ? static_cast<void> (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16781, __PRETTY_FUNCTION__)); | |||
16782 | ||||
16783 | auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); | |||
16784 | llvm::APInt &FlagBits = R.first->second; | |||
16785 | ||||
16786 | if (R.second) { | |||
16787 | for (auto *E : ED->enumerators()) { | |||
16788 | const auto &EVal = E->getInitVal(); | |||
16789 | // Only single-bit enumerators introduce new flag values. | |||
16790 | if (EVal.isPowerOf2()) | |||
16791 | FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; | |||
16792 | } | |||
16793 | } | |||
16794 | ||||
16795 | // A value is in a flag enum if either its bits are a subset of the enum's | |||
16796 | // flag bits (the first condition) or we are allowing masks and the same is | |||
16797 | // true of its complement (the second condition). When masks are allowed, we | |||
16798 | // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. | |||
16799 | // | |||
16800 | // While it's true that any value could be used as a mask, the assumption is | |||
16801 | // that a mask will have all of the insignificant bits set. Anything else is | |||
16802 | // likely a logic error. | |||
16803 | llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); | |||
16804 | return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); | |||
16805 | } | |||
16806 | ||||
16807 | void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, | |||
16808 | Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, | |||
16809 | const ParsedAttributesView &Attrs) { | |||
16810 | EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); | |||
16811 | QualType EnumType = Context.getTypeDeclType(Enum); | |||
16812 | ||||
16813 | ProcessDeclAttributeList(S, Enum, Attrs); | |||
16814 | ||||
16815 | if (Enum->isDependentType()) { | |||
16816 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | |||
16817 | EnumConstantDecl *ECD = | |||
16818 | cast_or_null<EnumConstantDecl>(Elements[i]); | |||
16819 | if (!ECD) continue; | |||
16820 | ||||
16821 | ECD->setType(EnumType); | |||
16822 | } | |||
16823 | ||||
16824 | Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); | |||
16825 | return; | |||
16826 | } | |||
16827 | ||||
16828 | // TODO: If the result value doesn't fit in an int, it must be a long or long | |||
16829 | // long value. ISO C does not support this, but GCC does as an extension, | |||
16830 | // emit a warning. | |||
16831 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | |||
16832 | unsigned CharWidth = Context.getTargetInfo().getCharWidth(); | |||
16833 | unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); | |||
16834 | ||||
16835 | // Verify that all the values are okay, compute the size of the values, and | |||
16836 | // reverse the list. | |||
16837 | unsigned NumNegativeBits = 0; | |||
16838 | unsigned NumPositiveBits = 0; | |||
16839 | ||||
16840 | // Keep track of whether all elements have type int. | |||
16841 | bool AllElementsInt = true; | |||
16842 | ||||
16843 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | |||
16844 | EnumConstantDecl *ECD = | |||
16845 | cast_or_null<EnumConstantDecl>(Elements[i]); | |||
16846 | if (!ECD) continue; // Already issued a diagnostic. | |||
16847 | ||||
16848 | const llvm::APSInt &InitVal = ECD->getInitVal(); | |||
16849 | ||||
16850 | // Keep track of the size of positive and negative values. | |||
16851 | if (InitVal.isUnsigned() || InitVal.isNonNegative()) | |||
16852 | NumPositiveBits = std::max(NumPositiveBits, | |||
16853 | (unsigned)InitVal.getActiveBits()); | |||
16854 | else | |||
16855 | NumNegativeBits = std::max(NumNegativeBits, | |||
16856 | (unsigned)InitVal.getMinSignedBits()); | |||
16857 | ||||
16858 | // Keep track of whether every enum element has type int (very common). | |||
16859 | if (AllElementsInt) | |||
16860 | AllElementsInt = ECD->getType() == Context.IntTy; | |||
16861 | } | |||
16862 | ||||
16863 | // Figure out the type that should be used for this enum. | |||
16864 | QualType BestType; | |||
16865 | unsigned BestWidth; | |||
16866 | ||||
16867 | // C++0x N3000 [conv.prom]p3: | |||
16868 | // An rvalue of an unscoped enumeration type whose underlying | |||
16869 | // type is not fixed can be converted to an rvalue of the first | |||
16870 | // of the following types that can represent all the values of | |||
16871 | // the enumeration: int, unsigned int, long int, unsigned long | |||
16872 | // int, long long int, or unsigned long long int. | |||
16873 | // C99 6.4.4.3p2: | |||
16874 | // An identifier declared as an enumeration constant has type int. | |||
16875 | // The C99 rule is modified by a gcc extension | |||
16876 | QualType BestPromotionType; | |||
16877 | ||||
16878 | bool Packed = Enum->hasAttr<PackedAttr>(); | |||
16879 | // -fshort-enums is the equivalent to specifying the packed attribute on all | |||
16880 | // enum definitions. | |||
16881 | if (LangOpts.ShortEnums) | |||
16882 | Packed = true; | |||
16883 | ||||
16884 | // If the enum already has a type because it is fixed or dictated by the | |||
16885 | // target, promote that type instead of analyzing the enumerators. | |||
16886 | if (Enum->isComplete()) { | |||
16887 | BestType = Enum->getIntegerType(); | |||
16888 | if (BestType->isPromotableIntegerType()) | |||
16889 | BestPromotionType = Context.getPromotedIntegerType(BestType); | |||
16890 | else | |||
16891 | BestPromotionType = BestType; | |||
16892 | ||||
16893 | BestWidth = Context.getIntWidth(BestType); | |||
16894 | } | |||
16895 | else if (NumNegativeBits) { | |||
16896 | // If there is a negative value, figure out the smallest integer type (of | |||
16897 | // int/long/longlong) that fits. | |||
16898 | // If it's packed, check also if it fits a char or a short. | |||
16899 | if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { | |||
16900 | BestType = Context.SignedCharTy; | |||
16901 | BestWidth = CharWidth; | |||
16902 | } else if (Packed && NumNegativeBits <= ShortWidth && | |||
16903 | NumPositiveBits < ShortWidth) { | |||
16904 | BestType = Context.ShortTy; | |||
16905 | BestWidth = ShortWidth; | |||
16906 | } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { | |||
16907 | BestType = Context.IntTy; | |||
16908 | BestWidth = IntWidth; | |||
16909 | } else { | |||
16910 | BestWidth = Context.getTargetInfo().getLongWidth(); | |||
16911 | ||||
16912 | if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { | |||
16913 | BestType = Context.LongTy; | |||
16914 | } else { | |||
16915 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | |||
16916 | ||||
16917 | if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) | |||
16918 | Diag(Enum->getLocation(), diag::ext_enum_too_large); | |||
16919 | BestType = Context.LongLongTy; | |||
16920 | } | |||
16921 | } | |||
16922 | BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); | |||
16923 | } else { | |||
16924 | // If there is no negative value, figure out the smallest type that fits | |||
16925 | // all of the enumerator values. | |||
16926 | // If it's packed, check also if it fits a char or a short. | |||
16927 | if (Packed && NumPositiveBits <= CharWidth) { | |||
16928 | BestType = Context.UnsignedCharTy; | |||
16929 | BestPromotionType = Context.IntTy; | |||
16930 | BestWidth = CharWidth; | |||
16931 | } else if (Packed && NumPositiveBits <= ShortWidth) { | |||
16932 | BestType = Context.UnsignedShortTy; | |||
16933 | BestPromotionType = Context.IntTy; | |||
16934 | BestWidth = ShortWidth; | |||
16935 | } else if (NumPositiveBits <= IntWidth) { | |||
16936 | BestType = Context.UnsignedIntTy; | |||
16937 | BestWidth = IntWidth; | |||
16938 | BestPromotionType | |||
16939 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | |||
16940 | ? Context.UnsignedIntTy : Context.IntTy; | |||
16941 | } else if (NumPositiveBits <= | |||
16942 | (BestWidth = Context.getTargetInfo().getLongWidth())) { | |||
16943 | BestType = Context.UnsignedLongTy; | |||
16944 | BestPromotionType | |||
16945 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | |||
16946 | ? Context.UnsignedLongTy : Context.LongTy; | |||
16947 | } else { | |||
16948 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | |||
16949 | assert(NumPositiveBits <= BestWidth &&((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?" ) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16950, __PRETTY_FUNCTION__)) | |||
16950 | "How could an initializer get larger than ULL?")((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?" ) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Sema/SemaDecl.cpp" , 16950, __PRETTY_FUNCTION__)); | |||
16951 | BestType = Context.UnsignedLongLongTy; | |||
16952 | BestPromotionType | |||
16953 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | |||
16954 | ? Context.UnsignedLongLongTy : Context.LongLongTy; | |||
16955 | } | |||
16956 | } | |||
16957 | ||||
16958 | // Loop over all of the enumerator constants, changing their types to match | |||
16959 | // the type of the enum if needed. | |||
16960 | for (auto *D : Elements) { | |||
16961 | auto *ECD = cast_or_null<EnumConstantDecl>(D); | |||
16962 | if (!ECD) continue; // Already issued a diagnostic. | |||
16963 | ||||
16964 | // Standard C says the enumerators have int type, but we allow, as an | |||
16965 | // extension, the enumerators to be larger than int size. If each | |||
16966 | // enumerator value fits in an int, type it as an int, otherwise type it the | |||
16967 | // same as the enumerator decl itself. This means that in "enum { X = 1U }" | |||
16968 | // that X has type 'int', not 'unsigned'. | |||
16969 | ||||
16970 | // Determine whether the value fits into an int. | |||
16971 | llvm::APSInt InitVal = ECD->getInitVal(); | |||
16972 | ||||
16973 | // If it fits into an integer type, force it. Otherwise force it to match | |||
16974 | // the enum decl type. | |||
16975 | QualType NewTy; | |||
16976 | unsigned NewWidth; | |||
16977 | bool NewSign; | |||
16978 | if (!getLangOpts().CPlusPlus && | |||
16979 | !Enum->isFixed() && | |||
16980 | isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { | |||
16981 | NewTy = Context.IntTy; | |||
16982 | NewWidth = IntWidth; | |||
16983 | NewSign = true; | |||
16984 | } else if (ECD->getType() == BestType) { | |||
16985 | // Already the right type! | |||
16986 | if (getLangOpts().CPlusPlus) | |||
16987 | // C++ [dcl.enum]p4: Following the closing brace of an | |||
16988 | // enum-specifier, each enumerator has the type of its | |||
16989 | // enumeration. | |||
16990 | ECD->setType(EnumType); | |||
16991 | continue; | |||
16992 | } else { | |||
16993 | NewTy = BestType; | |||
16994 | NewWidth = BestWidth; | |||
16995 | NewSign = BestType->isSignedIntegerOrEnumerationType(); | |||
16996 | } | |||
16997 | ||||
16998 | // Adjust the APSInt value. | |||
16999 | InitVal = InitVal.extOrTrunc(NewWidth); | |||
17000 | InitVal.setIsSigned(NewSign); | |||
17001 | ECD->setInitVal(InitVal); | |||
17002 | ||||
17003 | // Adjust the Expr initializer and type. | |||
17004 | if (ECD->getInitExpr() && | |||
17005 | !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) | |||
17006 | ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, | |||
17007 | CK_IntegralCast, | |||
17008 | ECD->getInitExpr(), | |||
17009 | /*base paths*/ nullptr, | |||
17010 | VK_RValue)); | |||
17011 | if (getLangOpts().CPlusPlus) | |||
17012 | // C++ [dcl.enum]p4: Following the closing brace of an | |||
17013 | // enum-specifier, each enumerator has the type of its | |||
17014 | // enumeration. | |||
17015 | ECD->setType(EnumType); | |||
17016 | else | |||
17017 | ECD->setType(NewTy); | |||
17018 | } | |||
17019 | ||||
17020 | Enum->completeDefinition(BestType, BestPromotionType, | |||
17021 | NumPositiveBits, NumNegativeBits); | |||
17022 | ||||
17023 | CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); | |||
17024 | ||||
17025 | if (Enum->isClosedFlag()) { | |||
17026 | for (Decl *D : Elements) { | |||
17027 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); | |||
17028 | if (!ECD) continue; // Already issued a diagnostic. | |||
17029 | ||||
17030 | llvm::APSInt InitVal = ECD->getInitVal(); | |||
17031 | if (InitVal != 0 && !InitVal.isPowerOf2() && | |||
17032 | !IsValueInFlagEnum(Enum, InitVal, true)) | |||
17033 | Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) | |||
17034 | << ECD << Enum; | |||
17035 | } | |||
17036 | } | |||
17037 | ||||
17038 | // Now that the enum type is defined, ensure it's not been underaligned. | |||
17039 | if (Enum->hasAttrs()) | |||
17040 | CheckAlignasUnderalignment(Enum); | |||
17041 | } | |||
17042 | ||||
17043 | Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, | |||
17044 | SourceLocation StartLoc, | |||
17045 | SourceLocation EndLoc) { | |||
17046 | StringLiteral *AsmString = cast<StringLiteral>(expr); | |||
17047 | ||||
17048 | FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, | |||
17049 | AsmString, StartLoc, | |||
17050 | EndLoc); | |||
17051 | CurContext->addDecl(New); | |||
17052 | return New; | |||
17053 | } | |||
17054 | ||||
17055 | void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, | |||
17056 | IdentifierInfo* AliasName, | |||
17057 | SourceLocation PragmaLoc, | |||
17058 | SourceLocation NameLoc, | |||
17059 | SourceLocation AliasNameLoc) { | |||
17060 | NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, | |||
17061 | LookupOrdinaryName); | |||
17062 | AsmLabelAttr *Attr = | |||
17063 | AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); | |||
17064 | ||||
17065 | // If a declaration that: | |||
17066 | // 1) declares a function or a variable | |||
17067 | // 2) has external linkage | |||
17068 | // already exists, add a label attribute to it. | |||
17069 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | |||
17070 | if (isDeclExternC(PrevDecl)) | |||
17071 | PrevDecl->addAttr(Attr); | |||
17072 | else | |||
17073 | Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) | |||
17074 | << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; | |||
17075 | // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. | |||
17076 | } else | |||
17077 | (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); | |||
17078 | } | |||
17079 | ||||
17080 | void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, | |||
17081 | SourceLocation PragmaLoc, | |||
17082 | SourceLocation NameLoc) { | |||
17083 | Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); | |||
17084 | ||||
17085 | if (PrevDecl) { | |||
17086 | PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); | |||
17087 | } else { | |||
17088 | (void)WeakUndeclaredIdentifiers.insert( | |||
17089 | std::pair<IdentifierInfo*,WeakInfo> | |||
17090 | (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); | |||
17091 | } | |||
17092 | } | |||
17093 | ||||
17094 | void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, | |||
17095 | IdentifierInfo* AliasName, | |||
17096 | SourceLocation PragmaLoc, | |||
17097 | SourceLocation NameLoc, | |||
17098 | SourceLocation AliasNameLoc) { | |||
17099 | Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, | |||
17100 | LookupOrdinaryName); | |||
17101 | WeakInfo W = WeakInfo(Name, NameLoc); | |||
17102 | ||||
17103 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | |||
17104 | if (!PrevDecl->hasAttr<AliasAttr>()) | |||
17105 | if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) | |||
17106 | DeclApplyPragmaWeak(TUScope, ND, W); | |||
17107 | } else { | |||
17108 | (void)WeakUndeclaredIdentifiers.insert( | |||
17109 | std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); | |||
17110 | } | |||
17111 | } | |||
17112 | ||||
17113 | Decl *Sema::getObjCDeclContext() const { | |||
17114 | return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); | |||
17115 | } |