File: | tools/clang/lib/Sema/SemaDecl.cpp |
Warning: | line 11815, column 16 Called C++ object pointer is uninitialized |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// | |||
2 | // | |||
3 | // The LLVM Compiler Infrastructure | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | // | |||
10 | // This file implements semantic analysis for declarations. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "TypeLocBuilder.h" | |||
15 | #include "clang/AST/ASTConsumer.h" | |||
16 | #include "clang/AST/ASTContext.h" | |||
17 | #include "clang/AST/ASTLambda.h" | |||
18 | #include "clang/AST/CXXInheritance.h" | |||
19 | #include "clang/AST/CharUnits.h" | |||
20 | #include "clang/AST/CommentDiagnostic.h" | |||
21 | #include "clang/AST/DeclCXX.h" | |||
22 | #include "clang/AST/DeclObjC.h" | |||
23 | #include "clang/AST/DeclTemplate.h" | |||
24 | #include "clang/AST/EvaluatedExprVisitor.h" | |||
25 | #include "clang/AST/ExprCXX.h" | |||
26 | #include "clang/AST/StmtCXX.h" | |||
27 | #include "clang/Basic/Builtins.h" | |||
28 | #include "clang/Basic/PartialDiagnostic.h" | |||
29 | #include "clang/Basic/SourceManager.h" | |||
30 | #include "clang/Basic/TargetInfo.h" | |||
31 | #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex | |||
32 | #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. | |||
33 | #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex | |||
34 | #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() | |||
35 | #include "clang/Sema/CXXFieldCollector.h" | |||
36 | #include "clang/Sema/DeclSpec.h" | |||
37 | #include "clang/Sema/DelayedDiagnostic.h" | |||
38 | #include "clang/Sema/Initialization.h" | |||
39 | #include "clang/Sema/Lookup.h" | |||
40 | #include "clang/Sema/ParsedTemplate.h" | |||
41 | #include "clang/Sema/Scope.h" | |||
42 | #include "clang/Sema/ScopeInfo.h" | |||
43 | #include "clang/Sema/SemaInternal.h" | |||
44 | #include "clang/Sema/Template.h" | |||
45 | #include "llvm/ADT/SmallString.h" | |||
46 | #include "llvm/ADT/Triple.h" | |||
47 | #include <algorithm> | |||
48 | #include <cstring> | |||
49 | #include <functional> | |||
50 | ||||
51 | using namespace clang; | |||
52 | using namespace sema; | |||
53 | ||||
54 | Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { | |||
55 | if (OwnedType) { | |||
56 | Decl *Group[2] = { OwnedType, Ptr }; | |||
57 | return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); | |||
58 | } | |||
59 | ||||
60 | return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); | |||
61 | } | |||
62 | ||||
63 | namespace { | |||
64 | ||||
65 | class TypeNameValidatorCCC : public CorrectionCandidateCallback { | |||
66 | public: | |||
67 | TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, | |||
68 | bool AllowTemplates = false, | |||
69 | bool AllowNonTemplates = true) | |||
70 | : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), | |||
71 | AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { | |||
72 | WantExpressionKeywords = false; | |||
73 | WantCXXNamedCasts = false; | |||
74 | WantRemainingKeywords = false; | |||
75 | } | |||
76 | ||||
77 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
78 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | |||
79 | if (!AllowInvalidDecl && ND->isInvalidDecl()) | |||
80 | return false; | |||
81 | ||||
82 | if (getAsTypeTemplateDecl(ND)) | |||
83 | return AllowTemplates; | |||
84 | ||||
85 | bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); | |||
86 | if (!IsType) | |||
87 | return false; | |||
88 | ||||
89 | if (AllowNonTemplates) | |||
90 | return true; | |||
91 | ||||
92 | // An injected-class-name of a class template (specialization) is valid | |||
93 | // as a template or as a non-template. | |||
94 | if (AllowTemplates) { | |||
95 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | |||
96 | if (!RD || !RD->isInjectedClassName()) | |||
97 | return false; | |||
98 | RD = cast<CXXRecordDecl>(RD->getDeclContext()); | |||
99 | return RD->getDescribedClassTemplate() || | |||
100 | isa<ClassTemplateSpecializationDecl>(RD); | |||
101 | } | |||
102 | ||||
103 | return false; | |||
104 | } | |||
105 | ||||
106 | return !WantClassName && candidate.isKeyword(); | |||
107 | } | |||
108 | ||||
109 | private: | |||
110 | bool AllowInvalidDecl; | |||
111 | bool WantClassName; | |||
112 | bool AllowTemplates; | |||
113 | bool AllowNonTemplates; | |||
114 | }; | |||
115 | ||||
116 | } // end anonymous namespace | |||
117 | ||||
118 | /// Determine whether the token kind starts a simple-type-specifier. | |||
119 | bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { | |||
120 | switch (Kind) { | |||
121 | // FIXME: Take into account the current language when deciding whether a | |||
122 | // token kind is a valid type specifier | |||
123 | case tok::kw_short: | |||
124 | case tok::kw_long: | |||
125 | case tok::kw___int64: | |||
126 | case tok::kw___int128: | |||
127 | case tok::kw_signed: | |||
128 | case tok::kw_unsigned: | |||
129 | case tok::kw_void: | |||
130 | case tok::kw_char: | |||
131 | case tok::kw_int: | |||
132 | case tok::kw_half: | |||
133 | case tok::kw_float: | |||
134 | case tok::kw_double: | |||
135 | case tok::kw__Float16: | |||
136 | case tok::kw___float128: | |||
137 | case tok::kw_wchar_t: | |||
138 | case tok::kw_bool: | |||
139 | case tok::kw___underlying_type: | |||
140 | case tok::kw___auto_type: | |||
141 | return true; | |||
142 | ||||
143 | case tok::annot_typename: | |||
144 | case tok::kw_char16_t: | |||
145 | case tok::kw_char32_t: | |||
146 | case tok::kw_typeof: | |||
147 | case tok::annot_decltype: | |||
148 | case tok::kw_decltype: | |||
149 | return getLangOpts().CPlusPlus; | |||
150 | ||||
151 | case tok::kw_char8_t: | |||
152 | return getLangOpts().Char8; | |||
153 | ||||
154 | default: | |||
155 | break; | |||
156 | } | |||
157 | ||||
158 | return false; | |||
159 | } | |||
160 | ||||
161 | namespace { | |||
162 | enum class UnqualifiedTypeNameLookupResult { | |||
163 | NotFound, | |||
164 | FoundNonType, | |||
165 | FoundType | |||
166 | }; | |||
167 | } // end anonymous namespace | |||
168 | ||||
169 | /// Tries to perform unqualified lookup of the type decls in bases for | |||
170 | /// dependent class. | |||
171 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a | |||
172 | /// type decl, \a FoundType if only type decls are found. | |||
173 | static UnqualifiedTypeNameLookupResult | |||
174 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, | |||
175 | SourceLocation NameLoc, | |||
176 | const CXXRecordDecl *RD) { | |||
177 | if (!RD->hasDefinition()) | |||
178 | return UnqualifiedTypeNameLookupResult::NotFound; | |||
179 | // Look for type decls in base classes. | |||
180 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | |||
181 | UnqualifiedTypeNameLookupResult::NotFound; | |||
182 | for (const auto &Base : RD->bases()) { | |||
183 | const CXXRecordDecl *BaseRD = nullptr; | |||
184 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) | |||
185 | BaseRD = BaseTT->getAsCXXRecordDecl(); | |||
186 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { | |||
187 | // Look for type decls in dependent base classes that have known primary | |||
188 | // templates. | |||
189 | if (!TST || !TST->isDependentType()) | |||
190 | continue; | |||
191 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); | |||
192 | if (!TD) | |||
193 | continue; | |||
194 | if (auto *BasePrimaryTemplate = | |||
195 | dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { | |||
196 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) | |||
197 | BaseRD = BasePrimaryTemplate; | |||
198 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { | |||
199 | if (const ClassTemplatePartialSpecializationDecl *PS = | |||
200 | CTD->findPartialSpecialization(Base.getType())) | |||
201 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) | |||
202 | BaseRD = PS; | |||
203 | } | |||
204 | } | |||
205 | } | |||
206 | if (BaseRD) { | |||
207 | for (NamedDecl *ND : BaseRD->lookup(&II)) { | |||
208 | if (!isa<TypeDecl>(ND)) | |||
209 | return UnqualifiedTypeNameLookupResult::FoundNonType; | |||
210 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | |||
211 | } | |||
212 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { | |||
213 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { | |||
214 | case UnqualifiedTypeNameLookupResult::FoundNonType: | |||
215 | return UnqualifiedTypeNameLookupResult::FoundNonType; | |||
216 | case UnqualifiedTypeNameLookupResult::FoundType: | |||
217 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | |||
218 | break; | |||
219 | case UnqualifiedTypeNameLookupResult::NotFound: | |||
220 | break; | |||
221 | } | |||
222 | } | |||
223 | } | |||
224 | } | |||
225 | ||||
226 | return FoundTypeDecl; | |||
227 | } | |||
228 | ||||
229 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, | |||
230 | const IdentifierInfo &II, | |||
231 | SourceLocation NameLoc) { | |||
232 | // Lookup in the parent class template context, if any. | |||
233 | const CXXRecordDecl *RD = nullptr; | |||
234 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | |||
235 | UnqualifiedTypeNameLookupResult::NotFound; | |||
236 | for (DeclContext *DC = S.CurContext; | |||
237 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; | |||
238 | DC = DC->getParent()) { | |||
239 | // Look for type decls in dependent base classes that have known primary | |||
240 | // templates. | |||
241 | RD = dyn_cast<CXXRecordDecl>(DC); | |||
242 | if (RD && RD->getDescribedClassTemplate()) | |||
243 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); | |||
244 | } | |||
245 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) | |||
246 | return nullptr; | |||
247 | ||||
248 | // We found some types in dependent base classes. Recover as if the user | |||
249 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the | |||
250 | // lookup during template instantiation. | |||
251 | S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; | |||
252 | ||||
253 | ASTContext &Context = S.Context; | |||
254 | auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, | |||
255 | cast<Type>(Context.getRecordType(RD))); | |||
256 | QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); | |||
257 | ||||
258 | CXXScopeSpec SS; | |||
259 | SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
260 | ||||
261 | TypeLocBuilder Builder; | |||
262 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | |||
263 | DepTL.setNameLoc(NameLoc); | |||
264 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | |||
265 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
266 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
267 | } | |||
268 | ||||
269 | /// If the identifier refers to a type name within this scope, | |||
270 | /// return the declaration of that type. | |||
271 | /// | |||
272 | /// This routine performs ordinary name lookup of the identifier II | |||
273 | /// within the given scope, with optional C++ scope specifier SS, to | |||
274 | /// determine whether the name refers to a type. If so, returns an | |||
275 | /// opaque pointer (actually a QualType) corresponding to that | |||
276 | /// type. Otherwise, returns NULL. | |||
277 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, | |||
278 | Scope *S, CXXScopeSpec *SS, | |||
279 | bool isClassName, bool HasTrailingDot, | |||
280 | ParsedType ObjectTypePtr, | |||
281 | bool IsCtorOrDtorName, | |||
282 | bool WantNontrivialTypeSourceInfo, | |||
283 | bool IsClassTemplateDeductionContext, | |||
284 | IdentifierInfo **CorrectedII) { | |||
285 | // FIXME: Consider allowing this outside C++1z mode as an extension. | |||
286 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && | |||
287 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && | |||
288 | !isClassName && !HasTrailingDot; | |||
289 | ||||
290 | // Determine where we will perform name lookup. | |||
291 | DeclContext *LookupCtx = nullptr; | |||
292 | if (ObjectTypePtr) { | |||
293 | QualType ObjectType = ObjectTypePtr.get(); | |||
294 | if (ObjectType->isRecordType()) | |||
295 | LookupCtx = computeDeclContext(ObjectType); | |||
296 | } else if (SS && SS->isNotEmpty()) { | |||
297 | LookupCtx = computeDeclContext(*SS, false); | |||
298 | ||||
299 | if (!LookupCtx) { | |||
300 | if (isDependentScopeSpecifier(*SS)) { | |||
301 | // C++ [temp.res]p3: | |||
302 | // A qualified-id that refers to a type and in which the | |||
303 | // nested-name-specifier depends on a template-parameter (14.6.2) | |||
304 | // shall be prefixed by the keyword typename to indicate that the | |||
305 | // qualified-id denotes a type, forming an | |||
306 | // elaborated-type-specifier (7.1.5.3). | |||
307 | // | |||
308 | // We therefore do not perform any name lookup if the result would | |||
309 | // refer to a member of an unknown specialization. | |||
310 | if (!isClassName && !IsCtorOrDtorName) | |||
311 | return nullptr; | |||
312 | ||||
313 | // We know from the grammar that this name refers to a type, | |||
314 | // so build a dependent node to describe the type. | |||
315 | if (WantNontrivialTypeSourceInfo) | |||
316 | return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); | |||
317 | ||||
318 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); | |||
319 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, | |||
320 | II, NameLoc); | |||
321 | return ParsedType::make(T); | |||
322 | } | |||
323 | ||||
324 | return nullptr; | |||
325 | } | |||
326 | ||||
327 | if (!LookupCtx->isDependentContext() && | |||
328 | RequireCompleteDeclContext(*SS, LookupCtx)) | |||
329 | return nullptr; | |||
330 | } | |||
331 | ||||
332 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of | |||
333 | // lookup for class-names. | |||
334 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : | |||
335 | LookupOrdinaryName; | |||
336 | LookupResult Result(*this, &II, NameLoc, Kind); | |||
337 | if (LookupCtx) { | |||
338 | // Perform "qualified" name lookup into the declaration context we | |||
339 | // computed, which is either the type of the base of a member access | |||
340 | // expression or the declaration context associated with a prior | |||
341 | // nested-name-specifier. | |||
342 | LookupQualifiedName(Result, LookupCtx); | |||
343 | ||||
344 | if (ObjectTypePtr && Result.empty()) { | |||
345 | // C++ [basic.lookup.classref]p3: | |||
346 | // If the unqualified-id is ~type-name, the type-name is looked up | |||
347 | // in the context of the entire postfix-expression. If the type T of | |||
348 | // the object expression is of a class type C, the type-name is also | |||
349 | // looked up in the scope of class C. At least one of the lookups shall | |||
350 | // find a name that refers to (possibly cv-qualified) T. | |||
351 | LookupName(Result, S); | |||
352 | } | |||
353 | } else { | |||
354 | // Perform unqualified name lookup. | |||
355 | LookupName(Result, S); | |||
356 | ||||
357 | // For unqualified lookup in a class template in MSVC mode, look into | |||
358 | // dependent base classes where the primary class template is known. | |||
359 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { | |||
360 | if (ParsedType TypeInBase = | |||
361 | recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) | |||
362 | return TypeInBase; | |||
363 | } | |||
364 | } | |||
365 | ||||
366 | NamedDecl *IIDecl = nullptr; | |||
367 | switch (Result.getResultKind()) { | |||
368 | case LookupResult::NotFound: | |||
369 | case LookupResult::NotFoundInCurrentInstantiation: | |||
370 | if (CorrectedII) { | |||
371 | TypoCorrection Correction = | |||
372 | CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, | |||
373 | llvm::make_unique<TypeNameValidatorCCC>( | |||
374 | true, isClassName, AllowDeducedTemplate), | |||
375 | CTK_ErrorRecovery); | |||
376 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); | |||
377 | TemplateTy Template; | |||
378 | bool MemberOfUnknownSpecialization; | |||
379 | UnqualifiedId TemplateName; | |||
380 | TemplateName.setIdentifier(NewII, NameLoc); | |||
381 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); | |||
382 | CXXScopeSpec NewSS, *NewSSPtr = SS; | |||
383 | if (SS && NNS) { | |||
384 | NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
385 | NewSSPtr = &NewSS; | |||
386 | } | |||
387 | if (Correction && (NNS || NewII != &II) && | |||
388 | // Ignore a correction to a template type as the to-be-corrected | |||
389 | // identifier is not a template (typo correction for template names | |||
390 | // is handled elsewhere). | |||
391 | !(getLangOpts().CPlusPlus && NewSSPtr && | |||
392 | isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, | |||
393 | Template, MemberOfUnknownSpecialization))) { | |||
394 | ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, | |||
395 | isClassName, HasTrailingDot, ObjectTypePtr, | |||
396 | IsCtorOrDtorName, | |||
397 | WantNontrivialTypeSourceInfo, | |||
398 | IsClassTemplateDeductionContext); | |||
399 | if (Ty) { | |||
400 | diagnoseTypo(Correction, | |||
401 | PDiag(diag::err_unknown_type_or_class_name_suggest) | |||
402 | << Result.getLookupName() << isClassName); | |||
403 | if (SS && NNS) | |||
404 | SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
405 | *CorrectedII = NewII; | |||
406 | return Ty; | |||
407 | } | |||
408 | } | |||
409 | } | |||
410 | // If typo correction failed or was not performed, fall through | |||
411 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
412 | case LookupResult::FoundOverloaded: | |||
413 | case LookupResult::FoundUnresolvedValue: | |||
414 | Result.suppressDiagnostics(); | |||
415 | return nullptr; | |||
416 | ||||
417 | case LookupResult::Ambiguous: | |||
418 | // Recover from type-hiding ambiguities by hiding the type. We'll | |||
419 | // do the lookup again when looking for an object, and we can | |||
420 | // diagnose the error then. If we don't do this, then the error | |||
421 | // about hiding the type will be immediately followed by an error | |||
422 | // that only makes sense if the identifier was treated like a type. | |||
423 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { | |||
424 | Result.suppressDiagnostics(); | |||
425 | return nullptr; | |||
426 | } | |||
427 | ||||
428 | // Look to see if we have a type anywhere in the list of results. | |||
429 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); | |||
430 | Res != ResEnd; ++Res) { | |||
431 | if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || | |||
432 | (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { | |||
433 | if (!IIDecl || | |||
434 | (*Res)->getLocation().getRawEncoding() < | |||
435 | IIDecl->getLocation().getRawEncoding()) | |||
436 | IIDecl = *Res; | |||
437 | } | |||
438 | } | |||
439 | ||||
440 | if (!IIDecl) { | |||
441 | // None of the entities we found is a type, so there is no way | |||
442 | // to even assume that the result is a type. In this case, don't | |||
443 | // complain about the ambiguity. The parser will either try to | |||
444 | // perform this lookup again (e.g., as an object name), which | |||
445 | // will produce the ambiguity, or will complain that it expected | |||
446 | // a type name. | |||
447 | Result.suppressDiagnostics(); | |||
448 | return nullptr; | |||
449 | } | |||
450 | ||||
451 | // We found a type within the ambiguous lookup; diagnose the | |||
452 | // ambiguity and then return that type. This might be the right | |||
453 | // answer, or it might not be, but it suppresses any attempt to | |||
454 | // perform the name lookup again. | |||
455 | break; | |||
456 | ||||
457 | case LookupResult::Found: | |||
458 | IIDecl = Result.getFoundDecl(); | |||
459 | break; | |||
460 | } | |||
461 | ||||
462 | assert(IIDecl && "Didn't find decl")(static_cast <bool> (IIDecl && "Didn't find decl" ) ? void (0) : __assert_fail ("IIDecl && \"Didn't find decl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 462, __extension__ __PRETTY_FUNCTION__)); | |||
463 | ||||
464 | QualType T; | |||
465 | if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { | |||
466 | // C++ [class.qual]p2: A lookup that would find the injected-class-name | |||
467 | // instead names the constructors of the class, except when naming a class. | |||
468 | // This is ill-formed when we're not actually forming a ctor or dtor name. | |||
469 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); | |||
470 | auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); | |||
471 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && | |||
472 | FoundRD->isInjectedClassName() && | |||
473 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) | |||
474 | Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) | |||
475 | << &II << /*Type*/1; | |||
476 | ||||
477 | DiagnoseUseOfDecl(IIDecl, NameLoc); | |||
478 | ||||
479 | T = Context.getTypeDeclType(TD); | |||
480 | MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); | |||
481 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { | |||
482 | (void)DiagnoseUseOfDecl(IDecl, NameLoc); | |||
483 | if (!HasTrailingDot) | |||
484 | T = Context.getObjCInterfaceType(IDecl); | |||
485 | } else if (AllowDeducedTemplate) { | |||
486 | if (auto *TD = getAsTypeTemplateDecl(IIDecl)) | |||
487 | T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), | |||
488 | QualType(), false); | |||
489 | } | |||
490 | ||||
491 | if (T.isNull()) { | |||
492 | // If it's not plausibly a type, suppress diagnostics. | |||
493 | Result.suppressDiagnostics(); | |||
494 | return nullptr; | |||
495 | } | |||
496 | ||||
497 | // NOTE: avoid constructing an ElaboratedType(Loc) if this is a | |||
498 | // constructor or destructor name (in such a case, the scope specifier | |||
499 | // will be attached to the enclosing Expr or Decl node). | |||
500 | if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && | |||
501 | !isa<ObjCInterfaceDecl>(IIDecl)) { | |||
502 | if (WantNontrivialTypeSourceInfo) { | |||
503 | // Construct a type with type-source information. | |||
504 | TypeLocBuilder Builder; | |||
505 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | |||
506 | ||||
507 | T = getElaboratedType(ETK_None, *SS, T); | |||
508 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | |||
509 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | |||
510 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); | |||
511 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
512 | } else { | |||
513 | T = getElaboratedType(ETK_None, *SS, T); | |||
514 | } | |||
515 | } | |||
516 | ||||
517 | return ParsedType::make(T); | |||
518 | } | |||
519 | ||||
520 | // Builds a fake NNS for the given decl context. | |||
521 | static NestedNameSpecifier * | |||
522 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { | |||
523 | for (;; DC = DC->getLookupParent()) { | |||
524 | DC = DC->getPrimaryContext(); | |||
525 | auto *ND = dyn_cast<NamespaceDecl>(DC); | |||
526 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) | |||
527 | return NestedNameSpecifier::Create(Context, nullptr, ND); | |||
528 | else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) | |||
529 | return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | |||
530 | RD->getTypeForDecl()); | |||
531 | else if (isa<TranslationUnitDecl>(DC)) | |||
532 | return NestedNameSpecifier::GlobalSpecifier(Context); | |||
533 | } | |||
534 | llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 534); | |||
535 | } | |||
536 | ||||
537 | /// Find the parent class with dependent bases of the innermost enclosing method | |||
538 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end | |||
539 | /// up allowing unqualified dependent type names at class-level, which MSVC | |||
540 | /// correctly rejects. | |||
541 | static const CXXRecordDecl * | |||
542 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { | |||
543 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { | |||
544 | DC = DC->getPrimaryContext(); | |||
545 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | |||
546 | if (MD->getParent()->hasAnyDependentBases()) | |||
547 | return MD->getParent(); | |||
548 | } | |||
549 | return nullptr; | |||
550 | } | |||
551 | ||||
552 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, | |||
553 | SourceLocation NameLoc, | |||
554 | bool IsTemplateTypeArg) { | |||
555 | assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")(static_cast <bool> (getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode") ? void (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 555, __extension__ __PRETTY_FUNCTION__)); | |||
556 | ||||
557 | NestedNameSpecifier *NNS = nullptr; | |||
558 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { | |||
559 | // If we weren't able to parse a default template argument, delay lookup | |||
560 | // until instantiation time by making a non-dependent DependentTypeName. We | |||
561 | // pretend we saw a NestedNameSpecifier referring to the current scope, and | |||
562 | // lookup is retried. | |||
563 | // FIXME: This hurts our diagnostic quality, since we get errors like "no | |||
564 | // type named 'Foo' in 'current_namespace'" when the user didn't write any | |||
565 | // name specifiers. | |||
566 | NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); | |||
567 | Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; | |||
568 | } else if (const CXXRecordDecl *RD = | |||
569 | findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { | |||
570 | // Build a DependentNameType that will perform lookup into RD at | |||
571 | // instantiation time. | |||
572 | NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | |||
573 | RD->getTypeForDecl()); | |||
574 | ||||
575 | // Diagnose that this identifier was undeclared, and retry the lookup during | |||
576 | // template instantiation. | |||
577 | Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II | |||
578 | << RD; | |||
579 | } else { | |||
580 | // This is not a situation that we should recover from. | |||
581 | return ParsedType(); | |||
582 | } | |||
583 | ||||
584 | QualType T = Context.getDependentNameType(ETK_None, NNS, &II); | |||
585 | ||||
586 | // Build type location information. We synthesized the qualifier, so we have | |||
587 | // to build a fake NestedNameSpecifierLoc. | |||
588 | NestedNameSpecifierLocBuilder NNSLocBuilder; | |||
589 | NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
590 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); | |||
591 | ||||
592 | TypeLocBuilder Builder; | |||
593 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | |||
594 | DepTL.setNameLoc(NameLoc); | |||
595 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | |||
596 | DepTL.setQualifierLoc(QualifierLoc); | |||
597 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
598 | } | |||
599 | ||||
600 | /// isTagName() - This method is called *for error recovery purposes only* | |||
601 | /// to determine if the specified name is a valid tag name ("struct foo"). If | |||
602 | /// so, this returns the TST for the tag corresponding to it (TST_enum, | |||
603 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose | |||
604 | /// cases in C where the user forgot to specify the tag. | |||
605 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { | |||
606 | // Do a tag name lookup in this scope. | |||
607 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); | |||
608 | LookupName(R, S, false); | |||
609 | R.suppressDiagnostics(); | |||
610 | if (R.getResultKind() == LookupResult::Found) | |||
611 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { | |||
612 | switch (TD->getTagKind()) { | |||
613 | case TTK_Struct: return DeclSpec::TST_struct; | |||
614 | case TTK_Interface: return DeclSpec::TST_interface; | |||
615 | case TTK_Union: return DeclSpec::TST_union; | |||
616 | case TTK_Class: return DeclSpec::TST_class; | |||
617 | case TTK_Enum: return DeclSpec::TST_enum; | |||
618 | } | |||
619 | } | |||
620 | ||||
621 | return DeclSpec::TST_unspecified; | |||
622 | } | |||
623 | ||||
624 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, | |||
625 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes | |||
626 | /// then downgrade the missing typename error to a warning. | |||
627 | /// This is needed for MSVC compatibility; Example: | |||
628 | /// @code | |||
629 | /// template<class T> class A { | |||
630 | /// public: | |||
631 | /// typedef int TYPE; | |||
632 | /// }; | |||
633 | /// template<class T> class B : public A<T> { | |||
634 | /// public: | |||
635 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. | |||
636 | /// }; | |||
637 | /// @endcode | |||
638 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { | |||
639 | if (CurContext->isRecord()) { | |||
640 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) | |||
641 | return true; | |||
642 | ||||
643 | const Type *Ty = SS->getScopeRep()->getAsType(); | |||
644 | ||||
645 | CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); | |||
646 | for (const auto &Base : RD->bases()) | |||
647 | if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) | |||
648 | return true; | |||
649 | return S->isFunctionPrototypeScope(); | |||
650 | } | |||
651 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); | |||
652 | } | |||
653 | ||||
654 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, | |||
655 | SourceLocation IILoc, | |||
656 | Scope *S, | |||
657 | CXXScopeSpec *SS, | |||
658 | ParsedType &SuggestedType, | |||
659 | bool IsTemplateName) { | |||
660 | // Don't report typename errors for editor placeholders. | |||
661 | if (II->isEditorPlaceholder()) | |||
662 | return; | |||
663 | // We don't have anything to suggest (yet). | |||
664 | SuggestedType = nullptr; | |||
665 | ||||
666 | // There may have been a typo in the name of the type. Look up typo | |||
667 | // results, in case we have something that we can suggest. | |||
668 | if (TypoCorrection Corrected = | |||
669 | CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, | |||
670 | llvm::make_unique<TypeNameValidatorCCC>( | |||
671 | false, false, IsTemplateName, !IsTemplateName), | |||
672 | CTK_ErrorRecovery)) { | |||
673 | // FIXME: Support error recovery for the template-name case. | |||
674 | bool CanRecover = !IsTemplateName; | |||
675 | if (Corrected.isKeyword()) { | |||
676 | // We corrected to a keyword. | |||
677 | diagnoseTypo(Corrected, | |||
678 | PDiag(IsTemplateName ? diag::err_no_template_suggest | |||
679 | : diag::err_unknown_typename_suggest) | |||
680 | << II); | |||
681 | II = Corrected.getCorrectionAsIdentifierInfo(); | |||
682 | } else { | |||
683 | // We found a similarly-named type or interface; suggest that. | |||
684 | if (!SS || !SS->isSet()) { | |||
685 | diagnoseTypo(Corrected, | |||
686 | PDiag(IsTemplateName ? diag::err_no_template_suggest | |||
687 | : diag::err_unknown_typename_suggest) | |||
688 | << II, CanRecover); | |||
689 | } else if (DeclContext *DC = computeDeclContext(*SS, false)) { | |||
690 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | |||
691 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | |||
692 | II->getName().equals(CorrectedStr); | |||
693 | diagnoseTypo(Corrected, | |||
694 | PDiag(IsTemplateName | |||
695 | ? diag::err_no_member_template_suggest | |||
696 | : diag::err_unknown_nested_typename_suggest) | |||
697 | << II << DC << DroppedSpecifier << SS->getRange(), | |||
698 | CanRecover); | |||
699 | } else { | |||
700 | llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 700); | |||
701 | } | |||
702 | ||||
703 | if (!CanRecover) | |||
704 | return; | |||
705 | ||||
706 | CXXScopeSpec tmpSS; | |||
707 | if (Corrected.getCorrectionSpecifier()) | |||
708 | tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | |||
709 | SourceRange(IILoc)); | |||
710 | // FIXME: Support class template argument deduction here. | |||
711 | SuggestedType = | |||
712 | getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, | |||
713 | tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, | |||
714 | /*IsCtorOrDtorName=*/false, | |||
715 | /*NonTrivialTypeSourceInfo=*/true); | |||
716 | } | |||
717 | return; | |||
718 | } | |||
719 | ||||
720 | if (getLangOpts().CPlusPlus && !IsTemplateName) { | |||
721 | // See if II is a class template that the user forgot to pass arguments to. | |||
722 | UnqualifiedId Name; | |||
723 | Name.setIdentifier(II, IILoc); | |||
724 | CXXScopeSpec EmptySS; | |||
725 | TemplateTy TemplateResult; | |||
726 | bool MemberOfUnknownSpecialization; | |||
727 | if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, | |||
728 | Name, nullptr, true, TemplateResult, | |||
729 | MemberOfUnknownSpecialization) == TNK_Type_template) { | |||
730 | diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); | |||
731 | return; | |||
732 | } | |||
733 | } | |||
734 | ||||
735 | // FIXME: Should we move the logic that tries to recover from a missing tag | |||
736 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? | |||
737 | ||||
738 | if (!SS || (!SS->isSet() && !SS->isInvalid())) | |||
739 | Diag(IILoc, IsTemplateName ? diag::err_no_template | |||
740 | : diag::err_unknown_typename) | |||
741 | << II; | |||
742 | else if (DeclContext *DC = computeDeclContext(*SS, false)) | |||
743 | Diag(IILoc, IsTemplateName ? diag::err_no_member_template | |||
744 | : diag::err_typename_nested_not_found) | |||
745 | << II << DC << SS->getRange(); | |||
746 | else if (isDependentScopeSpecifier(*SS)) { | |||
747 | unsigned DiagID = diag::err_typename_missing; | |||
748 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) | |||
749 | DiagID = diag::ext_typename_missing; | |||
750 | ||||
751 | Diag(SS->getRange().getBegin(), DiagID) | |||
752 | << SS->getScopeRep() << II->getName() | |||
753 | << SourceRange(SS->getRange().getBegin(), IILoc) | |||
754 | << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); | |||
755 | SuggestedType = ActOnTypenameType(S, SourceLocation(), | |||
756 | *SS, *II, IILoc).get(); | |||
757 | } else { | |||
758 | assert(SS && SS->isInvalid() &&(static_cast <bool> (SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed") ? void (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 759, __extension__ __PRETTY_FUNCTION__)) | |||
759 | "Invalid scope specifier has already been diagnosed")(static_cast <bool> (SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed") ? void (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 759, __extension__ __PRETTY_FUNCTION__)); | |||
760 | } | |||
761 | } | |||
762 | ||||
763 | /// Determine whether the given result set contains either a type name | |||
764 | /// or | |||
765 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { | |||
766 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && | |||
767 | NextToken.is(tok::less); | |||
768 | ||||
769 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { | |||
770 | if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) | |||
771 | return true; | |||
772 | ||||
773 | if (CheckTemplate && isa<TemplateDecl>(*I)) | |||
774 | return true; | |||
775 | } | |||
776 | ||||
777 | return false; | |||
778 | } | |||
779 | ||||
780 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, | |||
781 | Scope *S, CXXScopeSpec &SS, | |||
782 | IdentifierInfo *&Name, | |||
783 | SourceLocation NameLoc) { | |||
784 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); | |||
785 | SemaRef.LookupParsedName(R, S, &SS); | |||
786 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { | |||
787 | StringRef FixItTagName; | |||
788 | switch (Tag->getTagKind()) { | |||
789 | case TTK_Class: | |||
790 | FixItTagName = "class "; | |||
791 | break; | |||
792 | ||||
793 | case TTK_Enum: | |||
794 | FixItTagName = "enum "; | |||
795 | break; | |||
796 | ||||
797 | case TTK_Struct: | |||
798 | FixItTagName = "struct "; | |||
799 | break; | |||
800 | ||||
801 | case TTK_Interface: | |||
802 | FixItTagName = "__interface "; | |||
803 | break; | |||
804 | ||||
805 | case TTK_Union: | |||
806 | FixItTagName = "union "; | |||
807 | break; | |||
808 | } | |||
809 | ||||
810 | StringRef TagName = FixItTagName.drop_back(); | |||
811 | SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) | |||
812 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus | |||
813 | << FixItHint::CreateInsertion(NameLoc, FixItTagName); | |||
814 | ||||
815 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); | |||
816 | I != IEnd; ++I) | |||
817 | SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) | |||
818 | << Name << TagName; | |||
819 | ||||
820 | // Replace lookup results with just the tag decl. | |||
821 | Result.clear(Sema::LookupTagName); | |||
822 | SemaRef.LookupParsedName(Result, S, &SS); | |||
823 | return true; | |||
824 | } | |||
825 | ||||
826 | return false; | |||
827 | } | |||
828 | ||||
829 | /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. | |||
830 | static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, | |||
831 | QualType T, SourceLocation NameLoc) { | |||
832 | ASTContext &Context = S.Context; | |||
833 | ||||
834 | TypeLocBuilder Builder; | |||
835 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | |||
836 | ||||
837 | T = S.getElaboratedType(ETK_None, SS, T); | |||
838 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | |||
839 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | |||
840 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
841 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
842 | } | |||
843 | ||||
844 | Sema::NameClassification | |||
845 | Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, | |||
846 | SourceLocation NameLoc, const Token &NextToken, | |||
847 | bool IsAddressOfOperand, | |||
848 | std::unique_ptr<CorrectionCandidateCallback> CCC) { | |||
849 | DeclarationNameInfo NameInfo(Name, NameLoc); | |||
850 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | |||
851 | ||||
852 | if (NextToken.is(tok::coloncolon)) { | |||
853 | NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); | |||
854 | BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); | |||
855 | } else if (getLangOpts().CPlusPlus && SS.isSet() && | |||
856 | isCurrentClassName(*Name, S, &SS)) { | |||
857 | // Per [class.qual]p2, this names the constructors of SS, not the | |||
858 | // injected-class-name. We don't have a classification for that. | |||
859 | // There's not much point caching this result, since the parser | |||
860 | // will reject it later. | |||
861 | return NameClassification::Unknown(); | |||
862 | } | |||
863 | ||||
864 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | |||
865 | LookupParsedName(Result, S, &SS, !CurMethod); | |||
866 | ||||
867 | // For unqualified lookup in a class template in MSVC mode, look into | |||
868 | // dependent base classes where the primary class template is known. | |||
869 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { | |||
870 | if (ParsedType TypeInBase = | |||
871 | recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) | |||
872 | return TypeInBase; | |||
873 | } | |||
874 | ||||
875 | // Perform lookup for Objective-C instance variables (including automatically | |||
876 | // synthesized instance variables), if we're in an Objective-C method. | |||
877 | // FIXME: This lookup really, really needs to be folded in to the normal | |||
878 | // unqualified lookup mechanism. | |||
879 | if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { | |||
880 | ExprResult E = LookupInObjCMethod(Result, S, Name, true); | |||
881 | if (E.get() || E.isInvalid()) | |||
882 | return E; | |||
883 | } | |||
884 | ||||
885 | bool SecondTry = false; | |||
886 | bool IsFilteredTemplateName = false; | |||
887 | ||||
888 | Corrected: | |||
889 | switch (Result.getResultKind()) { | |||
890 | case LookupResult::NotFound: | |||
891 | // If an unqualified-id is followed by a '(', then we have a function | |||
892 | // call. | |||
893 | if (!SS.isSet() && NextToken.is(tok::l_paren)) { | |||
894 | // In C++, this is an ADL-only call. | |||
895 | // FIXME: Reference? | |||
896 | if (getLangOpts().CPlusPlus) | |||
897 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); | |||
898 | ||||
899 | // C90 6.3.2.2: | |||
900 | // If the expression that precedes the parenthesized argument list in a | |||
901 | // function call consists solely of an identifier, and if no | |||
902 | // declaration is visible for this identifier, the identifier is | |||
903 | // implicitly declared exactly as if, in the innermost block containing | |||
904 | // the function call, the declaration | |||
905 | // | |||
906 | // extern int identifier (); | |||
907 | // | |||
908 | // appeared. | |||
909 | // | |||
910 | // We also allow this in C99 as an extension. | |||
911 | if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { | |||
912 | Result.addDecl(D); | |||
913 | Result.resolveKind(); | |||
914 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); | |||
915 | } | |||
916 | } | |||
917 | ||||
918 | // In C, we first see whether there is a tag type by the same name, in | |||
919 | // which case it's likely that the user just forgot to write "enum", | |||
920 | // "struct", or "union". | |||
921 | if (!getLangOpts().CPlusPlus && !SecondTry && | |||
922 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | |||
923 | break; | |||
924 | } | |||
925 | ||||
926 | // Perform typo correction to determine if there is another name that is | |||
927 | // close to this name. | |||
928 | if (!SecondTry && CCC) { | |||
929 | SecondTry = true; | |||
930 | if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), | |||
931 | Result.getLookupKind(), S, | |||
932 | &SS, std::move(CCC), | |||
933 | CTK_ErrorRecovery)) { | |||
934 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; | |||
935 | unsigned QualifiedDiag = diag::err_no_member_suggest; | |||
936 | ||||
937 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); | |||
938 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); | |||
939 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | |||
940 | UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { | |||
941 | UnqualifiedDiag = diag::err_no_template_suggest; | |||
942 | QualifiedDiag = diag::err_no_member_template_suggest; | |||
943 | } else if (UnderlyingFirstDecl && | |||
944 | (isa<TypeDecl>(UnderlyingFirstDecl) || | |||
945 | isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || | |||
946 | isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { | |||
947 | UnqualifiedDiag = diag::err_unknown_typename_suggest; | |||
948 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; | |||
949 | } | |||
950 | ||||
951 | if (SS.isEmpty()) { | |||
952 | diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); | |||
953 | } else {// FIXME: is this even reachable? Test it. | |||
954 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | |||
955 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | |||
956 | Name->getName().equals(CorrectedStr); | |||
957 | diagnoseTypo(Corrected, PDiag(QualifiedDiag) | |||
958 | << Name << computeDeclContext(SS, false) | |||
959 | << DroppedSpecifier << SS.getRange()); | |||
960 | } | |||
961 | ||||
962 | // Update the name, so that the caller has the new name. | |||
963 | Name = Corrected.getCorrectionAsIdentifierInfo(); | |||
964 | ||||
965 | // Typo correction corrected to a keyword. | |||
966 | if (Corrected.isKeyword()) | |||
967 | return Name; | |||
968 | ||||
969 | // Also update the LookupResult... | |||
970 | // FIXME: This should probably go away at some point | |||
971 | Result.clear(); | |||
972 | Result.setLookupName(Corrected.getCorrection()); | |||
973 | if (FirstDecl) | |||
974 | Result.addDecl(FirstDecl); | |||
975 | ||||
976 | // If we found an Objective-C instance variable, let | |||
977 | // LookupInObjCMethod build the appropriate expression to | |||
978 | // reference the ivar. | |||
979 | // FIXME: This is a gross hack. | |||
980 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { | |||
981 | Result.clear(); | |||
982 | ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); | |||
983 | return E; | |||
984 | } | |||
985 | ||||
986 | goto Corrected; | |||
987 | } | |||
988 | } | |||
989 | ||||
990 | // We failed to correct; just fall through and let the parser deal with it. | |||
991 | Result.suppressDiagnostics(); | |||
992 | return NameClassification::Unknown(); | |||
993 | ||||
994 | case LookupResult::NotFoundInCurrentInstantiation: { | |||
995 | // We performed name lookup into the current instantiation, and there were | |||
996 | // dependent bases, so we treat this result the same way as any other | |||
997 | // dependent nested-name-specifier. | |||
998 | ||||
999 | // C++ [temp.res]p2: | |||
1000 | // A name used in a template declaration or definition and that is | |||
1001 | // dependent on a template-parameter is assumed not to name a type | |||
1002 | // unless the applicable name lookup finds a type name or the name is | |||
1003 | // qualified by the keyword typename. | |||
1004 | // | |||
1005 | // FIXME: If the next token is '<', we might want to ask the parser to | |||
1006 | // perform some heroics to see if we actually have a | |||
1007 | // template-argument-list, which would indicate a missing 'template' | |||
1008 | // keyword here. | |||
1009 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
1010 | NameInfo, IsAddressOfOperand, | |||
1011 | /*TemplateArgs=*/nullptr); | |||
1012 | } | |||
1013 | ||||
1014 | case LookupResult::Found: | |||
1015 | case LookupResult::FoundOverloaded: | |||
1016 | case LookupResult::FoundUnresolvedValue: | |||
1017 | break; | |||
1018 | ||||
1019 | case LookupResult::Ambiguous: | |||
1020 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | |||
1021 | hasAnyAcceptableTemplateNames(Result)) { | |||
1022 | // C++ [temp.local]p3: | |||
1023 | // A lookup that finds an injected-class-name (10.2) can result in an | |||
1024 | // ambiguity in certain cases (for example, if it is found in more than | |||
1025 | // one base class). If all of the injected-class-names that are found | |||
1026 | // refer to specializations of the same class template, and if the name | |||
1027 | // is followed by a template-argument-list, the reference refers to the | |||
1028 | // class template itself and not a specialization thereof, and is not | |||
1029 | // ambiguous. | |||
1030 | // | |||
1031 | // This filtering can make an ambiguous result into an unambiguous one, | |||
1032 | // so try again after filtering out template names. | |||
1033 | FilterAcceptableTemplateNames(Result); | |||
1034 | if (!Result.isAmbiguous()) { | |||
1035 | IsFilteredTemplateName = true; | |||
1036 | break; | |||
1037 | } | |||
1038 | } | |||
1039 | ||||
1040 | // Diagnose the ambiguity and return an error. | |||
1041 | return NameClassification::Error(); | |||
1042 | } | |||
1043 | ||||
1044 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | |||
1045 | (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { | |||
1046 | // C++ [temp.names]p3: | |||
1047 | // After name lookup (3.4) finds that a name is a template-name or that | |||
1048 | // an operator-function-id or a literal- operator-id refers to a set of | |||
1049 | // overloaded functions any member of which is a function template if | |||
1050 | // this is followed by a <, the < is always taken as the delimiter of a | |||
1051 | // template-argument-list and never as the less-than operator. | |||
1052 | if (!IsFilteredTemplateName) | |||
1053 | FilterAcceptableTemplateNames(Result); | |||
1054 | ||||
1055 | if (!Result.empty()) { | |||
1056 | bool IsFunctionTemplate; | |||
1057 | bool IsVarTemplate; | |||
1058 | TemplateName Template; | |||
1059 | if (Result.end() - Result.begin() > 1) { | |||
1060 | IsFunctionTemplate = true; | |||
1061 | Template = Context.getOverloadedTemplateName(Result.begin(), | |||
1062 | Result.end()); | |||
1063 | } else { | |||
1064 | TemplateDecl *TD | |||
1065 | = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); | |||
1066 | IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); | |||
1067 | IsVarTemplate = isa<VarTemplateDecl>(TD); | |||
1068 | ||||
1069 | if (SS.isSet() && !SS.isInvalid()) | |||
1070 | Template = Context.getQualifiedTemplateName(SS.getScopeRep(), | |||
1071 | /*TemplateKeyword=*/false, | |||
1072 | TD); | |||
1073 | else | |||
1074 | Template = TemplateName(TD); | |||
1075 | } | |||
1076 | ||||
1077 | if (IsFunctionTemplate) { | |||
1078 | // Function templates always go through overload resolution, at which | |||
1079 | // point we'll perform the various checks (e.g., accessibility) we need | |||
1080 | // to based on which function we selected. | |||
1081 | Result.suppressDiagnostics(); | |||
1082 | ||||
1083 | return NameClassification::FunctionTemplate(Template); | |||
1084 | } | |||
1085 | ||||
1086 | return IsVarTemplate ? NameClassification::VarTemplate(Template) | |||
1087 | : NameClassification::TypeTemplate(Template); | |||
1088 | } | |||
1089 | } | |||
1090 | ||||
1091 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); | |||
1092 | if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { | |||
1093 | DiagnoseUseOfDecl(Type, NameLoc); | |||
1094 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | |||
1095 | QualType T = Context.getTypeDeclType(Type); | |||
1096 | if (SS.isNotEmpty()) | |||
1097 | return buildNestedType(*this, SS, T, NameLoc); | |||
1098 | return ParsedType::make(T); | |||
1099 | } | |||
1100 | ||||
1101 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); | |||
1102 | if (!Class) { | |||
1103 | // FIXME: It's unfortunate that we don't have a Type node for handling this. | |||
1104 | if (ObjCCompatibleAliasDecl *Alias = | |||
1105 | dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) | |||
1106 | Class = Alias->getClassInterface(); | |||
1107 | } | |||
1108 | ||||
1109 | if (Class) { | |||
1110 | DiagnoseUseOfDecl(Class, NameLoc); | |||
1111 | ||||
1112 | if (NextToken.is(tok::period)) { | |||
1113 | // Interface. <something> is parsed as a property reference expression. | |||
1114 | // Just return "unknown" as a fall-through for now. | |||
1115 | Result.suppressDiagnostics(); | |||
1116 | return NameClassification::Unknown(); | |||
1117 | } | |||
1118 | ||||
1119 | QualType T = Context.getObjCInterfaceType(Class); | |||
1120 | return ParsedType::make(T); | |||
1121 | } | |||
1122 | ||||
1123 | // We can have a type template here if we're classifying a template argument. | |||
1124 | if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && | |||
1125 | !isa<VarTemplateDecl>(FirstDecl)) | |||
1126 | return NameClassification::TypeTemplate( | |||
1127 | TemplateName(cast<TemplateDecl>(FirstDecl))); | |||
1128 | ||||
1129 | // Check for a tag type hidden by a non-type decl in a few cases where it | |||
1130 | // seems likely a type is wanted instead of the non-type that was found. | |||
1131 | bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); | |||
1132 | if ((NextToken.is(tok::identifier) || | |||
1133 | (NextIsOp && | |||
1134 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && | |||
1135 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | |||
1136 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); | |||
1137 | DiagnoseUseOfDecl(Type, NameLoc); | |||
1138 | QualType T = Context.getTypeDeclType(Type); | |||
1139 | if (SS.isNotEmpty()) | |||
1140 | return buildNestedType(*this, SS, T, NameLoc); | |||
1141 | return ParsedType::make(T); | |||
1142 | } | |||
1143 | ||||
1144 | if (FirstDecl->isCXXClassMember()) | |||
1145 | return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, | |||
1146 | nullptr, S); | |||
1147 | ||||
1148 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | |||
1149 | return BuildDeclarationNameExpr(SS, Result, ADL); | |||
1150 | } | |||
1151 | ||||
1152 | Sema::TemplateNameKindForDiagnostics | |||
1153 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { | |||
1154 | auto *TD = Name.getAsTemplateDecl(); | |||
1155 | if (!TD) | |||
1156 | return TemplateNameKindForDiagnostics::DependentTemplate; | |||
1157 | if (isa<ClassTemplateDecl>(TD)) | |||
1158 | return TemplateNameKindForDiagnostics::ClassTemplate; | |||
1159 | if (isa<FunctionTemplateDecl>(TD)) | |||
1160 | return TemplateNameKindForDiagnostics::FunctionTemplate; | |||
1161 | if (isa<VarTemplateDecl>(TD)) | |||
1162 | return TemplateNameKindForDiagnostics::VarTemplate; | |||
1163 | if (isa<TypeAliasTemplateDecl>(TD)) | |||
1164 | return TemplateNameKindForDiagnostics::AliasTemplate; | |||
1165 | if (isa<TemplateTemplateParmDecl>(TD)) | |||
1166 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; | |||
1167 | return TemplateNameKindForDiagnostics::DependentTemplate; | |||
1168 | } | |||
1169 | ||||
1170 | // Determines the context to return to after temporarily entering a | |||
1171 | // context. This depends in an unnecessarily complicated way on the | |||
1172 | // exact ordering of callbacks from the parser. | |||
1173 | DeclContext *Sema::getContainingDC(DeclContext *DC) { | |||
1174 | ||||
1175 | // Functions defined inline within classes aren't parsed until we've | |||
1176 | // finished parsing the top-level class, so the top-level class is | |||
1177 | // the context we'll need to return to. | |||
1178 | // A Lambda call operator whose parent is a class must not be treated | |||
1179 | // as an inline member function. A Lambda can be used legally | |||
1180 | // either as an in-class member initializer or a default argument. These | |||
1181 | // are parsed once the class has been marked complete and so the containing | |||
1182 | // context would be the nested class (when the lambda is defined in one); | |||
1183 | // If the class is not complete, then the lambda is being used in an | |||
1184 | // ill-formed fashion (such as to specify the width of a bit-field, or | |||
1185 | // in an array-bound) - in which case we still want to return the | |||
1186 | // lexically containing DC (which could be a nested class). | |||
1187 | if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { | |||
1188 | DC = DC->getLexicalParent(); | |||
1189 | ||||
1190 | // A function not defined within a class will always return to its | |||
1191 | // lexical context. | |||
1192 | if (!isa<CXXRecordDecl>(DC)) | |||
1193 | return DC; | |||
1194 | ||||
1195 | // A C++ inline method/friend is parsed *after* the topmost class | |||
1196 | // it was declared in is fully parsed ("complete"); the topmost | |||
1197 | // class is the context we need to return to. | |||
1198 | while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) | |||
1199 | DC = RD; | |||
1200 | ||||
1201 | // Return the declaration context of the topmost class the inline method is | |||
1202 | // declared in. | |||
1203 | return DC; | |||
1204 | } | |||
1205 | ||||
1206 | return DC->getLexicalParent(); | |||
1207 | } | |||
1208 | ||||
1209 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { | |||
1210 | assert(getContainingDC(DC) == CurContext &&(static_cast <bool> (getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1211, __extension__ __PRETTY_FUNCTION__)) | |||
1211 | "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1211, __extension__ __PRETTY_FUNCTION__)); | |||
1212 | CurContext = DC; | |||
1213 | S->setEntity(DC); | |||
1214 | } | |||
1215 | ||||
1216 | void Sema::PopDeclContext() { | |||
1217 | assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!" ) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1217, __extension__ __PRETTY_FUNCTION__)); | |||
1218 | ||||
1219 | CurContext = getContainingDC(CurContext); | |||
1220 | assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!" ) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1220, __extension__ __PRETTY_FUNCTION__)); | |||
1221 | } | |||
1222 | ||||
1223 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, | |||
1224 | Decl *D) { | |||
1225 | // Unlike PushDeclContext, the context to which we return is not necessarily | |||
1226 | // the containing DC of TD, because the new context will be some pre-existing | |||
1227 | // TagDecl definition instead of a fresh one. | |||
1228 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); | |||
1229 | CurContext = cast<TagDecl>(D)->getDefinition(); | |||
1230 | assert(CurContext && "skipping definition of undefined tag")(static_cast <bool> (CurContext && "skipping definition of undefined tag" ) ? void (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1230, __extension__ __PRETTY_FUNCTION__)); | |||
1231 | // Start lookups from the parent of the current context; we don't want to look | |||
1232 | // into the pre-existing complete definition. | |||
1233 | S->setEntity(CurContext->getLookupParent()); | |||
1234 | return Result; | |||
1235 | } | |||
1236 | ||||
1237 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { | |||
1238 | CurContext = static_cast<decltype(CurContext)>(Context); | |||
1239 | } | |||
1240 | ||||
1241 | /// EnterDeclaratorContext - Used when we must lookup names in the context | |||
1242 | /// of a declarator's nested name specifier. | |||
1243 | /// | |||
1244 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { | |||
1245 | // C++0x [basic.lookup.unqual]p13: | |||
1246 | // A name used in the definition of a static data member of class | |||
1247 | // X (after the qualified-id of the static member) is looked up as | |||
1248 | // if the name was used in a member function of X. | |||
1249 | // C++0x [basic.lookup.unqual]p14: | |||
1250 | // If a variable member of a namespace is defined outside of the | |||
1251 | // scope of its namespace then any name used in the definition of | |||
1252 | // the variable member (after the declarator-id) is looked up as | |||
1253 | // if the definition of the variable member occurred in its | |||
1254 | // namespace. | |||
1255 | // Both of these imply that we should push a scope whose context | |||
1256 | // is the semantic context of the declaration. We can't use | |||
1257 | // PushDeclContext here because that context is not necessarily | |||
1258 | // lexically contained in the current context. Fortunately, | |||
1259 | // the containing scope should have the appropriate information. | |||
1260 | ||||
1261 | assert(!S->getEntity() && "scope already has entity")(static_cast <bool> (!S->getEntity() && "scope already has entity" ) ? void (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1261, __extension__ __PRETTY_FUNCTION__)); | |||
1262 | ||||
1263 | #ifndef NDEBUG | |||
1264 | Scope *Ancestor = S->getParent(); | |||
1265 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | |||
1266 | assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")(static_cast <bool> (Ancestor->getEntity() == CurContext && "ancestor context mismatch") ? void (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1266, __extension__ __PRETTY_FUNCTION__)); | |||
1267 | #endif | |||
1268 | ||||
1269 | CurContext = DC; | |||
1270 | S->setEntity(DC); | |||
1271 | } | |||
1272 | ||||
1273 | void Sema::ExitDeclaratorContext(Scope *S) { | |||
1274 | assert(S->getEntity() == CurContext && "Context imbalance!")(static_cast <bool> (S->getEntity() == CurContext && "Context imbalance!") ? void (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1274, __extension__ __PRETTY_FUNCTION__)); | |||
1275 | ||||
1276 | // Switch back to the lexical context. The safety of this is | |||
1277 | // enforced by an assert in EnterDeclaratorContext. | |||
1278 | Scope *Ancestor = S->getParent(); | |||
1279 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | |||
1280 | CurContext = Ancestor->getEntity(); | |||
1281 | ||||
1282 | // We don't need to do anything with the scope, which is going to | |||
1283 | // disappear. | |||
1284 | } | |||
1285 | ||||
1286 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { | |||
1287 | // We assume that the caller has already called | |||
1288 | // ActOnReenterTemplateScope so getTemplatedDecl() works. | |||
1289 | FunctionDecl *FD = D->getAsFunction(); | |||
1290 | if (!FD) | |||
1291 | return; | |||
1292 | ||||
1293 | // Same implementation as PushDeclContext, but enters the context | |||
1294 | // from the lexical parent, rather than the top-level class. | |||
1295 | assert(CurContext == FD->getLexicalParent() &&(static_cast <bool> (CurContext == FD->getLexicalParent () && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1296, __extension__ __PRETTY_FUNCTION__)) | |||
1296 | "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (CurContext == FD->getLexicalParent () && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1296, __extension__ __PRETTY_FUNCTION__)); | |||
1297 | CurContext = FD; | |||
1298 | S->setEntity(CurContext); | |||
1299 | ||||
1300 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { | |||
1301 | ParmVarDecl *Param = FD->getParamDecl(P); | |||
1302 | // If the parameter has an identifier, then add it to the scope | |||
1303 | if (Param->getIdentifier()) { | |||
1304 | S->AddDecl(Param); | |||
1305 | IdResolver.AddDecl(Param); | |||
1306 | } | |||
1307 | } | |||
1308 | } | |||
1309 | ||||
1310 | void Sema::ActOnExitFunctionContext() { | |||
1311 | // Same implementation as PopDeclContext, but returns to the lexical parent, | |||
1312 | // rather than the top-level class. | |||
1313 | assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!" ) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1313, __extension__ __PRETTY_FUNCTION__)); | |||
1314 | CurContext = CurContext->getLexicalParent(); | |||
1315 | assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!" ) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1315, __extension__ __PRETTY_FUNCTION__)); | |||
1316 | } | |||
1317 | ||||
1318 | /// Determine whether we allow overloading of the function | |||
1319 | /// PrevDecl with another declaration. | |||
1320 | /// | |||
1321 | /// This routine determines whether overloading is possible, not | |||
1322 | /// whether some new function is actually an overload. It will return | |||
1323 | /// true in C++ (where we can always provide overloads) or, as an | |||
1324 | /// extension, in C when the previous function is already an | |||
1325 | /// overloaded function declaration or has the "overloadable" | |||
1326 | /// attribute. | |||
1327 | static bool AllowOverloadingOfFunction(LookupResult &Previous, | |||
1328 | ASTContext &Context, | |||
1329 | const FunctionDecl *New) { | |||
1330 | if (Context.getLangOpts().CPlusPlus) | |||
1331 | return true; | |||
1332 | ||||
1333 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) | |||
1334 | return true; | |||
1335 | ||||
1336 | return Previous.getResultKind() == LookupResult::Found && | |||
1337 | (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || | |||
1338 | New->hasAttr<OverloadableAttr>()); | |||
1339 | } | |||
1340 | ||||
1341 | /// Add this decl to the scope shadowed decl chains. | |||
1342 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { | |||
1343 | // Move up the scope chain until we find the nearest enclosing | |||
1344 | // non-transparent context. The declaration will be introduced into this | |||
1345 | // scope. | |||
1346 | while (S->getEntity() && S->getEntity()->isTransparentContext()) | |||
1347 | S = S->getParent(); | |||
1348 | ||||
1349 | // Add scoped declarations into their context, so that they can be | |||
1350 | // found later. Declarations without a context won't be inserted | |||
1351 | // into any context. | |||
1352 | if (AddToContext) | |||
1353 | CurContext->addDecl(D); | |||
1354 | ||||
1355 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they | |||
1356 | // are function-local declarations. | |||
1357 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && | |||
1358 | !D->getDeclContext()->getRedeclContext()->Equals( | |||
1359 | D->getLexicalDeclContext()->getRedeclContext()) && | |||
1360 | !D->getLexicalDeclContext()->isFunctionOrMethod()) | |||
1361 | return; | |||
1362 | ||||
1363 | // Template instantiations should also not be pushed into scope. | |||
1364 | if (isa<FunctionDecl>(D) && | |||
1365 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) | |||
1366 | return; | |||
1367 | ||||
1368 | // If this replaces anything in the current scope, | |||
1369 | IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), | |||
1370 | IEnd = IdResolver.end(); | |||
1371 | for (; I != IEnd; ++I) { | |||
1372 | if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { | |||
1373 | S->RemoveDecl(*I); | |||
1374 | IdResolver.RemoveDecl(*I); | |||
1375 | ||||
1376 | // Should only need to replace one decl. | |||
1377 | break; | |||
1378 | } | |||
1379 | } | |||
1380 | ||||
1381 | S->AddDecl(D); | |||
1382 | ||||
1383 | if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { | |||
1384 | // Implicitly-generated labels may end up getting generated in an order that | |||
1385 | // isn't strictly lexical, which breaks name lookup. Be careful to insert | |||
1386 | // the label at the appropriate place in the identifier chain. | |||
1387 | for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { | |||
1388 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); | |||
1389 | if (IDC == CurContext) { | |||
1390 | if (!S->isDeclScope(*I)) | |||
1391 | continue; | |||
1392 | } else if (IDC->Encloses(CurContext)) | |||
1393 | break; | |||
1394 | } | |||
1395 | ||||
1396 | IdResolver.InsertDeclAfter(I, D); | |||
1397 | } else { | |||
1398 | IdResolver.AddDecl(D); | |||
1399 | } | |||
1400 | } | |||
1401 | ||||
1402 | void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { | |||
1403 | if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) | |||
1404 | TUScope->AddDecl(D); | |||
1405 | } | |||
1406 | ||||
1407 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, | |||
1408 | bool AllowInlineNamespace) { | |||
1409 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); | |||
1410 | } | |||
1411 | ||||
1412 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { | |||
1413 | DeclContext *TargetDC = DC->getPrimaryContext(); | |||
1414 | do { | |||
1415 | if (DeclContext *ScopeDC = S->getEntity()) | |||
1416 | if (ScopeDC->getPrimaryContext() == TargetDC) | |||
1417 | return S; | |||
1418 | } while ((S = S->getParent())); | |||
1419 | ||||
1420 | return nullptr; | |||
1421 | } | |||
1422 | ||||
1423 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, | |||
1424 | DeclContext*, | |||
1425 | ASTContext&); | |||
1426 | ||||
1427 | /// Filters out lookup results that don't fall within the given scope | |||
1428 | /// as determined by isDeclInScope. | |||
1429 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, | |||
1430 | bool ConsiderLinkage, | |||
1431 | bool AllowInlineNamespace) { | |||
1432 | LookupResult::Filter F = R.makeFilter(); | |||
1433 | while (F.hasNext()) { | |||
1434 | NamedDecl *D = F.next(); | |||
1435 | ||||
1436 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) | |||
1437 | continue; | |||
1438 | ||||
1439 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) | |||
1440 | continue; | |||
1441 | ||||
1442 | F.erase(); | |||
1443 | } | |||
1444 | ||||
1445 | F.done(); | |||
1446 | } | |||
1447 | ||||
1448 | /// We've determined that \p New is a redeclaration of \p Old. Check that they | |||
1449 | /// have compatible owning modules. | |||
1450 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { | |||
1451 | // FIXME: The Modules TS is not clear about how friend declarations are | |||
1452 | // to be treated. It's not meaningful to have different owning modules for | |||
1453 | // linkage in redeclarations of the same entity, so for now allow the | |||
1454 | // redeclaration and change the owning modules to match. | |||
1455 | if (New->getFriendObjectKind() && | |||
1456 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { | |||
1457 | New->setLocalOwningModule(Old->getOwningModule()); | |||
1458 | makeMergedDefinitionVisible(New); | |||
1459 | return false; | |||
1460 | } | |||
1461 | ||||
1462 | Module *NewM = New->getOwningModule(); | |||
1463 | Module *OldM = Old->getOwningModule(); | |||
1464 | if (NewM == OldM) | |||
1465 | return false; | |||
1466 | ||||
1467 | // FIXME: Check proclaimed-ownership-declarations here too. | |||
1468 | bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit; | |||
1469 | bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit; | |||
1470 | if (NewIsModuleInterface || OldIsModuleInterface) { | |||
1471 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: | |||
1472 | // if a declaration of D [...] appears in the purview of a module, all | |||
1473 | // other such declarations shall appear in the purview of the same module | |||
1474 | Diag(New->getLocation(), diag::err_mismatched_owning_module) | |||
1475 | << New | |||
1476 | << NewIsModuleInterface | |||
1477 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "") | |||
1478 | << OldIsModuleInterface | |||
1479 | << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); | |||
1480 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
1481 | New->setInvalidDecl(); | |||
1482 | return true; | |||
1483 | } | |||
1484 | ||||
1485 | return false; | |||
1486 | } | |||
1487 | ||||
1488 | static bool isUsingDecl(NamedDecl *D) { | |||
1489 | return isa<UsingShadowDecl>(D) || | |||
1490 | isa<UnresolvedUsingTypenameDecl>(D) || | |||
1491 | isa<UnresolvedUsingValueDecl>(D); | |||
1492 | } | |||
1493 | ||||
1494 | /// Removes using shadow declarations from the lookup results. | |||
1495 | static void RemoveUsingDecls(LookupResult &R) { | |||
1496 | LookupResult::Filter F = R.makeFilter(); | |||
1497 | while (F.hasNext()) | |||
1498 | if (isUsingDecl(F.next())) | |||
1499 | F.erase(); | |||
1500 | ||||
1501 | F.done(); | |||
1502 | } | |||
1503 | ||||
1504 | /// Check for this common pattern: | |||
1505 | /// @code | |||
1506 | /// class S { | |||
1507 | /// S(const S&); // DO NOT IMPLEMENT | |||
1508 | /// void operator=(const S&); // DO NOT IMPLEMENT | |||
1509 | /// }; | |||
1510 | /// @endcode | |||
1511 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { | |||
1512 | // FIXME: Should check for private access too but access is set after we get | |||
1513 | // the decl here. | |||
1514 | if (D->doesThisDeclarationHaveABody()) | |||
1515 | return false; | |||
1516 | ||||
1517 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) | |||
1518 | return CD->isCopyConstructor(); | |||
1519 | return D->isCopyAssignmentOperator(); | |||
1520 | } | |||
1521 | ||||
1522 | // We need this to handle | |||
1523 | // | |||
1524 | // typedef struct { | |||
1525 | // void *foo() { return 0; } | |||
1526 | // } A; | |||
1527 | // | |||
1528 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' | |||
1529 | // for example. If 'A', foo will have external linkage. If we have '*A', | |||
1530 | // foo will have no linkage. Since we can't know until we get to the end | |||
1531 | // of the typedef, this function finds out if D might have non-external linkage. | |||
1532 | // Callers should verify at the end of the TU if it D has external linkage or | |||
1533 | // not. | |||
1534 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { | |||
1535 | const DeclContext *DC = D->getDeclContext(); | |||
1536 | while (!DC->isTranslationUnit()) { | |||
1537 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ | |||
1538 | if (!RD->hasNameForLinkage()) | |||
1539 | return true; | |||
1540 | } | |||
1541 | DC = DC->getParent(); | |||
1542 | } | |||
1543 | ||||
1544 | return !D->isExternallyVisible(); | |||
1545 | } | |||
1546 | ||||
1547 | // FIXME: This needs to be refactored; some other isInMainFile users want | |||
1548 | // these semantics. | |||
1549 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { | |||
1550 | if (S.TUKind != TU_Complete) | |||
1551 | return false; | |||
1552 | return S.SourceMgr.isInMainFile(Loc); | |||
1553 | } | |||
1554 | ||||
1555 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { | |||
1556 | assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1556, __extension__ __PRETTY_FUNCTION__)); | |||
1557 | ||||
1558 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) | |||
1559 | return false; | |||
1560 | ||||
1561 | // Ignore all entities declared within templates, and out-of-line definitions | |||
1562 | // of members of class templates. | |||
1563 | if (D->getDeclContext()->isDependentContext() || | |||
1564 | D->getLexicalDeclContext()->isDependentContext()) | |||
1565 | return false; | |||
1566 | ||||
1567 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
1568 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | |||
1569 | return false; | |||
1570 | // A non-out-of-line declaration of a member specialization was implicitly | |||
1571 | // instantiated; it's the out-of-line declaration that we're interested in. | |||
1572 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | |||
1573 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) | |||
1574 | return false; | |||
1575 | ||||
1576 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | |||
1577 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) | |||
1578 | return false; | |||
1579 | } else { | |||
1580 | // 'static inline' functions are defined in headers; don't warn. | |||
1581 | if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) | |||
1582 | return false; | |||
1583 | } | |||
1584 | ||||
1585 | if (FD->doesThisDeclarationHaveABody() && | |||
1586 | Context.DeclMustBeEmitted(FD)) | |||
1587 | return false; | |||
1588 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1589 | // Constants and utility variables are defined in headers with internal | |||
1590 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker | |||
1591 | // like "inline".) | |||
1592 | if (!isMainFileLoc(*this, VD->getLocation())) | |||
1593 | return false; | |||
1594 | ||||
1595 | if (Context.DeclMustBeEmitted(VD)) | |||
1596 | return false; | |||
1597 | ||||
1598 | if (VD->isStaticDataMember() && | |||
1599 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | |||
1600 | return false; | |||
1601 | if (VD->isStaticDataMember() && | |||
1602 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | |||
1603 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) | |||
1604 | return false; | |||
1605 | ||||
1606 | if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) | |||
1607 | return false; | |||
1608 | } else { | |||
1609 | return false; | |||
1610 | } | |||
1611 | ||||
1612 | // Only warn for unused decls internal to the translation unit. | |||
1613 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function | |||
1614 | // for inline functions defined in the main source file, for instance. | |||
1615 | return mightHaveNonExternalLinkage(D); | |||
1616 | } | |||
1617 | ||||
1618 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { | |||
1619 | if (!D) | |||
1620 | return; | |||
1621 | ||||
1622 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
1623 | const FunctionDecl *First = FD->getFirstDecl(); | |||
1624 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | |||
1625 | return; // First should already be in the vector. | |||
1626 | } | |||
1627 | ||||
1628 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1629 | const VarDecl *First = VD->getFirstDecl(); | |||
1630 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | |||
1631 | return; // First should already be in the vector. | |||
1632 | } | |||
1633 | ||||
1634 | if (ShouldWarnIfUnusedFileScopedDecl(D)) | |||
1635 | UnusedFileScopedDecls.push_back(D); | |||
1636 | } | |||
1637 | ||||
1638 | static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { | |||
1639 | if (D->isInvalidDecl()) | |||
1640 | return false; | |||
1641 | ||||
1642 | bool Referenced = false; | |||
1643 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) { | |||
1644 | // For a decomposition declaration, warn if none of the bindings are | |||
1645 | // referenced, instead of if the variable itself is referenced (which | |||
1646 | // it is, by the bindings' expressions). | |||
1647 | for (auto *BD : DD->bindings()) { | |||
1648 | if (BD->isReferenced()) { | |||
1649 | Referenced = true; | |||
1650 | break; | |||
1651 | } | |||
1652 | } | |||
1653 | } else if (!D->getDeclName()) { | |||
1654 | return false; | |||
1655 | } else if (D->isReferenced() || D->isUsed()) { | |||
1656 | Referenced = true; | |||
1657 | } | |||
1658 | ||||
1659 | if (Referenced || D->hasAttr<UnusedAttr>() || | |||
1660 | D->hasAttr<ObjCPreciseLifetimeAttr>()) | |||
1661 | return false; | |||
1662 | ||||
1663 | if (isa<LabelDecl>(D)) | |||
1664 | return true; | |||
1665 | ||||
1666 | // Except for labels, we only care about unused decls that are local to | |||
1667 | // functions. | |||
1668 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); | |||
1669 | if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) | |||
1670 | // For dependent types, the diagnostic is deferred. | |||
1671 | WithinFunction = | |||
1672 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); | |||
1673 | if (!WithinFunction) | |||
1674 | return false; | |||
1675 | ||||
1676 | if (isa<TypedefNameDecl>(D)) | |||
1677 | return true; | |||
1678 | ||||
1679 | // White-list anything that isn't a local variable. | |||
1680 | if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) | |||
1681 | return false; | |||
1682 | ||||
1683 | // Types of valid local variables should be complete, so this should succeed. | |||
1684 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1685 | ||||
1686 | // White-list anything with an __attribute__((unused)) type. | |||
1687 | const auto *Ty = VD->getType().getTypePtr(); | |||
1688 | ||||
1689 | // Only look at the outermost level of typedef. | |||
1690 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { | |||
1691 | if (TT->getDecl()->hasAttr<UnusedAttr>()) | |||
1692 | return false; | |||
1693 | } | |||
1694 | ||||
1695 | // If we failed to complete the type for some reason, or if the type is | |||
1696 | // dependent, don't diagnose the variable. | |||
1697 | if (Ty->isIncompleteType() || Ty->isDependentType()) | |||
1698 | return false; | |||
1699 | ||||
1700 | // Look at the element type to ensure that the warning behaviour is | |||
1701 | // consistent for both scalars and arrays. | |||
1702 | Ty = Ty->getBaseElementTypeUnsafe(); | |||
1703 | ||||
1704 | if (const TagType *TT = Ty->getAs<TagType>()) { | |||
1705 | const TagDecl *Tag = TT->getDecl(); | |||
1706 | if (Tag->hasAttr<UnusedAttr>()) | |||
1707 | return false; | |||
1708 | ||||
1709 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { | |||
1710 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) | |||
1711 | return false; | |||
1712 | ||||
1713 | if (const Expr *Init = VD->getInit()) { | |||
1714 | if (const ExprWithCleanups *Cleanups = | |||
1715 | dyn_cast<ExprWithCleanups>(Init)) | |||
1716 | Init = Cleanups->getSubExpr(); | |||
1717 | const CXXConstructExpr *Construct = | |||
1718 | dyn_cast<CXXConstructExpr>(Init); | |||
1719 | if (Construct && !Construct->isElidable()) { | |||
1720 | CXXConstructorDecl *CD = Construct->getConstructor(); | |||
1721 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && | |||
1722 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) | |||
1723 | return false; | |||
1724 | } | |||
1725 | } | |||
1726 | } | |||
1727 | } | |||
1728 | ||||
1729 | // TODO: __attribute__((unused)) templates? | |||
1730 | } | |||
1731 | ||||
1732 | return true; | |||
1733 | } | |||
1734 | ||||
1735 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, | |||
1736 | FixItHint &Hint) { | |||
1737 | if (isa<LabelDecl>(D)) { | |||
1738 | SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), | |||
1739 | tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); | |||
1740 | if (AfterColon.isInvalid()) | |||
1741 | return; | |||
1742 | Hint = FixItHint::CreateRemoval(CharSourceRange:: | |||
1743 | getCharRange(D->getLocStart(), AfterColon)); | |||
1744 | } | |||
1745 | } | |||
1746 | ||||
1747 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { | |||
1748 | if (D->getTypeForDecl()->isDependentType()) | |||
1749 | return; | |||
1750 | ||||
1751 | for (auto *TmpD : D->decls()) { | |||
1752 | if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) | |||
1753 | DiagnoseUnusedDecl(T); | |||
1754 | else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) | |||
1755 | DiagnoseUnusedNestedTypedefs(R); | |||
1756 | } | |||
1757 | } | |||
1758 | ||||
1759 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used | |||
1760 | /// unless they are marked attr(unused). | |||
1761 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { | |||
1762 | if (!ShouldDiagnoseUnusedDecl(D)) | |||
1763 | return; | |||
1764 | ||||
1765 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { | |||
1766 | // typedefs can be referenced later on, so the diagnostics are emitted | |||
1767 | // at end-of-translation-unit. | |||
1768 | UnusedLocalTypedefNameCandidates.insert(TD); | |||
1769 | return; | |||
1770 | } | |||
1771 | ||||
1772 | FixItHint Hint; | |||
1773 | GenerateFixForUnusedDecl(D, Context, Hint); | |||
1774 | ||||
1775 | unsigned DiagID; | |||
1776 | if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) | |||
1777 | DiagID = diag::warn_unused_exception_param; | |||
1778 | else if (isa<LabelDecl>(D)) | |||
1779 | DiagID = diag::warn_unused_label; | |||
1780 | else | |||
1781 | DiagID = diag::warn_unused_variable; | |||
1782 | ||||
1783 | Diag(D->getLocation(), DiagID) << D << Hint; | |||
1784 | } | |||
1785 | ||||
1786 | static void CheckPoppedLabel(LabelDecl *L, Sema &S) { | |||
1787 | // Verify that we have no forward references left. If so, there was a goto | |||
1788 | // or address of a label taken, but no definition of it. Label fwd | |||
1789 | // definitions are indicated with a null substmt which is also not a resolved | |||
1790 | // MS inline assembly label name. | |||
1791 | bool Diagnose = false; | |||
1792 | if (L->isMSAsmLabel()) | |||
1793 | Diagnose = !L->isResolvedMSAsmLabel(); | |||
1794 | else | |||
1795 | Diagnose = L->getStmt() == nullptr; | |||
1796 | if (Diagnose) | |||
1797 | S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); | |||
1798 | } | |||
1799 | ||||
1800 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { | |||
1801 | S->mergeNRVOIntoParent(); | |||
1802 | ||||
1803 | if (S->decl_empty()) return; | |||
1804 | assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(static_cast <bool> ((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && "Scope shouldn't contain decls!" ) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1805, __extension__ __PRETTY_FUNCTION__)) | |||
1805 | "Scope shouldn't contain decls!")(static_cast <bool> ((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && "Scope shouldn't contain decls!" ) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1805, __extension__ __PRETTY_FUNCTION__)); | |||
1806 | ||||
1807 | for (auto *TmpD : S->decls()) { | |||
1808 | assert(TmpD && "This decl didn't get pushed??")(static_cast <bool> (TmpD && "This decl didn't get pushed??" ) ? void (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1808, __extension__ __PRETTY_FUNCTION__)); | |||
1809 | ||||
1810 | assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")(static_cast <bool> (isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?") ? void (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1810, __extension__ __PRETTY_FUNCTION__)); | |||
1811 | NamedDecl *D = cast<NamedDecl>(TmpD); | |||
1812 | ||||
1813 | // Diagnose unused variables in this scope. | |||
1814 | if (!S->hasUnrecoverableErrorOccurred()) { | |||
1815 | DiagnoseUnusedDecl(D); | |||
1816 | if (const auto *RD = dyn_cast<RecordDecl>(D)) | |||
1817 | DiagnoseUnusedNestedTypedefs(RD); | |||
1818 | } | |||
1819 | ||||
1820 | if (!D->getDeclName()) continue; | |||
1821 | ||||
1822 | // If this was a forward reference to a label, verify it was defined. | |||
1823 | if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) | |||
1824 | CheckPoppedLabel(LD, *this); | |||
1825 | ||||
1826 | // Remove this name from our lexical scope, and warn on it if we haven't | |||
1827 | // already. | |||
1828 | IdResolver.RemoveDecl(D); | |||
1829 | auto ShadowI = ShadowingDecls.find(D); | |||
1830 | if (ShadowI != ShadowingDecls.end()) { | |||
1831 | if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { | |||
1832 | Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) | |||
1833 | << D << FD << FD->getParent(); | |||
1834 | Diag(FD->getLocation(), diag::note_previous_declaration); | |||
1835 | } | |||
1836 | ShadowingDecls.erase(ShadowI); | |||
1837 | } | |||
1838 | } | |||
1839 | } | |||
1840 | ||||
1841 | /// Look for an Objective-C class in the translation unit. | |||
1842 | /// | |||
1843 | /// \param Id The name of the Objective-C class we're looking for. If | |||
1844 | /// typo-correction fixes this name, the Id will be updated | |||
1845 | /// to the fixed name. | |||
1846 | /// | |||
1847 | /// \param IdLoc The location of the name in the translation unit. | |||
1848 | /// | |||
1849 | /// \param DoTypoCorrection If true, this routine will attempt typo correction | |||
1850 | /// if there is no class with the given name. | |||
1851 | /// | |||
1852 | /// \returns The declaration of the named Objective-C class, or NULL if the | |||
1853 | /// class could not be found. | |||
1854 | ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, | |||
1855 | SourceLocation IdLoc, | |||
1856 | bool DoTypoCorrection) { | |||
1857 | // The third "scope" argument is 0 since we aren't enabling lazy built-in | |||
1858 | // creation from this context. | |||
1859 | NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); | |||
1860 | ||||
1861 | if (!IDecl && DoTypoCorrection) { | |||
1862 | // Perform typo correction at the given location, but only if we | |||
1863 | // find an Objective-C class name. | |||
1864 | if (TypoCorrection C = CorrectTypo( | |||
1865 | DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, | |||
1866 | llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), | |||
1867 | CTK_ErrorRecovery)) { | |||
1868 | diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); | |||
1869 | IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); | |||
1870 | Id = IDecl->getIdentifier(); | |||
1871 | } | |||
1872 | } | |||
1873 | ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); | |||
1874 | // This routine must always return a class definition, if any. | |||
1875 | if (Def && Def->getDefinition()) | |||
1876 | Def = Def->getDefinition(); | |||
1877 | return Def; | |||
1878 | } | |||
1879 | ||||
1880 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting | |||
1881 | /// from S, where a non-field would be declared. This routine copes | |||
1882 | /// with the difference between C and C++ scoping rules in structs and | |||
1883 | /// unions. For example, the following code is well-formed in C but | |||
1884 | /// ill-formed in C++: | |||
1885 | /// @code | |||
1886 | /// struct S6 { | |||
1887 | /// enum { BAR } e; | |||
1888 | /// }; | |||
1889 | /// | |||
1890 | /// void test_S6() { | |||
1891 | /// struct S6 a; | |||
1892 | /// a.e = BAR; | |||
1893 | /// } | |||
1894 | /// @endcode | |||
1895 | /// For the declaration of BAR, this routine will return a different | |||
1896 | /// scope. The scope S will be the scope of the unnamed enumeration | |||
1897 | /// within S6. In C++, this routine will return the scope associated | |||
1898 | /// with S6, because the enumeration's scope is a transparent | |||
1899 | /// context but structures can contain non-field names. In C, this | |||
1900 | /// routine will return the translation unit scope, since the | |||
1901 | /// enumeration's scope is a transparent context and structures cannot | |||
1902 | /// contain non-field names. | |||
1903 | Scope *Sema::getNonFieldDeclScope(Scope *S) { | |||
1904 | while (((S->getFlags() & Scope::DeclScope) == 0) || | |||
1905 | (S->getEntity() && S->getEntity()->isTransparentContext()) || | |||
1906 | (S->isClassScope() && !getLangOpts().CPlusPlus)) | |||
1907 | S = S->getParent(); | |||
1908 | return S; | |||
1909 | } | |||
1910 | ||||
1911 | /// Looks up the declaration of "struct objc_super" and | |||
1912 | /// saves it for later use in building builtin declaration of | |||
1913 | /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such | |||
1914 | /// pre-existing declaration exists no action takes place. | |||
1915 | static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, | |||
1916 | IdentifierInfo *II) { | |||
1917 | if (!II->isStr("objc_msgSendSuper")) | |||
1918 | return; | |||
1919 | ASTContext &Context = ThisSema.Context; | |||
1920 | ||||
1921 | LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), | |||
1922 | SourceLocation(), Sema::LookupTagName); | |||
1923 | ThisSema.LookupName(Result, S); | |||
1924 | if (Result.getResultKind() == LookupResult::Found) | |||
1925 | if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) | |||
1926 | Context.setObjCSuperType(Context.getTagDeclType(TD)); | |||
1927 | } | |||
1928 | ||||
1929 | static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { | |||
1930 | switch (Error) { | |||
1931 | case ASTContext::GE_None: | |||
1932 | return ""; | |||
1933 | case ASTContext::GE_Missing_stdio: | |||
1934 | return "stdio.h"; | |||
1935 | case ASTContext::GE_Missing_setjmp: | |||
1936 | return "setjmp.h"; | |||
1937 | case ASTContext::GE_Missing_ucontext: | |||
1938 | return "ucontext.h"; | |||
1939 | } | |||
1940 | llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 1940); | |||
1941 | } | |||
1942 | ||||
1943 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at | |||
1944 | /// file scope. lazily create a decl for it. ForRedeclaration is true | |||
1945 | /// if we're creating this built-in in anticipation of redeclaring the | |||
1946 | /// built-in. | |||
1947 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, | |||
1948 | Scope *S, bool ForRedeclaration, | |||
1949 | SourceLocation Loc) { | |||
1950 | LookupPredefedObjCSuperType(*this, S, II); | |||
1951 | ||||
1952 | ASTContext::GetBuiltinTypeError Error; | |||
1953 | QualType R = Context.GetBuiltinType(ID, Error); | |||
1954 | if (Error) { | |||
1955 | if (ForRedeclaration) | |||
1956 | Diag(Loc, diag::warn_implicit_decl_requires_sysheader) | |||
1957 | << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); | |||
1958 | return nullptr; | |||
1959 | } | |||
1960 | ||||
1961 | if (!ForRedeclaration && | |||
1962 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || | |||
1963 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { | |||
1964 | Diag(Loc, diag::ext_implicit_lib_function_decl) | |||
1965 | << Context.BuiltinInfo.getName(ID) << R; | |||
1966 | if (Context.BuiltinInfo.getHeaderName(ID) && | |||
1967 | !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) | |||
1968 | Diag(Loc, diag::note_include_header_or_declare) | |||
1969 | << Context.BuiltinInfo.getHeaderName(ID) | |||
1970 | << Context.BuiltinInfo.getName(ID); | |||
1971 | } | |||
1972 | ||||
1973 | if (R.isNull()) | |||
1974 | return nullptr; | |||
1975 | ||||
1976 | DeclContext *Parent = Context.getTranslationUnitDecl(); | |||
1977 | if (getLangOpts().CPlusPlus) { | |||
1978 | LinkageSpecDecl *CLinkageDecl = | |||
1979 | LinkageSpecDecl::Create(Context, Parent, Loc, Loc, | |||
1980 | LinkageSpecDecl::lang_c, false); | |||
1981 | CLinkageDecl->setImplicit(); | |||
1982 | Parent->addDecl(CLinkageDecl); | |||
1983 | Parent = CLinkageDecl; | |||
1984 | } | |||
1985 | ||||
1986 | FunctionDecl *New = FunctionDecl::Create(Context, | |||
1987 | Parent, | |||
1988 | Loc, Loc, II, R, /*TInfo=*/nullptr, | |||
1989 | SC_Extern, | |||
1990 | false, | |||
1991 | R->isFunctionProtoType()); | |||
1992 | New->setImplicit(); | |||
1993 | ||||
1994 | // Create Decl objects for each parameter, adding them to the | |||
1995 | // FunctionDecl. | |||
1996 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { | |||
1997 | SmallVector<ParmVarDecl*, 16> Params; | |||
1998 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | |||
1999 | ParmVarDecl *parm = | |||
2000 | ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), | |||
2001 | nullptr, FT->getParamType(i), /*TInfo=*/nullptr, | |||
2002 | SC_None, nullptr); | |||
2003 | parm->setScopeInfo(0, i); | |||
2004 | Params.push_back(parm); | |||
2005 | } | |||
2006 | New->setParams(Params); | |||
2007 | } | |||
2008 | ||||
2009 | AddKnownFunctionAttributes(New); | |||
2010 | RegisterLocallyScopedExternCDecl(New, S); | |||
2011 | ||||
2012 | // TUScope is the translation-unit scope to insert this function into. | |||
2013 | // FIXME: This is hideous. We need to teach PushOnScopeChains to | |||
2014 | // relate Scopes to DeclContexts, and probably eliminate CurContext | |||
2015 | // entirely, but we're not there yet. | |||
2016 | DeclContext *SavedContext = CurContext; | |||
2017 | CurContext = Parent; | |||
2018 | PushOnScopeChains(New, TUScope); | |||
2019 | CurContext = SavedContext; | |||
2020 | return New; | |||
2021 | } | |||
2022 | ||||
2023 | /// Typedef declarations don't have linkage, but they still denote the same | |||
2024 | /// entity if their types are the same. | |||
2025 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's | |||
2026 | /// isSameEntity. | |||
2027 | static void filterNonConflictingPreviousTypedefDecls(Sema &S, | |||
2028 | TypedefNameDecl *Decl, | |||
2029 | LookupResult &Previous) { | |||
2030 | // This is only interesting when modules are enabled. | |||
2031 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) | |||
2032 | return; | |||
2033 | ||||
2034 | // Empty sets are uninteresting. | |||
2035 | if (Previous.empty()) | |||
2036 | return; | |||
2037 | ||||
2038 | LookupResult::Filter Filter = Previous.makeFilter(); | |||
2039 | while (Filter.hasNext()) { | |||
2040 | NamedDecl *Old = Filter.next(); | |||
2041 | ||||
2042 | // Non-hidden declarations are never ignored. | |||
2043 | if (S.isVisible(Old)) | |||
2044 | continue; | |||
2045 | ||||
2046 | // Declarations of the same entity are not ignored, even if they have | |||
2047 | // different linkages. | |||
2048 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | |||
2049 | if (S.Context.hasSameType(OldTD->getUnderlyingType(), | |||
2050 | Decl->getUnderlyingType())) | |||
2051 | continue; | |||
2052 | ||||
2053 | // If both declarations give a tag declaration a typedef name for linkage | |||
2054 | // purposes, then they declare the same entity. | |||
2055 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && | |||
2056 | Decl->getAnonDeclWithTypedefName()) | |||
2057 | continue; | |||
2058 | } | |||
2059 | ||||
2060 | Filter.erase(); | |||
2061 | } | |||
2062 | ||||
2063 | Filter.done(); | |||
2064 | } | |||
2065 | ||||
2066 | bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { | |||
2067 | QualType OldType; | |||
2068 | if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) | |||
2069 | OldType = OldTypedef->getUnderlyingType(); | |||
2070 | else | |||
2071 | OldType = Context.getTypeDeclType(Old); | |||
2072 | QualType NewType = New->getUnderlyingType(); | |||
2073 | ||||
2074 | if (NewType->isVariablyModifiedType()) { | |||
2075 | // Must not redefine a typedef with a variably-modified type. | |||
2076 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | |||
2077 | Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) | |||
2078 | << Kind << NewType; | |||
2079 | if (Old->getLocation().isValid()) | |||
2080 | notePreviousDefinition(Old, New->getLocation()); | |||
2081 | New->setInvalidDecl(); | |||
2082 | return true; | |||
2083 | } | |||
2084 | ||||
2085 | if (OldType != NewType && | |||
2086 | !OldType->isDependentType() && | |||
2087 | !NewType->isDependentType() && | |||
2088 | !Context.hasSameType(OldType, NewType)) { | |||
2089 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | |||
2090 | Diag(New->getLocation(), diag::err_redefinition_different_typedef) | |||
2091 | << Kind << NewType << OldType; | |||
2092 | if (Old->getLocation().isValid()) | |||
2093 | notePreviousDefinition(Old, New->getLocation()); | |||
2094 | New->setInvalidDecl(); | |||
2095 | return true; | |||
2096 | } | |||
2097 | return false; | |||
2098 | } | |||
2099 | ||||
2100 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the | |||
2101 | /// same name and scope as a previous declaration 'Old'. Figure out | |||
2102 | /// how to resolve this situation, merging decls or emitting | |||
2103 | /// diagnostics as appropriate. If there was an error, set New to be invalid. | |||
2104 | /// | |||
2105 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, | |||
2106 | LookupResult &OldDecls) { | |||
2107 | // If the new decl is known invalid already, don't bother doing any | |||
2108 | // merging checks. | |||
2109 | if (New->isInvalidDecl()) return; | |||
2110 | ||||
2111 | // Allow multiple definitions for ObjC built-in typedefs. | |||
2112 | // FIXME: Verify the underlying types are equivalent! | |||
2113 | if (getLangOpts().ObjC1) { | |||
2114 | const IdentifierInfo *TypeID = New->getIdentifier(); | |||
2115 | switch (TypeID->getLength()) { | |||
2116 | default: break; | |||
2117 | case 2: | |||
2118 | { | |||
2119 | if (!TypeID->isStr("id")) | |||
2120 | break; | |||
2121 | QualType T = New->getUnderlyingType(); | |||
2122 | if (!T->isPointerType()) | |||
2123 | break; | |||
2124 | if (!T->isVoidPointerType()) { | |||
2125 | QualType PT = T->getAs<PointerType>()->getPointeeType(); | |||
2126 | if (!PT->isStructureType()) | |||
2127 | break; | |||
2128 | } | |||
2129 | Context.setObjCIdRedefinitionType(T); | |||
2130 | // Install the built-in type for 'id', ignoring the current definition. | |||
2131 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); | |||
2132 | return; | |||
2133 | } | |||
2134 | case 5: | |||
2135 | if (!TypeID->isStr("Class")) | |||
2136 | break; | |||
2137 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); | |||
2138 | // Install the built-in type for 'Class', ignoring the current definition. | |||
2139 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); | |||
2140 | return; | |||
2141 | case 3: | |||
2142 | if (!TypeID->isStr("SEL")) | |||
2143 | break; | |||
2144 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); | |||
2145 | // Install the built-in type for 'SEL', ignoring the current definition. | |||
2146 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); | |||
2147 | return; | |||
2148 | } | |||
2149 | // Fall through - the typedef name was not a builtin type. | |||
2150 | } | |||
2151 | ||||
2152 | // Verify the old decl was also a type. | |||
2153 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); | |||
2154 | if (!Old) { | |||
2155 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | |||
2156 | << New->getDeclName(); | |||
2157 | ||||
2158 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); | |||
2159 | if (OldD->getLocation().isValid()) | |||
2160 | notePreviousDefinition(OldD, New->getLocation()); | |||
2161 | ||||
2162 | return New->setInvalidDecl(); | |||
2163 | } | |||
2164 | ||||
2165 | // If the old declaration is invalid, just give up here. | |||
2166 | if (Old->isInvalidDecl()) | |||
2167 | return New->setInvalidDecl(); | |||
2168 | ||||
2169 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | |||
2170 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); | |||
2171 | auto *NewTag = New->getAnonDeclWithTypedefName(); | |||
2172 | NamedDecl *Hidden = nullptr; | |||
2173 | if (OldTag && NewTag && | |||
2174 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && | |||
2175 | !hasVisibleDefinition(OldTag, &Hidden)) { | |||
2176 | // There is a definition of this tag, but it is not visible. Use it | |||
2177 | // instead of our tag. | |||
2178 | New->setTypeForDecl(OldTD->getTypeForDecl()); | |||
2179 | if (OldTD->isModed()) | |||
2180 | New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), | |||
2181 | OldTD->getUnderlyingType()); | |||
2182 | else | |||
2183 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); | |||
2184 | ||||
2185 | // Make the old tag definition visible. | |||
2186 | makeMergedDefinitionVisible(Hidden); | |||
2187 | ||||
2188 | // If this was an unscoped enumeration, yank all of its enumerators | |||
2189 | // out of the scope. | |||
2190 | if (isa<EnumDecl>(NewTag)) { | |||
2191 | Scope *EnumScope = getNonFieldDeclScope(S); | |||
2192 | for (auto *D : NewTag->decls()) { | |||
2193 | auto *ED = cast<EnumConstantDecl>(D); | |||
2194 | assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void (0) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 2194, __extension__ __PRETTY_FUNCTION__)); | |||
2195 | EnumScope->RemoveDecl(ED); | |||
2196 | IdResolver.RemoveDecl(ED); | |||
2197 | ED->getLexicalDeclContext()->removeDecl(ED); | |||
2198 | } | |||
2199 | } | |||
2200 | } | |||
2201 | } | |||
2202 | ||||
2203 | // If the typedef types are not identical, reject them in all languages and | |||
2204 | // with any extensions enabled. | |||
2205 | if (isIncompatibleTypedef(Old, New)) | |||
2206 | return; | |||
2207 | ||||
2208 | // The types match. Link up the redeclaration chain and merge attributes if | |||
2209 | // the old declaration was a typedef. | |||
2210 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { | |||
2211 | New->setPreviousDecl(Typedef); | |||
2212 | mergeDeclAttributes(New, Old); | |||
2213 | } | |||
2214 | ||||
2215 | if (getLangOpts().MicrosoftExt) | |||
2216 | return; | |||
2217 | ||||
2218 | if (getLangOpts().CPlusPlus) { | |||
2219 | // C++ [dcl.typedef]p2: | |||
2220 | // In a given non-class scope, a typedef specifier can be used to | |||
2221 | // redefine the name of any type declared in that scope to refer | |||
2222 | // to the type to which it already refers. | |||
2223 | if (!isa<CXXRecordDecl>(CurContext)) | |||
2224 | return; | |||
2225 | ||||
2226 | // C++0x [dcl.typedef]p4: | |||
2227 | // In a given class scope, a typedef specifier can be used to redefine | |||
2228 | // any class-name declared in that scope that is not also a typedef-name | |||
2229 | // to refer to the type to which it already refers. | |||
2230 | // | |||
2231 | // This wording came in via DR424, which was a correction to the | |||
2232 | // wording in DR56, which accidentally banned code like: | |||
2233 | // | |||
2234 | // struct S { | |||
2235 | // typedef struct A { } A; | |||
2236 | // }; | |||
2237 | // | |||
2238 | // in the C++03 standard. We implement the C++0x semantics, which | |||
2239 | // allow the above but disallow | |||
2240 | // | |||
2241 | // struct S { | |||
2242 | // typedef int I; | |||
2243 | // typedef int I; | |||
2244 | // }; | |||
2245 | // | |||
2246 | // since that was the intent of DR56. | |||
2247 | if (!isa<TypedefNameDecl>(Old)) | |||
2248 | return; | |||
2249 | ||||
2250 | Diag(New->getLocation(), diag::err_redefinition) | |||
2251 | << New->getDeclName(); | |||
2252 | notePreviousDefinition(Old, New->getLocation()); | |||
2253 | return New->setInvalidDecl(); | |||
2254 | } | |||
2255 | ||||
2256 | // Modules always permit redefinition of typedefs, as does C11. | |||
2257 | if (getLangOpts().Modules || getLangOpts().C11) | |||
2258 | return; | |||
2259 | ||||
2260 | // If we have a redefinition of a typedef in C, emit a warning. This warning | |||
2261 | // is normally mapped to an error, but can be controlled with | |||
2262 | // -Wtypedef-redefinition. If either the original or the redefinition is | |||
2263 | // in a system header, don't emit this for compatibility with GCC. | |||
2264 | if (getDiagnostics().getSuppressSystemWarnings() && | |||
2265 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). | |||
2266 | (Old->isImplicit() || | |||
2267 | Context.getSourceManager().isInSystemHeader(Old->getLocation()) || | |||
2268 | Context.getSourceManager().isInSystemHeader(New->getLocation()))) | |||
2269 | return; | |||
2270 | ||||
2271 | Diag(New->getLocation(), diag::ext_redefinition_of_typedef) | |||
2272 | << New->getDeclName(); | |||
2273 | notePreviousDefinition(Old, New->getLocation()); | |||
2274 | } | |||
2275 | ||||
2276 | /// DeclhasAttr - returns true if decl Declaration already has the target | |||
2277 | /// attribute. | |||
2278 | static bool DeclHasAttr(const Decl *D, const Attr *A) { | |||
2279 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); | |||
2280 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); | |||
2281 | for (const auto *i : D->attrs()) | |||
2282 | if (i->getKind() == A->getKind()) { | |||
2283 | if (Ann) { | |||
2284 | if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) | |||
2285 | return true; | |||
2286 | continue; | |||
2287 | } | |||
2288 | // FIXME: Don't hardcode this check | |||
2289 | if (OA && isa<OwnershipAttr>(i)) | |||
2290 | return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); | |||
2291 | return true; | |||
2292 | } | |||
2293 | ||||
2294 | return false; | |||
2295 | } | |||
2296 | ||||
2297 | static bool isAttributeTargetADefinition(Decl *D) { | |||
2298 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) | |||
2299 | return VD->isThisDeclarationADefinition(); | |||
2300 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) | |||
2301 | return TD->isCompleteDefinition() || TD->isBeingDefined(); | |||
2302 | return true; | |||
2303 | } | |||
2304 | ||||
2305 | /// Merge alignment attributes from \p Old to \p New, taking into account the | |||
2306 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. | |||
2307 | /// | |||
2308 | /// \return \c true if any attributes were added to \p New. | |||
2309 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { | |||
2310 | // Look for alignas attributes on Old, and pick out whichever attribute | |||
2311 | // specifies the strictest alignment requirement. | |||
2312 | AlignedAttr *OldAlignasAttr = nullptr; | |||
2313 | AlignedAttr *OldStrictestAlignAttr = nullptr; | |||
2314 | unsigned OldAlign = 0; | |||
2315 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { | |||
2316 | // FIXME: We have no way of representing inherited dependent alignments | |||
2317 | // in a case like: | |||
2318 | // template<int A, int B> struct alignas(A) X; | |||
2319 | // template<int A, int B> struct alignas(B) X {}; | |||
2320 | // For now, we just ignore any alignas attributes which are not on the | |||
2321 | // definition in such a case. | |||
2322 | if (I->isAlignmentDependent()) | |||
2323 | return false; | |||
2324 | ||||
2325 | if (I->isAlignas()) | |||
2326 | OldAlignasAttr = I; | |||
2327 | ||||
2328 | unsigned Align = I->getAlignment(S.Context); | |||
2329 | if (Align > OldAlign) { | |||
2330 | OldAlign = Align; | |||
2331 | OldStrictestAlignAttr = I; | |||
2332 | } | |||
2333 | } | |||
2334 | ||||
2335 | // Look for alignas attributes on New. | |||
2336 | AlignedAttr *NewAlignasAttr = nullptr; | |||
2337 | unsigned NewAlign = 0; | |||
2338 | for (auto *I : New->specific_attrs<AlignedAttr>()) { | |||
2339 | if (I->isAlignmentDependent()) | |||
2340 | return false; | |||
2341 | ||||
2342 | if (I->isAlignas()) | |||
2343 | NewAlignasAttr = I; | |||
2344 | ||||
2345 | unsigned Align = I->getAlignment(S.Context); | |||
2346 | if (Align > NewAlign) | |||
2347 | NewAlign = Align; | |||
2348 | } | |||
2349 | ||||
2350 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { | |||
2351 | // Both declarations have 'alignas' attributes. We require them to match. | |||
2352 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but | |||
2353 | // fall short. (If two declarations both have alignas, they must both match | |||
2354 | // every definition, and so must match each other if there is a definition.) | |||
2355 | ||||
2356 | // If either declaration only contains 'alignas(0)' specifiers, then it | |||
2357 | // specifies the natural alignment for the type. | |||
2358 | if (OldAlign == 0 || NewAlign == 0) { | |||
2359 | QualType Ty; | |||
2360 | if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) | |||
2361 | Ty = VD->getType(); | |||
2362 | else | |||
2363 | Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); | |||
2364 | ||||
2365 | if (OldAlign == 0) | |||
2366 | OldAlign = S.Context.getTypeAlign(Ty); | |||
2367 | if (NewAlign == 0) | |||
2368 | NewAlign = S.Context.getTypeAlign(Ty); | |||
2369 | } | |||
2370 | ||||
2371 | if (OldAlign != NewAlign) { | |||
2372 | S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) | |||
2373 | << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() | |||
2374 | << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); | |||
2375 | S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); | |||
2376 | } | |||
2377 | } | |||
2378 | ||||
2379 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { | |||
2380 | // C++11 [dcl.align]p6: | |||
2381 | // if any declaration of an entity has an alignment-specifier, | |||
2382 | // every defining declaration of that entity shall specify an | |||
2383 | // equivalent alignment. | |||
2384 | // C11 6.7.5/7: | |||
2385 | // If the definition of an object does not have an alignment | |||
2386 | // specifier, any other declaration of that object shall also | |||
2387 | // have no alignment specifier. | |||
2388 | S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) | |||
2389 | << OldAlignasAttr; | |||
2390 | S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) | |||
2391 | << OldAlignasAttr; | |||
2392 | } | |||
2393 | ||||
2394 | bool AnyAdded = false; | |||
2395 | ||||
2396 | // Ensure we have an attribute representing the strictest alignment. | |||
2397 | if (OldAlign > NewAlign) { | |||
2398 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); | |||
2399 | Clone->setInherited(true); | |||
2400 | New->addAttr(Clone); | |||
2401 | AnyAdded = true; | |||
2402 | } | |||
2403 | ||||
2404 | // Ensure we have an alignas attribute if the old declaration had one. | |||
2405 | if (OldAlignasAttr && !NewAlignasAttr && | |||
2406 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { | |||
2407 | AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); | |||
2408 | Clone->setInherited(true); | |||
2409 | New->addAttr(Clone); | |||
2410 | AnyAdded = true; | |||
2411 | } | |||
2412 | ||||
2413 | return AnyAdded; | |||
2414 | } | |||
2415 | ||||
2416 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, | |||
2417 | const InheritableAttr *Attr, | |||
2418 | Sema::AvailabilityMergeKind AMK) { | |||
2419 | // This function copies an attribute Attr from a previous declaration to the | |||
2420 | // new declaration D if the new declaration doesn't itself have that attribute | |||
2421 | // yet or if that attribute allows duplicates. | |||
2422 | // If you're adding a new attribute that requires logic different from | |||
2423 | // "use explicit attribute on decl if present, else use attribute from | |||
2424 | // previous decl", for example if the attribute needs to be consistent | |||
2425 | // between redeclarations, you need to call a custom merge function here. | |||
2426 | InheritableAttr *NewAttr = nullptr; | |||
2427 | unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); | |||
2428 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) | |||
2429 | NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), | |||
2430 | AA->isImplicit(), AA->getIntroduced(), | |||
2431 | AA->getDeprecated(), | |||
2432 | AA->getObsoleted(), AA->getUnavailable(), | |||
2433 | AA->getMessage(), AA->getStrict(), | |||
2434 | AA->getReplacement(), AMK, | |||
2435 | AttrSpellingListIndex); | |||
2436 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) | |||
2437 | NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), | |||
2438 | AttrSpellingListIndex); | |||
2439 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) | |||
2440 | NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), | |||
2441 | AttrSpellingListIndex); | |||
2442 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) | |||
2443 | NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), | |||
2444 | AttrSpellingListIndex); | |||
2445 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) | |||
2446 | NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), | |||
2447 | AttrSpellingListIndex); | |||
2448 | else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) | |||
2449 | NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), | |||
2450 | FA->getFormatIdx(), FA->getFirstArg(), | |||
2451 | AttrSpellingListIndex); | |||
2452 | else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) | |||
2453 | NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), | |||
2454 | AttrSpellingListIndex); | |||
2455 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) | |||
2456 | NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(), | |||
2457 | AttrSpellingListIndex); | |||
2458 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) | |||
2459 | NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), | |||
2460 | AttrSpellingListIndex, | |||
2461 | IA->getSemanticSpelling()); | |||
2462 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) | |||
2463 | NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), | |||
2464 | &S.Context.Idents.get(AA->getSpelling()), | |||
2465 | AttrSpellingListIndex); | |||
2466 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && | |||
2467 | (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || | |||
2468 | isa<CUDAGlobalAttr>(Attr))) { | |||
2469 | // CUDA target attributes are part of function signature for | |||
2470 | // overloading purposes and must not be merged. | |||
2471 | return false; | |||
2472 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) | |||
2473 | NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); | |||
2474 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) | |||
2475 | NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); | |||
2476 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) | |||
2477 | NewAttr = S.mergeInternalLinkageAttr( | |||
2478 | D, InternalLinkageA->getRange(), | |||
2479 | &S.Context.Idents.get(InternalLinkageA->getSpelling()), | |||
2480 | AttrSpellingListIndex); | |||
2481 | else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) | |||
2482 | NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), | |||
2483 | &S.Context.Idents.get(CommonA->getSpelling()), | |||
2484 | AttrSpellingListIndex); | |||
2485 | else if (isa<AlignedAttr>(Attr)) | |||
2486 | // AlignedAttrs are handled separately, because we need to handle all | |||
2487 | // such attributes on a declaration at the same time. | |||
2488 | NewAttr = nullptr; | |||
2489 | else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && | |||
2490 | (AMK == Sema::AMK_Override || | |||
2491 | AMK == Sema::AMK_ProtocolImplementation)) | |||
2492 | NewAttr = nullptr; | |||
2493 | else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) | |||
2494 | NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, | |||
2495 | UA->getGuid()); | |||
2496 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) | |||
2497 | NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); | |||
2498 | ||||
2499 | if (NewAttr) { | |||
2500 | NewAttr->setInherited(true); | |||
2501 | D->addAttr(NewAttr); | |||
2502 | if (isa<MSInheritanceAttr>(NewAttr)) | |||
2503 | S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); | |||
2504 | return true; | |||
2505 | } | |||
2506 | ||||
2507 | return false; | |||
2508 | } | |||
2509 | ||||
2510 | static const NamedDecl *getDefinition(const Decl *D) { | |||
2511 | if (const TagDecl *TD = dyn_cast<TagDecl>(D)) | |||
2512 | return TD->getDefinition(); | |||
2513 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
2514 | const VarDecl *Def = VD->getDefinition(); | |||
2515 | if (Def) | |||
2516 | return Def; | |||
2517 | return VD->getActingDefinition(); | |||
2518 | } | |||
2519 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) | |||
2520 | return FD->getDefinition(); | |||
2521 | return nullptr; | |||
2522 | } | |||
2523 | ||||
2524 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { | |||
2525 | for (const auto *Attribute : D->attrs()) | |||
2526 | if (Attribute->getKind() == Kind) | |||
2527 | return true; | |||
2528 | return false; | |||
2529 | } | |||
2530 | ||||
2531 | /// checkNewAttributesAfterDef - If we already have a definition, check that | |||
2532 | /// there are no new attributes in this declaration. | |||
2533 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { | |||
2534 | if (!New->hasAttrs()) | |||
2535 | return; | |||
2536 | ||||
2537 | const NamedDecl *Def = getDefinition(Old); | |||
2538 | if (!Def || Def == New) | |||
2539 | return; | |||
2540 | ||||
2541 | AttrVec &NewAttributes = New->getAttrs(); | |||
2542 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { | |||
2543 | const Attr *NewAttribute = NewAttributes[I]; | |||
2544 | ||||
2545 | if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { | |||
2546 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { | |||
2547 | Sema::SkipBodyInfo SkipBody; | |||
2548 | S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); | |||
2549 | ||||
2550 | // If we're skipping this definition, drop the "alias" attribute. | |||
2551 | if (SkipBody.ShouldSkip) { | |||
2552 | NewAttributes.erase(NewAttributes.begin() + I); | |||
2553 | --E; | |||
2554 | continue; | |||
2555 | } | |||
2556 | } else { | |||
2557 | VarDecl *VD = cast<VarDecl>(New); | |||
2558 | unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == | |||
2559 | VarDecl::TentativeDefinition | |||
2560 | ? diag::err_alias_after_tentative | |||
2561 | : diag::err_redefinition; | |||
2562 | S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); | |||
2563 | if (Diag == diag::err_redefinition) | |||
2564 | S.notePreviousDefinition(Def, VD->getLocation()); | |||
2565 | else | |||
2566 | S.Diag(Def->getLocation(), diag::note_previous_definition); | |||
2567 | VD->setInvalidDecl(); | |||
2568 | } | |||
2569 | ++I; | |||
2570 | continue; | |||
2571 | } | |||
2572 | ||||
2573 | if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { | |||
2574 | // Tentative definitions are only interesting for the alias check above. | |||
2575 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { | |||
2576 | ++I; | |||
2577 | continue; | |||
2578 | } | |||
2579 | } | |||
2580 | ||||
2581 | if (hasAttribute(Def, NewAttribute->getKind())) { | |||
2582 | ++I; | |||
2583 | continue; // regular attr merging will take care of validating this. | |||
2584 | } | |||
2585 | ||||
2586 | if (isa<C11NoReturnAttr>(NewAttribute)) { | |||
2587 | // C's _Noreturn is allowed to be added to a function after it is defined. | |||
2588 | ++I; | |||
2589 | continue; | |||
2590 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { | |||
2591 | if (AA->isAlignas()) { | |||
2592 | // C++11 [dcl.align]p6: | |||
2593 | // if any declaration of an entity has an alignment-specifier, | |||
2594 | // every defining declaration of that entity shall specify an | |||
2595 | // equivalent alignment. | |||
2596 | // C11 6.7.5/7: | |||
2597 | // If the definition of an object does not have an alignment | |||
2598 | // specifier, any other declaration of that object shall also | |||
2599 | // have no alignment specifier. | |||
2600 | S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) | |||
2601 | << AA; | |||
2602 | S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) | |||
2603 | << AA; | |||
2604 | NewAttributes.erase(NewAttributes.begin() + I); | |||
2605 | --E; | |||
2606 | continue; | |||
2607 | } | |||
2608 | } | |||
2609 | ||||
2610 | S.Diag(NewAttribute->getLocation(), | |||
2611 | diag::warn_attribute_precede_definition); | |||
2612 | S.Diag(Def->getLocation(), diag::note_previous_definition); | |||
2613 | NewAttributes.erase(NewAttributes.begin() + I); | |||
2614 | --E; | |||
2615 | } | |||
2616 | } | |||
2617 | ||||
2618 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. | |||
2619 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, | |||
2620 | AvailabilityMergeKind AMK) { | |||
2621 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { | |||
2622 | UsedAttr *NewAttr = OldAttr->clone(Context); | |||
2623 | NewAttr->setInherited(true); | |||
2624 | New->addAttr(NewAttr); | |||
2625 | } | |||
2626 | ||||
2627 | if (!Old->hasAttrs() && !New->hasAttrs()) | |||
2628 | return; | |||
2629 | ||||
2630 | // Attributes declared post-definition are currently ignored. | |||
2631 | checkNewAttributesAfterDef(*this, New, Old); | |||
2632 | ||||
2633 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { | |||
2634 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { | |||
2635 | if (OldA->getLabel() != NewA->getLabel()) { | |||
2636 | // This redeclaration changes __asm__ label. | |||
2637 | Diag(New->getLocation(), diag::err_different_asm_label); | |||
2638 | Diag(OldA->getLocation(), diag::note_previous_declaration); | |||
2639 | } | |||
2640 | } else if (Old->isUsed()) { | |||
2641 | // This redeclaration adds an __asm__ label to a declaration that has | |||
2642 | // already been ODR-used. | |||
2643 | Diag(New->getLocation(), diag::err_late_asm_label_name) | |||
2644 | << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); | |||
2645 | } | |||
2646 | } | |||
2647 | ||||
2648 | // Re-declaration cannot add abi_tag's. | |||
2649 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { | |||
2650 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { | |||
2651 | for (const auto &NewTag : NewAbiTagAttr->tags()) { | |||
2652 | if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), | |||
2653 | NewTag) == OldAbiTagAttr->tags_end()) { | |||
2654 | Diag(NewAbiTagAttr->getLocation(), | |||
2655 | diag::err_new_abi_tag_on_redeclaration) | |||
2656 | << NewTag; | |||
2657 | Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); | |||
2658 | } | |||
2659 | } | |||
2660 | } else { | |||
2661 | Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); | |||
2662 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
2663 | } | |||
2664 | } | |||
2665 | ||||
2666 | // This redeclaration adds a section attribute. | |||
2667 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { | |||
2668 | if (auto *VD = dyn_cast<VarDecl>(New)) { | |||
2669 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { | |||
2670 | Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); | |||
2671 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
2672 | } | |||
2673 | } | |||
2674 | } | |||
2675 | ||||
2676 | // Redeclaration adds code-seg attribute. | |||
2677 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); | |||
2678 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && | |||
2679 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { | |||
2680 | Diag(New->getLocation(), diag::warn_mismatched_section) | |||
2681 | << 0 /*codeseg*/; | |||
2682 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
2683 | } | |||
2684 | ||||
2685 | if (!Old->hasAttrs()) | |||
2686 | return; | |||
2687 | ||||
2688 | bool foundAny = New->hasAttrs(); | |||
2689 | ||||
2690 | // Ensure that any moving of objects within the allocated map is done before | |||
2691 | // we process them. | |||
2692 | if (!foundAny) New->setAttrs(AttrVec()); | |||
2693 | ||||
2694 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { | |||
2695 | // Ignore deprecated/unavailable/availability attributes if requested. | |||
2696 | AvailabilityMergeKind LocalAMK = AMK_None; | |||
2697 | if (isa<DeprecatedAttr>(I) || | |||
2698 | isa<UnavailableAttr>(I) || | |||
2699 | isa<AvailabilityAttr>(I)) { | |||
2700 | switch (AMK) { | |||
2701 | case AMK_None: | |||
2702 | continue; | |||
2703 | ||||
2704 | case AMK_Redeclaration: | |||
2705 | case AMK_Override: | |||
2706 | case AMK_ProtocolImplementation: | |||
2707 | LocalAMK = AMK; | |||
2708 | break; | |||
2709 | } | |||
2710 | } | |||
2711 | ||||
2712 | // Already handled. | |||
2713 | if (isa<UsedAttr>(I)) | |||
2714 | continue; | |||
2715 | ||||
2716 | if (mergeDeclAttribute(*this, New, I, LocalAMK)) | |||
2717 | foundAny = true; | |||
2718 | } | |||
2719 | ||||
2720 | if (mergeAlignedAttrs(*this, New, Old)) | |||
2721 | foundAny = true; | |||
2722 | ||||
2723 | if (!foundAny) New->dropAttrs(); | |||
2724 | } | |||
2725 | ||||
2726 | /// mergeParamDeclAttributes - Copy attributes from the old parameter | |||
2727 | /// to the new one. | |||
2728 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, | |||
2729 | const ParmVarDecl *oldDecl, | |||
2730 | Sema &S) { | |||
2731 | // C++11 [dcl.attr.depend]p2: | |||
2732 | // The first declaration of a function shall specify the | |||
2733 | // carries_dependency attribute for its declarator-id if any declaration | |||
2734 | // of the function specifies the carries_dependency attribute. | |||
2735 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); | |||
2736 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { | |||
2737 | S.Diag(CDA->getLocation(), | |||
2738 | diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; | |||
2739 | // Find the first declaration of the parameter. | |||
2740 | // FIXME: Should we build redeclaration chains for function parameters? | |||
2741 | const FunctionDecl *FirstFD = | |||
2742 | cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); | |||
2743 | const ParmVarDecl *FirstVD = | |||
2744 | FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); | |||
2745 | S.Diag(FirstVD->getLocation(), | |||
2746 | diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; | |||
2747 | } | |||
2748 | ||||
2749 | if (!oldDecl->hasAttrs()) | |||
2750 | return; | |||
2751 | ||||
2752 | bool foundAny = newDecl->hasAttrs(); | |||
2753 | ||||
2754 | // Ensure that any moving of objects within the allocated map is | |||
2755 | // done before we process them. | |||
2756 | if (!foundAny) newDecl->setAttrs(AttrVec()); | |||
2757 | ||||
2758 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { | |||
2759 | if (!DeclHasAttr(newDecl, I)) { | |||
2760 | InheritableAttr *newAttr = | |||
2761 | cast<InheritableParamAttr>(I->clone(S.Context)); | |||
2762 | newAttr->setInherited(true); | |||
2763 | newDecl->addAttr(newAttr); | |||
2764 | foundAny = true; | |||
2765 | } | |||
2766 | } | |||
2767 | ||||
2768 | if (!foundAny) newDecl->dropAttrs(); | |||
2769 | } | |||
2770 | ||||
2771 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, | |||
2772 | const ParmVarDecl *OldParam, | |||
2773 | Sema &S) { | |||
2774 | if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { | |||
2775 | if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { | |||
2776 | if (*Oldnullability != *Newnullability) { | |||
2777 | S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) | |||
2778 | << DiagNullabilityKind( | |||
2779 | *Newnullability, | |||
2780 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | |||
2781 | != 0)) | |||
2782 | << DiagNullabilityKind( | |||
2783 | *Oldnullability, | |||
2784 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | |||
2785 | != 0)); | |||
2786 | S.Diag(OldParam->getLocation(), diag::note_previous_declaration); | |||
2787 | } | |||
2788 | } else { | |||
2789 | QualType NewT = NewParam->getType(); | |||
2790 | NewT = S.Context.getAttributedType( | |||
2791 | AttributedType::getNullabilityAttrKind(*Oldnullability), | |||
2792 | NewT, NewT); | |||
2793 | NewParam->setType(NewT); | |||
2794 | } | |||
2795 | } | |||
2796 | } | |||
2797 | ||||
2798 | namespace { | |||
2799 | ||||
2800 | /// Used in MergeFunctionDecl to keep track of function parameters in | |||
2801 | /// C. | |||
2802 | struct GNUCompatibleParamWarning { | |||
2803 | ParmVarDecl *OldParm; | |||
2804 | ParmVarDecl *NewParm; | |||
2805 | QualType PromotedType; | |||
2806 | }; | |||
2807 | ||||
2808 | } // end anonymous namespace | |||
2809 | ||||
2810 | /// getSpecialMember - get the special member enum for a method. | |||
2811 | Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { | |||
2812 | if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { | |||
2813 | if (Ctor->isDefaultConstructor()) | |||
2814 | return Sema::CXXDefaultConstructor; | |||
2815 | ||||
2816 | if (Ctor->isCopyConstructor()) | |||
2817 | return Sema::CXXCopyConstructor; | |||
2818 | ||||
2819 | if (Ctor->isMoveConstructor()) | |||
2820 | return Sema::CXXMoveConstructor; | |||
2821 | } else if (isa<CXXDestructorDecl>(MD)) { | |||
2822 | return Sema::CXXDestructor; | |||
2823 | } else if (MD->isCopyAssignmentOperator()) { | |||
2824 | return Sema::CXXCopyAssignment; | |||
2825 | } else if (MD->isMoveAssignmentOperator()) { | |||
2826 | return Sema::CXXMoveAssignment; | |||
2827 | } | |||
2828 | ||||
2829 | return Sema::CXXInvalid; | |||
2830 | } | |||
2831 | ||||
2832 | // Determine whether the previous declaration was a definition, implicit | |||
2833 | // declaration, or a declaration. | |||
2834 | template <typename T> | |||
2835 | static std::pair<diag::kind, SourceLocation> | |||
2836 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { | |||
2837 | diag::kind PrevDiag; | |||
2838 | SourceLocation OldLocation = Old->getLocation(); | |||
2839 | if (Old->isThisDeclarationADefinition()) | |||
2840 | PrevDiag = diag::note_previous_definition; | |||
2841 | else if (Old->isImplicit()) { | |||
2842 | PrevDiag = diag::note_previous_implicit_declaration; | |||
2843 | if (OldLocation.isInvalid()) | |||
2844 | OldLocation = New->getLocation(); | |||
2845 | } else | |||
2846 | PrevDiag = diag::note_previous_declaration; | |||
2847 | return std::make_pair(PrevDiag, OldLocation); | |||
2848 | } | |||
2849 | ||||
2850 | /// canRedefineFunction - checks if a function can be redefined. Currently, | |||
2851 | /// only extern inline functions can be redefined, and even then only in | |||
2852 | /// GNU89 mode. | |||
2853 | static bool canRedefineFunction(const FunctionDecl *FD, | |||
2854 | const LangOptions& LangOpts) { | |||
2855 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && | |||
2856 | !LangOpts.CPlusPlus && | |||
2857 | FD->isInlineSpecified() && | |||
2858 | FD->getStorageClass() == SC_Extern); | |||
2859 | } | |||
2860 | ||||
2861 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { | |||
2862 | const AttributedType *AT = T->getAs<AttributedType>(); | |||
2863 | while (AT && !AT->isCallingConv()) | |||
2864 | AT = AT->getModifiedType()->getAs<AttributedType>(); | |||
2865 | return AT; | |||
2866 | } | |||
2867 | ||||
2868 | template <typename T> | |||
2869 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { | |||
2870 | const DeclContext *DC = Old->getDeclContext(); | |||
2871 | if (DC->isRecord()) | |||
2872 | return false; | |||
2873 | ||||
2874 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); | |||
2875 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) | |||
2876 | return true; | |||
2877 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) | |||
2878 | return true; | |||
2879 | return false; | |||
2880 | } | |||
2881 | ||||
2882 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } | |||
2883 | static bool isExternC(VarTemplateDecl *) { return false; } | |||
2884 | ||||
2885 | /// Check whether a redeclaration of an entity introduced by a | |||
2886 | /// using-declaration is valid, given that we know it's not an overload | |||
2887 | /// (nor a hidden tag declaration). | |||
2888 | template<typename ExpectedDecl> | |||
2889 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, | |||
2890 | ExpectedDecl *New) { | |||
2891 | // C++11 [basic.scope.declarative]p4: | |||
2892 | // Given a set of declarations in a single declarative region, each of | |||
2893 | // which specifies the same unqualified name, | |||
2894 | // -- they shall all refer to the same entity, or all refer to functions | |||
2895 | // and function templates; or | |||
2896 | // -- exactly one declaration shall declare a class name or enumeration | |||
2897 | // name that is not a typedef name and the other declarations shall all | |||
2898 | // refer to the same variable or enumerator, or all refer to functions | |||
2899 | // and function templates; in this case the class name or enumeration | |||
2900 | // name is hidden (3.3.10). | |||
2901 | ||||
2902 | // C++11 [namespace.udecl]p14: | |||
2903 | // If a function declaration in namespace scope or block scope has the | |||
2904 | // same name and the same parameter-type-list as a function introduced | |||
2905 | // by a using-declaration, and the declarations do not declare the same | |||
2906 | // function, the program is ill-formed. | |||
2907 | ||||
2908 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); | |||
2909 | if (Old && | |||
2910 | !Old->getDeclContext()->getRedeclContext()->Equals( | |||
2911 | New->getDeclContext()->getRedeclContext()) && | |||
2912 | !(isExternC(Old) && isExternC(New))) | |||
2913 | Old = nullptr; | |||
2914 | ||||
2915 | if (!Old) { | |||
2916 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); | |||
2917 | S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); | |||
2918 | S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; | |||
2919 | return true; | |||
2920 | } | |||
2921 | return false; | |||
2922 | } | |||
2923 | ||||
2924 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, | |||
2925 | const FunctionDecl *B) { | |||
2926 | assert(A->getNumParams() == B->getNumParams())(static_cast <bool> (A->getNumParams() == B->getNumParams ()) ? void (0) : __assert_fail ("A->getNumParams() == B->getNumParams()" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 2926, __extension__ __PRETTY_FUNCTION__)); | |||
2927 | ||||
2928 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { | |||
2929 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); | |||
2930 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); | |||
2931 | if (AttrA == AttrB) | |||
2932 | return true; | |||
2933 | return AttrA && AttrB && AttrA->getType() == AttrB->getType(); | |||
2934 | }; | |||
2935 | ||||
2936 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); | |||
2937 | } | |||
2938 | ||||
2939 | /// If necessary, adjust the semantic declaration context for a qualified | |||
2940 | /// declaration to name the correct inline namespace within the qualifier. | |||
2941 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, | |||
2942 | DeclaratorDecl *OldD) { | |||
2943 | // The only case where we need to update the DeclContext is when | |||
2944 | // redeclaration lookup for a qualified name finds a declaration | |||
2945 | // in an inline namespace within the context named by the qualifier: | |||
2946 | // | |||
2947 | // inline namespace N { int f(); } | |||
2948 | // int ::f(); // Sema DC needs adjusting from :: to N::. | |||
2949 | // | |||
2950 | // For unqualified declarations, the semantic context *can* change | |||
2951 | // along the redeclaration chain (for local extern declarations, | |||
2952 | // extern "C" declarations, and friend declarations in particular). | |||
2953 | if (!NewD->getQualifier()) | |||
2954 | return; | |||
2955 | ||||
2956 | // NewD is probably already in the right context. | |||
2957 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); | |||
2958 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); | |||
2959 | if (NamedDC->Equals(SemaDC)) | |||
2960 | return; | |||
2961 | ||||
2962 | assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf (SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl ()) && "unexpected context for redeclaration") ? void (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 2964, __extension__ __PRETTY_FUNCTION__)) | |||
2963 | NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf (SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl ()) && "unexpected context for redeclaration") ? void (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 2964, __extension__ __PRETTY_FUNCTION__)) | |||
2964 | "unexpected context for redeclaration")(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf (SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl ()) && "unexpected context for redeclaration") ? void (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 2964, __extension__ __PRETTY_FUNCTION__)); | |||
2965 | ||||
2966 | auto *LexDC = NewD->getLexicalDeclContext(); | |||
2967 | auto FixSemaDC = [=](NamedDecl *D) { | |||
2968 | if (!D) | |||
2969 | return; | |||
2970 | D->setDeclContext(SemaDC); | |||
2971 | D->setLexicalDeclContext(LexDC); | |||
2972 | }; | |||
2973 | ||||
2974 | FixSemaDC(NewD); | |||
2975 | if (auto *FD = dyn_cast<FunctionDecl>(NewD)) | |||
2976 | FixSemaDC(FD->getDescribedFunctionTemplate()); | |||
2977 | else if (auto *VD = dyn_cast<VarDecl>(NewD)) | |||
2978 | FixSemaDC(VD->getDescribedVarTemplate()); | |||
2979 | } | |||
2980 | ||||
2981 | /// MergeFunctionDecl - We just parsed a function 'New' from | |||
2982 | /// declarator D which has the same name and scope as a previous | |||
2983 | /// declaration 'Old'. Figure out how to resolve this situation, | |||
2984 | /// merging decls or emitting diagnostics as appropriate. | |||
2985 | /// | |||
2986 | /// In C++, New and Old must be declarations that are not | |||
2987 | /// overloaded. Use IsOverload to determine whether New and Old are | |||
2988 | /// overloaded, and to select the Old declaration that New should be | |||
2989 | /// merged with. | |||
2990 | /// | |||
2991 | /// Returns true if there was an error, false otherwise. | |||
2992 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, | |||
2993 | Scope *S, bool MergeTypeWithOld) { | |||
2994 | // Verify the old decl was also a function. | |||
2995 | FunctionDecl *Old = OldD->getAsFunction(); | |||
2996 | if (!Old) { | |||
2997 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { | |||
2998 | if (New->getFriendObjectKind()) { | |||
2999 | Diag(New->getLocation(), diag::err_using_decl_friend); | |||
3000 | Diag(Shadow->getTargetDecl()->getLocation(), | |||
3001 | diag::note_using_decl_target); | |||
3002 | Diag(Shadow->getUsingDecl()->getLocation(), | |||
3003 | diag::note_using_decl) << 0; | |||
3004 | return true; | |||
3005 | } | |||
3006 | ||||
3007 | // Check whether the two declarations might declare the same function. | |||
3008 | if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) | |||
3009 | return true; | |||
3010 | OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); | |||
3011 | } else { | |||
3012 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | |||
3013 | << New->getDeclName(); | |||
3014 | notePreviousDefinition(OldD, New->getLocation()); | |||
3015 | return true; | |||
3016 | } | |||
3017 | } | |||
3018 | ||||
3019 | // If the old declaration is invalid, just give up here. | |||
3020 | if (Old->isInvalidDecl()) | |||
3021 | return true; | |||
3022 | ||||
3023 | // Disallow redeclaration of some builtins. | |||
3024 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { | |||
3025 | Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); | |||
3026 | Diag(Old->getLocation(), diag::note_previous_builtin_declaration) | |||
3027 | << Old << Old->getType(); | |||
3028 | return true; | |||
3029 | } | |||
3030 | ||||
3031 | diag::kind PrevDiag; | |||
3032 | SourceLocation OldLocation; | |||
3033 | std::tie(PrevDiag, OldLocation) = | |||
3034 | getNoteDiagForInvalidRedeclaration(Old, New); | |||
3035 | ||||
3036 | // Don't complain about this if we're in GNU89 mode and the old function | |||
3037 | // is an extern inline function. | |||
3038 | // Don't complain about specializations. They are not supposed to have | |||
3039 | // storage classes. | |||
3040 | if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && | |||
3041 | New->getStorageClass() == SC_Static && | |||
3042 | Old->hasExternalFormalLinkage() && | |||
3043 | !New->getTemplateSpecializationInfo() && | |||
3044 | !canRedefineFunction(Old, getLangOpts())) { | |||
3045 | if (getLangOpts().MicrosoftExt) { | |||
3046 | Diag(New->getLocation(), diag::ext_static_non_static) << New; | |||
3047 | Diag(OldLocation, PrevDiag); | |||
3048 | } else { | |||
3049 | Diag(New->getLocation(), diag::err_static_non_static) << New; | |||
3050 | Diag(OldLocation, PrevDiag); | |||
3051 | return true; | |||
3052 | } | |||
3053 | } | |||
3054 | ||||
3055 | if (New->hasAttr<InternalLinkageAttr>() && | |||
3056 | !Old->hasAttr<InternalLinkageAttr>()) { | |||
3057 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | |||
3058 | << New->getDeclName(); | |||
3059 | notePreviousDefinition(Old, New->getLocation()); | |||
3060 | New->dropAttr<InternalLinkageAttr>(); | |||
3061 | } | |||
3062 | ||||
3063 | if (CheckRedeclarationModuleOwnership(New, Old)) | |||
3064 | return true; | |||
3065 | ||||
3066 | if (!getLangOpts().CPlusPlus) { | |||
3067 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); | |||
3068 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { | |||
3069 | Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) | |||
3070 | << New << OldOvl; | |||
3071 | ||||
3072 | // Try our best to find a decl that actually has the overloadable | |||
3073 | // attribute for the note. In most cases (e.g. programs with only one | |||
3074 | // broken declaration/definition), this won't matter. | |||
3075 | // | |||
3076 | // FIXME: We could do this if we juggled some extra state in | |||
3077 | // OverloadableAttr, rather than just removing it. | |||
3078 | const Decl *DiagOld = Old; | |||
3079 | if (OldOvl) { | |||
3080 | auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { | |||
3081 | const auto *A = D->getAttr<OverloadableAttr>(); | |||
3082 | return A && !A->isImplicit(); | |||
3083 | }); | |||
3084 | // If we've implicitly added *all* of the overloadable attrs to this | |||
3085 | // chain, emitting a "previous redecl" note is pointless. | |||
3086 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; | |||
3087 | } | |||
3088 | ||||
3089 | if (DiagOld) | |||
3090 | Diag(DiagOld->getLocation(), | |||
3091 | diag::note_attribute_overloadable_prev_overload) | |||
3092 | << OldOvl; | |||
3093 | ||||
3094 | if (OldOvl) | |||
3095 | New->addAttr(OverloadableAttr::CreateImplicit(Context)); | |||
3096 | else | |||
3097 | New->dropAttr<OverloadableAttr>(); | |||
3098 | } | |||
3099 | } | |||
3100 | ||||
3101 | // If a function is first declared with a calling convention, but is later | |||
3102 | // declared or defined without one, all following decls assume the calling | |||
3103 | // convention of the first. | |||
3104 | // | |||
3105 | // It's OK if a function is first declared without a calling convention, | |||
3106 | // but is later declared or defined with the default calling convention. | |||
3107 | // | |||
3108 | // To test if either decl has an explicit calling convention, we look for | |||
3109 | // AttributedType sugar nodes on the type as written. If they are missing or | |||
3110 | // were canonicalized away, we assume the calling convention was implicit. | |||
3111 | // | |||
3112 | // Note also that we DO NOT return at this point, because we still have | |||
3113 | // other tests to run. | |||
3114 | QualType OldQType = Context.getCanonicalType(Old->getType()); | |||
3115 | QualType NewQType = Context.getCanonicalType(New->getType()); | |||
3116 | const FunctionType *OldType = cast<FunctionType>(OldQType); | |||
3117 | const FunctionType *NewType = cast<FunctionType>(NewQType); | |||
3118 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | |||
3119 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | |||
3120 | bool RequiresAdjustment = false; | |||
3121 | ||||
3122 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { | |||
3123 | FunctionDecl *First = Old->getFirstDecl(); | |||
3124 | const FunctionType *FT = | |||
3125 | First->getType().getCanonicalType()->castAs<FunctionType>(); | |||
3126 | FunctionType::ExtInfo FI = FT->getExtInfo(); | |||
3127 | bool NewCCExplicit = getCallingConvAttributedType(New->getType()); | |||
3128 | if (!NewCCExplicit) { | |||
3129 | // Inherit the CC from the previous declaration if it was specified | |||
3130 | // there but not here. | |||
3131 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | |||
3132 | RequiresAdjustment = true; | |||
3133 | } else { | |||
3134 | // Calling conventions aren't compatible, so complain. | |||
3135 | bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); | |||
3136 | Diag(New->getLocation(), diag::err_cconv_change) | |||
3137 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | |||
3138 | << !FirstCCExplicit | |||
3139 | << (!FirstCCExplicit ? "" : | |||
3140 | FunctionType::getNameForCallConv(FI.getCC())); | |||
3141 | ||||
3142 | // Put the note on the first decl, since it is the one that matters. | |||
3143 | Diag(First->getLocation(), diag::note_previous_declaration); | |||
3144 | return true; | |||
3145 | } | |||
3146 | } | |||
3147 | ||||
3148 | // FIXME: diagnose the other way around? | |||
3149 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { | |||
3150 | NewTypeInfo = NewTypeInfo.withNoReturn(true); | |||
3151 | RequiresAdjustment = true; | |||
3152 | } | |||
3153 | ||||
3154 | // Merge regparm attribute. | |||
3155 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || | |||
3156 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { | |||
3157 | if (NewTypeInfo.getHasRegParm()) { | |||
3158 | Diag(New->getLocation(), diag::err_regparm_mismatch) | |||
3159 | << NewType->getRegParmType() | |||
3160 | << OldType->getRegParmType(); | |||
3161 | Diag(OldLocation, diag::note_previous_declaration); | |||
3162 | return true; | |||
3163 | } | |||
3164 | ||||
3165 | NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); | |||
3166 | RequiresAdjustment = true; | |||
3167 | } | |||
3168 | ||||
3169 | // Merge ns_returns_retained attribute. | |||
3170 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { | |||
3171 | if (NewTypeInfo.getProducesResult()) { | |||
3172 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) | |||
3173 | << "'ns_returns_retained'"; | |||
3174 | Diag(OldLocation, diag::note_previous_declaration); | |||
3175 | return true; | |||
3176 | } | |||
3177 | ||||
3178 | NewTypeInfo = NewTypeInfo.withProducesResult(true); | |||
3179 | RequiresAdjustment = true; | |||
3180 | } | |||
3181 | ||||
3182 | if (OldTypeInfo.getNoCallerSavedRegs() != | |||
3183 | NewTypeInfo.getNoCallerSavedRegs()) { | |||
3184 | if (NewTypeInfo.getNoCallerSavedRegs()) { | |||
3185 | AnyX86NoCallerSavedRegistersAttr *Attr = | |||
3186 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); | |||
3187 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; | |||
3188 | Diag(OldLocation, diag::note_previous_declaration); | |||
3189 | return true; | |||
3190 | } | |||
3191 | ||||
3192 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); | |||
3193 | RequiresAdjustment = true; | |||
3194 | } | |||
3195 | ||||
3196 | if (RequiresAdjustment) { | |||
3197 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); | |||
3198 | AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); | |||
3199 | New->setType(QualType(AdjustedType, 0)); | |||
3200 | NewQType = Context.getCanonicalType(New->getType()); | |||
3201 | NewType = cast<FunctionType>(NewQType); | |||
3202 | } | |||
3203 | ||||
3204 | // If this redeclaration makes the function inline, we may need to add it to | |||
3205 | // UndefinedButUsed. | |||
3206 | if (!Old->isInlined() && New->isInlined() && | |||
3207 | !New->hasAttr<GNUInlineAttr>() && | |||
3208 | !getLangOpts().GNUInline && | |||
3209 | Old->isUsed(false) && | |||
3210 | !Old->isDefined() && !New->isThisDeclarationADefinition()) | |||
3211 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | |||
3212 | SourceLocation())); | |||
3213 | ||||
3214 | // If this redeclaration makes it newly gnu_inline, we don't want to warn | |||
3215 | // about it. | |||
3216 | if (New->hasAttr<GNUInlineAttr>() && | |||
3217 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { | |||
3218 | UndefinedButUsed.erase(Old->getCanonicalDecl()); | |||
3219 | } | |||
3220 | ||||
3221 | // If pass_object_size params don't match up perfectly, this isn't a valid | |||
3222 | // redeclaration. | |||
3223 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && | |||
3224 | !hasIdenticalPassObjectSizeAttrs(Old, New)) { | |||
3225 | Diag(New->getLocation(), diag::err_different_pass_object_size_params) | |||
3226 | << New->getDeclName(); | |||
3227 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3228 | return true; | |||
3229 | } | |||
3230 | ||||
3231 | if (getLangOpts().CPlusPlus) { | |||
3232 | // C++1z [over.load]p2 | |||
3233 | // Certain function declarations cannot be overloaded: | |||
3234 | // -- Function declarations that differ only in the return type, | |||
3235 | // the exception specification, or both cannot be overloaded. | |||
3236 | ||||
3237 | // Check the exception specifications match. This may recompute the type of | |||
3238 | // both Old and New if it resolved exception specifications, so grab the | |||
3239 | // types again after this. Because this updates the type, we do this before | |||
3240 | // any of the other checks below, which may update the "de facto" NewQType | |||
3241 | // but do not necessarily update the type of New. | |||
3242 | if (CheckEquivalentExceptionSpec(Old, New)) | |||
3243 | return true; | |||
3244 | OldQType = Context.getCanonicalType(Old->getType()); | |||
3245 | NewQType = Context.getCanonicalType(New->getType()); | |||
3246 | ||||
3247 | // Go back to the type source info to compare the declared return types, | |||
3248 | // per C++1y [dcl.type.auto]p13: | |||
3249 | // Redeclarations or specializations of a function or function template | |||
3250 | // with a declared return type that uses a placeholder type shall also | |||
3251 | // use that placeholder, not a deduced type. | |||
3252 | QualType OldDeclaredReturnType = | |||
3253 | (Old->getTypeSourceInfo() | |||
3254 | ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() | |||
3255 | : OldType)->getReturnType(); | |||
3256 | QualType NewDeclaredReturnType = | |||
3257 | (New->getTypeSourceInfo() | |||
3258 | ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() | |||
3259 | : NewType)->getReturnType(); | |||
3260 | if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && | |||
3261 | !((NewQType->isDependentType() || OldQType->isDependentType()) && | |||
3262 | New->isLocalExternDecl())) { | |||
3263 | QualType ResQT; | |||
3264 | if (NewDeclaredReturnType->isObjCObjectPointerType() && | |||
3265 | OldDeclaredReturnType->isObjCObjectPointerType()) | |||
3266 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); | |||
3267 | if (ResQT.isNull()) { | |||
3268 | if (New->isCXXClassMember() && New->isOutOfLine()) | |||
3269 | Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) | |||
3270 | << New << New->getReturnTypeSourceRange(); | |||
3271 | else | |||
3272 | Diag(New->getLocation(), diag::err_ovl_diff_return_type) | |||
3273 | << New->getReturnTypeSourceRange(); | |||
3274 | Diag(OldLocation, PrevDiag) << Old << Old->getType() | |||
3275 | << Old->getReturnTypeSourceRange(); | |||
3276 | return true; | |||
3277 | } | |||
3278 | else | |||
3279 | NewQType = ResQT; | |||
3280 | } | |||
3281 | ||||
3282 | QualType OldReturnType = OldType->getReturnType(); | |||
3283 | QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); | |||
3284 | if (OldReturnType != NewReturnType) { | |||
3285 | // If this function has a deduced return type and has already been | |||
3286 | // defined, copy the deduced value from the old declaration. | |||
3287 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); | |||
3288 | if (OldAT && OldAT->isDeduced()) { | |||
3289 | New->setType( | |||
3290 | SubstAutoType(New->getType(), | |||
3291 | OldAT->isDependentType() ? Context.DependentTy | |||
3292 | : OldAT->getDeducedType())); | |||
3293 | NewQType = Context.getCanonicalType( | |||
3294 | SubstAutoType(NewQType, | |||
3295 | OldAT->isDependentType() ? Context.DependentTy | |||
3296 | : OldAT->getDeducedType())); | |||
3297 | } | |||
3298 | } | |||
3299 | ||||
3300 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); | |||
3301 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); | |||
3302 | if (OldMethod && NewMethod) { | |||
3303 | // Preserve triviality. | |||
3304 | NewMethod->setTrivial(OldMethod->isTrivial()); | |||
3305 | ||||
3306 | // MSVC allows explicit template specialization at class scope: | |||
3307 | // 2 CXXMethodDecls referring to the same function will be injected. | |||
3308 | // We don't want a redeclaration error. | |||
3309 | bool IsClassScopeExplicitSpecialization = | |||
3310 | OldMethod->isFunctionTemplateSpecialization() && | |||
3311 | NewMethod->isFunctionTemplateSpecialization(); | |||
3312 | bool isFriend = NewMethod->getFriendObjectKind(); | |||
3313 | ||||
3314 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && | |||
3315 | !IsClassScopeExplicitSpecialization) { | |||
3316 | // -- Member function declarations with the same name and the | |||
3317 | // same parameter types cannot be overloaded if any of them | |||
3318 | // is a static member function declaration. | |||
3319 | if (OldMethod->isStatic() != NewMethod->isStatic()) { | |||
3320 | Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); | |||
3321 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3322 | return true; | |||
3323 | } | |||
3324 | ||||
3325 | // C++ [class.mem]p1: | |||
3326 | // [...] A member shall not be declared twice in the | |||
3327 | // member-specification, except that a nested class or member | |||
3328 | // class template can be declared and then later defined. | |||
3329 | if (!inTemplateInstantiation()) { | |||
3330 | unsigned NewDiag; | |||
3331 | if (isa<CXXConstructorDecl>(OldMethod)) | |||
3332 | NewDiag = diag::err_constructor_redeclared; | |||
3333 | else if (isa<CXXDestructorDecl>(NewMethod)) | |||
3334 | NewDiag = diag::err_destructor_redeclared; | |||
3335 | else if (isa<CXXConversionDecl>(NewMethod)) | |||
3336 | NewDiag = diag::err_conv_function_redeclared; | |||
3337 | else | |||
3338 | NewDiag = diag::err_member_redeclared; | |||
3339 | ||||
3340 | Diag(New->getLocation(), NewDiag); | |||
3341 | } else { | |||
3342 | Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) | |||
3343 | << New << New->getType(); | |||
3344 | } | |||
3345 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3346 | return true; | |||
3347 | ||||
3348 | // Complain if this is an explicit declaration of a special | |||
3349 | // member that was initially declared implicitly. | |||
3350 | // | |||
3351 | // As an exception, it's okay to befriend such methods in order | |||
3352 | // to permit the implicit constructor/destructor/operator calls. | |||
3353 | } else if (OldMethod->isImplicit()) { | |||
3354 | if (isFriend) { | |||
3355 | NewMethod->setImplicit(); | |||
3356 | } else { | |||
3357 | Diag(NewMethod->getLocation(), | |||
3358 | diag::err_definition_of_implicitly_declared_member) | |||
3359 | << New << getSpecialMember(OldMethod); | |||
3360 | return true; | |||
3361 | } | |||
3362 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { | |||
3363 | Diag(NewMethod->getLocation(), | |||
3364 | diag::err_definition_of_explicitly_defaulted_member) | |||
3365 | << getSpecialMember(OldMethod); | |||
3366 | return true; | |||
3367 | } | |||
3368 | } | |||
3369 | ||||
3370 | // C++11 [dcl.attr.noreturn]p1: | |||
3371 | // The first declaration of a function shall specify the noreturn | |||
3372 | // attribute if any declaration of that function specifies the noreturn | |||
3373 | // attribute. | |||
3374 | const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); | |||
3375 | if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { | |||
3376 | Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); | |||
3377 | Diag(Old->getFirstDecl()->getLocation(), | |||
3378 | diag::note_noreturn_missing_first_decl); | |||
3379 | } | |||
3380 | ||||
3381 | // C++11 [dcl.attr.depend]p2: | |||
3382 | // The first declaration of a function shall specify the | |||
3383 | // carries_dependency attribute for its declarator-id if any declaration | |||
3384 | // of the function specifies the carries_dependency attribute. | |||
3385 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); | |||
3386 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { | |||
3387 | Diag(CDA->getLocation(), | |||
3388 | diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; | |||
3389 | Diag(Old->getFirstDecl()->getLocation(), | |||
3390 | diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; | |||
3391 | } | |||
3392 | ||||
3393 | // (C++98 8.3.5p3): | |||
3394 | // All declarations for a function shall agree exactly in both the | |||
3395 | // return type and the parameter-type-list. | |||
3396 | // We also want to respect all the extended bits except noreturn. | |||
3397 | ||||
3398 | // noreturn should now match unless the old type info didn't have it. | |||
3399 | QualType OldQTypeForComparison = OldQType; | |||
3400 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { | |||
3401 | auto *OldType = OldQType->castAs<FunctionProtoType>(); | |||
3402 | const FunctionType *OldTypeForComparison | |||
3403 | = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); | |||
3404 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); | |||
3405 | assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical( )) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 3405, __extension__ __PRETTY_FUNCTION__)); | |||
3406 | } | |||
3407 | ||||
3408 | if (haveIncompatibleLanguageLinkages(Old, New)) { | |||
3409 | // As a special case, retain the language linkage from previous | |||
3410 | // declarations of a friend function as an extension. | |||
3411 | // | |||
3412 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC | |||
3413 | // and is useful because there's otherwise no way to specify language | |||
3414 | // linkage within class scope. | |||
3415 | // | |||
3416 | // Check cautiously as the friend object kind isn't yet complete. | |||
3417 | if (New->getFriendObjectKind() != Decl::FOK_None) { | |||
3418 | Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; | |||
3419 | Diag(OldLocation, PrevDiag); | |||
3420 | } else { | |||
3421 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | |||
3422 | Diag(OldLocation, PrevDiag); | |||
3423 | return true; | |||
3424 | } | |||
3425 | } | |||
3426 | ||||
3427 | if (OldQTypeForComparison == NewQType) | |||
3428 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | |||
3429 | ||||
3430 | if ((NewQType->isDependentType() || OldQType->isDependentType()) && | |||
3431 | New->isLocalExternDecl()) { | |||
3432 | // It's OK if we couldn't merge types for a local function declaraton | |||
3433 | // if either the old or new type is dependent. We'll merge the types | |||
3434 | // when we instantiate the function. | |||
3435 | return false; | |||
3436 | } | |||
3437 | ||||
3438 | // Fall through for conflicting redeclarations and redefinitions. | |||
3439 | } | |||
3440 | ||||
3441 | // C: Function types need to be compatible, not identical. This handles | |||
3442 | // duplicate function decls like "void f(int); void f(enum X);" properly. | |||
3443 | if (!getLangOpts().CPlusPlus && | |||
3444 | Context.typesAreCompatible(OldQType, NewQType)) { | |||
3445 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); | |||
3446 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); | |||
3447 | const FunctionProtoType *OldProto = nullptr; | |||
3448 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && | |||
3449 | (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { | |||
3450 | // The old declaration provided a function prototype, but the | |||
3451 | // new declaration does not. Merge in the prototype. | |||
3452 | assert(!OldProto->hasExceptionSpec() && "Exception spec in C")(static_cast <bool> (!OldProto->hasExceptionSpec() && "Exception spec in C") ? void (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 3452, __extension__ __PRETTY_FUNCTION__)); | |||
3453 | SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); | |||
3454 | NewQType = | |||
3455 | Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, | |||
3456 | OldProto->getExtProtoInfo()); | |||
3457 | New->setType(NewQType); | |||
3458 | New->setHasInheritedPrototype(); | |||
3459 | ||||
3460 | // Synthesize parameters with the same types. | |||
3461 | SmallVector<ParmVarDecl*, 16> Params; | |||
3462 | for (const auto &ParamType : OldProto->param_types()) { | |||
3463 | ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), | |||
3464 | SourceLocation(), nullptr, | |||
3465 | ParamType, /*TInfo=*/nullptr, | |||
3466 | SC_None, nullptr); | |||
3467 | Param->setScopeInfo(0, Params.size()); | |||
3468 | Param->setImplicit(); | |||
3469 | Params.push_back(Param); | |||
3470 | } | |||
3471 | ||||
3472 | New->setParams(Params); | |||
3473 | } | |||
3474 | ||||
3475 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | |||
3476 | } | |||
3477 | ||||
3478 | // GNU C permits a K&R definition to follow a prototype declaration | |||
3479 | // if the declared types of the parameters in the K&R definition | |||
3480 | // match the types in the prototype declaration, even when the | |||
3481 | // promoted types of the parameters from the K&R definition differ | |||
3482 | // from the types in the prototype. GCC then keeps the types from | |||
3483 | // the prototype. | |||
3484 | // | |||
3485 | // If a variadic prototype is followed by a non-variadic K&R definition, | |||
3486 | // the K&R definition becomes variadic. This is sort of an edge case, but | |||
3487 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and | |||
3488 | // C99 6.9.1p8. | |||
3489 | if (!getLangOpts().CPlusPlus && | |||
3490 | Old->hasPrototype() && !New->hasPrototype() && | |||
3491 | New->getType()->getAs<FunctionProtoType>() && | |||
3492 | Old->getNumParams() == New->getNumParams()) { | |||
3493 | SmallVector<QualType, 16> ArgTypes; | |||
3494 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; | |||
3495 | const FunctionProtoType *OldProto | |||
3496 | = Old->getType()->getAs<FunctionProtoType>(); | |||
3497 | const FunctionProtoType *NewProto | |||
3498 | = New->getType()->getAs<FunctionProtoType>(); | |||
3499 | ||||
3500 | // Determine whether this is the GNU C extension. | |||
3501 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), | |||
3502 | NewProto->getReturnType()); | |||
3503 | bool LooseCompatible = !MergedReturn.isNull(); | |||
3504 | for (unsigned Idx = 0, End = Old->getNumParams(); | |||
3505 | LooseCompatible && Idx != End; ++Idx) { | |||
3506 | ParmVarDecl *OldParm = Old->getParamDecl(Idx); | |||
3507 | ParmVarDecl *NewParm = New->getParamDecl(Idx); | |||
3508 | if (Context.typesAreCompatible(OldParm->getType(), | |||
3509 | NewProto->getParamType(Idx))) { | |||
3510 | ArgTypes.push_back(NewParm->getType()); | |||
3511 | } else if (Context.typesAreCompatible(OldParm->getType(), | |||
3512 | NewParm->getType(), | |||
3513 | /*CompareUnqualified=*/true)) { | |||
3514 | GNUCompatibleParamWarning Warn = { OldParm, NewParm, | |||
3515 | NewProto->getParamType(Idx) }; | |||
3516 | Warnings.push_back(Warn); | |||
3517 | ArgTypes.push_back(NewParm->getType()); | |||
3518 | } else | |||
3519 | LooseCompatible = false; | |||
3520 | } | |||
3521 | ||||
3522 | if (LooseCompatible) { | |||
3523 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { | |||
3524 | Diag(Warnings[Warn].NewParm->getLocation(), | |||
3525 | diag::ext_param_promoted_not_compatible_with_prototype) | |||
3526 | << Warnings[Warn].PromotedType | |||
3527 | << Warnings[Warn].OldParm->getType(); | |||
3528 | if (Warnings[Warn].OldParm->getLocation().isValid()) | |||
3529 | Diag(Warnings[Warn].OldParm->getLocation(), | |||
3530 | diag::note_previous_declaration); | |||
3531 | } | |||
3532 | ||||
3533 | if (MergeTypeWithOld) | |||
3534 | New->setType(Context.getFunctionType(MergedReturn, ArgTypes, | |||
3535 | OldProto->getExtProtoInfo())); | |||
3536 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | |||
3537 | } | |||
3538 | ||||
3539 | // Fall through to diagnose conflicting types. | |||
3540 | } | |||
3541 | ||||
3542 | // A function that has already been declared has been redeclared or | |||
3543 | // defined with a different type; show an appropriate diagnostic. | |||
3544 | ||||
3545 | // If the previous declaration was an implicitly-generated builtin | |||
3546 | // declaration, then at the very least we should use a specialized note. | |||
3547 | unsigned BuiltinID; | |||
3548 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { | |||
3549 | // If it's actually a library-defined builtin function like 'malloc' | |||
3550 | // or 'printf', just warn about the incompatible redeclaration. | |||
3551 | if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { | |||
3552 | Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; | |||
3553 | Diag(OldLocation, diag::note_previous_builtin_declaration) | |||
3554 | << Old << Old->getType(); | |||
3555 | ||||
3556 | // If this is a global redeclaration, just forget hereafter | |||
3557 | // about the "builtin-ness" of the function. | |||
3558 | // | |||
3559 | // Doing this for local extern declarations is problematic. If | |||
3560 | // the builtin declaration remains visible, a second invalid | |||
3561 | // local declaration will produce a hard error; if it doesn't | |||
3562 | // remain visible, a single bogus local redeclaration (which is | |||
3563 | // actually only a warning) could break all the downstream code. | |||
3564 | if (!New->getLexicalDeclContext()->isFunctionOrMethod()) | |||
3565 | New->getIdentifier()->revertBuiltin(); | |||
3566 | ||||
3567 | return false; | |||
3568 | } | |||
3569 | ||||
3570 | PrevDiag = diag::note_previous_builtin_declaration; | |||
3571 | } | |||
3572 | ||||
3573 | Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); | |||
3574 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3575 | return true; | |||
3576 | } | |||
3577 | ||||
3578 | /// Completes the merge of two function declarations that are | |||
3579 | /// known to be compatible. | |||
3580 | /// | |||
3581 | /// This routine handles the merging of attributes and other | |||
3582 | /// properties of function declarations from the old declaration to | |||
3583 | /// the new declaration, once we know that New is in fact a | |||
3584 | /// redeclaration of Old. | |||
3585 | /// | |||
3586 | /// \returns false | |||
3587 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, | |||
3588 | Scope *S, bool MergeTypeWithOld) { | |||
3589 | // Merge the attributes | |||
3590 | mergeDeclAttributes(New, Old); | |||
3591 | ||||
3592 | // Merge "pure" flag. | |||
3593 | if (Old->isPure()) | |||
3594 | New->setPure(); | |||
3595 | ||||
3596 | // Merge "used" flag. | |||
3597 | if (Old->getMostRecentDecl()->isUsed(false)) | |||
3598 | New->setIsUsed(); | |||
3599 | ||||
3600 | // Merge attributes from the parameters. These can mismatch with K&R | |||
3601 | // declarations. | |||
3602 | if (New->getNumParams() == Old->getNumParams()) | |||
3603 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { | |||
3604 | ParmVarDecl *NewParam = New->getParamDecl(i); | |||
3605 | ParmVarDecl *OldParam = Old->getParamDecl(i); | |||
3606 | mergeParamDeclAttributes(NewParam, OldParam, *this); | |||
3607 | mergeParamDeclTypes(NewParam, OldParam, *this); | |||
3608 | } | |||
3609 | ||||
3610 | if (getLangOpts().CPlusPlus) | |||
3611 | return MergeCXXFunctionDecl(New, Old, S); | |||
3612 | ||||
3613 | // Merge the function types so the we get the composite types for the return | |||
3614 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl | |||
3615 | // was visible. | |||
3616 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); | |||
3617 | if (!Merged.isNull() && MergeTypeWithOld) | |||
3618 | New->setType(Merged); | |||
3619 | ||||
3620 | return false; | |||
3621 | } | |||
3622 | ||||
3623 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, | |||
3624 | ObjCMethodDecl *oldMethod) { | |||
3625 | // Merge the attributes, including deprecated/unavailable | |||
3626 | AvailabilityMergeKind MergeKind = | |||
3627 | isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) | |||
3628 | ? AMK_ProtocolImplementation | |||
3629 | : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration | |||
3630 | : AMK_Override; | |||
3631 | ||||
3632 | mergeDeclAttributes(newMethod, oldMethod, MergeKind); | |||
3633 | ||||
3634 | // Merge attributes from the parameters. | |||
3635 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), | |||
3636 | oe = oldMethod->param_end(); | |||
3637 | for (ObjCMethodDecl::param_iterator | |||
3638 | ni = newMethod->param_begin(), ne = newMethod->param_end(); | |||
3639 | ni != ne && oi != oe; ++ni, ++oi) | |||
3640 | mergeParamDeclAttributes(*ni, *oi, *this); | |||
3641 | ||||
3642 | CheckObjCMethodOverride(newMethod, oldMethod); | |||
3643 | } | |||
3644 | ||||
3645 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { | |||
3646 | assert(!S.Context.hasSameType(New->getType(), Old->getType()))(static_cast <bool> (!S.Context.hasSameType(New->getType (), Old->getType())) ? void (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 3646, __extension__ __PRETTY_FUNCTION__)); | |||
3647 | ||||
3648 | S.Diag(New->getLocation(), New->isThisDeclarationADefinition() | |||
3649 | ? diag::err_redefinition_different_type | |||
3650 | : diag::err_redeclaration_different_type) | |||
3651 | << New->getDeclName() << New->getType() << Old->getType(); | |||
3652 | ||||
3653 | diag::kind PrevDiag; | |||
3654 | SourceLocation OldLocation; | |||
3655 | std::tie(PrevDiag, OldLocation) | |||
3656 | = getNoteDiagForInvalidRedeclaration(Old, New); | |||
3657 | S.Diag(OldLocation, PrevDiag); | |||
3658 | New->setInvalidDecl(); | |||
3659 | } | |||
3660 | ||||
3661 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and | |||
3662 | /// scope as a previous declaration 'Old'. Figure out how to merge their types, | |||
3663 | /// emitting diagnostics as appropriate. | |||
3664 | /// | |||
3665 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back | |||
3666 | /// to here in AddInitializerToDecl. We can't check them before the initializer | |||
3667 | /// is attached. | |||
3668 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, | |||
3669 | bool MergeTypeWithOld) { | |||
3670 | if (New->isInvalidDecl() || Old->isInvalidDecl()) | |||
3671 | return; | |||
3672 | ||||
3673 | QualType MergedT; | |||
3674 | if (getLangOpts().CPlusPlus) { | |||
3675 | if (New->getType()->isUndeducedType()) { | |||
3676 | // We don't know what the new type is until the initializer is attached. | |||
3677 | return; | |||
3678 | } else if (Context.hasSameType(New->getType(), Old->getType())) { | |||
3679 | // These could still be something that needs exception specs checked. | |||
3680 | return MergeVarDeclExceptionSpecs(New, Old); | |||
3681 | } | |||
3682 | // C++ [basic.link]p10: | |||
3683 | // [...] the types specified by all declarations referring to a given | |||
3684 | // object or function shall be identical, except that declarations for an | |||
3685 | // array object can specify array types that differ by the presence or | |||
3686 | // absence of a major array bound (8.3.4). | |||
3687 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { | |||
3688 | const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); | |||
3689 | const ArrayType *NewArray = Context.getAsArrayType(New->getType()); | |||
3690 | ||||
3691 | // We are merging a variable declaration New into Old. If it has an array | |||
3692 | // bound, and that bound differs from Old's bound, we should diagnose the | |||
3693 | // mismatch. | |||
3694 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { | |||
3695 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; | |||
3696 | PrevVD = PrevVD->getPreviousDecl()) { | |||
3697 | const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); | |||
3698 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) | |||
3699 | continue; | |||
3700 | ||||
3701 | if (!Context.hasSameType(NewArray, PrevVDTy)) | |||
3702 | return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); | |||
3703 | } | |||
3704 | } | |||
3705 | ||||
3706 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { | |||
3707 | if (Context.hasSameType(OldArray->getElementType(), | |||
3708 | NewArray->getElementType())) | |||
3709 | MergedT = New->getType(); | |||
3710 | } | |||
3711 | // FIXME: Check visibility. New is hidden but has a complete type. If New | |||
3712 | // has no array bound, it should not inherit one from Old, if Old is not | |||
3713 | // visible. | |||
3714 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { | |||
3715 | if (Context.hasSameType(OldArray->getElementType(), | |||
3716 | NewArray->getElementType())) | |||
3717 | MergedT = Old->getType(); | |||
3718 | } | |||
3719 | } | |||
3720 | else if (New->getType()->isObjCObjectPointerType() && | |||
3721 | Old->getType()->isObjCObjectPointerType()) { | |||
3722 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), | |||
3723 | Old->getType()); | |||
3724 | } | |||
3725 | } else { | |||
3726 | // C 6.2.7p2: | |||
3727 | // All declarations that refer to the same object or function shall have | |||
3728 | // compatible type. | |||
3729 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); | |||
3730 | } | |||
3731 | if (MergedT.isNull()) { | |||
3732 | // It's OK if we couldn't merge types if either type is dependent, for a | |||
3733 | // block-scope variable. In other cases (static data members of class | |||
3734 | // templates, variable templates, ...), we require the types to be | |||
3735 | // equivalent. | |||
3736 | // FIXME: The C++ standard doesn't say anything about this. | |||
3737 | if ((New->getType()->isDependentType() || | |||
3738 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { | |||
3739 | // If the old type was dependent, we can't merge with it, so the new type | |||
3740 | // becomes dependent for now. We'll reproduce the original type when we | |||
3741 | // instantiate the TypeSourceInfo for the variable. | |||
3742 | if (!New->getType()->isDependentType() && MergeTypeWithOld) | |||
3743 | New->setType(Context.DependentTy); | |||
3744 | return; | |||
3745 | } | |||
3746 | return diagnoseVarDeclTypeMismatch(*this, New, Old); | |||
3747 | } | |||
3748 | ||||
3749 | // Don't actually update the type on the new declaration if the old | |||
3750 | // declaration was an extern declaration in a different scope. | |||
3751 | if (MergeTypeWithOld) | |||
3752 | New->setType(MergedT); | |||
3753 | } | |||
3754 | ||||
3755 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, | |||
3756 | LookupResult &Previous) { | |||
3757 | // C11 6.2.7p4: | |||
3758 | // For an identifier with internal or external linkage declared | |||
3759 | // in a scope in which a prior declaration of that identifier is | |||
3760 | // visible, if the prior declaration specifies internal or | |||
3761 | // external linkage, the type of the identifier at the later | |||
3762 | // declaration becomes the composite type. | |||
3763 | // | |||
3764 | // If the variable isn't visible, we do not merge with its type. | |||
3765 | if (Previous.isShadowed()) | |||
3766 | return false; | |||
3767 | ||||
3768 | if (S.getLangOpts().CPlusPlus) { | |||
3769 | // C++11 [dcl.array]p3: | |||
3770 | // If there is a preceding declaration of the entity in the same | |||
3771 | // scope in which the bound was specified, an omitted array bound | |||
3772 | // is taken to be the same as in that earlier declaration. | |||
3773 | return NewVD->isPreviousDeclInSameBlockScope() || | |||
3774 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && | |||
3775 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); | |||
3776 | } else { | |||
3777 | // If the old declaration was function-local, don't merge with its | |||
3778 | // type unless we're in the same function. | |||
3779 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || | |||
3780 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); | |||
3781 | } | |||
3782 | } | |||
3783 | ||||
3784 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name | |||
3785 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this | |||
3786 | /// situation, merging decls or emitting diagnostics as appropriate. | |||
3787 | /// | |||
3788 | /// Tentative definition rules (C99 6.9.2p2) are checked by | |||
3789 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative | |||
3790 | /// definitions here, since the initializer hasn't been attached. | |||
3791 | /// | |||
3792 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { | |||
3793 | // If the new decl is already invalid, don't do any other checking. | |||
3794 | if (New->isInvalidDecl()) | |||
3795 | return; | |||
3796 | ||||
3797 | if (!shouldLinkPossiblyHiddenDecl(Previous, New)) | |||
3798 | return; | |||
3799 | ||||
3800 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); | |||
3801 | ||||
3802 | // Verify the old decl was also a variable or variable template. | |||
3803 | VarDecl *Old = nullptr; | |||
3804 | VarTemplateDecl *OldTemplate = nullptr; | |||
3805 | if (Previous.isSingleResult()) { | |||
3806 | if (NewTemplate) { | |||
3807 | OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); | |||
3808 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; | |||
3809 | ||||
3810 | if (auto *Shadow = | |||
3811 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | |||
3812 | if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) | |||
3813 | return New->setInvalidDecl(); | |||
3814 | } else { | |||
3815 | Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); | |||
3816 | ||||
3817 | if (auto *Shadow = | |||
3818 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | |||
3819 | if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) | |||
3820 | return New->setInvalidDecl(); | |||
3821 | } | |||
3822 | } | |||
3823 | if (!Old) { | |||
3824 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | |||
3825 | << New->getDeclName(); | |||
3826 | notePreviousDefinition(Previous.getRepresentativeDecl(), | |||
3827 | New->getLocation()); | |||
3828 | return New->setInvalidDecl(); | |||
3829 | } | |||
3830 | ||||
3831 | // Ensure the template parameters are compatible. | |||
3832 | if (NewTemplate && | |||
3833 | !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), | |||
3834 | OldTemplate->getTemplateParameters(), | |||
3835 | /*Complain=*/true, TPL_TemplateMatch)) | |||
3836 | return New->setInvalidDecl(); | |||
3837 | ||||
3838 | // C++ [class.mem]p1: | |||
3839 | // A member shall not be declared twice in the member-specification [...] | |||
3840 | // | |||
3841 | // Here, we need only consider static data members. | |||
3842 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { | |||
3843 | Diag(New->getLocation(), diag::err_duplicate_member) | |||
3844 | << New->getIdentifier(); | |||
3845 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
3846 | New->setInvalidDecl(); | |||
3847 | } | |||
3848 | ||||
3849 | mergeDeclAttributes(New, Old); | |||
3850 | // Warn if an already-declared variable is made a weak_import in a subsequent | |||
3851 | // declaration | |||
3852 | if (New->hasAttr<WeakImportAttr>() && | |||
3853 | Old->getStorageClass() == SC_None && | |||
3854 | !Old->hasAttr<WeakImportAttr>()) { | |||
3855 | Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); | |||
3856 | notePreviousDefinition(Old, New->getLocation()); | |||
3857 | // Remove weak_import attribute on new declaration. | |||
3858 | New->dropAttr<WeakImportAttr>(); | |||
3859 | } | |||
3860 | ||||
3861 | if (New->hasAttr<InternalLinkageAttr>() && | |||
3862 | !Old->hasAttr<InternalLinkageAttr>()) { | |||
3863 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | |||
3864 | << New->getDeclName(); | |||
3865 | notePreviousDefinition(Old, New->getLocation()); | |||
3866 | New->dropAttr<InternalLinkageAttr>(); | |||
3867 | } | |||
3868 | ||||
3869 | // Merge the types. | |||
3870 | VarDecl *MostRecent = Old->getMostRecentDecl(); | |||
3871 | if (MostRecent != Old) { | |||
3872 | MergeVarDeclTypes(New, MostRecent, | |||
3873 | mergeTypeWithPrevious(*this, New, MostRecent, Previous)); | |||
3874 | if (New->isInvalidDecl()) | |||
3875 | return; | |||
3876 | } | |||
3877 | ||||
3878 | MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); | |||
3879 | if (New->isInvalidDecl()) | |||
3880 | return; | |||
3881 | ||||
3882 | diag::kind PrevDiag; | |||
3883 | SourceLocation OldLocation; | |||
3884 | std::tie(PrevDiag, OldLocation) = | |||
3885 | getNoteDiagForInvalidRedeclaration(Old, New); | |||
3886 | ||||
3887 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. | |||
3888 | if (New->getStorageClass() == SC_Static && | |||
3889 | !New->isStaticDataMember() && | |||
3890 | Old->hasExternalFormalLinkage()) { | |||
3891 | if (getLangOpts().MicrosoftExt) { | |||
3892 | Diag(New->getLocation(), diag::ext_static_non_static) | |||
3893 | << New->getDeclName(); | |||
3894 | Diag(OldLocation, PrevDiag); | |||
3895 | } else { | |||
3896 | Diag(New->getLocation(), diag::err_static_non_static) | |||
3897 | << New->getDeclName(); | |||
3898 | Diag(OldLocation, PrevDiag); | |||
3899 | return New->setInvalidDecl(); | |||
3900 | } | |||
3901 | } | |||
3902 | // C99 6.2.2p4: | |||
3903 | // For an identifier declared with the storage-class specifier | |||
3904 | // extern in a scope in which a prior declaration of that | |||
3905 | // identifier is visible,23) if the prior declaration specifies | |||
3906 | // internal or external linkage, the linkage of the identifier at | |||
3907 | // the later declaration is the same as the linkage specified at | |||
3908 | // the prior declaration. If no prior declaration is visible, or | |||
3909 | // if the prior declaration specifies no linkage, then the | |||
3910 | // identifier has external linkage. | |||
3911 | if (New->hasExternalStorage() && Old->hasLinkage()) | |||
3912 | /* Okay */; | |||
3913 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && | |||
3914 | !New->isStaticDataMember() && | |||
3915 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { | |||
3916 | Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); | |||
3917 | Diag(OldLocation, PrevDiag); | |||
3918 | return New->setInvalidDecl(); | |||
3919 | } | |||
3920 | ||||
3921 | // Check if extern is followed by non-extern and vice-versa. | |||
3922 | if (New->hasExternalStorage() && | |||
3923 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { | |||
3924 | Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); | |||
3925 | Diag(OldLocation, PrevDiag); | |||
3926 | return New->setInvalidDecl(); | |||
3927 | } | |||
3928 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && | |||
3929 | !New->hasExternalStorage()) { | |||
3930 | Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); | |||
3931 | Diag(OldLocation, PrevDiag); | |||
3932 | return New->setInvalidDecl(); | |||
3933 | } | |||
3934 | ||||
3935 | if (CheckRedeclarationModuleOwnership(New, Old)) | |||
3936 | return; | |||
3937 | ||||
3938 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. | |||
3939 | ||||
3940 | // FIXME: The test for external storage here seems wrong? We still | |||
3941 | // need to check for mismatches. | |||
3942 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && | |||
3943 | // Don't complain about out-of-line definitions of static members. | |||
3944 | !(Old->getLexicalDeclContext()->isRecord() && | |||
3945 | !New->getLexicalDeclContext()->isRecord())) { | |||
3946 | Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); | |||
3947 | Diag(OldLocation, PrevDiag); | |||
3948 | return New->setInvalidDecl(); | |||
3949 | } | |||
3950 | ||||
3951 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { | |||
3952 | if (VarDecl *Def = Old->getDefinition()) { | |||
3953 | // C++1z [dcl.fcn.spec]p4: | |||
3954 | // If the definition of a variable appears in a translation unit before | |||
3955 | // its first declaration as inline, the program is ill-formed. | |||
3956 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; | |||
3957 | Diag(Def->getLocation(), diag::note_previous_definition); | |||
3958 | } | |||
3959 | } | |||
3960 | ||||
3961 | // If this redeclaration makes the variable inline, we may need to add it to | |||
3962 | // UndefinedButUsed. | |||
3963 | if (!Old->isInline() && New->isInline() && Old->isUsed(false) && | |||
3964 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) | |||
3965 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | |||
3966 | SourceLocation())); | |||
3967 | ||||
3968 | if (New->getTLSKind() != Old->getTLSKind()) { | |||
3969 | if (!Old->getTLSKind()) { | |||
3970 | Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); | |||
3971 | Diag(OldLocation, PrevDiag); | |||
3972 | } else if (!New->getTLSKind()) { | |||
3973 | Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); | |||
3974 | Diag(OldLocation, PrevDiag); | |||
3975 | } else { | |||
3976 | // Do not allow redeclaration to change the variable between requiring | |||
3977 | // static and dynamic initialization. | |||
3978 | // FIXME: GCC allows this, but uses the TLS keyword on the first | |||
3979 | // declaration to determine the kind. Do we need to be compatible here? | |||
3980 | Diag(New->getLocation(), diag::err_thread_thread_different_kind) | |||
3981 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); | |||
3982 | Diag(OldLocation, PrevDiag); | |||
3983 | } | |||
3984 | } | |||
3985 | ||||
3986 | // C++ doesn't have tentative definitions, so go right ahead and check here. | |||
3987 | if (getLangOpts().CPlusPlus && | |||
3988 | New->isThisDeclarationADefinition() == VarDecl::Definition) { | |||
3989 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && | |||
3990 | Old->getCanonicalDecl()->isConstexpr()) { | |||
3991 | // This definition won't be a definition any more once it's been merged. | |||
3992 | Diag(New->getLocation(), | |||
3993 | diag::warn_deprecated_redundant_constexpr_static_def); | |||
3994 | } else if (VarDecl *Def = Old->getDefinition()) { | |||
3995 | if (checkVarDeclRedefinition(Def, New)) | |||
3996 | return; | |||
3997 | } | |||
3998 | } | |||
3999 | ||||
4000 | if (haveIncompatibleLanguageLinkages(Old, New)) { | |||
4001 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | |||
4002 | Diag(OldLocation, PrevDiag); | |||
4003 | New->setInvalidDecl(); | |||
4004 | return; | |||
4005 | } | |||
4006 | ||||
4007 | // Merge "used" flag. | |||
4008 | if (Old->getMostRecentDecl()->isUsed(false)) | |||
4009 | New->setIsUsed(); | |||
4010 | ||||
4011 | // Keep a chain of previous declarations. | |||
4012 | New->setPreviousDecl(Old); | |||
4013 | if (NewTemplate) | |||
4014 | NewTemplate->setPreviousDecl(OldTemplate); | |||
4015 | adjustDeclContextForDeclaratorDecl(New, Old); | |||
4016 | ||||
4017 | // Inherit access appropriately. | |||
4018 | New->setAccess(Old->getAccess()); | |||
4019 | if (NewTemplate) | |||
4020 | NewTemplate->setAccess(New->getAccess()); | |||
4021 | ||||
4022 | if (Old->isInline()) | |||
4023 | New->setImplicitlyInline(); | |||
4024 | } | |||
4025 | ||||
4026 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { | |||
4027 | SourceManager &SrcMgr = getSourceManager(); | |||
4028 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); | |||
4029 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); | |||
4030 | auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); | |||
4031 | auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); | |||
4032 | auto &HSI = PP.getHeaderSearchInfo(); | |||
4033 | StringRef HdrFilename = | |||
4034 | SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); | |||
4035 | ||||
4036 | auto noteFromModuleOrInclude = [&](Module *Mod, | |||
4037 | SourceLocation IncLoc) -> bool { | |||
4038 | // Redefinition errors with modules are common with non modular mapped | |||
4039 | // headers, example: a non-modular header H in module A that also gets | |||
4040 | // included directly in a TU. Pointing twice to the same header/definition | |||
4041 | // is confusing, try to get better diagnostics when modules is on. | |||
4042 | if (IncLoc.isValid()) { | |||
4043 | if (Mod) { | |||
4044 | Diag(IncLoc, diag::note_redefinition_modules_same_file) | |||
4045 | << HdrFilename.str() << Mod->getFullModuleName(); | |||
4046 | if (!Mod->DefinitionLoc.isInvalid()) | |||
4047 | Diag(Mod->DefinitionLoc, diag::note_defined_here) | |||
4048 | << Mod->getFullModuleName(); | |||
4049 | } else { | |||
4050 | Diag(IncLoc, diag::note_redefinition_include_same_file) | |||
4051 | << HdrFilename.str(); | |||
4052 | } | |||
4053 | return true; | |||
4054 | } | |||
4055 | ||||
4056 | return false; | |||
4057 | }; | |||
4058 | ||||
4059 | // Is it the same file and same offset? Provide more information on why | |||
4060 | // this leads to a redefinition error. | |||
4061 | bool EmittedDiag = false; | |||
4062 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { | |||
4063 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); | |||
4064 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); | |||
4065 | EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); | |||
4066 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); | |||
4067 | ||||
4068 | // If the header has no guards, emit a note suggesting one. | |||
4069 | if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) | |||
4070 | Diag(Old->getLocation(), diag::note_use_ifdef_guards); | |||
4071 | ||||
4072 | if (EmittedDiag) | |||
4073 | return; | |||
4074 | } | |||
4075 | ||||
4076 | // Redefinition coming from different files or couldn't do better above. | |||
4077 | if (Old->getLocation().isValid()) | |||
4078 | Diag(Old->getLocation(), diag::note_previous_definition); | |||
4079 | } | |||
4080 | ||||
4081 | /// We've just determined that \p Old and \p New both appear to be definitions | |||
4082 | /// of the same variable. Either diagnose or fix the problem. | |||
4083 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { | |||
4084 | if (!hasVisibleDefinition(Old) && | |||
4085 | (New->getFormalLinkage() == InternalLinkage || | |||
4086 | New->isInline() || | |||
4087 | New->getDescribedVarTemplate() || | |||
4088 | New->getNumTemplateParameterLists() || | |||
4089 | New->getDeclContext()->isDependentContext())) { | |||
4090 | // The previous definition is hidden, and multiple definitions are | |||
4091 | // permitted (in separate TUs). Demote this to a declaration. | |||
4092 | New->demoteThisDefinitionToDeclaration(); | |||
4093 | ||||
4094 | // Make the canonical definition visible. | |||
4095 | if (auto *OldTD = Old->getDescribedVarTemplate()) | |||
4096 | makeMergedDefinitionVisible(OldTD); | |||
4097 | makeMergedDefinitionVisible(Old); | |||
4098 | return false; | |||
4099 | } else { | |||
4100 | Diag(New->getLocation(), diag::err_redefinition) << New; | |||
4101 | notePreviousDefinition(Old, New->getLocation()); | |||
4102 | New->setInvalidDecl(); | |||
4103 | return true; | |||
4104 | } | |||
4105 | } | |||
4106 | ||||
4107 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | |||
4108 | /// no declarator (e.g. "struct foo;") is parsed. | |||
4109 | Decl * | |||
4110 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | |||
4111 | RecordDecl *&AnonRecord) { | |||
4112 | return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, | |||
4113 | AnonRecord); | |||
4114 | } | |||
4115 | ||||
4116 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to | |||
4117 | // disambiguate entities defined in different scopes. | |||
4118 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks | |||
4119 | // compatibility. | |||
4120 | // We will pick our mangling number depending on which version of MSVC is being | |||
4121 | // targeted. | |||
4122 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { | |||
4123 | return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) | |||
4124 | ? S->getMSCurManglingNumber() | |||
4125 | : S->getMSLastManglingNumber(); | |||
4126 | } | |||
4127 | ||||
4128 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { | |||
4129 | if (!Context.getLangOpts().CPlusPlus) | |||
4130 | return; | |||
4131 | ||||
4132 | if (isa<CXXRecordDecl>(Tag->getParent())) { | |||
4133 | // If this tag is the direct child of a class, number it if | |||
4134 | // it is anonymous. | |||
4135 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) | |||
4136 | return; | |||
4137 | MangleNumberingContext &MCtx = | |||
4138 | Context.getManglingNumberContext(Tag->getParent()); | |||
4139 | Context.setManglingNumber( | |||
4140 | Tag, MCtx.getManglingNumber( | |||
4141 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | |||
4142 | return; | |||
4143 | } | |||
4144 | ||||
4145 | // If this tag isn't a direct child of a class, number it if it is local. | |||
4146 | Decl *ManglingContextDecl; | |||
4147 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( | |||
4148 | Tag->getDeclContext(), ManglingContextDecl)) { | |||
4149 | Context.setManglingNumber( | |||
4150 | Tag, MCtx->getManglingNumber( | |||
4151 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | |||
4152 | } | |||
4153 | } | |||
4154 | ||||
4155 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, | |||
4156 | TypedefNameDecl *NewTD) { | |||
4157 | if (TagFromDeclSpec->isInvalidDecl()) | |||
4158 | return; | |||
4159 | ||||
4160 | // Do nothing if the tag already has a name for linkage purposes. | |||
4161 | if (TagFromDeclSpec->hasNameForLinkage()) | |||
4162 | return; | |||
4163 | ||||
4164 | // A well-formed anonymous tag must always be a TUK_Definition. | |||
4165 | assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition ()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4165, __extension__ __PRETTY_FUNCTION__)); | |||
4166 | ||||
4167 | // The type must match the tag exactly; no qualifiers allowed. | |||
4168 | if (!Context.hasSameType(NewTD->getUnderlyingType(), | |||
4169 | Context.getTagDeclType(TagFromDeclSpec))) { | |||
4170 | if (getLangOpts().CPlusPlus) | |||
4171 | Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); | |||
4172 | return; | |||
4173 | } | |||
4174 | ||||
4175 | // If we've already computed linkage for the anonymous tag, then | |||
4176 | // adding a typedef name for the anonymous decl can change that | |||
4177 | // linkage, which might be a serious problem. Diagnose this as | |||
4178 | // unsupported and ignore the typedef name. TODO: we should | |||
4179 | // pursue this as a language defect and establish a formal rule | |||
4180 | // for how to handle it. | |||
4181 | if (TagFromDeclSpec->hasLinkageBeenComputed()) { | |||
4182 | Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); | |||
4183 | ||||
4184 | SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); | |||
4185 | tagLoc = getLocForEndOfToken(tagLoc); | |||
4186 | ||||
4187 | llvm::SmallString<40> textToInsert; | |||
4188 | textToInsert += ' '; | |||
4189 | textToInsert += NewTD->getIdentifier()->getName(); | |||
4190 | Diag(tagLoc, diag::note_typedef_changes_linkage) | |||
4191 | << FixItHint::CreateInsertion(tagLoc, textToInsert); | |||
4192 | return; | |||
4193 | } | |||
4194 | ||||
4195 | // Otherwise, set this is the anon-decl typedef for the tag. | |||
4196 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); | |||
4197 | } | |||
4198 | ||||
4199 | static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { | |||
4200 | switch (T) { | |||
4201 | case DeclSpec::TST_class: | |||
4202 | return 0; | |||
4203 | case DeclSpec::TST_struct: | |||
4204 | return 1; | |||
4205 | case DeclSpec::TST_interface: | |||
4206 | return 2; | |||
4207 | case DeclSpec::TST_union: | |||
4208 | return 3; | |||
4209 | case DeclSpec::TST_enum: | |||
4210 | return 4; | |||
4211 | default: | |||
4212 | llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4212); | |||
4213 | } | |||
4214 | } | |||
4215 | ||||
4216 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | |||
4217 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template | |||
4218 | /// parameters to cope with template friend declarations. | |||
4219 | Decl * | |||
4220 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | |||
4221 | MultiTemplateParamsArg TemplateParams, | |||
4222 | bool IsExplicitInstantiation, | |||
4223 | RecordDecl *&AnonRecord) { | |||
4224 | Decl *TagD = nullptr; | |||
4225 | TagDecl *Tag = nullptr; | |||
4226 | if (DS.getTypeSpecType() == DeclSpec::TST_class || | |||
4227 | DS.getTypeSpecType() == DeclSpec::TST_struct || | |||
4228 | DS.getTypeSpecType() == DeclSpec::TST_interface || | |||
4229 | DS.getTypeSpecType() == DeclSpec::TST_union || | |||
4230 | DS.getTypeSpecType() == DeclSpec::TST_enum) { | |||
4231 | TagD = DS.getRepAsDecl(); | |||
4232 | ||||
4233 | if (!TagD) // We probably had an error | |||
4234 | return nullptr; | |||
4235 | ||||
4236 | // Note that the above type specs guarantee that the | |||
4237 | // type rep is a Decl, whereas in many of the others | |||
4238 | // it's a Type. | |||
4239 | if (isa<TagDecl>(TagD)) | |||
4240 | Tag = cast<TagDecl>(TagD); | |||
4241 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) | |||
4242 | Tag = CTD->getTemplatedDecl(); | |||
4243 | } | |||
4244 | ||||
4245 | if (Tag) { | |||
4246 | handleTagNumbering(Tag, S); | |||
4247 | Tag->setFreeStanding(); | |||
4248 | if (Tag->isInvalidDecl()) | |||
4249 | return Tag; | |||
4250 | } | |||
4251 | ||||
4252 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | |||
4253 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object | |||
4254 | // or incomplete types shall not be restrict-qualified." | |||
4255 | if (TypeQuals & DeclSpec::TQ_restrict) | |||
4256 | Diag(DS.getRestrictSpecLoc(), | |||
4257 | diag::err_typecheck_invalid_restrict_not_pointer_noarg) | |||
4258 | << DS.getSourceRange(); | |||
4259 | } | |||
4260 | ||||
4261 | if (DS.isInlineSpecified()) | |||
4262 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | |||
4263 | << getLangOpts().CPlusPlus17; | |||
4264 | ||||
4265 | if (DS.isConstexprSpecified()) { | |||
4266 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations | |||
4267 | // and definitions of functions and variables. | |||
4268 | if (Tag) | |||
4269 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) | |||
4270 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); | |||
4271 | else | |||
4272 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); | |||
4273 | // Don't emit warnings after this error. | |||
4274 | return TagD; | |||
4275 | } | |||
4276 | ||||
4277 | DiagnoseFunctionSpecifiers(DS); | |||
4278 | ||||
4279 | if (DS.isFriendSpecified()) { | |||
4280 | // If we're dealing with a decl but not a TagDecl, assume that | |||
4281 | // whatever routines created it handled the friendship aspect. | |||
4282 | if (TagD && !Tag) | |||
4283 | return nullptr; | |||
4284 | return ActOnFriendTypeDecl(S, DS, TemplateParams); | |||
4285 | } | |||
4286 | ||||
4287 | const CXXScopeSpec &SS = DS.getTypeSpecScope(); | |||
4288 | bool IsExplicitSpecialization = | |||
4289 | !TemplateParams.empty() && TemplateParams.back()->size() == 0; | |||
4290 | if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && | |||
4291 | !IsExplicitInstantiation && !IsExplicitSpecialization && | |||
4292 | !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { | |||
4293 | // Per C++ [dcl.type.elab]p1, a class declaration cannot have a | |||
4294 | // nested-name-specifier unless it is an explicit instantiation | |||
4295 | // or an explicit specialization. | |||
4296 | // | |||
4297 | // FIXME: We allow class template partial specializations here too, per the | |||
4298 | // obvious intent of DR1819. | |||
4299 | // | |||
4300 | // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. | |||
4301 | Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) | |||
4302 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); | |||
4303 | return nullptr; | |||
4304 | } | |||
4305 | ||||
4306 | // Track whether this decl-specifier declares anything. | |||
4307 | bool DeclaresAnything = true; | |||
4308 | ||||
4309 | // Handle anonymous struct definitions. | |||
4310 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { | |||
4311 | if (!Record->getDeclName() && Record->isCompleteDefinition() && | |||
4312 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { | |||
4313 | if (getLangOpts().CPlusPlus || | |||
4314 | Record->getDeclContext()->isRecord()) { | |||
4315 | // If CurContext is a DeclContext that can contain statements, | |||
4316 | // RecursiveASTVisitor won't visit the decls that | |||
4317 | // BuildAnonymousStructOrUnion() will put into CurContext. | |||
4318 | // Also store them here so that they can be part of the | |||
4319 | // DeclStmt that gets created in this case. | |||
4320 | // FIXME: Also return the IndirectFieldDecls created by | |||
4321 | // BuildAnonymousStructOr union, for the same reason? | |||
4322 | if (CurContext->isFunctionOrMethod()) | |||
4323 | AnonRecord = Record; | |||
4324 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, | |||
4325 | Context.getPrintingPolicy()); | |||
4326 | } | |||
4327 | ||||
4328 | DeclaresAnything = false; | |||
4329 | } | |||
4330 | } | |||
4331 | ||||
4332 | // C11 6.7.2.1p2: | |||
4333 | // A struct-declaration that does not declare an anonymous structure or | |||
4334 | // anonymous union shall contain a struct-declarator-list. | |||
4335 | // | |||
4336 | // This rule also existed in C89 and C99; the grammar for struct-declaration | |||
4337 | // did not permit a struct-declaration without a struct-declarator-list. | |||
4338 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && | |||
4339 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { | |||
4340 | // Check for Microsoft C extension: anonymous struct/union member. | |||
4341 | // Handle 2 kinds of anonymous struct/union: | |||
4342 | // struct STRUCT; | |||
4343 | // union UNION; | |||
4344 | // and | |||
4345 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. | |||
4346 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. | |||
4347 | if ((Tag && Tag->getDeclName()) || | |||
4348 | DS.getTypeSpecType() == DeclSpec::TST_typename) { | |||
4349 | RecordDecl *Record = nullptr; | |||
4350 | if (Tag) | |||
4351 | Record = dyn_cast<RecordDecl>(Tag); | |||
4352 | else if (const RecordType *RT = | |||
4353 | DS.getRepAsType().get()->getAsStructureType()) | |||
4354 | Record = RT->getDecl(); | |||
4355 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) | |||
4356 | Record = UT->getDecl(); | |||
4357 | ||||
4358 | if (Record && getLangOpts().MicrosoftExt) { | |||
4359 | Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) | |||
4360 | << Record->isUnion() << DS.getSourceRange(); | |||
4361 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); | |||
4362 | } | |||
4363 | ||||
4364 | DeclaresAnything = false; | |||
4365 | } | |||
4366 | } | |||
4367 | ||||
4368 | // Skip all the checks below if we have a type error. | |||
4369 | if (DS.getTypeSpecType() == DeclSpec::TST_error || | |||
4370 | (TagD && TagD->isInvalidDecl())) | |||
4371 | return TagD; | |||
4372 | ||||
4373 | if (getLangOpts().CPlusPlus && | |||
4374 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) | |||
4375 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) | |||
4376 | if (Enum->enumerator_begin() == Enum->enumerator_end() && | |||
4377 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) | |||
4378 | DeclaresAnything = false; | |||
4379 | ||||
4380 | if (!DS.isMissingDeclaratorOk()) { | |||
4381 | // Customize diagnostic for a typedef missing a name. | |||
4382 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
4383 | Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) | |||
4384 | << DS.getSourceRange(); | |||
4385 | else | |||
4386 | DeclaresAnything = false; | |||
4387 | } | |||
4388 | ||||
4389 | if (DS.isModulePrivateSpecified() && | |||
4390 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) | |||
4391 | Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) | |||
4392 | << Tag->getTagKind() | |||
4393 | << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); | |||
4394 | ||||
4395 | ActOnDocumentableDecl(TagD); | |||
4396 | ||||
4397 | // C 6.7/2: | |||
4398 | // A declaration [...] shall declare at least a declarator [...], a tag, | |||
4399 | // or the members of an enumeration. | |||
4400 | // C++ [dcl.dcl]p3: | |||
4401 | // [If there are no declarators], and except for the declaration of an | |||
4402 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | |||
4403 | // names into the program, or shall redeclare a name introduced by a | |||
4404 | // previous declaration. | |||
4405 | if (!DeclaresAnything) { | |||
4406 | // In C, we allow this as a (popular) extension / bug. Don't bother | |||
4407 | // producing further diagnostics for redundant qualifiers after this. | |||
4408 | Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); | |||
4409 | return TagD; | |||
4410 | } | |||
4411 | ||||
4412 | // C++ [dcl.stc]p1: | |||
4413 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the | |||
4414 | // init-declarator-list of the declaration shall not be empty. | |||
4415 | // C++ [dcl.fct.spec]p1: | |||
4416 | // If a cv-qualifier appears in a decl-specifier-seq, the | |||
4417 | // init-declarator-list of the declaration shall not be empty. | |||
4418 | // | |||
4419 | // Spurious qualifiers here appear to be valid in C. | |||
4420 | unsigned DiagID = diag::warn_standalone_specifier; | |||
4421 | if (getLangOpts().CPlusPlus) | |||
4422 | DiagID = diag::ext_standalone_specifier; | |||
4423 | ||||
4424 | // Note that a linkage-specification sets a storage class, but | |||
4425 | // 'extern "C" struct foo;' is actually valid and not theoretically | |||
4426 | // useless. | |||
4427 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { | |||
4428 | if (SCS == DeclSpec::SCS_mutable) | |||
4429 | // Since mutable is not a viable storage class specifier in C, there is | |||
4430 | // no reason to treat it as an extension. Instead, diagnose as an error. | |||
4431 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); | |||
4432 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) | |||
4433 | Diag(DS.getStorageClassSpecLoc(), DiagID) | |||
4434 | << DeclSpec::getSpecifierName(SCS); | |||
4435 | } | |||
4436 | ||||
4437 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | |||
4438 | Diag(DS.getThreadStorageClassSpecLoc(), DiagID) | |||
4439 | << DeclSpec::getSpecifierName(TSCS); | |||
4440 | if (DS.getTypeQualifiers()) { | |||
4441 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | |||
4442 | Diag(DS.getConstSpecLoc(), DiagID) << "const"; | |||
4443 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | |||
4444 | Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; | |||
4445 | // Restrict is covered above. | |||
4446 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | |||
4447 | Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; | |||
4448 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | |||
4449 | Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; | |||
4450 | } | |||
4451 | ||||
4452 | // Warn about ignored type attributes, for example: | |||
4453 | // __attribute__((aligned)) struct A; | |||
4454 | // Attributes should be placed after tag to apply to type declaration. | |||
4455 | if (!DS.getAttributes().empty()) { | |||
4456 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); | |||
4457 | if (TypeSpecType == DeclSpec::TST_class || | |||
4458 | TypeSpecType == DeclSpec::TST_struct || | |||
4459 | TypeSpecType == DeclSpec::TST_interface || | |||
4460 | TypeSpecType == DeclSpec::TST_union || | |||
4461 | TypeSpecType == DeclSpec::TST_enum) { | |||
4462 | for (const ParsedAttr &AL : DS.getAttributes()) | |||
4463 | Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) | |||
4464 | << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); | |||
4465 | } | |||
4466 | } | |||
4467 | ||||
4468 | return TagD; | |||
4469 | } | |||
4470 | ||||
4471 | /// We are trying to inject an anonymous member into the given scope; | |||
4472 | /// check if there's an existing declaration that can't be overloaded. | |||
4473 | /// | |||
4474 | /// \return true if this is a forbidden redeclaration | |||
4475 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, | |||
4476 | Scope *S, | |||
4477 | DeclContext *Owner, | |||
4478 | DeclarationName Name, | |||
4479 | SourceLocation NameLoc, | |||
4480 | bool IsUnion) { | |||
4481 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, | |||
4482 | Sema::ForVisibleRedeclaration); | |||
4483 | if (!SemaRef.LookupName(R, S)) return false; | |||
4484 | ||||
4485 | // Pick a representative declaration. | |||
4486 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); | |||
4487 | assert(PrevDecl && "Expected a non-null Decl")(static_cast <bool> (PrevDecl && "Expected a non-null Decl" ) ? void (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4487, __extension__ __PRETTY_FUNCTION__)); | |||
4488 | ||||
4489 | if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) | |||
4490 | return false; | |||
4491 | ||||
4492 | SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) | |||
4493 | << IsUnion << Name; | |||
4494 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
4495 | ||||
4496 | return true; | |||
4497 | } | |||
4498 | ||||
4499 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the | |||
4500 | /// anonymous struct or union AnonRecord into the owning context Owner | |||
4501 | /// and scope S. This routine will be invoked just after we realize | |||
4502 | /// that an unnamed union or struct is actually an anonymous union or | |||
4503 | /// struct, e.g., | |||
4504 | /// | |||
4505 | /// @code | |||
4506 | /// union { | |||
4507 | /// int i; | |||
4508 | /// float f; | |||
4509 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and | |||
4510 | /// // f into the surrounding scope.x | |||
4511 | /// @endcode | |||
4512 | /// | |||
4513 | /// This routine is recursive, injecting the names of nested anonymous | |||
4514 | /// structs/unions into the owning context and scope as well. | |||
4515 | static bool | |||
4516 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, | |||
4517 | RecordDecl *AnonRecord, AccessSpecifier AS, | |||
4518 | SmallVectorImpl<NamedDecl *> &Chaining) { | |||
4519 | bool Invalid = false; | |||
4520 | ||||
4521 | // Look every FieldDecl and IndirectFieldDecl with a name. | |||
4522 | for (auto *D : AnonRecord->decls()) { | |||
4523 | if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && | |||
4524 | cast<NamedDecl>(D)->getDeclName()) { | |||
4525 | ValueDecl *VD = cast<ValueDecl>(D); | |||
4526 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), | |||
4527 | VD->getLocation(), | |||
4528 | AnonRecord->isUnion())) { | |||
4529 | // C++ [class.union]p2: | |||
4530 | // The names of the members of an anonymous union shall be | |||
4531 | // distinct from the names of any other entity in the | |||
4532 | // scope in which the anonymous union is declared. | |||
4533 | Invalid = true; | |||
4534 | } else { | |||
4535 | // C++ [class.union]p2: | |||
4536 | // For the purpose of name lookup, after the anonymous union | |||
4537 | // definition, the members of the anonymous union are | |||
4538 | // considered to have been defined in the scope in which the | |||
4539 | // anonymous union is declared. | |||
4540 | unsigned OldChainingSize = Chaining.size(); | |||
4541 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) | |||
4542 | Chaining.append(IF->chain_begin(), IF->chain_end()); | |||
4543 | else | |||
4544 | Chaining.push_back(VD); | |||
4545 | ||||
4546 | assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0 ) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4546, __extension__ __PRETTY_FUNCTION__)); | |||
4547 | NamedDecl **NamedChain = | |||
4548 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; | |||
4549 | for (unsigned i = 0; i < Chaining.size(); i++) | |||
4550 | NamedChain[i] = Chaining[i]; | |||
4551 | ||||
4552 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( | |||
4553 | SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), | |||
4554 | VD->getType(), {NamedChain, Chaining.size()}); | |||
4555 | ||||
4556 | for (const auto *Attr : VD->attrs()) | |||
4557 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); | |||
4558 | ||||
4559 | IndirectField->setAccess(AS); | |||
4560 | IndirectField->setImplicit(); | |||
4561 | SemaRef.PushOnScopeChains(IndirectField, S); | |||
4562 | ||||
4563 | // That includes picking up the appropriate access specifier. | |||
4564 | if (AS != AS_none) IndirectField->setAccess(AS); | |||
4565 | ||||
4566 | Chaining.resize(OldChainingSize); | |||
4567 | } | |||
4568 | } | |||
4569 | } | |||
4570 | ||||
4571 | return Invalid; | |||
4572 | } | |||
4573 | ||||
4574 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to | |||
4575 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: | |||
4576 | /// illegal input values are mapped to SC_None. | |||
4577 | static StorageClass | |||
4578 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { | |||
4579 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); | |||
4580 | assert(StorageClassSpec != DeclSpec::SCS_typedef &&(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4581, __extension__ __PRETTY_FUNCTION__)) | |||
4581 | "Parser allowed 'typedef' as storage class VarDecl.")(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4581, __extension__ __PRETTY_FUNCTION__)); | |||
4582 | switch (StorageClassSpec) { | |||
4583 | case DeclSpec::SCS_unspecified: return SC_None; | |||
4584 | case DeclSpec::SCS_extern: | |||
4585 | if (DS.isExternInLinkageSpec()) | |||
4586 | return SC_None; | |||
4587 | return SC_Extern; | |||
4588 | case DeclSpec::SCS_static: return SC_Static; | |||
4589 | case DeclSpec::SCS_auto: return SC_Auto; | |||
4590 | case DeclSpec::SCS_register: return SC_Register; | |||
4591 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | |||
4592 | // Illegal SCSs map to None: error reporting is up to the caller. | |||
4593 | case DeclSpec::SCS_mutable: // Fall through. | |||
4594 | case DeclSpec::SCS_typedef: return SC_None; | |||
4595 | } | |||
4596 | llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4596); | |||
4597 | } | |||
4598 | ||||
4599 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { | |||
4600 | assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer() ) ? void (0) : __assert_fail ("Record->hasInClassInitializer()" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4600, __extension__ __PRETTY_FUNCTION__)); | |||
4601 | ||||
4602 | for (const auto *I : Record->decls()) { | |||
4603 | const auto *FD = dyn_cast<FieldDecl>(I); | |||
4604 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | |||
4605 | FD = IFD->getAnonField(); | |||
4606 | if (FD && FD->hasInClassInitializer()) | |||
4607 | return FD->getLocation(); | |||
4608 | } | |||
4609 | ||||
4610 | llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4610); | |||
4611 | } | |||
4612 | ||||
4613 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | |||
4614 | SourceLocation DefaultInitLoc) { | |||
4615 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | |||
4616 | return; | |||
4617 | ||||
4618 | S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); | |||
4619 | S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; | |||
4620 | } | |||
4621 | ||||
4622 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | |||
4623 | CXXRecordDecl *AnonUnion) { | |||
4624 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | |||
4625 | return; | |||
4626 | ||||
4627 | checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); | |||
4628 | } | |||
4629 | ||||
4630 | /// BuildAnonymousStructOrUnion - Handle the declaration of an | |||
4631 | /// anonymous structure or union. Anonymous unions are a C++ feature | |||
4632 | /// (C++ [class.union]) and a C11 feature; anonymous structures | |||
4633 | /// are a C11 feature and GNU C++ extension. | |||
4634 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, | |||
4635 | AccessSpecifier AS, | |||
4636 | RecordDecl *Record, | |||
4637 | const PrintingPolicy &Policy) { | |||
4638 | DeclContext *Owner = Record->getDeclContext(); | |||
4639 | ||||
4640 | // Diagnose whether this anonymous struct/union is an extension. | |||
4641 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) | |||
4642 | Diag(Record->getLocation(), diag::ext_anonymous_union); | |||
4643 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) | |||
4644 | Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); | |||
4645 | else if (!Record->isUnion() && !getLangOpts().C11) | |||
4646 | Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); | |||
4647 | ||||
4648 | // C and C++ require different kinds of checks for anonymous | |||
4649 | // structs/unions. | |||
4650 | bool Invalid = false; | |||
4651 | if (getLangOpts().CPlusPlus) { | |||
4652 | const char *PrevSpec = nullptr; | |||
4653 | unsigned DiagID; | |||
4654 | if (Record->isUnion()) { | |||
4655 | // C++ [class.union]p6: | |||
4656 | // C++17 [class.union.anon]p2: | |||
4657 | // Anonymous unions declared in a named namespace or in the | |||
4658 | // global namespace shall be declared static. | |||
4659 | DeclContext *OwnerScope = Owner->getRedeclContext(); | |||
4660 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && | |||
4661 | (OwnerScope->isTranslationUnit() || | |||
4662 | (OwnerScope->isNamespace() && | |||
4663 | !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { | |||
4664 | Diag(Record->getLocation(), diag::err_anonymous_union_not_static) | |||
4665 | << FixItHint::CreateInsertion(Record->getLocation(), "static "); | |||
4666 | ||||
4667 | // Recover by adding 'static'. | |||
4668 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), | |||
4669 | PrevSpec, DiagID, Policy); | |||
4670 | } | |||
4671 | // C++ [class.union]p6: | |||
4672 | // A storage class is not allowed in a declaration of an | |||
4673 | // anonymous union in a class scope. | |||
4674 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && | |||
4675 | isa<RecordDecl>(Owner)) { | |||
4676 | Diag(DS.getStorageClassSpecLoc(), | |||
4677 | diag::err_anonymous_union_with_storage_spec) | |||
4678 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | |||
4679 | ||||
4680 | // Recover by removing the storage specifier. | |||
4681 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, | |||
4682 | SourceLocation(), | |||
4683 | PrevSpec, DiagID, Context.getPrintingPolicy()); | |||
4684 | } | |||
4685 | } | |||
4686 | ||||
4687 | // Ignore const/volatile/restrict qualifiers. | |||
4688 | if (DS.getTypeQualifiers()) { | |||
4689 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | |||
4690 | Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) | |||
4691 | << Record->isUnion() << "const" | |||
4692 | << FixItHint::CreateRemoval(DS.getConstSpecLoc()); | |||
4693 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | |||
4694 | Diag(DS.getVolatileSpecLoc(), | |||
4695 | diag::ext_anonymous_struct_union_qualified) | |||
4696 | << Record->isUnion() << "volatile" | |||
4697 | << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); | |||
4698 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) | |||
4699 | Diag(DS.getRestrictSpecLoc(), | |||
4700 | diag::ext_anonymous_struct_union_qualified) | |||
4701 | << Record->isUnion() << "restrict" | |||
4702 | << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); | |||
4703 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | |||
4704 | Diag(DS.getAtomicSpecLoc(), | |||
4705 | diag::ext_anonymous_struct_union_qualified) | |||
4706 | << Record->isUnion() << "_Atomic" | |||
4707 | << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); | |||
4708 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | |||
4709 | Diag(DS.getUnalignedSpecLoc(), | |||
4710 | diag::ext_anonymous_struct_union_qualified) | |||
4711 | << Record->isUnion() << "__unaligned" | |||
4712 | << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); | |||
4713 | ||||
4714 | DS.ClearTypeQualifiers(); | |||
4715 | } | |||
4716 | ||||
4717 | // C++ [class.union]p2: | |||
4718 | // The member-specification of an anonymous union shall only | |||
4719 | // define non-static data members. [Note: nested types and | |||
4720 | // functions cannot be declared within an anonymous union. ] | |||
4721 | for (auto *Mem : Record->decls()) { | |||
4722 | if (auto *FD = dyn_cast<FieldDecl>(Mem)) { | |||
4723 | // C++ [class.union]p3: | |||
4724 | // An anonymous union shall not have private or protected | |||
4725 | // members (clause 11). | |||
4726 | assert(FD->getAccess() != AS_none)(static_cast <bool> (FD->getAccess() != AS_none) ? void (0) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4726, __extension__ __PRETTY_FUNCTION__)); | |||
4727 | if (FD->getAccess() != AS_public) { | |||
4728 | Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) | |||
4729 | << Record->isUnion() << (FD->getAccess() == AS_protected); | |||
4730 | Invalid = true; | |||
4731 | } | |||
4732 | ||||
4733 | // C++ [class.union]p1 | |||
4734 | // An object of a class with a non-trivial constructor, a non-trivial | |||
4735 | // copy constructor, a non-trivial destructor, or a non-trivial copy | |||
4736 | // assignment operator cannot be a member of a union, nor can an | |||
4737 | // array of such objects. | |||
4738 | if (CheckNontrivialField(FD)) | |||
4739 | Invalid = true; | |||
4740 | } else if (Mem->isImplicit()) { | |||
4741 | // Any implicit members are fine. | |||
4742 | } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { | |||
4743 | // This is a type that showed up in an | |||
4744 | // elaborated-type-specifier inside the anonymous struct or | |||
4745 | // union, but which actually declares a type outside of the | |||
4746 | // anonymous struct or union. It's okay. | |||
4747 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { | |||
4748 | if (!MemRecord->isAnonymousStructOrUnion() && | |||
4749 | MemRecord->getDeclName()) { | |||
4750 | // Visual C++ allows type definition in anonymous struct or union. | |||
4751 | if (getLangOpts().MicrosoftExt) | |||
4752 | Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) | |||
4753 | << Record->isUnion(); | |||
4754 | else { | |||
4755 | // This is a nested type declaration. | |||
4756 | Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) | |||
4757 | << Record->isUnion(); | |||
4758 | Invalid = true; | |||
4759 | } | |||
4760 | } else { | |||
4761 | // This is an anonymous type definition within another anonymous type. | |||
4762 | // This is a popular extension, provided by Plan9, MSVC and GCC, but | |||
4763 | // not part of standard C++. | |||
4764 | Diag(MemRecord->getLocation(), | |||
4765 | diag::ext_anonymous_record_with_anonymous_type) | |||
4766 | << Record->isUnion(); | |||
4767 | } | |||
4768 | } else if (isa<AccessSpecDecl>(Mem)) { | |||
4769 | // Any access specifier is fine. | |||
4770 | } else if (isa<StaticAssertDecl>(Mem)) { | |||
4771 | // In C++1z, static_assert declarations are also fine. | |||
4772 | } else { | |||
4773 | // We have something that isn't a non-static data | |||
4774 | // member. Complain about it. | |||
4775 | unsigned DK = diag::err_anonymous_record_bad_member; | |||
4776 | if (isa<TypeDecl>(Mem)) | |||
4777 | DK = diag::err_anonymous_record_with_type; | |||
4778 | else if (isa<FunctionDecl>(Mem)) | |||
4779 | DK = diag::err_anonymous_record_with_function; | |||
4780 | else if (isa<VarDecl>(Mem)) | |||
4781 | DK = diag::err_anonymous_record_with_static; | |||
4782 | ||||
4783 | // Visual C++ allows type definition in anonymous struct or union. | |||
4784 | if (getLangOpts().MicrosoftExt && | |||
4785 | DK == diag::err_anonymous_record_with_type) | |||
4786 | Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) | |||
4787 | << Record->isUnion(); | |||
4788 | else { | |||
4789 | Diag(Mem->getLocation(), DK) << Record->isUnion(); | |||
4790 | Invalid = true; | |||
4791 | } | |||
4792 | } | |||
4793 | } | |||
4794 | ||||
4795 | // C++11 [class.union]p8 (DR1460): | |||
4796 | // At most one variant member of a union may have a | |||
4797 | // brace-or-equal-initializer. | |||
4798 | if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && | |||
4799 | Owner->isRecord()) | |||
4800 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), | |||
4801 | cast<CXXRecordDecl>(Record)); | |||
4802 | } | |||
4803 | ||||
4804 | if (!Record->isUnion() && !Owner->isRecord()) { | |||
4805 | Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) | |||
4806 | << getLangOpts().CPlusPlus; | |||
4807 | Invalid = true; | |||
4808 | } | |||
4809 | ||||
4810 | // Mock up a declarator. | |||
4811 | Declarator Dc(DS, DeclaratorContext::MemberContext); | |||
4812 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | |||
4813 | assert(TInfo && "couldn't build declarator info for anonymous struct/union")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct/union" ) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4813, __extension__ __PRETTY_FUNCTION__)); | |||
4814 | ||||
4815 | // Create a declaration for this anonymous struct/union. | |||
4816 | NamedDecl *Anon = nullptr; | |||
4817 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { | |||
4818 | Anon = FieldDecl::Create(Context, OwningClass, | |||
4819 | DS.getLocStart(), | |||
4820 | Record->getLocation(), | |||
4821 | /*IdentifierInfo=*/nullptr, | |||
4822 | Context.getTypeDeclType(Record), | |||
4823 | TInfo, | |||
4824 | /*BitWidth=*/nullptr, /*Mutable=*/false, | |||
4825 | /*InitStyle=*/ICIS_NoInit); | |||
4826 | Anon->setAccess(AS); | |||
4827 | if (getLangOpts().CPlusPlus) | |||
4828 | FieldCollector->Add(cast<FieldDecl>(Anon)); | |||
4829 | } else { | |||
4830 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); | |||
4831 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); | |||
4832 | if (SCSpec == DeclSpec::SCS_mutable) { | |||
4833 | // mutable can only appear on non-static class members, so it's always | |||
4834 | // an error here | |||
4835 | Diag(Record->getLocation(), diag::err_mutable_nonmember); | |||
4836 | Invalid = true; | |||
4837 | SC = SC_None; | |||
4838 | } | |||
4839 | ||||
4840 | Anon = VarDecl::Create(Context, Owner, | |||
4841 | DS.getLocStart(), | |||
4842 | Record->getLocation(), /*IdentifierInfo=*/nullptr, | |||
4843 | Context.getTypeDeclType(Record), | |||
4844 | TInfo, SC); | |||
4845 | ||||
4846 | // Default-initialize the implicit variable. This initialization will be | |||
4847 | // trivial in almost all cases, except if a union member has an in-class | |||
4848 | // initializer: | |||
4849 | // union { int n = 0; }; | |||
4850 | ActOnUninitializedDecl(Anon); | |||
4851 | } | |||
4852 | Anon->setImplicit(); | |||
4853 | ||||
4854 | // Mark this as an anonymous struct/union type. | |||
4855 | Record->setAnonymousStructOrUnion(true); | |||
4856 | ||||
4857 | // Add the anonymous struct/union object to the current | |||
4858 | // context. We'll be referencing this object when we refer to one of | |||
4859 | // its members. | |||
4860 | Owner->addDecl(Anon); | |||
4861 | ||||
4862 | // Inject the members of the anonymous struct/union into the owning | |||
4863 | // context and into the identifier resolver chain for name lookup | |||
4864 | // purposes. | |||
4865 | SmallVector<NamedDecl*, 2> Chain; | |||
4866 | Chain.push_back(Anon); | |||
4867 | ||||
4868 | if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) | |||
4869 | Invalid = true; | |||
4870 | ||||
4871 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { | |||
4872 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | |||
4873 | Decl *ManglingContextDecl; | |||
4874 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( | |||
4875 | NewVD->getDeclContext(), ManglingContextDecl)) { | |||
4876 | Context.setManglingNumber( | |||
4877 | NewVD, MCtx->getManglingNumber( | |||
4878 | NewVD, getMSManglingNumber(getLangOpts(), S))); | |||
4879 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | |||
4880 | } | |||
4881 | } | |||
4882 | } | |||
4883 | ||||
4884 | if (Invalid) | |||
4885 | Anon->setInvalidDecl(); | |||
4886 | ||||
4887 | return Anon; | |||
4888 | } | |||
4889 | ||||
4890 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an | |||
4891 | /// Microsoft C anonymous structure. | |||
4892 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx | |||
4893 | /// Example: | |||
4894 | /// | |||
4895 | /// struct A { int a; }; | |||
4896 | /// struct B { struct A; int b; }; | |||
4897 | /// | |||
4898 | /// void foo() { | |||
4899 | /// B var; | |||
4900 | /// var.a = 3; | |||
4901 | /// } | |||
4902 | /// | |||
4903 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, | |||
4904 | RecordDecl *Record) { | |||
4905 | assert(Record && "expected a record!")(static_cast <bool> (Record && "expected a record!" ) ? void (0) : __assert_fail ("Record && \"expected a record!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4905, __extension__ __PRETTY_FUNCTION__)); | |||
4906 | ||||
4907 | // Mock up a declarator. | |||
4908 | Declarator Dc(DS, DeclaratorContext::TypeNameContext); | |||
4909 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | |||
4910 | assert(TInfo && "couldn't build declarator info for anonymous struct")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct" ) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 4910, __extension__ __PRETTY_FUNCTION__)); | |||
4911 | ||||
4912 | auto *ParentDecl = cast<RecordDecl>(CurContext); | |||
4913 | QualType RecTy = Context.getTypeDeclType(Record); | |||
4914 | ||||
4915 | // Create a declaration for this anonymous struct. | |||
4916 | NamedDecl *Anon = FieldDecl::Create(Context, | |||
4917 | ParentDecl, | |||
4918 | DS.getLocStart(), | |||
4919 | DS.getLocStart(), | |||
4920 | /*IdentifierInfo=*/nullptr, | |||
4921 | RecTy, | |||
4922 | TInfo, | |||
4923 | /*BitWidth=*/nullptr, /*Mutable=*/false, | |||
4924 | /*InitStyle=*/ICIS_NoInit); | |||
4925 | Anon->setImplicit(); | |||
4926 | ||||
4927 | // Add the anonymous struct object to the current context. | |||
4928 | CurContext->addDecl(Anon); | |||
4929 | ||||
4930 | // Inject the members of the anonymous struct into the current | |||
4931 | // context and into the identifier resolver chain for name lookup | |||
4932 | // purposes. | |||
4933 | SmallVector<NamedDecl*, 2> Chain; | |||
4934 | Chain.push_back(Anon); | |||
4935 | ||||
4936 | RecordDecl *RecordDef = Record->getDefinition(); | |||
4937 | if (RequireCompleteType(Anon->getLocation(), RecTy, | |||
4938 | diag::err_field_incomplete) || | |||
4939 | InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, | |||
4940 | AS_none, Chain)) { | |||
4941 | Anon->setInvalidDecl(); | |||
4942 | ParentDecl->setInvalidDecl(); | |||
4943 | } | |||
4944 | ||||
4945 | return Anon; | |||
4946 | } | |||
4947 | ||||
4948 | /// GetNameForDeclarator - Determine the full declaration name for the | |||
4949 | /// given Declarator. | |||
4950 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { | |||
4951 | return GetNameFromUnqualifiedId(D.getName()); | |||
4952 | } | |||
4953 | ||||
4954 | /// Retrieves the declaration name from a parsed unqualified-id. | |||
4955 | DeclarationNameInfo | |||
4956 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { | |||
4957 | DeclarationNameInfo NameInfo; | |||
4958 | NameInfo.setLoc(Name.StartLocation); | |||
4959 | ||||
4960 | switch (Name.getKind()) { | |||
4961 | ||||
4962 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
4963 | case UnqualifiedIdKind::IK_Identifier: | |||
4964 | NameInfo.setName(Name.Identifier); | |||
4965 | NameInfo.setLoc(Name.StartLocation); | |||
4966 | return NameInfo; | |||
4967 | ||||
4968 | case UnqualifiedIdKind::IK_DeductionGuideName: { | |||
4969 | // C++ [temp.deduct.guide]p3: | |||
4970 | // The simple-template-id shall name a class template specialization. | |||
4971 | // The template-name shall be the same identifier as the template-name | |||
4972 | // of the simple-template-id. | |||
4973 | // These together intend to imply that the template-name shall name a | |||
4974 | // class template. | |||
4975 | // FIXME: template<typename T> struct X {}; | |||
4976 | // template<typename T> using Y = X<T>; | |||
4977 | // Y(int) -> Y<int>; | |||
4978 | // satisfies these rules but does not name a class template. | |||
4979 | TemplateName TN = Name.TemplateName.get().get(); | |||
4980 | auto *Template = TN.getAsTemplateDecl(); | |||
4981 | if (!Template || !isa<ClassTemplateDecl>(Template)) { | |||
4982 | Diag(Name.StartLocation, | |||
4983 | diag::err_deduction_guide_name_not_class_template) | |||
4984 | << (int)getTemplateNameKindForDiagnostics(TN) << TN; | |||
4985 | if (Template) | |||
4986 | Diag(Template->getLocation(), diag::note_template_decl_here); | |||
4987 | return DeclarationNameInfo(); | |||
4988 | } | |||
4989 | ||||
4990 | NameInfo.setName( | |||
4991 | Context.DeclarationNames.getCXXDeductionGuideName(Template)); | |||
4992 | NameInfo.setLoc(Name.StartLocation); | |||
4993 | return NameInfo; | |||
4994 | } | |||
4995 | ||||
4996 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
4997 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( | |||
4998 | Name.OperatorFunctionId.Operator)); | |||
4999 | NameInfo.setLoc(Name.StartLocation); | |||
5000 | NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc | |||
5001 | = Name.OperatorFunctionId.SymbolLocations[0]; | |||
5002 | NameInfo.getInfo().CXXOperatorName.EndOpNameLoc | |||
5003 | = Name.EndLocation.getRawEncoding(); | |||
5004 | return NameInfo; | |||
5005 | ||||
5006 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
5007 | NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( | |||
5008 | Name.Identifier)); | |||
5009 | NameInfo.setLoc(Name.StartLocation); | |||
5010 | NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); | |||
5011 | return NameInfo; | |||
5012 | ||||
5013 | case UnqualifiedIdKind::IK_ConversionFunctionId: { | |||
5014 | TypeSourceInfo *TInfo; | |||
5015 | QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); | |||
5016 | if (Ty.isNull()) | |||
5017 | return DeclarationNameInfo(); | |||
5018 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( | |||
5019 | Context.getCanonicalType(Ty))); | |||
5020 | NameInfo.setLoc(Name.StartLocation); | |||
5021 | NameInfo.setNamedTypeInfo(TInfo); | |||
5022 | return NameInfo; | |||
5023 | } | |||
5024 | ||||
5025 | case UnqualifiedIdKind::IK_ConstructorName: { | |||
5026 | TypeSourceInfo *TInfo; | |||
5027 | QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); | |||
5028 | if (Ty.isNull()) | |||
5029 | return DeclarationNameInfo(); | |||
5030 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | |||
5031 | Context.getCanonicalType(Ty))); | |||
5032 | NameInfo.setLoc(Name.StartLocation); | |||
5033 | NameInfo.setNamedTypeInfo(TInfo); | |||
5034 | return NameInfo; | |||
5035 | } | |||
5036 | ||||
5037 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { | |||
5038 | // In well-formed code, we can only have a constructor | |||
5039 | // template-id that refers to the current context, so go there | |||
5040 | // to find the actual type being constructed. | |||
5041 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); | |||
5042 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) | |||
5043 | return DeclarationNameInfo(); | |||
5044 | ||||
5045 | // Determine the type of the class being constructed. | |||
5046 | QualType CurClassType = Context.getTypeDeclType(CurClass); | |||
5047 | ||||
5048 | // FIXME: Check two things: that the template-id names the same type as | |||
5049 | // CurClassType, and that the template-id does not occur when the name | |||
5050 | // was qualified. | |||
5051 | ||||
5052 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | |||
5053 | Context.getCanonicalType(CurClassType))); | |||
5054 | NameInfo.setLoc(Name.StartLocation); | |||
5055 | // FIXME: should we retrieve TypeSourceInfo? | |||
5056 | NameInfo.setNamedTypeInfo(nullptr); | |||
5057 | return NameInfo; | |||
5058 | } | |||
5059 | ||||
5060 | case UnqualifiedIdKind::IK_DestructorName: { | |||
5061 | TypeSourceInfo *TInfo; | |||
5062 | QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); | |||
5063 | if (Ty.isNull()) | |||
5064 | return DeclarationNameInfo(); | |||
5065 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( | |||
5066 | Context.getCanonicalType(Ty))); | |||
5067 | NameInfo.setLoc(Name.StartLocation); | |||
5068 | NameInfo.setNamedTypeInfo(TInfo); | |||
5069 | return NameInfo; | |||
5070 | } | |||
5071 | ||||
5072 | case UnqualifiedIdKind::IK_TemplateId: { | |||
5073 | TemplateName TName = Name.TemplateId->Template.get(); | |||
5074 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; | |||
5075 | return Context.getNameForTemplate(TName, TNameLoc); | |||
5076 | } | |||
5077 | ||||
5078 | } // switch (Name.getKind()) | |||
5079 | ||||
5080 | llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 5080); | |||
5081 | } | |||
5082 | ||||
5083 | static QualType getCoreType(QualType Ty) { | |||
5084 | do { | |||
5085 | if (Ty->isPointerType() || Ty->isReferenceType()) | |||
5086 | Ty = Ty->getPointeeType(); | |||
5087 | else if (Ty->isArrayType()) | |||
5088 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); | |||
5089 | else | |||
5090 | return Ty.withoutLocalFastQualifiers(); | |||
5091 | } while (true); | |||
5092 | } | |||
5093 | ||||
5094 | /// hasSimilarParameters - Determine whether the C++ functions Declaration | |||
5095 | /// and Definition have "nearly" matching parameters. This heuristic is | |||
5096 | /// used to improve diagnostics in the case where an out-of-line function | |||
5097 | /// definition doesn't match any declaration within the class or namespace. | |||
5098 | /// Also sets Params to the list of indices to the parameters that differ | |||
5099 | /// between the declaration and the definition. If hasSimilarParameters | |||
5100 | /// returns true and Params is empty, then all of the parameters match. | |||
5101 | static bool hasSimilarParameters(ASTContext &Context, | |||
5102 | FunctionDecl *Declaration, | |||
5103 | FunctionDecl *Definition, | |||
5104 | SmallVectorImpl<unsigned> &Params) { | |||
5105 | Params.clear(); | |||
5106 | if (Declaration->param_size() != Definition->param_size()) | |||
5107 | return false; | |||
5108 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { | |||
5109 | QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); | |||
5110 | QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); | |||
5111 | ||||
5112 | // The parameter types are identical | |||
5113 | if (Context.hasSameType(DefParamTy, DeclParamTy)) | |||
5114 | continue; | |||
5115 | ||||
5116 | QualType DeclParamBaseTy = getCoreType(DeclParamTy); | |||
5117 | QualType DefParamBaseTy = getCoreType(DefParamTy); | |||
5118 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); | |||
5119 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); | |||
5120 | ||||
5121 | if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || | |||
5122 | (DeclTyName && DeclTyName == DefTyName)) | |||
5123 | Params.push_back(Idx); | |||
5124 | else // The two parameters aren't even close | |||
5125 | return false; | |||
5126 | } | |||
5127 | ||||
5128 | return true; | |||
5129 | } | |||
5130 | ||||
5131 | /// NeedsRebuildingInCurrentInstantiation - Checks whether the given | |||
5132 | /// declarator needs to be rebuilt in the current instantiation. | |||
5133 | /// Any bits of declarator which appear before the name are valid for | |||
5134 | /// consideration here. That's specifically the type in the decl spec | |||
5135 | /// and the base type in any member-pointer chunks. | |||
5136 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, | |||
5137 | DeclarationName Name) { | |||
5138 | // The types we specifically need to rebuild are: | |||
5139 | // - typenames, typeofs, and decltypes | |||
5140 | // - types which will become injected class names | |||
5141 | // Of course, we also need to rebuild any type referencing such a | |||
5142 | // type. It's safest to just say "dependent", but we call out a | |||
5143 | // few cases here. | |||
5144 | ||||
5145 | DeclSpec &DS = D.getMutableDeclSpec(); | |||
5146 | switch (DS.getTypeSpecType()) { | |||
5147 | case DeclSpec::TST_typename: | |||
5148 | case DeclSpec::TST_typeofType: | |||
5149 | case DeclSpec::TST_underlyingType: | |||
5150 | case DeclSpec::TST_atomic: { | |||
5151 | // Grab the type from the parser. | |||
5152 | TypeSourceInfo *TSI = nullptr; | |||
5153 | QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); | |||
5154 | if (T.isNull() || !T->isDependentType()) break; | |||
5155 | ||||
5156 | // Make sure there's a type source info. This isn't really much | |||
5157 | // of a waste; most dependent types should have type source info | |||
5158 | // attached already. | |||
5159 | if (!TSI) | |||
5160 | TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); | |||
5161 | ||||
5162 | // Rebuild the type in the current instantiation. | |||
5163 | TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); | |||
5164 | if (!TSI) return true; | |||
5165 | ||||
5166 | // Store the new type back in the decl spec. | |||
5167 | ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); | |||
5168 | DS.UpdateTypeRep(LocType); | |||
5169 | break; | |||
5170 | } | |||
5171 | ||||
5172 | case DeclSpec::TST_decltype: | |||
5173 | case DeclSpec::TST_typeofExpr: { | |||
5174 | Expr *E = DS.getRepAsExpr(); | |||
5175 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); | |||
5176 | if (Result.isInvalid()) return true; | |||
5177 | DS.UpdateExprRep(Result.get()); | |||
5178 | break; | |||
5179 | } | |||
5180 | ||||
5181 | default: | |||
5182 | // Nothing to do for these decl specs. | |||
5183 | break; | |||
5184 | } | |||
5185 | ||||
5186 | // It doesn't matter what order we do this in. | |||
5187 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | |||
5188 | DeclaratorChunk &Chunk = D.getTypeObject(I); | |||
5189 | ||||
5190 | // The only type information in the declarator which can come | |||
5191 | // before the declaration name is the base type of a member | |||
5192 | // pointer. | |||
5193 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) | |||
5194 | continue; | |||
5195 | ||||
5196 | // Rebuild the scope specifier in-place. | |||
5197 | CXXScopeSpec &SS = Chunk.Mem.Scope(); | |||
5198 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) | |||
5199 | return true; | |||
5200 | } | |||
5201 | ||||
5202 | return false; | |||
5203 | } | |||
5204 | ||||
5205 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { | |||
5206 | D.setFunctionDefinitionKind(FDK_Declaration); | |||
5207 | Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); | |||
5208 | ||||
5209 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && | |||
5210 | Dcl && Dcl->getDeclContext()->isFileContext()) | |||
5211 | Dcl->setTopLevelDeclInObjCContainer(); | |||
5212 | ||||
5213 | if (getLangOpts().OpenCL) | |||
5214 | setCurrentOpenCLExtensionForDecl(Dcl); | |||
5215 | ||||
5216 | return Dcl; | |||
5217 | } | |||
5218 | ||||
5219 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: | |||
5220 | /// If T is the name of a class, then each of the following shall have a | |||
5221 | /// name different from T: | |||
5222 | /// - every static data member of class T; | |||
5223 | /// - every member function of class T | |||
5224 | /// - every member of class T that is itself a type; | |||
5225 | /// \returns true if the declaration name violates these rules. | |||
5226 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, | |||
5227 | DeclarationNameInfo NameInfo) { | |||
5228 | DeclarationName Name = NameInfo.getName(); | |||
5229 | ||||
5230 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); | |||
5231 | while (Record && Record->isAnonymousStructOrUnion()) | |||
5232 | Record = dyn_cast<CXXRecordDecl>(Record->getParent()); | |||
5233 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { | |||
5234 | Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; | |||
5235 | return true; | |||
5236 | } | |||
5237 | ||||
5238 | return false; | |||
5239 | } | |||
5240 | ||||
5241 | /// Diagnose a declaration whose declarator-id has the given | |||
5242 | /// nested-name-specifier. | |||
5243 | /// | |||
5244 | /// \param SS The nested-name-specifier of the declarator-id. | |||
5245 | /// | |||
5246 | /// \param DC The declaration context to which the nested-name-specifier | |||
5247 | /// resolves. | |||
5248 | /// | |||
5249 | /// \param Name The name of the entity being declared. | |||
5250 | /// | |||
5251 | /// \param Loc The location of the name of the entity being declared. | |||
5252 | /// | |||
5253 | /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus | |||
5254 | /// we're declaring an explicit / partial specialization / instantiation. | |||
5255 | /// | |||
5256 | /// \returns true if we cannot safely recover from this error, false otherwise. | |||
5257 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, | |||
5258 | DeclarationName Name, | |||
5259 | SourceLocation Loc, bool IsTemplateId) { | |||
5260 | DeclContext *Cur = CurContext; | |||
5261 | while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) | |||
5262 | Cur = Cur->getParent(); | |||
5263 | ||||
5264 | // If the user provided a superfluous scope specifier that refers back to the | |||
5265 | // class in which the entity is already declared, diagnose and ignore it. | |||
5266 | // | |||
5267 | // class X { | |||
5268 | // void X::f(); | |||
5269 | // }; | |||
5270 | // | |||
5271 | // Note, it was once ill-formed to give redundant qualification in all | |||
5272 | // contexts, but that rule was removed by DR482. | |||
5273 | if (Cur->Equals(DC)) { | |||
5274 | if (Cur->isRecord()) { | |||
5275 | Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification | |||
5276 | : diag::err_member_extra_qualification) | |||
5277 | << Name << FixItHint::CreateRemoval(SS.getRange()); | |||
5278 | SS.clear(); | |||
5279 | } else { | |||
5280 | Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; | |||
5281 | } | |||
5282 | return false; | |||
5283 | } | |||
5284 | ||||
5285 | // Check whether the qualifying scope encloses the scope of the original | |||
5286 | // declaration. For a template-id, we perform the checks in | |||
5287 | // CheckTemplateSpecializationScope. | |||
5288 | if (!Cur->Encloses(DC) && !IsTemplateId) { | |||
5289 | if (Cur->isRecord()) | |||
5290 | Diag(Loc, diag::err_member_qualification) | |||
5291 | << Name << SS.getRange(); | |||
5292 | else if (isa<TranslationUnitDecl>(DC)) | |||
5293 | Diag(Loc, diag::err_invalid_declarator_global_scope) | |||
5294 | << Name << SS.getRange(); | |||
5295 | else if (isa<FunctionDecl>(Cur)) | |||
5296 | Diag(Loc, diag::err_invalid_declarator_in_function) | |||
5297 | << Name << SS.getRange(); | |||
5298 | else if (isa<BlockDecl>(Cur)) | |||
5299 | Diag(Loc, diag::err_invalid_declarator_in_block) | |||
5300 | << Name << SS.getRange(); | |||
5301 | else | |||
5302 | Diag(Loc, diag::err_invalid_declarator_scope) | |||
5303 | << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); | |||
5304 | ||||
5305 | return true; | |||
5306 | } | |||
5307 | ||||
5308 | if (Cur->isRecord()) { | |||
5309 | // Cannot qualify members within a class. | |||
5310 | Diag(Loc, diag::err_member_qualification) | |||
5311 | << Name << SS.getRange(); | |||
5312 | SS.clear(); | |||
5313 | ||||
5314 | // C++ constructors and destructors with incorrect scopes can break | |||
5315 | // our AST invariants by having the wrong underlying types. If | |||
5316 | // that's the case, then drop this declaration entirely. | |||
5317 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || | |||
5318 | Name.getNameKind() == DeclarationName::CXXDestructorName) && | |||
5319 | !Context.hasSameType(Name.getCXXNameType(), | |||
5320 | Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) | |||
5321 | return true; | |||
5322 | ||||
5323 | return false; | |||
5324 | } | |||
5325 | ||||
5326 | // C++11 [dcl.meaning]p1: | |||
5327 | // [...] "The nested-name-specifier of the qualified declarator-id shall | |||
5328 | // not begin with a decltype-specifer" | |||
5329 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); | |||
5330 | while (SpecLoc.getPrefix()) | |||
5331 | SpecLoc = SpecLoc.getPrefix(); | |||
5332 | if (dyn_cast_or_null<DecltypeType>( | |||
5333 | SpecLoc.getNestedNameSpecifier()->getAsType())) | |||
5334 | Diag(Loc, diag::err_decltype_in_declarator) | |||
5335 | << SpecLoc.getTypeLoc().getSourceRange(); | |||
5336 | ||||
5337 | return false; | |||
5338 | } | |||
5339 | ||||
5340 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, | |||
5341 | MultiTemplateParamsArg TemplateParamLists) { | |||
5342 | // TODO: consider using NameInfo for diagnostic. | |||
5343 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | |||
5344 | DeclarationName Name = NameInfo.getName(); | |||
5345 | ||||
5346 | // All of these full declarators require an identifier. If it doesn't have | |||
5347 | // one, the ParsedFreeStandingDeclSpec action should be used. | |||
5348 | if (D.isDecompositionDeclarator()) { | |||
5349 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); | |||
5350 | } else if (!Name) { | |||
5351 | if (!D.isInvalidType()) // Reject this if we think it is valid. | |||
5352 | Diag(D.getDeclSpec().getLocStart(), | |||
5353 | diag::err_declarator_need_ident) | |||
5354 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); | |||
5355 | return nullptr; | |||
5356 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) | |||
5357 | return nullptr; | |||
5358 | ||||
5359 | // The scope passed in may not be a decl scope. Zip up the scope tree until | |||
5360 | // we find one that is. | |||
5361 | while ((S->getFlags() & Scope::DeclScope) == 0 || | |||
5362 | (S->getFlags() & Scope::TemplateParamScope) != 0) | |||
5363 | S = S->getParent(); | |||
5364 | ||||
5365 | DeclContext *DC = CurContext; | |||
5366 | if (D.getCXXScopeSpec().isInvalid()) | |||
5367 | D.setInvalidType(); | |||
5368 | else if (D.getCXXScopeSpec().isSet()) { | |||
5369 | if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), | |||
5370 | UPPC_DeclarationQualifier)) | |||
5371 | return nullptr; | |||
5372 | ||||
5373 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); | |||
5374 | DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); | |||
5375 | if (!DC || isa<EnumDecl>(DC)) { | |||
5376 | // If we could not compute the declaration context, it's because the | |||
5377 | // declaration context is dependent but does not refer to a class, | |||
5378 | // class template, or class template partial specialization. Complain | |||
5379 | // and return early, to avoid the coming semantic disaster. | |||
5380 | Diag(D.getIdentifierLoc(), | |||
5381 | diag::err_template_qualified_declarator_no_match) | |||
5382 | << D.getCXXScopeSpec().getScopeRep() | |||
5383 | << D.getCXXScopeSpec().getRange(); | |||
5384 | return nullptr; | |||
5385 | } | |||
5386 | bool IsDependentContext = DC->isDependentContext(); | |||
5387 | ||||
5388 | if (!IsDependentContext && | |||
5389 | RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) | |||
5390 | return nullptr; | |||
5391 | ||||
5392 | // If a class is incomplete, do not parse entities inside it. | |||
5393 | if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { | |||
5394 | Diag(D.getIdentifierLoc(), | |||
5395 | diag::err_member_def_undefined_record) | |||
5396 | << Name << DC << D.getCXXScopeSpec().getRange(); | |||
5397 | return nullptr; | |||
5398 | } | |||
5399 | if (!D.getDeclSpec().isFriendSpecified()) { | |||
5400 | if (diagnoseQualifiedDeclaration( | |||
5401 | D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), | |||
5402 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { | |||
5403 | if (DC->isRecord()) | |||
5404 | return nullptr; | |||
5405 | ||||
5406 | D.setInvalidType(); | |||
5407 | } | |||
5408 | } | |||
5409 | ||||
5410 | // Check whether we need to rebuild the type of the given | |||
5411 | // declaration in the current instantiation. | |||
5412 | if (EnteringContext && IsDependentContext && | |||
5413 | TemplateParamLists.size() != 0) { | |||
5414 | ContextRAII SavedContext(*this, DC); | |||
5415 | if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) | |||
5416 | D.setInvalidType(); | |||
5417 | } | |||
5418 | } | |||
5419 | ||||
5420 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
5421 | QualType R = TInfo->getType(); | |||
5422 | ||||
5423 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
5424 | UPPC_DeclarationType)) | |||
5425 | D.setInvalidType(); | |||
5426 | ||||
5427 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
5428 | forRedeclarationInCurContext()); | |||
5429 | ||||
5430 | // See if this is a redefinition of a variable in the same scope. | |||
5431 | if (!D.getCXXScopeSpec().isSet()) { | |||
5432 | bool IsLinkageLookup = false; | |||
5433 | bool CreateBuiltins = false; | |||
5434 | ||||
5435 | // If the declaration we're planning to build will be a function | |||
5436 | // or object with linkage, then look for another declaration with | |||
5437 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). | |||
5438 | // | |||
5439 | // If the declaration we're planning to build will be declared with | |||
5440 | // external linkage in the translation unit, create any builtin with | |||
5441 | // the same name. | |||
5442 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
5443 | /* Do nothing*/; | |||
5444 | else if (CurContext->isFunctionOrMethod() && | |||
5445 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || | |||
5446 | R->isFunctionType())) { | |||
5447 | IsLinkageLookup = true; | |||
5448 | CreateBuiltins = | |||
5449 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); | |||
5450 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && | |||
5451 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) | |||
5452 | CreateBuiltins = true; | |||
5453 | ||||
5454 | if (IsLinkageLookup) { | |||
5455 | Previous.clear(LookupRedeclarationWithLinkage); | |||
5456 | Previous.setRedeclarationKind(ForExternalRedeclaration); | |||
5457 | } | |||
5458 | ||||
5459 | LookupName(Previous, S, CreateBuiltins); | |||
5460 | } else { // Something like "int foo::x;" | |||
5461 | LookupQualifiedName(Previous, DC); | |||
5462 | ||||
5463 | // C++ [dcl.meaning]p1: | |||
5464 | // When the declarator-id is qualified, the declaration shall refer to a | |||
5465 | // previously declared member of the class or namespace to which the | |||
5466 | // qualifier refers (or, in the case of a namespace, of an element of the | |||
5467 | // inline namespace set of that namespace (7.3.1)) or to a specialization | |||
5468 | // thereof; [...] | |||
5469 | // | |||
5470 | // Note that we already checked the context above, and that we do not have | |||
5471 | // enough information to make sure that Previous contains the declaration | |||
5472 | // we want to match. For example, given: | |||
5473 | // | |||
5474 | // class X { | |||
5475 | // void f(); | |||
5476 | // void f(float); | |||
5477 | // }; | |||
5478 | // | |||
5479 | // void X::f(int) { } // ill-formed | |||
5480 | // | |||
5481 | // In this case, Previous will point to the overload set | |||
5482 | // containing the two f's declared in X, but neither of them | |||
5483 | // matches. | |||
5484 | ||||
5485 | // C++ [dcl.meaning]p1: | |||
5486 | // [...] the member shall not merely have been introduced by a | |||
5487 | // using-declaration in the scope of the class or namespace nominated by | |||
5488 | // the nested-name-specifier of the declarator-id. | |||
5489 | RemoveUsingDecls(Previous); | |||
5490 | } | |||
5491 | ||||
5492 | if (Previous.isSingleResult() && | |||
5493 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
5494 | // Maybe we will complain about the shadowed template parameter. | |||
5495 | if (!D.isInvalidType()) | |||
5496 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | |||
5497 | Previous.getFoundDecl()); | |||
5498 | ||||
5499 | // Just pretend that we didn't see the previous declaration. | |||
5500 | Previous.clear(); | |||
5501 | } | |||
5502 | ||||
5503 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) | |||
5504 | // Forget that the previous declaration is the injected-class-name. | |||
5505 | Previous.clear(); | |||
5506 | ||||
5507 | // In C++, the previous declaration we find might be a tag type | |||
5508 | // (class or enum). In this case, the new declaration will hide the | |||
5509 | // tag type. Note that this applies to functions, function templates, and | |||
5510 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. | |||
5511 | if (Previous.isSingleTagDecl() && | |||
5512 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | |||
5513 | (TemplateParamLists.size() == 0 || R->isFunctionType())) | |||
5514 | Previous.clear(); | |||
5515 | ||||
5516 | // Check that there are no default arguments other than in the parameters | |||
5517 | // of a function declaration (C++ only). | |||
5518 | if (getLangOpts().CPlusPlus) | |||
5519 | CheckExtraCXXDefaultArguments(D); | |||
5520 | ||||
5521 | NamedDecl *New; | |||
5522 | ||||
5523 | bool AddToScope = true; | |||
5524 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { | |||
5525 | if (TemplateParamLists.size()) { | |||
5526 | Diag(D.getIdentifierLoc(), diag::err_template_typedef); | |||
5527 | return nullptr; | |||
5528 | } | |||
5529 | ||||
5530 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); | |||
5531 | } else if (R->isFunctionType()) { | |||
5532 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, | |||
5533 | TemplateParamLists, | |||
5534 | AddToScope); | |||
5535 | } else { | |||
5536 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, | |||
5537 | AddToScope); | |||
5538 | } | |||
5539 | ||||
5540 | if (!New) | |||
5541 | return nullptr; | |||
5542 | ||||
5543 | // If this has an identifier and is not a function template specialization, | |||
5544 | // add it to the scope stack. | |||
5545 | if (New->getDeclName() && AddToScope) { | |||
5546 | // Only make a locally-scoped extern declaration visible if it is the first | |||
5547 | // declaration of this entity. Qualified lookup for such an entity should | |||
5548 | // only find this declaration if there is no visible declaration of it. | |||
5549 | bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); | |||
5550 | PushOnScopeChains(New, S, AddToContext); | |||
5551 | if (!AddToContext) | |||
5552 | CurContext->addHiddenDecl(New); | |||
5553 | } | |||
5554 | ||||
5555 | if (isInOpenMPDeclareTargetContext()) | |||
5556 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | |||
5557 | ||||
5558 | return New; | |||
5559 | } | |||
5560 | ||||
5561 | /// Helper method to turn variable array types into constant array | |||
5562 | /// types in certain situations which would otherwise be errors (for | |||
5563 | /// GCC compatibility). | |||
5564 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, | |||
5565 | ASTContext &Context, | |||
5566 | bool &SizeIsNegative, | |||
5567 | llvm::APSInt &Oversized) { | |||
5568 | // This method tries to turn a variable array into a constant | |||
5569 | // array even when the size isn't an ICE. This is necessary | |||
5570 | // for compatibility with code that depends on gcc's buggy | |||
5571 | // constant expression folding, like struct {char x[(int)(char*)2];} | |||
5572 | SizeIsNegative = false; | |||
5573 | Oversized = 0; | |||
5574 | ||||
5575 | if (T->isDependentType()) | |||
5576 | return QualType(); | |||
5577 | ||||
5578 | QualifierCollector Qs; | |||
5579 | const Type *Ty = Qs.strip(T); | |||
5580 | ||||
5581 | if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { | |||
5582 | QualType Pointee = PTy->getPointeeType(); | |||
5583 | QualType FixedType = | |||
5584 | TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, | |||
5585 | Oversized); | |||
5586 | if (FixedType.isNull()) return FixedType; | |||
5587 | FixedType = Context.getPointerType(FixedType); | |||
5588 | return Qs.apply(Context, FixedType); | |||
5589 | } | |||
5590 | if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { | |||
5591 | QualType Inner = PTy->getInnerType(); | |||
5592 | QualType FixedType = | |||
5593 | TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, | |||
5594 | Oversized); | |||
5595 | if (FixedType.isNull()) return FixedType; | |||
5596 | FixedType = Context.getParenType(FixedType); | |||
5597 | return Qs.apply(Context, FixedType); | |||
5598 | } | |||
5599 | ||||
5600 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); | |||
5601 | if (!VLATy) | |||
5602 | return QualType(); | |||
5603 | // FIXME: We should probably handle this case | |||
5604 | if (VLATy->getElementType()->isVariablyModifiedType()) | |||
5605 | return QualType(); | |||
5606 | ||||
5607 | llvm::APSInt Res; | |||
5608 | if (!VLATy->getSizeExpr() || | |||
5609 | !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) | |||
5610 | return QualType(); | |||
5611 | ||||
5612 | // Check whether the array size is negative. | |||
5613 | if (Res.isSigned() && Res.isNegative()) { | |||
5614 | SizeIsNegative = true; | |||
5615 | return QualType(); | |||
5616 | } | |||
5617 | ||||
5618 | // Check whether the array is too large to be addressed. | |||
5619 | unsigned ActiveSizeBits | |||
5620 | = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), | |||
5621 | Res); | |||
5622 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | |||
5623 | Oversized = Res; | |||
5624 | return QualType(); | |||
5625 | } | |||
5626 | ||||
5627 | return Context.getConstantArrayType(VLATy->getElementType(), | |||
5628 | Res, ArrayType::Normal, 0); | |||
5629 | } | |||
5630 | ||||
5631 | static void | |||
5632 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { | |||
5633 | SrcTL = SrcTL.getUnqualifiedLoc(); | |||
5634 | DstTL = DstTL.getUnqualifiedLoc(); | |||
5635 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { | |||
5636 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); | |||
5637 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), | |||
5638 | DstPTL.getPointeeLoc()); | |||
5639 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); | |||
5640 | return; | |||
5641 | } | |||
5642 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { | |||
5643 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); | |||
5644 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), | |||
5645 | DstPTL.getInnerLoc()); | |||
5646 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); | |||
5647 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); | |||
5648 | return; | |||
5649 | } | |||
5650 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); | |||
5651 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); | |||
5652 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); | |||
5653 | TypeLoc DstElemTL = DstATL.getElementLoc(); | |||
5654 | DstElemTL.initializeFullCopy(SrcElemTL); | |||
5655 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); | |||
5656 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); | |||
5657 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); | |||
5658 | } | |||
5659 | ||||
5660 | /// Helper method to turn variable array types into constant array | |||
5661 | /// types in certain situations which would otherwise be errors (for | |||
5662 | /// GCC compatibility). | |||
5663 | static TypeSourceInfo* | |||
5664 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, | |||
5665 | ASTContext &Context, | |||
5666 | bool &SizeIsNegative, | |||
5667 | llvm::APSInt &Oversized) { | |||
5668 | QualType FixedTy | |||
5669 | = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, | |||
5670 | SizeIsNegative, Oversized); | |||
5671 | if (FixedTy.isNull()) | |||
5672 | return nullptr; | |||
5673 | TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); | |||
5674 | FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), | |||
5675 | FixedTInfo->getTypeLoc()); | |||
5676 | return FixedTInfo; | |||
5677 | } | |||
5678 | ||||
5679 | /// Register the given locally-scoped extern "C" declaration so | |||
5680 | /// that it can be found later for redeclarations. We include any extern "C" | |||
5681 | /// declaration that is not visible in the translation unit here, not just | |||
5682 | /// function-scope declarations. | |||
5683 | void | |||
5684 | Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { | |||
5685 | if (!getLangOpts().CPlusPlus && | |||
5686 | ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) | |||
5687 | // Don't need to track declarations in the TU in C. | |||
5688 | return; | |||
5689 | ||||
5690 | // Note that we have a locally-scoped external with this name. | |||
5691 | Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); | |||
5692 | } | |||
5693 | ||||
5694 | NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { | |||
5695 | // FIXME: We can have multiple results via __attribute__((overloadable)). | |||
5696 | auto Result = Context.getExternCContextDecl()->lookup(Name); | |||
5697 | return Result.empty() ? nullptr : *Result.begin(); | |||
5698 | } | |||
5699 | ||||
5700 | /// Diagnose function specifiers on a declaration of an identifier that | |||
5701 | /// does not identify a function. | |||
5702 | void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { | |||
5703 | // FIXME: We should probably indicate the identifier in question to avoid | |||
5704 | // confusion for constructs like "virtual int a(), b;" | |||
5705 | if (DS.isVirtualSpecified()) | |||
5706 | Diag(DS.getVirtualSpecLoc(), | |||
5707 | diag::err_virtual_non_function); | |||
5708 | ||||
5709 | if (DS.isExplicitSpecified()) | |||
5710 | Diag(DS.getExplicitSpecLoc(), | |||
5711 | diag::err_explicit_non_function); | |||
5712 | ||||
5713 | if (DS.isNoreturnSpecified()) | |||
5714 | Diag(DS.getNoreturnSpecLoc(), | |||
5715 | diag::err_noreturn_non_function); | |||
5716 | } | |||
5717 | ||||
5718 | NamedDecl* | |||
5719 | Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, | |||
5720 | TypeSourceInfo *TInfo, LookupResult &Previous) { | |||
5721 | // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). | |||
5722 | if (D.getCXXScopeSpec().isSet()) { | |||
5723 | Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) | |||
5724 | << D.getCXXScopeSpec().getRange(); | |||
5725 | D.setInvalidType(); | |||
5726 | // Pretend we didn't see the scope specifier. | |||
5727 | DC = CurContext; | |||
5728 | Previous.clear(); | |||
5729 | } | |||
5730 | ||||
5731 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
5732 | ||||
5733 | if (D.getDeclSpec().isInlineSpecified()) | |||
5734 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
5735 | << getLangOpts().CPlusPlus17; | |||
5736 | if (D.getDeclSpec().isConstexprSpecified()) | |||
5737 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) | |||
5738 | << 1; | |||
5739 | ||||
5740 | if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { | |||
5741 | if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) | |||
5742 | Diag(D.getName().StartLocation, | |||
5743 | diag::err_deduction_guide_invalid_specifier) | |||
5744 | << "typedef"; | |||
5745 | else | |||
5746 | Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) | |||
5747 | << D.getName().getSourceRange(); | |||
5748 | return nullptr; | |||
5749 | } | |||
5750 | ||||
5751 | TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); | |||
5752 | if (!NewTD) return nullptr; | |||
5753 | ||||
5754 | // Handle attributes prior to checking for duplicates in MergeVarDecl | |||
5755 | ProcessDeclAttributes(S, NewTD, D); | |||
5756 | ||||
5757 | CheckTypedefForVariablyModifiedType(S, NewTD); | |||
5758 | ||||
5759 | bool Redeclaration = D.isRedeclaration(); | |||
5760 | NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); | |||
5761 | D.setRedeclaration(Redeclaration); | |||
5762 | return ND; | |||
5763 | } | |||
5764 | ||||
5765 | void | |||
5766 | Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { | |||
5767 | // C99 6.7.7p2: If a typedef name specifies a variably modified type | |||
5768 | // then it shall have block scope. | |||
5769 | // Note that variably modified types must be fixed before merging the decl so | |||
5770 | // that redeclarations will match. | |||
5771 | TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); | |||
5772 | QualType T = TInfo->getType(); | |||
5773 | if (T->isVariablyModifiedType()) { | |||
5774 | setFunctionHasBranchProtectedScope(); | |||
5775 | ||||
5776 | if (S->getFnParent() == nullptr) { | |||
5777 | bool SizeIsNegative; | |||
5778 | llvm::APSInt Oversized; | |||
5779 | TypeSourceInfo *FixedTInfo = | |||
5780 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | |||
5781 | SizeIsNegative, | |||
5782 | Oversized); | |||
5783 | if (FixedTInfo) { | |||
5784 | Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); | |||
5785 | NewTD->setTypeSourceInfo(FixedTInfo); | |||
5786 | } else { | |||
5787 | if (SizeIsNegative) | |||
5788 | Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); | |||
5789 | else if (T->isVariableArrayType()) | |||
5790 | Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); | |||
5791 | else if (Oversized.getBoolValue()) | |||
5792 | Diag(NewTD->getLocation(), diag::err_array_too_large) | |||
5793 | << Oversized.toString(10); | |||
5794 | else | |||
5795 | Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); | |||
5796 | NewTD->setInvalidDecl(); | |||
5797 | } | |||
5798 | } | |||
5799 | } | |||
5800 | } | |||
5801 | ||||
5802 | /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which | |||
5803 | /// declares a typedef-name, either using the 'typedef' type specifier or via | |||
5804 | /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. | |||
5805 | NamedDecl* | |||
5806 | Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, | |||
5807 | LookupResult &Previous, bool &Redeclaration) { | |||
5808 | ||||
5809 | // Find the shadowed declaration before filtering for scope. | |||
5810 | NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); | |||
5811 | ||||
5812 | // Merge the decl with the existing one if appropriate. If the decl is | |||
5813 | // in an outer scope, it isn't the same thing. | |||
5814 | FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, | |||
5815 | /*AllowInlineNamespace*/false); | |||
5816 | filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); | |||
5817 | if (!Previous.empty()) { | |||
5818 | Redeclaration = true; | |||
5819 | MergeTypedefNameDecl(S, NewTD, Previous); | |||
5820 | } | |||
5821 | ||||
5822 | if (ShadowedDecl && !Redeclaration) | |||
5823 | CheckShadow(NewTD, ShadowedDecl, Previous); | |||
5824 | ||||
5825 | // If this is the C FILE type, notify the AST context. | |||
5826 | if (IdentifierInfo *II = NewTD->getIdentifier()) | |||
5827 | if (!NewTD->isInvalidDecl() && | |||
5828 | NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | |||
5829 | if (II->isStr("FILE")) | |||
5830 | Context.setFILEDecl(NewTD); | |||
5831 | else if (II->isStr("jmp_buf")) | |||
5832 | Context.setjmp_bufDecl(NewTD); | |||
5833 | else if (II->isStr("sigjmp_buf")) | |||
5834 | Context.setsigjmp_bufDecl(NewTD); | |||
5835 | else if (II->isStr("ucontext_t")) | |||
5836 | Context.setucontext_tDecl(NewTD); | |||
5837 | } | |||
5838 | ||||
5839 | return NewTD; | |||
5840 | } | |||
5841 | ||||
5842 | /// Determines whether the given declaration is an out-of-scope | |||
5843 | /// previous declaration. | |||
5844 | /// | |||
5845 | /// This routine should be invoked when name lookup has found a | |||
5846 | /// previous declaration (PrevDecl) that is not in the scope where a | |||
5847 | /// new declaration by the same name is being introduced. If the new | |||
5848 | /// declaration occurs in a local scope, previous declarations with | |||
5849 | /// linkage may still be considered previous declarations (C99 | |||
5850 | /// 6.2.2p4-5, C++ [basic.link]p6). | |||
5851 | /// | |||
5852 | /// \param PrevDecl the previous declaration found by name | |||
5853 | /// lookup | |||
5854 | /// | |||
5855 | /// \param DC the context in which the new declaration is being | |||
5856 | /// declared. | |||
5857 | /// | |||
5858 | /// \returns true if PrevDecl is an out-of-scope previous declaration | |||
5859 | /// for a new delcaration with the same name. | |||
5860 | static bool | |||
5861 | isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, | |||
5862 | ASTContext &Context) { | |||
5863 | if (!PrevDecl) | |||
5864 | return false; | |||
5865 | ||||
5866 | if (!PrevDecl->hasLinkage()) | |||
5867 | return false; | |||
5868 | ||||
5869 | if (Context.getLangOpts().CPlusPlus) { | |||
5870 | // C++ [basic.link]p6: | |||
5871 | // If there is a visible declaration of an entity with linkage | |||
5872 | // having the same name and type, ignoring entities declared | |||
5873 | // outside the innermost enclosing namespace scope, the block | |||
5874 | // scope declaration declares that same entity and receives the | |||
5875 | // linkage of the previous declaration. | |||
5876 | DeclContext *OuterContext = DC->getRedeclContext(); | |||
5877 | if (!OuterContext->isFunctionOrMethod()) | |||
5878 | // This rule only applies to block-scope declarations. | |||
5879 | return false; | |||
5880 | ||||
5881 | DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); | |||
5882 | if (PrevOuterContext->isRecord()) | |||
5883 | // We found a member function: ignore it. | |||
5884 | return false; | |||
5885 | ||||
5886 | // Find the innermost enclosing namespace for the new and | |||
5887 | // previous declarations. | |||
5888 | OuterContext = OuterContext->getEnclosingNamespaceContext(); | |||
5889 | PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); | |||
5890 | ||||
5891 | // The previous declaration is in a different namespace, so it | |||
5892 | // isn't the same function. | |||
5893 | if (!OuterContext->Equals(PrevOuterContext)) | |||
5894 | return false; | |||
5895 | } | |||
5896 | ||||
5897 | return true; | |||
5898 | } | |||
5899 | ||||
5900 | static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { | |||
5901 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | |||
5902 | if (!SS.isSet()) return; | |||
5903 | DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); | |||
5904 | } | |||
5905 | ||||
5906 | bool Sema::inferObjCARCLifetime(ValueDecl *decl) { | |||
5907 | QualType type = decl->getType(); | |||
5908 | Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); | |||
5909 | if (lifetime == Qualifiers::OCL_Autoreleasing) { | |||
5910 | // Various kinds of declaration aren't allowed to be __autoreleasing. | |||
5911 | unsigned kind = -1U; | |||
5912 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | |||
5913 | if (var->hasAttr<BlocksAttr>()) | |||
5914 | kind = 0; // __block | |||
5915 | else if (!var->hasLocalStorage()) | |||
5916 | kind = 1; // global | |||
5917 | } else if (isa<ObjCIvarDecl>(decl)) { | |||
5918 | kind = 3; // ivar | |||
5919 | } else if (isa<FieldDecl>(decl)) { | |||
5920 | kind = 2; // field | |||
5921 | } | |||
5922 | ||||
5923 | if (kind != -1U) { | |||
5924 | Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) | |||
5925 | << kind; | |||
5926 | } | |||
5927 | } else if (lifetime == Qualifiers::OCL_None) { | |||
5928 | // Try to infer lifetime. | |||
5929 | if (!type->isObjCLifetimeType()) | |||
5930 | return false; | |||
5931 | ||||
5932 | lifetime = type->getObjCARCImplicitLifetime(); | |||
5933 | type = Context.getLifetimeQualifiedType(type, lifetime); | |||
5934 | decl->setType(type); | |||
5935 | } | |||
5936 | ||||
5937 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | |||
5938 | // Thread-local variables cannot have lifetime. | |||
5939 | if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && | |||
5940 | var->getTLSKind()) { | |||
5941 | Diag(var->getLocation(), diag::err_arc_thread_ownership) | |||
5942 | << var->getType(); | |||
5943 | return true; | |||
5944 | } | |||
5945 | } | |||
5946 | ||||
5947 | return false; | |||
5948 | } | |||
5949 | ||||
5950 | static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { | |||
5951 | // Ensure that an auto decl is deduced otherwise the checks below might cache | |||
5952 | // the wrong linkage. | |||
5953 | assert(S.ParsingInitForAutoVars.count(&ND) == 0)(static_cast <bool> (S.ParsingInitForAutoVars.count(& ND) == 0) ? void (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 5953, __extension__ __PRETTY_FUNCTION__)); | |||
5954 | ||||
5955 | // 'weak' only applies to declarations with external linkage. | |||
5956 | if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { | |||
5957 | if (!ND.isExternallyVisible()) { | |||
5958 | S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); | |||
5959 | ND.dropAttr<WeakAttr>(); | |||
5960 | } | |||
5961 | } | |||
5962 | if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { | |||
5963 | if (ND.isExternallyVisible()) { | |||
5964 | S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); | |||
5965 | ND.dropAttr<WeakRefAttr>(); | |||
5966 | ND.dropAttr<AliasAttr>(); | |||
5967 | } | |||
5968 | } | |||
5969 | ||||
5970 | if (auto *VD = dyn_cast<VarDecl>(&ND)) { | |||
5971 | if (VD->hasInit()) { | |||
5972 | if (const auto *Attr = VD->getAttr<AliasAttr>()) { | |||
5973 | assert(VD->isThisDeclarationADefinition() &&(static_cast <bool> (VD->isThisDeclarationADefinition () && !VD->isExternallyVisible() && "Broken AliasAttr handled late!" ) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 5974, __extension__ __PRETTY_FUNCTION__)) | |||
5974 | !VD->isExternallyVisible() && "Broken AliasAttr handled late!")(static_cast <bool> (VD->isThisDeclarationADefinition () && !VD->isExternallyVisible() && "Broken AliasAttr handled late!" ) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 5974, __extension__ __PRETTY_FUNCTION__)); | |||
5975 | S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; | |||
5976 | VD->dropAttr<AliasAttr>(); | |||
5977 | } | |||
5978 | } | |||
5979 | } | |||
5980 | ||||
5981 | // 'selectany' only applies to externally visible variable declarations. | |||
5982 | // It does not apply to functions. | |||
5983 | if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { | |||
5984 | if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { | |||
5985 | S.Diag(Attr->getLocation(), | |||
5986 | diag::err_attribute_selectany_non_extern_data); | |||
5987 | ND.dropAttr<SelectAnyAttr>(); | |||
5988 | } | |||
5989 | } | |||
5990 | ||||
5991 | if (const InheritableAttr *Attr = getDLLAttr(&ND)) { | |||
5992 | // dll attributes require external linkage. Static locals may have external | |||
5993 | // linkage but still cannot be explicitly imported or exported. | |||
5994 | auto *VD = dyn_cast<VarDecl>(&ND); | |||
5995 | if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { | |||
5996 | S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) | |||
5997 | << &ND << Attr; | |||
5998 | ND.setInvalidDecl(); | |||
5999 | } | |||
6000 | } | |||
6001 | ||||
6002 | // Virtual functions cannot be marked as 'notail'. | |||
6003 | if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) | |||
6004 | if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) | |||
6005 | if (MD->isVirtual()) { | |||
6006 | S.Diag(ND.getLocation(), | |||
6007 | diag::err_invalid_attribute_on_virtual_function) | |||
6008 | << Attr; | |||
6009 | ND.dropAttr<NotTailCalledAttr>(); | |||
6010 | } | |||
6011 | } | |||
6012 | ||||
6013 | static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, | |||
6014 | NamedDecl *NewDecl, | |||
6015 | bool IsSpecialization, | |||
6016 | bool IsDefinition) { | |||
6017 | if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) | |||
6018 | return; | |||
6019 | ||||
6020 | bool IsTemplate = false; | |||
6021 | if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { | |||
6022 | OldDecl = OldTD->getTemplatedDecl(); | |||
6023 | IsTemplate = true; | |||
6024 | if (!IsSpecialization) | |||
6025 | IsDefinition = false; | |||
6026 | } | |||
6027 | if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { | |||
6028 | NewDecl = NewTD->getTemplatedDecl(); | |||
6029 | IsTemplate = true; | |||
6030 | } | |||
6031 | ||||
6032 | if (!OldDecl || !NewDecl) | |||
6033 | return; | |||
6034 | ||||
6035 | const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); | |||
6036 | const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); | |||
6037 | const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); | |||
6038 | const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); | |||
6039 | ||||
6040 | // dllimport and dllexport are inheritable attributes so we have to exclude | |||
6041 | // inherited attribute instances. | |||
6042 | bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || | |||
6043 | (NewExportAttr && !NewExportAttr->isInherited()); | |||
6044 | ||||
6045 | // A redeclaration is not allowed to add a dllimport or dllexport attribute, | |||
6046 | // the only exception being explicit specializations. | |||
6047 | // Implicitly generated declarations are also excluded for now because there | |||
6048 | // is no other way to switch these to use dllimport or dllexport. | |||
6049 | bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; | |||
6050 | ||||
6051 | if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { | |||
6052 | // Allow with a warning for free functions and global variables. | |||
6053 | bool JustWarn = false; | |||
6054 | if (!OldDecl->isCXXClassMember()) { | |||
6055 | auto *VD = dyn_cast<VarDecl>(OldDecl); | |||
6056 | if (VD && !VD->getDescribedVarTemplate()) | |||
6057 | JustWarn = true; | |||
6058 | auto *FD = dyn_cast<FunctionDecl>(OldDecl); | |||
6059 | if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) | |||
6060 | JustWarn = true; | |||
6061 | } | |||
6062 | ||||
6063 | // We cannot change a declaration that's been used because IR has already | |||
6064 | // been emitted. Dllimported functions will still work though (modulo | |||
6065 | // address equality) as they can use the thunk. | |||
6066 | if (OldDecl->isUsed()) | |||
6067 | if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) | |||
6068 | JustWarn = false; | |||
6069 | ||||
6070 | unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration | |||
6071 | : diag::err_attribute_dll_redeclaration; | |||
6072 | S.Diag(NewDecl->getLocation(), DiagID) | |||
6073 | << NewDecl | |||
6074 | << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); | |||
6075 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | |||
6076 | if (!JustWarn) { | |||
6077 | NewDecl->setInvalidDecl(); | |||
6078 | return; | |||
6079 | } | |||
6080 | } | |||
6081 | ||||
6082 | // A redeclaration is not allowed to drop a dllimport attribute, the only | |||
6083 | // exceptions being inline function definitions (except for function | |||
6084 | // templates), local extern declarations, qualified friend declarations or | |||
6085 | // special MSVC extension: in the last case, the declaration is treated as if | |||
6086 | // it were marked dllexport. | |||
6087 | bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; | |||
6088 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | |||
6089 | if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { | |||
6090 | // Ignore static data because out-of-line definitions are diagnosed | |||
6091 | // separately. | |||
6092 | IsStaticDataMember = VD->isStaticDataMember(); | |||
6093 | IsDefinition = VD->isThisDeclarationADefinition(S.Context) != | |||
6094 | VarDecl::DeclarationOnly; | |||
6095 | } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { | |||
6096 | IsInline = FD->isInlined(); | |||
6097 | IsQualifiedFriend = FD->getQualifier() && | |||
6098 | FD->getFriendObjectKind() == Decl::FOK_Declared; | |||
6099 | } | |||
6100 | ||||
6101 | if (OldImportAttr && !HasNewAttr && | |||
6102 | (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && | |||
6103 | !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { | |||
6104 | if (IsMicrosoft && IsDefinition) { | |||
6105 | S.Diag(NewDecl->getLocation(), | |||
6106 | diag::warn_redeclaration_without_import_attribute) | |||
6107 | << NewDecl; | |||
6108 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | |||
6109 | NewDecl->dropAttr<DLLImportAttr>(); | |||
6110 | NewDecl->addAttr(::new (S.Context) DLLExportAttr( | |||
6111 | NewImportAttr->getRange(), S.Context, | |||
6112 | NewImportAttr->getSpellingListIndex())); | |||
6113 | } else { | |||
6114 | S.Diag(NewDecl->getLocation(), | |||
6115 | diag::warn_redeclaration_without_attribute_prev_attribute_ignored) | |||
6116 | << NewDecl << OldImportAttr; | |||
6117 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | |||
6118 | S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); | |||
6119 | OldDecl->dropAttr<DLLImportAttr>(); | |||
6120 | NewDecl->dropAttr<DLLImportAttr>(); | |||
6121 | } | |||
6122 | } else if (IsInline && OldImportAttr && !IsMicrosoft) { | |||
6123 | // In MinGW, seeing a function declared inline drops the dllimport | |||
6124 | // attribute. | |||
6125 | OldDecl->dropAttr<DLLImportAttr>(); | |||
6126 | NewDecl->dropAttr<DLLImportAttr>(); | |||
6127 | S.Diag(NewDecl->getLocation(), | |||
6128 | diag::warn_dllimport_dropped_from_inline_function) | |||
6129 | << NewDecl << OldImportAttr; | |||
6130 | } | |||
6131 | ||||
6132 | // A specialization of a class template member function is processed here | |||
6133 | // since it's a redeclaration. If the parent class is dllexport, the | |||
6134 | // specialization inherits that attribute. This doesn't happen automatically | |||
6135 | // since the parent class isn't instantiated until later. | |||
6136 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { | |||
6137 | if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && | |||
6138 | !NewImportAttr && !NewExportAttr) { | |||
6139 | if (const DLLExportAttr *ParentExportAttr = | |||
6140 | MD->getParent()->getAttr<DLLExportAttr>()) { | |||
6141 | DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); | |||
6142 | NewAttr->setInherited(true); | |||
6143 | NewDecl->addAttr(NewAttr); | |||
6144 | } | |||
6145 | } | |||
6146 | } | |||
6147 | } | |||
6148 | ||||
6149 | /// Given that we are within the definition of the given function, | |||
6150 | /// will that definition behave like C99's 'inline', where the | |||
6151 | /// definition is discarded except for optimization purposes? | |||
6152 | static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { | |||
6153 | // Try to avoid calling GetGVALinkageForFunction. | |||
6154 | ||||
6155 | // All cases of this require the 'inline' keyword. | |||
6156 | if (!FD->isInlined()) return false; | |||
6157 | ||||
6158 | // This is only possible in C++ with the gnu_inline attribute. | |||
6159 | if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) | |||
6160 | return false; | |||
6161 | ||||
6162 | // Okay, go ahead and call the relatively-more-expensive function. | |||
6163 | return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; | |||
6164 | } | |||
6165 | ||||
6166 | /// Determine whether a variable is extern "C" prior to attaching | |||
6167 | /// an initializer. We can't just call isExternC() here, because that | |||
6168 | /// will also compute and cache whether the declaration is externally | |||
6169 | /// visible, which might change when we attach the initializer. | |||
6170 | /// | |||
6171 | /// This can only be used if the declaration is known to not be a | |||
6172 | /// redeclaration of an internal linkage declaration. | |||
6173 | /// | |||
6174 | /// For instance: | |||
6175 | /// | |||
6176 | /// auto x = []{}; | |||
6177 | /// | |||
6178 | /// Attaching the initializer here makes this declaration not externally | |||
6179 | /// visible, because its type has internal linkage. | |||
6180 | /// | |||
6181 | /// FIXME: This is a hack. | |||
6182 | template<typename T> | |||
6183 | static bool isIncompleteDeclExternC(Sema &S, const T *D) { | |||
6184 | if (S.getLangOpts().CPlusPlus) { | |||
6185 | // In C++, the overloadable attribute negates the effects of extern "C". | |||
6186 | if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) | |||
6187 | return false; | |||
6188 | ||||
6189 | // So do CUDA's host/device attributes. | |||
6190 | if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || | |||
6191 | D->template hasAttr<CUDAHostAttr>())) | |||
6192 | return false; | |||
6193 | } | |||
6194 | return D->isExternC(); | |||
6195 | } | |||
6196 | ||||
6197 | static bool shouldConsiderLinkage(const VarDecl *VD) { | |||
6198 | const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); | |||
6199 | if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) | |||
6200 | return VD->hasExternalStorage(); | |||
6201 | if (DC->isFileContext()) | |||
6202 | return true; | |||
6203 | if (DC->isRecord()) | |||
6204 | return false; | |||
6205 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 6205); | |||
6206 | } | |||
6207 | ||||
6208 | static bool shouldConsiderLinkage(const FunctionDecl *FD) { | |||
6209 | const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); | |||
6210 | if (DC->isFileContext() || DC->isFunctionOrMethod() || | |||
6211 | isa<OMPDeclareReductionDecl>(DC)) | |||
6212 | return true; | |||
6213 | if (DC->isRecord()) | |||
6214 | return false; | |||
6215 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 6215); | |||
6216 | } | |||
6217 | ||||
6218 | static bool hasParsedAttr(Scope *S, const Declarator &PD, | |||
6219 | ParsedAttr::Kind Kind) { | |||
6220 | // Check decl attributes on the DeclSpec. | |||
6221 | if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) | |||
6222 | return true; | |||
6223 | ||||
6224 | // Walk the declarator structure, checking decl attributes that were in a type | |||
6225 | // position to the decl itself. | |||
6226 | for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { | |||
6227 | if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) | |||
6228 | return true; | |||
6229 | } | |||
6230 | ||||
6231 | // Finally, check attributes on the decl itself. | |||
6232 | return PD.getAttributes().hasAttribute(Kind); | |||
6233 | } | |||
6234 | ||||
6235 | /// Adjust the \c DeclContext for a function or variable that might be a | |||
6236 | /// function-local external declaration. | |||
6237 | bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { | |||
6238 | if (!DC->isFunctionOrMethod()) | |||
6239 | return false; | |||
6240 | ||||
6241 | // If this is a local extern function or variable declared within a function | |||
6242 | // template, don't add it into the enclosing namespace scope until it is | |||
6243 | // instantiated; it might have a dependent type right now. | |||
6244 | if (DC->isDependentContext()) | |||
6245 | return true; | |||
6246 | ||||
6247 | // C++11 [basic.link]p7: | |||
6248 | // When a block scope declaration of an entity with linkage is not found to | |||
6249 | // refer to some other declaration, then that entity is a member of the | |||
6250 | // innermost enclosing namespace. | |||
6251 | // | |||
6252 | // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a | |||
6253 | // semantically-enclosing namespace, not a lexically-enclosing one. | |||
6254 | while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) | |||
6255 | DC = DC->getParent(); | |||
6256 | return true; | |||
6257 | } | |||
6258 | ||||
6259 | /// Returns true if given declaration has external C language linkage. | |||
6260 | static bool isDeclExternC(const Decl *D) { | |||
6261 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) | |||
6262 | return FD->isExternC(); | |||
6263 | if (const auto *VD = dyn_cast<VarDecl>(D)) | |||
6264 | return VD->isExternC(); | |||
6265 | ||||
6266 | llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 6266); | |||
6267 | } | |||
6268 | ||||
6269 | NamedDecl *Sema::ActOnVariableDeclarator( | |||
6270 | Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, | |||
6271 | LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, | |||
6272 | bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { | |||
6273 | QualType R = TInfo->getType(); | |||
6274 | DeclarationName Name = GetNameForDeclarator(D).getName(); | |||
6275 | ||||
6276 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
6277 | ||||
6278 | if (D.isDecompositionDeclarator()) { | |||
6279 | // Take the name of the first declarator as our name for diagnostic | |||
6280 | // purposes. | |||
6281 | auto &Decomp = D.getDecompositionDeclarator(); | |||
6282 | if (!Decomp.bindings().empty()) { | |||
6283 | II = Decomp.bindings()[0].Name; | |||
6284 | Name = II; | |||
6285 | } | |||
6286 | } else if (!II) { | |||
6287 | Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; | |||
6288 | return nullptr; | |||
6289 | } | |||
6290 | ||||
6291 | if (getLangOpts().OpenCL) { | |||
6292 | // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. | |||
6293 | // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function | |||
6294 | // argument. | |||
6295 | if (R->isImageType() || R->isPipeType()) { | |||
6296 | Diag(D.getIdentifierLoc(), | |||
6297 | diag::err_opencl_type_can_only_be_used_as_function_parameter) | |||
6298 | << R; | |||
6299 | D.setInvalidType(); | |||
6300 | return nullptr; | |||
6301 | } | |||
6302 | ||||
6303 | // OpenCL v1.2 s6.9.r: | |||
6304 | // The event type cannot be used to declare a program scope variable. | |||
6305 | // OpenCL v2.0 s6.9.q: | |||
6306 | // The clk_event_t and reserve_id_t types cannot be declared in program scope. | |||
6307 | if (NULL__null == S->getParent()) { | |||
6308 | if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { | |||
6309 | Diag(D.getIdentifierLoc(), | |||
6310 | diag::err_invalid_type_for_program_scope_var) << R; | |||
6311 | D.setInvalidType(); | |||
6312 | return nullptr; | |||
6313 | } | |||
6314 | } | |||
6315 | ||||
6316 | // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. | |||
6317 | QualType NR = R; | |||
6318 | while (NR->isPointerType()) { | |||
6319 | if (NR->isFunctionPointerType()) { | |||
6320 | Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); | |||
6321 | D.setInvalidType(); | |||
6322 | break; | |||
6323 | } | |||
6324 | NR = NR->getPointeeType(); | |||
6325 | } | |||
6326 | ||||
6327 | if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { | |||
6328 | // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and | |||
6329 | // half array type (unless the cl_khr_fp16 extension is enabled). | |||
6330 | if (Context.getBaseElementType(R)->isHalfType()) { | |||
6331 | Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; | |||
6332 | D.setInvalidType(); | |||
6333 | } | |||
6334 | } | |||
6335 | ||||
6336 | if (R->isSamplerT()) { | |||
6337 | // OpenCL v1.2 s6.9.b p4: | |||
6338 | // The sampler type cannot be used with the __local and __global address | |||
6339 | // space qualifiers. | |||
6340 | if (R.getAddressSpace() == LangAS::opencl_local || | |||
6341 | R.getAddressSpace() == LangAS::opencl_global) { | |||
6342 | Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); | |||
6343 | } | |||
6344 | ||||
6345 | // OpenCL v1.2 s6.12.14.1: | |||
6346 | // A global sampler must be declared with either the constant address | |||
6347 | // space qualifier or with the const qualifier. | |||
6348 | if (DC->isTranslationUnit() && | |||
6349 | !(R.getAddressSpace() == LangAS::opencl_constant || | |||
6350 | R.isConstQualified())) { | |||
6351 | Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); | |||
6352 | D.setInvalidType(); | |||
6353 | } | |||
6354 | } | |||
6355 | ||||
6356 | // OpenCL v1.2 s6.9.r: | |||
6357 | // The event type cannot be used with the __local, __constant and __global | |||
6358 | // address space qualifiers. | |||
6359 | if (R->isEventT()) { | |||
6360 | if (R.getAddressSpace() != LangAS::opencl_private) { | |||
6361 | Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); | |||
6362 | D.setInvalidType(); | |||
6363 | } | |||
6364 | } | |||
6365 | ||||
6366 | // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not | |||
6367 | // supported. OpenCL C does not support thread_local either, and | |||
6368 | // also reject all other thread storage class specifiers. | |||
6369 | DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); | |||
6370 | if (TSC != TSCS_unspecified) { | |||
6371 | bool IsCXX = getLangOpts().OpenCLCPlusPlus; | |||
6372 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
6373 | diag::err_opencl_unknown_type_specifier) | |||
6374 | << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() | |||
6375 | << DeclSpec::getSpecifierName(TSC) << 1; | |||
6376 | D.setInvalidType(); | |||
6377 | return nullptr; | |||
6378 | } | |||
6379 | } | |||
6380 | ||||
6381 | DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); | |||
6382 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); | |||
6383 | ||||
6384 | // dllimport globals without explicit storage class are treated as extern. We | |||
6385 | // have to change the storage class this early to get the right DeclContext. | |||
6386 | if (SC == SC_None && !DC->isRecord() && | |||
6387 | hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && | |||
6388 | !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) | |||
6389 | SC = SC_Extern; | |||
6390 | ||||
6391 | DeclContext *OriginalDC = DC; | |||
6392 | bool IsLocalExternDecl = SC == SC_Extern && | |||
6393 | adjustContextForLocalExternDecl(DC); | |||
6394 | ||||
6395 | if (SCSpec == DeclSpec::SCS_mutable) { | |||
6396 | // mutable can only appear on non-static class members, so it's always | |||
6397 | // an error here | |||
6398 | Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); | |||
6399 | D.setInvalidType(); | |||
6400 | SC = SC_None; | |||
6401 | } | |||
6402 | ||||
6403 | if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && | |||
6404 | !D.getAsmLabel() && !getSourceManager().isInSystemMacro( | |||
6405 | D.getDeclSpec().getStorageClassSpecLoc())) { | |||
6406 | // In C++11, the 'register' storage class specifier is deprecated. | |||
6407 | // Suppress the warning in system macros, it's used in macros in some | |||
6408 | // popular C system headers, such as in glibc's htonl() macro. | |||
6409 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
6410 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | |||
6411 | : diag::warn_deprecated_register) | |||
6412 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
6413 | } | |||
6414 | ||||
6415 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
6416 | ||||
6417 | if (!DC->isRecord() && S->getFnParent() == nullptr) { | |||
6418 | // C99 6.9p2: The storage-class specifiers auto and register shall not | |||
6419 | // appear in the declaration specifiers in an external declaration. | |||
6420 | // Global Register+Asm is a GNU extension we support. | |||
6421 | if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { | |||
6422 | Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); | |||
6423 | D.setInvalidType(); | |||
6424 | } | |||
6425 | } | |||
6426 | ||||
6427 | bool IsMemberSpecialization = false; | |||
6428 | bool IsVariableTemplateSpecialization = false; | |||
6429 | bool IsPartialSpecialization = false; | |||
6430 | bool IsVariableTemplate = false; | |||
6431 | VarDecl *NewVD = nullptr; | |||
6432 | VarTemplateDecl *NewTemplate = nullptr; | |||
6433 | TemplateParameterList *TemplateParams = nullptr; | |||
6434 | if (!getLangOpts().CPlusPlus) { | |||
6435 | NewVD = VarDecl::Create(Context, DC, D.getLocStart(), | |||
6436 | D.getIdentifierLoc(), II, | |||
6437 | R, TInfo, SC); | |||
6438 | ||||
6439 | if (R->getContainedDeducedType()) | |||
6440 | ParsingInitForAutoVars.insert(NewVD); | |||
6441 | ||||
6442 | if (D.isInvalidType()) | |||
6443 | NewVD->setInvalidDecl(); | |||
6444 | } else { | |||
6445 | bool Invalid = false; | |||
6446 | ||||
6447 | if (DC->isRecord() && !CurContext->isRecord()) { | |||
6448 | // This is an out-of-line definition of a static data member. | |||
6449 | switch (SC) { | |||
6450 | case SC_None: | |||
6451 | break; | |||
6452 | case SC_Static: | |||
6453 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
6454 | diag::err_static_out_of_line) | |||
6455 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
6456 | break; | |||
6457 | case SC_Auto: | |||
6458 | case SC_Register: | |||
6459 | case SC_Extern: | |||
6460 | // [dcl.stc] p2: The auto or register specifiers shall be applied only | |||
6461 | // to names of variables declared in a block or to function parameters. | |||
6462 | // [dcl.stc] p6: The extern specifier cannot be used in the declaration | |||
6463 | // of class members | |||
6464 | ||||
6465 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
6466 | diag::err_storage_class_for_static_member) | |||
6467 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
6468 | break; | |||
6469 | case SC_PrivateExtern: | |||
6470 | llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 6470); | |||
6471 | } | |||
6472 | } | |||
6473 | ||||
6474 | if (SC == SC_Static && CurContext->isRecord()) { | |||
6475 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { | |||
6476 | if (RD->isLocalClass()) | |||
6477 | Diag(D.getIdentifierLoc(), | |||
6478 | diag::err_static_data_member_not_allowed_in_local_class) | |||
6479 | << Name << RD->getDeclName(); | |||
6480 | ||||
6481 | // C++98 [class.union]p1: If a union contains a static data member, | |||
6482 | // the program is ill-formed. C++11 drops this restriction. | |||
6483 | if (RD->isUnion()) | |||
6484 | Diag(D.getIdentifierLoc(), | |||
6485 | getLangOpts().CPlusPlus11 | |||
6486 | ? diag::warn_cxx98_compat_static_data_member_in_union | |||
6487 | : diag::ext_static_data_member_in_union) << Name; | |||
6488 | // We conservatively disallow static data members in anonymous structs. | |||
6489 | else if (!RD->getDeclName()) | |||
6490 | Diag(D.getIdentifierLoc(), | |||
6491 | diag::err_static_data_member_not_allowed_in_anon_struct) | |||
6492 | << Name << RD->isUnion(); | |||
6493 | } | |||
6494 | } | |||
6495 | ||||
6496 | // Match up the template parameter lists with the scope specifier, then | |||
6497 | // determine whether we have a template or a template specialization. | |||
6498 | TemplateParams = MatchTemplateParametersToScopeSpecifier( | |||
6499 | D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), | |||
6500 | D.getCXXScopeSpec(), | |||
6501 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | |||
6502 | ? D.getName().TemplateId | |||
6503 | : nullptr, | |||
6504 | TemplateParamLists, | |||
6505 | /*never a friend*/ false, IsMemberSpecialization, Invalid); | |||
6506 | ||||
6507 | if (TemplateParams) { | |||
6508 | if (!TemplateParams->size() && | |||
6509 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | |||
6510 | // There is an extraneous 'template<>' for this variable. Complain | |||
6511 | // about it, but allow the declaration of the variable. | |||
6512 | Diag(TemplateParams->getTemplateLoc(), | |||
6513 | diag::err_template_variable_noparams) | |||
6514 | << II | |||
6515 | << SourceRange(TemplateParams->getTemplateLoc(), | |||
6516 | TemplateParams->getRAngleLoc()); | |||
6517 | TemplateParams = nullptr; | |||
6518 | } else { | |||
6519 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | |||
6520 | // This is an explicit specialization or a partial specialization. | |||
6521 | // FIXME: Check that we can declare a specialization here. | |||
6522 | IsVariableTemplateSpecialization = true; | |||
6523 | IsPartialSpecialization = TemplateParams->size() > 0; | |||
6524 | } else { // if (TemplateParams->size() > 0) | |||
6525 | // This is a template declaration. | |||
6526 | IsVariableTemplate = true; | |||
6527 | ||||
6528 | // Check that we can declare a template here. | |||
6529 | if (CheckTemplateDeclScope(S, TemplateParams)) | |||
6530 | return nullptr; | |||
6531 | ||||
6532 | // Only C++1y supports variable templates (N3651). | |||
6533 | Diag(D.getIdentifierLoc(), | |||
6534 | getLangOpts().CPlusPlus14 | |||
6535 | ? diag::warn_cxx11_compat_variable_template | |||
6536 | : diag::ext_variable_template); | |||
6537 | } | |||
6538 | } | |||
6539 | } else { | |||
6540 | assert((Invalid ||(static_cast <bool> ((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 6542, __extension__ __PRETTY_FUNCTION__)) | |||
6541 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(static_cast <bool> ((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 6542, __extension__ __PRETTY_FUNCTION__)) | |||
6542 | "should have a 'template<>' for this decl")(static_cast <bool> ((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 6542, __extension__ __PRETTY_FUNCTION__)); | |||
6543 | } | |||
6544 | ||||
6545 | if (IsVariableTemplateSpecialization) { | |||
6546 | SourceLocation TemplateKWLoc = | |||
6547 | TemplateParamLists.size() > 0 | |||
6548 | ? TemplateParamLists[0]->getTemplateLoc() | |||
6549 | : SourceLocation(); | |||
6550 | DeclResult Res = ActOnVarTemplateSpecialization( | |||
6551 | S, D, TInfo, TemplateKWLoc, TemplateParams, SC, | |||
6552 | IsPartialSpecialization); | |||
6553 | if (Res.isInvalid()) | |||
6554 | return nullptr; | |||
6555 | NewVD = cast<VarDecl>(Res.get()); | |||
6556 | AddToScope = false; | |||
6557 | } else if (D.isDecompositionDeclarator()) { | |||
6558 | NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), | |||
6559 | D.getIdentifierLoc(), R, TInfo, SC, | |||
6560 | Bindings); | |||
6561 | } else | |||
6562 | NewVD = VarDecl::Create(Context, DC, D.getLocStart(), | |||
6563 | D.getIdentifierLoc(), II, R, TInfo, SC); | |||
6564 | ||||
6565 | // If this is supposed to be a variable template, create it as such. | |||
6566 | if (IsVariableTemplate) { | |||
6567 | NewTemplate = | |||
6568 | VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, | |||
6569 | TemplateParams, NewVD); | |||
6570 | NewVD->setDescribedVarTemplate(NewTemplate); | |||
6571 | } | |||
6572 | ||||
6573 | // If this decl has an auto type in need of deduction, make a note of the | |||
6574 | // Decl so we can diagnose uses of it in its own initializer. | |||
6575 | if (R->getContainedDeducedType()) | |||
6576 | ParsingInitForAutoVars.insert(NewVD); | |||
6577 | ||||
6578 | if (D.isInvalidType() || Invalid) { | |||
6579 | NewVD->setInvalidDecl(); | |||
6580 | if (NewTemplate) | |||
6581 | NewTemplate->setInvalidDecl(); | |||
6582 | } | |||
6583 | ||||
6584 | SetNestedNameSpecifier(NewVD, D); | |||
6585 | ||||
6586 | // If we have any template parameter lists that don't directly belong to | |||
6587 | // the variable (matching the scope specifier), store them. | |||
6588 | unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; | |||
6589 | if (TemplateParamLists.size() > VDTemplateParamLists) | |||
6590 | NewVD->setTemplateParameterListsInfo( | |||
6591 | Context, TemplateParamLists.drop_back(VDTemplateParamLists)); | |||
6592 | ||||
6593 | if (D.getDeclSpec().isConstexprSpecified()) { | |||
6594 | NewVD->setConstexpr(true); | |||
6595 | // C++1z [dcl.spec.constexpr]p1: | |||
6596 | // A static data member declared with the constexpr specifier is | |||
6597 | // implicitly an inline variable. | |||
6598 | if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) | |||
6599 | NewVD->setImplicitlyInline(); | |||
6600 | } | |||
6601 | } | |||
6602 | ||||
6603 | if (D.getDeclSpec().isInlineSpecified()) { | |||
6604 | if (!getLangOpts().CPlusPlus) { | |||
6605 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
6606 | << 0; | |||
6607 | } else if (CurContext->isFunctionOrMethod()) { | |||
6608 | // 'inline' is not allowed on block scope variable declaration. | |||
6609 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
6610 | diag::err_inline_declaration_block_scope) << Name | |||
6611 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | |||
6612 | } else { | |||
6613 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
6614 | getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable | |||
6615 | : diag::ext_inline_variable); | |||
6616 | NewVD->setInlineSpecified(); | |||
6617 | } | |||
6618 | } | |||
6619 | ||||
6620 | // Set the lexical context. If the declarator has a C++ scope specifier, the | |||
6621 | // lexical context will be different from the semantic context. | |||
6622 | NewVD->setLexicalDeclContext(CurContext); | |||
6623 | if (NewTemplate) | |||
6624 | NewTemplate->setLexicalDeclContext(CurContext); | |||
6625 | ||||
6626 | if (IsLocalExternDecl) { | |||
6627 | if (D.isDecompositionDeclarator()) | |||
6628 | for (auto *B : Bindings) | |||
6629 | B->setLocalExternDecl(); | |||
6630 | else | |||
6631 | NewVD->setLocalExternDecl(); | |||
6632 | } | |||
6633 | ||||
6634 | bool EmitTLSUnsupportedError = false; | |||
6635 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { | |||
6636 | // C++11 [dcl.stc]p4: | |||
6637 | // When thread_local is applied to a variable of block scope the | |||
6638 | // storage-class-specifier static is implied if it does not appear | |||
6639 | // explicitly. | |||
6640 | // Core issue: 'static' is not implied if the variable is declared | |||
6641 | // 'extern'. | |||
6642 | if (NewVD->hasLocalStorage() && | |||
6643 | (SCSpec != DeclSpec::SCS_unspecified || | |||
6644 | TSCS != DeclSpec::TSCS_thread_local || | |||
6645 | !DC->isFunctionOrMethod())) | |||
6646 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
6647 | diag::err_thread_non_global) | |||
6648 | << DeclSpec::getSpecifierName(TSCS); | |||
6649 | else if (!Context.getTargetInfo().isTLSSupported()) { | |||
6650 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { | |||
6651 | // Postpone error emission until we've collected attributes required to | |||
6652 | // figure out whether it's a host or device variable and whether the | |||
6653 | // error should be ignored. | |||
6654 | EmitTLSUnsupportedError = true; | |||
6655 | // We still need to mark the variable as TLS so it shows up in AST with | |||
6656 | // proper storage class for other tools to use even if we're not going | |||
6657 | // to emit any code for it. | |||
6658 | NewVD->setTSCSpec(TSCS); | |||
6659 | } else | |||
6660 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
6661 | diag::err_thread_unsupported); | |||
6662 | } else | |||
6663 | NewVD->setTSCSpec(TSCS); | |||
6664 | } | |||
6665 | ||||
6666 | // C99 6.7.4p3 | |||
6667 | // An inline definition of a function with external linkage shall | |||
6668 | // not contain a definition of a modifiable object with static or | |||
6669 | // thread storage duration... | |||
6670 | // We only apply this when the function is required to be defined | |||
6671 | // elsewhere, i.e. when the function is not 'extern inline'. Note | |||
6672 | // that a local variable with thread storage duration still has to | |||
6673 | // be marked 'static'. Also note that it's possible to get these | |||
6674 | // semantics in C++ using __attribute__((gnu_inline)). | |||
6675 | if (SC == SC_Static && S->getFnParent() != nullptr && | |||
6676 | !NewVD->getType().isConstQualified()) { | |||
6677 | FunctionDecl *CurFD = getCurFunctionDecl(); | |||
6678 | if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { | |||
6679 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
6680 | diag::warn_static_local_in_extern_inline); | |||
6681 | MaybeSuggestAddingStaticToDecl(CurFD); | |||
6682 | } | |||
6683 | } | |||
6684 | ||||
6685 | if (D.getDeclSpec().isModulePrivateSpecified()) { | |||
6686 | if (IsVariableTemplateSpecialization) | |||
6687 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | |||
6688 | << (IsPartialSpecialization ? 1 : 0) | |||
6689 | << FixItHint::CreateRemoval( | |||
6690 | D.getDeclSpec().getModulePrivateSpecLoc()); | |||
6691 | else if (IsMemberSpecialization) | |||
6692 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | |||
6693 | << 2 | |||
6694 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | |||
6695 | else if (NewVD->hasLocalStorage()) | |||
6696 | Diag(NewVD->getLocation(), diag::err_module_private_local) | |||
6697 | << 0 << NewVD->getDeclName() | |||
6698 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | |||
6699 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | |||
6700 | else { | |||
6701 | NewVD->setModulePrivate(); | |||
6702 | if (NewTemplate) | |||
6703 | NewTemplate->setModulePrivate(); | |||
6704 | for (auto *B : Bindings) | |||
6705 | B->setModulePrivate(); | |||
6706 | } | |||
6707 | } | |||
6708 | ||||
6709 | // Handle attributes prior to checking for duplicates in MergeVarDecl | |||
6710 | ProcessDeclAttributes(S, NewVD, D); | |||
6711 | ||||
6712 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { | |||
6713 | if (EmitTLSUnsupportedError && | |||
6714 | ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || | |||
6715 | (getLangOpts().OpenMPIsDevice && | |||
6716 | NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) | |||
6717 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
6718 | diag::err_thread_unsupported); | |||
6719 | // CUDA B.2.5: "__shared__ and __constant__ variables have implied static | |||
6720 | // storage [duration]." | |||
6721 | if (SC == SC_None && S->getFnParent() != nullptr && | |||
6722 | (NewVD->hasAttr<CUDASharedAttr>() || | |||
6723 | NewVD->hasAttr<CUDAConstantAttr>())) { | |||
6724 | NewVD->setStorageClass(SC_Static); | |||
6725 | } | |||
6726 | } | |||
6727 | ||||
6728 | // Ensure that dllimport globals without explicit storage class are treated as | |||
6729 | // extern. The storage class is set above using parsed attributes. Now we can | |||
6730 | // check the VarDecl itself. | |||
6731 | assert(!NewVD->hasAttr<DLLImportAttr>() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr >() || NewVD->getAttr<DLLImportAttr>()->isInherited () || NewVD->isStaticDataMember() || NewVD->getStorageClass () != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 6733, __extension__ __PRETTY_FUNCTION__)) | |||
6732 | NewVD->getAttr<DLLImportAttr>()->isInherited() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr >() || NewVD->getAttr<DLLImportAttr>()->isInherited () || NewVD->isStaticDataMember() || NewVD->getStorageClass () != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 6733, __extension__ __PRETTY_FUNCTION__)) | |||
6733 | NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr >() || NewVD->getAttr<DLLImportAttr>()->isInherited () || NewVD->isStaticDataMember() || NewVD->getStorageClass () != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 6733, __extension__ __PRETTY_FUNCTION__)); | |||
6734 | ||||
6735 | // In auto-retain/release, infer strong retension for variables of | |||
6736 | // retainable type. | |||
6737 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) | |||
6738 | NewVD->setInvalidDecl(); | |||
6739 | ||||
6740 | // Handle GNU asm-label extension (encoded as an attribute). | |||
6741 | if (Expr *E = (Expr*)D.getAsmLabel()) { | |||
6742 | // The parser guarantees this is a string. | |||
6743 | StringLiteral *SE = cast<StringLiteral>(E); | |||
6744 | StringRef Label = SE->getString(); | |||
6745 | if (S->getFnParent() != nullptr) { | |||
6746 | switch (SC) { | |||
6747 | case SC_None: | |||
6748 | case SC_Auto: | |||
6749 | Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; | |||
6750 | break; | |||
6751 | case SC_Register: | |||
6752 | // Local Named register | |||
6753 | if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && | |||
6754 | DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) | |||
6755 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | |||
6756 | break; | |||
6757 | case SC_Static: | |||
6758 | case SC_Extern: | |||
6759 | case SC_PrivateExtern: | |||
6760 | break; | |||
6761 | } | |||
6762 | } else if (SC == SC_Register) { | |||
6763 | // Global Named register | |||
6764 | if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { | |||
6765 | const auto &TI = Context.getTargetInfo(); | |||
6766 | bool HasSizeMismatch; | |||
6767 | ||||
6768 | if (!TI.isValidGCCRegisterName(Label)) | |||
6769 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | |||
6770 | else if (!TI.validateGlobalRegisterVariable(Label, | |||
6771 | Context.getTypeSize(R), | |||
6772 | HasSizeMismatch)) | |||
6773 | Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; | |||
6774 | else if (HasSizeMismatch) | |||
6775 | Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; | |||
6776 | } | |||
6777 | ||||
6778 | if (!R->isIntegralType(Context) && !R->isPointerType()) { | |||
6779 | Diag(D.getLocStart(), diag::err_asm_bad_register_type); | |||
6780 | NewVD->setInvalidDecl(true); | |||
6781 | } | |||
6782 | } | |||
6783 | ||||
6784 | NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), | |||
6785 | Context, Label, 0)); | |||
6786 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | |||
6787 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | |||
6788 | ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); | |||
6789 | if (I != ExtnameUndeclaredIdentifiers.end()) { | |||
6790 | if (isDeclExternC(NewVD)) { | |||
6791 | NewVD->addAttr(I->second); | |||
6792 | ExtnameUndeclaredIdentifiers.erase(I); | |||
6793 | } else | |||
6794 | Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) | |||
6795 | << /*Variable*/1 << NewVD; | |||
6796 | } | |||
6797 | } | |||
6798 | ||||
6799 | // Find the shadowed declaration before filtering for scope. | |||
6800 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() | |||
6801 | ? getShadowedDeclaration(NewVD, Previous) | |||
6802 | : nullptr; | |||
6803 | ||||
6804 | // Don't consider existing declarations that are in a different | |||
6805 | // scope and are out-of-semantic-context declarations (if the new | |||
6806 | // declaration has linkage). | |||
6807 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), | |||
6808 | D.getCXXScopeSpec().isNotEmpty() || | |||
6809 | IsMemberSpecialization || | |||
6810 | IsVariableTemplateSpecialization); | |||
6811 | ||||
6812 | // Check whether the previous declaration is in the same block scope. This | |||
6813 | // affects whether we merge types with it, per C++11 [dcl.array]p3. | |||
6814 | if (getLangOpts().CPlusPlus && | |||
6815 | NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) | |||
6816 | NewVD->setPreviousDeclInSameBlockScope( | |||
6817 | Previous.isSingleResult() && !Previous.isShadowed() && | |||
6818 | isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); | |||
6819 | ||||
6820 | if (!getLangOpts().CPlusPlus) { | |||
6821 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | |||
6822 | } else { | |||
6823 | // If this is an explicit specialization of a static data member, check it. | |||
6824 | if (IsMemberSpecialization && !NewVD->isInvalidDecl() && | |||
6825 | CheckMemberSpecialization(NewVD, Previous)) | |||
6826 | NewVD->setInvalidDecl(); | |||
6827 | ||||
6828 | // Merge the decl with the existing one if appropriate. | |||
6829 | if (!Previous.empty()) { | |||
6830 | if (Previous.isSingleResult() && | |||
6831 | isa<FieldDecl>(Previous.getFoundDecl()) && | |||
6832 | D.getCXXScopeSpec().isSet()) { | |||
6833 | // The user tried to define a non-static data member | |||
6834 | // out-of-line (C++ [dcl.meaning]p1). | |||
6835 | Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) | |||
6836 | << D.getCXXScopeSpec().getRange(); | |||
6837 | Previous.clear(); | |||
6838 | NewVD->setInvalidDecl(); | |||
6839 | } | |||
6840 | } else if (D.getCXXScopeSpec().isSet()) { | |||
6841 | // No previous declaration in the qualifying scope. | |||
6842 | Diag(D.getIdentifierLoc(), diag::err_no_member) | |||
6843 | << Name << computeDeclContext(D.getCXXScopeSpec(), true) | |||
6844 | << D.getCXXScopeSpec().getRange(); | |||
6845 | NewVD->setInvalidDecl(); | |||
6846 | } | |||
6847 | ||||
6848 | if (!IsVariableTemplateSpecialization) | |||
6849 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | |||
6850 | ||||
6851 | if (NewTemplate) { | |||
6852 | VarTemplateDecl *PrevVarTemplate = | |||
6853 | NewVD->getPreviousDecl() | |||
6854 | ? NewVD->getPreviousDecl()->getDescribedVarTemplate() | |||
6855 | : nullptr; | |||
6856 | ||||
6857 | // Check the template parameter list of this declaration, possibly | |||
6858 | // merging in the template parameter list from the previous variable | |||
6859 | // template declaration. | |||
6860 | if (CheckTemplateParameterList( | |||
6861 | TemplateParams, | |||
6862 | PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() | |||
6863 | : nullptr, | |||
6864 | (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && | |||
6865 | DC->isDependentContext()) | |||
6866 | ? TPC_ClassTemplateMember | |||
6867 | : TPC_VarTemplate)) | |||
6868 | NewVD->setInvalidDecl(); | |||
6869 | ||||
6870 | // If we are providing an explicit specialization of a static variable | |||
6871 | // template, make a note of that. | |||
6872 | if (PrevVarTemplate && | |||
6873 | PrevVarTemplate->getInstantiatedFromMemberTemplate()) | |||
6874 | PrevVarTemplate->setMemberSpecialization(); | |||
6875 | } | |||
6876 | } | |||
6877 | ||||
6878 | // Diagnose shadowed variables iff this isn't a redeclaration. | |||
6879 | if (ShadowedDecl && !D.isRedeclaration()) | |||
6880 | CheckShadow(NewVD, ShadowedDecl, Previous); | |||
6881 | ||||
6882 | ProcessPragmaWeak(S, NewVD); | |||
6883 | ||||
6884 | // If this is the first declaration of an extern C variable, update | |||
6885 | // the map of such variables. | |||
6886 | if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && | |||
6887 | isIncompleteDeclExternC(*this, NewVD)) | |||
6888 | RegisterLocallyScopedExternCDecl(NewVD, S); | |||
6889 | ||||
6890 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | |||
6891 | Decl *ManglingContextDecl; | |||
6892 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( | |||
6893 | NewVD->getDeclContext(), ManglingContextDecl)) { | |||
6894 | Context.setManglingNumber( | |||
6895 | NewVD, MCtx->getManglingNumber( | |||
6896 | NewVD, getMSManglingNumber(getLangOpts(), S))); | |||
6897 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | |||
6898 | } | |||
6899 | } | |||
6900 | ||||
6901 | // Special handling of variable named 'main'. | |||
6902 | if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && | |||
6903 | NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && | |||
6904 | !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { | |||
6905 | ||||
6906 | // C++ [basic.start.main]p3 | |||
6907 | // A program that declares a variable main at global scope is ill-formed. | |||
6908 | if (getLangOpts().CPlusPlus) | |||
6909 | Diag(D.getLocStart(), diag::err_main_global_variable); | |||
6910 | ||||
6911 | // In C, and external-linkage variable named main results in undefined | |||
6912 | // behavior. | |||
6913 | else if (NewVD->hasExternalFormalLinkage()) | |||
6914 | Diag(D.getLocStart(), diag::warn_main_redefined); | |||
6915 | } | |||
6916 | ||||
6917 | if (D.isRedeclaration() && !Previous.empty()) { | |||
6918 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | |||
6919 | checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, | |||
6920 | D.isFunctionDefinition()); | |||
6921 | } | |||
6922 | ||||
6923 | if (NewTemplate) { | |||
6924 | if (NewVD->isInvalidDecl()) | |||
6925 | NewTemplate->setInvalidDecl(); | |||
6926 | ActOnDocumentableDecl(NewTemplate); | |||
6927 | return NewTemplate; | |||
6928 | } | |||
6929 | ||||
6930 | if (IsMemberSpecialization && !NewVD->isInvalidDecl()) | |||
6931 | CompleteMemberSpecialization(NewVD, Previous); | |||
6932 | ||||
6933 | return NewVD; | |||
6934 | } | |||
6935 | ||||
6936 | /// Enum describing the %select options in diag::warn_decl_shadow. | |||
6937 | enum ShadowedDeclKind { | |||
6938 | SDK_Local, | |||
6939 | SDK_Global, | |||
6940 | SDK_StaticMember, | |||
6941 | SDK_Field, | |||
6942 | SDK_Typedef, | |||
6943 | SDK_Using | |||
6944 | }; | |||
6945 | ||||
6946 | /// Determine what kind of declaration we're shadowing. | |||
6947 | static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, | |||
6948 | const DeclContext *OldDC) { | |||
6949 | if (isa<TypeAliasDecl>(ShadowedDecl)) | |||
6950 | return SDK_Using; | |||
6951 | else if (isa<TypedefDecl>(ShadowedDecl)) | |||
6952 | return SDK_Typedef; | |||
6953 | else if (isa<RecordDecl>(OldDC)) | |||
6954 | return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; | |||
6955 | ||||
6956 | return OldDC->isFileContext() ? SDK_Global : SDK_Local; | |||
6957 | } | |||
6958 | ||||
6959 | /// Return the location of the capture if the given lambda captures the given | |||
6960 | /// variable \p VD, or an invalid source location otherwise. | |||
6961 | static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, | |||
6962 | const VarDecl *VD) { | |||
6963 | for (const Capture &Capture : LSI->Captures) { | |||
6964 | if (Capture.isVariableCapture() && Capture.getVariable() == VD) | |||
6965 | return Capture.getLocation(); | |||
6966 | } | |||
6967 | return SourceLocation(); | |||
6968 | } | |||
6969 | ||||
6970 | static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, | |||
6971 | const LookupResult &R) { | |||
6972 | // Only diagnose if we're shadowing an unambiguous field or variable. | |||
6973 | if (R.getResultKind() != LookupResult::Found) | |||
6974 | return false; | |||
6975 | ||||
6976 | // Return false if warning is ignored. | |||
6977 | return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); | |||
6978 | } | |||
6979 | ||||
6980 | /// Return the declaration shadowed by the given variable \p D, or null | |||
6981 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | |||
6982 | NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, | |||
6983 | const LookupResult &R) { | |||
6984 | if (!shouldWarnIfShadowedDecl(Diags, R)) | |||
6985 | return nullptr; | |||
6986 | ||||
6987 | // Don't diagnose declarations at file scope. | |||
6988 | if (D->hasGlobalStorage()) | |||
6989 | return nullptr; | |||
6990 | ||||
6991 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | |||
6992 | return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) | |||
6993 | ? ShadowedDecl | |||
6994 | : nullptr; | |||
6995 | } | |||
6996 | ||||
6997 | /// Return the declaration shadowed by the given typedef \p D, or null | |||
6998 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | |||
6999 | NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, | |||
7000 | const LookupResult &R) { | |||
7001 | // Don't warn if typedef declaration is part of a class | |||
7002 | if (D->getDeclContext()->isRecord()) | |||
7003 | return nullptr; | |||
7004 | ||||
7005 | if (!shouldWarnIfShadowedDecl(Diags, R)) | |||
7006 | return nullptr; | |||
7007 | ||||
7008 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | |||
7009 | return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; | |||
7010 | } | |||
7011 | ||||
7012 | /// Diagnose variable or built-in function shadowing. Implements | |||
7013 | /// -Wshadow. | |||
7014 | /// | |||
7015 | /// This method is called whenever a VarDecl is added to a "useful" | |||
7016 | /// scope. | |||
7017 | /// | |||
7018 | /// \param ShadowedDecl the declaration that is shadowed by the given variable | |||
7019 | /// \param R the lookup of the name | |||
7020 | /// | |||
7021 | void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, | |||
7022 | const LookupResult &R) { | |||
7023 | DeclContext *NewDC = D->getDeclContext(); | |||
7024 | ||||
7025 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { | |||
7026 | // Fields are not shadowed by variables in C++ static methods. | |||
7027 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) | |||
7028 | if (MD->isStatic()) | |||
7029 | return; | |||
7030 | ||||
7031 | // Fields shadowed by constructor parameters are a special case. Usually | |||
7032 | // the constructor initializes the field with the parameter. | |||
7033 | if (isa<CXXConstructorDecl>(NewDC)) | |||
7034 | if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { | |||
7035 | // Remember that this was shadowed so we can either warn about its | |||
7036 | // modification or its existence depending on warning settings. | |||
7037 | ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); | |||
7038 | return; | |||
7039 | } | |||
7040 | } | |||
7041 | ||||
7042 | if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) | |||
7043 | if (shadowedVar->isExternC()) { | |||
7044 | // For shadowing external vars, make sure that we point to the global | |||
7045 | // declaration, not a locally scoped extern declaration. | |||
7046 | for (auto I : shadowedVar->redecls()) | |||
7047 | if (I->isFileVarDecl()) { | |||
7048 | ShadowedDecl = I; | |||
7049 | break; | |||
7050 | } | |||
7051 | } | |||
7052 | ||||
7053 | DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); | |||
7054 | ||||
7055 | unsigned WarningDiag = diag::warn_decl_shadow; | |||
7056 | SourceLocation CaptureLoc; | |||
7057 | if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && | |||
7058 | isa<CXXMethodDecl>(NewDC)) { | |||
7059 | if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { | |||
7060 | if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { | |||
7061 | if (RD->getLambdaCaptureDefault() == LCD_None) { | |||
7062 | // Try to avoid warnings for lambdas with an explicit capture list. | |||
7063 | const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); | |||
7064 | // Warn only when the lambda captures the shadowed decl explicitly. | |||
7065 | CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); | |||
7066 | if (CaptureLoc.isInvalid()) | |||
7067 | WarningDiag = diag::warn_decl_shadow_uncaptured_local; | |||
7068 | } else { | |||
7069 | // Remember that this was shadowed so we can avoid the warning if the | |||
7070 | // shadowed decl isn't captured and the warning settings allow it. | |||
7071 | cast<LambdaScopeInfo>(getCurFunction()) | |||
7072 | ->ShadowingDecls.push_back( | |||
7073 | {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); | |||
7074 | return; | |||
7075 | } | |||
7076 | } | |||
7077 | ||||
7078 | if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { | |||
7079 | // A variable can't shadow a local variable in an enclosing scope, if | |||
7080 | // they are separated by a non-capturing declaration context. | |||
7081 | for (DeclContext *ParentDC = NewDC; | |||
7082 | ParentDC && !ParentDC->Equals(OldDC); | |||
7083 | ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { | |||
7084 | // Only block literals, captured statements, and lambda expressions | |||
7085 | // can capture; other scopes don't. | |||
7086 | if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && | |||
7087 | !isLambdaCallOperator(ParentDC)) { | |||
7088 | return; | |||
7089 | } | |||
7090 | } | |||
7091 | } | |||
7092 | } | |||
7093 | } | |||
7094 | ||||
7095 | // Only warn about certain kinds of shadowing for class members. | |||
7096 | if (NewDC && NewDC->isRecord()) { | |||
7097 | // In particular, don't warn about shadowing non-class members. | |||
7098 | if (!OldDC->isRecord()) | |||
7099 | return; | |||
7100 | ||||
7101 | // TODO: should we warn about static data members shadowing | |||
7102 | // static data members from base classes? | |||
7103 | ||||
7104 | // TODO: don't diagnose for inaccessible shadowed members. | |||
7105 | // This is hard to do perfectly because we might friend the | |||
7106 | // shadowing context, but that's just a false negative. | |||
7107 | } | |||
7108 | ||||
7109 | ||||
7110 | DeclarationName Name = R.getLookupName(); | |||
7111 | ||||
7112 | // Emit warning and note. | |||
7113 | if (getSourceManager().isInSystemMacro(R.getNameLoc())) | |||
7114 | return; | |||
7115 | ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); | |||
7116 | Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; | |||
7117 | if (!CaptureLoc.isInvalid()) | |||
7118 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | |||
7119 | << Name << /*explicitly*/ 1; | |||
7120 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | |||
7121 | } | |||
7122 | ||||
7123 | /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD | |||
7124 | /// when these variables are captured by the lambda. | |||
7125 | void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { | |||
7126 | for (const auto &Shadow : LSI->ShadowingDecls) { | |||
7127 | const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; | |||
7128 | // Try to avoid the warning when the shadowed decl isn't captured. | |||
7129 | SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); | |||
7130 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | |||
7131 | Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() | |||
7132 | ? diag::warn_decl_shadow_uncaptured_local | |||
7133 | : diag::warn_decl_shadow) | |||
7134 | << Shadow.VD->getDeclName() | |||
7135 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; | |||
7136 | if (!CaptureLoc.isInvalid()) | |||
7137 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | |||
7138 | << Shadow.VD->getDeclName() << /*explicitly*/ 0; | |||
7139 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | |||
7140 | } | |||
7141 | } | |||
7142 | ||||
7143 | /// Check -Wshadow without the advantage of a previous lookup. | |||
7144 | void Sema::CheckShadow(Scope *S, VarDecl *D) { | |||
7145 | if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) | |||
7146 | return; | |||
7147 | ||||
7148 | LookupResult R(*this, D->getDeclName(), D->getLocation(), | |||
7149 | Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); | |||
7150 | LookupName(R, S); | |||
7151 | if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) | |||
7152 | CheckShadow(D, ShadowedDecl, R); | |||
7153 | } | |||
7154 | ||||
7155 | /// Check if 'E', which is an expression that is about to be modified, refers | |||
7156 | /// to a constructor parameter that shadows a field. | |||
7157 | void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { | |||
7158 | // Quickly ignore expressions that can't be shadowing ctor parameters. | |||
7159 | if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) | |||
7160 | return; | |||
7161 | E = E->IgnoreParenImpCasts(); | |||
7162 | auto *DRE = dyn_cast<DeclRefExpr>(E); | |||
7163 | if (!DRE) | |||
7164 | return; | |||
7165 | const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); | |||
7166 | auto I = ShadowingDecls.find(D); | |||
7167 | if (I == ShadowingDecls.end()) | |||
7168 | return; | |||
7169 | const NamedDecl *ShadowedDecl = I->second; | |||
7170 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | |||
7171 | Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; | |||
7172 | Diag(D->getLocation(), diag::note_var_declared_here) << D; | |||
7173 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | |||
7174 | ||||
7175 | // Avoid issuing multiple warnings about the same decl. | |||
7176 | ShadowingDecls.erase(I); | |||
7177 | } | |||
7178 | ||||
7179 | /// Check for conflict between this global or extern "C" declaration and | |||
7180 | /// previous global or extern "C" declarations. This is only used in C++. | |||
7181 | template<typename T> | |||
7182 | static bool checkGlobalOrExternCConflict( | |||
7183 | Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { | |||
7184 | assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")(static_cast <bool> (S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 7184, __extension__ __PRETTY_FUNCTION__)); | |||
7185 | NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); | |||
7186 | ||||
7187 | if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { | |||
7188 | // The common case: this global doesn't conflict with any extern "C" | |||
7189 | // declaration. | |||
7190 | return false; | |||
7191 | } | |||
7192 | ||||
7193 | if (Prev) { | |||
7194 | if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { | |||
7195 | // Both the old and new declarations have C language linkage. This is a | |||
7196 | // redeclaration. | |||
7197 | Previous.clear(); | |||
7198 | Previous.addDecl(Prev); | |||
7199 | return true; | |||
7200 | } | |||
7201 | ||||
7202 | // This is a global, non-extern "C" declaration, and there is a previous | |||
7203 | // non-global extern "C" declaration. Diagnose if this is a variable | |||
7204 | // declaration. | |||
7205 | if (!isa<VarDecl>(ND)) | |||
7206 | return false; | |||
7207 | } else { | |||
7208 | // The declaration is extern "C". Check for any declaration in the | |||
7209 | // translation unit which might conflict. | |||
7210 | if (IsGlobal) { | |||
7211 | // We have already performed the lookup into the translation unit. | |||
7212 | IsGlobal = false; | |||
7213 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | |||
7214 | I != E; ++I) { | |||
7215 | if (isa<VarDecl>(*I)) { | |||
7216 | Prev = *I; | |||
7217 | break; | |||
7218 | } | |||
7219 | } | |||
7220 | } else { | |||
7221 | DeclContext::lookup_result R = | |||
7222 | S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); | |||
7223 | for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); | |||
7224 | I != E; ++I) { | |||
7225 | if (isa<VarDecl>(*I)) { | |||
7226 | Prev = *I; | |||
7227 | break; | |||
7228 | } | |||
7229 | // FIXME: If we have any other entity with this name in global scope, | |||
7230 | // the declaration is ill-formed, but that is a defect: it breaks the | |||
7231 | // 'stat' hack, for instance. Only variables can have mangled name | |||
7232 | // clashes with extern "C" declarations, so only they deserve a | |||
7233 | // diagnostic. | |||
7234 | } | |||
7235 | } | |||
7236 | ||||
7237 | if (!Prev) | |||
7238 | return false; | |||
7239 | } | |||
7240 | ||||
7241 | // Use the first declaration's location to ensure we point at something which | |||
7242 | // is lexically inside an extern "C" linkage-spec. | |||
7243 | assert(Prev && "should have found a previous declaration to diagnose")(static_cast <bool> (Prev && "should have found a previous declaration to diagnose" ) ? void (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 7243, __extension__ __PRETTY_FUNCTION__)); | |||
7244 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) | |||
7245 | Prev = FD->getFirstDecl(); | |||
7246 | else | |||
7247 | Prev = cast<VarDecl>(Prev)->getFirstDecl(); | |||
7248 | ||||
7249 | S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) | |||
7250 | << IsGlobal << ND; | |||
7251 | S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) | |||
7252 | << IsGlobal; | |||
7253 | return false; | |||
7254 | } | |||
7255 | ||||
7256 | /// Apply special rules for handling extern "C" declarations. Returns \c true | |||
7257 | /// if we have found that this is a redeclaration of some prior entity. | |||
7258 | /// | |||
7259 | /// Per C++ [dcl.link]p6: | |||
7260 | /// Two declarations [for a function or variable] with C language linkage | |||
7261 | /// with the same name that appear in different scopes refer to the same | |||
7262 | /// [entity]. An entity with C language linkage shall not be declared with | |||
7263 | /// the same name as an entity in global scope. | |||
7264 | template<typename T> | |||
7265 | static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, | |||
7266 | LookupResult &Previous) { | |||
7267 | if (!S.getLangOpts().CPlusPlus) { | |||
7268 | // In C, when declaring a global variable, look for a corresponding 'extern' | |||
7269 | // variable declared in function scope. We don't need this in C++, because | |||
7270 | // we find local extern decls in the surrounding file-scope DeclContext. | |||
7271 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | |||
7272 | if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { | |||
7273 | Previous.clear(); | |||
7274 | Previous.addDecl(Prev); | |||
7275 | return true; | |||
7276 | } | |||
7277 | } | |||
7278 | return false; | |||
7279 | } | |||
7280 | ||||
7281 | // A declaration in the translation unit can conflict with an extern "C" | |||
7282 | // declaration. | |||
7283 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) | |||
7284 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); | |||
7285 | ||||
7286 | // An extern "C" declaration can conflict with a declaration in the | |||
7287 | // translation unit or can be a redeclaration of an extern "C" declaration | |||
7288 | // in another scope. | |||
7289 | if (isIncompleteDeclExternC(S,ND)) | |||
7290 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); | |||
7291 | ||||
7292 | // Neither global nor extern "C": nothing to do. | |||
7293 | return false; | |||
7294 | } | |||
7295 | ||||
7296 | void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { | |||
7297 | // If the decl is already known invalid, don't check it. | |||
7298 | if (NewVD->isInvalidDecl()) | |||
7299 | return; | |||
7300 | ||||
7301 | QualType T = NewVD->getType(); | |||
7302 | ||||
7303 | // Defer checking an 'auto' type until its initializer is attached. | |||
7304 | if (T->isUndeducedType()) | |||
7305 | return; | |||
7306 | ||||
7307 | if (NewVD->hasAttrs()) | |||
7308 | CheckAlignasUnderalignment(NewVD); | |||
7309 | ||||
7310 | if (T->isObjCObjectType()) { | |||
7311 | Diag(NewVD->getLocation(), diag::err_statically_allocated_object) | |||
7312 | << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); | |||
7313 | T = Context.getObjCObjectPointerType(T); | |||
7314 | NewVD->setType(T); | |||
7315 | } | |||
7316 | ||||
7317 | // Emit an error if an address space was applied to decl with local storage. | |||
7318 | // This includes arrays of objects with address space qualifiers, but not | |||
7319 | // automatic variables that point to other address spaces. | |||
7320 | // ISO/IEC TR 18037 S5.1.2 | |||
7321 | if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && | |||
7322 | T.getAddressSpace() != LangAS::Default) { | |||
7323 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; | |||
7324 | NewVD->setInvalidDecl(); | |||
7325 | return; | |||
7326 | } | |||
7327 | ||||
7328 | // OpenCL v1.2 s6.8 - The static qualifier is valid only in program | |||
7329 | // scope. | |||
7330 | if (getLangOpts().OpenCLVersion == 120 && | |||
7331 | !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && | |||
7332 | NewVD->isStaticLocal()) { | |||
7333 | Diag(NewVD->getLocation(), diag::err_static_function_scope); | |||
7334 | NewVD->setInvalidDecl(); | |||
7335 | return; | |||
7336 | } | |||
7337 | ||||
7338 | if (getLangOpts().OpenCL) { | |||
7339 | // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. | |||
7340 | if (NewVD->hasAttr<BlocksAttr>()) { | |||
7341 | Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); | |||
7342 | return; | |||
7343 | } | |||
7344 | ||||
7345 | if (T->isBlockPointerType()) { | |||
7346 | // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and | |||
7347 | // can't use 'extern' storage class. | |||
7348 | if (!T.isConstQualified()) { | |||
7349 | Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) | |||
7350 | << 0 /*const*/; | |||
7351 | NewVD->setInvalidDecl(); | |||
7352 | return; | |||
7353 | } | |||
7354 | if (NewVD->hasExternalStorage()) { | |||
7355 | Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); | |||
7356 | NewVD->setInvalidDecl(); | |||
7357 | return; | |||
7358 | } | |||
7359 | } | |||
7360 | // OpenCL v1.2 s6.5 - All program scope variables must be declared in the | |||
7361 | // __constant address space. | |||
7362 | // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static | |||
7363 | // variables inside a function can also be declared in the global | |||
7364 | // address space. | |||
7365 | if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || | |||
7366 | NewVD->hasExternalStorage()) { | |||
7367 | if (!T->isSamplerT() && | |||
7368 | !(T.getAddressSpace() == LangAS::opencl_constant || | |||
7369 | (T.getAddressSpace() == LangAS::opencl_global && | |||
7370 | getLangOpts().OpenCLVersion == 200))) { | |||
7371 | int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; | |||
7372 | if (getLangOpts().OpenCLVersion == 200) | |||
7373 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | |||
7374 | << Scope << "global or constant"; | |||
7375 | else | |||
7376 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | |||
7377 | << Scope << "constant"; | |||
7378 | NewVD->setInvalidDecl(); | |||
7379 | return; | |||
7380 | } | |||
7381 | } else { | |||
7382 | if (T.getAddressSpace() == LangAS::opencl_global) { | |||
7383 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | |||
7384 | << 1 /*is any function*/ << "global"; | |||
7385 | NewVD->setInvalidDecl(); | |||
7386 | return; | |||
7387 | } | |||
7388 | if (T.getAddressSpace() == LangAS::opencl_constant || | |||
7389 | T.getAddressSpace() == LangAS::opencl_local) { | |||
7390 | FunctionDecl *FD = getCurFunctionDecl(); | |||
7391 | // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables | |||
7392 | // in functions. | |||
7393 | if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { | |||
7394 | if (T.getAddressSpace() == LangAS::opencl_constant) | |||
7395 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | |||
7396 | << 0 /*non-kernel only*/ << "constant"; | |||
7397 | else | |||
7398 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | |||
7399 | << 0 /*non-kernel only*/ << "local"; | |||
7400 | NewVD->setInvalidDecl(); | |||
7401 | return; | |||
7402 | } | |||
7403 | // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be | |||
7404 | // in the outermost scope of a kernel function. | |||
7405 | if (FD && FD->hasAttr<OpenCLKernelAttr>()) { | |||
7406 | if (!getCurScope()->isFunctionScope()) { | |||
7407 | if (T.getAddressSpace() == LangAS::opencl_constant) | |||
7408 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | |||
7409 | << "constant"; | |||
7410 | else | |||
7411 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | |||
7412 | << "local"; | |||
7413 | NewVD->setInvalidDecl(); | |||
7414 | return; | |||
7415 | } | |||
7416 | } | |||
7417 | } else if (T.getAddressSpace() != LangAS::opencl_private) { | |||
7418 | // Do not allow other address spaces on automatic variable. | |||
7419 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; | |||
7420 | NewVD->setInvalidDecl(); | |||
7421 | return; | |||
7422 | } | |||
7423 | } | |||
7424 | } | |||
7425 | ||||
7426 | if (NewVD->hasLocalStorage() && T.isObjCGCWeak() | |||
7427 | && !NewVD->hasAttr<BlocksAttr>()) { | |||
7428 | if (getLangOpts().getGC() != LangOptions::NonGC) | |||
7429 | Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); | |||
7430 | else { | |||
7431 | assert(!getLangOpts().ObjCAutoRefCount)(static_cast <bool> (!getLangOpts().ObjCAutoRefCount) ? void (0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 7431, __extension__ __PRETTY_FUNCTION__)); | |||
7432 | Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); | |||
7433 | } | |||
7434 | } | |||
7435 | ||||
7436 | bool isVM = T->isVariablyModifiedType(); | |||
7437 | if (isVM || NewVD->hasAttr<CleanupAttr>() || | |||
7438 | NewVD->hasAttr<BlocksAttr>()) | |||
7439 | setFunctionHasBranchProtectedScope(); | |||
7440 | ||||
7441 | if ((isVM && NewVD->hasLinkage()) || | |||
7442 | (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { | |||
7443 | bool SizeIsNegative; | |||
7444 | llvm::APSInt Oversized; | |||
7445 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( | |||
7446 | NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); | |||
7447 | QualType FixedT; | |||
7448 | if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) | |||
7449 | FixedT = FixedTInfo->getType(); | |||
7450 | else if (FixedTInfo) { | |||
7451 | // Type and type-as-written are canonically different. We need to fix up | |||
7452 | // both types separately. | |||
7453 | FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, | |||
7454 | Oversized); | |||
7455 | } | |||
7456 | if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { | |||
7457 | const VariableArrayType *VAT = Context.getAsVariableArrayType(T); | |||
7458 | // FIXME: This won't give the correct result for | |||
7459 | // int a[10][n]; | |||
7460 | SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); | |||
7461 | ||||
7462 | if (NewVD->isFileVarDecl()) | |||
7463 | Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) | |||
7464 | << SizeRange; | |||
7465 | else if (NewVD->isStaticLocal()) | |||
7466 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) | |||
7467 | << SizeRange; | |||
7468 | else | |||
7469 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) | |||
7470 | << SizeRange; | |||
7471 | NewVD->setInvalidDecl(); | |||
7472 | return; | |||
7473 | } | |||
7474 | ||||
7475 | if (!FixedTInfo) { | |||
7476 | if (NewVD->isFileVarDecl()) | |||
7477 | Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); | |||
7478 | else | |||
7479 | Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); | |||
7480 | NewVD->setInvalidDecl(); | |||
7481 | return; | |||
7482 | } | |||
7483 | ||||
7484 | Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); | |||
7485 | NewVD->setType(FixedT); | |||
7486 | NewVD->setTypeSourceInfo(FixedTInfo); | |||
7487 | } | |||
7488 | ||||
7489 | if (T->isVoidType()) { | |||
7490 | // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names | |||
7491 | // of objects and functions. | |||
7492 | if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { | |||
7493 | Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) | |||
7494 | << T; | |||
7495 | NewVD->setInvalidDecl(); | |||
7496 | return; | |||
7497 | } | |||
7498 | } | |||
7499 | ||||
7500 | if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { | |||
7501 | Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); | |||
7502 | NewVD->setInvalidDecl(); | |||
7503 | return; | |||
7504 | } | |||
7505 | ||||
7506 | if (isVM && NewVD->hasAttr<BlocksAttr>()) { | |||
7507 | Diag(NewVD->getLocation(), diag::err_block_on_vm); | |||
7508 | NewVD->setInvalidDecl(); | |||
7509 | return; | |||
7510 | } | |||
7511 | ||||
7512 | if (NewVD->isConstexpr() && !T->isDependentType() && | |||
7513 | RequireLiteralType(NewVD->getLocation(), T, | |||
7514 | diag::err_constexpr_var_non_literal)) { | |||
7515 | NewVD->setInvalidDecl(); | |||
7516 | return; | |||
7517 | } | |||
7518 | } | |||
7519 | ||||
7520 | /// Perform semantic checking on a newly-created variable | |||
7521 | /// declaration. | |||
7522 | /// | |||
7523 | /// This routine performs all of the type-checking required for a | |||
7524 | /// variable declaration once it has been built. It is used both to | |||
7525 | /// check variables after they have been parsed and their declarators | |||
7526 | /// have been translated into a declaration, and to check variables | |||
7527 | /// that have been instantiated from a template. | |||
7528 | /// | |||
7529 | /// Sets NewVD->isInvalidDecl() if an error was encountered. | |||
7530 | /// | |||
7531 | /// Returns true if the variable declaration is a redeclaration. | |||
7532 | bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { | |||
7533 | CheckVariableDeclarationType(NewVD); | |||
7534 | ||||
7535 | // If the decl is already known invalid, don't check it. | |||
7536 | if (NewVD->isInvalidDecl()) | |||
7537 | return false; | |||
7538 | ||||
7539 | // If we did not find anything by this name, look for a non-visible | |||
7540 | // extern "C" declaration with the same name. | |||
7541 | if (Previous.empty() && | |||
7542 | checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) | |||
7543 | Previous.setShadowed(); | |||
7544 | ||||
7545 | if (!Previous.empty()) { | |||
7546 | MergeVarDecl(NewVD, Previous); | |||
7547 | return true; | |||
7548 | } | |||
7549 | return false; | |||
7550 | } | |||
7551 | ||||
7552 | namespace { | |||
7553 | struct FindOverriddenMethod { | |||
7554 | Sema *S; | |||
7555 | CXXMethodDecl *Method; | |||
7556 | ||||
7557 | /// Member lookup function that determines whether a given C++ | |||
7558 | /// method overrides a method in a base class, to be used with | |||
7559 | /// CXXRecordDecl::lookupInBases(). | |||
7560 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | |||
7561 | RecordDecl *BaseRecord = | |||
7562 | Specifier->getType()->getAs<RecordType>()->getDecl(); | |||
7563 | ||||
7564 | DeclarationName Name = Method->getDeclName(); | |||
7565 | ||||
7566 | // FIXME: Do we care about other names here too? | |||
7567 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | |||
7568 | // We really want to find the base class destructor here. | |||
7569 | QualType T = S->Context.getTypeDeclType(BaseRecord); | |||
7570 | CanQualType CT = S->Context.getCanonicalType(T); | |||
7571 | ||||
7572 | Name = S->Context.DeclarationNames.getCXXDestructorName(CT); | |||
7573 | } | |||
7574 | ||||
7575 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); | |||
7576 | Path.Decls = Path.Decls.slice(1)) { | |||
7577 | NamedDecl *D = Path.Decls.front(); | |||
7578 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { | |||
7579 | if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) | |||
7580 | return true; | |||
7581 | } | |||
7582 | } | |||
7583 | ||||
7584 | return false; | |||
7585 | } | |||
7586 | }; | |||
7587 | ||||
7588 | enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; | |||
7589 | } // end anonymous namespace | |||
7590 | ||||
7591 | /// Report an error regarding overriding, along with any relevant | |||
7592 | /// overridden methods. | |||
7593 | /// | |||
7594 | /// \param DiagID the primary error to report. | |||
7595 | /// \param MD the overriding method. | |||
7596 | /// \param OEK which overrides to include as notes. | |||
7597 | static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, | |||
7598 | OverrideErrorKind OEK = OEK_All) { | |||
7599 | S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); | |||
7600 | for (const CXXMethodDecl *O : MD->overridden_methods()) { | |||
7601 | // This check (& the OEK parameter) could be replaced by a predicate, but | |||
7602 | // without lambdas that would be overkill. This is still nicer than writing | |||
7603 | // out the diag loop 3 times. | |||
7604 | if ((OEK == OEK_All) || | |||
7605 | (OEK == OEK_NonDeleted && !O->isDeleted()) || | |||
7606 | (OEK == OEK_Deleted && O->isDeleted())) | |||
7607 | S.Diag(O->getLocation(), diag::note_overridden_virtual_function); | |||
7608 | } | |||
7609 | } | |||
7610 | ||||
7611 | /// AddOverriddenMethods - See if a method overrides any in the base classes, | |||
7612 | /// and if so, check that it's a valid override and remember it. | |||
7613 | bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { | |||
7614 | // Look for methods in base classes that this method might override. | |||
7615 | CXXBasePaths Paths; | |||
7616 | FindOverriddenMethod FOM; | |||
7617 | FOM.Method = MD; | |||
7618 | FOM.S = this; | |||
7619 | bool hasDeletedOverridenMethods = false; | |||
7620 | bool hasNonDeletedOverridenMethods = false; | |||
7621 | bool AddedAny = false; | |||
7622 | if (DC->lookupInBases(FOM, Paths)) { | |||
7623 | for (auto *I : Paths.found_decls()) { | |||
7624 | if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { | |||
7625 | MD->addOverriddenMethod(OldMD->getCanonicalDecl()); | |||
7626 | if (!CheckOverridingFunctionReturnType(MD, OldMD) && | |||
7627 | !CheckOverridingFunctionAttributes(MD, OldMD) && | |||
7628 | !CheckOverridingFunctionExceptionSpec(MD, OldMD) && | |||
7629 | !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { | |||
7630 | hasDeletedOverridenMethods |= OldMD->isDeleted(); | |||
7631 | hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); | |||
7632 | AddedAny = true; | |||
7633 | } | |||
7634 | } | |||
7635 | } | |||
7636 | } | |||
7637 | ||||
7638 | if (hasDeletedOverridenMethods && !MD->isDeleted()) { | |||
7639 | ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); | |||
7640 | } | |||
7641 | if (hasNonDeletedOverridenMethods && MD->isDeleted()) { | |||
7642 | ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); | |||
7643 | } | |||
7644 | ||||
7645 | return AddedAny; | |||
7646 | } | |||
7647 | ||||
7648 | namespace { | |||
7649 | // Struct for holding all of the extra arguments needed by | |||
7650 | // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. | |||
7651 | struct ActOnFDArgs { | |||
7652 | Scope *S; | |||
7653 | Declarator &D; | |||
7654 | MultiTemplateParamsArg TemplateParamLists; | |||
7655 | bool AddToScope; | |||
7656 | }; | |||
7657 | } // end anonymous namespace | |||
7658 | ||||
7659 | namespace { | |||
7660 | ||||
7661 | // Callback to only accept typo corrections that have a non-zero edit distance. | |||
7662 | // Also only accept corrections that have the same parent decl. | |||
7663 | class DifferentNameValidatorCCC : public CorrectionCandidateCallback { | |||
7664 | public: | |||
7665 | DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, | |||
7666 | CXXRecordDecl *Parent) | |||
7667 | : Context(Context), OriginalFD(TypoFD), | |||
7668 | ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} | |||
7669 | ||||
7670 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
7671 | if (candidate.getEditDistance() == 0) | |||
7672 | return false; | |||
7673 | ||||
7674 | SmallVector<unsigned, 1> MismatchedParams; | |||
7675 | for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), | |||
7676 | CDeclEnd = candidate.end(); | |||
7677 | CDecl != CDeclEnd; ++CDecl) { | |||
7678 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | |||
7679 | ||||
7680 | if (FD && !FD->hasBody() && | |||
7681 | hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { | |||
7682 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | |||
7683 | CXXRecordDecl *Parent = MD->getParent(); | |||
7684 | if (Parent && Parent->getCanonicalDecl() == ExpectedParent) | |||
7685 | return true; | |||
7686 | } else if (!ExpectedParent) { | |||
7687 | return true; | |||
7688 | } | |||
7689 | } | |||
7690 | } | |||
7691 | ||||
7692 | return false; | |||
7693 | } | |||
7694 | ||||
7695 | private: | |||
7696 | ASTContext &Context; | |||
7697 | FunctionDecl *OriginalFD; | |||
7698 | CXXRecordDecl *ExpectedParent; | |||
7699 | }; | |||
7700 | ||||
7701 | } // end anonymous namespace | |||
7702 | ||||
7703 | void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { | |||
7704 | TypoCorrectedFunctionDefinitions.insert(F); | |||
7705 | } | |||
7706 | ||||
7707 | /// Generate diagnostics for an invalid function redeclaration. | |||
7708 | /// | |||
7709 | /// This routine handles generating the diagnostic messages for an invalid | |||
7710 | /// function redeclaration, including finding possible similar declarations | |||
7711 | /// or performing typo correction if there are no previous declarations with | |||
7712 | /// the same name. | |||
7713 | /// | |||
7714 | /// Returns a NamedDecl iff typo correction was performed and substituting in | |||
7715 | /// the new declaration name does not cause new errors. | |||
7716 | static NamedDecl *DiagnoseInvalidRedeclaration( | |||
7717 | Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, | |||
7718 | ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { | |||
7719 | DeclarationName Name = NewFD->getDeclName(); | |||
7720 | DeclContext *NewDC = NewFD->getDeclContext(); | |||
7721 | SmallVector<unsigned, 1> MismatchedParams; | |||
7722 | SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; | |||
7723 | TypoCorrection Correction; | |||
7724 | bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); | |||
7725 | unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend | |||
7726 | : diag::err_member_decl_does_not_match; | |||
7727 | LookupResult Prev(SemaRef, Name, NewFD->getLocation(), | |||
7728 | IsLocalFriend ? Sema::LookupLocalFriendName | |||
7729 | : Sema::LookupOrdinaryName, | |||
7730 | Sema::ForVisibleRedeclaration); | |||
7731 | ||||
7732 | NewFD->setInvalidDecl(); | |||
7733 | if (IsLocalFriend) | |||
7734 | SemaRef.LookupName(Prev, S); | |||
7735 | else | |||
7736 | SemaRef.LookupQualifiedName(Prev, NewDC); | |||
7737 | assert(!Prev.isAmbiguous() &&(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 7738, __extension__ __PRETTY_FUNCTION__)) | |||
7738 | "Cannot have an ambiguity in previous-declaration lookup")(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 7738, __extension__ __PRETTY_FUNCTION__)); | |||
7739 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | |||
7740 | if (!Prev.empty()) { | |||
7741 | for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); | |||
7742 | Func != FuncEnd; ++Func) { | |||
7743 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); | |||
7744 | if (FD && | |||
7745 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | |||
7746 | // Add 1 to the index so that 0 can mean the mismatch didn't | |||
7747 | // involve a parameter | |||
7748 | unsigned ParamNum = | |||
7749 | MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; | |||
7750 | NearMatches.push_back(std::make_pair(FD, ParamNum)); | |||
7751 | } | |||
7752 | } | |||
7753 | // If the qualified name lookup yielded nothing, try typo correction | |||
7754 | } else if ((Correction = SemaRef.CorrectTypo( | |||
7755 | Prev.getLookupNameInfo(), Prev.getLookupKind(), S, | |||
7756 | &ExtraArgs.D.getCXXScopeSpec(), | |||
7757 | llvm::make_unique<DifferentNameValidatorCCC>( | |||
7758 | SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), | |||
7759 | Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { | |||
7760 | // Set up everything for the call to ActOnFunctionDeclarator | |||
7761 | ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), | |||
7762 | ExtraArgs.D.getIdentifierLoc()); | |||
7763 | Previous.clear(); | |||
7764 | Previous.setLookupName(Correction.getCorrection()); | |||
7765 | for (TypoCorrection::decl_iterator CDecl = Correction.begin(), | |||
7766 | CDeclEnd = Correction.end(); | |||
7767 | CDecl != CDeclEnd; ++CDecl) { | |||
7768 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | |||
7769 | if (FD && !FD->hasBody() && | |||
7770 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | |||
7771 | Previous.addDecl(FD); | |||
7772 | } | |||
7773 | } | |||
7774 | bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); | |||
7775 | ||||
7776 | NamedDecl *Result; | |||
7777 | // Retry building the function declaration with the new previous | |||
7778 | // declarations, and with errors suppressed. | |||
7779 | { | |||
7780 | // Trap errors. | |||
7781 | Sema::SFINAETrap Trap(SemaRef); | |||
7782 | ||||
7783 | // TODO: Refactor ActOnFunctionDeclarator so that we can call only the | |||
7784 | // pieces need to verify the typo-corrected C++ declaration and hopefully | |||
7785 | // eliminate the need for the parameter pack ExtraArgs. | |||
7786 | Result = SemaRef.ActOnFunctionDeclarator( | |||
7787 | ExtraArgs.S, ExtraArgs.D, | |||
7788 | Correction.getCorrectionDecl()->getDeclContext(), | |||
7789 | NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, | |||
7790 | ExtraArgs.AddToScope); | |||
7791 | ||||
7792 | if (Trap.hasErrorOccurred()) | |||
7793 | Result = nullptr; | |||
7794 | } | |||
7795 | ||||
7796 | if (Result) { | |||
7797 | // Determine which correction we picked. | |||
7798 | Decl *Canonical = Result->getCanonicalDecl(); | |||
7799 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | |||
7800 | I != E; ++I) | |||
7801 | if ((*I)->getCanonicalDecl() == Canonical) | |||
7802 | Correction.setCorrectionDecl(*I); | |||
7803 | ||||
7804 | // Let Sema know about the correction. | |||
7805 | SemaRef.MarkTypoCorrectedFunctionDefinition(Result); | |||
7806 | SemaRef.diagnoseTypo( | |||
7807 | Correction, | |||
7808 | SemaRef.PDiag(IsLocalFriend | |||
7809 | ? diag::err_no_matching_local_friend_suggest | |||
7810 | : diag::err_member_decl_does_not_match_suggest) | |||
7811 | << Name << NewDC << IsDefinition); | |||
7812 | return Result; | |||
7813 | } | |||
7814 | ||||
7815 | // Pretend the typo correction never occurred | |||
7816 | ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), | |||
7817 | ExtraArgs.D.getIdentifierLoc()); | |||
7818 | ExtraArgs.D.setRedeclaration(wasRedeclaration); | |||
7819 | Previous.clear(); | |||
7820 | Previous.setLookupName(Name); | |||
7821 | } | |||
7822 | ||||
7823 | SemaRef.Diag(NewFD->getLocation(), DiagMsg) | |||
7824 | << Name << NewDC << IsDefinition << NewFD->getLocation(); | |||
7825 | ||||
7826 | bool NewFDisConst = false; | |||
7827 | if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) | |||
7828 | NewFDisConst = NewMD->isConst(); | |||
7829 | ||||
7830 | for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator | |||
7831 | NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); | |||
7832 | NearMatch != NearMatchEnd; ++NearMatch) { | |||
7833 | FunctionDecl *FD = NearMatch->first; | |||
7834 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | |||
7835 | bool FDisConst = MD && MD->isConst(); | |||
7836 | bool IsMember = MD || !IsLocalFriend; | |||
7837 | ||||
7838 | // FIXME: These notes are poorly worded for the local friend case. | |||
7839 | if (unsigned Idx = NearMatch->second) { | |||
7840 | ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); | |||
7841 | SourceLocation Loc = FDParam->getTypeSpecStartLoc(); | |||
7842 | if (Loc.isInvalid()) Loc = FD->getLocation(); | |||
7843 | SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match | |||
7844 | : diag::note_local_decl_close_param_match) | |||
7845 | << Idx << FDParam->getType() | |||
7846 | << NewFD->getParamDecl(Idx - 1)->getType(); | |||
7847 | } else if (FDisConst != NewFDisConst) { | |||
7848 | SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) | |||
7849 | << NewFDisConst << FD->getSourceRange().getEnd(); | |||
7850 | } else | |||
7851 | SemaRef.Diag(FD->getLocation(), | |||
7852 | IsMember ? diag::note_member_def_close_match | |||
7853 | : diag::note_local_decl_close_match); | |||
7854 | } | |||
7855 | return nullptr; | |||
7856 | } | |||
7857 | ||||
7858 | static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { | |||
7859 | switch (D.getDeclSpec().getStorageClassSpec()) { | |||
7860 | default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 7860); | |||
7861 | case DeclSpec::SCS_auto: | |||
7862 | case DeclSpec::SCS_register: | |||
7863 | case DeclSpec::SCS_mutable: | |||
7864 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
7865 | diag::err_typecheck_sclass_func); | |||
7866 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | |||
7867 | D.setInvalidType(); | |||
7868 | break; | |||
7869 | case DeclSpec::SCS_unspecified: break; | |||
7870 | case DeclSpec::SCS_extern: | |||
7871 | if (D.getDeclSpec().isExternInLinkageSpec()) | |||
7872 | return SC_None; | |||
7873 | return SC_Extern; | |||
7874 | case DeclSpec::SCS_static: { | |||
7875 | if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { | |||
7876 | // C99 6.7.1p5: | |||
7877 | // The declaration of an identifier for a function that has | |||
7878 | // block scope shall have no explicit storage-class specifier | |||
7879 | // other than extern | |||
7880 | // See also (C++ [dcl.stc]p4). | |||
7881 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
7882 | diag::err_static_block_func); | |||
7883 | break; | |||
7884 | } else | |||
7885 | return SC_Static; | |||
7886 | } | |||
7887 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | |||
7888 | } | |||
7889 | ||||
7890 | // No explicit storage class has already been returned | |||
7891 | return SC_None; | |||
7892 | } | |||
7893 | ||||
7894 | static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, | |||
7895 | DeclContext *DC, QualType &R, | |||
7896 | TypeSourceInfo *TInfo, | |||
7897 | StorageClass SC, | |||
7898 | bool &IsVirtualOkay) { | |||
7899 | DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); | |||
7900 | DeclarationName Name = NameInfo.getName(); | |||
7901 | ||||
7902 | FunctionDecl *NewFD = nullptr; | |||
7903 | bool isInline = D.getDeclSpec().isInlineSpecified(); | |||
7904 | ||||
7905 | if (!SemaRef.getLangOpts().CPlusPlus) { | |||
7906 | // Determine whether the function was written with a | |||
7907 | // prototype. This true when: | |||
7908 | // - there is a prototype in the declarator, or | |||
7909 | // - the type R of the function is some kind of typedef or other non- | |||
7910 | // attributed reference to a type name (which eventually refers to a | |||
7911 | // function type). | |||
7912 | bool HasPrototype = | |||
7913 | (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || | |||
7914 | (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); | |||
7915 | ||||
7916 | NewFD = FunctionDecl::Create(SemaRef.Context, DC, | |||
7917 | D.getLocStart(), NameInfo, R, | |||
7918 | TInfo, SC, isInline, | |||
7919 | HasPrototype, false); | |||
7920 | if (D.isInvalidType()) | |||
7921 | NewFD->setInvalidDecl(); | |||
7922 | ||||
7923 | return NewFD; | |||
7924 | } | |||
7925 | ||||
7926 | bool isExplicit = D.getDeclSpec().isExplicitSpecified(); | |||
7927 | bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); | |||
7928 | ||||
7929 | // Check that the return type is not an abstract class type. | |||
7930 | // For record types, this is done by the AbstractClassUsageDiagnoser once | |||
7931 | // the class has been completely parsed. | |||
7932 | if (!DC->isRecord() && | |||
7933 | SemaRef.RequireNonAbstractType( | |||
7934 | D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), | |||
7935 | diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) | |||
7936 | D.setInvalidType(); | |||
7937 | ||||
7938 | if (Name.getNameKind() == DeclarationName::CXXConstructorName) { | |||
7939 | // This is a C++ constructor declaration. | |||
7940 | assert(DC->isRecord() &&(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context" ) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 7941, __extension__ __PRETTY_FUNCTION__)) | |||
7941 | "Constructors can only be declared in a member context")(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context" ) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 7941, __extension__ __PRETTY_FUNCTION__)); | |||
7942 | ||||
7943 | R = SemaRef.CheckConstructorDeclarator(D, R, SC); | |||
7944 | return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), | |||
7945 | D.getLocStart(), NameInfo, | |||
7946 | R, TInfo, isExplicit, isInline, | |||
7947 | /*isImplicitlyDeclared=*/false, | |||
7948 | isConstexpr); | |||
7949 | ||||
7950 | } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | |||
7951 | // This is a C++ destructor declaration. | |||
7952 | if (DC->isRecord()) { | |||
7953 | R = SemaRef.CheckDestructorDeclarator(D, R, SC); | |||
7954 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); | |||
7955 | CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( | |||
7956 | SemaRef.Context, Record, | |||
7957 | D.getLocStart(), | |||
7958 | NameInfo, R, TInfo, isInline, | |||
7959 | /*isImplicitlyDeclared=*/false); | |||
7960 | ||||
7961 | // If the class is complete, then we now create the implicit exception | |||
7962 | // specification. If the class is incomplete or dependent, we can't do | |||
7963 | // it yet. | |||
7964 | if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && | |||
7965 | Record->getDefinition() && !Record->isBeingDefined() && | |||
7966 | R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { | |||
7967 | SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); | |||
7968 | } | |||
7969 | ||||
7970 | IsVirtualOkay = true; | |||
7971 | return NewDD; | |||
7972 | ||||
7973 | } else { | |||
7974 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); | |||
7975 | D.setInvalidType(); | |||
7976 | ||||
7977 | // Create a FunctionDecl to satisfy the function definition parsing | |||
7978 | // code path. | |||
7979 | return FunctionDecl::Create(SemaRef.Context, DC, | |||
7980 | D.getLocStart(), | |||
7981 | D.getIdentifierLoc(), Name, R, TInfo, | |||
7982 | SC, isInline, | |||
7983 | /*hasPrototype=*/true, isConstexpr); | |||
7984 | } | |||
7985 | ||||
7986 | } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | |||
7987 | if (!DC->isRecord()) { | |||
7988 | SemaRef.Diag(D.getIdentifierLoc(), | |||
7989 | diag::err_conv_function_not_member); | |||
7990 | return nullptr; | |||
7991 | } | |||
7992 | ||||
7993 | SemaRef.CheckConversionDeclarator(D, R, SC); | |||
7994 | IsVirtualOkay = true; | |||
7995 | return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), | |||
7996 | D.getLocStart(), NameInfo, | |||
7997 | R, TInfo, isInline, isExplicit, | |||
7998 | isConstexpr, SourceLocation()); | |||
7999 | ||||
8000 | } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { | |||
8001 | SemaRef.CheckDeductionGuideDeclarator(D, R, SC); | |||
8002 | ||||
8003 | return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), | |||
8004 | isExplicit, NameInfo, R, TInfo, | |||
8005 | D.getLocEnd()); | |||
8006 | } else if (DC->isRecord()) { | |||
8007 | // If the name of the function is the same as the name of the record, | |||
8008 | // then this must be an invalid constructor that has a return type. | |||
8009 | // (The parser checks for a return type and makes the declarator a | |||
8010 | // constructor if it has no return type). | |||
8011 | if (Name.getAsIdentifierInfo() && | |||
8012 | Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ | |||
8013 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) | |||
8014 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | |||
8015 | << SourceRange(D.getIdentifierLoc()); | |||
8016 | return nullptr; | |||
8017 | } | |||
8018 | ||||
8019 | // This is a C++ method declaration. | |||
8020 | CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, | |||
8021 | cast<CXXRecordDecl>(DC), | |||
8022 | D.getLocStart(), NameInfo, R, | |||
8023 | TInfo, SC, isInline, | |||
8024 | isConstexpr, SourceLocation()); | |||
8025 | IsVirtualOkay = !Ret->isStatic(); | |||
8026 | return Ret; | |||
8027 | } else { | |||
8028 | bool isFriend = | |||
8029 | SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); | |||
8030 | if (!isFriend && SemaRef.CurContext->isRecord()) | |||
8031 | return nullptr; | |||
8032 | ||||
8033 | // Determine whether the function was written with a | |||
8034 | // prototype. This true when: | |||
8035 | // - we're in C++ (where every function has a prototype), | |||
8036 | return FunctionDecl::Create(SemaRef.Context, DC, | |||
8037 | D.getLocStart(), | |||
8038 | NameInfo, R, TInfo, SC, isInline, | |||
8039 | true/*HasPrototype*/, isConstexpr); | |||
8040 | } | |||
8041 | } | |||
8042 | ||||
8043 | enum OpenCLParamType { | |||
8044 | ValidKernelParam, | |||
8045 | PtrPtrKernelParam, | |||
8046 | PtrKernelParam, | |||
8047 | InvalidAddrSpacePtrKernelParam, | |||
8048 | InvalidKernelParam, | |||
8049 | RecordKernelParam | |||
8050 | }; | |||
8051 | ||||
8052 | static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { | |||
8053 | if (PT->isPointerType()) { | |||
8054 | QualType PointeeType = PT->getPointeeType(); | |||
8055 | if (PointeeType->isPointerType()) | |||
8056 | return PtrPtrKernelParam; | |||
8057 | if (PointeeType.getAddressSpace() == LangAS::opencl_generic || | |||
8058 | PointeeType.getAddressSpace() == LangAS::opencl_private || | |||
8059 | PointeeType.getAddressSpace() == LangAS::Default) | |||
8060 | return InvalidAddrSpacePtrKernelParam; | |||
8061 | return PtrKernelParam; | |||
8062 | } | |||
8063 | ||||
8064 | // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can | |||
8065 | // be used as builtin types. | |||
8066 | ||||
8067 | if (PT->isImageType()) | |||
8068 | return PtrKernelParam; | |||
8069 | ||||
8070 | if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) | |||
8071 | return InvalidKernelParam; | |||
8072 | ||||
8073 | // OpenCL extension spec v1.2 s9.5: | |||
8074 | // This extension adds support for half scalar and vector types as built-in | |||
8075 | // types that can be used for arithmetic operations, conversions etc. | |||
8076 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) | |||
8077 | return InvalidKernelParam; | |||
8078 | ||||
8079 | if (PT->isRecordType()) | |||
8080 | return RecordKernelParam; | |||
8081 | ||||
8082 | return ValidKernelParam; | |||
8083 | } | |||
8084 | ||||
8085 | static void checkIsValidOpenCLKernelParameter( | |||
8086 | Sema &S, | |||
8087 | Declarator &D, | |||
8088 | ParmVarDecl *Param, | |||
8089 | llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { | |||
8090 | QualType PT = Param->getType(); | |||
8091 | ||||
8092 | // Cache the valid types we encounter to avoid rechecking structs that are | |||
8093 | // used again | |||
8094 | if (ValidTypes.count(PT.getTypePtr())) | |||
8095 | return; | |||
8096 | ||||
8097 | switch (getOpenCLKernelParameterType(S, PT)) { | |||
8098 | case PtrPtrKernelParam: | |||
8099 | // OpenCL v1.2 s6.9.a: | |||
8100 | // A kernel function argument cannot be declared as a | |||
8101 | // pointer to a pointer type. | |||
8102 | S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); | |||
8103 | D.setInvalidType(); | |||
8104 | return; | |||
8105 | ||||
8106 | case InvalidAddrSpacePtrKernelParam: | |||
8107 | // OpenCL v1.0 s6.5: | |||
8108 | // __kernel function arguments declared to be a pointer of a type can point | |||
8109 | // to one of the following address spaces only : __global, __local or | |||
8110 | // __constant. | |||
8111 | S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); | |||
8112 | D.setInvalidType(); | |||
8113 | return; | |||
8114 | ||||
8115 | // OpenCL v1.2 s6.9.k: | |||
8116 | // Arguments to kernel functions in a program cannot be declared with the | |||
8117 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | |||
8118 | // uintptr_t or a struct and/or union that contain fields declared to be | |||
8119 | // one of these built-in scalar types. | |||
8120 | ||||
8121 | case InvalidKernelParam: | |||
8122 | // OpenCL v1.2 s6.8 n: | |||
8123 | // A kernel function argument cannot be declared | |||
8124 | // of event_t type. | |||
8125 | // Do not diagnose half type since it is diagnosed as invalid argument | |||
8126 | // type for any function elsewhere. | |||
8127 | if (!PT->isHalfType()) | |||
8128 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | |||
8129 | D.setInvalidType(); | |||
8130 | return; | |||
8131 | ||||
8132 | case PtrKernelParam: | |||
8133 | case ValidKernelParam: | |||
8134 | ValidTypes.insert(PT.getTypePtr()); | |||
8135 | return; | |||
8136 | ||||
8137 | case RecordKernelParam: | |||
8138 | break; | |||
8139 | } | |||
8140 | ||||
8141 | // Track nested structs we will inspect | |||
8142 | SmallVector<const Decl *, 4> VisitStack; | |||
8143 | ||||
8144 | // Track where we are in the nested structs. Items will migrate from | |||
8145 | // VisitStack to HistoryStack as we do the DFS for bad field. | |||
8146 | SmallVector<const FieldDecl *, 4> HistoryStack; | |||
8147 | HistoryStack.push_back(nullptr); | |||
8148 | ||||
8149 | const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); | |||
8150 | VisitStack.push_back(PD); | |||
8151 | ||||
8152 | assert(VisitStack.back() && "First decl null?")(static_cast <bool> (VisitStack.back() && "First decl null?" ) ? void (0) : __assert_fail ("VisitStack.back() && \"First decl null?\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8152, __extension__ __PRETTY_FUNCTION__)); | |||
8153 | ||||
8154 | do { | |||
8155 | const Decl *Next = VisitStack.pop_back_val(); | |||
8156 | if (!Next) { | |||
8157 | assert(!HistoryStack.empty())(static_cast <bool> (!HistoryStack.empty()) ? void (0) : __assert_fail ("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8157, __extension__ __PRETTY_FUNCTION__)); | |||
8158 | // Found a marker, we have gone up a level | |||
8159 | if (const FieldDecl *Hist = HistoryStack.pop_back_val()) | |||
8160 | ValidTypes.insert(Hist->getType().getTypePtr()); | |||
8161 | ||||
8162 | continue; | |||
8163 | } | |||
8164 | ||||
8165 | // Adds everything except the original parameter declaration (which is not a | |||
8166 | // field itself) to the history stack. | |||
8167 | const RecordDecl *RD; | |||
8168 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { | |||
8169 | HistoryStack.push_back(Field); | |||
8170 | RD = Field->getType()->castAs<RecordType>()->getDecl(); | |||
8171 | } else { | |||
8172 | RD = cast<RecordDecl>(Next); | |||
8173 | } | |||
8174 | ||||
8175 | // Add a null marker so we know when we've gone back up a level | |||
8176 | VisitStack.push_back(nullptr); | |||
8177 | ||||
8178 | for (const auto *FD : RD->fields()) { | |||
8179 | QualType QT = FD->getType(); | |||
8180 | ||||
8181 | if (ValidTypes.count(QT.getTypePtr())) | |||
8182 | continue; | |||
8183 | ||||
8184 | OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); | |||
8185 | if (ParamType == ValidKernelParam) | |||
8186 | continue; | |||
8187 | ||||
8188 | if (ParamType == RecordKernelParam) { | |||
8189 | VisitStack.push_back(FD); | |||
8190 | continue; | |||
8191 | } | |||
8192 | ||||
8193 | // OpenCL v1.2 s6.9.p: | |||
8194 | // Arguments to kernel functions that are declared to be a struct or union | |||
8195 | // do not allow OpenCL objects to be passed as elements of the struct or | |||
8196 | // union. | |||
8197 | if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || | |||
8198 | ParamType == InvalidAddrSpacePtrKernelParam) { | |||
8199 | S.Diag(Param->getLocation(), | |||
8200 | diag::err_record_with_pointers_kernel_param) | |||
8201 | << PT->isUnionType() | |||
8202 | << PT; | |||
8203 | } else { | |||
8204 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | |||
8205 | } | |||
8206 | ||||
8207 | S.Diag(PD->getLocation(), diag::note_within_field_of_type) | |||
8208 | << PD->getDeclName(); | |||
8209 | ||||
8210 | // We have an error, now let's go back up through history and show where | |||
8211 | // the offending field came from | |||
8212 | for (ArrayRef<const FieldDecl *>::const_iterator | |||
8213 | I = HistoryStack.begin() + 1, | |||
8214 | E = HistoryStack.end(); | |||
8215 | I != E; ++I) { | |||
8216 | const FieldDecl *OuterField = *I; | |||
8217 | S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) | |||
8218 | << OuterField->getType(); | |||
8219 | } | |||
8220 | ||||
8221 | S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) | |||
8222 | << QT->isPointerType() | |||
8223 | << QT; | |||
8224 | D.setInvalidType(); | |||
8225 | return; | |||
8226 | } | |||
8227 | } while (!VisitStack.empty()); | |||
8228 | } | |||
8229 | ||||
8230 | /// Find the DeclContext in which a tag is implicitly declared if we see an | |||
8231 | /// elaborated type specifier in the specified context, and lookup finds | |||
8232 | /// nothing. | |||
8233 | static DeclContext *getTagInjectionContext(DeclContext *DC) { | |||
8234 | while (!DC->isFileContext() && !DC->isFunctionOrMethod()) | |||
8235 | DC = DC->getParent(); | |||
8236 | return DC; | |||
8237 | } | |||
8238 | ||||
8239 | /// Find the Scope in which a tag is implicitly declared if we see an | |||
8240 | /// elaborated type specifier in the specified context, and lookup finds | |||
8241 | /// nothing. | |||
8242 | static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { | |||
8243 | while (S->isClassScope() || | |||
8244 | (LangOpts.CPlusPlus && | |||
8245 | S->isFunctionPrototypeScope()) || | |||
8246 | ((S->getFlags() & Scope::DeclScope) == 0) || | |||
8247 | (S->getEntity() && S->getEntity()->isTransparentContext())) | |||
8248 | S = S->getParent(); | |||
8249 | return S; | |||
8250 | } | |||
8251 | ||||
8252 | NamedDecl* | |||
8253 | Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, | |||
8254 | TypeSourceInfo *TInfo, LookupResult &Previous, | |||
8255 | MultiTemplateParamsArg TemplateParamLists, | |||
8256 | bool &AddToScope) { | |||
8257 | QualType R = TInfo->getType(); | |||
8258 | ||||
8259 | assert(R->isFunctionType())(static_cast <bool> (R->isFunctionType()) ? void (0) : __assert_fail ("R->isFunctionType()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8259, __extension__ __PRETTY_FUNCTION__)); | |||
8260 | ||||
8261 | // TODO: consider using NameInfo for diagnostic. | |||
8262 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | |||
8263 | DeclarationName Name = NameInfo.getName(); | |||
8264 | StorageClass SC = getFunctionStorageClass(*this, D); | |||
8265 | ||||
8266 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | |||
8267 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
8268 | diag::err_invalid_thread) | |||
8269 | << DeclSpec::getSpecifierName(TSCS); | |||
8270 | ||||
8271 | if (D.isFirstDeclarationOfMember()) | |||
8272 | adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), | |||
8273 | D.getIdentifierLoc()); | |||
8274 | ||||
8275 | bool isFriend = false; | |||
8276 | FunctionTemplateDecl *FunctionTemplate = nullptr; | |||
8277 | bool isMemberSpecialization = false; | |||
8278 | bool isFunctionTemplateSpecialization = false; | |||
8279 | ||||
8280 | bool isDependentClassScopeExplicitSpecialization = false; | |||
8281 | bool HasExplicitTemplateArgs = false; | |||
8282 | TemplateArgumentListInfo TemplateArgs; | |||
8283 | ||||
8284 | bool isVirtualOkay = false; | |||
8285 | ||||
8286 | DeclContext *OriginalDC = DC; | |||
8287 | bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); | |||
8288 | ||||
8289 | FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, | |||
8290 | isVirtualOkay); | |||
8291 | if (!NewFD) return nullptr; | |||
8292 | ||||
8293 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) | |||
8294 | NewFD->setTopLevelDeclInObjCContainer(); | |||
8295 | ||||
8296 | // Set the lexical context. If this is a function-scope declaration, or has a | |||
8297 | // C++ scope specifier, or is the object of a friend declaration, the lexical | |||
8298 | // context will be different from the semantic context. | |||
8299 | NewFD->setLexicalDeclContext(CurContext); | |||
8300 | ||||
8301 | if (IsLocalExternDecl) | |||
8302 | NewFD->setLocalExternDecl(); | |||
8303 | ||||
8304 | if (getLangOpts().CPlusPlus) { | |||
8305 | bool isInline = D.getDeclSpec().isInlineSpecified(); | |||
8306 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | |||
8307 | bool isExplicit = D.getDeclSpec().isExplicitSpecified(); | |||
8308 | bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); | |||
8309 | isFriend = D.getDeclSpec().isFriendSpecified(); | |||
8310 | if (isFriend && !isInline && D.isFunctionDefinition()) { | |||
8311 | // C++ [class.friend]p5 | |||
8312 | // A function can be defined in a friend declaration of a | |||
8313 | // class . . . . Such a function is implicitly inline. | |||
8314 | NewFD->setImplicitlyInline(); | |||
8315 | } | |||
8316 | ||||
8317 | // If this is a method defined in an __interface, and is not a constructor | |||
8318 | // or an overloaded operator, then set the pure flag (isVirtual will already | |||
8319 | // return true). | |||
8320 | if (const CXXRecordDecl *Parent = | |||
8321 | dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { | |||
8322 | if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) | |||
8323 | NewFD->setPure(true); | |||
8324 | ||||
8325 | // C++ [class.union]p2 | |||
8326 | // A union can have member functions, but not virtual functions. | |||
8327 | if (isVirtual && Parent->isUnion()) | |||
8328 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); | |||
8329 | } | |||
8330 | ||||
8331 | SetNestedNameSpecifier(NewFD, D); | |||
8332 | isMemberSpecialization = false; | |||
8333 | isFunctionTemplateSpecialization = false; | |||
8334 | if (D.isInvalidType()) | |||
8335 | NewFD->setInvalidDecl(); | |||
8336 | ||||
8337 | // Match up the template parameter lists with the scope specifier, then | |||
8338 | // determine whether we have a template or a template specialization. | |||
8339 | bool Invalid = false; | |||
8340 | if (TemplateParameterList *TemplateParams = | |||
8341 | MatchTemplateParametersToScopeSpecifier( | |||
8342 | D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), | |||
8343 | D.getCXXScopeSpec(), | |||
8344 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | |||
8345 | ? D.getName().TemplateId | |||
8346 | : nullptr, | |||
8347 | TemplateParamLists, isFriend, isMemberSpecialization, | |||
8348 | Invalid)) { | |||
8349 | if (TemplateParams->size() > 0) { | |||
8350 | // This is a function template | |||
8351 | ||||
8352 | // Check that we can declare a template here. | |||
8353 | if (CheckTemplateDeclScope(S, TemplateParams)) | |||
8354 | NewFD->setInvalidDecl(); | |||
8355 | ||||
8356 | // A destructor cannot be a template. | |||
8357 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | |||
8358 | Diag(NewFD->getLocation(), diag::err_destructor_template); | |||
8359 | NewFD->setInvalidDecl(); | |||
8360 | } | |||
8361 | ||||
8362 | // If we're adding a template to a dependent context, we may need to | |||
8363 | // rebuilding some of the types used within the template parameter list, | |||
8364 | // now that we know what the current instantiation is. | |||
8365 | if (DC->isDependentContext()) { | |||
8366 | ContextRAII SavedContext(*this, DC); | |||
8367 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) | |||
8368 | Invalid = true; | |||
8369 | } | |||
8370 | ||||
8371 | FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, | |||
8372 | NewFD->getLocation(), | |||
8373 | Name, TemplateParams, | |||
8374 | NewFD); | |||
8375 | FunctionTemplate->setLexicalDeclContext(CurContext); | |||
8376 | NewFD->setDescribedFunctionTemplate(FunctionTemplate); | |||
8377 | ||||
8378 | // For source fidelity, store the other template param lists. | |||
8379 | if (TemplateParamLists.size() > 1) { | |||
8380 | NewFD->setTemplateParameterListsInfo(Context, | |||
8381 | TemplateParamLists.drop_back(1)); | |||
8382 | } | |||
8383 | } else { | |||
8384 | // This is a function template specialization. | |||
8385 | isFunctionTemplateSpecialization = true; | |||
8386 | // For source fidelity, store all the template param lists. | |||
8387 | if (TemplateParamLists.size() > 0) | |||
8388 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | |||
8389 | ||||
8390 | // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". | |||
8391 | if (isFriend) { | |||
8392 | // We want to remove the "template<>", found here. | |||
8393 | SourceRange RemoveRange = TemplateParams->getSourceRange(); | |||
8394 | ||||
8395 | // If we remove the template<> and the name is not a | |||
8396 | // template-id, we're actually silently creating a problem: | |||
8397 | // the friend declaration will refer to an untemplated decl, | |||
8398 | // and clearly the user wants a template specialization. So | |||
8399 | // we need to insert '<>' after the name. | |||
8400 | SourceLocation InsertLoc; | |||
8401 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | |||
8402 | InsertLoc = D.getName().getSourceRange().getEnd(); | |||
8403 | InsertLoc = getLocForEndOfToken(InsertLoc); | |||
8404 | } | |||
8405 | ||||
8406 | Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) | |||
8407 | << Name << RemoveRange | |||
8408 | << FixItHint::CreateRemoval(RemoveRange) | |||
8409 | << FixItHint::CreateInsertion(InsertLoc, "<>"); | |||
8410 | } | |||
8411 | } | |||
8412 | } | |||
8413 | else { | |||
8414 | // All template param lists were matched against the scope specifier: | |||
8415 | // this is NOT (an explicit specialization of) a template. | |||
8416 | if (TemplateParamLists.size() > 0) | |||
8417 | // For source fidelity, store all the template param lists. | |||
8418 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | |||
8419 | } | |||
8420 | ||||
8421 | if (Invalid) { | |||
8422 | NewFD->setInvalidDecl(); | |||
8423 | if (FunctionTemplate) | |||
8424 | FunctionTemplate->setInvalidDecl(); | |||
8425 | } | |||
8426 | ||||
8427 | // C++ [dcl.fct.spec]p5: | |||
8428 | // The virtual specifier shall only be used in declarations of | |||
8429 | // nonstatic class member functions that appear within a | |||
8430 | // member-specification of a class declaration; see 10.3. | |||
8431 | // | |||
8432 | if (isVirtual && !NewFD->isInvalidDecl()) { | |||
8433 | if (!isVirtualOkay) { | |||
8434 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | |||
8435 | diag::err_virtual_non_function); | |||
8436 | } else if (!CurContext->isRecord()) { | |||
8437 | // 'virtual' was specified outside of the class. | |||
8438 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | |||
8439 | diag::err_virtual_out_of_class) | |||
8440 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | |||
8441 | } else if (NewFD->getDescribedFunctionTemplate()) { | |||
8442 | // C++ [temp.mem]p3: | |||
8443 | // A member function template shall not be virtual. | |||
8444 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | |||
8445 | diag::err_virtual_member_function_template) | |||
8446 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | |||
8447 | } else { | |||
8448 | // Okay: Add virtual to the method. | |||
8449 | NewFD->setVirtualAsWritten(true); | |||
8450 | } | |||
8451 | ||||
8452 | if (getLangOpts().CPlusPlus14 && | |||
8453 | NewFD->getReturnType()->isUndeducedType()) | |||
8454 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); | |||
8455 | } | |||
8456 | ||||
8457 | if (getLangOpts().CPlusPlus14 && | |||
8458 | (NewFD->isDependentContext() || | |||
8459 | (isFriend && CurContext->isDependentContext())) && | |||
8460 | NewFD->getReturnType()->isUndeducedType()) { | |||
8461 | // If the function template is referenced directly (for instance, as a | |||
8462 | // member of the current instantiation), pretend it has a dependent type. | |||
8463 | // This is not really justified by the standard, but is the only sane | |||
8464 | // thing to do. | |||
8465 | // FIXME: For a friend function, we have not marked the function as being | |||
8466 | // a friend yet, so 'isDependentContext' on the FD doesn't work. | |||
8467 | const FunctionProtoType *FPT = | |||
8468 | NewFD->getType()->castAs<FunctionProtoType>(); | |||
8469 | QualType Result = | |||
8470 | SubstAutoType(FPT->getReturnType(), Context.DependentTy); | |||
8471 | NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), | |||
8472 | FPT->getExtProtoInfo())); | |||
8473 | } | |||
8474 | ||||
8475 | // C++ [dcl.fct.spec]p3: | |||
8476 | // The inline specifier shall not appear on a block scope function | |||
8477 | // declaration. | |||
8478 | if (isInline && !NewFD->isInvalidDecl()) { | |||
8479 | if (CurContext->isFunctionOrMethod()) { | |||
8480 | // 'inline' is not allowed on block scope function declaration. | |||
8481 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
8482 | diag::err_inline_declaration_block_scope) << Name | |||
8483 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | |||
8484 | } | |||
8485 | } | |||
8486 | ||||
8487 | // C++ [dcl.fct.spec]p6: | |||
8488 | // The explicit specifier shall be used only in the declaration of a | |||
8489 | // constructor or conversion function within its class definition; | |||
8490 | // see 12.3.1 and 12.3.2. | |||
8491 | if (isExplicit && !NewFD->isInvalidDecl() && | |||
8492 | !isa<CXXDeductionGuideDecl>(NewFD)) { | |||
8493 | if (!CurContext->isRecord()) { | |||
8494 | // 'explicit' was specified outside of the class. | |||
8495 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | |||
8496 | diag::err_explicit_out_of_class) | |||
8497 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); | |||
8498 | } else if (!isa<CXXConstructorDecl>(NewFD) && | |||
8499 | !isa<CXXConversionDecl>(NewFD)) { | |||
8500 | // 'explicit' was specified on a function that wasn't a constructor | |||
8501 | // or conversion function. | |||
8502 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | |||
8503 | diag::err_explicit_non_ctor_or_conv_function) | |||
8504 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); | |||
8505 | } | |||
8506 | } | |||
8507 | ||||
8508 | if (isConstexpr) { | |||
8509 | // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors | |||
8510 | // are implicitly inline. | |||
8511 | NewFD->setImplicitlyInline(); | |||
8512 | ||||
8513 | // C++11 [dcl.constexpr]p3: functions declared constexpr are required to | |||
8514 | // be either constructors or to return a literal type. Therefore, | |||
8515 | // destructors cannot be declared constexpr. | |||
8516 | if (isa<CXXDestructorDecl>(NewFD)) | |||
8517 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); | |||
8518 | } | |||
8519 | ||||
8520 | // If __module_private__ was specified, mark the function accordingly. | |||
8521 | if (D.getDeclSpec().isModulePrivateSpecified()) { | |||
8522 | if (isFunctionTemplateSpecialization) { | |||
8523 | SourceLocation ModulePrivateLoc | |||
8524 | = D.getDeclSpec().getModulePrivateSpecLoc(); | |||
8525 | Diag(ModulePrivateLoc, diag::err_module_private_specialization) | |||
8526 | << 0 | |||
8527 | << FixItHint::CreateRemoval(ModulePrivateLoc); | |||
8528 | } else { | |||
8529 | NewFD->setModulePrivate(); | |||
8530 | if (FunctionTemplate) | |||
8531 | FunctionTemplate->setModulePrivate(); | |||
8532 | } | |||
8533 | } | |||
8534 | ||||
8535 | if (isFriend) { | |||
8536 | if (FunctionTemplate) { | |||
8537 | FunctionTemplate->setObjectOfFriendDecl(); | |||
8538 | FunctionTemplate->setAccess(AS_public); | |||
8539 | } | |||
8540 | NewFD->setObjectOfFriendDecl(); | |||
8541 | NewFD->setAccess(AS_public); | |||
8542 | } | |||
8543 | ||||
8544 | // If a function is defined as defaulted or deleted, mark it as such now. | |||
8545 | // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function | |||
8546 | // definition kind to FDK_Definition. | |||
8547 | switch (D.getFunctionDefinitionKind()) { | |||
8548 | case FDK_Declaration: | |||
8549 | case FDK_Definition: | |||
8550 | break; | |||
8551 | ||||
8552 | case FDK_Defaulted: | |||
8553 | NewFD->setDefaulted(); | |||
8554 | break; | |||
8555 | ||||
8556 | case FDK_Deleted: | |||
8557 | NewFD->setDeletedAsWritten(); | |||
8558 | break; | |||
8559 | } | |||
8560 | ||||
8561 | if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && | |||
8562 | D.isFunctionDefinition()) { | |||
8563 | // C++ [class.mfct]p2: | |||
8564 | // A member function may be defined (8.4) in its class definition, in | |||
8565 | // which case it is an inline member function (7.1.2) | |||
8566 | NewFD->setImplicitlyInline(); | |||
8567 | } | |||
8568 | ||||
8569 | if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && | |||
8570 | !CurContext->isRecord()) { | |||
8571 | // C++ [class.static]p1: | |||
8572 | // A data or function member of a class may be declared static | |||
8573 | // in a class definition, in which case it is a static member of | |||
8574 | // the class. | |||
8575 | ||||
8576 | // Complain about the 'static' specifier if it's on an out-of-line | |||
8577 | // member function definition. | |||
8578 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
8579 | diag::err_static_out_of_line) | |||
8580 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
8581 | } | |||
8582 | ||||
8583 | // C++11 [except.spec]p15: | |||
8584 | // A deallocation function with no exception-specification is treated | |||
8585 | // as if it were specified with noexcept(true). | |||
8586 | const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); | |||
8587 | if ((Name.getCXXOverloadedOperator() == OO_Delete || | |||
8588 | Name.getCXXOverloadedOperator() == OO_Array_Delete) && | |||
8589 | getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) | |||
8590 | NewFD->setType(Context.getFunctionType( | |||
8591 | FPT->getReturnType(), FPT->getParamTypes(), | |||
8592 | FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); | |||
8593 | } | |||
8594 | ||||
8595 | // Filter out previous declarations that don't match the scope. | |||
8596 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), | |||
8597 | D.getCXXScopeSpec().isNotEmpty() || | |||
8598 | isMemberSpecialization || | |||
8599 | isFunctionTemplateSpecialization); | |||
8600 | ||||
8601 | // Handle GNU asm-label extension (encoded as an attribute). | |||
8602 | if (Expr *E = (Expr*) D.getAsmLabel()) { | |||
8603 | // The parser guarantees this is a string. | |||
8604 | StringLiteral *SE = cast<StringLiteral>(E); | |||
8605 | NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, | |||
8606 | SE->getString(), 0)); | |||
8607 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | |||
8608 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | |||
8609 | ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); | |||
8610 | if (I != ExtnameUndeclaredIdentifiers.end()) { | |||
8611 | if (isDeclExternC(NewFD)) { | |||
8612 | NewFD->addAttr(I->second); | |||
8613 | ExtnameUndeclaredIdentifiers.erase(I); | |||
8614 | } else | |||
8615 | Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) | |||
8616 | << /*Variable*/0 << NewFD; | |||
8617 | } | |||
8618 | } | |||
8619 | ||||
8620 | // Copy the parameter declarations from the declarator D to the function | |||
8621 | // declaration NewFD, if they are available. First scavenge them into Params. | |||
8622 | SmallVector<ParmVarDecl*, 16> Params; | |||
8623 | unsigned FTIIdx; | |||
8624 | if (D.isFunctionDeclarator(FTIIdx)) { | |||
8625 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; | |||
8626 | ||||
8627 | // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs | |||
8628 | // function that takes no arguments, not a function that takes a | |||
8629 | // single void argument. | |||
8630 | // We let through "const void" here because Sema::GetTypeForDeclarator | |||
8631 | // already checks for that case. | |||
8632 | if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { | |||
8633 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | |||
8634 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
8635 | assert(Param->getDeclContext() != NewFD && "Was set before ?")(static_cast <bool> (Param->getDeclContext() != NewFD && "Was set before ?") ? void (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8635, __extension__ __PRETTY_FUNCTION__)); | |||
8636 | Param->setDeclContext(NewFD); | |||
8637 | Params.push_back(Param); | |||
8638 | ||||
8639 | if (Param->isInvalidDecl()) | |||
8640 | NewFD->setInvalidDecl(); | |||
8641 | } | |||
8642 | } | |||
8643 | ||||
8644 | if (!getLangOpts().CPlusPlus) { | |||
8645 | // In C, find all the tag declarations from the prototype and move them | |||
8646 | // into the function DeclContext. Remove them from the surrounding tag | |||
8647 | // injection context of the function, which is typically but not always | |||
8648 | // the TU. | |||
8649 | DeclContext *PrototypeTagContext = | |||
8650 | getTagInjectionContext(NewFD->getLexicalDeclContext()); | |||
8651 | for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { | |||
8652 | auto *TD = dyn_cast<TagDecl>(NonParmDecl); | |||
8653 | ||||
8654 | // We don't want to reparent enumerators. Look at their parent enum | |||
8655 | // instead. | |||
8656 | if (!TD) { | |||
8657 | if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) | |||
8658 | TD = cast<EnumDecl>(ECD->getDeclContext()); | |||
8659 | } | |||
8660 | if (!TD) | |||
8661 | continue; | |||
8662 | DeclContext *TagDC = TD->getLexicalDeclContext(); | |||
8663 | if (!TagDC->containsDecl(TD)) | |||
8664 | continue; | |||
8665 | TagDC->removeDecl(TD); | |||
8666 | TD->setDeclContext(NewFD); | |||
8667 | NewFD->addDecl(TD); | |||
8668 | ||||
8669 | // Preserve the lexical DeclContext if it is not the surrounding tag | |||
8670 | // injection context of the FD. In this example, the semantic context of | |||
8671 | // E will be f and the lexical context will be S, while both the | |||
8672 | // semantic and lexical contexts of S will be f: | |||
8673 | // void f(struct S { enum E { a } f; } s); | |||
8674 | if (TagDC != PrototypeTagContext) | |||
8675 | TD->setLexicalDeclContext(TagDC); | |||
8676 | } | |||
8677 | } | |||
8678 | } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { | |||
8679 | // When we're declaring a function with a typedef, typeof, etc as in the | |||
8680 | // following example, we'll need to synthesize (unnamed) | |||
8681 | // parameters for use in the declaration. | |||
8682 | // | |||
8683 | // @code | |||
8684 | // typedef void fn(int); | |||
8685 | // fn f; | |||
8686 | // @endcode | |||
8687 | ||||
8688 | // Synthesize a parameter for each argument type. | |||
8689 | for (const auto &AI : FT->param_types()) { | |||
8690 | ParmVarDecl *Param = | |||
8691 | BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); | |||
8692 | Param->setScopeInfo(0, Params.size()); | |||
8693 | Params.push_back(Param); | |||
8694 | } | |||
8695 | } else { | |||
8696 | assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&(static_cast <bool> (R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn" ) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8697, __extension__ __PRETTY_FUNCTION__)) | |||
8697 | "Should not need args for typedef of non-prototype fn")(static_cast <bool> (R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn" ) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8697, __extension__ __PRETTY_FUNCTION__)); | |||
8698 | } | |||
8699 | ||||
8700 | // Finally, we know we have the right number of parameters, install them. | |||
8701 | NewFD->setParams(Params); | |||
8702 | ||||
8703 | if (D.getDeclSpec().isNoreturnSpecified()) | |||
8704 | NewFD->addAttr( | |||
8705 | ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), | |||
8706 | Context, 0)); | |||
8707 | ||||
8708 | // Functions returning a variably modified type violate C99 6.7.5.2p2 | |||
8709 | // because all functions have linkage. | |||
8710 | if (!NewFD->isInvalidDecl() && | |||
8711 | NewFD->getReturnType()->isVariablyModifiedType()) { | |||
8712 | Diag(NewFD->getLocation(), diag::err_vm_func_decl); | |||
8713 | NewFD->setInvalidDecl(); | |||
8714 | } | |||
8715 | ||||
8716 | // Apply an implicit SectionAttr if '#pragma clang section text' is active | |||
8717 | if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && | |||
8718 | !NewFD->hasAttr<SectionAttr>()) { | |||
8719 | NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, | |||
8720 | PragmaClangTextSection.SectionName, | |||
8721 | PragmaClangTextSection.PragmaLocation)); | |||
8722 | } | |||
8723 | ||||
8724 | // Apply an implicit SectionAttr if #pragma code_seg is active. | |||
8725 | if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && | |||
8726 | !NewFD->hasAttr<SectionAttr>()) { | |||
8727 | NewFD->addAttr( | |||
8728 | SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, | |||
8729 | CodeSegStack.CurrentValue->getString(), | |||
8730 | CodeSegStack.CurrentPragmaLocation)); | |||
8731 | if (UnifySection(CodeSegStack.CurrentValue->getString(), | |||
8732 | ASTContext::PSF_Implicit | ASTContext::PSF_Execute | | |||
8733 | ASTContext::PSF_Read, | |||
8734 | NewFD)) | |||
8735 | NewFD->dropAttr<SectionAttr>(); | |||
8736 | } | |||
8737 | ||||
8738 | // Apply an implicit CodeSegAttr from class declspec or | |||
8739 | // apply an implicit SectionAttr from #pragma code_seg if active. | |||
8740 | if (!NewFD->hasAttr<CodeSegAttr>()) { | |||
8741 | if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, | |||
8742 | D.isFunctionDefinition())) { | |||
8743 | NewFD->addAttr(SAttr); | |||
8744 | } | |||
8745 | } | |||
8746 | ||||
8747 | // Handle attributes. | |||
8748 | ProcessDeclAttributes(S, NewFD, D); | |||
8749 | ||||
8750 | if (getLangOpts().OpenCL) { | |||
8751 | // OpenCL v1.1 s6.5: Using an address space qualifier in a function return | |||
8752 | // type declaration will generate a compilation error. | |||
8753 | LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); | |||
8754 | if (AddressSpace != LangAS::Default) { | |||
8755 | Diag(NewFD->getLocation(), | |||
8756 | diag::err_opencl_return_value_with_address_space); | |||
8757 | NewFD->setInvalidDecl(); | |||
8758 | } | |||
8759 | } | |||
8760 | ||||
8761 | if (!getLangOpts().CPlusPlus) { | |||
8762 | // Perform semantic checking on the function declaration. | |||
8763 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | |||
8764 | CheckMain(NewFD, D.getDeclSpec()); | |||
8765 | ||||
8766 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | |||
8767 | CheckMSVCRTEntryPoint(NewFD); | |||
8768 | ||||
8769 | if (!NewFD->isInvalidDecl()) | |||
8770 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | |||
8771 | isMemberSpecialization)); | |||
8772 | else if (!Previous.empty()) | |||
8773 | // Recover gracefully from an invalid redeclaration. | |||
8774 | D.setRedeclaration(true); | |||
8775 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8777, __extension__ __PRETTY_FUNCTION__)) | |||
8776 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8777, __extension__ __PRETTY_FUNCTION__)) | |||
8777 | "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8777, __extension__ __PRETTY_FUNCTION__)); | |||
8778 | ||||
8779 | // Diagnose no-prototype function declarations with calling conventions that | |||
8780 | // don't support variadic calls. Only do this in C and do it after merging | |||
8781 | // possibly prototyped redeclarations. | |||
8782 | const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); | |||
8783 | if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { | |||
8784 | CallingConv CC = FT->getExtInfo().getCC(); | |||
8785 | if (!supportsVariadicCall(CC)) { | |||
8786 | // Windows system headers sometimes accidentally use stdcall without | |||
8787 | // (void) parameters, so we relax this to a warning. | |||
8788 | int DiagID = | |||
8789 | CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; | |||
8790 | Diag(NewFD->getLocation(), DiagID) | |||
8791 | << FunctionType::getNameForCallConv(CC); | |||
8792 | } | |||
8793 | } | |||
8794 | } else { | |||
8795 | // C++11 [replacement.functions]p3: | |||
8796 | // The program's definitions shall not be specified as inline. | |||
8797 | // | |||
8798 | // N.B. We diagnose declarations instead of definitions per LWG issue 2340. | |||
8799 | // | |||
8800 | // Suppress the diagnostic if the function is __attribute__((used)), since | |||
8801 | // that forces an external definition to be emitted. | |||
8802 | if (D.getDeclSpec().isInlineSpecified() && | |||
8803 | NewFD->isReplaceableGlobalAllocationFunction() && | |||
8804 | !NewFD->hasAttr<UsedAttr>()) | |||
8805 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
8806 | diag::ext_operator_new_delete_declared_inline) | |||
8807 | << NewFD->getDeclName(); | |||
8808 | ||||
8809 | // If the declarator is a template-id, translate the parser's template | |||
8810 | // argument list into our AST format. | |||
8811 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | |||
8812 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; | |||
8813 | TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); | |||
8814 | TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); | |||
8815 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
8816 | TemplateId->NumArgs); | |||
8817 | translateTemplateArguments(TemplateArgsPtr, | |||
8818 | TemplateArgs); | |||
8819 | ||||
8820 | HasExplicitTemplateArgs = true; | |||
8821 | ||||
8822 | if (NewFD->isInvalidDecl()) { | |||
8823 | HasExplicitTemplateArgs = false; | |||
8824 | } else if (FunctionTemplate) { | |||
8825 | // Function template with explicit template arguments. | |||
8826 | Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) | |||
8827 | << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); | |||
8828 | ||||
8829 | HasExplicitTemplateArgs = false; | |||
8830 | } else { | |||
8831 | assert((isFunctionTemplateSpecialization ||(static_cast <bool> ((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8833, __extension__ __PRETTY_FUNCTION__)) | |||
8832 | D.getDeclSpec().isFriendSpecified()) &&(static_cast <bool> ((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8833, __extension__ __PRETTY_FUNCTION__)) | |||
8833 | "should have a 'template<>' for this decl")(static_cast <bool> ((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8833, __extension__ __PRETTY_FUNCTION__)); | |||
8834 | // "friend void foo<>(int);" is an implicit specialization decl. | |||
8835 | isFunctionTemplateSpecialization = true; | |||
8836 | } | |||
8837 | } else if (isFriend && isFunctionTemplateSpecialization) { | |||
8838 | // This combination is only possible in a recovery case; the user | |||
8839 | // wrote something like: | |||
8840 | // template <> friend void foo(int); | |||
8841 | // which we're recovering from as if the user had written: | |||
8842 | // friend void foo<>(int); | |||
8843 | // Go ahead and fake up a template id. | |||
8844 | HasExplicitTemplateArgs = true; | |||
8845 | TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); | |||
8846 | TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); | |||
8847 | } | |||
8848 | ||||
8849 | // We do not add HD attributes to specializations here because | |||
8850 | // they may have different constexpr-ness compared to their | |||
8851 | // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, | |||
8852 | // may end up with different effective targets. Instead, a | |||
8853 | // specialization inherits its target attributes from its template | |||
8854 | // in the CheckFunctionTemplateSpecialization() call below. | |||
8855 | if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) | |||
8856 | maybeAddCUDAHostDeviceAttrs(NewFD, Previous); | |||
8857 | ||||
8858 | // If it's a friend (and only if it's a friend), it's possible | |||
8859 | // that either the specialized function type or the specialized | |||
8860 | // template is dependent, and therefore matching will fail. In | |||
8861 | // this case, don't check the specialization yet. | |||
8862 | bool InstantiationDependent = false; | |||
8863 | if (isFunctionTemplateSpecialization && isFriend && | |||
8864 | (NewFD->getType()->isDependentType() || DC->isDependentContext() || | |||
8865 | TemplateSpecializationType::anyDependentTemplateArguments( | |||
8866 | TemplateArgs, | |||
8867 | InstantiationDependent))) { | |||
8868 | assert(HasExplicitTemplateArgs &&(static_cast <bool> (HasExplicitTemplateArgs && "friend function specialization without template args") ? void (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8869, __extension__ __PRETTY_FUNCTION__)) | |||
8869 | "friend function specialization without template args")(static_cast <bool> (HasExplicitTemplateArgs && "friend function specialization without template args") ? void (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8869, __extension__ __PRETTY_FUNCTION__)); | |||
8870 | if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, | |||
8871 | Previous)) | |||
8872 | NewFD->setInvalidDecl(); | |||
8873 | } else if (isFunctionTemplateSpecialization) { | |||
8874 | if (CurContext->isDependentContext() && CurContext->isRecord() | |||
8875 | && !isFriend) { | |||
8876 | isDependentClassScopeExplicitSpecialization = true; | |||
8877 | } else if (!NewFD->isInvalidDecl() && | |||
8878 | CheckFunctionTemplateSpecialization( | |||
8879 | NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), | |||
8880 | Previous)) | |||
8881 | NewFD->setInvalidDecl(); | |||
8882 | ||||
8883 | // C++ [dcl.stc]p1: | |||
8884 | // A storage-class-specifier shall not be specified in an explicit | |||
8885 | // specialization (14.7.3) | |||
8886 | FunctionTemplateSpecializationInfo *Info = | |||
8887 | NewFD->getTemplateSpecializationInfo(); | |||
8888 | if (Info && SC != SC_None) { | |||
8889 | if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) | |||
8890 | Diag(NewFD->getLocation(), | |||
8891 | diag::err_explicit_specialization_inconsistent_storage_class) | |||
8892 | << SC | |||
8893 | << FixItHint::CreateRemoval( | |||
8894 | D.getDeclSpec().getStorageClassSpecLoc()); | |||
8895 | ||||
8896 | else | |||
8897 | Diag(NewFD->getLocation(), | |||
8898 | diag::ext_explicit_specialization_storage_class) | |||
8899 | << FixItHint::CreateRemoval( | |||
8900 | D.getDeclSpec().getStorageClassSpecLoc()); | |||
8901 | } | |||
8902 | } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { | |||
8903 | if (CheckMemberSpecialization(NewFD, Previous)) | |||
8904 | NewFD->setInvalidDecl(); | |||
8905 | } | |||
8906 | ||||
8907 | // Perform semantic checking on the function declaration. | |||
8908 | if (!isDependentClassScopeExplicitSpecialization) { | |||
8909 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | |||
8910 | CheckMain(NewFD, D.getDeclSpec()); | |||
8911 | ||||
8912 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | |||
8913 | CheckMSVCRTEntryPoint(NewFD); | |||
8914 | ||||
8915 | if (!NewFD->isInvalidDecl()) | |||
8916 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | |||
8917 | isMemberSpecialization)); | |||
8918 | else if (!Previous.empty()) | |||
8919 | // Recover gracefully from an invalid redeclaration. | |||
8920 | D.setRedeclaration(true); | |||
8921 | } | |||
8922 | ||||
8923 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8925, __extension__ __PRETTY_FUNCTION__)) | |||
8924 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8925, __extension__ __PRETTY_FUNCTION__)) | |||
8925 | "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 8925, __extension__ __PRETTY_FUNCTION__)); | |||
8926 | ||||
8927 | NamedDecl *PrincipalDecl = (FunctionTemplate | |||
8928 | ? cast<NamedDecl>(FunctionTemplate) | |||
8929 | : NewFD); | |||
8930 | ||||
8931 | if (isFriend && NewFD->getPreviousDecl()) { | |||
8932 | AccessSpecifier Access = AS_public; | |||
8933 | if (!NewFD->isInvalidDecl()) | |||
8934 | Access = NewFD->getPreviousDecl()->getAccess(); | |||
8935 | ||||
8936 | NewFD->setAccess(Access); | |||
8937 | if (FunctionTemplate) FunctionTemplate->setAccess(Access); | |||
8938 | } | |||
8939 | ||||
8940 | if (NewFD->isOverloadedOperator() && !DC->isRecord() && | |||
8941 | PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) | |||
8942 | PrincipalDecl->setNonMemberOperator(); | |||
8943 | ||||
8944 | // If we have a function template, check the template parameter | |||
8945 | // list. This will check and merge default template arguments. | |||
8946 | if (FunctionTemplate) { | |||
8947 | FunctionTemplateDecl *PrevTemplate = | |||
8948 | FunctionTemplate->getPreviousDecl(); | |||
8949 | CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), | |||
8950 | PrevTemplate ? PrevTemplate->getTemplateParameters() | |||
8951 | : nullptr, | |||
8952 | D.getDeclSpec().isFriendSpecified() | |||
8953 | ? (D.isFunctionDefinition() | |||
8954 | ? TPC_FriendFunctionTemplateDefinition | |||
8955 | : TPC_FriendFunctionTemplate) | |||
8956 | : (D.getCXXScopeSpec().isSet() && | |||
8957 | DC && DC->isRecord() && | |||
8958 | DC->isDependentContext()) | |||
8959 | ? TPC_ClassTemplateMember | |||
8960 | : TPC_FunctionTemplate); | |||
8961 | } | |||
8962 | ||||
8963 | if (NewFD->isInvalidDecl()) { | |||
8964 | // Ignore all the rest of this. | |||
8965 | } else if (!D.isRedeclaration()) { | |||
8966 | struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, | |||
8967 | AddToScope }; | |||
8968 | // Fake up an access specifier if it's supposed to be a class member. | |||
8969 | if (isa<CXXRecordDecl>(NewFD->getDeclContext())) | |||
8970 | NewFD->setAccess(AS_public); | |||
8971 | ||||
8972 | // Qualified decls generally require a previous declaration. | |||
8973 | if (D.getCXXScopeSpec().isSet()) { | |||
8974 | // ...with the major exception of templated-scope or | |||
8975 | // dependent-scope friend declarations. | |||
8976 | ||||
8977 | // TODO: we currently also suppress this check in dependent | |||
8978 | // contexts because (1) the parameter depth will be off when | |||
8979 | // matching friend templates and (2) we might actually be | |||
8980 | // selecting a friend based on a dependent factor. But there | |||
8981 | // are situations where these conditions don't apply and we | |||
8982 | // can actually do this check immediately. | |||
8983 | if (isFriend && | |||
8984 | (TemplateParamLists.size() || | |||
8985 | D.getCXXScopeSpec().getScopeRep()->isDependent() || | |||
8986 | CurContext->isDependentContext())) { | |||
8987 | // ignore these | |||
8988 | } else { | |||
8989 | // The user tried to provide an out-of-line definition for a | |||
8990 | // function that is a member of a class or namespace, but there | |||
8991 | // was no such member function declared (C++ [class.mfct]p2, | |||
8992 | // C++ [namespace.memdef]p2). For example: | |||
8993 | // | |||
8994 | // class X { | |||
8995 | // void f() const; | |||
8996 | // }; | |||
8997 | // | |||
8998 | // void X::f() { } // ill-formed | |||
8999 | // | |||
9000 | // Complain about this problem, and attempt to suggest close | |||
9001 | // matches (e.g., those that differ only in cv-qualifiers and | |||
9002 | // whether the parameter types are references). | |||
9003 | ||||
9004 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | |||
9005 | *this, Previous, NewFD, ExtraArgs, false, nullptr)) { | |||
9006 | AddToScope = ExtraArgs.AddToScope; | |||
9007 | return Result; | |||
9008 | } | |||
9009 | } | |||
9010 | ||||
9011 | // Unqualified local friend declarations are required to resolve | |||
9012 | // to something. | |||
9013 | } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { | |||
9014 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | |||
9015 | *this, Previous, NewFD, ExtraArgs, true, S)) { | |||
9016 | AddToScope = ExtraArgs.AddToScope; | |||
9017 | return Result; | |||
9018 | } | |||
9019 | } | |||
9020 | } else if (!D.isFunctionDefinition() && | |||
9021 | isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && | |||
9022 | !isFriend && !isFunctionTemplateSpecialization && | |||
9023 | !isMemberSpecialization) { | |||
9024 | // An out-of-line member function declaration must also be a | |||
9025 | // definition (C++ [class.mfct]p2). | |||
9026 | // Note that this is not the case for explicit specializations of | |||
9027 | // function templates or member functions of class templates, per | |||
9028 | // C++ [temp.expl.spec]p2. We also allow these declarations as an | |||
9029 | // extension for compatibility with old SWIG code which likes to | |||
9030 | // generate them. | |||
9031 | Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) | |||
9032 | << D.getCXXScopeSpec().getRange(); | |||
9033 | } | |||
9034 | } | |||
9035 | ||||
9036 | ProcessPragmaWeak(S, NewFD); | |||
9037 | checkAttributesAfterMerging(*this, *NewFD); | |||
9038 | ||||
9039 | AddKnownFunctionAttributes(NewFD); | |||
9040 | ||||
9041 | if (NewFD->hasAttr<OverloadableAttr>() && | |||
9042 | !NewFD->getType()->getAs<FunctionProtoType>()) { | |||
9043 | Diag(NewFD->getLocation(), | |||
9044 | diag::err_attribute_overloadable_no_prototype) | |||
9045 | << NewFD; | |||
9046 | ||||
9047 | // Turn this into a variadic function with no parameters. | |||
9048 | const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); | |||
9049 | FunctionProtoType::ExtProtoInfo EPI( | |||
9050 | Context.getDefaultCallingConvention(true, false)); | |||
9051 | EPI.Variadic = true; | |||
9052 | EPI.ExtInfo = FT->getExtInfo(); | |||
9053 | ||||
9054 | QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); | |||
9055 | NewFD->setType(R); | |||
9056 | } | |||
9057 | ||||
9058 | // If there's a #pragma GCC visibility in scope, and this isn't a class | |||
9059 | // member, set the visibility of this function. | |||
9060 | if (!DC->isRecord() && NewFD->isExternallyVisible()) | |||
9061 | AddPushedVisibilityAttribute(NewFD); | |||
9062 | ||||
9063 | // If there's a #pragma clang arc_cf_code_audited in scope, consider | |||
9064 | // marking the function. | |||
9065 | AddCFAuditedAttribute(NewFD); | |||
9066 | ||||
9067 | // If this is a function definition, check if we have to apply optnone due to | |||
9068 | // a pragma. | |||
9069 | if(D.isFunctionDefinition()) | |||
9070 | AddRangeBasedOptnone(NewFD); | |||
9071 | ||||
9072 | // If this is the first declaration of an extern C variable, update | |||
9073 | // the map of such variables. | |||
9074 | if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && | |||
9075 | isIncompleteDeclExternC(*this, NewFD)) | |||
9076 | RegisterLocallyScopedExternCDecl(NewFD, S); | |||
9077 | ||||
9078 | // Set this FunctionDecl's range up to the right paren. | |||
9079 | NewFD->setRangeEnd(D.getSourceRange().getEnd()); | |||
9080 | ||||
9081 | if (D.isRedeclaration() && !Previous.empty()) { | |||
9082 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | |||
9083 | checkDLLAttributeRedeclaration(*this, Prev, NewFD, | |||
9084 | isMemberSpecialization || | |||
9085 | isFunctionTemplateSpecialization, | |||
9086 | D.isFunctionDefinition()); | |||
9087 | } | |||
9088 | ||||
9089 | if (getLangOpts().CUDA) { | |||
9090 | IdentifierInfo *II = NewFD->getIdentifier(); | |||
9091 | if (II && | |||
9092 | II->isStr(getLangOpts().HIP ? "hipConfigureCall" | |||
9093 | : "cudaConfigureCall") && | |||
9094 | !NewFD->isInvalidDecl() && | |||
9095 | NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | |||
9096 | if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) | |||
9097 | Diag(NewFD->getLocation(), diag::err_config_scalar_return); | |||
9098 | Context.setcudaConfigureCallDecl(NewFD); | |||
9099 | } | |||
9100 | ||||
9101 | // Variadic functions, other than a *declaration* of printf, are not allowed | |||
9102 | // in device-side CUDA code, unless someone passed | |||
9103 | // -fcuda-allow-variadic-functions. | |||
9104 | if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && | |||
9105 | (NewFD->hasAttr<CUDADeviceAttr>() || | |||
9106 | NewFD->hasAttr<CUDAGlobalAttr>()) && | |||
9107 | !(II && II->isStr("printf") && NewFD->isExternC() && | |||
9108 | !D.isFunctionDefinition())) { | |||
9109 | Diag(NewFD->getLocation(), diag::err_variadic_device_fn); | |||
9110 | } | |||
9111 | } | |||
9112 | ||||
9113 | MarkUnusedFileScopedDecl(NewFD); | |||
9114 | ||||
9115 | if (getLangOpts().CPlusPlus) { | |||
9116 | if (FunctionTemplate) { | |||
9117 | if (NewFD->isInvalidDecl()) | |||
9118 | FunctionTemplate->setInvalidDecl(); | |||
9119 | return FunctionTemplate; | |||
9120 | } | |||
9121 | ||||
9122 | if (isMemberSpecialization && !NewFD->isInvalidDecl()) | |||
9123 | CompleteMemberSpecialization(NewFD, Previous); | |||
9124 | } | |||
9125 | ||||
9126 | if (NewFD->hasAttr<OpenCLKernelAttr>()) { | |||
9127 | // OpenCL v1.2 s6.8 static is invalid for kernel functions. | |||
9128 | if ((getLangOpts().OpenCLVersion >= 120) | |||
9129 | && (SC == SC_Static)) { | |||
9130 | Diag(D.getIdentifierLoc(), diag::err_static_kernel); | |||
9131 | D.setInvalidType(); | |||
9132 | } | |||
9133 | ||||
9134 | // OpenCL v1.2, s6.9 -- Kernels can only have return type void. | |||
9135 | if (!NewFD->getReturnType()->isVoidType()) { | |||
9136 | SourceRange RTRange = NewFD->getReturnTypeSourceRange(); | |||
9137 | Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) | |||
9138 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") | |||
9139 | : FixItHint()); | |||
9140 | D.setInvalidType(); | |||
9141 | } | |||
9142 | ||||
9143 | llvm::SmallPtrSet<const Type *, 16> ValidTypes; | |||
9144 | for (auto Param : NewFD->parameters()) | |||
9145 | checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); | |||
9146 | } | |||
9147 | for (const ParmVarDecl *Param : NewFD->parameters()) { | |||
9148 | QualType PT = Param->getType(); | |||
9149 | ||||
9150 | // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value | |||
9151 | // types. | |||
9152 | if (getLangOpts().OpenCLVersion >= 200) { | |||
9153 | if(const PipeType *PipeTy = PT->getAs<PipeType>()) { | |||
9154 | QualType ElemTy = PipeTy->getElementType(); | |||
9155 | if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { | |||
9156 | Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); | |||
9157 | D.setInvalidType(); | |||
9158 | } | |||
9159 | } | |||
9160 | } | |||
9161 | } | |||
9162 | ||||
9163 | // Here we have an function template explicit specialization at class scope. | |||
9164 | // The actual specialization will be postponed to template instatiation | |||
9165 | // time via the ClassScopeFunctionSpecializationDecl node. | |||
9166 | if (isDependentClassScopeExplicitSpecialization) { | |||
9167 | ClassScopeFunctionSpecializationDecl *NewSpec = | |||
9168 | ClassScopeFunctionSpecializationDecl::Create( | |||
9169 | Context, CurContext, NewFD->getLocation(), | |||
9170 | cast<CXXMethodDecl>(NewFD), | |||
9171 | HasExplicitTemplateArgs, TemplateArgs); | |||
9172 | CurContext->addDecl(NewSpec); | |||
9173 | AddToScope = false; | |||
9174 | } | |||
9175 | ||||
9176 | // Diagnose availability attributes. Availability cannot be used on functions | |||
9177 | // that are run during load/unload. | |||
9178 | if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { | |||
9179 | if (NewFD->hasAttr<ConstructorAttr>()) { | |||
9180 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | |||
9181 | << 1; | |||
9182 | NewFD->dropAttr<AvailabilityAttr>(); | |||
9183 | } | |||
9184 | if (NewFD->hasAttr<DestructorAttr>()) { | |||
9185 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | |||
9186 | << 2; | |||
9187 | NewFD->dropAttr<AvailabilityAttr>(); | |||
9188 | } | |||
9189 | } | |||
9190 | ||||
9191 | return NewFD; | |||
9192 | } | |||
9193 | ||||
9194 | /// Return a CodeSegAttr from a containing class. The Microsoft docs say | |||
9195 | /// when __declspec(code_seg) "is applied to a class, all member functions of | |||
9196 | /// the class and nested classes -- this includes compiler-generated special | |||
9197 | /// member functions -- are put in the specified segment." | |||
9198 | /// The actual behavior is a little more complicated. The Microsoft compiler | |||
9199 | /// won't check outer classes if there is an active value from #pragma code_seg. | |||
9200 | /// The CodeSeg is always applied from the direct parent but only from outer | |||
9201 | /// classes when the #pragma code_seg stack is empty. See: | |||
9202 | /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer | |||
9203 | /// available since MS has removed the page. | |||
9204 | static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { | |||
9205 | const auto *Method = dyn_cast<CXXMethodDecl>(FD); | |||
9206 | if (!Method) | |||
9207 | return nullptr; | |||
9208 | const CXXRecordDecl *Parent = Method->getParent(); | |||
9209 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | |||
9210 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | |||
9211 | NewAttr->setImplicit(true); | |||
9212 | return NewAttr; | |||
9213 | } | |||
9214 | ||||
9215 | // The Microsoft compiler won't check outer classes for the CodeSeg | |||
9216 | // when the #pragma code_seg stack is active. | |||
9217 | if (S.CodeSegStack.CurrentValue) | |||
9218 | return nullptr; | |||
9219 | ||||
9220 | while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { | |||
9221 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | |||
9222 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | |||
9223 | NewAttr->setImplicit(true); | |||
9224 | return NewAttr; | |||
9225 | } | |||
9226 | } | |||
9227 | return nullptr; | |||
9228 | } | |||
9229 | ||||
9230 | /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a | |||
9231 | /// containing class. Otherwise it will return implicit SectionAttr if the | |||
9232 | /// function is a definition and there is an active value on CodeSegStack | |||
9233 | /// (from the current #pragma code-seg value). | |||
9234 | /// | |||
9235 | /// \param FD Function being declared. | |||
9236 | /// \param IsDefinition Whether it is a definition or just a declarartion. | |||
9237 | /// \returns A CodeSegAttr or SectionAttr to apply to the function or | |||
9238 | /// nullptr if no attribute should be added. | |||
9239 | Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, | |||
9240 | bool IsDefinition) { | |||
9241 | if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) | |||
9242 | return A; | |||
9243 | if (!FD->hasAttr<SectionAttr>() && IsDefinition && | |||
9244 | CodeSegStack.CurrentValue) { | |||
9245 | return SectionAttr::CreateImplicit(getASTContext(), | |||
9246 | SectionAttr::Declspec_allocate, | |||
9247 | CodeSegStack.CurrentValue->getString(), | |||
9248 | CodeSegStack.CurrentPragmaLocation); | |||
9249 | } | |||
9250 | return nullptr; | |||
9251 | } | |||
9252 | /// Checks if the new declaration declared in dependent context must be | |||
9253 | /// put in the same redeclaration chain as the specified declaration. | |||
9254 | /// | |||
9255 | /// \param D Declaration that is checked. | |||
9256 | /// \param PrevDecl Previous declaration found with proper lookup method for the | |||
9257 | /// same declaration name. | |||
9258 | /// \returns True if D must be added to the redeclaration chain which PrevDecl | |||
9259 | /// belongs to. | |||
9260 | /// | |||
9261 | bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { | |||
9262 | // Any declarations should be put into redeclaration chains except for | |||
9263 | // friend declaration in a dependent context that names a function in | |||
9264 | // namespace scope. | |||
9265 | // | |||
9266 | // This allows to compile code like: | |||
9267 | // | |||
9268 | // void func(); | |||
9269 | // template<typename T> class C1 { friend void func() { } }; | |||
9270 | // template<typename T> class C2 { friend void func() { } }; | |||
9271 | // | |||
9272 | // This code snippet is a valid code unless both templates are instantiated. | |||
9273 | return !(D->getLexicalDeclContext()->isDependentContext() && | |||
9274 | D->getDeclContext()->isFileContext() && | |||
9275 | D->getFriendObjectKind() != Decl::FOK_None); | |||
9276 | } | |||
9277 | ||||
9278 | namespace MultiVersioning { | |||
9279 | enum Type { None, Target, CPUSpecific, CPUDispatch}; | |||
9280 | } // MultiVersionType | |||
9281 | ||||
9282 | static MultiVersioning::Type | |||
9283 | getMultiVersionType(const FunctionDecl *FD) { | |||
9284 | if (FD->hasAttr<TargetAttr>()) | |||
9285 | return MultiVersioning::Target; | |||
9286 | if (FD->hasAttr<CPUDispatchAttr>()) | |||
9287 | return MultiVersioning::CPUDispatch; | |||
9288 | if (FD->hasAttr<CPUSpecificAttr>()) | |||
9289 | return MultiVersioning::CPUSpecific; | |||
9290 | return MultiVersioning::None; | |||
9291 | } | |||
9292 | /// Check the target attribute of the function for MultiVersion | |||
9293 | /// validity. | |||
9294 | /// | |||
9295 | /// Returns true if there was an error, false otherwise. | |||
9296 | static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { | |||
9297 | const auto *TA = FD->getAttr<TargetAttr>(); | |||
9298 | assert(TA && "MultiVersion Candidate requires a target attribute")(static_cast <bool> (TA && "MultiVersion Candidate requires a target attribute" ) ? void (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9298, __extension__ __PRETTY_FUNCTION__)); | |||
9299 | TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); | |||
9300 | const TargetInfo &TargetInfo = S.Context.getTargetInfo(); | |||
9301 | enum ErrType { Feature = 0, Architecture = 1 }; | |||
9302 | ||||
9303 | if (!ParseInfo.Architecture.empty() && | |||
9304 | !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { | |||
9305 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | |||
9306 | << Architecture << ParseInfo.Architecture; | |||
9307 | return true; | |||
9308 | } | |||
9309 | ||||
9310 | for (const auto &Feat : ParseInfo.Features) { | |||
9311 | auto BareFeat = StringRef{Feat}.substr(1); | |||
9312 | if (Feat[0] == '-') { | |||
9313 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | |||
9314 | << Feature << ("no-" + BareFeat).str(); | |||
9315 | return true; | |||
9316 | } | |||
9317 | ||||
9318 | if (!TargetInfo.validateCpuSupports(BareFeat) || | |||
9319 | !TargetInfo.isValidFeatureName(BareFeat)) { | |||
9320 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | |||
9321 | << Feature << BareFeat; | |||
9322 | return true; | |||
9323 | } | |||
9324 | } | |||
9325 | return false; | |||
9326 | } | |||
9327 | ||||
9328 | static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, | |||
9329 | const FunctionDecl *NewFD, | |||
9330 | bool CausesMV, | |||
9331 | MultiVersioning::Type MVType) { | |||
9332 | enum DoesntSupport { | |||
9333 | FuncTemplates = 0, | |||
9334 | VirtFuncs = 1, | |||
9335 | DeducedReturn = 2, | |||
9336 | Constructors = 3, | |||
9337 | Destructors = 4, | |||
9338 | DeletedFuncs = 5, | |||
9339 | DefaultedFuncs = 6, | |||
9340 | ConstexprFuncs = 7, | |||
9341 | }; | |||
9342 | enum Different { | |||
9343 | CallingConv = 0, | |||
9344 | ReturnType = 1, | |||
9345 | ConstexprSpec = 2, | |||
9346 | InlineSpec = 3, | |||
9347 | StorageClass = 4, | |||
9348 | Linkage = 5 | |||
9349 | }; | |||
9350 | ||||
9351 | bool IsCPUSpecificCPUDispatchMVType = | |||
9352 | MVType == MultiVersioning::CPUDispatch || | |||
9353 | MVType == MultiVersioning::CPUSpecific; | |||
9354 | ||||
9355 | if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { | |||
9356 | S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); | |||
9357 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
9358 | return true; | |||
9359 | } | |||
9360 | ||||
9361 | if (!NewFD->getType()->getAs<FunctionProtoType>()) | |||
9362 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); | |||
9363 | ||||
9364 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | |||
9365 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | |||
9366 | if (OldFD) | |||
9367 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
9368 | return true; | |||
9369 | } | |||
9370 | ||||
9371 | // For now, disallow all other attributes. These should be opt-in, but | |||
9372 | // an analysis of all of them is a future FIXME. | |||
9373 | if (CausesMV && OldFD && | |||
9374 | std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) { | |||
9375 | S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) | |||
9376 | << IsCPUSpecificCPUDispatchMVType; | |||
9377 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
9378 | return true; | |||
9379 | } | |||
9380 | ||||
9381 | if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1) | |||
9382 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) | |||
9383 | << IsCPUSpecificCPUDispatchMVType; | |||
9384 | ||||
9385 | if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) | |||
9386 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) | |||
9387 | << IsCPUSpecificCPUDispatchMVType << FuncTemplates; | |||
9388 | ||||
9389 | if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { | |||
9390 | if (NewCXXFD->isVirtual()) | |||
9391 | return S.Diag(NewCXXFD->getLocation(), | |||
9392 | diag::err_multiversion_doesnt_support) | |||
9393 | << IsCPUSpecificCPUDispatchMVType << VirtFuncs; | |||
9394 | ||||
9395 | if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) | |||
9396 | return S.Diag(NewCXXCtor->getLocation(), | |||
9397 | diag::err_multiversion_doesnt_support) | |||
9398 | << IsCPUSpecificCPUDispatchMVType << Constructors; | |||
9399 | ||||
9400 | if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) | |||
9401 | return S.Diag(NewCXXDtor->getLocation(), | |||
9402 | diag::err_multiversion_doesnt_support) | |||
9403 | << IsCPUSpecificCPUDispatchMVType << Destructors; | |||
9404 | } | |||
9405 | ||||
9406 | if (NewFD->isDeleted()) | |||
9407 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) | |||
9408 | << IsCPUSpecificCPUDispatchMVType << DeletedFuncs; | |||
9409 | ||||
9410 | if (NewFD->isDefaulted()) | |||
9411 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) | |||
9412 | << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs; | |||
9413 | ||||
9414 | if (NewFD->isConstexpr() && (MVType == MultiVersioning::CPUDispatch || | |||
9415 | MVType == MultiVersioning::CPUSpecific)) | |||
9416 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) | |||
9417 | << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs; | |||
9418 | ||||
9419 | QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); | |||
9420 | const auto *NewType = cast<FunctionType>(NewQType); | |||
9421 | QualType NewReturnType = NewType->getReturnType(); | |||
9422 | ||||
9423 | if (NewReturnType->isUndeducedType()) | |||
9424 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) | |||
9425 | << IsCPUSpecificCPUDispatchMVType << DeducedReturn; | |||
9426 | ||||
9427 | // Only allow transition to MultiVersion if it hasn't been used. | |||
9428 | if (OldFD && CausesMV && OldFD->isUsed(false)) | |||
9429 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); | |||
9430 | ||||
9431 | // Ensure the return type is identical. | |||
9432 | if (OldFD) { | |||
9433 | QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); | |||
9434 | const auto *OldType = cast<FunctionType>(OldQType); | |||
9435 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | |||
9436 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | |||
9437 | ||||
9438 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) | |||
9439 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9440 | << CallingConv; | |||
9441 | ||||
9442 | QualType OldReturnType = OldType->getReturnType(); | |||
9443 | ||||
9444 | if (OldReturnType != NewReturnType) | |||
9445 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9446 | << ReturnType; | |||
9447 | ||||
9448 | if (OldFD->isConstexpr() != NewFD->isConstexpr()) | |||
9449 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9450 | << ConstexprSpec; | |||
9451 | ||||
9452 | if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) | |||
9453 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9454 | << InlineSpec; | |||
9455 | ||||
9456 | if (OldFD->getStorageClass() != NewFD->getStorageClass()) | |||
9457 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9458 | << StorageClass; | |||
9459 | ||||
9460 | if (OldFD->isExternC() != NewFD->isExternC()) | |||
9461 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) | |||
9462 | << Linkage; | |||
9463 | ||||
9464 | if (S.CheckEquivalentExceptionSpec( | |||
9465 | OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), | |||
9466 | NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) | |||
9467 | return true; | |||
9468 | } | |||
9469 | return false; | |||
9470 | } | |||
9471 | ||||
9472 | /// Check the validity of a multiversion function declaration that is the | |||
9473 | /// first of its kind. Also sets the multiversion'ness' of the function itself. | |||
9474 | /// | |||
9475 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | |||
9476 | /// | |||
9477 | /// Returns true if there was an error, false otherwise. | |||
9478 | static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, | |||
9479 | MultiVersioning::Type MVType, | |||
9480 | const TargetAttr *TA, | |||
9481 | const CPUDispatchAttr *CPUDisp, | |||
9482 | const CPUSpecificAttr *CPUSpec) { | |||
9483 | assert(MVType != MultiVersioning::None &&(static_cast <bool> (MVType != MultiVersioning::None && "Function lacks multiversion attribute") ? void (0) : __assert_fail ("MVType != MultiVersioning::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9484, __extension__ __PRETTY_FUNCTION__)) | |||
9484 | "Function lacks multiversion attribute")(static_cast <bool> (MVType != MultiVersioning::None && "Function lacks multiversion attribute") ? void (0) : __assert_fail ("MVType != MultiVersioning::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9484, __extension__ __PRETTY_FUNCTION__)); | |||
9485 | ||||
9486 | // Target only causes MV if it is default, otherwise this is a normal | |||
9487 | // function. | |||
9488 | if (MVType == MultiVersioning::Target && !TA->isDefaultVersion()) | |||
9489 | return false; | |||
9490 | ||||
9491 | if (MVType == MultiVersioning::Target && CheckMultiVersionValue(S, FD)) { | |||
9492 | FD->setInvalidDecl(); | |||
9493 | return true; | |||
9494 | } | |||
9495 | ||||
9496 | if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { | |||
9497 | FD->setInvalidDecl(); | |||
9498 | return true; | |||
9499 | } | |||
9500 | ||||
9501 | FD->setIsMultiVersion(); | |||
9502 | return false; | |||
9503 | } | |||
9504 | ||||
9505 | static bool CheckTargetCausesMultiVersioning( | |||
9506 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, | |||
9507 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | |||
9508 | LookupResult &Previous) { | |||
9509 | const auto *OldTA = OldFD->getAttr<TargetAttr>(); | |||
9510 | TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); | |||
9511 | // Sort order doesn't matter, it just needs to be consistent. | |||
9512 | llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end()); | |||
9513 | ||||
9514 | // If the old decl is NOT MultiVersioned yet, and we don't cause that | |||
9515 | // to change, this is a simple redeclaration. | |||
9516 | if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()) | |||
9517 | return false; | |||
9518 | ||||
9519 | // Otherwise, this decl causes MultiVersioning. | |||
9520 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | |||
9521 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | |||
9522 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
9523 | NewFD->setInvalidDecl(); | |||
9524 | return true; | |||
9525 | } | |||
9526 | ||||
9527 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, | |||
9528 | MultiVersioning::Target)) { | |||
9529 | NewFD->setInvalidDecl(); | |||
9530 | return true; | |||
9531 | } | |||
9532 | ||||
9533 | if (CheckMultiVersionValue(S, NewFD)) { | |||
9534 | NewFD->setInvalidDecl(); | |||
9535 | return true; | |||
9536 | } | |||
9537 | ||||
9538 | if (CheckMultiVersionValue(S, OldFD)) { | |||
9539 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
9540 | NewFD->setInvalidDecl(); | |||
9541 | return true; | |||
9542 | } | |||
9543 | ||||
9544 | TargetAttr::ParsedTargetAttr OldParsed = | |||
9545 | OldTA->parse(std::less<std::string>()); | |||
9546 | ||||
9547 | if (OldParsed == NewParsed) { | |||
9548 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | |||
9549 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
9550 | NewFD->setInvalidDecl(); | |||
9551 | return true; | |||
9552 | } | |||
9553 | ||||
9554 | for (const auto *FD : OldFD->redecls()) { | |||
9555 | const auto *CurTA = FD->getAttr<TargetAttr>(); | |||
9556 | if (!CurTA || CurTA->isInherited()) { | |||
9557 | S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) | |||
9558 | << 0; | |||
9559 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
9560 | NewFD->setInvalidDecl(); | |||
9561 | return true; | |||
9562 | } | |||
9563 | } | |||
9564 | ||||
9565 | OldFD->setIsMultiVersion(); | |||
9566 | NewFD->setIsMultiVersion(); | |||
9567 | Redeclaration = false; | |||
9568 | MergeTypeWithPrevious = false; | |||
9569 | OldDecl = nullptr; | |||
9570 | Previous.clear(); | |||
9571 | return false; | |||
9572 | } | |||
9573 | ||||
9574 | /// Check the validity of a new function declaration being added to an existing | |||
9575 | /// multiversioned declaration collection. | |||
9576 | static bool CheckMultiVersionAdditionalDecl( | |||
9577 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, | |||
9578 | MultiVersioning::Type NewMVType, const TargetAttr *NewTA, | |||
9579 | const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, | |||
9580 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | |||
9581 | LookupResult &Previous) { | |||
9582 | ||||
9583 | MultiVersioning::Type OldMVType = getMultiVersionType(OldFD); | |||
9584 | // Disallow mixing of multiversioning types. | |||
9585 | if ((OldMVType == MultiVersioning::Target && | |||
9586 | NewMVType != MultiVersioning::Target) || | |||
9587 | (NewMVType == MultiVersioning::Target && | |||
9588 | OldMVType != MultiVersioning::Target)) { | |||
9589 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | |||
9590 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
9591 | NewFD->setInvalidDecl(); | |||
9592 | return true; | |||
9593 | } | |||
9594 | ||||
9595 | TargetAttr::ParsedTargetAttr NewParsed; | |||
9596 | if (NewTA) { | |||
9597 | NewParsed = NewTA->parse(); | |||
9598 | llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end()); | |||
9599 | } | |||
9600 | ||||
9601 | bool UseMemberUsingDeclRules = | |||
9602 | S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); | |||
9603 | ||||
9604 | // Next, check ALL non-overloads to see if this is a redeclaration of a | |||
9605 | // previous member of the MultiVersion set. | |||
9606 | for (NamedDecl *ND : Previous) { | |||
9607 | FunctionDecl *CurFD = ND->getAsFunction(); | |||
9608 | if (!CurFD) | |||
9609 | continue; | |||
9610 | if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) | |||
9611 | continue; | |||
9612 | ||||
9613 | if (NewMVType == MultiVersioning::Target) { | |||
9614 | const auto *CurTA = CurFD->getAttr<TargetAttr>(); | |||
9615 | if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { | |||
9616 | NewFD->setIsMultiVersion(); | |||
9617 | Redeclaration = true; | |||
9618 | OldDecl = ND; | |||
9619 | return false; | |||
9620 | } | |||
9621 | ||||
9622 | TargetAttr::ParsedTargetAttr CurParsed = | |||
9623 | CurTA->parse(std::less<std::string>()); | |||
9624 | if (CurParsed == NewParsed) { | |||
9625 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | |||
9626 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | |||
9627 | NewFD->setInvalidDecl(); | |||
9628 | return true; | |||
9629 | } | |||
9630 | } else { | |||
9631 | const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); | |||
9632 | const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); | |||
9633 | // Handle CPUDispatch/CPUSpecific versions. | |||
9634 | // Only 1 CPUDispatch function is allowed, this will make it go through | |||
9635 | // the redeclaration errors. | |||
9636 | if (NewMVType == MultiVersioning::CPUDispatch && | |||
9637 | CurFD->hasAttr<CPUDispatchAttr>()) { | |||
9638 | if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && | |||
9639 | std::equal( | |||
9640 | CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), | |||
9641 | NewCPUDisp->cpus_begin(), | |||
9642 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | |||
9643 | return Cur->getName() == New->getName(); | |||
9644 | })) { | |||
9645 | NewFD->setIsMultiVersion(); | |||
9646 | Redeclaration = true; | |||
9647 | OldDecl = ND; | |||
9648 | return false; | |||
9649 | } | |||
9650 | ||||
9651 | // If the declarations don't match, this is an error condition. | |||
9652 | S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); | |||
9653 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | |||
9654 | NewFD->setInvalidDecl(); | |||
9655 | return true; | |||
9656 | } | |||
9657 | if (NewMVType == MultiVersioning::CPUSpecific && CurCPUSpec) { | |||
9658 | ||||
9659 | if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && | |||
9660 | std::equal( | |||
9661 | CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), | |||
9662 | NewCPUSpec->cpus_begin(), | |||
9663 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | |||
9664 | return Cur->getName() == New->getName(); | |||
9665 | })) { | |||
9666 | NewFD->setIsMultiVersion(); | |||
9667 | Redeclaration = true; | |||
9668 | OldDecl = ND; | |||
9669 | return false; | |||
9670 | } | |||
9671 | ||||
9672 | // Only 1 version of CPUSpecific is allowed for each CPU. | |||
9673 | for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { | |||
9674 | for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { | |||
9675 | if (CurII == NewII) { | |||
9676 | S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) | |||
9677 | << NewII; | |||
9678 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | |||
9679 | NewFD->setInvalidDecl(); | |||
9680 | return true; | |||
9681 | } | |||
9682 | } | |||
9683 | } | |||
9684 | } | |||
9685 | // If the two decls aren't the same MVType, there is no possible error | |||
9686 | // condition. | |||
9687 | } | |||
9688 | } | |||
9689 | ||||
9690 | // Else, this is simply a non-redecl case. Checking the 'value' is only | |||
9691 | // necessary in the Target case, since The CPUSpecific/Dispatch cases are | |||
9692 | // handled in the attribute adding step. | |||
9693 | if (NewMVType == MultiVersioning::Target && | |||
9694 | CheckMultiVersionValue(S, NewFD)) { | |||
9695 | NewFD->setInvalidDecl(); | |||
9696 | return true; | |||
9697 | } | |||
9698 | ||||
9699 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false, NewMVType)) { | |||
9700 | NewFD->setInvalidDecl(); | |||
9701 | return true; | |||
9702 | } | |||
9703 | ||||
9704 | NewFD->setIsMultiVersion(); | |||
9705 | Redeclaration = false; | |||
9706 | MergeTypeWithPrevious = false; | |||
9707 | OldDecl = nullptr; | |||
9708 | Previous.clear(); | |||
9709 | return false; | |||
9710 | } | |||
9711 | ||||
9712 | ||||
9713 | /// Check the validity of a mulitversion function declaration. | |||
9714 | /// Also sets the multiversion'ness' of the function itself. | |||
9715 | /// | |||
9716 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | |||
9717 | /// | |||
9718 | /// Returns true if there was an error, false otherwise. | |||
9719 | static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, | |||
9720 | bool &Redeclaration, NamedDecl *&OldDecl, | |||
9721 | bool &MergeTypeWithPrevious, | |||
9722 | LookupResult &Previous) { | |||
9723 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); | |||
9724 | const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); | |||
9725 | const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); | |||
9726 | ||||
9727 | // Mixing Multiversioning types is prohibited. | |||
9728 | if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || | |||
9729 | (NewCPUDisp && NewCPUSpec)) { | |||
9730 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | |||
9731 | NewFD->setInvalidDecl(); | |||
9732 | return true; | |||
9733 | } | |||
9734 | ||||
9735 | MultiVersioning::Type MVType = getMultiVersionType(NewFD); | |||
9736 | ||||
9737 | // Main isn't allowed to become a multiversion function, however it IS | |||
9738 | // permitted to have 'main' be marked with the 'target' optimization hint. | |||
9739 | if (NewFD->isMain()) { | |||
9740 | if ((MVType == MultiVersioning::Target && NewTA->isDefaultVersion()) || | |||
9741 | MVType == MultiVersioning::CPUDispatch || | |||
9742 | MVType == MultiVersioning::CPUSpecific) { | |||
9743 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); | |||
9744 | NewFD->setInvalidDecl(); | |||
9745 | return true; | |||
9746 | } | |||
9747 | return false; | |||
9748 | } | |||
9749 | ||||
9750 | if (!OldDecl || !OldDecl->getAsFunction() || | |||
9751 | OldDecl->getDeclContext()->getRedeclContext() != | |||
9752 | NewFD->getDeclContext()->getRedeclContext()) { | |||
9753 | // If there's no previous declaration, AND this isn't attempting to cause | |||
9754 | // multiversioning, this isn't an error condition. | |||
9755 | if (MVType == MultiVersioning::None) | |||
9756 | return false; | |||
9757 | return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp, | |||
9758 | NewCPUSpec); | |||
9759 | } | |||
9760 | ||||
9761 | FunctionDecl *OldFD = OldDecl->getAsFunction(); | |||
9762 | ||||
9763 | if (!OldFD->isMultiVersion() && MVType == MultiVersioning::None) | |||
9764 | return false; | |||
9765 | ||||
9766 | if (OldFD->isMultiVersion() && MVType == MultiVersioning::None) { | |||
9767 | S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) | |||
9768 | << (getMultiVersionType(OldFD) != MultiVersioning::Target); | |||
9769 | NewFD->setInvalidDecl(); | |||
9770 | return true; | |||
9771 | } | |||
9772 | ||||
9773 | // Handle the target potentially causes multiversioning case. | |||
9774 | if (!OldFD->isMultiVersion() && MVType == MultiVersioning::Target) | |||
9775 | return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, | |||
9776 | Redeclaration, OldDecl, | |||
9777 | MergeTypeWithPrevious, Previous); | |||
9778 | // Previous declarations lack CPUDispatch/CPUSpecific. | |||
9779 | if (!OldFD->isMultiVersion()) { | |||
9780 | S.Diag(OldFD->getLocation(), diag::err_multiversion_required_in_redecl) | |||
9781 | << 1; | |||
9782 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
9783 | NewFD->setInvalidDecl(); | |||
9784 | return true; | |||
9785 | } | |||
9786 | ||||
9787 | // At this point, we have a multiversion function decl (in OldFD) AND an | |||
9788 | // appropriate attribute in the current function decl. Resolve that these are | |||
9789 | // still compatible with previous declarations. | |||
9790 | return CheckMultiVersionAdditionalDecl( | |||
9791 | S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, | |||
9792 | OldDecl, MergeTypeWithPrevious, Previous); | |||
9793 | } | |||
9794 | ||||
9795 | /// Perform semantic checking of a new function declaration. | |||
9796 | /// | |||
9797 | /// Performs semantic analysis of the new function declaration | |||
9798 | /// NewFD. This routine performs all semantic checking that does not | |||
9799 | /// require the actual declarator involved in the declaration, and is | |||
9800 | /// used both for the declaration of functions as they are parsed | |||
9801 | /// (called via ActOnDeclarator) and for the declaration of functions | |||
9802 | /// that have been instantiated via C++ template instantiation (called | |||
9803 | /// via InstantiateDecl). | |||
9804 | /// | |||
9805 | /// \param IsMemberSpecialization whether this new function declaration is | |||
9806 | /// a member specialization (that replaces any definition provided by the | |||
9807 | /// previous declaration). | |||
9808 | /// | |||
9809 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | |||
9810 | /// | |||
9811 | /// \returns true if the function declaration is a redeclaration. | |||
9812 | bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, | |||
9813 | LookupResult &Previous, | |||
9814 | bool IsMemberSpecialization) { | |||
9815 | assert(!NewFD->getReturnType()->isVariablyModifiedType() &&(static_cast <bool> (!NewFD->getReturnType()->isVariablyModifiedType () && "Variably modified return types are not handled here" ) ? void (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9816, __extension__ __PRETTY_FUNCTION__)) | |||
9816 | "Variably modified return types are not handled here")(static_cast <bool> (!NewFD->getReturnType()->isVariablyModifiedType () && "Variably modified return types are not handled here" ) ? void (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9816, __extension__ __PRETTY_FUNCTION__)); | |||
9817 | ||||
9818 | // Determine whether the type of this function should be merged with | |||
9819 | // a previous visible declaration. This never happens for functions in C++, | |||
9820 | // and always happens in C if the previous declaration was visible. | |||
9821 | bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && | |||
9822 | !Previous.isShadowed(); | |||
9823 | ||||
9824 | bool Redeclaration = false; | |||
9825 | NamedDecl *OldDecl = nullptr; | |||
9826 | bool MayNeedOverloadableChecks = false; | |||
9827 | ||||
9828 | // Merge or overload the declaration with an existing declaration of | |||
9829 | // the same name, if appropriate. | |||
9830 | if (!Previous.empty()) { | |||
9831 | // Determine whether NewFD is an overload of PrevDecl or | |||
9832 | // a declaration that requires merging. If it's an overload, | |||
9833 | // there's no more work to do here; we'll just add the new | |||
9834 | // function to the scope. | |||
9835 | if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { | |||
9836 | NamedDecl *Candidate = Previous.getRepresentativeDecl(); | |||
9837 | if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { | |||
9838 | Redeclaration = true; | |||
9839 | OldDecl = Candidate; | |||
9840 | } | |||
9841 | } else { | |||
9842 | MayNeedOverloadableChecks = true; | |||
9843 | switch (CheckOverload(S, NewFD, Previous, OldDecl, | |||
9844 | /*NewIsUsingDecl*/ false)) { | |||
9845 | case Ovl_Match: | |||
9846 | Redeclaration = true; | |||
9847 | break; | |||
9848 | ||||
9849 | case Ovl_NonFunction: | |||
9850 | Redeclaration = true; | |||
9851 | break; | |||
9852 | ||||
9853 | case Ovl_Overload: | |||
9854 | Redeclaration = false; | |||
9855 | break; | |||
9856 | } | |||
9857 | } | |||
9858 | } | |||
9859 | ||||
9860 | // Check for a previous extern "C" declaration with this name. | |||
9861 | if (!Redeclaration && | |||
9862 | checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { | |||
9863 | if (!Previous.empty()) { | |||
9864 | // This is an extern "C" declaration with the same name as a previous | |||
9865 | // declaration, and thus redeclares that entity... | |||
9866 | Redeclaration = true; | |||
9867 | OldDecl = Previous.getFoundDecl(); | |||
9868 | MergeTypeWithPrevious = false; | |||
9869 | ||||
9870 | // ... except in the presence of __attribute__((overloadable)). | |||
9871 | if (OldDecl->hasAttr<OverloadableAttr>() || | |||
9872 | NewFD->hasAttr<OverloadableAttr>()) { | |||
9873 | if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { | |||
9874 | MayNeedOverloadableChecks = true; | |||
9875 | Redeclaration = false; | |||
9876 | OldDecl = nullptr; | |||
9877 | } | |||
9878 | } | |||
9879 | } | |||
9880 | } | |||
9881 | ||||
9882 | if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, | |||
9883 | MergeTypeWithPrevious, Previous)) | |||
9884 | return Redeclaration; | |||
9885 | ||||
9886 | // C++11 [dcl.constexpr]p8: | |||
9887 | // A constexpr specifier for a non-static member function that is not | |||
9888 | // a constructor declares that member function to be const. | |||
9889 | // | |||
9890 | // This needs to be delayed until we know whether this is an out-of-line | |||
9891 | // definition of a static member function. | |||
9892 | // | |||
9893 | // This rule is not present in C++1y, so we produce a backwards | |||
9894 | // compatibility warning whenever it happens in C++11. | |||
9895 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | |||
9896 | if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && | |||
9897 | !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && | |||
9898 | (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { | |||
9899 | CXXMethodDecl *OldMD = nullptr; | |||
9900 | if (OldDecl) | |||
9901 | OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); | |||
9902 | if (!OldMD || !OldMD->isStatic()) { | |||
9903 | const FunctionProtoType *FPT = | |||
9904 | MD->getType()->castAs<FunctionProtoType>(); | |||
9905 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | |||
9906 | EPI.TypeQuals |= Qualifiers::Const; | |||
9907 | MD->setType(Context.getFunctionType(FPT->getReturnType(), | |||
9908 | FPT->getParamTypes(), EPI)); | |||
9909 | ||||
9910 | // Warn that we did this, if we're not performing template instantiation. | |||
9911 | // In that case, we'll have warned already when the template was defined. | |||
9912 | if (!inTemplateInstantiation()) { | |||
9913 | SourceLocation AddConstLoc; | |||
9914 | if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() | |||
9915 | .IgnoreParens().getAs<FunctionTypeLoc>()) | |||
9916 | AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); | |||
9917 | ||||
9918 | Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) | |||
9919 | << FixItHint::CreateInsertion(AddConstLoc, " const"); | |||
9920 | } | |||
9921 | } | |||
9922 | } | |||
9923 | ||||
9924 | if (Redeclaration) { | |||
9925 | // NewFD and OldDecl represent declarations that need to be | |||
9926 | // merged. | |||
9927 | if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { | |||
9928 | NewFD->setInvalidDecl(); | |||
9929 | return Redeclaration; | |||
9930 | } | |||
9931 | ||||
9932 | Previous.clear(); | |||
9933 | Previous.addDecl(OldDecl); | |||
9934 | ||||
9935 | if (FunctionTemplateDecl *OldTemplateDecl = | |||
9936 | dyn_cast<FunctionTemplateDecl>(OldDecl)) { | |||
9937 | auto *OldFD = OldTemplateDecl->getTemplatedDecl(); | |||
9938 | NewFD->setPreviousDeclaration(OldFD); | |||
9939 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | |||
9940 | FunctionTemplateDecl *NewTemplateDecl | |||
9941 | = NewFD->getDescribedFunctionTemplate(); | |||
9942 | assert(NewTemplateDecl && "Template/non-template mismatch")(static_cast <bool> (NewTemplateDecl && "Template/non-template mismatch" ) ? void (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9942, __extension__ __PRETTY_FUNCTION__)); | |||
9943 | if (NewFD->isCXXClassMember()) { | |||
9944 | NewFD->setAccess(OldTemplateDecl->getAccess()); | |||
9945 | NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); | |||
9946 | } | |||
9947 | ||||
9948 | // If this is an explicit specialization of a member that is a function | |||
9949 | // template, mark it as a member specialization. | |||
9950 | if (IsMemberSpecialization && | |||
9951 | NewTemplateDecl->getInstantiatedFromMemberTemplate()) { | |||
9952 | NewTemplateDecl->setMemberSpecialization(); | |||
9953 | assert(OldTemplateDecl->isMemberSpecialization())(static_cast <bool> (OldTemplateDecl->isMemberSpecialization ()) ? void (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9953, __extension__ __PRETTY_FUNCTION__)); | |||
9954 | // Explicit specializations of a member template do not inherit deleted | |||
9955 | // status from the parent member template that they are specializing. | |||
9956 | if (OldFD->isDeleted()) { | |||
9957 | // FIXME: This assert will not hold in the presence of modules. | |||
9958 | assert(OldFD->getCanonicalDecl() == OldFD)(static_cast <bool> (OldFD->getCanonicalDecl() == OldFD ) ? void (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9958, __extension__ __PRETTY_FUNCTION__)); | |||
9959 | // FIXME: We need an update record for this AST mutation. | |||
9960 | OldFD->setDeletedAsWritten(false); | |||
9961 | } | |||
9962 | } | |||
9963 | ||||
9964 | } else { | |||
9965 | if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { | |||
9966 | auto *OldFD = cast<FunctionDecl>(OldDecl); | |||
9967 | // This needs to happen first so that 'inline' propagates. | |||
9968 | NewFD->setPreviousDeclaration(OldFD); | |||
9969 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | |||
9970 | if (NewFD->isCXXClassMember()) | |||
9971 | NewFD->setAccess(OldFD->getAccess()); | |||
9972 | } | |||
9973 | } | |||
9974 | } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && | |||
9975 | !NewFD->getAttr<OverloadableAttr>()) { | |||
9976 | assert((Previous.empty() ||(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9981, __extension__ __PRETTY_FUNCTION__)) | |||
9977 | llvm::any_of(Previous,(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9981, __extension__ __PRETTY_FUNCTION__)) | |||
9978 | [](const NamedDecl *ND) {(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9981, __extension__ __PRETTY_FUNCTION__)) | |||
9979 | return ND->hasAttr<OverloadableAttr>();(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9981, __extension__ __PRETTY_FUNCTION__)) | |||
9980 | })) &&(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9981, __extension__ __PRETTY_FUNCTION__)) | |||
9981 | "Non-redecls shouldn't happen without overloadable present")(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 9981, __extension__ __PRETTY_FUNCTION__)); | |||
9982 | ||||
9983 | auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { | |||
9984 | const auto *FD = dyn_cast<FunctionDecl>(ND); | |||
9985 | return FD && !FD->hasAttr<OverloadableAttr>(); | |||
9986 | }); | |||
9987 | ||||
9988 | if (OtherUnmarkedIter != Previous.end()) { | |||
9989 | Diag(NewFD->getLocation(), | |||
9990 | diag::err_attribute_overloadable_multiple_unmarked_overloads); | |||
9991 | Diag((*OtherUnmarkedIter)->getLocation(), | |||
9992 | diag::note_attribute_overloadable_prev_overload) | |||
9993 | << false; | |||
9994 | ||||
9995 | NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); | |||
9996 | } | |||
9997 | } | |||
9998 | ||||
9999 | // Semantic checking for this function declaration (in isolation). | |||
10000 | ||||
10001 | if (getLangOpts().CPlusPlus) { | |||
10002 | // C++-specific checks. | |||
10003 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { | |||
10004 | CheckConstructor(Constructor); | |||
10005 | } else if (CXXDestructorDecl *Destructor = | |||
10006 | dyn_cast<CXXDestructorDecl>(NewFD)) { | |||
10007 | CXXRecordDecl *Record = Destructor->getParent(); | |||
10008 | QualType ClassType = Context.getTypeDeclType(Record); | |||
10009 | ||||
10010 | // FIXME: Shouldn't we be able to perform this check even when the class | |||
10011 | // type is dependent? Both gcc and edg can handle that. | |||
10012 | if (!ClassType->isDependentType()) { | |||
10013 | DeclarationName Name | |||
10014 | = Context.DeclarationNames.getCXXDestructorName( | |||
10015 | Context.getCanonicalType(ClassType)); | |||
10016 | if (NewFD->getDeclName() != Name) { | |||
10017 | Diag(NewFD->getLocation(), diag::err_destructor_name); | |||
10018 | NewFD->setInvalidDecl(); | |||
10019 | return Redeclaration; | |||
10020 | } | |||
10021 | } | |||
10022 | } else if (CXXConversionDecl *Conversion | |||
10023 | = dyn_cast<CXXConversionDecl>(NewFD)) { | |||
10024 | ActOnConversionDeclarator(Conversion); | |||
10025 | } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { | |||
10026 | if (auto *TD = Guide->getDescribedFunctionTemplate()) | |||
10027 | CheckDeductionGuideTemplate(TD); | |||
10028 | ||||
10029 | // A deduction guide is not on the list of entities that can be | |||
10030 | // explicitly specialized. | |||
10031 | if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) | |||
10032 | Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) | |||
10033 | << /*explicit specialization*/ 1; | |||
10034 | } | |||
10035 | ||||
10036 | // Find any virtual functions that this function overrides. | |||
10037 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { | |||
10038 | if (!Method->isFunctionTemplateSpecialization() && | |||
10039 | !Method->getDescribedFunctionTemplate() && | |||
10040 | Method->isCanonicalDecl()) { | |||
10041 | if (AddOverriddenMethods(Method->getParent(), Method)) { | |||
10042 | // If the function was marked as "static", we have a problem. | |||
10043 | if (NewFD->getStorageClass() == SC_Static) { | |||
10044 | ReportOverrides(*this, diag::err_static_overrides_virtual, Method); | |||
10045 | } | |||
10046 | } | |||
10047 | } | |||
10048 | ||||
10049 | if (Method->isStatic()) | |||
10050 | checkThisInStaticMemberFunctionType(Method); | |||
10051 | } | |||
10052 | ||||
10053 | // Extra checking for C++ overloaded operators (C++ [over.oper]). | |||
10054 | if (NewFD->isOverloadedOperator() && | |||
10055 | CheckOverloadedOperatorDeclaration(NewFD)) { | |||
10056 | NewFD->setInvalidDecl(); | |||
10057 | return Redeclaration; | |||
10058 | } | |||
10059 | ||||
10060 | // Extra checking for C++0x literal operators (C++0x [over.literal]). | |||
10061 | if (NewFD->getLiteralIdentifier() && | |||
10062 | CheckLiteralOperatorDeclaration(NewFD)) { | |||
10063 | NewFD->setInvalidDecl(); | |||
10064 | return Redeclaration; | |||
10065 | } | |||
10066 | ||||
10067 | // In C++, check default arguments now that we have merged decls. Unless | |||
10068 | // the lexical context is the class, because in this case this is done | |||
10069 | // during delayed parsing anyway. | |||
10070 | if (!CurContext->isRecord()) | |||
10071 | CheckCXXDefaultArguments(NewFD); | |||
10072 | ||||
10073 | // If this function declares a builtin function, check the type of this | |||
10074 | // declaration against the expected type for the builtin. | |||
10075 | if (unsigned BuiltinID = NewFD->getBuiltinID()) { | |||
10076 | ASTContext::GetBuiltinTypeError Error; | |||
10077 | LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); | |||
10078 | QualType T = Context.GetBuiltinType(BuiltinID, Error); | |||
10079 | // If the type of the builtin differs only in its exception | |||
10080 | // specification, that's OK. | |||
10081 | // FIXME: If the types do differ in this way, it would be better to | |||
10082 | // retain the 'noexcept' form of the type. | |||
10083 | if (!T.isNull() && | |||
10084 | !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, | |||
10085 | NewFD->getType())) | |||
10086 | // The type of this function differs from the type of the builtin, | |||
10087 | // so forget about the builtin entirely. | |||
10088 | Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); | |||
10089 | } | |||
10090 | ||||
10091 | // If this function is declared as being extern "C", then check to see if | |||
10092 | // the function returns a UDT (class, struct, or union type) that is not C | |||
10093 | // compatible, and if it does, warn the user. | |||
10094 | // But, issue any diagnostic on the first declaration only. | |||
10095 | if (Previous.empty() && NewFD->isExternC()) { | |||
10096 | QualType R = NewFD->getReturnType(); | |||
10097 | if (R->isIncompleteType() && !R->isVoidType()) | |||
10098 | Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) | |||
10099 | << NewFD << R; | |||
10100 | else if (!R.isPODType(Context) && !R->isVoidType() && | |||
10101 | !R->isObjCObjectPointerType()) | |||
10102 | Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; | |||
10103 | } | |||
10104 | ||||
10105 | // C++1z [dcl.fct]p6: | |||
10106 | // [...] whether the function has a non-throwing exception-specification | |||
10107 | // [is] part of the function type | |||
10108 | // | |||
10109 | // This results in an ABI break between C++14 and C++17 for functions whose | |||
10110 | // declared type includes an exception-specification in a parameter or | |||
10111 | // return type. (Exception specifications on the function itself are OK in | |||
10112 | // most cases, and exception specifications are not permitted in most other | |||
10113 | // contexts where they could make it into a mangling.) | |||
10114 | if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { | |||
10115 | auto HasNoexcept = [&](QualType T) -> bool { | |||
10116 | // Strip off declarator chunks that could be between us and a function | |||
10117 | // type. We don't need to look far, exception specifications are very | |||
10118 | // restricted prior to C++17. | |||
10119 | if (auto *RT = T->getAs<ReferenceType>()) | |||
10120 | T = RT->getPointeeType(); | |||
10121 | else if (T->isAnyPointerType()) | |||
10122 | T = T->getPointeeType(); | |||
10123 | else if (auto *MPT = T->getAs<MemberPointerType>()) | |||
10124 | T = MPT->getPointeeType(); | |||
10125 | if (auto *FPT = T->getAs<FunctionProtoType>()) | |||
10126 | if (FPT->isNothrow()) | |||
10127 | return true; | |||
10128 | return false; | |||
10129 | }; | |||
10130 | ||||
10131 | auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); | |||
10132 | bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); | |||
10133 | for (QualType T : FPT->param_types()) | |||
10134 | AnyNoexcept |= HasNoexcept(T); | |||
10135 | if (AnyNoexcept) | |||
10136 | Diag(NewFD->getLocation(), | |||
10137 | diag::warn_cxx17_compat_exception_spec_in_signature) | |||
10138 | << NewFD; | |||
10139 | } | |||
10140 | ||||
10141 | if (!Redeclaration && LangOpts.CUDA) | |||
10142 | checkCUDATargetOverload(NewFD, Previous); | |||
10143 | } | |||
10144 | return Redeclaration; | |||
10145 | } | |||
10146 | ||||
10147 | void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { | |||
10148 | // C++11 [basic.start.main]p3: | |||
10149 | // A program that [...] declares main to be inline, static or | |||
10150 | // constexpr is ill-formed. | |||
10151 | // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall | |||
10152 | // appear in a declaration of main. | |||
10153 | // static main is not an error under C99, but we should warn about it. | |||
10154 | // We accept _Noreturn main as an extension. | |||
10155 | if (FD->getStorageClass() == SC_Static) | |||
10156 | Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus | |||
10157 | ? diag::err_static_main : diag::warn_static_main) | |||
10158 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | |||
10159 | if (FD->isInlineSpecified()) | |||
10160 | Diag(DS.getInlineSpecLoc(), diag::err_inline_main) | |||
10161 | << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); | |||
10162 | if (DS.isNoreturnSpecified()) { | |||
10163 | SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); | |||
10164 | SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); | |||
10165 | Diag(NoreturnLoc, diag::ext_noreturn_main); | |||
10166 | Diag(NoreturnLoc, diag::note_main_remove_noreturn) | |||
10167 | << FixItHint::CreateRemoval(NoreturnRange); | |||
10168 | } | |||
10169 | if (FD->isConstexpr()) { | |||
10170 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) | |||
10171 | << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); | |||
10172 | FD->setConstexpr(false); | |||
10173 | } | |||
10174 | ||||
10175 | if (getLangOpts().OpenCL) { | |||
10176 | Diag(FD->getLocation(), diag::err_opencl_no_main) | |||
10177 | << FD->hasAttr<OpenCLKernelAttr>(); | |||
10178 | FD->setInvalidDecl(); | |||
10179 | return; | |||
10180 | } | |||
10181 | ||||
10182 | QualType T = FD->getType(); | |||
10183 | assert(T->isFunctionType() && "function decl is not of function type")(static_cast <bool> (T->isFunctionType() && "function decl is not of function type" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 10183, __extension__ __PRETTY_FUNCTION__)); | |||
10184 | const FunctionType* FT = T->castAs<FunctionType>(); | |||
10185 | ||||
10186 | // Set default calling convention for main() | |||
10187 | if (FT->getCallConv() != CC_C) { | |||
10188 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); | |||
10189 | FD->setType(QualType(FT, 0)); | |||
10190 | T = Context.getCanonicalType(FD->getType()); | |||
10191 | } | |||
10192 | ||||
10193 | if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { | |||
10194 | // In C with GNU extensions we allow main() to have non-integer return | |||
10195 | // type, but we should warn about the extension, and we disable the | |||
10196 | // implicit-return-zero rule. | |||
10197 | ||||
10198 | // GCC in C mode accepts qualified 'int'. | |||
10199 | if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) | |||
10200 | FD->setHasImplicitReturnZero(true); | |||
10201 | else { | |||
10202 | Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); | |||
10203 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | |||
10204 | if (RTRange.isValid()) | |||
10205 | Diag(RTRange.getBegin(), diag::note_main_change_return_type) | |||
10206 | << FixItHint::CreateReplacement(RTRange, "int"); | |||
10207 | } | |||
10208 | } else { | |||
10209 | // In C and C++, main magically returns 0 if you fall off the end; | |||
10210 | // set the flag which tells us that. | |||
10211 | // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. | |||
10212 | ||||
10213 | // All the standards say that main() should return 'int'. | |||
10214 | if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) | |||
10215 | FD->setHasImplicitReturnZero(true); | |||
10216 | else { | |||
10217 | // Otherwise, this is just a flat-out error. | |||
10218 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | |||
10219 | Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) | |||
10220 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") | |||
10221 | : FixItHint()); | |||
10222 | FD->setInvalidDecl(true); | |||
10223 | } | |||
10224 | } | |||
10225 | ||||
10226 | // Treat protoless main() as nullary. | |||
10227 | if (isa<FunctionNoProtoType>(FT)) return; | |||
10228 | ||||
10229 | const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); | |||
10230 | unsigned nparams = FTP->getNumParams(); | |||
10231 | assert(FD->getNumParams() == nparams)(static_cast <bool> (FD->getNumParams() == nparams) ? void (0) : __assert_fail ("FD->getNumParams() == nparams" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 10231, __extension__ __PRETTY_FUNCTION__)); | |||
10232 | ||||
10233 | bool HasExtraParameters = (nparams > 3); | |||
10234 | ||||
10235 | if (FTP->isVariadic()) { | |||
10236 | Diag(FD->getLocation(), diag::ext_variadic_main); | |||
10237 | // FIXME: if we had information about the location of the ellipsis, we | |||
10238 | // could add a FixIt hint to remove it as a parameter. | |||
10239 | } | |||
10240 | ||||
10241 | // Darwin passes an undocumented fourth argument of type char**. If | |||
10242 | // other platforms start sprouting these, the logic below will start | |||
10243 | // getting shifty. | |||
10244 | if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) | |||
10245 | HasExtraParameters = false; | |||
10246 | ||||
10247 | if (HasExtraParameters) { | |||
10248 | Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; | |||
10249 | FD->setInvalidDecl(true); | |||
10250 | nparams = 3; | |||
10251 | } | |||
10252 | ||||
10253 | // FIXME: a lot of the following diagnostics would be improved | |||
10254 | // if we had some location information about types. | |||
10255 | ||||
10256 | QualType CharPP = | |||
10257 | Context.getPointerType(Context.getPointerType(Context.CharTy)); | |||
10258 | QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; | |||
10259 | ||||
10260 | for (unsigned i = 0; i < nparams; ++i) { | |||
10261 | QualType AT = FTP->getParamType(i); | |||
10262 | ||||
10263 | bool mismatch = true; | |||
10264 | ||||
10265 | if (Context.hasSameUnqualifiedType(AT, Expected[i])) | |||
10266 | mismatch = false; | |||
10267 | else if (Expected[i] == CharPP) { | |||
10268 | // As an extension, the following forms are okay: | |||
10269 | // char const ** | |||
10270 | // char const * const * | |||
10271 | // char * const * | |||
10272 | ||||
10273 | QualifierCollector qs; | |||
10274 | const PointerType* PT; | |||
10275 | if ((PT = qs.strip(AT)->getAs<PointerType>()) && | |||
10276 | (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && | |||
10277 | Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), | |||
10278 | Context.CharTy)) { | |||
10279 | qs.removeConst(); | |||
10280 | mismatch = !qs.empty(); | |||
10281 | } | |||
10282 | } | |||
10283 | ||||
10284 | if (mismatch) { | |||
10285 | Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; | |||
10286 | // TODO: suggest replacing given type with expected type | |||
10287 | FD->setInvalidDecl(true); | |||
10288 | } | |||
10289 | } | |||
10290 | ||||
10291 | if (nparams == 1 && !FD->isInvalidDecl()) { | |||
10292 | Diag(FD->getLocation(), diag::warn_main_one_arg); | |||
10293 | } | |||
10294 | ||||
10295 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | |||
10296 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | |||
10297 | FD->setInvalidDecl(); | |||
10298 | } | |||
10299 | } | |||
10300 | ||||
10301 | void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { | |||
10302 | QualType T = FD->getType(); | |||
10303 | assert(T->isFunctionType() && "function decl is not of function type")(static_cast <bool> (T->isFunctionType() && "function decl is not of function type" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 10303, __extension__ __PRETTY_FUNCTION__)); | |||
10304 | const FunctionType *FT = T->castAs<FunctionType>(); | |||
10305 | ||||
10306 | // Set an implicit return of 'zero' if the function can return some integral, | |||
10307 | // enumeration, pointer or nullptr type. | |||
10308 | if (FT->getReturnType()->isIntegralOrEnumerationType() || | |||
10309 | FT->getReturnType()->isAnyPointerType() || | |||
10310 | FT->getReturnType()->isNullPtrType()) | |||
10311 | // DllMain is exempt because a return value of zero means it failed. | |||
10312 | if (FD->getName() != "DllMain") | |||
10313 | FD->setHasImplicitReturnZero(true); | |||
10314 | ||||
10315 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | |||
10316 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | |||
10317 | FD->setInvalidDecl(); | |||
10318 | } | |||
10319 | } | |||
10320 | ||||
10321 | bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { | |||
10322 | // FIXME: Need strict checking. In C89, we need to check for | |||
10323 | // any assignment, increment, decrement, function-calls, or | |||
10324 | // commas outside of a sizeof. In C99, it's the same list, | |||
10325 | // except that the aforementioned are allowed in unevaluated | |||
10326 | // expressions. Everything else falls under the | |||
10327 | // "may accept other forms of constant expressions" exception. | |||
10328 | // (We never end up here for C++, so the constant expression | |||
10329 | // rules there don't matter.) | |||
10330 | const Expr *Culprit; | |||
10331 | if (Init->isConstantInitializer(Context, false, &Culprit)) | |||
10332 | return false; | |||
10333 | Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) | |||
10334 | << Culprit->getSourceRange(); | |||
10335 | return true; | |||
10336 | } | |||
10337 | ||||
10338 | namespace { | |||
10339 | // Visits an initialization expression to see if OrigDecl is evaluated in | |||
10340 | // its own initialization and throws a warning if it does. | |||
10341 | class SelfReferenceChecker | |||
10342 | : public EvaluatedExprVisitor<SelfReferenceChecker> { | |||
10343 | Sema &S; | |||
10344 | Decl *OrigDecl; | |||
10345 | bool isRecordType; | |||
10346 | bool isPODType; | |||
10347 | bool isReferenceType; | |||
10348 | ||||
10349 | bool isInitList; | |||
10350 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | |||
10351 | ||||
10352 | public: | |||
10353 | typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; | |||
10354 | ||||
10355 | SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), | |||
10356 | S(S), OrigDecl(OrigDecl) { | |||
10357 | isPODType = false; | |||
10358 | isRecordType = false; | |||
10359 | isReferenceType = false; | |||
10360 | isInitList = false; | |||
10361 | if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { | |||
10362 | isPODType = VD->getType().isPODType(S.Context); | |||
10363 | isRecordType = VD->getType()->isRecordType(); | |||
10364 | isReferenceType = VD->getType()->isReferenceType(); | |||
10365 | } | |||
10366 | } | |||
10367 | ||||
10368 | // For most expressions, just call the visitor. For initializer lists, | |||
10369 | // track the index of the field being initialized since fields are | |||
10370 | // initialized in order allowing use of previously initialized fields. | |||
10371 | void CheckExpr(Expr *E) { | |||
10372 | InitListExpr *InitList = dyn_cast<InitListExpr>(E); | |||
10373 | if (!InitList) { | |||
10374 | Visit(E); | |||
10375 | return; | |||
10376 | } | |||
10377 | ||||
10378 | // Track and increment the index here. | |||
10379 | isInitList = true; | |||
10380 | InitFieldIndex.push_back(0); | |||
10381 | for (auto Child : InitList->children()) { | |||
10382 | CheckExpr(cast<Expr>(Child)); | |||
10383 | ++InitFieldIndex.back(); | |||
10384 | } | |||
10385 | InitFieldIndex.pop_back(); | |||
10386 | } | |||
10387 | ||||
10388 | // Returns true if MemberExpr is checked and no further checking is needed. | |||
10389 | // Returns false if additional checking is required. | |||
10390 | bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { | |||
10391 | llvm::SmallVector<FieldDecl*, 4> Fields; | |||
10392 | Expr *Base = E; | |||
10393 | bool ReferenceField = false; | |||
10394 | ||||
10395 | // Get the field memebers used. | |||
10396 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | |||
10397 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | |||
10398 | if (!FD) | |||
10399 | return false; | |||
10400 | Fields.push_back(FD); | |||
10401 | if (FD->getType()->isReferenceType()) | |||
10402 | ReferenceField = true; | |||
10403 | Base = ME->getBase()->IgnoreParenImpCasts(); | |||
10404 | } | |||
10405 | ||||
10406 | // Keep checking only if the base Decl is the same. | |||
10407 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); | |||
10408 | if (!DRE || DRE->getDecl() != OrigDecl) | |||
10409 | return false; | |||
10410 | ||||
10411 | // A reference field can be bound to an unininitialized field. | |||
10412 | if (CheckReference && !ReferenceField) | |||
10413 | return true; | |||
10414 | ||||
10415 | // Convert FieldDecls to their index number. | |||
10416 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | |||
10417 | for (const FieldDecl *I : llvm::reverse(Fields)) | |||
10418 | UsedFieldIndex.push_back(I->getFieldIndex()); | |||
10419 | ||||
10420 | // See if a warning is needed by checking the first difference in index | |||
10421 | // numbers. If field being used has index less than the field being | |||
10422 | // initialized, then the use is safe. | |||
10423 | for (auto UsedIter = UsedFieldIndex.begin(), | |||
10424 | UsedEnd = UsedFieldIndex.end(), | |||
10425 | OrigIter = InitFieldIndex.begin(), | |||
10426 | OrigEnd = InitFieldIndex.end(); | |||
10427 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | |||
10428 | if (*UsedIter < *OrigIter) | |||
10429 | return true; | |||
10430 | if (*UsedIter > *OrigIter) | |||
10431 | break; | |||
10432 | } | |||
10433 | ||||
10434 | // TODO: Add a different warning which will print the field names. | |||
10435 | HandleDeclRefExpr(DRE); | |||
10436 | return true; | |||
10437 | } | |||
10438 | ||||
10439 | // For most expressions, the cast is directly above the DeclRefExpr. | |||
10440 | // For conditional operators, the cast can be outside the conditional | |||
10441 | // operator if both expressions are DeclRefExpr's. | |||
10442 | void HandleValue(Expr *E) { | |||
10443 | E = E->IgnoreParens(); | |||
10444 | if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { | |||
10445 | HandleDeclRefExpr(DRE); | |||
10446 | return; | |||
10447 | } | |||
10448 | ||||
10449 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | |||
10450 | Visit(CO->getCond()); | |||
10451 | HandleValue(CO->getTrueExpr()); | |||
10452 | HandleValue(CO->getFalseExpr()); | |||
10453 | return; | |||
10454 | } | |||
10455 | ||||
10456 | if (BinaryConditionalOperator *BCO = | |||
10457 | dyn_cast<BinaryConditionalOperator>(E)) { | |||
10458 | Visit(BCO->getCond()); | |||
10459 | HandleValue(BCO->getFalseExpr()); | |||
10460 | return; | |||
10461 | } | |||
10462 | ||||
10463 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | |||
10464 | HandleValue(OVE->getSourceExpr()); | |||
10465 | return; | |||
10466 | } | |||
10467 | ||||
10468 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
10469 | if (BO->getOpcode() == BO_Comma) { | |||
10470 | Visit(BO->getLHS()); | |||
10471 | HandleValue(BO->getRHS()); | |||
10472 | return; | |||
10473 | } | |||
10474 | } | |||
10475 | ||||
10476 | if (isa<MemberExpr>(E)) { | |||
10477 | if (isInitList) { | |||
10478 | if (CheckInitListMemberExpr(cast<MemberExpr>(E), | |||
10479 | false /*CheckReference*/)) | |||
10480 | return; | |||
10481 | } | |||
10482 | ||||
10483 | Expr *Base = E->IgnoreParenImpCasts(); | |||
10484 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | |||
10485 | // Check for static member variables and don't warn on them. | |||
10486 | if (!isa<FieldDecl>(ME->getMemberDecl())) | |||
10487 | return; | |||
10488 | Base = ME->getBase()->IgnoreParenImpCasts(); | |||
10489 | } | |||
10490 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) | |||
10491 | HandleDeclRefExpr(DRE); | |||
10492 | return; | |||
10493 | } | |||
10494 | ||||
10495 | Visit(E); | |||
10496 | } | |||
10497 | ||||
10498 | // Reference types not handled in HandleValue are handled here since all | |||
10499 | // uses of references are bad, not just r-value uses. | |||
10500 | void VisitDeclRefExpr(DeclRefExpr *E) { | |||
10501 | if (isReferenceType) | |||
10502 | HandleDeclRefExpr(E); | |||
10503 | } | |||
10504 | ||||
10505 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
10506 | if (E->getCastKind() == CK_LValueToRValue) { | |||
10507 | HandleValue(E->getSubExpr()); | |||
10508 | return; | |||
10509 | } | |||
10510 | ||||
10511 | Inherited::VisitImplicitCastExpr(E); | |||
10512 | } | |||
10513 | ||||
10514 | void VisitMemberExpr(MemberExpr *E) { | |||
10515 | if (isInitList) { | |||
10516 | if (CheckInitListMemberExpr(E, true /*CheckReference*/)) | |||
10517 | return; | |||
10518 | } | |||
10519 | ||||
10520 | // Don't warn on arrays since they can be treated as pointers. | |||
10521 | if (E->getType()->canDecayToPointerType()) return; | |||
10522 | ||||
10523 | // Warn when a non-static method call is followed by non-static member | |||
10524 | // field accesses, which is followed by a DeclRefExpr. | |||
10525 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); | |||
10526 | bool Warn = (MD && !MD->isStatic()); | |||
10527 | Expr *Base = E->getBase()->IgnoreParenImpCasts(); | |||
10528 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | |||
10529 | if (!isa<FieldDecl>(ME->getMemberDecl())) | |||
10530 | Warn = false; | |||
10531 | Base = ME->getBase()->IgnoreParenImpCasts(); | |||
10532 | } | |||
10533 | ||||
10534 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { | |||
10535 | if (Warn) | |||
10536 | HandleDeclRefExpr(DRE); | |||
10537 | return; | |||
10538 | } | |||
10539 | ||||
10540 | // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. | |||
10541 | // Visit that expression. | |||
10542 | Visit(Base); | |||
10543 | } | |||
10544 | ||||
10545 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | |||
10546 | Expr *Callee = E->getCallee(); | |||
10547 | ||||
10548 | if (isa<UnresolvedLookupExpr>(Callee)) | |||
10549 | return Inherited::VisitCXXOperatorCallExpr(E); | |||
10550 | ||||
10551 | Visit(Callee); | |||
10552 | for (auto Arg: E->arguments()) | |||
10553 | HandleValue(Arg->IgnoreParenImpCasts()); | |||
10554 | } | |||
10555 | ||||
10556 | void VisitUnaryOperator(UnaryOperator *E) { | |||
10557 | // For POD record types, addresses of its own members are well-defined. | |||
10558 | if (E->getOpcode() == UO_AddrOf && isRecordType && | |||
10559 | isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { | |||
10560 | if (!isPODType) | |||
10561 | HandleValue(E->getSubExpr()); | |||
10562 | return; | |||
10563 | } | |||
10564 | ||||
10565 | if (E->isIncrementDecrementOp()) { | |||
10566 | HandleValue(E->getSubExpr()); | |||
10567 | return; | |||
10568 | } | |||
10569 | ||||
10570 | Inherited::VisitUnaryOperator(E); | |||
10571 | } | |||
10572 | ||||
10573 | void VisitObjCMessageExpr(ObjCMessageExpr *E) {} | |||
10574 | ||||
10575 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | |||
10576 | if (E->getConstructor()->isCopyConstructor()) { | |||
10577 | Expr *ArgExpr = E->getArg(0); | |||
10578 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | |||
10579 | if (ILE->getNumInits() == 1) | |||
10580 | ArgExpr = ILE->getInit(0); | |||
10581 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | |||
10582 | if (ICE->getCastKind() == CK_NoOp) | |||
10583 | ArgExpr = ICE->getSubExpr(); | |||
10584 | HandleValue(ArgExpr); | |||
10585 | return; | |||
10586 | } | |||
10587 | Inherited::VisitCXXConstructExpr(E); | |||
10588 | } | |||
10589 | ||||
10590 | void VisitCallExpr(CallExpr *E) { | |||
10591 | // Treat std::move as a use. | |||
10592 | if (E->isCallToStdMove()) { | |||
10593 | HandleValue(E->getArg(0)); | |||
10594 | return; | |||
10595 | } | |||
10596 | ||||
10597 | Inherited::VisitCallExpr(E); | |||
10598 | } | |||
10599 | ||||
10600 | void VisitBinaryOperator(BinaryOperator *E) { | |||
10601 | if (E->isCompoundAssignmentOp()) { | |||
10602 | HandleValue(E->getLHS()); | |||
10603 | Visit(E->getRHS()); | |||
10604 | return; | |||
10605 | } | |||
10606 | ||||
10607 | Inherited::VisitBinaryOperator(E); | |||
10608 | } | |||
10609 | ||||
10610 | // A custom visitor for BinaryConditionalOperator is needed because the | |||
10611 | // regular visitor would check the condition and true expression separately | |||
10612 | // but both point to the same place giving duplicate diagnostics. | |||
10613 | void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { | |||
10614 | Visit(E->getCond()); | |||
10615 | Visit(E->getFalseExpr()); | |||
10616 | } | |||
10617 | ||||
10618 | void HandleDeclRefExpr(DeclRefExpr *DRE) { | |||
10619 | Decl* ReferenceDecl = DRE->getDecl(); | |||
10620 | if (OrigDecl != ReferenceDecl) return; | |||
10621 | unsigned diag; | |||
10622 | if (isReferenceType) { | |||
10623 | diag = diag::warn_uninit_self_reference_in_reference_init; | |||
10624 | } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { | |||
10625 | diag = diag::warn_static_self_reference_in_init; | |||
10626 | } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || | |||
10627 | isa<NamespaceDecl>(OrigDecl->getDeclContext()) || | |||
10628 | DRE->getDecl()->getType()->isRecordType()) { | |||
10629 | diag = diag::warn_uninit_self_reference_in_init; | |||
10630 | } else { | |||
10631 | // Local variables will be handled by the CFG analysis. | |||
10632 | return; | |||
10633 | } | |||
10634 | ||||
10635 | S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, | |||
10636 | S.PDiag(diag) | |||
10637 | << DRE->getDecl() | |||
10638 | << OrigDecl->getLocation() | |||
10639 | << DRE->getSourceRange()); | |||
10640 | } | |||
10641 | }; | |||
10642 | ||||
10643 | /// CheckSelfReference - Warns if OrigDecl is used in expression E. | |||
10644 | static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, | |||
10645 | bool DirectInit) { | |||
10646 | // Parameters arguments are occassionially constructed with itself, | |||
10647 | // for instance, in recursive functions. Skip them. | |||
10648 | if (isa<ParmVarDecl>(OrigDecl)) | |||
10649 | return; | |||
10650 | ||||
10651 | E = E->IgnoreParens(); | |||
10652 | ||||
10653 | // Skip checking T a = a where T is not a record or reference type. | |||
10654 | // Doing so is a way to silence uninitialized warnings. | |||
10655 | if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) | |||
10656 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) | |||
10657 | if (ICE->getCastKind() == CK_LValueToRValue) | |||
10658 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) | |||
10659 | if (DRE->getDecl() == OrigDecl) | |||
10660 | return; | |||
10661 | ||||
10662 | SelfReferenceChecker(S, OrigDecl).CheckExpr(E); | |||
10663 | } | |||
10664 | } // end anonymous namespace | |||
10665 | ||||
10666 | namespace { | |||
10667 | // Simple wrapper to add the name of a variable or (if no variable is | |||
10668 | // available) a DeclarationName into a diagnostic. | |||
10669 | struct VarDeclOrName { | |||
10670 | VarDecl *VDecl; | |||
10671 | DeclarationName Name; | |||
10672 | ||||
10673 | friend const Sema::SemaDiagnosticBuilder & | |||
10674 | operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { | |||
10675 | return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; | |||
10676 | } | |||
10677 | }; | |||
10678 | } // end anonymous namespace | |||
10679 | ||||
10680 | QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, | |||
10681 | DeclarationName Name, QualType Type, | |||
10682 | TypeSourceInfo *TSI, | |||
10683 | SourceRange Range, bool DirectInit, | |||
10684 | Expr *Init) { | |||
10685 | bool IsInitCapture = !VDecl; | |||
10686 | assert((!VDecl || !VDecl->isInitCapture()) &&(static_cast <bool> ((!VDecl || !VDecl->isInitCapture ()) && "init captures are expected to be deduced prior to initialization" ) ? void (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 10687, __extension__ __PRETTY_FUNCTION__)) | |||
10687 | "init captures are expected to be deduced prior to initialization")(static_cast <bool> ((!VDecl || !VDecl->isInitCapture ()) && "init captures are expected to be deduced prior to initialization" ) ? void (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 10687, __extension__ __PRETTY_FUNCTION__)); | |||
10688 | ||||
10689 | VarDeclOrName VN{VDecl, Name}; | |||
10690 | ||||
10691 | DeducedType *Deduced = Type->getContainedDeducedType(); | |||
10692 | assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")(static_cast <bool> (Deduced && "deduceVarTypeFromInitializer for non-deduced type" ) ? void (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 10692, __extension__ __PRETTY_FUNCTION__)); | |||
10693 | ||||
10694 | // C++11 [dcl.spec.auto]p3 | |||
10695 | if (!Init) { | |||
10696 | assert(VDecl && "no init for init capture deduction?")(static_cast <bool> (VDecl && "no init for init capture deduction?" ) ? void (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 10696, __extension__ __PRETTY_FUNCTION__)); | |||
10697 | ||||
10698 | // Except for class argument deduction, and then for an initializing | |||
10699 | // declaration only, i.e. no static at class scope or extern. | |||
10700 | if (!isa<DeducedTemplateSpecializationType>(Deduced) || | |||
10701 | VDecl->hasExternalStorage() || | |||
10702 | VDecl->isStaticDataMember()) { | |||
10703 | Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) | |||
10704 | << VDecl->getDeclName() << Type; | |||
10705 | return QualType(); | |||
10706 | } | |||
10707 | } | |||
10708 | ||||
10709 | ArrayRef<Expr*> DeduceInits; | |||
10710 | if (Init) | |||
10711 | DeduceInits = Init; | |||
10712 | ||||
10713 | if (DirectInit) { | |||
10714 | if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) | |||
10715 | DeduceInits = PL->exprs(); | |||
10716 | } | |||
10717 | ||||
10718 | if (isa<DeducedTemplateSpecializationType>(Deduced)) { | |||
10719 | assert(VDecl && "non-auto type for init capture deduction?")(static_cast <bool> (VDecl && "non-auto type for init capture deduction?" ) ? void (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 10719, __extension__ __PRETTY_FUNCTION__)); | |||
10720 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | |||
10721 | InitializationKind Kind = InitializationKind::CreateForInit( | |||
10722 | VDecl->getLocation(), DirectInit, Init); | |||
10723 | // FIXME: Initialization should not be taking a mutable list of inits. | |||
10724 | SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); | |||
10725 | return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, | |||
10726 | InitsCopy); | |||
10727 | } | |||
10728 | ||||
10729 | if (DirectInit) { | |||
10730 | if (auto *IL = dyn_cast<InitListExpr>(Init)) | |||
10731 | DeduceInits = IL->inits(); | |||
10732 | } | |||
10733 | ||||
10734 | // Deduction only works if we have exactly one source expression. | |||
10735 | if (DeduceInits.empty()) { | |||
10736 | // It isn't possible to write this directly, but it is possible to | |||
10737 | // end up in this situation with "auto x(some_pack...);" | |||
10738 | Diag(Init->getLocStart(), IsInitCapture | |||
10739 | ? diag::err_init_capture_no_expression | |||
10740 | : diag::err_auto_var_init_no_expression) | |||
10741 | << VN << Type << Range; | |||
10742 | return QualType(); | |||
10743 | } | |||
10744 | ||||
10745 | if (DeduceInits.size() > 1) { | |||
10746 | Diag(DeduceInits[1]->getLocStart(), | |||
10747 | IsInitCapture ? diag::err_init_capture_multiple_expressions | |||
10748 | : diag::err_auto_var_init_multiple_expressions) | |||
10749 | << VN << Type << Range; | |||
10750 | return QualType(); | |||
10751 | } | |||
10752 | ||||
10753 | Expr *DeduceInit = DeduceInits[0]; | |||
10754 | if (DirectInit && isa<InitListExpr>(DeduceInit)) { | |||
10755 | Diag(Init->getLocStart(), IsInitCapture | |||
10756 | ? diag::err_init_capture_paren_braces | |||
10757 | : diag::err_auto_var_init_paren_braces) | |||
10758 | << isa<InitListExpr>(Init) << VN << Type << Range; | |||
10759 | return QualType(); | |||
10760 | } | |||
10761 | ||||
10762 | // Expressions default to 'id' when we're in a debugger. | |||
10763 | bool DefaultedAnyToId = false; | |||
10764 | if (getLangOpts().DebuggerCastResultToId && | |||
10765 | Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { | |||
10766 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | |||
10767 | if (Result.isInvalid()) { | |||
10768 | return QualType(); | |||
10769 | } | |||
10770 | Init = Result.get(); | |||
10771 | DefaultedAnyToId = true; | |||
10772 | } | |||
10773 | ||||
10774 | // C++ [dcl.decomp]p1: | |||
10775 | // If the assignment-expression [...] has array type A and no ref-qualifier | |||
10776 | // is present, e has type cv A | |||
10777 | if (VDecl && isa<DecompositionDecl>(VDecl) && | |||
10778 | Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && | |||
10779 | DeduceInit->getType()->isConstantArrayType()) | |||
10780 | return Context.getQualifiedType(DeduceInit->getType(), | |||
10781 | Type.getQualifiers()); | |||
10782 | ||||
10783 | QualType DeducedType; | |||
10784 | if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { | |||
10785 | if (!IsInitCapture) | |||
10786 | DiagnoseAutoDeductionFailure(VDecl, DeduceInit); | |||
10787 | else if (isa<InitListExpr>(Init)) | |||
10788 | Diag(Range.getBegin(), | |||
10789 | diag::err_init_capture_deduction_failure_from_init_list) | |||
10790 | << VN | |||
10791 | << (DeduceInit->getType().isNull() ? TSI->getType() | |||
10792 | : DeduceInit->getType()) | |||
10793 | << DeduceInit->getSourceRange(); | |||
10794 | else | |||
10795 | Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) | |||
10796 | << VN << TSI->getType() | |||
10797 | << (DeduceInit->getType().isNull() ? TSI->getType() | |||
10798 | : DeduceInit->getType()) | |||
10799 | << DeduceInit->getSourceRange(); | |||
10800 | } | |||
10801 | ||||
10802 | // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using | |||
10803 | // 'id' instead of a specific object type prevents most of our usual | |||
10804 | // checks. | |||
10805 | // We only want to warn outside of template instantiations, though: | |||
10806 | // inside a template, the 'id' could have come from a parameter. | |||
10807 | if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && | |||
10808 | !DeducedType.isNull() && DeducedType->isObjCIdType()) { | |||
10809 | SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); | |||
10810 | Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; | |||
10811 | } | |||
10812 | ||||
10813 | return DeducedType; | |||
10814 | } | |||
10815 | ||||
10816 | bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, | |||
10817 | Expr *Init) { | |||
10818 | QualType DeducedType = deduceVarTypeFromInitializer( | |||
10819 | VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), | |||
10820 | VDecl->getSourceRange(), DirectInit, Init); | |||
10821 | if (DeducedType.isNull()) { | |||
10822 | VDecl->setInvalidDecl(); | |||
10823 | return true; | |||
10824 | } | |||
10825 | ||||
10826 | VDecl->setType(DeducedType); | |||
10827 | assert(VDecl->isLinkageValid())(static_cast <bool> (VDecl->isLinkageValid()) ? void (0) : __assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 10827, __extension__ __PRETTY_FUNCTION__)); | |||
10828 | ||||
10829 | // In ARC, infer lifetime. | |||
10830 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) | |||
10831 | VDecl->setInvalidDecl(); | |||
10832 | ||||
10833 | // If this is a redeclaration, check that the type we just deduced matches | |||
10834 | // the previously declared type. | |||
10835 | if (VarDecl *Old = VDecl->getPreviousDecl()) { | |||
10836 | // We never need to merge the type, because we cannot form an incomplete | |||
10837 | // array of auto, nor deduce such a type. | |||
10838 | MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); | |||
10839 | } | |||
10840 | ||||
10841 | // Check the deduced type is valid for a variable declaration. | |||
10842 | CheckVariableDeclarationType(VDecl); | |||
10843 | return VDecl->isInvalidDecl(); | |||
10844 | } | |||
10845 | ||||
10846 | /// AddInitializerToDecl - Adds the initializer Init to the | |||
10847 | /// declaration dcl. If DirectInit is true, this is C++ direct | |||
10848 | /// initialization rather than copy initialization. | |||
10849 | void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { | |||
10850 | // If there is no declaration, there was an error parsing it. Just ignore | |||
10851 | // the initializer. | |||
10852 | if (!RealDecl || RealDecl->isInvalidDecl()) { | |||
10853 | CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); | |||
10854 | return; | |||
10855 | } | |||
10856 | ||||
10857 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { | |||
10858 | // Pure-specifiers are handled in ActOnPureSpecifier. | |||
10859 | Diag(Method->getLocation(), diag::err_member_function_initialization) | |||
10860 | << Method->getDeclName() << Init->getSourceRange(); | |||
10861 | Method->setInvalidDecl(); | |||
10862 | return; | |||
10863 | } | |||
10864 | ||||
10865 | VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); | |||
10866 | if (!VDecl) { | |||
10867 | assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")(static_cast <bool> (!isa<FieldDecl>(RealDecl) && "field init shouldn't get here") ? void (0) : __assert_fail ( "!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 10867, __extension__ __PRETTY_FUNCTION__)); | |||
10868 | Diag(RealDecl->getLocation(), diag::err_illegal_initializer); | |||
10869 | RealDecl->setInvalidDecl(); | |||
10870 | return; | |||
10871 | } | |||
10872 | ||||
10873 | // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. | |||
10874 | if (VDecl->getType()->isUndeducedType()) { | |||
10875 | // Attempt typo correction early so that the type of the init expression can | |||
10876 | // be deduced based on the chosen correction if the original init contains a | |||
10877 | // TypoExpr. | |||
10878 | ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); | |||
10879 | if (!Res.isUsable()) { | |||
10880 | RealDecl->setInvalidDecl(); | |||
10881 | return; | |||
10882 | } | |||
10883 | Init = Res.get(); | |||
10884 | ||||
10885 | if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) | |||
10886 | return; | |||
10887 | } | |||
10888 | ||||
10889 | // dllimport cannot be used on variable definitions. | |||
10890 | if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { | |||
10891 | Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); | |||
10892 | VDecl->setInvalidDecl(); | |||
10893 | return; | |||
10894 | } | |||
10895 | ||||
10896 | if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { | |||
10897 | // C99 6.7.8p5. C++ has no such restriction, but that is a defect. | |||
10898 | Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); | |||
10899 | VDecl->setInvalidDecl(); | |||
10900 | return; | |||
10901 | } | |||
10902 | ||||
10903 | if (!VDecl->getType()->isDependentType()) { | |||
10904 | // A definition must end up with a complete type, which means it must be | |||
10905 | // complete with the restriction that an array type might be completed by | |||
10906 | // the initializer; note that later code assumes this restriction. | |||
10907 | QualType BaseDeclType = VDecl->getType(); | |||
10908 | if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) | |||
10909 | BaseDeclType = Array->getElementType(); | |||
10910 | if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, | |||
10911 | diag::err_typecheck_decl_incomplete_type)) { | |||
10912 | RealDecl->setInvalidDecl(); | |||
10913 | return; | |||
10914 | } | |||
10915 | ||||
10916 | // The variable can not have an abstract class type. | |||
10917 | if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), | |||
10918 | diag::err_abstract_type_in_decl, | |||
10919 | AbstractVariableType)) | |||
10920 | VDecl->setInvalidDecl(); | |||
10921 | } | |||
10922 | ||||
10923 | // If adding the initializer will turn this declaration into a definition, | |||
10924 | // and we already have a definition for this variable, diagnose or otherwise | |||
10925 | // handle the situation. | |||
10926 | VarDecl *Def; | |||
10927 | if ((Def = VDecl->getDefinition()) && Def != VDecl && | |||
10928 | (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && | |||
10929 | !VDecl->isThisDeclarationADemotedDefinition() && | |||
10930 | checkVarDeclRedefinition(Def, VDecl)) | |||
10931 | return; | |||
10932 | ||||
10933 | if (getLangOpts().CPlusPlus) { | |||
10934 | // C++ [class.static.data]p4 | |||
10935 | // If a static data member is of const integral or const | |||
10936 | // enumeration type, its declaration in the class definition can | |||
10937 | // specify a constant-initializer which shall be an integral | |||
10938 | // constant expression (5.19). In that case, the member can appear | |||
10939 | // in integral constant expressions. The member shall still be | |||
10940 | // defined in a namespace scope if it is used in the program and the | |||
10941 | // namespace scope definition shall not contain an initializer. | |||
10942 | // | |||
10943 | // We already performed a redefinition check above, but for static | |||
10944 | // data members we also need to check whether there was an in-class | |||
10945 | // declaration with an initializer. | |||
10946 | if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { | |||
10947 | Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) | |||
10948 | << VDecl->getDeclName(); | |||
10949 | Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), | |||
10950 | diag::note_previous_initializer) | |||
10951 | << 0; | |||
10952 | return; | |||
10953 | } | |||
10954 | ||||
10955 | if (VDecl->hasLocalStorage()) | |||
10956 | setFunctionHasBranchProtectedScope(); | |||
10957 | ||||
10958 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { | |||
10959 | VDecl->setInvalidDecl(); | |||
10960 | return; | |||
10961 | } | |||
10962 | } | |||
10963 | ||||
10964 | // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside | |||
10965 | // a kernel function cannot be initialized." | |||
10966 | if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { | |||
10967 | Diag(VDecl->getLocation(), diag::err_local_cant_init); | |||
10968 | VDecl->setInvalidDecl(); | |||
10969 | return; | |||
10970 | } | |||
10971 | ||||
10972 | // Get the decls type and save a reference for later, since | |||
10973 | // CheckInitializerTypes may change it. | |||
10974 | QualType DclT = VDecl->getType(), SavT = DclT; | |||
10975 | ||||
10976 | // Expressions default to 'id' when we're in a debugger | |||
10977 | // and we are assigning it to a variable of Objective-C pointer type. | |||
10978 | if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && | |||
10979 | Init->getType() == Context.UnknownAnyTy) { | |||
10980 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | |||
10981 | if (Result.isInvalid()) { | |||
10982 | VDecl->setInvalidDecl(); | |||
10983 | return; | |||
10984 | } | |||
10985 | Init = Result.get(); | |||
10986 | } | |||
10987 | ||||
10988 | // Perform the initialization. | |||
10989 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); | |||
10990 | if (!VDecl->isInvalidDecl()) { | |||
10991 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | |||
10992 | InitializationKind Kind = InitializationKind::CreateForInit( | |||
10993 | VDecl->getLocation(), DirectInit, Init); | |||
10994 | ||||
10995 | MultiExprArg Args = Init; | |||
10996 | if (CXXDirectInit) | |||
10997 | Args = MultiExprArg(CXXDirectInit->getExprs(), | |||
10998 | CXXDirectInit->getNumExprs()); | |||
10999 | ||||
11000 | // Try to correct any TypoExprs in the initialization arguments. | |||
11001 | for (size_t Idx = 0; Idx < Args.size(); ++Idx) { | |||
11002 | ExprResult Res = CorrectDelayedTyposInExpr( | |||
11003 | Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { | |||
11004 | InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); | |||
11005 | return Init.Failed() ? ExprError() : E; | |||
11006 | }); | |||
11007 | if (Res.isInvalid()) { | |||
11008 | VDecl->setInvalidDecl(); | |||
11009 | } else if (Res.get() != Args[Idx]) { | |||
11010 | Args[Idx] = Res.get(); | |||
11011 | } | |||
11012 | } | |||
11013 | if (VDecl->isInvalidDecl()) | |||
11014 | return; | |||
11015 | ||||
11016 | InitializationSequence InitSeq(*this, Entity, Kind, Args, | |||
11017 | /*TopLevelOfInitList=*/false, | |||
11018 | /*TreatUnavailableAsInvalid=*/false); | |||
11019 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); | |||
11020 | if (Result.isInvalid()) { | |||
11021 | VDecl->setInvalidDecl(); | |||
11022 | return; | |||
11023 | } | |||
11024 | ||||
11025 | Init = Result.getAs<Expr>(); | |||
11026 | } | |||
11027 | ||||
11028 | // Check for self-references within variable initializers. | |||
11029 | // Variables declared within a function/method body (except for references) | |||
11030 | // are handled by a dataflow analysis. | |||
11031 | if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || | |||
11032 | VDecl->getType()->isReferenceType()) { | |||
11033 | CheckSelfReference(*this, RealDecl, Init, DirectInit); | |||
11034 | } | |||
11035 | ||||
11036 | // If the type changed, it means we had an incomplete type that was | |||
11037 | // completed by the initializer. For example: | |||
11038 | // int ary[] = { 1, 3, 5 }; | |||
11039 | // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. | |||
11040 | if (!VDecl->isInvalidDecl() && (DclT != SavT)) | |||
11041 | VDecl->setType(DclT); | |||
11042 | ||||
11043 | if (!VDecl->isInvalidDecl()) { | |||
11044 | checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); | |||
11045 | ||||
11046 | if (VDecl->hasAttr<BlocksAttr>()) | |||
11047 | checkRetainCycles(VDecl, Init); | |||
11048 | ||||
11049 | // It is safe to assign a weak reference into a strong variable. | |||
11050 | // Although this code can still have problems: | |||
11051 | // id x = self.weakProp; | |||
11052 | // id y = self.weakProp; | |||
11053 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | |||
11054 | // paths through the function. This should be revisited if | |||
11055 | // -Wrepeated-use-of-weak is made flow-sensitive. | |||
11056 | if (FunctionScopeInfo *FSI = getCurFunction()) | |||
11057 | if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || | |||
11058 | VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && | |||
11059 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | |||
11060 | Init->getLocStart())) | |||
11061 | FSI->markSafeWeakUse(Init); | |||
11062 | } | |||
11063 | ||||
11064 | // The initialization is usually a full-expression. | |||
11065 | // | |||
11066 | // FIXME: If this is a braced initialization of an aggregate, it is not | |||
11067 | // an expression, and each individual field initializer is a separate | |||
11068 | // full-expression. For instance, in: | |||
11069 | // | |||
11070 | // struct Temp { ~Temp(); }; | |||
11071 | // struct S { S(Temp); }; | |||
11072 | // struct T { S a, b; } t = { Temp(), Temp() } | |||
11073 | // | |||
11074 | // we should destroy the first Temp before constructing the second. | |||
11075 | ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), | |||
11076 | false, | |||
11077 | VDecl->isConstexpr()); | |||
11078 | if (Result.isInvalid()) { | |||
11079 | VDecl->setInvalidDecl(); | |||
11080 | return; | |||
11081 | } | |||
11082 | Init = Result.get(); | |||
11083 | ||||
11084 | // Attach the initializer to the decl. | |||
11085 | VDecl->setInit(Init); | |||
11086 | ||||
11087 | if (VDecl->isLocalVarDecl()) { | |||
11088 | // Don't check the initializer if the declaration is malformed. | |||
11089 | if (VDecl->isInvalidDecl()) { | |||
11090 | // do nothing | |||
11091 | ||||
11092 | // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. | |||
11093 | // This is true even in OpenCL C++. | |||
11094 | } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { | |||
11095 | CheckForConstantInitializer(Init, DclT); | |||
11096 | ||||
11097 | // Otherwise, C++ does not restrict the initializer. | |||
11098 | } else if (getLangOpts().CPlusPlus) { | |||
11099 | // do nothing | |||
11100 | ||||
11101 | // C99 6.7.8p4: All the expressions in an initializer for an object that has | |||
11102 | // static storage duration shall be constant expressions or string literals. | |||
11103 | } else if (VDecl->getStorageClass() == SC_Static) { | |||
11104 | CheckForConstantInitializer(Init, DclT); | |||
11105 | ||||
11106 | // C89 is stricter than C99 for aggregate initializers. | |||
11107 | // C89 6.5.7p3: All the expressions [...] in an initializer list | |||
11108 | // for an object that has aggregate or union type shall be | |||
11109 | // constant expressions. | |||
11110 | } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && | |||
11111 | isa<InitListExpr>(Init)) { | |||
11112 | const Expr *Culprit; | |||
11113 | if (!Init->isConstantInitializer(Context, false, &Culprit)) { | |||
11114 | Diag(Culprit->getExprLoc(), | |||
11115 | diag::ext_aggregate_init_not_constant) | |||
11116 | << Culprit->getSourceRange(); | |||
11117 | } | |||
11118 | } | |||
11119 | } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && | |||
11120 | VDecl->getLexicalDeclContext()->isRecord()) { | |||
11121 | // This is an in-class initialization for a static data member, e.g., | |||
11122 | // | |||
11123 | // struct S { | |||
11124 | // static const int value = 17; | |||
11125 | // }; | |||
11126 | ||||
11127 | // C++ [class.mem]p4: | |||
11128 | // A member-declarator can contain a constant-initializer only | |||
11129 | // if it declares a static member (9.4) of const integral or | |||
11130 | // const enumeration type, see 9.4.2. | |||
11131 | // | |||
11132 | // C++11 [class.static.data]p3: | |||
11133 | // If a non-volatile non-inline const static data member is of integral | |||
11134 | // or enumeration type, its declaration in the class definition can | |||
11135 | // specify a brace-or-equal-initializer in which every initializer-clause | |||
11136 | // that is an assignment-expression is a constant expression. A static | |||
11137 | // data member of literal type can be declared in the class definition | |||
11138 | // with the constexpr specifier; if so, its declaration shall specify a | |||
11139 | // brace-or-equal-initializer in which every initializer-clause that is | |||
11140 | // an assignment-expression is a constant expression. | |||
11141 | ||||
11142 | // Do nothing on dependent types. | |||
11143 | if (DclT->isDependentType()) { | |||
11144 | ||||
11145 | // Allow any 'static constexpr' members, whether or not they are of literal | |||
11146 | // type. We separately check that every constexpr variable is of literal | |||
11147 | // type. | |||
11148 | } else if (VDecl->isConstexpr()) { | |||
11149 | ||||
11150 | // Require constness. | |||
11151 | } else if (!DclT.isConstQualified()) { | |||
11152 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) | |||
11153 | << Init->getSourceRange(); | |||
11154 | VDecl->setInvalidDecl(); | |||
11155 | ||||
11156 | // We allow integer constant expressions in all cases. | |||
11157 | } else if (DclT->isIntegralOrEnumerationType()) { | |||
11158 | // Check whether the expression is a constant expression. | |||
11159 | SourceLocation Loc; | |||
11160 | if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) | |||
11161 | // In C++11, a non-constexpr const static data member with an | |||
11162 | // in-class initializer cannot be volatile. | |||
11163 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); | |||
11164 | else if (Init->isValueDependent()) | |||
11165 | ; // Nothing to check. | |||
11166 | else if (Init->isIntegerConstantExpr(Context, &Loc)) | |||
11167 | ; // Ok, it's an ICE! | |||
11168 | else if (Init->getType()->isScopedEnumeralType() && | |||
11169 | Init->isCXX11ConstantExpr(Context)) | |||
11170 | ; // Ok, it is a scoped-enum constant expression. | |||
11171 | else if (Init->isEvaluatable(Context)) { | |||
11172 | // If we can constant fold the initializer through heroics, accept it, | |||
11173 | // but report this as a use of an extension for -pedantic. | |||
11174 | Diag(Loc, diag::ext_in_class_initializer_non_constant) | |||
11175 | << Init->getSourceRange(); | |||
11176 | } else { | |||
11177 | // Otherwise, this is some crazy unknown case. Report the issue at the | |||
11178 | // location provided by the isIntegerConstantExpr failed check. | |||
11179 | Diag(Loc, diag::err_in_class_initializer_non_constant) | |||
11180 | << Init->getSourceRange(); | |||
11181 | VDecl->setInvalidDecl(); | |||
11182 | } | |||
11183 | ||||
11184 | // We allow foldable floating-point constants as an extension. | |||
11185 | } else if (DclT->isFloatingType()) { // also permits complex, which is ok | |||
11186 | // In C++98, this is a GNU extension. In C++11, it is not, but we support | |||
11187 | // it anyway and provide a fixit to add the 'constexpr'. | |||
11188 | if (getLangOpts().CPlusPlus11) { | |||
11189 | Diag(VDecl->getLocation(), | |||
11190 | diag::ext_in_class_initializer_float_type_cxx11) | |||
11191 | << DclT << Init->getSourceRange(); | |||
11192 | Diag(VDecl->getLocStart(), | |||
11193 | diag::note_in_class_initializer_float_type_cxx11) | |||
11194 | << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); | |||
11195 | } else { | |||
11196 | Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) | |||
11197 | << DclT << Init->getSourceRange(); | |||
11198 | ||||
11199 | if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { | |||
11200 | Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) | |||
11201 | << Init->getSourceRange(); | |||
11202 | VDecl->setInvalidDecl(); | |||
11203 | } | |||
11204 | } | |||
11205 | ||||
11206 | // Suggest adding 'constexpr' in C++11 for literal types. | |||
11207 | } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { | |||
11208 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) | |||
11209 | << DclT << Init->getSourceRange() | |||
11210 | << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); | |||
11211 | VDecl->setConstexpr(true); | |||
11212 | ||||
11213 | } else { | |||
11214 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) | |||
11215 | << DclT << Init->getSourceRange(); | |||
11216 | VDecl->setInvalidDecl(); | |||
11217 | } | |||
11218 | } else if (VDecl->isFileVarDecl()) { | |||
11219 | // In C, extern is typically used to avoid tentative definitions when | |||
11220 | // declaring variables in headers, but adding an intializer makes it a | |||
11221 | // definition. This is somewhat confusing, so GCC and Clang both warn on it. | |||
11222 | // In C++, extern is often used to give implictly static const variables | |||
11223 | // external linkage, so don't warn in that case. If selectany is present, | |||
11224 | // this might be header code intended for C and C++ inclusion, so apply the | |||
11225 | // C++ rules. | |||
11226 | if (VDecl->getStorageClass() == SC_Extern && | |||
11227 | ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || | |||
11228 | !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && | |||
11229 | !(getLangOpts().CPlusPlus && VDecl->isExternC()) && | |||
11230 | !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) | |||
11231 | Diag(VDecl->getLocation(), diag::warn_extern_init); | |||
11232 | ||||
11233 | // C99 6.7.8p4. All file scoped initializers need to be constant. | |||
11234 | if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) | |||
11235 | CheckForConstantInitializer(Init, DclT); | |||
11236 | } | |||
11237 | ||||
11238 | // We will represent direct-initialization similarly to copy-initialization: | |||
11239 | // int x(1); -as-> int x = 1; | |||
11240 | // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); | |||
11241 | // | |||
11242 | // Clients that want to distinguish between the two forms, can check for | |||
11243 | // direct initializer using VarDecl::getInitStyle(). | |||
11244 | // A major benefit is that clients that don't particularly care about which | |||
11245 | // exactly form was it (like the CodeGen) can handle both cases without | |||
11246 | // special case code. | |||
11247 | ||||
11248 | // C++ 8.5p11: | |||
11249 | // The form of initialization (using parentheses or '=') is generally | |||
11250 | // insignificant, but does matter when the entity being initialized has a | |||
11251 | // class type. | |||
11252 | if (CXXDirectInit) { | |||
11253 | assert(DirectInit && "Call-style initializer must be direct init.")(static_cast <bool> (DirectInit && "Call-style initializer must be direct init." ) ? void (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 11253, __extension__ __PRETTY_FUNCTION__)); | |||
11254 | VDecl->setInitStyle(VarDecl::CallInit); | |||
11255 | } else if (DirectInit) { | |||
11256 | // This must be list-initialization. No other way is direct-initialization. | |||
11257 | VDecl->setInitStyle(VarDecl::ListInit); | |||
11258 | } | |||
11259 | ||||
11260 | CheckCompleteVariableDeclaration(VDecl); | |||
11261 | } | |||
11262 | ||||
11263 | /// ActOnInitializerError - Given that there was an error parsing an | |||
11264 | /// initializer for the given declaration, try to return to some form | |||
11265 | /// of sanity. | |||
11266 | void Sema::ActOnInitializerError(Decl *D) { | |||
11267 | // Our main concern here is re-establishing invariants like "a | |||
11268 | // variable's type is either dependent or complete". | |||
11269 | if (!D || D->isInvalidDecl()) return; | |||
11270 | ||||
11271 | VarDecl *VD = dyn_cast<VarDecl>(D); | |||
11272 | if (!VD) return; | |||
11273 | ||||
11274 | // Bindings are not usable if we can't make sense of the initializer. | |||
11275 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) | |||
11276 | for (auto *BD : DD->bindings()) | |||
11277 | BD->setInvalidDecl(); | |||
11278 | ||||
11279 | // Auto types are meaningless if we can't make sense of the initializer. | |||
11280 | if (ParsingInitForAutoVars.count(D)) { | |||
11281 | D->setInvalidDecl(); | |||
11282 | return; | |||
11283 | } | |||
11284 | ||||
11285 | QualType Ty = VD->getType(); | |||
11286 | if (Ty->isDependentType()) return; | |||
11287 | ||||
11288 | // Require a complete type. | |||
11289 | if (RequireCompleteType(VD->getLocation(), | |||
11290 | Context.getBaseElementType(Ty), | |||
11291 | diag::err_typecheck_decl_incomplete_type)) { | |||
11292 | VD->setInvalidDecl(); | |||
11293 | return; | |||
11294 | } | |||
11295 | ||||
11296 | // Require a non-abstract type. | |||
11297 | if (RequireNonAbstractType(VD->getLocation(), Ty, | |||
11298 | diag::err_abstract_type_in_decl, | |||
11299 | AbstractVariableType)) { | |||
11300 | VD->setInvalidDecl(); | |||
11301 | return; | |||
11302 | } | |||
11303 | ||||
11304 | // Don't bother complaining about constructors or destructors, | |||
11305 | // though. | |||
11306 | } | |||
11307 | ||||
11308 | void Sema::ActOnUninitializedDecl(Decl *RealDecl) { | |||
11309 | // If there is no declaration, there was an error parsing it. Just ignore it. | |||
11310 | if (!RealDecl) | |||
11311 | return; | |||
11312 | ||||
11313 | if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { | |||
11314 | QualType Type = Var->getType(); | |||
11315 | ||||
11316 | // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. | |||
11317 | if (isa<DecompositionDecl>(RealDecl)) { | |||
11318 | Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; | |||
11319 | Var->setInvalidDecl(); | |||
11320 | return; | |||
11321 | } | |||
11322 | ||||
11323 | if (Type->isUndeducedType() && | |||
11324 | DeduceVariableDeclarationType(Var, false, nullptr)) | |||
11325 | return; | |||
11326 | ||||
11327 | // C++11 [class.static.data]p3: A static data member can be declared with | |||
11328 | // the constexpr specifier; if so, its declaration shall specify | |||
11329 | // a brace-or-equal-initializer. | |||
11330 | // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to | |||
11331 | // the definition of a variable [...] or the declaration of a static data | |||
11332 | // member. | |||
11333 | if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && | |||
11334 | !Var->isThisDeclarationADemotedDefinition()) { | |||
11335 | if (Var->isStaticDataMember()) { | |||
11336 | // C++1z removes the relevant rule; the in-class declaration is always | |||
11337 | // a definition there. | |||
11338 | if (!getLangOpts().CPlusPlus17) { | |||
11339 | Diag(Var->getLocation(), | |||
11340 | diag::err_constexpr_static_mem_var_requires_init) | |||
11341 | << Var->getDeclName(); | |||
11342 | Var->setInvalidDecl(); | |||
11343 | return; | |||
11344 | } | |||
11345 | } else { | |||
11346 | Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); | |||
11347 | Var->setInvalidDecl(); | |||
11348 | return; | |||
11349 | } | |||
11350 | } | |||
11351 | ||||
11352 | // OpenCL v1.1 s6.5.3: variables declared in the constant address space must | |||
11353 | // be initialized. | |||
11354 | if (!Var->isInvalidDecl() && | |||
11355 | Var->getType().getAddressSpace() == LangAS::opencl_constant && | |||
11356 | Var->getStorageClass() != SC_Extern && !Var->getInit()) { | |||
11357 | Diag(Var->getLocation(), diag::err_opencl_constant_no_init); | |||
11358 | Var->setInvalidDecl(); | |||
11359 | return; | |||
11360 | } | |||
11361 | ||||
11362 | switch (Var->isThisDeclarationADefinition()) { | |||
11363 | case VarDecl::Definition: | |||
11364 | if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) | |||
11365 | break; | |||
11366 | ||||
11367 | // We have an out-of-line definition of a static data member | |||
11368 | // that has an in-class initializer, so we type-check this like | |||
11369 | // a declaration. | |||
11370 | // | |||
11371 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
11372 | ||||
11373 | case VarDecl::DeclarationOnly: | |||
11374 | // It's only a declaration. | |||
11375 | ||||
11376 | // Block scope. C99 6.7p7: If an identifier for an object is | |||
11377 | // declared with no linkage (C99 6.2.2p6), the type for the | |||
11378 | // object shall be complete. | |||
11379 | if (!Type->isDependentType() && Var->isLocalVarDecl() && | |||
11380 | !Var->hasLinkage() && !Var->isInvalidDecl() && | |||
11381 | RequireCompleteType(Var->getLocation(), Type, | |||
11382 | diag::err_typecheck_decl_incomplete_type)) | |||
11383 | Var->setInvalidDecl(); | |||
11384 | ||||
11385 | // Make sure that the type is not abstract. | |||
11386 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | |||
11387 | RequireNonAbstractType(Var->getLocation(), Type, | |||
11388 | diag::err_abstract_type_in_decl, | |||
11389 | AbstractVariableType)) | |||
11390 | Var->setInvalidDecl(); | |||
11391 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | |||
11392 | Var->getStorageClass() == SC_PrivateExtern) { | |||
11393 | Diag(Var->getLocation(), diag::warn_private_extern); | |||
11394 | Diag(Var->getLocation(), diag::note_private_extern); | |||
11395 | } | |||
11396 | ||||
11397 | return; | |||
11398 | ||||
11399 | case VarDecl::TentativeDefinition: | |||
11400 | // File scope. C99 6.9.2p2: A declaration of an identifier for an | |||
11401 | // object that has file scope without an initializer, and without a | |||
11402 | // storage-class specifier or with the storage-class specifier "static", | |||
11403 | // constitutes a tentative definition. Note: A tentative definition with | |||
11404 | // external linkage is valid (C99 6.2.2p5). | |||
11405 | if (!Var->isInvalidDecl()) { | |||
11406 | if (const IncompleteArrayType *ArrayT | |||
11407 | = Context.getAsIncompleteArrayType(Type)) { | |||
11408 | if (RequireCompleteType(Var->getLocation(), | |||
11409 | ArrayT->getElementType(), | |||
11410 | diag::err_illegal_decl_array_incomplete_type)) | |||
11411 | Var->setInvalidDecl(); | |||
11412 | } else if (Var->getStorageClass() == SC_Static) { | |||
11413 | // C99 6.9.2p3: If the declaration of an identifier for an object is | |||
11414 | // a tentative definition and has internal linkage (C99 6.2.2p3), the | |||
11415 | // declared type shall not be an incomplete type. | |||
11416 | // NOTE: code such as the following | |||
11417 | // static struct s; | |||
11418 | // struct s { int a; }; | |||
11419 | // is accepted by gcc. Hence here we issue a warning instead of | |||
11420 | // an error and we do not invalidate the static declaration. | |||
11421 | // NOTE: to avoid multiple warnings, only check the first declaration. | |||
11422 | if (Var->isFirstDecl()) | |||
11423 | RequireCompleteType(Var->getLocation(), Type, | |||
11424 | diag::ext_typecheck_decl_incomplete_type); | |||
11425 | } | |||
11426 | } | |||
11427 | ||||
11428 | // Record the tentative definition; we're done. | |||
11429 | if (!Var->isInvalidDecl()) | |||
11430 | TentativeDefinitions.push_back(Var); | |||
11431 | return; | |||
11432 | } | |||
11433 | ||||
11434 | // Provide a specific diagnostic for uninitialized variable | |||
11435 | // definitions with incomplete array type. | |||
11436 | if (Type->isIncompleteArrayType()) { | |||
11437 | Diag(Var->getLocation(), | |||
11438 | diag::err_typecheck_incomplete_array_needs_initializer); | |||
11439 | Var->setInvalidDecl(); | |||
11440 | return; | |||
11441 | } | |||
11442 | ||||
11443 | // Provide a specific diagnostic for uninitialized variable | |||
11444 | // definitions with reference type. | |||
11445 | if (Type->isReferenceType()) { | |||
11446 | Diag(Var->getLocation(), diag::err_reference_var_requires_init) | |||
11447 | << Var->getDeclName() | |||
11448 | << SourceRange(Var->getLocation(), Var->getLocation()); | |||
11449 | Var->setInvalidDecl(); | |||
11450 | return; | |||
11451 | } | |||
11452 | ||||
11453 | // Do not attempt to type-check the default initializer for a | |||
11454 | // variable with dependent type. | |||
11455 | if (Type->isDependentType()) | |||
11456 | return; | |||
11457 | ||||
11458 | if (Var->isInvalidDecl()) | |||
11459 | return; | |||
11460 | ||||
11461 | if (!Var->hasAttr<AliasAttr>()) { | |||
11462 | if (RequireCompleteType(Var->getLocation(), | |||
11463 | Context.getBaseElementType(Type), | |||
11464 | diag::err_typecheck_decl_incomplete_type)) { | |||
11465 | Var->setInvalidDecl(); | |||
11466 | return; | |||
11467 | } | |||
11468 | } else { | |||
11469 | return; | |||
11470 | } | |||
11471 | ||||
11472 | // The variable can not have an abstract class type. | |||
11473 | if (RequireNonAbstractType(Var->getLocation(), Type, | |||
11474 | diag::err_abstract_type_in_decl, | |||
11475 | AbstractVariableType)) { | |||
11476 | Var->setInvalidDecl(); | |||
11477 | return; | |||
11478 | } | |||
11479 | ||||
11480 | // Check for jumps past the implicit initializer. C++0x | |||
11481 | // clarifies that this applies to a "variable with automatic | |||
11482 | // storage duration", not a "local variable". | |||
11483 | // C++11 [stmt.dcl]p3 | |||
11484 | // A program that jumps from a point where a variable with automatic | |||
11485 | // storage duration is not in scope to a point where it is in scope is | |||
11486 | // ill-formed unless the variable has scalar type, class type with a | |||
11487 | // trivial default constructor and a trivial destructor, a cv-qualified | |||
11488 | // version of one of these types, or an array of one of the preceding | |||
11489 | // types and is declared without an initializer. | |||
11490 | if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { | |||
11491 | if (const RecordType *Record | |||
11492 | = Context.getBaseElementType(Type)->getAs<RecordType>()) { | |||
11493 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); | |||
11494 | // Mark the function (if we're in one) for further checking even if the | |||
11495 | // looser rules of C++11 do not require such checks, so that we can | |||
11496 | // diagnose incompatibilities with C++98. | |||
11497 | if (!CXXRecord->isPOD()) | |||
11498 | setFunctionHasBranchProtectedScope(); | |||
11499 | } | |||
11500 | } | |||
11501 | ||||
11502 | // C++03 [dcl.init]p9: | |||
11503 | // If no initializer is specified for an object, and the | |||
11504 | // object is of (possibly cv-qualified) non-POD class type (or | |||
11505 | // array thereof), the object shall be default-initialized; if | |||
11506 | // the object is of const-qualified type, the underlying class | |||
11507 | // type shall have a user-declared default | |||
11508 | // constructor. Otherwise, if no initializer is specified for | |||
11509 | // a non- static object, the object and its subobjects, if | |||
11510 | // any, have an indeterminate initial value); if the object | |||
11511 | // or any of its subobjects are of const-qualified type, the | |||
11512 | // program is ill-formed. | |||
11513 | // C++0x [dcl.init]p11: | |||
11514 | // If no initializer is specified for an object, the object is | |||
11515 | // default-initialized; [...]. | |||
11516 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); | |||
11517 | InitializationKind Kind | |||
11518 | = InitializationKind::CreateDefault(Var->getLocation()); | |||
11519 | ||||
11520 | InitializationSequence InitSeq(*this, Entity, Kind, None); | |||
11521 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); | |||
11522 | if (Init.isInvalid()) | |||
11523 | Var->setInvalidDecl(); | |||
11524 | else if (Init.get()) { | |||
11525 | Var->setInit(MaybeCreateExprWithCleanups(Init.get())); | |||
11526 | // This is important for template substitution. | |||
11527 | Var->setInitStyle(VarDecl::CallInit); | |||
11528 | } | |||
11529 | ||||
11530 | CheckCompleteVariableDeclaration(Var); | |||
11531 | } | |||
11532 | } | |||
11533 | ||||
11534 | void Sema::ActOnCXXForRangeDecl(Decl *D) { | |||
11535 | // If there is no declaration, there was an error parsing it. Ignore it. | |||
11536 | if (!D) | |||
11537 | return; | |||
11538 | ||||
11539 | VarDecl *VD = dyn_cast<VarDecl>(D); | |||
11540 | if (!VD) { | |||
11541 | Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); | |||
11542 | D->setInvalidDecl(); | |||
11543 | return; | |||
11544 | } | |||
11545 | ||||
11546 | VD->setCXXForRangeDecl(true); | |||
11547 | ||||
11548 | // for-range-declaration cannot be given a storage class specifier. | |||
11549 | int Error = -1; | |||
11550 | switch (VD->getStorageClass()) { | |||
11551 | case SC_None: | |||
11552 | break; | |||
11553 | case SC_Extern: | |||
11554 | Error = 0; | |||
11555 | break; | |||
11556 | case SC_Static: | |||
11557 | Error = 1; | |||
11558 | break; | |||
11559 | case SC_PrivateExtern: | |||
11560 | Error = 2; | |||
11561 | break; | |||
11562 | case SC_Auto: | |||
11563 | Error = 3; | |||
11564 | break; | |||
11565 | case SC_Register: | |||
11566 | Error = 4; | |||
11567 | break; | |||
11568 | } | |||
11569 | if (Error != -1) { | |||
11570 | Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) | |||
11571 | << VD->getDeclName() << Error; | |||
11572 | D->setInvalidDecl(); | |||
11573 | } | |||
11574 | } | |||
11575 | ||||
11576 | StmtResult | |||
11577 | Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, | |||
11578 | IdentifierInfo *Ident, | |||
11579 | ParsedAttributes &Attrs, | |||
11580 | SourceLocation AttrEnd) { | |||
11581 | // C++1y [stmt.iter]p1: | |||
11582 | // A range-based for statement of the form | |||
11583 | // for ( for-range-identifier : for-range-initializer ) statement | |||
11584 | // is equivalent to | |||
11585 | // for ( auto&& for-range-identifier : for-range-initializer ) statement | |||
11586 | DeclSpec DS(Attrs.getPool().getFactory()); | |||
11587 | ||||
11588 | const char *PrevSpec; | |||
11589 | unsigned DiagID; | |||
11590 | DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, | |||
11591 | getPrintingPolicy()); | |||
11592 | ||||
11593 | Declarator D(DS, DeclaratorContext::ForContext); | |||
11594 | D.SetIdentifier(Ident, IdentLoc); | |||
11595 | D.takeAttributes(Attrs, AttrEnd); | |||
11596 | ||||
11597 | ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); | |||
11598 | D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), | |||
11599 | IdentLoc); | |||
11600 | Decl *Var = ActOnDeclarator(S, D); | |||
11601 | cast<VarDecl>(Var)->setCXXForRangeDecl(true); | |||
11602 | FinalizeDeclaration(Var); | |||
11603 | return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, | |||
11604 | AttrEnd.isValid() ? AttrEnd : IdentLoc); | |||
11605 | } | |||
11606 | ||||
11607 | void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { | |||
11608 | if (var->isInvalidDecl()) return; | |||
| ||||
11609 | ||||
11610 | if (getLangOpts().OpenCL) { | |||
11611 | // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an | |||
11612 | // initialiser | |||
11613 | if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && | |||
11614 | !var->hasInit()) { | |||
11615 | Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) | |||
11616 | << 1 /*Init*/; | |||
11617 | var->setInvalidDecl(); | |||
11618 | return; | |||
11619 | } | |||
11620 | } | |||
11621 | ||||
11622 | // In Objective-C, don't allow jumps past the implicit initialization of a | |||
11623 | // local retaining variable. | |||
11624 | if (getLangOpts().ObjC1 && | |||
11625 | var->hasLocalStorage()) { | |||
11626 | switch (var->getType().getObjCLifetime()) { | |||
11627 | case Qualifiers::OCL_None: | |||
11628 | case Qualifiers::OCL_ExplicitNone: | |||
11629 | case Qualifiers::OCL_Autoreleasing: | |||
11630 | break; | |||
11631 | ||||
11632 | case Qualifiers::OCL_Weak: | |||
11633 | case Qualifiers::OCL_Strong: | |||
11634 | setFunctionHasBranchProtectedScope(); | |||
11635 | break; | |||
11636 | } | |||
11637 | } | |||
11638 | ||||
11639 | if (var->hasLocalStorage() && | |||
11640 | var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
11641 | setFunctionHasBranchProtectedScope(); | |||
11642 | ||||
11643 | // Warn about externally-visible variables being defined without a | |||
11644 | // prior declaration. We only want to do this for global | |||
11645 | // declarations, but we also specifically need to avoid doing it for | |||
11646 | // class members because the linkage of an anonymous class can | |||
11647 | // change if it's later given a typedef name. | |||
11648 | if (var->isThisDeclarationADefinition() && | |||
11649 | var->getDeclContext()->getRedeclContext()->isFileContext() && | |||
11650 | var->isExternallyVisible() && var->hasLinkage() && | |||
11651 | !var->isInline() && !var->getDescribedVarTemplate() && | |||
11652 | !isTemplateInstantiation(var->getTemplateSpecializationKind()) && | |||
11653 | !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, | |||
11654 | var->getLocation())) { | |||
11655 | // Find a previous declaration that's not a definition. | |||
11656 | VarDecl *prev = var->getPreviousDecl(); | |||
11657 | while (prev && prev->isThisDeclarationADefinition()) | |||
11658 | prev = prev->getPreviousDecl(); | |||
11659 | ||||
11660 | if (!prev) | |||
11661 | Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; | |||
11662 | } | |||
11663 | ||||
11664 | // Cache the result of checking for constant initialization. | |||
11665 | Optional<bool> CacheHasConstInit; | |||
11666 | const Expr *CacheCulprit; | |||
11667 | auto checkConstInit = [&]() mutable { | |||
11668 | if (!CacheHasConstInit) | |||
11669 | CacheHasConstInit = var->getInit()->isConstantInitializer( | |||
11670 | Context, var->getType()->isReferenceType(), &CacheCulprit); | |||
11671 | return *CacheHasConstInit; | |||
11672 | }; | |||
11673 | ||||
11674 | if (var->getTLSKind() == VarDecl::TLS_Static) { | |||
11675 | if (var->getType().isDestructedType()) { | |||
11676 | // GNU C++98 edits for __thread, [basic.start.term]p3: | |||
11677 | // The type of an object with thread storage duration shall not | |||
11678 | // have a non-trivial destructor. | |||
11679 | Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); | |||
11680 | if (getLangOpts().CPlusPlus11) | |||
11681 | Diag(var->getLocation(), diag::note_use_thread_local); | |||
11682 | } else if (getLangOpts().CPlusPlus && var->hasInit()) { | |||
11683 | if (!checkConstInit()) { | |||
11684 | // GNU C++98 edits for __thread, [basic.start.init]p4: | |||
11685 | // An object of thread storage duration shall not require dynamic | |||
11686 | // initialization. | |||
11687 | // FIXME: Need strict checking here. | |||
11688 | Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) | |||
11689 | << CacheCulprit->getSourceRange(); | |||
11690 | if (getLangOpts().CPlusPlus11) | |||
11691 | Diag(var->getLocation(), diag::note_use_thread_local); | |||
11692 | } | |||
11693 | } | |||
11694 | } | |||
11695 | ||||
11696 | // Apply section attributes and pragmas to global variables. | |||
11697 | bool GlobalStorage = var->hasGlobalStorage(); | |||
11698 | if (GlobalStorage && var->isThisDeclarationADefinition() && | |||
11699 | !inTemplateInstantiation()) { | |||
11700 | PragmaStack<StringLiteral *> *Stack = nullptr; | |||
11701 | int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; | |||
11702 | if (var->getType().isConstQualified()) | |||
11703 | Stack = &ConstSegStack; | |||
11704 | else if (!var->getInit()) { | |||
11705 | Stack = &BSSSegStack; | |||
11706 | SectionFlags |= ASTContext::PSF_Write; | |||
11707 | } else { | |||
11708 | Stack = &DataSegStack; | |||
11709 | SectionFlags |= ASTContext::PSF_Write; | |||
11710 | } | |||
11711 | if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { | |||
11712 | var->addAttr(SectionAttr::CreateImplicit( | |||
11713 | Context, SectionAttr::Declspec_allocate, | |||
11714 | Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); | |||
11715 | } | |||
11716 | if (const SectionAttr *SA = var->getAttr<SectionAttr>()) | |||
11717 | if (UnifySection(SA->getName(), SectionFlags, var)) | |||
11718 | var->dropAttr<SectionAttr>(); | |||
11719 | ||||
11720 | // Apply the init_seg attribute if this has an initializer. If the | |||
11721 | // initializer turns out to not be dynamic, we'll end up ignoring this | |||
11722 | // attribute. | |||
11723 | if (CurInitSeg && var->getInit()) | |||
11724 | var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), | |||
11725 | CurInitSegLoc)); | |||
11726 | } | |||
11727 | ||||
11728 | // All the following checks are C++ only. | |||
11729 | if (!getLangOpts().CPlusPlus) { | |||
11730 | // If this variable must be emitted, add it as an initializer for the | |||
11731 | // current module. | |||
11732 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | |||
11733 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | |||
11734 | return; | |||
11735 | } | |||
11736 | ||||
11737 | if (auto *DD = dyn_cast<DecompositionDecl>(var)) | |||
11738 | CheckCompleteDecompositionDeclaration(DD); | |||
11739 | ||||
11740 | QualType type = var->getType(); | |||
11741 | if (type->isDependentType()) return; | |||
11742 | ||||
11743 | // __block variables might require us to capture a copy-initializer. | |||
11744 | if (var->hasAttr<BlocksAttr>()) { | |||
11745 | // It's currently invalid to ever have a __block variable with an | |||
11746 | // array type; should we diagnose that here? | |||
11747 | ||||
11748 | // Regardless, we don't want to ignore array nesting when | |||
11749 | // constructing this copy. | |||
11750 | if (type->isStructureOrClassType()) { | |||
11751 | EnterExpressionEvaluationContext scope( | |||
11752 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | |||
11753 | SourceLocation poi = var->getLocation(); | |||
11754 | Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); | |||
11755 | ExprResult result | |||
11756 | = PerformMoveOrCopyInitialization( | |||
11757 | InitializedEntity::InitializeBlock(poi, type, false), | |||
11758 | var, var->getType(), varRef, /*AllowNRVO=*/true); | |||
11759 | if (!result.isInvalid()) { | |||
11760 | result = MaybeCreateExprWithCleanups(result); | |||
11761 | Expr *init = result.getAs<Expr>(); | |||
11762 | Context.setBlockVarCopyInits(var, init); | |||
11763 | } | |||
11764 | } | |||
11765 | } | |||
11766 | ||||
11767 | Expr *Init = var->getInit(); | |||
11768 | bool IsGlobal = GlobalStorage && !var->isStaticLocal(); | |||
11769 | QualType baseType = Context.getBaseElementType(type); | |||
11770 | ||||
11771 | if (Init && !Init->isValueDependent()) { | |||
11772 | if (var->isConstexpr()) { | |||
11773 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
11774 | if (!var->evaluateValue(Notes) || !var->isInitICE()) { | |||
11775 | SourceLocation DiagLoc = var->getLocation(); | |||
11776 | // If the note doesn't add any useful information other than a source | |||
11777 | // location, fold it into the primary diagnostic. | |||
11778 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | |||
11779 | diag::note_invalid_subexpr_in_const_expr) { | |||
11780 | DiagLoc = Notes[0].first; | |||
11781 | Notes.clear(); | |||
11782 | } | |||
11783 | Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) | |||
11784 | << var << Init->getSourceRange(); | |||
11785 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) | |||
11786 | Diag(Notes[I].first, Notes[I].second); | |||
11787 | } | |||
11788 | } else if (var->isUsableInConstantExpressions(Context)) { | |||
11789 | // Check whether the initializer of a const variable of integral or | |||
11790 | // enumeration type is an ICE now, since we can't tell whether it was | |||
11791 | // initialized by a constant expression if we check later. | |||
11792 | var->checkInitIsICE(); | |||
11793 | } | |||
11794 | ||||
11795 | // Don't emit further diagnostics about constexpr globals since they | |||
11796 | // were just diagnosed. | |||
11797 | if (!var->isConstexpr() && GlobalStorage && | |||
11798 | var->hasAttr<RequireConstantInitAttr>()) { | |||
11799 | // FIXME: Need strict checking in C++03 here. | |||
11800 | bool DiagErr = getLangOpts().CPlusPlus11 | |||
11801 | ? !var->checkInitIsICE() : !checkConstInit(); | |||
11802 | if (DiagErr) { | |||
11803 | auto attr = var->getAttr<RequireConstantInitAttr>(); | |||
11804 | Diag(var->getLocation(), diag::err_require_constant_init_failed) | |||
11805 | << Init->getSourceRange(); | |||
11806 | Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) | |||
11807 | << attr->getRange(); | |||
11808 | if (getLangOpts().CPlusPlus11) { | |||
11809 | APValue Value; | |||
11810 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
11811 | Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); | |||
11812 | for (auto &it : Notes) | |||
11813 | Diag(it.first, it.second); | |||
11814 | } else { | |||
11815 | Diag(CacheCulprit->getExprLoc(), | |||
| ||||
11816 | diag::note_invalid_subexpr_in_const_expr) | |||
11817 | << CacheCulprit->getSourceRange(); | |||
11818 | } | |||
11819 | } | |||
11820 | } | |||
11821 | else if (!var->isConstexpr() && IsGlobal && | |||
11822 | !getDiagnostics().isIgnored(diag::warn_global_constructor, | |||
11823 | var->getLocation())) { | |||
11824 | // Warn about globals which don't have a constant initializer. Don't | |||
11825 | // warn about globals with a non-trivial destructor because we already | |||
11826 | // warned about them. | |||
11827 | CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); | |||
11828 | if (!(RD && !RD->hasTrivialDestructor())) { | |||
11829 | if (!checkConstInit()) | |||
11830 | Diag(var->getLocation(), diag::warn_global_constructor) | |||
11831 | << Init->getSourceRange(); | |||
11832 | } | |||
11833 | } | |||
11834 | } | |||
11835 | ||||
11836 | // Require the destructor. | |||
11837 | if (const RecordType *recordType = baseType->getAs<RecordType>()) | |||
11838 | FinalizeVarWithDestructor(var, recordType); | |||
11839 | ||||
11840 | // If this variable must be emitted, add it as an initializer for the current | |||
11841 | // module. | |||
11842 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | |||
11843 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | |||
11844 | } | |||
11845 | ||||
11846 | /// Determines if a variable's alignment is dependent. | |||
11847 | static bool hasDependentAlignment(VarDecl *VD) { | |||
11848 | if (VD->getType()->isDependentType()) | |||
11849 | return true; | |||
11850 | for (auto *I : VD->specific_attrs<AlignedAttr>()) | |||
11851 | if (I->isAlignmentDependent()) | |||
11852 | return true; | |||
11853 | return false; | |||
11854 | } | |||
11855 | ||||
11856 | /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform | |||
11857 | /// any semantic actions necessary after any initializer has been attached. | |||
11858 | void Sema::FinalizeDeclaration(Decl *ThisDecl) { | |||
11859 | // Note that we are no longer parsing the initializer for this declaration. | |||
11860 | ParsingInitForAutoVars.erase(ThisDecl); | |||
11861 | ||||
11862 | VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); | |||
11863 | if (!VD) | |||
11864 | return; | |||
11865 | ||||
11866 | // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active | |||
11867 | if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && | |||
11868 | !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { | |||
11869 | if (PragmaClangBSSSection.Valid) | |||
11870 | VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, | |||
11871 | PragmaClangBSSSection.SectionName, | |||
11872 | PragmaClangBSSSection.PragmaLocation)); | |||
11873 | if (PragmaClangDataSection.Valid) | |||
11874 | VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, | |||
11875 | PragmaClangDataSection.SectionName, | |||
11876 | PragmaClangDataSection.PragmaLocation)); | |||
11877 | if (PragmaClangRodataSection.Valid) | |||
11878 | VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, | |||
11879 | PragmaClangRodataSection.SectionName, | |||
11880 | PragmaClangRodataSection.PragmaLocation)); | |||
11881 | } | |||
11882 | ||||
11883 | if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { | |||
11884 | for (auto *BD : DD->bindings()) { | |||
11885 | FinalizeDeclaration(BD); | |||
11886 | } | |||
11887 | } | |||
11888 | ||||
11889 | checkAttributesAfterMerging(*this, *VD); | |||
11890 | ||||
11891 | // Perform TLS alignment check here after attributes attached to the variable | |||
11892 | // which may affect the alignment have been processed. Only perform the check | |||
11893 | // if the target has a maximum TLS alignment (zero means no constraints). | |||
11894 | if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { | |||
11895 | // Protect the check so that it's not performed on dependent types and | |||
11896 | // dependent alignments (we can't determine the alignment in that case). | |||
11897 | if (VD->getTLSKind() && !hasDependentAlignment(VD) && | |||
11898 | !VD->isInvalidDecl()) { | |||
11899 | CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); | |||
11900 | if (Context.getDeclAlign(VD) > MaxAlignChars) { | |||
11901 | Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) | |||
11902 | << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD | |||
11903 | << (unsigned)MaxAlignChars.getQuantity(); | |||
11904 | } | |||
11905 | } | |||
11906 | } | |||
11907 | ||||
11908 | if (VD->isStaticLocal()) { | |||
11909 | if (FunctionDecl *FD = | |||
11910 | dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { | |||
11911 | // Static locals inherit dll attributes from their function. | |||
11912 | if (Attr *A = getDLLAttr(FD)) { | |||
11913 | auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); | |||
11914 | NewAttr->setInherited(true); | |||
11915 | VD->addAttr(NewAttr); | |||
11916 | } | |||
11917 | // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ | |||
11918 | // function, only __shared__ variables or variables without any device | |||
11919 | // memory qualifiers may be declared with static storage class. | |||
11920 | // Note: It is unclear how a function-scope non-const static variable | |||
11921 | // without device memory qualifier is implemented, therefore only static | |||
11922 | // const variable without device memory qualifier is allowed. | |||
11923 | [&]() { | |||
11924 | if (!getLangOpts().CUDA) | |||
11925 | return; | |||
11926 | if (VD->hasAttr<CUDASharedAttr>()) | |||
11927 | return; | |||
11928 | if (VD->getType().isConstQualified() && | |||
11929 | !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) | |||
11930 | return; | |||
11931 | if (CUDADiagIfDeviceCode(VD->getLocation(), | |||
11932 | diag::err_device_static_local_var) | |||
11933 | << CurrentCUDATarget()) | |||
11934 | VD->setInvalidDecl(); | |||
11935 | }(); | |||
11936 | } | |||
11937 | } | |||
11938 | ||||
11939 | // Perform check for initializers of device-side global variables. | |||
11940 | // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA | |||
11941 | // 7.5). We must also apply the same checks to all __shared__ | |||
11942 | // variables whether they are local or not. CUDA also allows | |||
11943 | // constant initializers for __constant__ and __device__ variables. | |||
11944 | if (getLangOpts().CUDA) | |||
11945 | checkAllowedCUDAInitializer(VD); | |||
11946 | ||||
11947 | // Grab the dllimport or dllexport attribute off of the VarDecl. | |||
11948 | const InheritableAttr *DLLAttr = getDLLAttr(VD); | |||
11949 | ||||
11950 | // Imported static data members cannot be defined out-of-line. | |||
11951 | if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { | |||
11952 | if (VD->isStaticDataMember() && VD->isOutOfLine() && | |||
11953 | VD->isThisDeclarationADefinition()) { | |||
11954 | // We allow definitions of dllimport class template static data members | |||
11955 | // with a warning. | |||
11956 | CXXRecordDecl *Context = | |||
11957 | cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); | |||
11958 | bool IsClassTemplateMember = | |||
11959 | isa<ClassTemplatePartialSpecializationDecl>(Context) || | |||
11960 | Context->getDescribedClassTemplate(); | |||
11961 | ||||
11962 | Diag(VD->getLocation(), | |||
11963 | IsClassTemplateMember | |||
11964 | ? diag::warn_attribute_dllimport_static_field_definition | |||
11965 | : diag::err_attribute_dllimport_static_field_definition); | |||
11966 | Diag(IA->getLocation(), diag::note_attribute); | |||
11967 | if (!IsClassTemplateMember) | |||
11968 | VD->setInvalidDecl(); | |||
11969 | } | |||
11970 | } | |||
11971 | ||||
11972 | // dllimport/dllexport variables cannot be thread local, their TLS index | |||
11973 | // isn't exported with the variable. | |||
11974 | if (DLLAttr && VD->getTLSKind()) { | |||
11975 | auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | |||
11976 | if (F && getDLLAttr(F)) { | |||
11977 | assert(VD->isStaticLocal())(static_cast <bool> (VD->isStaticLocal()) ? void (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 11977, __extension__ __PRETTY_FUNCTION__)); | |||
11978 | // But if this is a static local in a dlimport/dllexport function, the | |||
11979 | // function will never be inlined, which means the var would never be | |||
11980 | // imported, so having it marked import/export is safe. | |||
11981 | } else { | |||
11982 | Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD | |||
11983 | << DLLAttr; | |||
11984 | VD->setInvalidDecl(); | |||
11985 | } | |||
11986 | } | |||
11987 | ||||
11988 | if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { | |||
11989 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { | |||
11990 | Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; | |||
11991 | VD->dropAttr<UsedAttr>(); | |||
11992 | } | |||
11993 | } | |||
11994 | ||||
11995 | const DeclContext *DC = VD->getDeclContext(); | |||
11996 | // If there's a #pragma GCC visibility in scope, and this isn't a class | |||
11997 | // member, set the visibility of this variable. | |||
11998 | if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) | |||
11999 | AddPushedVisibilityAttribute(VD); | |||
12000 | ||||
12001 | // FIXME: Warn on unused var template partial specializations. | |||
12002 | if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) | |||
12003 | MarkUnusedFileScopedDecl(VD); | |||
12004 | ||||
12005 | // Now we have parsed the initializer and can update the table of magic | |||
12006 | // tag values. | |||
12007 | if (!VD->hasAttr<TypeTagForDatatypeAttr>() || | |||
12008 | !VD->getType()->isIntegralOrEnumerationType()) | |||
12009 | return; | |||
12010 | ||||
12011 | for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { | |||
12012 | const Expr *MagicValueExpr = VD->getInit(); | |||
12013 | if (!MagicValueExpr) { | |||
12014 | continue; | |||
12015 | } | |||
12016 | llvm::APSInt MagicValueInt; | |||
12017 | if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { | |||
12018 | Diag(I->getRange().getBegin(), | |||
12019 | diag::err_type_tag_for_datatype_not_ice) | |||
12020 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | |||
12021 | continue; | |||
12022 | } | |||
12023 | if (MagicValueInt.getActiveBits() > 64) { | |||
12024 | Diag(I->getRange().getBegin(), | |||
12025 | diag::err_type_tag_for_datatype_too_large) | |||
12026 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | |||
12027 | continue; | |||
12028 | } | |||
12029 | uint64_t MagicValue = MagicValueInt.getZExtValue(); | |||
12030 | RegisterTypeTagForDatatype(I->getArgumentKind(), | |||
12031 | MagicValue, | |||
12032 | I->getMatchingCType(), | |||
12033 | I->getLayoutCompatible(), | |||
12034 | I->getMustBeNull()); | |||
12035 | } | |||
12036 | } | |||
12037 | ||||
12038 | static bool hasDeducedAuto(DeclaratorDecl *DD) { | |||
12039 | auto *VD = dyn_cast<VarDecl>(DD); | |||
12040 | return VD && !VD->getType()->hasAutoForTrailingReturnType(); | |||
12041 | } | |||
12042 | ||||
12043 | Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, | |||
12044 | ArrayRef<Decl *> Group) { | |||
12045 | SmallVector<Decl*, 8> Decls; | |||
12046 | ||||
12047 | if (DS.isTypeSpecOwned()) | |||
12048 | Decls.push_back(DS.getRepAsDecl()); | |||
12049 | ||||
12050 | DeclaratorDecl *FirstDeclaratorInGroup = nullptr; | |||
12051 | DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; | |||
12052 | bool DiagnosedMultipleDecomps = false; | |||
12053 | DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; | |||
12054 | bool DiagnosedNonDeducedAuto = false; | |||
12055 | ||||
12056 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | |||
12057 | if (Decl *D = Group[i]) { | |||
12058 | // For declarators, there are some additional syntactic-ish checks we need | |||
12059 | // to perform. | |||
12060 | if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { | |||
12061 | if (!FirstDeclaratorInGroup) | |||
12062 | FirstDeclaratorInGroup = DD; | |||
12063 | if (!FirstDecompDeclaratorInGroup) | |||
12064 | FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); | |||
12065 | if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && | |||
12066 | !hasDeducedAuto(DD)) | |||
12067 | FirstNonDeducedAutoInGroup = DD; | |||
12068 | ||||
12069 | if (FirstDeclaratorInGroup != DD) { | |||
12070 | // A decomposition declaration cannot be combined with any other | |||
12071 | // declaration in the same group. | |||
12072 | if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { | |||
12073 | Diag(FirstDecompDeclaratorInGroup->getLocation(), | |||
12074 | diag::err_decomp_decl_not_alone) | |||
12075 | << FirstDeclaratorInGroup->getSourceRange() | |||
12076 | << DD->getSourceRange(); | |||
12077 | DiagnosedMultipleDecomps = true; | |||
12078 | } | |||
12079 | ||||
12080 | // A declarator that uses 'auto' in any way other than to declare a | |||
12081 | // variable with a deduced type cannot be combined with any other | |||
12082 | // declarator in the same group. | |||
12083 | if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { | |||
12084 | Diag(FirstNonDeducedAutoInGroup->getLocation(), | |||
12085 | diag::err_auto_non_deduced_not_alone) | |||
12086 | << FirstNonDeducedAutoInGroup->getType() | |||
12087 | ->hasAutoForTrailingReturnType() | |||
12088 | << FirstDeclaratorInGroup->getSourceRange() | |||
12089 | << DD->getSourceRange(); | |||
12090 | DiagnosedNonDeducedAuto = true; | |||
12091 | } | |||
12092 | } | |||
12093 | } | |||
12094 | ||||
12095 | Decls.push_back(D); | |||
12096 | } | |||
12097 | } | |||
12098 | ||||
12099 | if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { | |||
12100 | if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { | |||
12101 | handleTagNumbering(Tag, S); | |||
12102 | if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && | |||
12103 | getLangOpts().CPlusPlus) | |||
12104 | Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); | |||
12105 | } | |||
12106 | } | |||
12107 | ||||
12108 | return BuildDeclaratorGroup(Decls); | |||
12109 | } | |||
12110 | ||||
12111 | /// BuildDeclaratorGroup - convert a list of declarations into a declaration | |||
12112 | /// group, performing any necessary semantic checking. | |||
12113 | Sema::DeclGroupPtrTy | |||
12114 | Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { | |||
12115 | // C++14 [dcl.spec.auto]p7: (DR1347) | |||
12116 | // If the type that replaces the placeholder type is not the same in each | |||
12117 | // deduction, the program is ill-formed. | |||
12118 | if (Group.size() > 1) { | |||
12119 | QualType Deduced; | |||
12120 | VarDecl *DeducedDecl = nullptr; | |||
12121 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | |||
12122 | VarDecl *D = dyn_cast<VarDecl>(Group[i]); | |||
12123 | if (!D || D->isInvalidDecl()) | |||
12124 | break; | |||
12125 | DeducedType *DT = D->getType()->getContainedDeducedType(); | |||
12126 | if (!DT || DT->getDeducedType().isNull()) | |||
12127 | continue; | |||
12128 | if (Deduced.isNull()) { | |||
12129 | Deduced = DT->getDeducedType(); | |||
12130 | DeducedDecl = D; | |||
12131 | } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { | |||
12132 | auto *AT = dyn_cast<AutoType>(DT); | |||
12133 | Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), | |||
12134 | diag::err_auto_different_deductions) | |||
12135 | << (AT ? (unsigned)AT->getKeyword() : 3) | |||
12136 | << Deduced << DeducedDecl->getDeclName() | |||
12137 | << DT->getDeducedType() << D->getDeclName() | |||
12138 | << DeducedDecl->getInit()->getSourceRange() | |||
12139 | << D->getInit()->getSourceRange(); | |||
12140 | D->setInvalidDecl(); | |||
12141 | break; | |||
12142 | } | |||
12143 | } | |||
12144 | } | |||
12145 | ||||
12146 | ActOnDocumentableDecls(Group); | |||
12147 | ||||
12148 | return DeclGroupPtrTy::make( | |||
12149 | DeclGroupRef::Create(Context, Group.data(), Group.size())); | |||
12150 | } | |||
12151 | ||||
12152 | void Sema::ActOnDocumentableDecl(Decl *D) { | |||
12153 | ActOnDocumentableDecls(D); | |||
12154 | } | |||
12155 | ||||
12156 | void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { | |||
12157 | // Don't parse the comment if Doxygen diagnostics are ignored. | |||
12158 | if (Group.empty() || !Group[0]) | |||
12159 | return; | |||
12160 | ||||
12161 | if (Diags.isIgnored(diag::warn_doc_param_not_found, | |||
12162 | Group[0]->getLocation()) && | |||
12163 | Diags.isIgnored(diag::warn_unknown_comment_command_name, | |||
12164 | Group[0]->getLocation())) | |||
12165 | return; | |||
12166 | ||||
12167 | if (Group.size() >= 2) { | |||
12168 | // This is a decl group. Normally it will contain only declarations | |||
12169 | // produced from declarator list. But in case we have any definitions or | |||
12170 | // additional declaration references: | |||
12171 | // 'typedef struct S {} S;' | |||
12172 | // 'typedef struct S *S;' | |||
12173 | // 'struct S *pS;' | |||
12174 | // FinalizeDeclaratorGroup adds these as separate declarations. | |||
12175 | Decl *MaybeTagDecl = Group[0]; | |||
12176 | if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { | |||
12177 | Group = Group.slice(1); | |||
12178 | } | |||
12179 | } | |||
12180 | ||||
12181 | // See if there are any new comments that are not attached to a decl. | |||
12182 | ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); | |||
12183 | if (!Comments.empty() && | |||
12184 | !Comments.back()->isAttached()) { | |||
12185 | // There is at least one comment that not attached to a decl. | |||
12186 | // Maybe it should be attached to one of these decls? | |||
12187 | // | |||
12188 | // Note that this way we pick up not only comments that precede the | |||
12189 | // declaration, but also comments that *follow* the declaration -- thanks to | |||
12190 | // the lookahead in the lexer: we've consumed the semicolon and looked | |||
12191 | // ahead through comments. | |||
12192 | for (unsigned i = 0, e = Group.size(); i != e; ++i) | |||
12193 | Context.getCommentForDecl(Group[i], &PP); | |||
12194 | } | |||
12195 | } | |||
12196 | ||||
12197 | /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() | |||
12198 | /// to introduce parameters into function prototype scope. | |||
12199 | Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { | |||
12200 | const DeclSpec &DS = D.getDeclSpec(); | |||
12201 | ||||
12202 | // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. | |||
12203 | ||||
12204 | // C++03 [dcl.stc]p2 also permits 'auto'. | |||
12205 | StorageClass SC = SC_None; | |||
12206 | if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { | |||
12207 | SC = SC_Register; | |||
12208 | // In C++11, the 'register' storage class specifier is deprecated. | |||
12209 | // In C++17, it is not allowed, but we tolerate it as an extension. | |||
12210 | if (getLangOpts().CPlusPlus11) { | |||
12211 | Diag(DS.getStorageClassSpecLoc(), | |||
12212 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | |||
12213 | : diag::warn_deprecated_register) | |||
12214 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | |||
12215 | } | |||
12216 | } else if (getLangOpts().CPlusPlus && | |||
12217 | DS.getStorageClassSpec() == DeclSpec::SCS_auto) { | |||
12218 | SC = SC_Auto; | |||
12219 | } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { | |||
12220 | Diag(DS.getStorageClassSpecLoc(), | |||
12221 | diag::err_invalid_storage_class_in_func_decl); | |||
12222 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | |||
12223 | } | |||
12224 | ||||
12225 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | |||
12226 | Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) | |||
12227 | << DeclSpec::getSpecifierName(TSCS); | |||
12228 | if (DS.isInlineSpecified()) | |||
12229 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | |||
12230 | << getLangOpts().CPlusPlus17; | |||
12231 | if (DS.isConstexprSpecified()) | |||
12232 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) | |||
12233 | << 0; | |||
12234 | ||||
12235 | DiagnoseFunctionSpecifiers(DS); | |||
12236 | ||||
12237 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
12238 | QualType parmDeclType = TInfo->getType(); | |||
12239 | ||||
12240 | if (getLangOpts().CPlusPlus) { | |||
12241 | // Check that there are no default arguments inside the type of this | |||
12242 | // parameter. | |||
12243 | CheckExtraCXXDefaultArguments(D); | |||
12244 | ||||
12245 | // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). | |||
12246 | if (D.getCXXScopeSpec().isSet()) { | |||
12247 | Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) | |||
12248 | << D.getCXXScopeSpec().getRange(); | |||
12249 | D.getCXXScopeSpec().clear(); | |||
12250 | } | |||
12251 | } | |||
12252 | ||||
12253 | // Ensure we have a valid name | |||
12254 | IdentifierInfo *II = nullptr; | |||
12255 | if (D.hasName()) { | |||
12256 | II = D.getIdentifier(); | |||
12257 | if (!II) { | |||
12258 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) | |||
12259 | << GetNameForDeclarator(D).getName(); | |||
12260 | D.setInvalidType(true); | |||
12261 | } | |||
12262 | } | |||
12263 | ||||
12264 | // Check for redeclaration of parameters, e.g. int foo(int x, int x); | |||
12265 | if (II) { | |||
12266 | LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, | |||
12267 | ForVisibleRedeclaration); | |||
12268 | LookupName(R, S); | |||
12269 | if (R.isSingleResult()) { | |||
12270 | NamedDecl *PrevDecl = R.getFoundDecl(); | |||
12271 | if (PrevDecl->isTemplateParameter()) { | |||
12272 | // Maybe we will complain about the shadowed template parameter. | |||
12273 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | |||
12274 | // Just pretend that we didn't see the previous declaration. | |||
12275 | PrevDecl = nullptr; | |||
12276 | } else if (S->isDeclScope(PrevDecl)) { | |||
12277 | Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; | |||
12278 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
12279 | ||||
12280 | // Recover by removing the name | |||
12281 | II = nullptr; | |||
12282 | D.SetIdentifier(nullptr, D.getIdentifierLoc()); | |||
12283 | D.setInvalidType(true); | |||
12284 | } | |||
12285 | } | |||
12286 | } | |||
12287 | ||||
12288 | // Temporarily put parameter variables in the translation unit, not | |||
12289 | // the enclosing context. This prevents them from accidentally | |||
12290 | // looking like class members in C++. | |||
12291 | ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), | |||
12292 | D.getLocStart(), | |||
12293 | D.getIdentifierLoc(), II, | |||
12294 | parmDeclType, TInfo, | |||
12295 | SC); | |||
12296 | ||||
12297 | if (D.isInvalidType()) | |||
12298 | New->setInvalidDecl(); | |||
12299 | ||||
12300 | assert(S->isFunctionPrototypeScope())(static_cast <bool> (S->isFunctionPrototypeScope()) ? void (0) : __assert_fail ("S->isFunctionPrototypeScope()" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 12300, __extension__ __PRETTY_FUNCTION__)); | |||
12301 | assert(S->getFunctionPrototypeDepth() >= 1)(static_cast <bool> (S->getFunctionPrototypeDepth() >= 1) ? void (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 12301, __extension__ __PRETTY_FUNCTION__)); | |||
12302 | New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, | |||
12303 | S->getNextFunctionPrototypeIndex()); | |||
12304 | ||||
12305 | // Add the parameter declaration into this scope. | |||
12306 | S->AddDecl(New); | |||
12307 | if (II) | |||
12308 | IdResolver.AddDecl(New); | |||
12309 | ||||
12310 | ProcessDeclAttributes(S, New, D); | |||
12311 | ||||
12312 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
12313 | Diag(New->getLocation(), diag::err_module_private_local) | |||
12314 | << 1 << New->getDeclName() | |||
12315 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | |||
12316 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | |||
12317 | ||||
12318 | if (New->hasAttr<BlocksAttr>()) { | |||
12319 | Diag(New->getLocation(), diag::err_block_on_nonlocal); | |||
12320 | } | |||
12321 | return New; | |||
12322 | } | |||
12323 | ||||
12324 | /// Synthesizes a variable for a parameter arising from a | |||
12325 | /// typedef. | |||
12326 | ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, | |||
12327 | SourceLocation Loc, | |||
12328 | QualType T) { | |||
12329 | /* FIXME: setting StartLoc == Loc. | |||
12330 | Would it be worth to modify callers so as to provide proper source | |||
12331 | location for the unnamed parameters, embedding the parameter's type? */ | |||
12332 | ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, | |||
12333 | T, Context.getTrivialTypeSourceInfo(T, Loc), | |||
12334 | SC_None, nullptr); | |||
12335 | Param->setImplicit(); | |||
12336 | return Param; | |||
12337 | } | |||
12338 | ||||
12339 | void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { | |||
12340 | // Don't diagnose unused-parameter errors in template instantiations; we | |||
12341 | // will already have done so in the template itself. | |||
12342 | if (inTemplateInstantiation()) | |||
12343 | return; | |||
12344 | ||||
12345 | for (const ParmVarDecl *Parameter : Parameters) { | |||
12346 | if (!Parameter->isReferenced() && Parameter->getDeclName() && | |||
12347 | !Parameter->hasAttr<UnusedAttr>()) { | |||
12348 | Diag(Parameter->getLocation(), diag::warn_unused_parameter) | |||
12349 | << Parameter->getDeclName(); | |||
12350 | } | |||
12351 | } | |||
12352 | } | |||
12353 | ||||
12354 | void Sema::DiagnoseSizeOfParametersAndReturnValue( | |||
12355 | ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { | |||
12356 | if (LangOpts.NumLargeByValueCopy == 0) // No check. | |||
12357 | return; | |||
12358 | ||||
12359 | // Warn if the return value is pass-by-value and larger than the specified | |||
12360 | // threshold. | |||
12361 | if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { | |||
12362 | unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); | |||
12363 | if (Size > LangOpts.NumLargeByValueCopy) | |||
12364 | Diag(D->getLocation(), diag::warn_return_value_size) | |||
12365 | << D->getDeclName() << Size; | |||
12366 | } | |||
12367 | ||||
12368 | // Warn if any parameter is pass-by-value and larger than the specified | |||
12369 | // threshold. | |||
12370 | for (const ParmVarDecl *Parameter : Parameters) { | |||
12371 | QualType T = Parameter->getType(); | |||
12372 | if (T->isDependentType() || !T.isPODType(Context)) | |||
12373 | continue; | |||
12374 | unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); | |||
12375 | if (Size > LangOpts.NumLargeByValueCopy) | |||
12376 | Diag(Parameter->getLocation(), diag::warn_parameter_size) | |||
12377 | << Parameter->getDeclName() << Size; | |||
12378 | } | |||
12379 | } | |||
12380 | ||||
12381 | ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, | |||
12382 | SourceLocation NameLoc, IdentifierInfo *Name, | |||
12383 | QualType T, TypeSourceInfo *TSInfo, | |||
12384 | StorageClass SC) { | |||
12385 | // In ARC, infer a lifetime qualifier for appropriate parameter types. | |||
12386 | if (getLangOpts().ObjCAutoRefCount && | |||
12387 | T.getObjCLifetime() == Qualifiers::OCL_None && | |||
12388 | T->isObjCLifetimeType()) { | |||
12389 | ||||
12390 | Qualifiers::ObjCLifetime lifetime; | |||
12391 | ||||
12392 | // Special cases for arrays: | |||
12393 | // - if it's const, use __unsafe_unretained | |||
12394 | // - otherwise, it's an error | |||
12395 | if (T->isArrayType()) { | |||
12396 | if (!T.isConstQualified()) { | |||
12397 | DelayedDiagnostics.add( | |||
12398 | sema::DelayedDiagnostic::makeForbiddenType( | |||
12399 | NameLoc, diag::err_arc_array_param_no_ownership, T, false)); | |||
12400 | } | |||
12401 | lifetime = Qualifiers::OCL_ExplicitNone; | |||
12402 | } else { | |||
12403 | lifetime = T->getObjCARCImplicitLifetime(); | |||
12404 | } | |||
12405 | T = Context.getLifetimeQualifiedType(T, lifetime); | |||
12406 | } | |||
12407 | ||||
12408 | ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, | |||
12409 | Context.getAdjustedParameterType(T), | |||
12410 | TSInfo, SC, nullptr); | |||
12411 | ||||
12412 | // Parameters can not be abstract class types. | |||
12413 | // For record types, this is done by the AbstractClassUsageDiagnoser once | |||
12414 | // the class has been completely parsed. | |||
12415 | if (!CurContext->isRecord() && | |||
12416 | RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, | |||
12417 | AbstractParamType)) | |||
12418 | New->setInvalidDecl(); | |||
12419 | ||||
12420 | // Parameter declarators cannot be interface types. All ObjC objects are | |||
12421 | // passed by reference. | |||
12422 | if (T->isObjCObjectType()) { | |||
12423 | SourceLocation TypeEndLoc = | |||
12424 | getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); | |||
12425 | Diag(NameLoc, | |||
12426 | diag::err_object_cannot_be_passed_returned_by_value) << 1 << T | |||
12427 | << FixItHint::CreateInsertion(TypeEndLoc, "*"); | |||
12428 | T = Context.getObjCObjectPointerType(T); | |||
12429 | New->setType(T); | |||
12430 | } | |||
12431 | ||||
12432 | // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage | |||
12433 | // duration shall not be qualified by an address-space qualifier." | |||
12434 | // Since all parameters have automatic store duration, they can not have | |||
12435 | // an address space. | |||
12436 | if (T.getAddressSpace() != LangAS::Default && | |||
12437 | // OpenCL allows function arguments declared to be an array of a type | |||
12438 | // to be qualified with an address space. | |||
12439 | !(getLangOpts().OpenCL && | |||
12440 | (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { | |||
12441 | Diag(NameLoc, diag::err_arg_with_address_space); | |||
12442 | New->setInvalidDecl(); | |||
12443 | } | |||
12444 | ||||
12445 | return New; | |||
12446 | } | |||
12447 | ||||
12448 | void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, | |||
12449 | SourceLocation LocAfterDecls) { | |||
12450 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | |||
12451 | ||||
12452 | // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' | |||
12453 | // for a K&R function. | |||
12454 | if (!FTI.hasPrototype) { | |||
12455 | for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { | |||
12456 | --i; | |||
12457 | if (FTI.Params[i].Param == nullptr) { | |||
12458 | SmallString<256> Code; | |||
12459 | llvm::raw_svector_ostream(Code) | |||
12460 | << " int " << FTI.Params[i].Ident->getName() << ";\n"; | |||
12461 | Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) | |||
12462 | << FTI.Params[i].Ident | |||
12463 | << FixItHint::CreateInsertion(LocAfterDecls, Code); | |||
12464 | ||||
12465 | // Implicitly declare the argument as type 'int' for lack of a better | |||
12466 | // type. | |||
12467 | AttributeFactory attrs; | |||
12468 | DeclSpec DS(attrs); | |||
12469 | const char* PrevSpec; // unused | |||
12470 | unsigned DiagID; // unused | |||
12471 | DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, | |||
12472 | DiagID, Context.getPrintingPolicy()); | |||
12473 | // Use the identifier location for the type source range. | |||
12474 | DS.SetRangeStart(FTI.Params[i].IdentLoc); | |||
12475 | DS.SetRangeEnd(FTI.Params[i].IdentLoc); | |||
12476 | Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); | |||
12477 | ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); | |||
12478 | FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); | |||
12479 | } | |||
12480 | } | |||
12481 | } | |||
12482 | } | |||
12483 | ||||
12484 | Decl * | |||
12485 | Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, | |||
12486 | MultiTemplateParamsArg TemplateParameterLists, | |||
12487 | SkipBodyInfo *SkipBody) { | |||
12488 | assert(getCurFunctionDecl() == nullptr && "Function parsing confused")(static_cast <bool> (getCurFunctionDecl() == nullptr && "Function parsing confused") ? void (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 12488, __extension__ __PRETTY_FUNCTION__)); | |||
12489 | assert(D.isFunctionDeclarator() && "Not a function declarator!")(static_cast <bool> (D.isFunctionDeclarator() && "Not a function declarator!") ? void (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 12489, __extension__ __PRETTY_FUNCTION__)); | |||
12490 | Scope *ParentScope = FnBodyScope->getParent(); | |||
12491 | ||||
12492 | D.setFunctionDefinitionKind(FDK_Definition); | |||
12493 | Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); | |||
12494 | return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); | |||
12495 | } | |||
12496 | ||||
12497 | void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { | |||
12498 | Consumer.HandleInlineFunctionDefinition(D); | |||
12499 | } | |||
12500 | ||||
12501 | static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, | |||
12502 | const FunctionDecl*& PossibleZeroParamPrototype) { | |||
12503 | // Don't warn about invalid declarations. | |||
12504 | if (FD->isInvalidDecl()) | |||
12505 | return false; | |||
12506 | ||||
12507 | // Or declarations that aren't global. | |||
12508 | if (!FD->isGlobal()) | |||
12509 | return false; | |||
12510 | ||||
12511 | // Don't warn about C++ member functions. | |||
12512 | if (isa<CXXMethodDecl>(FD)) | |||
12513 | return false; | |||
12514 | ||||
12515 | // Don't warn about 'main'. | |||
12516 | if (FD->isMain()) | |||
12517 | return false; | |||
12518 | ||||
12519 | // Don't warn about inline functions. | |||
12520 | if (FD->isInlined()) | |||
12521 | return false; | |||
12522 | ||||
12523 | // Don't warn about function templates. | |||
12524 | if (FD->getDescribedFunctionTemplate()) | |||
12525 | return false; | |||
12526 | ||||
12527 | // Don't warn about function template specializations. | |||
12528 | if (FD->isFunctionTemplateSpecialization()) | |||
12529 | return false; | |||
12530 | ||||
12531 | // Don't warn for OpenCL kernels. | |||
12532 | if (FD->hasAttr<OpenCLKernelAttr>()) | |||
12533 | return false; | |||
12534 | ||||
12535 | // Don't warn on explicitly deleted functions. | |||
12536 | if (FD->isDeleted()) | |||
12537 | return false; | |||
12538 | ||||
12539 | bool MissingPrototype = true; | |||
12540 | for (const FunctionDecl *Prev = FD->getPreviousDecl(); | |||
12541 | Prev; Prev = Prev->getPreviousDecl()) { | |||
12542 | // Ignore any declarations that occur in function or method | |||
12543 | // scope, because they aren't visible from the header. | |||
12544 | if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) | |||
12545 | continue; | |||
12546 | ||||
12547 | MissingPrototype = !Prev->getType()->isFunctionProtoType(); | |||
12548 | if (FD->getNumParams() == 0) | |||
12549 | PossibleZeroParamPrototype = Prev; | |||
12550 | break; | |||
12551 | } | |||
12552 | ||||
12553 | return MissingPrototype; | |||
12554 | } | |||
12555 | ||||
12556 | void | |||
12557 | Sema::CheckForFunctionRedefinition(FunctionDecl *FD, | |||
12558 | const FunctionDecl *EffectiveDefinition, | |||
12559 | SkipBodyInfo *SkipBody) { | |||
12560 | const FunctionDecl *Definition = EffectiveDefinition; | |||
12561 | if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { | |||
12562 | // If this is a friend function defined in a class template, it does not | |||
12563 | // have a body until it is used, nevertheless it is a definition, see | |||
12564 | // [temp.inst]p2: | |||
12565 | // | |||
12566 | // ... for the purpose of determining whether an instantiated redeclaration | |||
12567 | // is valid according to [basic.def.odr] and [class.mem], a declaration that | |||
12568 | // corresponds to a definition in the template is considered to be a | |||
12569 | // definition. | |||
12570 | // | |||
12571 | // The following code must produce redefinition error: | |||
12572 | // | |||
12573 | // template<typename T> struct C20 { friend void func_20() {} }; | |||
12574 | // C20<int> c20i; | |||
12575 | // void func_20() {} | |||
12576 | // | |||
12577 | for (auto I : FD->redecls()) { | |||
12578 | if (I != FD && !I->isInvalidDecl() && | |||
12579 | I->getFriendObjectKind() != Decl::FOK_None) { | |||
12580 | if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { | |||
12581 | if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { | |||
12582 | // A merged copy of the same function, instantiated as a member of | |||
12583 | // the same class, is OK. | |||
12584 | if (declaresSameEntity(OrigFD, Original) && | |||
12585 | declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), | |||
12586 | cast<Decl>(FD->getLexicalDeclContext()))) | |||
12587 | continue; | |||
12588 | } | |||
12589 | ||||
12590 | if (Original->isThisDeclarationADefinition()) { | |||
12591 | Definition = I; | |||
12592 | break; | |||
12593 | } | |||
12594 | } | |||
12595 | } | |||
12596 | } | |||
12597 | } | |||
12598 | if (!Definition) | |||
12599 | return; | |||
12600 | ||||
12601 | if (canRedefineFunction(Definition, getLangOpts())) | |||
12602 | return; | |||
12603 | ||||
12604 | // Don't emit an error when this is redefinition of a typo-corrected | |||
12605 | // definition. | |||
12606 | if (TypoCorrectedFunctionDefinitions.count(Definition)) | |||
12607 | return; | |||
12608 | ||||
12609 | // If we don't have a visible definition of the function, and it's inline or | |||
12610 | // a template, skip the new definition. | |||
12611 | if (SkipBody && !hasVisibleDefinition(Definition) && | |||
12612 | (Definition->getFormalLinkage() == InternalLinkage || | |||
12613 | Definition->isInlined() || | |||
12614 | Definition->getDescribedFunctionTemplate() || | |||
12615 | Definition->getNumTemplateParameterLists())) { | |||
12616 | SkipBody->ShouldSkip = true; | |||
12617 | if (auto *TD = Definition->getDescribedFunctionTemplate()) | |||
12618 | makeMergedDefinitionVisible(TD); | |||
12619 | makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); | |||
12620 | return; | |||
12621 | } | |||
12622 | ||||
12623 | if (getLangOpts().GNUMode && Definition->isInlineSpecified() && | |||
12624 | Definition->getStorageClass() == SC_Extern) | |||
12625 | Diag(FD->getLocation(), diag::err_redefinition_extern_inline) | |||
12626 | << FD->getDeclName() << getLangOpts().CPlusPlus; | |||
12627 | else | |||
12628 | Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); | |||
12629 | ||||
12630 | Diag(Definition->getLocation(), diag::note_previous_definition); | |||
12631 | FD->setInvalidDecl(); | |||
12632 | } | |||
12633 | ||||
12634 | static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, | |||
12635 | Sema &S) { | |||
12636 | CXXRecordDecl *const LambdaClass = CallOperator->getParent(); | |||
12637 | ||||
12638 | LambdaScopeInfo *LSI = S.PushLambdaScope(); | |||
12639 | LSI->CallOperator = CallOperator; | |||
12640 | LSI->Lambda = LambdaClass; | |||
12641 | LSI->ReturnType = CallOperator->getReturnType(); | |||
12642 | const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); | |||
12643 | ||||
12644 | if (LCD == LCD_None) | |||
12645 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; | |||
12646 | else if (LCD == LCD_ByCopy) | |||
12647 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; | |||
12648 | else if (LCD == LCD_ByRef) | |||
12649 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; | |||
12650 | DeclarationNameInfo DNI = CallOperator->getNameInfo(); | |||
12651 | ||||
12652 | LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); | |||
12653 | LSI->Mutable = !CallOperator->isConst(); | |||
12654 | ||||
12655 | // Add the captures to the LSI so they can be noted as already | |||
12656 | // captured within tryCaptureVar. | |||
12657 | auto I = LambdaClass->field_begin(); | |||
12658 | for (const auto &C : LambdaClass->captures()) { | |||
12659 | if (C.capturesVariable()) { | |||
12660 | VarDecl *VD = C.getCapturedVar(); | |||
12661 | if (VD->isInitCapture()) | |||
12662 | S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); | |||
12663 | QualType CaptureType = VD->getType(); | |||
12664 | const bool ByRef = C.getCaptureKind() == LCK_ByRef; | |||
12665 | LSI->addCapture(VD, /*IsBlock*/false, ByRef, | |||
12666 | /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), | |||
12667 | /*EllipsisLoc*/C.isPackExpansion() | |||
12668 | ? C.getEllipsisLoc() : SourceLocation(), | |||
12669 | CaptureType, /*Expr*/ nullptr); | |||
12670 | ||||
12671 | } else if (C.capturesThis()) { | |||
12672 | LSI->addThisCapture(/*Nested*/ false, C.getLocation(), | |||
12673 | /*Expr*/ nullptr, | |||
12674 | C.getCaptureKind() == LCK_StarThis); | |||
12675 | } else { | |||
12676 | LSI->addVLATypeCapture(C.getLocation(), I->getType()); | |||
12677 | } | |||
12678 | ++I; | |||
12679 | } | |||
12680 | } | |||
12681 | ||||
12682 | Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, | |||
12683 | SkipBodyInfo *SkipBody) { | |||
12684 | if (!D) { | |||
12685 | // Parsing the function declaration failed in some way. Push on a fake scope | |||
12686 | // anyway so we can try to parse the function body. | |||
12687 | PushFunctionScope(); | |||
12688 | return D; | |||
12689 | } | |||
12690 | ||||
12691 | FunctionDecl *FD = nullptr; | |||
12692 | ||||
12693 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) | |||
12694 | FD = FunTmpl->getTemplatedDecl(); | |||
12695 | else | |||
12696 | FD = cast<FunctionDecl>(D); | |||
12697 | ||||
12698 | // Check for defining attributes before the check for redefinition. | |||
12699 | if (const auto *Attr = FD->getAttr<AliasAttr>()) { | |||
12700 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; | |||
12701 | FD->dropAttr<AliasAttr>(); | |||
12702 | FD->setInvalidDecl(); | |||
12703 | } | |||
12704 | if (const auto *Attr = FD->getAttr<IFuncAttr>()) { | |||
12705 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; | |||
12706 | FD->dropAttr<IFuncAttr>(); | |||
12707 | FD->setInvalidDecl(); | |||
12708 | } | |||
12709 | ||||
12710 | // See if this is a redefinition. If 'will have body' is already set, then | |||
12711 | // these checks were already performed when it was set. | |||
12712 | if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { | |||
12713 | CheckForFunctionRedefinition(FD, nullptr, SkipBody); | |||
12714 | ||||
12715 | // If we're skipping the body, we're done. Don't enter the scope. | |||
12716 | if (SkipBody && SkipBody->ShouldSkip) | |||
12717 | return D; | |||
12718 | } | |||
12719 | ||||
12720 | // Mark this function as "will have a body eventually". This lets users to | |||
12721 | // call e.g. isInlineDefinitionExternallyVisible while we're still parsing | |||
12722 | // this function. | |||
12723 | FD->setWillHaveBody(); | |||
12724 | ||||
12725 | // If we are instantiating a generic lambda call operator, push | |||
12726 | // a LambdaScopeInfo onto the function stack. But use the information | |||
12727 | // that's already been calculated (ActOnLambdaExpr) to prime the current | |||
12728 | // LambdaScopeInfo. | |||
12729 | // When the template operator is being specialized, the LambdaScopeInfo, | |||
12730 | // has to be properly restored so that tryCaptureVariable doesn't try | |||
12731 | // and capture any new variables. In addition when calculating potential | |||
12732 | // captures during transformation of nested lambdas, it is necessary to | |||
12733 | // have the LSI properly restored. | |||
12734 | if (isGenericLambdaCallOperatorSpecialization(FD)) { | |||
12735 | assert(inTemplateInstantiation() &&(static_cast <bool> (inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? void (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 12737, __extension__ __PRETTY_FUNCTION__)) | |||
12736 | "There should be an active template instantiation on the stack "(static_cast <bool> (inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? void (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 12737, __extension__ __PRETTY_FUNCTION__)) | |||
12737 | "when instantiating a generic lambda!")(static_cast <bool> (inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? void (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 12737, __extension__ __PRETTY_FUNCTION__)); | |||
12738 | RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); | |||
12739 | } else { | |||
12740 | // Enter a new function scope | |||
12741 | PushFunctionScope(); | |||
12742 | } | |||
12743 | ||||
12744 | // Builtin functions cannot be defined. | |||
12745 | if (unsigned BuiltinID = FD->getBuiltinID()) { | |||
12746 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && | |||
12747 | !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { | |||
12748 | Diag(FD->getLocation(), diag::err_builtin_definition) << FD; | |||
12749 | FD->setInvalidDecl(); | |||
12750 | } | |||
12751 | } | |||
12752 | ||||
12753 | // The return type of a function definition must be complete | |||
12754 | // (C99 6.9.1p3, C++ [dcl.fct]p6). | |||
12755 | QualType ResultType = FD->getReturnType(); | |||
12756 | if (!ResultType->isDependentType() && !ResultType->isVoidType() && | |||
12757 | !FD->isInvalidDecl() && | |||
12758 | RequireCompleteType(FD->getLocation(), ResultType, | |||
12759 | diag::err_func_def_incomplete_result)) | |||
12760 | FD->setInvalidDecl(); | |||
12761 | ||||
12762 | if (FnBodyScope) | |||
12763 | PushDeclContext(FnBodyScope, FD); | |||
12764 | ||||
12765 | // Check the validity of our function parameters | |||
12766 | CheckParmsForFunctionDef(FD->parameters(), | |||
12767 | /*CheckParameterNames=*/true); | |||
12768 | ||||
12769 | // Add non-parameter declarations already in the function to the current | |||
12770 | // scope. | |||
12771 | if (FnBodyScope) { | |||
12772 | for (Decl *NPD : FD->decls()) { | |||
12773 | auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); | |||
12774 | if (!NonParmDecl) | |||
12775 | continue; | |||
12776 | assert(!isa<ParmVarDecl>(NonParmDecl) &&(static_cast <bool> (!isa<ParmVarDecl>(NonParmDecl ) && "parameters should not be in newly created FD yet" ) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 12777, __extension__ __PRETTY_FUNCTION__)) | |||
12777 | "parameters should not be in newly created FD yet")(static_cast <bool> (!isa<ParmVarDecl>(NonParmDecl ) && "parameters should not be in newly created FD yet" ) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 12777, __extension__ __PRETTY_FUNCTION__)); | |||
12778 | ||||
12779 | // If the decl has a name, make it accessible in the current scope. | |||
12780 | if (NonParmDecl->getDeclName()) | |||
12781 | PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); | |||
12782 | ||||
12783 | // Similarly, dive into enums and fish their constants out, making them | |||
12784 | // accessible in this scope. | |||
12785 | if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { | |||
12786 | for (auto *EI : ED->enumerators()) | |||
12787 | PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); | |||
12788 | } | |||
12789 | } | |||
12790 | } | |||
12791 | ||||
12792 | // Introduce our parameters into the function scope | |||
12793 | for (auto Param : FD->parameters()) { | |||
12794 | Param->setOwningFunction(FD); | |||
12795 | ||||
12796 | // If this has an identifier, add it to the scope stack. | |||
12797 | if (Param->getIdentifier() && FnBodyScope) { | |||
12798 | CheckShadow(FnBodyScope, Param); | |||
12799 | ||||
12800 | PushOnScopeChains(Param, FnBodyScope); | |||
12801 | } | |||
12802 | } | |||
12803 | ||||
12804 | // Ensure that the function's exception specification is instantiated. | |||
12805 | if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) | |||
12806 | ResolveExceptionSpec(D->getLocation(), FPT); | |||
12807 | ||||
12808 | // dllimport cannot be applied to non-inline function definitions. | |||
12809 | if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && | |||
12810 | !FD->isTemplateInstantiation()) { | |||
12811 | assert(!FD->hasAttr<DLLExportAttr>())(static_cast <bool> (!FD->hasAttr<DLLExportAttr> ()) ? void (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 12811, __extension__ __PRETTY_FUNCTION__)); | |||
12812 | Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); | |||
12813 | FD->setInvalidDecl(); | |||
12814 | return D; | |||
12815 | } | |||
12816 | // We want to attach documentation to original Decl (which might be | |||
12817 | // a function template). | |||
12818 | ActOnDocumentableDecl(D); | |||
12819 | if (getCurLexicalContext()->isObjCContainer() && | |||
12820 | getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && | |||
12821 | getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) | |||
12822 | Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); | |||
12823 | ||||
12824 | return D; | |||
12825 | } | |||
12826 | ||||
12827 | /// Given the set of return statements within a function body, | |||
12828 | /// compute the variables that are subject to the named return value | |||
12829 | /// optimization. | |||
12830 | /// | |||
12831 | /// Each of the variables that is subject to the named return value | |||
12832 | /// optimization will be marked as NRVO variables in the AST, and any | |||
12833 | /// return statement that has a marked NRVO variable as its NRVO candidate can | |||
12834 | /// use the named return value optimization. | |||
12835 | /// | |||
12836 | /// This function applies a very simplistic algorithm for NRVO: if every return | |||
12837 | /// statement in the scope of a variable has the same NRVO candidate, that | |||
12838 | /// candidate is an NRVO variable. | |||
12839 | void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { | |||
12840 | ReturnStmt **Returns = Scope->Returns.data(); | |||
12841 | ||||
12842 | for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { | |||
12843 | if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { | |||
12844 | if (!NRVOCandidate->isNRVOVariable()) | |||
12845 | Returns[I]->setNRVOCandidate(nullptr); | |||
12846 | } | |||
12847 | } | |||
12848 | } | |||
12849 | ||||
12850 | bool Sema::canDelayFunctionBody(const Declarator &D) { | |||
12851 | // We can't delay parsing the body of a constexpr function template (yet). | |||
12852 | if (D.getDeclSpec().isConstexprSpecified()) | |||
12853 | return false; | |||
12854 | ||||
12855 | // We can't delay parsing the body of a function template with a deduced | |||
12856 | // return type (yet). | |||
12857 | if (D.getDeclSpec().hasAutoTypeSpec()) { | |||
12858 | // If the placeholder introduces a non-deduced trailing return type, | |||
12859 | // we can still delay parsing it. | |||
12860 | if (D.getNumTypeObjects()) { | |||
12861 | const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); | |||
12862 | if (Outer.Kind == DeclaratorChunk::Function && | |||
12863 | Outer.Fun.hasTrailingReturnType()) { | |||
12864 | QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); | |||
12865 | return Ty.isNull() || !Ty->isUndeducedType(); | |||
12866 | } | |||
12867 | } | |||
12868 | return false; | |||
12869 | } | |||
12870 | ||||
12871 | return true; | |||
12872 | } | |||
12873 | ||||
12874 | bool Sema::canSkipFunctionBody(Decl *D) { | |||
12875 | // We cannot skip the body of a function (or function template) which is | |||
12876 | // constexpr, since we may need to evaluate its body in order to parse the | |||
12877 | // rest of the file. | |||
12878 | // We cannot skip the body of a function with an undeduced return type, | |||
12879 | // because any callers of that function need to know the type. | |||
12880 | if (const FunctionDecl *FD = D->getAsFunction()) { | |||
12881 | if (FD->isConstexpr()) | |||
12882 | return false; | |||
12883 | // We can't simply call Type::isUndeducedType here, because inside template | |||
12884 | // auto can be deduced to a dependent type, which is not considered | |||
12885 | // "undeduced". | |||
12886 | if (FD->getReturnType()->getContainedDeducedType()) | |||
12887 | return false; | |||
12888 | } | |||
12889 | return Consumer.shouldSkipFunctionBody(D); | |||
12890 | } | |||
12891 | ||||
12892 | Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { | |||
12893 | if (!Decl) | |||
12894 | return nullptr; | |||
12895 | if (FunctionDecl *FD = Decl->getAsFunction()) | |||
12896 | FD->setHasSkippedBody(); | |||
12897 | else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) | |||
12898 | MD->setHasSkippedBody(); | |||
12899 | return Decl; | |||
12900 | } | |||
12901 | ||||
12902 | Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { | |||
12903 | return ActOnFinishFunctionBody(D, BodyArg, false); | |||
12904 | } | |||
12905 | ||||
12906 | Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, | |||
12907 | bool IsInstantiation) { | |||
12908 | FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; | |||
12909 | ||||
12910 | sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | |||
12911 | sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; | |||
12912 | ||||
12913 | if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) | |||
12914 | CheckCompletedCoroutineBody(FD, Body); | |||
12915 | ||||
12916 | if (FD) { | |||
12917 | FD->setBody(Body); | |||
12918 | FD->setWillHaveBody(false); | |||
12919 | ||||
12920 | if (getLangOpts().CPlusPlus14) { | |||
12921 | if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && | |||
12922 | FD->getReturnType()->isUndeducedType()) { | |||
12923 | // If the function has a deduced result type but contains no 'return' | |||
12924 | // statements, the result type as written must be exactly 'auto', and | |||
12925 | // the deduced result type is 'void'. | |||
12926 | if (!FD->getReturnType()->getAs<AutoType>()) { | |||
12927 | Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) | |||
12928 | << FD->getReturnType(); | |||
12929 | FD->setInvalidDecl(); | |||
12930 | } else { | |||
12931 | // Substitute 'void' for the 'auto' in the type. | |||
12932 | TypeLoc ResultType = getReturnTypeLoc(FD); | |||
12933 | Context.adjustDeducedFunctionResultType( | |||
12934 | FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); | |||
12935 | } | |||
12936 | } | |||
12937 | } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { | |||
12938 | // In C++11, we don't use 'auto' deduction rules for lambda call | |||
12939 | // operators because we don't support return type deduction. | |||
12940 | auto *LSI = getCurLambda(); | |||
12941 | if (LSI->HasImplicitReturnType) { | |||
12942 | deduceClosureReturnType(*LSI); | |||
12943 | ||||
12944 | // C++11 [expr.prim.lambda]p4: | |||
12945 | // [...] if there are no return statements in the compound-statement | |||
12946 | // [the deduced type is] the type void | |||
12947 | QualType RetType = | |||
12948 | LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; | |||
12949 | ||||
12950 | // Update the return type to the deduced type. | |||
12951 | const FunctionProtoType *Proto = | |||
12952 | FD->getType()->getAs<FunctionProtoType>(); | |||
12953 | FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), | |||
12954 | Proto->getExtProtoInfo())); | |||
12955 | } | |||
12956 | } | |||
12957 | ||||
12958 | // If the function implicitly returns zero (like 'main') or is naked, | |||
12959 | // don't complain about missing return statements. | |||
12960 | if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) | |||
12961 | WP.disableCheckFallThrough(); | |||
12962 | ||||
12963 | // MSVC permits the use of pure specifier (=0) on function definition, | |||
12964 | // defined at class scope, warn about this non-standard construct. | |||
12965 | if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) | |||
12966 | Diag(FD->getLocation(), diag::ext_pure_function_definition); | |||
12967 | ||||
12968 | if (!FD->isInvalidDecl()) { | |||
12969 | // Don't diagnose unused parameters of defaulted or deleted functions. | |||
12970 | if (!FD->isDeleted() && !FD->isDefaulted()) | |||
12971 | DiagnoseUnusedParameters(FD->parameters()); | |||
12972 | DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), | |||
12973 | FD->getReturnType(), FD); | |||
12974 | ||||
12975 | // If this is a structor, we need a vtable. | |||
12976 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) | |||
12977 | MarkVTableUsed(FD->getLocation(), Constructor->getParent()); | |||
12978 | else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) | |||
12979 | MarkVTableUsed(FD->getLocation(), Destructor->getParent()); | |||
12980 | ||||
12981 | // Try to apply the named return value optimization. We have to check | |||
12982 | // if we can do this here because lambdas keep return statements around | |||
12983 | // to deduce an implicit return type. | |||
12984 | if (FD->getReturnType()->isRecordType() && | |||
12985 | (!getLangOpts().CPlusPlus || !FD->isDependentContext())) | |||
12986 | computeNRVO(Body, getCurFunction()); | |||
12987 | } | |||
12988 | ||||
12989 | // GNU warning -Wmissing-prototypes: | |||
12990 | // Warn if a global function is defined without a previous | |||
12991 | // prototype declaration. This warning is issued even if the | |||
12992 | // definition itself provides a prototype. The aim is to detect | |||
12993 | // global functions that fail to be declared in header files. | |||
12994 | const FunctionDecl *PossibleZeroParamPrototype = nullptr; | |||
12995 | if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { | |||
12996 | Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; | |||
12997 | ||||
12998 | if (PossibleZeroParamPrototype) { | |||
12999 | // We found a declaration that is not a prototype, | |||
13000 | // but that could be a zero-parameter prototype | |||
13001 | if (TypeSourceInfo *TI = | |||
13002 | PossibleZeroParamPrototype->getTypeSourceInfo()) { | |||
13003 | TypeLoc TL = TI->getTypeLoc(); | |||
13004 | if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) | |||
13005 | Diag(PossibleZeroParamPrototype->getLocation(), | |||
13006 | diag::note_declaration_not_a_prototype) | |||
13007 | << PossibleZeroParamPrototype | |||
13008 | << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); | |||
13009 | } | |||
13010 | } | |||
13011 | ||||
13012 | // GNU warning -Wstrict-prototypes | |||
13013 | // Warn if K&R function is defined without a previous declaration. | |||
13014 | // This warning is issued only if the definition itself does not provide | |||
13015 | // a prototype. Only K&R definitions do not provide a prototype. | |||
13016 | // An empty list in a function declarator that is part of a definition | |||
13017 | // of that function specifies that the function has no parameters | |||
13018 | // (C99 6.7.5.3p14) | |||
13019 | if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && | |||
13020 | !LangOpts.CPlusPlus) { | |||
13021 | TypeSourceInfo *TI = FD->getTypeSourceInfo(); | |||
13022 | TypeLoc TL = TI->getTypeLoc(); | |||
13023 | FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); | |||
13024 | Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; | |||
13025 | } | |||
13026 | } | |||
13027 | ||||
13028 | // Warn on CPUDispatch with an actual body. | |||
13029 | if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) | |||
13030 | if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) | |||
13031 | if (!CmpndBody->body_empty()) | |||
13032 | Diag(CmpndBody->body_front()->getLocStart(), | |||
13033 | diag::warn_dispatch_body_ignored); | |||
13034 | ||||
13035 | if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { | |||
13036 | const CXXMethodDecl *KeyFunction; | |||
13037 | if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && | |||
13038 | MD->isVirtual() && | |||
13039 | (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && | |||
13040 | MD == KeyFunction->getCanonicalDecl()) { | |||
13041 | // Update the key-function state if necessary for this ABI. | |||
13042 | if (FD->isInlined() && | |||
13043 | !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { | |||
13044 | Context.setNonKeyFunction(MD); | |||
13045 | ||||
13046 | // If the newly-chosen key function is already defined, then we | |||
13047 | // need to mark the vtable as used retroactively. | |||
13048 | KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); | |||
13049 | const FunctionDecl *Definition; | |||
13050 | if (KeyFunction && KeyFunction->isDefined(Definition)) | |||
13051 | MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); | |||
13052 | } else { | |||
13053 | // We just defined they key function; mark the vtable as used. | |||
13054 | MarkVTableUsed(FD->getLocation(), MD->getParent(), true); | |||
13055 | } | |||
13056 | } | |||
13057 | } | |||
13058 | ||||
13059 | assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda ()->CallOperator == FD) && "Function parsing confused" ) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13060, __extension__ __PRETTY_FUNCTION__)) | |||
13060 | "Function parsing confused")(static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda ()->CallOperator == FD) && "Function parsing confused" ) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13060, __extension__ __PRETTY_FUNCTION__)); | |||
13061 | } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { | |||
13062 | assert(MD == getCurMethodDecl() && "Method parsing confused")(static_cast <bool> (MD == getCurMethodDecl() && "Method parsing confused") ? void (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13062, __extension__ __PRETTY_FUNCTION__)); | |||
13063 | MD->setBody(Body); | |||
13064 | if (!MD->isInvalidDecl()) { | |||
13065 | DiagnoseUnusedParameters(MD->parameters()); | |||
13066 | DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), | |||
13067 | MD->getReturnType(), MD); | |||
13068 | ||||
13069 | if (Body) | |||
13070 | computeNRVO(Body, getCurFunction()); | |||
13071 | } | |||
13072 | if (getCurFunction()->ObjCShouldCallSuper) { | |||
13073 | Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) | |||
13074 | << MD->getSelector().getAsString(); | |||
13075 | getCurFunction()->ObjCShouldCallSuper = false; | |||
13076 | } | |||
13077 | if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { | |||
13078 | const ObjCMethodDecl *InitMethod = nullptr; | |||
13079 | bool isDesignated = | |||
13080 | MD->isDesignatedInitializerForTheInterface(&InitMethod); | |||
13081 | assert(isDesignated && InitMethod)(static_cast <bool> (isDesignated && InitMethod ) ? void (0) : __assert_fail ("isDesignated && InitMethod" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13081, __extension__ __PRETTY_FUNCTION__)); | |||
13082 | (void)isDesignated; | |||
13083 | ||||
13084 | auto superIsNSObject = [&](const ObjCMethodDecl *MD) { | |||
13085 | auto IFace = MD->getClassInterface(); | |||
13086 | if (!IFace) | |||
13087 | return false; | |||
13088 | auto SuperD = IFace->getSuperClass(); | |||
13089 | if (!SuperD) | |||
13090 | return false; | |||
13091 | return SuperD->getIdentifier() == | |||
13092 | NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); | |||
13093 | }; | |||
13094 | // Don't issue this warning for unavailable inits or direct subclasses | |||
13095 | // of NSObject. | |||
13096 | if (!MD->isUnavailable() && !superIsNSObject(MD)) { | |||
13097 | Diag(MD->getLocation(), | |||
13098 | diag::warn_objc_designated_init_missing_super_call); | |||
13099 | Diag(InitMethod->getLocation(), | |||
13100 | diag::note_objc_designated_init_marked_here); | |||
13101 | } | |||
13102 | getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; | |||
13103 | } | |||
13104 | if (getCurFunction()->ObjCWarnForNoInitDelegation) { | |||
13105 | // Don't issue this warning for unavaialable inits. | |||
13106 | if (!MD->isUnavailable()) | |||
13107 | Diag(MD->getLocation(), | |||
13108 | diag::warn_objc_secondary_init_missing_init_call); | |||
13109 | getCurFunction()->ObjCWarnForNoInitDelegation = false; | |||
13110 | } | |||
13111 | } else { | |||
13112 | // Parsing the function declaration failed in some way. Pop the fake scope | |||
13113 | // we pushed on. | |||
13114 | PopFunctionScopeInfo(ActivePolicy, dcl); | |||
13115 | return nullptr; | |||
13116 | } | |||
13117 | ||||
13118 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | |||
13119 | DiagnoseUnguardedAvailabilityViolations(dcl); | |||
13120 | ||||
13121 | assert(!getCurFunction()->ObjCShouldCallSuper &&(static_cast <bool> (!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? 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-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13123, __extension__ __PRETTY_FUNCTION__)) | |||
13122 | "This should only be set for ObjC methods, which should have been "(static_cast <bool> (!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? 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-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13123, __extension__ __PRETTY_FUNCTION__)) | |||
13123 | "handled in the block above.")(static_cast <bool> (!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? 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-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13123, __extension__ __PRETTY_FUNCTION__)); | |||
13124 | ||||
13125 | // Verify and clean out per-function state. | |||
13126 | if (Body && (!FD || !FD->isDefaulted())) { | |||
13127 | // C++ constructors that have function-try-blocks can't have return | |||
13128 | // statements in the handlers of that block. (C++ [except.handle]p14) | |||
13129 | // Verify this. | |||
13130 | if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) | |||
13131 | DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); | |||
13132 | ||||
13133 | // Verify that gotos and switch cases don't jump into scopes illegally. | |||
13134 | if (getCurFunction()->NeedsScopeChecking() && | |||
13135 | !PP.isCodeCompletionEnabled()) | |||
13136 | DiagnoseInvalidJumps(Body); | |||
13137 | ||||
13138 | if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { | |||
13139 | if (!Destructor->getParent()->isDependentType()) | |||
13140 | CheckDestructor(Destructor); | |||
13141 | ||||
13142 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | |||
13143 | Destructor->getParent()); | |||
13144 | } | |||
13145 | ||||
13146 | // If any errors have occurred, clear out any temporaries that may have | |||
13147 | // been leftover. This ensures that these temporaries won't be picked up for | |||
13148 | // deletion in some later function. | |||
13149 | if (getDiagnostics().hasErrorOccurred() || | |||
13150 | getDiagnostics().getSuppressAllDiagnostics()) { | |||
13151 | DiscardCleanupsInEvaluationContext(); | |||
13152 | } | |||
13153 | if (!getDiagnostics().hasUncompilableErrorOccurred() && | |||
13154 | !isa<FunctionTemplateDecl>(dcl)) { | |||
13155 | // Since the body is valid, issue any analysis-based warnings that are | |||
13156 | // enabled. | |||
13157 | ActivePolicy = &WP; | |||
13158 | } | |||
13159 | ||||
13160 | if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && | |||
13161 | (!CheckConstexprFunctionDecl(FD) || | |||
13162 | !CheckConstexprFunctionBody(FD, Body))) | |||
13163 | FD->setInvalidDecl(); | |||
13164 | ||||
13165 | if (FD && FD->hasAttr<NakedAttr>()) { | |||
13166 | for (const Stmt *S : Body->children()) { | |||
13167 | // Allow local register variables without initializer as they don't | |||
13168 | // require prologue. | |||
13169 | bool RegisterVariables = false; | |||
13170 | if (auto *DS = dyn_cast<DeclStmt>(S)) { | |||
13171 | for (const auto *Decl : DS->decls()) { | |||
13172 | if (const auto *Var = dyn_cast<VarDecl>(Decl)) { | |||
13173 | RegisterVariables = | |||
13174 | Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); | |||
13175 | if (!RegisterVariables) | |||
13176 | break; | |||
13177 | } | |||
13178 | } | |||
13179 | } | |||
13180 | if (RegisterVariables) | |||
13181 | continue; | |||
13182 | if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { | |||
13183 | Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); | |||
13184 | Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); | |||
13185 | FD->setInvalidDecl(); | |||
13186 | break; | |||
13187 | } | |||
13188 | } | |||
13189 | } | |||
13190 | ||||
13191 | assert(ExprCleanupObjects.size() ==(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts .back().NumCleanupObjects && "Leftover temporaries in function" ) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13193, __extension__ __PRETTY_FUNCTION__)) | |||
13192 | ExprEvalContexts.back().NumCleanupObjects &&(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts .back().NumCleanupObjects && "Leftover temporaries in function" ) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13193, __extension__ __PRETTY_FUNCTION__)) | |||
13193 | "Leftover temporaries in function")(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts .back().NumCleanupObjects && "Leftover temporaries in function" ) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13193, __extension__ __PRETTY_FUNCTION__)); | |||
13194 | assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13194, __extension__ __PRETTY_FUNCTION__)); | |||
13195 | assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13196, __extension__ __PRETTY_FUNCTION__)) | |||
13196 | "Leftover expressions for odr-use checking")(static_cast <bool> (MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13196, __extension__ __PRETTY_FUNCTION__)); | |||
13197 | } | |||
13198 | ||||
13199 | if (!IsInstantiation) | |||
13200 | PopDeclContext(); | |||
13201 | ||||
13202 | PopFunctionScopeInfo(ActivePolicy, dcl); | |||
13203 | // If any errors have occurred, clear out any temporaries that may have | |||
13204 | // been leftover. This ensures that these temporaries won't be picked up for | |||
13205 | // deletion in some later function. | |||
13206 | if (getDiagnostics().hasErrorOccurred()) { | |||
13207 | DiscardCleanupsInEvaluationContext(); | |||
13208 | } | |||
13209 | ||||
13210 | return dcl; | |||
13211 | } | |||
13212 | ||||
13213 | /// When we finish delayed parsing of an attribute, we must attach it to the | |||
13214 | /// relevant Decl. | |||
13215 | void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, | |||
13216 | ParsedAttributes &Attrs) { | |||
13217 | // Always attach attributes to the underlying decl. | |||
13218 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | |||
13219 | D = TD->getTemplatedDecl(); | |||
13220 | ProcessDeclAttributeList(S, D, Attrs); | |||
13221 | ||||
13222 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) | |||
13223 | if (Method->isStatic()) | |||
13224 | checkThisInStaticMemberFunctionAttributes(Method); | |||
13225 | } | |||
13226 | ||||
13227 | /// ImplicitlyDefineFunction - An undeclared identifier was used in a function | |||
13228 | /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). | |||
13229 | NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, | |||
13230 | IdentifierInfo &II, Scope *S) { | |||
13231 | // Find the scope in which the identifier is injected and the corresponding | |||
13232 | // DeclContext. | |||
13233 | // FIXME: C89 does not say what happens if there is no enclosing block scope. | |||
13234 | // In that case, we inject the declaration into the translation unit scope | |||
13235 | // instead. | |||
13236 | Scope *BlockScope = S; | |||
13237 | while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) | |||
13238 | BlockScope = BlockScope->getParent(); | |||
13239 | ||||
13240 | Scope *ContextScope = BlockScope; | |||
13241 | while (!ContextScope->getEntity()) | |||
13242 | ContextScope = ContextScope->getParent(); | |||
13243 | ContextRAII SavedContext(*this, ContextScope->getEntity()); | |||
13244 | ||||
13245 | // Before we produce a declaration for an implicitly defined | |||
13246 | // function, see whether there was a locally-scoped declaration of | |||
13247 | // this name as a function or variable. If so, use that | |||
13248 | // (non-visible) declaration, and complain about it. | |||
13249 | NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); | |||
13250 | if (ExternCPrev) { | |||
13251 | // We still need to inject the function into the enclosing block scope so | |||
13252 | // that later (non-call) uses can see it. | |||
13253 | PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); | |||
13254 | ||||
13255 | // C89 footnote 38: | |||
13256 | // If in fact it is not defined as having type "function returning int", | |||
13257 | // the behavior is undefined. | |||
13258 | if (!isa<FunctionDecl>(ExternCPrev) || | |||
13259 | !Context.typesAreCompatible( | |||
13260 | cast<FunctionDecl>(ExternCPrev)->getType(), | |||
13261 | Context.getFunctionNoProtoType(Context.IntTy))) { | |||
13262 | Diag(Loc, diag::ext_use_out_of_scope_declaration) | |||
13263 | << ExternCPrev << !getLangOpts().C99; | |||
13264 | Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); | |||
13265 | return ExternCPrev; | |||
13266 | } | |||
13267 | } | |||
13268 | ||||
13269 | // Extension in C99. Legal in C90, but warn about it. | |||
13270 | // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. | |||
13271 | unsigned diag_id; | |||
13272 | if (II.getName().startswith("__builtin_")) | |||
13273 | diag_id = diag::warn_builtin_unknown; | |||
13274 | else if (getLangOpts().C99 || getLangOpts().OpenCL) | |||
13275 | diag_id = diag::ext_implicit_function_decl; | |||
13276 | else | |||
13277 | diag_id = diag::warn_implicit_function_decl; | |||
13278 | Diag(Loc, diag_id) << &II << getLangOpts().OpenCL; | |||
13279 | ||||
13280 | // If we found a prior declaration of this function, don't bother building | |||
13281 | // another one. We've already pushed that one into scope, so there's nothing | |||
13282 | // more to do. | |||
13283 | if (ExternCPrev) | |||
13284 | return ExternCPrev; | |||
13285 | ||||
13286 | // Because typo correction is expensive, only do it if the implicit | |||
13287 | // function declaration is going to be treated as an error. | |||
13288 | if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { | |||
13289 | TypoCorrection Corrected; | |||
13290 | if (S && | |||
13291 | (Corrected = CorrectTypo( | |||
13292 | DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, | |||
13293 | llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) | |||
13294 | diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), | |||
13295 | /*ErrorRecovery*/false); | |||
13296 | } | |||
13297 | ||||
13298 | // Set a Declarator for the implicit definition: int foo(); | |||
13299 | const char *Dummy; | |||
13300 | AttributeFactory attrFactory; | |||
13301 | DeclSpec DS(attrFactory); | |||
13302 | unsigned DiagID; | |||
13303 | bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, | |||
13304 | Context.getPrintingPolicy()); | |||
13305 | (void)Error; // Silence warning. | |||
13306 | assert(!Error && "Error setting up implicit decl!")(static_cast <bool> (!Error && "Error setting up implicit decl!" ) ? void (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13306, __extension__ __PRETTY_FUNCTION__)); | |||
13307 | SourceLocation NoLoc; | |||
13308 | Declarator D(DS, DeclaratorContext::BlockContext); | |||
13309 | D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, | |||
13310 | /*IsAmbiguous=*/false, | |||
13311 | /*LParenLoc=*/NoLoc, | |||
13312 | /*Params=*/nullptr, | |||
13313 | /*NumParams=*/0, | |||
13314 | /*EllipsisLoc=*/NoLoc, | |||
13315 | /*RParenLoc=*/NoLoc, | |||
13316 | /*TypeQuals=*/0, | |||
13317 | /*RefQualifierIsLvalueRef=*/true, | |||
13318 | /*RefQualifierLoc=*/NoLoc, | |||
13319 | /*ConstQualifierLoc=*/NoLoc, | |||
13320 | /*VolatileQualifierLoc=*/NoLoc, | |||
13321 | /*RestrictQualifierLoc=*/NoLoc, | |||
13322 | /*MutableLoc=*/NoLoc, EST_None, | |||
13323 | /*ESpecRange=*/SourceRange(), | |||
13324 | /*Exceptions=*/nullptr, | |||
13325 | /*ExceptionRanges=*/nullptr, | |||
13326 | /*NumExceptions=*/0, | |||
13327 | /*NoexceptExpr=*/nullptr, | |||
13328 | /*ExceptionSpecTokens=*/nullptr, | |||
13329 | /*DeclsInPrototype=*/None, Loc, | |||
13330 | Loc, D), | |||
13331 | std::move(DS.getAttributes()), SourceLocation()); | |||
13332 | D.SetIdentifier(&II, Loc); | |||
13333 | ||||
13334 | // Insert this function into the enclosing block scope. | |||
13335 | FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); | |||
13336 | FD->setImplicit(); | |||
13337 | ||||
13338 | AddKnownFunctionAttributes(FD); | |||
13339 | ||||
13340 | return FD; | |||
13341 | } | |||
13342 | ||||
13343 | /// Adds any function attributes that we know a priori based on | |||
13344 | /// the declaration of this function. | |||
13345 | /// | |||
13346 | /// These attributes can apply both to implicitly-declared builtins | |||
13347 | /// (like __builtin___printf_chk) or to library-declared functions | |||
13348 | /// like NSLog or printf. | |||
13349 | /// | |||
13350 | /// We need to check for duplicate attributes both here and where user-written | |||
13351 | /// attributes are applied to declarations. | |||
13352 | void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { | |||
13353 | if (FD->isInvalidDecl()) | |||
13354 | return; | |||
13355 | ||||
13356 | // If this is a built-in function, map its builtin attributes to | |||
13357 | // actual attributes. | |||
13358 | if (unsigned BuiltinID = FD->getBuiltinID()) { | |||
13359 | // Handle printf-formatting attributes. | |||
13360 | unsigned FormatIdx; | |||
13361 | bool HasVAListArg; | |||
13362 | if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { | |||
13363 | if (!FD->hasAttr<FormatAttr>()) { | |||
13364 | const char *fmt = "printf"; | |||
13365 | unsigned int NumParams = FD->getNumParams(); | |||
13366 | if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) | |||
13367 | FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) | |||
13368 | fmt = "NSString"; | |||
13369 | FD->addAttr(FormatAttr::CreateImplicit(Context, | |||
13370 | &Context.Idents.get(fmt), | |||
13371 | FormatIdx+1, | |||
13372 | HasVAListArg ? 0 : FormatIdx+2, | |||
13373 | FD->getLocation())); | |||
13374 | } | |||
13375 | } | |||
13376 | if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, | |||
13377 | HasVAListArg)) { | |||
13378 | if (!FD->hasAttr<FormatAttr>()) | |||
13379 | FD->addAttr(FormatAttr::CreateImplicit(Context, | |||
13380 | &Context.Idents.get("scanf"), | |||
13381 | FormatIdx+1, | |||
13382 | HasVAListArg ? 0 : FormatIdx+2, | |||
13383 | FD->getLocation())); | |||
13384 | } | |||
13385 | ||||
13386 | // Mark const if we don't care about errno and that is the only thing | |||
13387 | // preventing the function from being const. This allows IRgen to use LLVM | |||
13388 | // intrinsics for such functions. | |||
13389 | if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && | |||
13390 | Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) | |||
13391 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | |||
13392 | ||||
13393 | // We make "fma" on some platforms const because we know it does not set | |||
13394 | // errno in those environments even though it could set errno based on the | |||
13395 | // C standard. | |||
13396 | const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); | |||
13397 | if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && | |||
13398 | !FD->hasAttr<ConstAttr>()) { | |||
13399 | switch (BuiltinID) { | |||
13400 | case Builtin::BI__builtin_fma: | |||
13401 | case Builtin::BI__builtin_fmaf: | |||
13402 | case Builtin::BI__builtin_fmal: | |||
13403 | case Builtin::BIfma: | |||
13404 | case Builtin::BIfmaf: | |||
13405 | case Builtin::BIfmal: | |||
13406 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | |||
13407 | break; | |||
13408 | default: | |||
13409 | break; | |||
13410 | } | |||
13411 | } | |||
13412 | ||||
13413 | if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && | |||
13414 | !FD->hasAttr<ReturnsTwiceAttr>()) | |||
13415 | FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, | |||
13416 | FD->getLocation())); | |||
13417 | if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) | |||
13418 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | |||
13419 | if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) | |||
13420 | FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); | |||
13421 | if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) | |||
13422 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | |||
13423 | if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && | |||
13424 | !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { | |||
13425 | // Add the appropriate attribute, depending on the CUDA compilation mode | |||
13426 | // and which target the builtin belongs to. For example, during host | |||
13427 | // compilation, aux builtins are __device__, while the rest are __host__. | |||
13428 | if (getLangOpts().CUDAIsDevice != | |||
13429 | Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) | |||
13430 | FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); | |||
13431 | else | |||
13432 | FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); | |||
13433 | } | |||
13434 | } | |||
13435 | ||||
13436 | // If C++ exceptions are enabled but we are told extern "C" functions cannot | |||
13437 | // throw, add an implicit nothrow attribute to any extern "C" function we come | |||
13438 | // across. | |||
13439 | if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && | |||
13440 | FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { | |||
13441 | const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); | |||
13442 | if (!FPT || FPT->getExceptionSpecType() == EST_None) | |||
13443 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | |||
13444 | } | |||
13445 | ||||
13446 | IdentifierInfo *Name = FD->getIdentifier(); | |||
13447 | if (!Name) | |||
13448 | return; | |||
13449 | if ((!getLangOpts().CPlusPlus && | |||
13450 | FD->getDeclContext()->isTranslationUnit()) || | |||
13451 | (isa<LinkageSpecDecl>(FD->getDeclContext()) && | |||
13452 | cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == | |||
13453 | LinkageSpecDecl::lang_c)) { | |||
13454 | // Okay: this could be a libc/libm/Objective-C function we know | |||
13455 | // about. | |||
13456 | } else | |||
13457 | return; | |||
13458 | ||||
13459 | if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { | |||
13460 | // FIXME: asprintf and vasprintf aren't C99 functions. Should they be | |||
13461 | // target-specific builtins, perhaps? | |||
13462 | if (!FD->hasAttr<FormatAttr>()) | |||
13463 | FD->addAttr(FormatAttr::CreateImplicit(Context, | |||
13464 | &Context.Idents.get("printf"), 2, | |||
13465 | Name->isStr("vasprintf") ? 0 : 3, | |||
13466 | FD->getLocation())); | |||
13467 | } | |||
13468 | ||||
13469 | if (Name->isStr("__CFStringMakeConstantString")) { | |||
13470 | // We already have a __builtin___CFStringMakeConstantString, | |||
13471 | // but builds that use -fno-constant-cfstrings don't go through that. | |||
13472 | if (!FD->hasAttr<FormatArgAttr>()) | |||
13473 | FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), | |||
13474 | FD->getLocation())); | |||
13475 | } | |||
13476 | } | |||
13477 | ||||
13478 | TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, | |||
13479 | TypeSourceInfo *TInfo) { | |||
13480 | assert(D.getIdentifier() && "Wrong callback for declspec without declarator")(static_cast <bool> (D.getIdentifier() && "Wrong callback for declspec without declarator" ) ? void (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13480, __extension__ __PRETTY_FUNCTION__)); | |||
13481 | assert(!T.isNull() && "GetTypeForDeclarator() returned null type")(static_cast <bool> (!T.isNull() && "GetTypeForDeclarator() returned null type" ) ? void (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13481, __extension__ __PRETTY_FUNCTION__)); | |||
13482 | ||||
13483 | if (!TInfo) { | |||
13484 | assert(D.isInvalidType() && "no declarator info for valid type")(static_cast <bool> (D.isInvalidType() && "no declarator info for valid type" ) ? void (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13484, __extension__ __PRETTY_FUNCTION__)); | |||
13485 | TInfo = Context.getTrivialTypeSourceInfo(T); | |||
13486 | } | |||
13487 | ||||
13488 | // Scope manipulation handled by caller. | |||
13489 | TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, | |||
13490 | D.getLocStart(), | |||
13491 | D.getIdentifierLoc(), | |||
13492 | D.getIdentifier(), | |||
13493 | TInfo); | |||
13494 | ||||
13495 | // Bail out immediately if we have an invalid declaration. | |||
13496 | if (D.isInvalidType()) { | |||
13497 | NewTD->setInvalidDecl(); | |||
13498 | return NewTD; | |||
13499 | } | |||
13500 | ||||
13501 | if (D.getDeclSpec().isModulePrivateSpecified()) { | |||
13502 | if (CurContext->isFunctionOrMethod()) | |||
13503 | Diag(NewTD->getLocation(), diag::err_module_private_local) | |||
13504 | << 2 << NewTD->getDeclName() | |||
13505 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | |||
13506 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | |||
13507 | else | |||
13508 | NewTD->setModulePrivate(); | |||
13509 | } | |||
13510 | ||||
13511 | // C++ [dcl.typedef]p8: | |||
13512 | // If the typedef declaration defines an unnamed class (or | |||
13513 | // enum), the first typedef-name declared by the declaration | |||
13514 | // to be that class type (or enum type) is used to denote the | |||
13515 | // class type (or enum type) for linkage purposes only. | |||
13516 | // We need to check whether the type was declared in the declaration. | |||
13517 | switch (D.getDeclSpec().getTypeSpecType()) { | |||
13518 | case TST_enum: | |||
13519 | case TST_struct: | |||
13520 | case TST_interface: | |||
13521 | case TST_union: | |||
13522 | case TST_class: { | |||
13523 | TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
13524 | setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); | |||
13525 | break; | |||
13526 | } | |||
13527 | ||||
13528 | default: | |||
13529 | break; | |||
13530 | } | |||
13531 | ||||
13532 | return NewTD; | |||
13533 | } | |||
13534 | ||||
13535 | /// Check that this is a valid underlying type for an enum declaration. | |||
13536 | bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { | |||
13537 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); | |||
13538 | QualType T = TI->getType(); | |||
13539 | ||||
13540 | if (T->isDependentType()) | |||
13541 | return false; | |||
13542 | ||||
13543 | if (const BuiltinType *BT = T->getAs<BuiltinType>()) | |||
13544 | if (BT->isInteger()) | |||
13545 | return false; | |||
13546 | ||||
13547 | Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; | |||
13548 | return true; | |||
13549 | } | |||
13550 | ||||
13551 | /// Check whether this is a valid redeclaration of a previous enumeration. | |||
13552 | /// \return true if the redeclaration was invalid. | |||
13553 | bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, | |||
13554 | QualType EnumUnderlyingTy, bool IsFixed, | |||
13555 | const EnumDecl *Prev) { | |||
13556 | if (IsScoped != Prev->isScoped()) { | |||
13557 | Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) | |||
13558 | << Prev->isScoped(); | |||
13559 | Diag(Prev->getLocation(), diag::note_previous_declaration); | |||
13560 | return true; | |||
13561 | } | |||
13562 | ||||
13563 | if (IsFixed && Prev->isFixed()) { | |||
13564 | if (!EnumUnderlyingTy->isDependentType() && | |||
13565 | !Prev->getIntegerType()->isDependentType() && | |||
13566 | !Context.hasSameUnqualifiedType(EnumUnderlyingTy, | |||
13567 | Prev->getIntegerType())) { | |||
13568 | // TODO: Highlight the underlying type of the redeclaration. | |||
13569 | Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) | |||
13570 | << EnumUnderlyingTy << Prev->getIntegerType(); | |||
13571 | Diag(Prev->getLocation(), diag::note_previous_declaration) | |||
13572 | << Prev->getIntegerTypeRange(); | |||
13573 | return true; | |||
13574 | } | |||
13575 | } else if (IsFixed != Prev->isFixed()) { | |||
13576 | Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) | |||
13577 | << Prev->isFixed(); | |||
13578 | Diag(Prev->getLocation(), diag::note_previous_declaration); | |||
13579 | return true; | |||
13580 | } | |||
13581 | ||||
13582 | return false; | |||
13583 | } | |||
13584 | ||||
13585 | /// Get diagnostic %select index for tag kind for | |||
13586 | /// redeclaration diagnostic message. | |||
13587 | /// WARNING: Indexes apply to particular diagnostics only! | |||
13588 | /// | |||
13589 | /// \returns diagnostic %select index. | |||
13590 | static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { | |||
13591 | switch (Tag) { | |||
13592 | case TTK_Struct: return 0; | |||
13593 | case TTK_Interface: return 1; | |||
13594 | case TTK_Class: return 2; | |||
13595 | default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13595); | |||
13596 | } | |||
13597 | } | |||
13598 | ||||
13599 | /// Determine if tag kind is a class-key compatible with | |||
13600 | /// class for redeclaration (class, struct, or __interface). | |||
13601 | /// | |||
13602 | /// \returns true iff the tag kind is compatible. | |||
13603 | static bool isClassCompatTagKind(TagTypeKind Tag) | |||
13604 | { | |||
13605 | return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; | |||
13606 | } | |||
13607 | ||||
13608 | Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, | |||
13609 | TagTypeKind TTK) { | |||
13610 | if (isa<TypedefDecl>(PrevDecl)) | |||
13611 | return NTK_Typedef; | |||
13612 | else if (isa<TypeAliasDecl>(PrevDecl)) | |||
13613 | return NTK_TypeAlias; | |||
13614 | else if (isa<ClassTemplateDecl>(PrevDecl)) | |||
13615 | return NTK_Template; | |||
13616 | else if (isa<TypeAliasTemplateDecl>(PrevDecl)) | |||
13617 | return NTK_TypeAliasTemplate; | |||
13618 | else if (isa<TemplateTemplateParmDecl>(PrevDecl)) | |||
13619 | return NTK_TemplateTemplateArgument; | |||
13620 | switch (TTK) { | |||
13621 | case TTK_Struct: | |||
13622 | case TTK_Interface: | |||
13623 | case TTK_Class: | |||
13624 | return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; | |||
13625 | case TTK_Union: | |||
13626 | return NTK_NonUnion; | |||
13627 | case TTK_Enum: | |||
13628 | return NTK_NonEnum; | |||
13629 | } | |||
13630 | llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13630); | |||
13631 | } | |||
13632 | ||||
13633 | /// Determine whether a tag with a given kind is acceptable | |||
13634 | /// as a redeclaration of the given tag declaration. | |||
13635 | /// | |||
13636 | /// \returns true if the new tag kind is acceptable, false otherwise. | |||
13637 | bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, | |||
13638 | TagTypeKind NewTag, bool isDefinition, | |||
13639 | SourceLocation NewTagLoc, | |||
13640 | const IdentifierInfo *Name) { | |||
13641 | // C++ [dcl.type.elab]p3: | |||
13642 | // The class-key or enum keyword present in the | |||
13643 | // elaborated-type-specifier shall agree in kind with the | |||
13644 | // declaration to which the name in the elaborated-type-specifier | |||
13645 | // refers. This rule also applies to the form of | |||
13646 | // elaborated-type-specifier that declares a class-name or | |||
13647 | // friend class since it can be construed as referring to the | |||
13648 | // definition of the class. Thus, in any | |||
13649 | // elaborated-type-specifier, the enum keyword shall be used to | |||
13650 | // refer to an enumeration (7.2), the union class-key shall be | |||
13651 | // used to refer to a union (clause 9), and either the class or | |||
13652 | // struct class-key shall be used to refer to a class (clause 9) | |||
13653 | // declared using the class or struct class-key. | |||
13654 | TagTypeKind OldTag = Previous->getTagKind(); | |||
13655 | if (!isDefinition || !isClassCompatTagKind(NewTag)) | |||
13656 | if (OldTag == NewTag) | |||
13657 | return true; | |||
13658 | ||||
13659 | if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { | |||
13660 | // Warn about the struct/class tag mismatch. | |||
13661 | bool isTemplate = false; | |||
13662 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) | |||
13663 | isTemplate = Record->getDescribedClassTemplate(); | |||
13664 | ||||
13665 | if (inTemplateInstantiation()) { | |||
13666 | // In a template instantiation, do not offer fix-its for tag mismatches | |||
13667 | // since they usually mess up the template instead of fixing the problem. | |||
13668 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | |||
13669 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | |||
13670 | << getRedeclDiagFromTagKind(OldTag); | |||
13671 | return true; | |||
13672 | } | |||
13673 | ||||
13674 | if (isDefinition) { | |||
13675 | // On definitions, check previous tags and issue a fix-it for each | |||
13676 | // one that doesn't match the current tag. | |||
13677 | if (Previous->getDefinition()) { | |||
13678 | // Don't suggest fix-its for redefinitions. | |||
13679 | return true; | |||
13680 | } | |||
13681 | ||||
13682 | bool previousMismatch = false; | |||
13683 | for (auto I : Previous->redecls()) { | |||
13684 | if (I->getTagKind() != NewTag) { | |||
13685 | if (!previousMismatch) { | |||
13686 | previousMismatch = true; | |||
13687 | Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) | |||
13688 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | |||
13689 | << getRedeclDiagFromTagKind(I->getTagKind()); | |||
13690 | } | |||
13691 | Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) | |||
13692 | << getRedeclDiagFromTagKind(NewTag) | |||
13693 | << FixItHint::CreateReplacement(I->getInnerLocStart(), | |||
13694 | TypeWithKeyword::getTagTypeKindName(NewTag)); | |||
13695 | } | |||
13696 | } | |||
13697 | return true; | |||
13698 | } | |||
13699 | ||||
13700 | // Check for a previous definition. If current tag and definition | |||
13701 | // are same type, do nothing. If no definition, but disagree with | |||
13702 | // with previous tag type, give a warning, but no fix-it. | |||
13703 | const TagDecl *Redecl = Previous->getDefinition() ? | |||
13704 | Previous->getDefinition() : Previous; | |||
13705 | if (Redecl->getTagKind() == NewTag) { | |||
13706 | return true; | |||
13707 | } | |||
13708 | ||||
13709 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | |||
13710 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | |||
13711 | << getRedeclDiagFromTagKind(OldTag); | |||
13712 | Diag(Redecl->getLocation(), diag::note_previous_use); | |||
13713 | ||||
13714 | // If there is a previous definition, suggest a fix-it. | |||
13715 | if (Previous->getDefinition()) { | |||
13716 | Diag(NewTagLoc, diag::note_struct_class_suggestion) | |||
13717 | << getRedeclDiagFromTagKind(Redecl->getTagKind()) | |||
13718 | << FixItHint::CreateReplacement(SourceRange(NewTagLoc), | |||
13719 | TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); | |||
13720 | } | |||
13721 | ||||
13722 | return true; | |||
13723 | } | |||
13724 | return false; | |||
13725 | } | |||
13726 | ||||
13727 | /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name | |||
13728 | /// from an outer enclosing namespace or file scope inside a friend declaration. | |||
13729 | /// This should provide the commented out code in the following snippet: | |||
13730 | /// namespace N { | |||
13731 | /// struct X; | |||
13732 | /// namespace M { | |||
13733 | /// struct Y { friend struct /*N::*/ X; }; | |||
13734 | /// } | |||
13735 | /// } | |||
13736 | static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, | |||
13737 | SourceLocation NameLoc) { | |||
13738 | // While the decl is in a namespace, do repeated lookup of that name and see | |||
13739 | // if we get the same namespace back. If we do not, continue until | |||
13740 | // translation unit scope, at which point we have a fully qualified NNS. | |||
13741 | SmallVector<IdentifierInfo *, 4> Namespaces; | |||
13742 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | |||
13743 | for (; !DC->isTranslationUnit(); DC = DC->getParent()) { | |||
13744 | // This tag should be declared in a namespace, which can only be enclosed by | |||
13745 | // other namespaces. Bail if there's an anonymous namespace in the chain. | |||
13746 | NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); | |||
13747 | if (!Namespace || Namespace->isAnonymousNamespace()) | |||
13748 | return FixItHint(); | |||
13749 | IdentifierInfo *II = Namespace->getIdentifier(); | |||
13750 | Namespaces.push_back(II); | |||
13751 | NamedDecl *Lookup = SemaRef.LookupSingleName( | |||
13752 | S, II, NameLoc, Sema::LookupNestedNameSpecifierName); | |||
13753 | if (Lookup == Namespace) | |||
13754 | break; | |||
13755 | } | |||
13756 | ||||
13757 | // Once we have all the namespaces, reverse them to go outermost first, and | |||
13758 | // build an NNS. | |||
13759 | SmallString<64> Insertion; | |||
13760 | llvm::raw_svector_ostream OS(Insertion); | |||
13761 | if (DC->isTranslationUnit()) | |||
13762 | OS << "::"; | |||
13763 | std::reverse(Namespaces.begin(), Namespaces.end()); | |||
13764 | for (auto *II : Namespaces) | |||
13765 | OS << II->getName() << "::"; | |||
13766 | return FixItHint::CreateInsertion(NameLoc, Insertion); | |||
13767 | } | |||
13768 | ||||
13769 | /// Determine whether a tag originally declared in context \p OldDC can | |||
13770 | /// be redeclared with an unqualified name in \p NewDC (assuming name lookup | |||
13771 | /// found a declaration in \p OldDC as a previous decl, perhaps through a | |||
13772 | /// using-declaration). | |||
13773 | static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, | |||
13774 | DeclContext *NewDC) { | |||
13775 | OldDC = OldDC->getRedeclContext(); | |||
13776 | NewDC = NewDC->getRedeclContext(); | |||
13777 | ||||
13778 | if (OldDC->Equals(NewDC)) | |||
13779 | return true; | |||
13780 | ||||
13781 | // In MSVC mode, we allow a redeclaration if the contexts are related (either | |||
13782 | // encloses the other). | |||
13783 | if (S.getLangOpts().MSVCCompat && | |||
13784 | (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) | |||
13785 | return true; | |||
13786 | ||||
13787 | return false; | |||
13788 | } | |||
13789 | ||||
13790 | /// This is invoked when we see 'struct foo' or 'struct {'. In the | |||
13791 | /// former case, Name will be non-null. In the later case, Name will be null. | |||
13792 | /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a | |||
13793 | /// reference/declaration/definition of a tag. | |||
13794 | /// | |||
13795 | /// \param IsTypeSpecifier \c true if this is a type-specifier (or | |||
13796 | /// trailing-type-specifier) other than one in an alias-declaration. | |||
13797 | /// | |||
13798 | /// \param SkipBody If non-null, will be set to indicate if the caller should | |||
13799 | /// skip the definition of this tag and treat it as if it were a declaration. | |||
13800 | Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, | |||
13801 | SourceLocation KWLoc, CXXScopeSpec &SS, | |||
13802 | IdentifierInfo *Name, SourceLocation NameLoc, | |||
13803 | const ParsedAttributesView &Attrs, AccessSpecifier AS, | |||
13804 | SourceLocation ModulePrivateLoc, | |||
13805 | MultiTemplateParamsArg TemplateParameterLists, | |||
13806 | bool &OwnedDecl, bool &IsDependent, | |||
13807 | SourceLocation ScopedEnumKWLoc, | |||
13808 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, | |||
13809 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, | |||
13810 | SkipBodyInfo *SkipBody) { | |||
13811 | // If this is not a definition, it must have a name. | |||
13812 | IdentifierInfo *OrigName = Name; | |||
13813 | assert((Name != nullptr || TUK == TUK_Definition) &&(static_cast <bool> ((Name != nullptr || TUK == TUK_Definition ) && "Nameless record must be a definition!") ? void ( 0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13814, __extension__ __PRETTY_FUNCTION__)) | |||
13814 | "Nameless record must be a definition!")(static_cast <bool> ((Name != nullptr || TUK == TUK_Definition ) && "Nameless record must be a definition!") ? void ( 0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13814, __extension__ __PRETTY_FUNCTION__)); | |||
13815 | assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)(static_cast <bool> (TemplateParameterLists.size() == 0 || TUK != TUK_Reference) ? void (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13815, __extension__ __PRETTY_FUNCTION__)); | |||
13816 | ||||
13817 | OwnedDecl = false; | |||
13818 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); | |||
13819 | bool ScopedEnum = ScopedEnumKWLoc.isValid(); | |||
13820 | ||||
13821 | // FIXME: Check member specializations more carefully. | |||
13822 | bool isMemberSpecialization = false; | |||
13823 | bool Invalid = false; | |||
13824 | ||||
13825 | // We only need to do this matching if we have template parameters | |||
13826 | // or a scope specifier, which also conveniently avoids this work | |||
13827 | // for non-C++ cases. | |||
13828 | if (TemplateParameterLists.size() > 0 || | |||
13829 | (SS.isNotEmpty() && TUK != TUK_Reference)) { | |||
13830 | if (TemplateParameterList *TemplateParams = | |||
13831 | MatchTemplateParametersToScopeSpecifier( | |||
13832 | KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, | |||
13833 | TUK == TUK_Friend, isMemberSpecialization, Invalid)) { | |||
13834 | if (Kind == TTK_Enum) { | |||
13835 | Diag(KWLoc, diag::err_enum_template); | |||
13836 | return nullptr; | |||
13837 | } | |||
13838 | ||||
13839 | if (TemplateParams->size() > 0) { | |||
13840 | // This is a declaration or definition of a class template (which may | |||
13841 | // be a member of another template). | |||
13842 | ||||
13843 | if (Invalid) | |||
13844 | return nullptr; | |||
13845 | ||||
13846 | OwnedDecl = false; | |||
13847 | DeclResult Result = CheckClassTemplate( | |||
13848 | S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, | |||
13849 | AS, ModulePrivateLoc, | |||
13850 | /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, | |||
13851 | TemplateParameterLists.data(), SkipBody); | |||
13852 | return Result.get(); | |||
13853 | } else { | |||
13854 | // The "template<>" header is extraneous. | |||
13855 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) | |||
13856 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; | |||
13857 | isMemberSpecialization = true; | |||
13858 | } | |||
13859 | } | |||
13860 | } | |||
13861 | ||||
13862 | // Figure out the underlying type if this a enum declaration. We need to do | |||
13863 | // this early, because it's needed to detect if this is an incompatible | |||
13864 | // redeclaration. | |||
13865 | llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; | |||
13866 | bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; | |||
13867 | ||||
13868 | if (Kind == TTK_Enum) { | |||
13869 | if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { | |||
13870 | // No underlying type explicitly specified, or we failed to parse the | |||
13871 | // type, default to int. | |||
13872 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
13873 | } else if (UnderlyingType.get()) { | |||
13874 | // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an | |||
13875 | // integral type; any cv-qualification is ignored. | |||
13876 | TypeSourceInfo *TI = nullptr; | |||
13877 | GetTypeFromParser(UnderlyingType.get(), &TI); | |||
13878 | EnumUnderlying = TI; | |||
13879 | ||||
13880 | if (CheckEnumUnderlyingType(TI)) | |||
13881 | // Recover by falling back to int. | |||
13882 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
13883 | ||||
13884 | if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, | |||
13885 | UPPC_FixedUnderlyingType)) | |||
13886 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
13887 | ||||
13888 | } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
13889 | // For MSVC ABI compatibility, unfixed enums must use an underlying type | |||
13890 | // of 'int'. However, if this is an unfixed forward declaration, don't set | |||
13891 | // the underlying type unless the user enables -fms-compatibility. This | |||
13892 | // makes unfixed forward declared enums incomplete and is more conforming. | |||
13893 | if (TUK == TUK_Definition || getLangOpts().MSVCCompat) | |||
13894 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
13895 | } | |||
13896 | } | |||
13897 | ||||
13898 | DeclContext *SearchDC = CurContext; | |||
13899 | DeclContext *DC = CurContext; | |||
13900 | bool isStdBadAlloc = false; | |||
13901 | bool isStdAlignValT = false; | |||
13902 | ||||
13903 | RedeclarationKind Redecl = forRedeclarationInCurContext(); | |||
13904 | if (TUK == TUK_Friend || TUK == TUK_Reference) | |||
13905 | Redecl = NotForRedeclaration; | |||
13906 | ||||
13907 | /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C | |||
13908 | /// implemented asks for structural equivalence checking, the returned decl | |||
13909 | /// here is passed back to the parser, allowing the tag body to be parsed. | |||
13910 | auto createTagFromNewDecl = [&]() -> TagDecl * { | |||
13911 | assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")(static_cast <bool> (!getLangOpts().CPlusPlus && "not meant for C++ usage") ? void (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 13911, __extension__ __PRETTY_FUNCTION__)); | |||
13912 | // If there is an identifier, use the location of the identifier as the | |||
13913 | // location of the decl, otherwise use the location of the struct/union | |||
13914 | // keyword. | |||
13915 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | |||
13916 | TagDecl *New = nullptr; | |||
13917 | ||||
13918 | if (Kind == TTK_Enum) { | |||
13919 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, | |||
13920 | ScopedEnum, ScopedEnumUsesClassTag, IsFixed); | |||
13921 | // If this is an undefined enum, bail. | |||
13922 | if (TUK != TUK_Definition && !Invalid) | |||
13923 | return nullptr; | |||
13924 | if (EnumUnderlying) { | |||
13925 | EnumDecl *ED = cast<EnumDecl>(New); | |||
13926 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) | |||
13927 | ED->setIntegerTypeSourceInfo(TI); | |||
13928 | else | |||
13929 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); | |||
13930 | ED->setPromotionType(ED->getIntegerType()); | |||
13931 | } | |||
13932 | } else { // struct/union | |||
13933 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | |||
13934 | nullptr); | |||
13935 | } | |||
13936 | ||||
13937 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | |||
13938 | // Add alignment attributes if necessary; these attributes are checked | |||
13939 | // when the ASTContext lays out the structure. | |||
13940 | // | |||
13941 | // It is important for implementing the correct semantics that this | |||
13942 | // happen here (in ActOnTag). The #pragma pack stack is | |||
13943 | // maintained as a result of parser callbacks which can occur at | |||
13944 | // many points during the parsing of a struct declaration (because | |||
13945 | // the #pragma tokens are effectively skipped over during the | |||
13946 | // parsing of the struct). | |||
13947 | if (TUK == TUK_Definition) { | |||
13948 | AddAlignmentAttributesForRecord(RD); | |||
13949 | AddMsStructLayoutForRecord(RD); | |||
13950 | } | |||
13951 | } | |||
13952 | New->setLexicalDeclContext(CurContext); | |||
13953 | return New; | |||
13954 | }; | |||
13955 | ||||
13956 | LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); | |||
13957 | if (Name && SS.isNotEmpty()) { | |||
13958 | // We have a nested-name tag ('struct foo::bar'). | |||
13959 | ||||
13960 | // Check for invalid 'foo::'. | |||
13961 | if (SS.isInvalid()) { | |||
13962 | Name = nullptr; | |||
13963 | goto CreateNewDecl; | |||
13964 | } | |||
13965 | ||||
13966 | // If this is a friend or a reference to a class in a dependent | |||
13967 | // context, don't try to make a decl for it. | |||
13968 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | |||
13969 | DC = computeDeclContext(SS, false); | |||
13970 | if (!DC) { | |||
13971 | IsDependent = true; | |||
13972 | return nullptr; | |||
13973 | } | |||
13974 | } else { | |||
13975 | DC = computeDeclContext(SS, true); | |||
13976 | if (!DC) { | |||
13977 | Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) | |||
13978 | << SS.getRange(); | |||
13979 | return nullptr; | |||
13980 | } | |||
13981 | } | |||
13982 | ||||
13983 | if (RequireCompleteDeclContext(SS, DC)) | |||
13984 | return nullptr; | |||
13985 | ||||
13986 | SearchDC = DC; | |||
13987 | // Look-up name inside 'foo::'. | |||
13988 | LookupQualifiedName(Previous, DC); | |||
13989 | ||||
13990 | if (Previous.isAmbiguous()) | |||
13991 | return nullptr; | |||
13992 | ||||
13993 | if (Previous.empty()) { | |||
13994 | // Name lookup did not find anything. However, if the | |||
13995 | // nested-name-specifier refers to the current instantiation, | |||
13996 | // and that current instantiation has any dependent base | |||
13997 | // classes, we might find something at instantiation time: treat | |||
13998 | // this as a dependent elaborated-type-specifier. | |||
13999 | // But this only makes any sense for reference-like lookups. | |||
14000 | if (Previous.wasNotFoundInCurrentInstantiation() && | |||
14001 | (TUK == TUK_Reference || TUK == TUK_Friend)) { | |||
14002 | IsDependent = true; | |||
14003 | return nullptr; | |||
14004 | } | |||
14005 | ||||
14006 | // A tag 'foo::bar' must already exist. | |||
14007 | Diag(NameLoc, diag::err_not_tag_in_scope) | |||
14008 | << Kind << Name << DC << SS.getRange(); | |||
14009 | Name = nullptr; | |||
14010 | Invalid = true; | |||
14011 | goto CreateNewDecl; | |||
14012 | } | |||
14013 | } else if (Name) { | |||
14014 | // C++14 [class.mem]p14: | |||
14015 | // If T is the name of a class, then each of the following shall have a | |||
14016 | // name different from T: | |||
14017 | // -- every member of class T that is itself a type | |||
14018 | if (TUK != TUK_Reference && TUK != TUK_Friend && | |||
14019 | DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) | |||
14020 | return nullptr; | |||
14021 | ||||
14022 | // If this is a named struct, check to see if there was a previous forward | |||
14023 | // declaration or definition. | |||
14024 | // FIXME: We're looking into outer scopes here, even when we | |||
14025 | // shouldn't be. Doing so can result in ambiguities that we | |||
14026 | // shouldn't be diagnosing. | |||
14027 | LookupName(Previous, S); | |||
14028 | ||||
14029 | // When declaring or defining a tag, ignore ambiguities introduced | |||
14030 | // by types using'ed into this scope. | |||
14031 | if (Previous.isAmbiguous() && | |||
14032 | (TUK == TUK_Definition || TUK == TUK_Declaration)) { | |||
14033 | LookupResult::Filter F = Previous.makeFilter(); | |||
14034 | while (F.hasNext()) { | |||
14035 | NamedDecl *ND = F.next(); | |||
14036 | if (!ND->getDeclContext()->getRedeclContext()->Equals( | |||
14037 | SearchDC->getRedeclContext())) | |||
14038 | F.erase(); | |||
14039 | } | |||
14040 | F.done(); | |||
14041 | } | |||
14042 | ||||
14043 | // C++11 [namespace.memdef]p3: | |||
14044 | // If the name in a friend declaration is neither qualified nor | |||
14045 | // a template-id and the declaration is a function or an | |||
14046 | // elaborated-type-specifier, the lookup to determine whether | |||
14047 | // the entity has been previously declared shall not consider | |||
14048 | // any scopes outside the innermost enclosing namespace. | |||
14049 | // | |||
14050 | // MSVC doesn't implement the above rule for types, so a friend tag | |||
14051 | // declaration may be a redeclaration of a type declared in an enclosing | |||
14052 | // scope. They do implement this rule for friend functions. | |||
14053 | // | |||
14054 | // Does it matter that this should be by scope instead of by | |||
14055 | // semantic context? | |||
14056 | if (!Previous.empty() && TUK == TUK_Friend) { | |||
14057 | DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); | |||
14058 | LookupResult::Filter F = Previous.makeFilter(); | |||
14059 | bool FriendSawTagOutsideEnclosingNamespace = false; | |||
14060 | while (F.hasNext()) { | |||
14061 | NamedDecl *ND = F.next(); | |||
14062 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | |||
14063 | if (DC->isFileContext() && | |||
14064 | !EnclosingNS->Encloses(ND->getDeclContext())) { | |||
14065 | if (getLangOpts().MSVCCompat) | |||
14066 | FriendSawTagOutsideEnclosingNamespace = true; | |||
14067 | else | |||
14068 | F.erase(); | |||
14069 | } | |||
14070 | } | |||
14071 | F.done(); | |||
14072 | ||||
14073 | // Diagnose this MSVC extension in the easy case where lookup would have | |||
14074 | // unambiguously found something outside the enclosing namespace. | |||
14075 | if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { | |||
14076 | NamedDecl *ND = Previous.getFoundDecl(); | |||
14077 | Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) | |||
14078 | << createFriendTagNNSFixIt(*this, ND, S, NameLoc); | |||
14079 | } | |||
14080 | } | |||
14081 | ||||
14082 | // Note: there used to be some attempt at recovery here. | |||
14083 | if (Previous.isAmbiguous()) | |||
14084 | return nullptr; | |||
14085 | ||||
14086 | if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { | |||
14087 | // FIXME: This makes sure that we ignore the contexts associated | |||
14088 | // with C structs, unions, and enums when looking for a matching | |||
14089 | // tag declaration or definition. See the similar lookup tweak | |||
14090 | // in Sema::LookupName; is there a better way to deal with this? | |||
14091 | while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) | |||
14092 | SearchDC = SearchDC->getParent(); | |||
14093 | } | |||
14094 | } | |||
14095 | ||||
14096 | if (Previous.isSingleResult() && | |||
14097 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
14098 | // Maybe we will complain about the shadowed template parameter. | |||
14099 | DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); | |||
14100 | // Just pretend that we didn't see the previous declaration. | |||
14101 | Previous.clear(); | |||
14102 | } | |||
14103 | ||||
14104 | if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && | |||
14105 | DC->Equals(getStdNamespace())) { | |||
14106 | if (Name->isStr("bad_alloc")) { | |||
14107 | // This is a declaration of or a reference to "std::bad_alloc". | |||
14108 | isStdBadAlloc = true; | |||
14109 | ||||
14110 | // If std::bad_alloc has been implicitly declared (but made invisible to | |||
14111 | // name lookup), fill in this implicit declaration as the previous | |||
14112 | // declaration, so that the declarations get chained appropriately. | |||
14113 | if (Previous.empty() && StdBadAlloc) | |||
14114 | Previous.addDecl(getStdBadAlloc()); | |||
14115 | } else if (Name->isStr("align_val_t")) { | |||
14116 | isStdAlignValT = true; | |||
14117 | if (Previous.empty() && StdAlignValT) | |||
14118 | Previous.addDecl(getStdAlignValT()); | |||
14119 | } | |||
14120 | } | |||
14121 | ||||
14122 | // If we didn't find a previous declaration, and this is a reference | |||
14123 | // (or friend reference), move to the correct scope. In C++, we | |||
14124 | // also need to do a redeclaration lookup there, just in case | |||
14125 | // there's a shadow friend decl. | |||
14126 | if (Name && Previous.empty() && | |||
14127 | (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { | |||
14128 | if (Invalid) goto CreateNewDecl; | |||
14129 | assert(SS.isEmpty())(static_cast <bool> (SS.isEmpty()) ? void (0) : __assert_fail ("SS.isEmpty()", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14129, __extension__ __PRETTY_FUNCTION__)); | |||
14130 | ||||
14131 | if (TUK == TUK_Reference || IsTemplateParamOrArg) { | |||
14132 | // C++ [basic.scope.pdecl]p5: | |||
14133 | // -- for an elaborated-type-specifier of the form | |||
14134 | // | |||
14135 | // class-key identifier | |||
14136 | // | |||
14137 | // if the elaborated-type-specifier is used in the | |||
14138 | // decl-specifier-seq or parameter-declaration-clause of a | |||
14139 | // function defined in namespace scope, the identifier is | |||
14140 | // declared as a class-name in the namespace that contains | |||
14141 | // the declaration; otherwise, except as a friend | |||
14142 | // declaration, the identifier is declared in the smallest | |||
14143 | // non-class, non-function-prototype scope that contains the | |||
14144 | // declaration. | |||
14145 | // | |||
14146 | // C99 6.7.2.3p8 has a similar (but not identical!) provision for | |||
14147 | // C structs and unions. | |||
14148 | // | |||
14149 | // It is an error in C++ to declare (rather than define) an enum | |||
14150 | // type, including via an elaborated type specifier. We'll | |||
14151 | // diagnose that later; for now, declare the enum in the same | |||
14152 | // scope as we would have picked for any other tag type. | |||
14153 | // | |||
14154 | // GNU C also supports this behavior as part of its incomplete | |||
14155 | // enum types extension, while GNU C++ does not. | |||
14156 | // | |||
14157 | // Find the context where we'll be declaring the tag. | |||
14158 | // FIXME: We would like to maintain the current DeclContext as the | |||
14159 | // lexical context, | |||
14160 | SearchDC = getTagInjectionContext(SearchDC); | |||
14161 | ||||
14162 | // Find the scope where we'll be declaring the tag. | |||
14163 | S = getTagInjectionScope(S, getLangOpts()); | |||
14164 | } else { | |||
14165 | assert(TUK == TUK_Friend)(static_cast <bool> (TUK == TUK_Friend) ? void (0) : __assert_fail ("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14165, __extension__ __PRETTY_FUNCTION__)); | |||
14166 | // C++ [namespace.memdef]p3: | |||
14167 | // If a friend declaration in a non-local class first declares a | |||
14168 | // class or function, the friend class or function is a member of | |||
14169 | // the innermost enclosing namespace. | |||
14170 | SearchDC = SearchDC->getEnclosingNamespaceContext(); | |||
14171 | } | |||
14172 | ||||
14173 | // In C++, we need to do a redeclaration lookup to properly | |||
14174 | // diagnose some problems. | |||
14175 | // FIXME: redeclaration lookup is also used (with and without C++) to find a | |||
14176 | // hidden declaration so that we don't get ambiguity errors when using a | |||
14177 | // type declared by an elaborated-type-specifier. In C that is not correct | |||
14178 | // and we should instead merge compatible types found by lookup. | |||
14179 | if (getLangOpts().CPlusPlus) { | |||
14180 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | |||
14181 | LookupQualifiedName(Previous, SearchDC); | |||
14182 | } else { | |||
14183 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | |||
14184 | LookupName(Previous, S); | |||
14185 | } | |||
14186 | } | |||
14187 | ||||
14188 | // If we have a known previous declaration to use, then use it. | |||
14189 | if (Previous.empty() && SkipBody && SkipBody->Previous) | |||
14190 | Previous.addDecl(SkipBody->Previous); | |||
14191 | ||||
14192 | if (!Previous.empty()) { | |||
14193 | NamedDecl *PrevDecl = Previous.getFoundDecl(); | |||
14194 | NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); | |||
14195 | ||||
14196 | // It's okay to have a tag decl in the same scope as a typedef | |||
14197 | // which hides a tag decl in the same scope. Finding this | |||
14198 | // insanity with a redeclaration lookup can only actually happen | |||
14199 | // in C++. | |||
14200 | // | |||
14201 | // This is also okay for elaborated-type-specifiers, which is | |||
14202 | // technically forbidden by the current standard but which is | |||
14203 | // okay according to the likely resolution of an open issue; | |||
14204 | // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 | |||
14205 | if (getLangOpts().CPlusPlus) { | |||
14206 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { | |||
14207 | if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { | |||
14208 | TagDecl *Tag = TT->getDecl(); | |||
14209 | if (Tag->getDeclName() == Name && | |||
14210 | Tag->getDeclContext()->getRedeclContext() | |||
14211 | ->Equals(TD->getDeclContext()->getRedeclContext())) { | |||
14212 | PrevDecl = Tag; | |||
14213 | Previous.clear(); | |||
14214 | Previous.addDecl(Tag); | |||
14215 | Previous.resolveKind(); | |||
14216 | } | |||
14217 | } | |||
14218 | } | |||
14219 | } | |||
14220 | ||||
14221 | // If this is a redeclaration of a using shadow declaration, it must | |||
14222 | // declare a tag in the same context. In MSVC mode, we allow a | |||
14223 | // redefinition if either context is within the other. | |||
14224 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { | |||
14225 | auto *OldTag = dyn_cast<TagDecl>(PrevDecl); | |||
14226 | if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && | |||
14227 | isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && | |||
14228 | !(OldTag && isAcceptableTagRedeclContext( | |||
14229 | *this, OldTag->getDeclContext(), SearchDC))) { | |||
14230 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); | |||
14231 | Diag(Shadow->getTargetDecl()->getLocation(), | |||
14232 | diag::note_using_decl_target); | |||
14233 | Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) | |||
14234 | << 0; | |||
14235 | // Recover by ignoring the old declaration. | |||
14236 | Previous.clear(); | |||
14237 | goto CreateNewDecl; | |||
14238 | } | |||
14239 | } | |||
14240 | ||||
14241 | if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { | |||
14242 | // If this is a use of a previous tag, or if the tag is already declared | |||
14243 | // in the same scope (so that the definition/declaration completes or | |||
14244 | // rementions the tag), reuse the decl. | |||
14245 | if (TUK == TUK_Reference || TUK == TUK_Friend || | |||
14246 | isDeclInScope(DirectPrevDecl, SearchDC, S, | |||
14247 | SS.isNotEmpty() || isMemberSpecialization)) { | |||
14248 | // Make sure that this wasn't declared as an enum and now used as a | |||
14249 | // struct or something similar. | |||
14250 | if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, | |||
14251 | TUK == TUK_Definition, KWLoc, | |||
14252 | Name)) { | |||
14253 | bool SafeToContinue | |||
14254 | = (PrevTagDecl->getTagKind() != TTK_Enum && | |||
14255 | Kind != TTK_Enum); | |||
14256 | if (SafeToContinue) | |||
14257 | Diag(KWLoc, diag::err_use_with_wrong_tag) | |||
14258 | << Name | |||
14259 | << FixItHint::CreateReplacement(SourceRange(KWLoc), | |||
14260 | PrevTagDecl->getKindName()); | |||
14261 | else | |||
14262 | Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; | |||
14263 | Diag(PrevTagDecl->getLocation(), diag::note_previous_use); | |||
14264 | ||||
14265 | if (SafeToContinue) | |||
14266 | Kind = PrevTagDecl->getTagKind(); | |||
14267 | else { | |||
14268 | // Recover by making this an anonymous redefinition. | |||
14269 | Name = nullptr; | |||
14270 | Previous.clear(); | |||
14271 | Invalid = true; | |||
14272 | } | |||
14273 | } | |||
14274 | ||||
14275 | if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { | |||
14276 | const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); | |||
14277 | ||||
14278 | // If this is an elaborated-type-specifier for a scoped enumeration, | |||
14279 | // the 'class' keyword is not necessary and not permitted. | |||
14280 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | |||
14281 | if (ScopedEnum) | |||
14282 | Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) | |||
14283 | << PrevEnum->isScoped() | |||
14284 | << FixItHint::CreateRemoval(ScopedEnumKWLoc); | |||
14285 | return PrevTagDecl; | |||
14286 | } | |||
14287 | ||||
14288 | QualType EnumUnderlyingTy; | |||
14289 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | |||
14290 | EnumUnderlyingTy = TI->getType().getUnqualifiedType(); | |||
14291 | else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) | |||
14292 | EnumUnderlyingTy = QualType(T, 0); | |||
14293 | ||||
14294 | // All conflicts with previous declarations are recovered by | |||
14295 | // returning the previous declaration, unless this is a definition, | |||
14296 | // in which case we want the caller to bail out. | |||
14297 | if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, | |||
14298 | ScopedEnum, EnumUnderlyingTy, | |||
14299 | IsFixed, PrevEnum)) | |||
14300 | return TUK == TUK_Declaration ? PrevTagDecl : nullptr; | |||
14301 | } | |||
14302 | ||||
14303 | // C++11 [class.mem]p1: | |||
14304 | // A member shall not be declared twice in the member-specification, | |||
14305 | // except that a nested class or member class template can be declared | |||
14306 | // and then later defined. | |||
14307 | if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && | |||
14308 | S->isDeclScope(PrevDecl)) { | |||
14309 | Diag(NameLoc, diag::ext_member_redeclared); | |||
14310 | Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); | |||
14311 | } | |||
14312 | ||||
14313 | if (!Invalid) { | |||
14314 | // If this is a use, just return the declaration we found, unless | |||
14315 | // we have attributes. | |||
14316 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | |||
14317 | if (!Attrs.empty()) { | |||
14318 | // FIXME: Diagnose these attributes. For now, we create a new | |||
14319 | // declaration to hold them. | |||
14320 | } else if (TUK == TUK_Reference && | |||
14321 | (PrevTagDecl->getFriendObjectKind() == | |||
14322 | Decl::FOK_Undeclared || | |||
14323 | PrevDecl->getOwningModule() != getCurrentModule()) && | |||
14324 | SS.isEmpty()) { | |||
14325 | // This declaration is a reference to an existing entity, but | |||
14326 | // has different visibility from that entity: it either makes | |||
14327 | // a friend visible or it makes a type visible in a new module. | |||
14328 | // In either case, create a new declaration. We only do this if | |||
14329 | // the declaration would have meant the same thing if no prior | |||
14330 | // declaration were found, that is, if it was found in the same | |||
14331 | // scope where we would have injected a declaration. | |||
14332 | if (!getTagInjectionContext(CurContext)->getRedeclContext() | |||
14333 | ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) | |||
14334 | return PrevTagDecl; | |||
14335 | // This is in the injected scope, create a new declaration in | |||
14336 | // that scope. | |||
14337 | S = getTagInjectionScope(S, getLangOpts()); | |||
14338 | } else { | |||
14339 | return PrevTagDecl; | |||
14340 | } | |||
14341 | } | |||
14342 | ||||
14343 | // Diagnose attempts to redefine a tag. | |||
14344 | if (TUK == TUK_Definition) { | |||
14345 | if (NamedDecl *Def = PrevTagDecl->getDefinition()) { | |||
14346 | // If we're defining a specialization and the previous definition | |||
14347 | // is from an implicit instantiation, don't emit an error | |||
14348 | // here; we'll catch this in the general case below. | |||
14349 | bool IsExplicitSpecializationAfterInstantiation = false; | |||
14350 | if (isMemberSpecialization) { | |||
14351 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) | |||
14352 | IsExplicitSpecializationAfterInstantiation = | |||
14353 | RD->getTemplateSpecializationKind() != | |||
14354 | TSK_ExplicitSpecialization; | |||
14355 | else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) | |||
14356 | IsExplicitSpecializationAfterInstantiation = | |||
14357 | ED->getTemplateSpecializationKind() != | |||
14358 | TSK_ExplicitSpecialization; | |||
14359 | } | |||
14360 | ||||
14361 | // Note that clang allows ODR-like semantics for ObjC/C, i.e., do | |||
14362 | // not keep more that one definition around (merge them). However, | |||
14363 | // ensure the decl passes the structural compatibility check in | |||
14364 | // C11 6.2.7/1 (or 6.1.2.6/1 in C89). | |||
14365 | NamedDecl *Hidden = nullptr; | |||
14366 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { | |||
14367 | // There is a definition of this tag, but it is not visible. We | |||
14368 | // explicitly make use of C++'s one definition rule here, and | |||
14369 | // assume that this definition is identical to the hidden one | |||
14370 | // we already have. Make the existing definition visible and | |||
14371 | // use it in place of this one. | |||
14372 | if (!getLangOpts().CPlusPlus) { | |||
14373 | // Postpone making the old definition visible until after we | |||
14374 | // complete parsing the new one and do the structural | |||
14375 | // comparison. | |||
14376 | SkipBody->CheckSameAsPrevious = true; | |||
14377 | SkipBody->New = createTagFromNewDecl(); | |||
14378 | SkipBody->Previous = Hidden; | |||
14379 | } else { | |||
14380 | SkipBody->ShouldSkip = true; | |||
14381 | makeMergedDefinitionVisible(Hidden); | |||
14382 | } | |||
14383 | return Def; | |||
14384 | } else if (!IsExplicitSpecializationAfterInstantiation) { | |||
14385 | // A redeclaration in function prototype scope in C isn't | |||
14386 | // visible elsewhere, so merely issue a warning. | |||
14387 | if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) | |||
14388 | Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; | |||
14389 | else | |||
14390 | Diag(NameLoc, diag::err_redefinition) << Name; | |||
14391 | notePreviousDefinition(Def, | |||
14392 | NameLoc.isValid() ? NameLoc : KWLoc); | |||
14393 | // If this is a redefinition, recover by making this | |||
14394 | // struct be anonymous, which will make any later | |||
14395 | // references get the previous definition. | |||
14396 | Name = nullptr; | |||
14397 | Previous.clear(); | |||
14398 | Invalid = true; | |||
14399 | } | |||
14400 | } else { | |||
14401 | // If the type is currently being defined, complain | |||
14402 | // about a nested redefinition. | |||
14403 | auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); | |||
14404 | if (TD->isBeingDefined()) { | |||
14405 | Diag(NameLoc, diag::err_nested_redefinition) << Name; | |||
14406 | Diag(PrevTagDecl->getLocation(), | |||
14407 | diag::note_previous_definition); | |||
14408 | Name = nullptr; | |||
14409 | Previous.clear(); | |||
14410 | Invalid = true; | |||
14411 | } | |||
14412 | } | |||
14413 | ||||
14414 | // Okay, this is definition of a previously declared or referenced | |||
14415 | // tag. We're going to create a new Decl for it. | |||
14416 | } | |||
14417 | ||||
14418 | // Okay, we're going to make a redeclaration. If this is some kind | |||
14419 | // of reference, make sure we build the redeclaration in the same DC | |||
14420 | // as the original, and ignore the current access specifier. | |||
14421 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | |||
14422 | SearchDC = PrevTagDecl->getDeclContext(); | |||
14423 | AS = AS_none; | |||
14424 | } | |||
14425 | } | |||
14426 | // If we get here we have (another) forward declaration or we | |||
14427 | // have a definition. Just create a new decl. | |||
14428 | ||||
14429 | } else { | |||
14430 | // If we get here, this is a definition of a new tag type in a nested | |||
14431 | // scope, e.g. "struct foo; void bar() { struct foo; }", just create a | |||
14432 | // new decl/type. We set PrevDecl to NULL so that the entities | |||
14433 | // have distinct types. | |||
14434 | Previous.clear(); | |||
14435 | } | |||
14436 | // If we get here, we're going to create a new Decl. If PrevDecl | |||
14437 | // is non-NULL, it's a definition of the tag declared by | |||
14438 | // PrevDecl. If it's NULL, we have a new definition. | |||
14439 | ||||
14440 | // Otherwise, PrevDecl is not a tag, but was found with tag | |||
14441 | // lookup. This is only actually possible in C++, where a few | |||
14442 | // things like templates still live in the tag namespace. | |||
14443 | } else { | |||
14444 | // Use a better diagnostic if an elaborated-type-specifier | |||
14445 | // found the wrong kind of type on the first | |||
14446 | // (non-redeclaration) lookup. | |||
14447 | if ((TUK == TUK_Reference || TUK == TUK_Friend) && | |||
14448 | !Previous.isForRedeclaration()) { | |||
14449 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | |||
14450 | Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK | |||
14451 | << Kind; | |||
14452 | Diag(PrevDecl->getLocation(), diag::note_declared_at); | |||
14453 | Invalid = true; | |||
14454 | ||||
14455 | // Otherwise, only diagnose if the declaration is in scope. | |||
14456 | } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, | |||
14457 | SS.isNotEmpty() || isMemberSpecialization)) { | |||
14458 | // do nothing | |||
14459 | ||||
14460 | // Diagnose implicit declarations introduced by elaborated types. | |||
14461 | } else if (TUK == TUK_Reference || TUK == TUK_Friend) { | |||
14462 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | |||
14463 | Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; | |||
14464 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | |||
14465 | Invalid = true; | |||
14466 | ||||
14467 | // Otherwise it's a declaration. Call out a particularly common | |||
14468 | // case here. | |||
14469 | } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { | |||
14470 | unsigned Kind = 0; | |||
14471 | if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; | |||
14472 | Diag(NameLoc, diag::err_tag_definition_of_typedef) | |||
14473 | << Name << Kind << TND->getUnderlyingType(); | |||
14474 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | |||
14475 | Invalid = true; | |||
14476 | ||||
14477 | // Otherwise, diagnose. | |||
14478 | } else { | |||
14479 | // The tag name clashes with something else in the target scope, | |||
14480 | // issue an error and recover by making this tag be anonymous. | |||
14481 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; | |||
14482 | notePreviousDefinition(PrevDecl, NameLoc); | |||
14483 | Name = nullptr; | |||
14484 | Invalid = true; | |||
14485 | } | |||
14486 | ||||
14487 | // The existing declaration isn't relevant to us; we're in a | |||
14488 | // new scope, so clear out the previous declaration. | |||
14489 | Previous.clear(); | |||
14490 | } | |||
14491 | } | |||
14492 | ||||
14493 | CreateNewDecl: | |||
14494 | ||||
14495 | TagDecl *PrevDecl = nullptr; | |||
14496 | if (Previous.isSingleResult()) | |||
14497 | PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); | |||
14498 | ||||
14499 | // If there is an identifier, use the location of the identifier as the | |||
14500 | // location of the decl, otherwise use the location of the struct/union | |||
14501 | // keyword. | |||
14502 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | |||
14503 | ||||
14504 | // Otherwise, create a new declaration. If there is a previous | |||
14505 | // declaration of the same entity, the two will be linked via | |||
14506 | // PrevDecl. | |||
14507 | TagDecl *New; | |||
14508 | ||||
14509 | if (Kind == TTK_Enum) { | |||
14510 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | |||
14511 | // enum X { A, B, C } D; D should chain to X. | |||
14512 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, | |||
14513 | cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, | |||
14514 | ScopedEnumUsesClassTag, IsFixed); | |||
14515 | ||||
14516 | if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) | |||
14517 | StdAlignValT = cast<EnumDecl>(New); | |||
14518 | ||||
14519 | // If this is an undefined enum, warn. | |||
14520 | if (TUK != TUK_Definition && !Invalid) { | |||
14521 | TagDecl *Def; | |||
14522 | if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && | |||
14523 | cast<EnumDecl>(New)->isFixed()) { | |||
14524 | // C++0x: 7.2p2: opaque-enum-declaration. | |||
14525 | // Conflicts are diagnosed above. Do nothing. | |||
14526 | } | |||
14527 | else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { | |||
14528 | Diag(Loc, diag::ext_forward_ref_enum_def) | |||
14529 | << New; | |||
14530 | Diag(Def->getLocation(), diag::note_previous_definition); | |||
14531 | } else { | |||
14532 | unsigned DiagID = diag::ext_forward_ref_enum; | |||
14533 | if (getLangOpts().MSVCCompat) | |||
14534 | DiagID = diag::ext_ms_forward_ref_enum; | |||
14535 | else if (getLangOpts().CPlusPlus) | |||
14536 | DiagID = diag::err_forward_ref_enum; | |||
14537 | Diag(Loc, DiagID); | |||
14538 | } | |||
14539 | } | |||
14540 | ||||
14541 | if (EnumUnderlying) { | |||
14542 | EnumDecl *ED = cast<EnumDecl>(New); | |||
14543 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | |||
14544 | ED->setIntegerTypeSourceInfo(TI); | |||
14545 | else | |||
14546 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); | |||
14547 | ED->setPromotionType(ED->getIntegerType()); | |||
14548 | assert(ED->isComplete() && "enum with type should be complete")(static_cast <bool> (ED->isComplete() && "enum with type should be complete" ) ? void (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14548, __extension__ __PRETTY_FUNCTION__)); | |||
14549 | } | |||
14550 | } else { | |||
14551 | // struct/union/class | |||
14552 | ||||
14553 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | |||
14554 | // struct X { int A; } D; D should chain to X. | |||
14555 | if (getLangOpts().CPlusPlus) { | |||
14556 | // FIXME: Look for a way to use RecordDecl for simple structs. | |||
14557 | New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | |||
14558 | cast_or_null<CXXRecordDecl>(PrevDecl)); | |||
14559 | ||||
14560 | if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) | |||
14561 | StdBadAlloc = cast<CXXRecordDecl>(New); | |||
14562 | } else | |||
14563 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | |||
14564 | cast_or_null<RecordDecl>(PrevDecl)); | |||
14565 | } | |||
14566 | ||||
14567 | // C++11 [dcl.type]p3: | |||
14568 | // A type-specifier-seq shall not define a class or enumeration [...]. | |||
14569 | if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && | |||
14570 | TUK == TUK_Definition) { | |||
14571 | Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) | |||
14572 | << Context.getTagDeclType(New); | |||
14573 | Invalid = true; | |||
14574 | } | |||
14575 | ||||
14576 | if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && | |||
14577 | DC->getDeclKind() == Decl::Enum) { | |||
14578 | Diag(New->getLocation(), diag::err_type_defined_in_enum) | |||
14579 | << Context.getTagDeclType(New); | |||
14580 | Invalid = true; | |||
14581 | } | |||
14582 | ||||
14583 | // Maybe add qualifier info. | |||
14584 | if (SS.isNotEmpty()) { | |||
14585 | if (SS.isSet()) { | |||
14586 | // If this is either a declaration or a definition, check the | |||
14587 | // nested-name-specifier against the current context. | |||
14588 | if ((TUK == TUK_Definition || TUK == TUK_Declaration) && | |||
14589 | diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, | |||
14590 | isMemberSpecialization)) | |||
14591 | Invalid = true; | |||
14592 | ||||
14593 | New->setQualifierInfo(SS.getWithLocInContext(Context)); | |||
14594 | if (TemplateParameterLists.size() > 0) { | |||
14595 | New->setTemplateParameterListsInfo(Context, TemplateParameterLists); | |||
14596 | } | |||
14597 | } | |||
14598 | else | |||
14599 | Invalid = true; | |||
14600 | } | |||
14601 | ||||
14602 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | |||
14603 | // Add alignment attributes if necessary; these attributes are checked when | |||
14604 | // the ASTContext lays out the structure. | |||
14605 | // | |||
14606 | // It is important for implementing the correct semantics that this | |||
14607 | // happen here (in ActOnTag). The #pragma pack stack is | |||
14608 | // maintained as a result of parser callbacks which can occur at | |||
14609 | // many points during the parsing of a struct declaration (because | |||
14610 | // the #pragma tokens are effectively skipped over during the | |||
14611 | // parsing of the struct). | |||
14612 | if (TUK == TUK_Definition) { | |||
14613 | AddAlignmentAttributesForRecord(RD); | |||
14614 | AddMsStructLayoutForRecord(RD); | |||
14615 | } | |||
14616 | } | |||
14617 | ||||
14618 | if (ModulePrivateLoc.isValid()) { | |||
14619 | if (isMemberSpecialization) | |||
14620 | Diag(New->getLocation(), diag::err_module_private_specialization) | |||
14621 | << 2 | |||
14622 | << FixItHint::CreateRemoval(ModulePrivateLoc); | |||
14623 | // __module_private__ does not apply to local classes. However, we only | |||
14624 | // diagnose this as an error when the declaration specifiers are | |||
14625 | // freestanding. Here, we just ignore the __module_private__. | |||
14626 | else if (!SearchDC->isFunctionOrMethod()) | |||
14627 | New->setModulePrivate(); | |||
14628 | } | |||
14629 | ||||
14630 | // If this is a specialization of a member class (of a class template), | |||
14631 | // check the specialization. | |||
14632 | if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) | |||
14633 | Invalid = true; | |||
14634 | ||||
14635 | // If we're declaring or defining a tag in function prototype scope in C, | |||
14636 | // note that this type can only be used within the function and add it to | |||
14637 | // the list of decls to inject into the function definition scope. | |||
14638 | if ((Name || Kind == TTK_Enum) && | |||
14639 | getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { | |||
14640 | if (getLangOpts().CPlusPlus) { | |||
14641 | // C++ [dcl.fct]p6: | |||
14642 | // Types shall not be defined in return or parameter types. | |||
14643 | if (TUK == TUK_Definition && !IsTypeSpecifier) { | |||
14644 | Diag(Loc, diag::err_type_defined_in_param_type) | |||
14645 | << Name; | |||
14646 | Invalid = true; | |||
14647 | } | |||
14648 | } else if (!PrevDecl) { | |||
14649 | Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); | |||
14650 | } | |||
14651 | } | |||
14652 | ||||
14653 | if (Invalid) | |||
14654 | New->setInvalidDecl(); | |||
14655 | ||||
14656 | // Set the lexical context. If the tag has a C++ scope specifier, the | |||
14657 | // lexical context will be different from the semantic context. | |||
14658 | New->setLexicalDeclContext(CurContext); | |||
14659 | ||||
14660 | // Mark this as a friend decl if applicable. | |||
14661 | // In Microsoft mode, a friend declaration also acts as a forward | |||
14662 | // declaration so we always pass true to setObjectOfFriendDecl to make | |||
14663 | // the tag name visible. | |||
14664 | if (TUK == TUK_Friend) | |||
14665 | New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); | |||
14666 | ||||
14667 | // Set the access specifier. | |||
14668 | if (!Invalid && SearchDC->isRecord()) | |||
14669 | SetMemberAccessSpecifier(New, PrevDecl, AS); | |||
14670 | ||||
14671 | if (PrevDecl) | |||
14672 | CheckRedeclarationModuleOwnership(New, PrevDecl); | |||
14673 | ||||
14674 | if (TUK == TUK_Definition) | |||
14675 | New->startDefinition(); | |||
14676 | ||||
14677 | ProcessDeclAttributeList(S, New, Attrs); | |||
14678 | AddPragmaAttributes(S, New); | |||
14679 | ||||
14680 | // If this has an identifier, add it to the scope stack. | |||
14681 | if (TUK == TUK_Friend) { | |||
14682 | // We might be replacing an existing declaration in the lookup tables; | |||
14683 | // if so, borrow its access specifier. | |||
14684 | if (PrevDecl) | |||
14685 | New->setAccess(PrevDecl->getAccess()); | |||
14686 | ||||
14687 | DeclContext *DC = New->getDeclContext()->getRedeclContext(); | |||
14688 | DC->makeDeclVisibleInContext(New); | |||
14689 | if (Name) // can be null along some error paths | |||
14690 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) | |||
14691 | PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); | |||
14692 | } else if (Name) { | |||
14693 | S = getNonFieldDeclScope(S); | |||
14694 | PushOnScopeChains(New, S, true); | |||
14695 | } else { | |||
14696 | CurContext->addDecl(New); | |||
14697 | } | |||
14698 | ||||
14699 | // If this is the C FILE type, notify the AST context. | |||
14700 | if (IdentifierInfo *II = New->getIdentifier()) | |||
14701 | if (!New->isInvalidDecl() && | |||
14702 | New->getDeclContext()->getRedeclContext()->isTranslationUnit() && | |||
14703 | II->isStr("FILE")) | |||
14704 | Context.setFILEDecl(New); | |||
14705 | ||||
14706 | if (PrevDecl) | |||
14707 | mergeDeclAttributes(New, PrevDecl); | |||
14708 | ||||
14709 | // If there's a #pragma GCC visibility in scope, set the visibility of this | |||
14710 | // record. | |||
14711 | AddPushedVisibilityAttribute(New); | |||
14712 | ||||
14713 | if (isMemberSpecialization && !New->isInvalidDecl()) | |||
14714 | CompleteMemberSpecialization(New, Previous); | |||
14715 | ||||
14716 | OwnedDecl = true; | |||
14717 | // In C++, don't return an invalid declaration. We can't recover well from | |||
14718 | // the cases where we make the type anonymous. | |||
14719 | if (Invalid && getLangOpts().CPlusPlus) { | |||
14720 | if (New->isBeingDefined()) | |||
14721 | if (auto RD = dyn_cast<RecordDecl>(New)) | |||
14722 | RD->completeDefinition(); | |||
14723 | return nullptr; | |||
14724 | } else { | |||
14725 | return New; | |||
14726 | } | |||
14727 | } | |||
14728 | ||||
14729 | void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { | |||
14730 | AdjustDeclIfTemplate(TagD); | |||
14731 | TagDecl *Tag = cast<TagDecl>(TagD); | |||
14732 | ||||
14733 | // Enter the tag context. | |||
14734 | PushDeclContext(S, Tag); | |||
14735 | ||||
14736 | ActOnDocumentableDecl(TagD); | |||
14737 | ||||
14738 | // If there's a #pragma GCC visibility in scope, set the visibility of this | |||
14739 | // record. | |||
14740 | AddPushedVisibilityAttribute(Tag); | |||
14741 | } | |||
14742 | ||||
14743 | bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, | |||
14744 | SkipBodyInfo &SkipBody) { | |||
14745 | if (!hasStructuralCompatLayout(Prev, SkipBody.New)) | |||
14746 | return false; | |||
14747 | ||||
14748 | // Make the previous decl visible. | |||
14749 | makeMergedDefinitionVisible(SkipBody.Previous); | |||
14750 | return true; | |||
14751 | } | |||
14752 | ||||
14753 | Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { | |||
14754 | assert(isa<ObjCContainerDecl>(IDecl) &&(static_cast <bool> (isa<ObjCContainerDecl>(IDecl ) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? void (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14755, __extension__ __PRETTY_FUNCTION__)) | |||
14755 | "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")(static_cast <bool> (isa<ObjCContainerDecl>(IDecl ) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? void (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14755, __extension__ __PRETTY_FUNCTION__)); | |||
14756 | DeclContext *OCD = cast<DeclContext>(IDecl); | |||
14757 | assert(getContainingDC(OCD) == CurContext &&(static_cast <bool> (getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14758, __extension__ __PRETTY_FUNCTION__)) | |||
14758 | "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14758, __extension__ __PRETTY_FUNCTION__)); | |||
14759 | CurContext = OCD; | |||
14760 | return IDecl; | |||
14761 | } | |||
14762 | ||||
14763 | void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, | |||
14764 | SourceLocation FinalLoc, | |||
14765 | bool IsFinalSpelledSealed, | |||
14766 | SourceLocation LBraceLoc) { | |||
14767 | AdjustDeclIfTemplate(TagD); | |||
14768 | CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); | |||
14769 | ||||
14770 | FieldCollector->StartClass(); | |||
14771 | ||||
14772 | if (!Record->getIdentifier()) | |||
14773 | return; | |||
14774 | ||||
14775 | if (FinalLoc.isValid()) | |||
14776 | Record->addAttr(new (Context) | |||
14777 | FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); | |||
14778 | ||||
14779 | // C++ [class]p2: | |||
14780 | // [...] The class-name is also inserted into the scope of the | |||
14781 | // class itself; this is known as the injected-class-name. For | |||
14782 | // purposes of access checking, the injected-class-name is treated | |||
14783 | // as if it were a public member name. | |||
14784 | CXXRecordDecl *InjectedClassName | |||
14785 | = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, | |||
14786 | Record->getLocStart(), Record->getLocation(), | |||
14787 | Record->getIdentifier(), | |||
14788 | /*PrevDecl=*/nullptr, | |||
14789 | /*DelayTypeCreation=*/true); | |||
14790 | Context.getTypeDeclType(InjectedClassName, Record); | |||
14791 | InjectedClassName->setImplicit(); | |||
14792 | InjectedClassName->setAccess(AS_public); | |||
14793 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) | |||
14794 | InjectedClassName->setDescribedClassTemplate(Template); | |||
14795 | PushOnScopeChains(InjectedClassName, S); | |||
14796 | assert(InjectedClassName->isInjectedClassName() &&(static_cast <bool> (InjectedClassName->isInjectedClassName () && "Broken injected-class-name") ? void (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14797, __extension__ __PRETTY_FUNCTION__)) | |||
14797 | "Broken injected-class-name")(static_cast <bool> (InjectedClassName->isInjectedClassName () && "Broken injected-class-name") ? void (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14797, __extension__ __PRETTY_FUNCTION__)); | |||
14798 | } | |||
14799 | ||||
14800 | void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, | |||
14801 | SourceRange BraceRange) { | |||
14802 | AdjustDeclIfTemplate(TagD); | |||
14803 | TagDecl *Tag = cast<TagDecl>(TagD); | |||
14804 | Tag->setBraceRange(BraceRange); | |||
14805 | ||||
14806 | // Make sure we "complete" the definition even it is invalid. | |||
14807 | if (Tag->isBeingDefined()) { | |||
14808 | assert(Tag->isInvalidDecl() && "We should already have completed it")(static_cast <bool> (Tag->isInvalidDecl() && "We should already have completed it") ? void (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14808, __extension__ __PRETTY_FUNCTION__)); | |||
14809 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | |||
14810 | RD->completeDefinition(); | |||
14811 | } | |||
14812 | ||||
14813 | if (isa<CXXRecordDecl>(Tag)) { | |||
14814 | FieldCollector->FinishClass(); | |||
14815 | } | |||
14816 | ||||
14817 | // Exit this scope of this tag's definition. | |||
14818 | PopDeclContext(); | |||
14819 | ||||
14820 | if (getCurLexicalContext()->isObjCContainer() && | |||
14821 | Tag->getDeclContext()->isFileContext()) | |||
14822 | Tag->setTopLevelDeclInObjCContainer(); | |||
14823 | ||||
14824 | // Notify the consumer that we've defined a tag. | |||
14825 | if (!Tag->isInvalidDecl()) | |||
14826 | Consumer.HandleTagDeclDefinition(Tag); | |||
14827 | } | |||
14828 | ||||
14829 | void Sema::ActOnObjCContainerFinishDefinition() { | |||
14830 | // Exit this scope of this interface definition. | |||
14831 | PopDeclContext(); | |||
14832 | } | |||
14833 | ||||
14834 | void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { | |||
14835 | assert(DC == CurContext && "Mismatch of container contexts")(static_cast <bool> (DC == CurContext && "Mismatch of container contexts" ) ? void (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 14835, __extension__ __PRETTY_FUNCTION__)); | |||
14836 | OriginalLexicalContext = DC; | |||
14837 | ActOnObjCContainerFinishDefinition(); | |||
14838 | } | |||
14839 | ||||
14840 | void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { | |||
14841 | ActOnObjCContainerStartDefinition(cast<Decl>(DC)); | |||
14842 | OriginalLexicalContext = nullptr; | |||
14843 | } | |||
14844 | ||||
14845 | void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { | |||
14846 | AdjustDeclIfTemplate(TagD); | |||
14847 | TagDecl *Tag = cast<TagDecl>(TagD); | |||
14848 | Tag->setInvalidDecl(); | |||
14849 | ||||
14850 | // Make sure we "complete" the definition even it is invalid. | |||
14851 | if (Tag->isBeingDefined()) { | |||
14852 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | |||
14853 | RD->completeDefinition(); | |||
14854 | } | |||
14855 | ||||
14856 | // We're undoing ActOnTagStartDefinition here, not | |||
14857 | // ActOnStartCXXMemberDeclarations, so we don't have to mess with | |||
14858 | // the FieldCollector. | |||
14859 | ||||
14860 | PopDeclContext(); | |||
14861 | } | |||
14862 | ||||
14863 | // Note that FieldName may be null for anonymous bitfields. | |||
14864 | ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, | |||
14865 | IdentifierInfo *FieldName, | |||
14866 | QualType FieldTy, bool IsMsStruct, | |||
14867 | Expr *BitWidth, bool *ZeroWidth) { | |||
14868 | // Default to true; that shouldn't confuse checks for emptiness | |||
14869 | if (ZeroWidth) | |||
14870 | *ZeroWidth = true; | |||
14871 | ||||
14872 | // C99 6.7.2.1p4 - verify the field type. | |||
14873 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | |||
14874 | if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { | |||
14875 | // Handle incomplete types with specific error. | |||
14876 | if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) | |||
14877 | return ExprError(); | |||
14878 | if (FieldName) | |||
14879 | return Diag(FieldLoc, diag::err_not_integral_type_bitfield) | |||
14880 | << FieldName << FieldTy << BitWidth->getSourceRange(); | |||
14881 | return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) | |||
14882 | << FieldTy << BitWidth->getSourceRange(); | |||
14883 | } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), | |||
14884 | UPPC_BitFieldWidth)) | |||
14885 | return ExprError(); | |||
14886 | ||||
14887 | // If the bit-width is type- or value-dependent, don't try to check | |||
14888 | // it now. | |||
14889 | if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) | |||
14890 | return BitWidth; | |||
14891 | ||||
14892 | llvm::APSInt Value; | |||
14893 | ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); | |||
14894 | if (ICE.isInvalid()) | |||
14895 | return ICE; | |||
14896 | BitWidth = ICE.get(); | |||
14897 | ||||
14898 | if (Value != 0 && ZeroWidth) | |||
14899 | *ZeroWidth = false; | |||
14900 | ||||
14901 | // Zero-width bitfield is ok for anonymous field. | |||
14902 | if (Value == 0 && FieldName) | |||
14903 | return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; | |||
14904 | ||||
14905 | if (Value.isSigned() && Value.isNegative()) { | |||
14906 | if (FieldName) | |||
14907 | return Diag(FieldLoc, diag::err_bitfield_has_negative_width) | |||
14908 | << FieldName << Value.toString(10); | |||
14909 | return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) | |||
14910 | << Value.toString(10); | |||
14911 | } | |||
14912 | ||||
14913 | if (!FieldTy->isDependentType()) { | |||
14914 | uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); | |||
14915 | uint64_t TypeWidth = Context.getIntWidth(FieldTy); | |||
14916 | bool BitfieldIsOverwide = Value.ugt(TypeWidth); | |||
14917 | ||||
14918 | // Over-wide bitfields are an error in C or when using the MSVC bitfield | |||
14919 | // ABI. | |||
14920 | bool CStdConstraintViolation = | |||
14921 | BitfieldIsOverwide && !getLangOpts().CPlusPlus; | |||
14922 | bool MSBitfieldViolation = | |||
14923 | Value.ugt(TypeStorageSize) && | |||
14924 | (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); | |||
14925 | if (CStdConstraintViolation || MSBitfieldViolation) { | |||
14926 | unsigned DiagWidth = | |||
14927 | CStdConstraintViolation ? TypeWidth : TypeStorageSize; | |||
14928 | if (FieldName) | |||
14929 | return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) | |||
14930 | << FieldName << (unsigned)Value.getZExtValue() | |||
14931 | << !CStdConstraintViolation << DiagWidth; | |||
14932 | ||||
14933 | return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) | |||
14934 | << (unsigned)Value.getZExtValue() << !CStdConstraintViolation | |||
14935 | << DiagWidth; | |||
14936 | } | |||
14937 | ||||
14938 | // Warn on types where the user might conceivably expect to get all | |||
14939 | // specified bits as value bits: that's all integral types other than | |||
14940 | // 'bool'. | |||
14941 | if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { | |||
14942 | if (FieldName) | |||
14943 | Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) | |||
14944 | << FieldName << (unsigned)Value.getZExtValue() | |||
14945 | << (unsigned)TypeWidth; | |||
14946 | else | |||
14947 | Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) | |||
14948 | << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; | |||
14949 | } | |||
14950 | } | |||
14951 | ||||
14952 | return BitWidth; | |||
14953 | } | |||
14954 | ||||
14955 | /// ActOnField - Each field of a C struct/union is passed into this in order | |||
14956 | /// to create a FieldDecl object for it. | |||
14957 | Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, | |||
14958 | Declarator &D, Expr *BitfieldWidth) { | |||
14959 | FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), | |||
14960 | DeclStart, D, static_cast<Expr*>(BitfieldWidth), | |||
14961 | /*InitStyle=*/ICIS_NoInit, AS_public); | |||
14962 | return Res; | |||
14963 | } | |||
14964 | ||||
14965 | /// HandleField - Analyze a field of a C struct or a C++ data member. | |||
14966 | /// | |||
14967 | FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, | |||
14968 | SourceLocation DeclStart, | |||
14969 | Declarator &D, Expr *BitWidth, | |||
14970 | InClassInitStyle InitStyle, | |||
14971 | AccessSpecifier AS) { | |||
14972 | if (D.isDecompositionDeclarator()) { | |||
14973 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); | |||
14974 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) | |||
14975 | << Decomp.getSourceRange(); | |||
14976 | return nullptr; | |||
14977 | } | |||
14978 | ||||
14979 | IdentifierInfo *II = D.getIdentifier(); | |||
14980 | SourceLocation Loc = DeclStart; | |||
14981 | if (II) Loc = D.getIdentifierLoc(); | |||
14982 | ||||
14983 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
14984 | QualType T = TInfo->getType(); | |||
14985 | if (getLangOpts().CPlusPlus) { | |||
14986 | CheckExtraCXXDefaultArguments(D); | |||
14987 | ||||
14988 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
14989 | UPPC_DataMemberType)) { | |||
14990 | D.setInvalidType(); | |||
14991 | T = Context.IntTy; | |||
14992 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
14993 | } | |||
14994 | } | |||
14995 | ||||
14996 | // TR 18037 does not allow fields to be declared with address spaces. | |||
14997 | if (T.getQualifiers().hasAddressSpace() || | |||
14998 | T->isDependentAddressSpaceType() || | |||
14999 | T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { | |||
15000 | Diag(Loc, diag::err_field_with_address_space); | |||
15001 | D.setInvalidType(); | |||
15002 | } | |||
15003 | ||||
15004 | // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be | |||
15005 | // used as structure or union field: image, sampler, event or block types. | |||
15006 | if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || | |||
15007 | T->isSamplerT() || T->isBlockPointerType())) { | |||
15008 | Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; | |||
15009 | D.setInvalidType(); | |||
15010 | } | |||
15011 | ||||
15012 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
15013 | ||||
15014 | if (D.getDeclSpec().isInlineSpecified()) | |||
15015 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
15016 | << getLangOpts().CPlusPlus17; | |||
15017 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | |||
15018 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
15019 | diag::err_invalid_thread) | |||
15020 | << DeclSpec::getSpecifierName(TSCS); | |||
15021 | ||||
15022 | // Check to see if this name was declared as a member previously | |||
15023 | NamedDecl *PrevDecl = nullptr; | |||
15024 | LookupResult Previous(*this, II, Loc, LookupMemberName, | |||
15025 | ForVisibleRedeclaration); | |||
15026 | LookupName(Previous, S); | |||
15027 | switch (Previous.getResultKind()) { | |||
15028 | case LookupResult::Found: | |||
15029 | case LookupResult::FoundUnresolvedValue: | |||
15030 | PrevDecl = Previous.getAsSingle<NamedDecl>(); | |||
15031 | break; | |||
15032 | ||||
15033 | case LookupResult::FoundOverloaded: | |||
15034 | PrevDecl = Previous.getRepresentativeDecl(); | |||
15035 | break; | |||
15036 | ||||
15037 | case LookupResult::NotFound: | |||
15038 | case LookupResult::NotFoundInCurrentInstantiation: | |||
15039 | case LookupResult::Ambiguous: | |||
15040 | break; | |||
15041 | } | |||
15042 | Previous.suppressDiagnostics(); | |||
15043 | ||||
15044 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | |||
15045 | // Maybe we will complain about the shadowed template parameter. | |||
15046 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | |||
15047 | // Just pretend that we didn't see the previous declaration. | |||
15048 | PrevDecl = nullptr; | |||
15049 | } | |||
15050 | ||||
15051 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) | |||
15052 | PrevDecl = nullptr; | |||
15053 | ||||
15054 | bool Mutable | |||
15055 | = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); | |||
15056 | SourceLocation TSSL = D.getLocStart(); | |||
15057 | FieldDecl *NewFD | |||
15058 | = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, | |||
15059 | TSSL, AS, PrevDecl, &D); | |||
15060 | ||||
15061 | if (NewFD->isInvalidDecl()) | |||
15062 | Record->setInvalidDecl(); | |||
15063 | ||||
15064 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
15065 | NewFD->setModulePrivate(); | |||
15066 | ||||
15067 | if (NewFD->isInvalidDecl() && PrevDecl) { | |||
15068 | // Don't introduce NewFD into scope; there's already something | |||
15069 | // with the same name in the same scope. | |||
15070 | } else if (II) { | |||
15071 | PushOnScopeChains(NewFD, S); | |||
15072 | } else | |||
15073 | Record->addDecl(NewFD); | |||
15074 | ||||
15075 | return NewFD; | |||
15076 | } | |||
15077 | ||||
15078 | /// Build a new FieldDecl and check its well-formedness. | |||
15079 | /// | |||
15080 | /// This routine builds a new FieldDecl given the fields name, type, | |||
15081 | /// record, etc. \p PrevDecl should refer to any previous declaration | |||
15082 | /// with the same name and in the same scope as the field to be | |||
15083 | /// created. | |||
15084 | /// | |||
15085 | /// \returns a new FieldDecl. | |||
15086 | /// | |||
15087 | /// \todo The Declarator argument is a hack. It will be removed once | |||
15088 | FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, | |||
15089 | TypeSourceInfo *TInfo, | |||
15090 | RecordDecl *Record, SourceLocation Loc, | |||
15091 | bool Mutable, Expr *BitWidth, | |||
15092 | InClassInitStyle InitStyle, | |||
15093 | SourceLocation TSSL, | |||
15094 | AccessSpecifier AS, NamedDecl *PrevDecl, | |||
15095 | Declarator *D) { | |||
15096 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
15097 | bool InvalidDecl = false; | |||
15098 | if (D) InvalidDecl = D->isInvalidType(); | |||
15099 | ||||
15100 | // If we receive a broken type, recover by assuming 'int' and | |||
15101 | // marking this declaration as invalid. | |||
15102 | if (T.isNull()) { | |||
15103 | InvalidDecl = true; | |||
15104 | T = Context.IntTy; | |||
15105 | } | |||
15106 | ||||
15107 | QualType EltTy = Context.getBaseElementType(T); | |||
15108 | if (!EltTy->isDependentType()) { | |||
15109 | if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { | |||
15110 | // Fields of incomplete type force their record to be invalid. | |||
15111 | Record->setInvalidDecl(); | |||
15112 | InvalidDecl = true; | |||
15113 | } else { | |||
15114 | NamedDecl *Def; | |||
15115 | EltTy->isIncompleteType(&Def); | |||
15116 | if (Def && Def->isInvalidDecl()) { | |||
15117 | Record->setInvalidDecl(); | |||
15118 | InvalidDecl = true; | |||
15119 | } | |||
15120 | } | |||
15121 | } | |||
15122 | ||||
15123 | // OpenCL v1.2 s6.9.c: bitfields are not supported. | |||
15124 | if (BitWidth && getLangOpts().OpenCL) { | |||
15125 | Diag(Loc, diag::err_opencl_bitfields); | |||
15126 | InvalidDecl = true; | |||
15127 | } | |||
15128 | ||||
15129 | // Anonymous bit-fields cannot be cv-qualified (CWG 2229). | |||
15130 | if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && | |||
15131 | T.hasQualifiers()) { | |||
15132 | InvalidDecl = true; | |||
15133 | Diag(Loc, diag::err_anon_bitfield_qualifiers); | |||
15134 | } | |||
15135 | ||||
15136 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | |||
15137 | // than a variably modified type. | |||
15138 | if (!InvalidDecl && T->isVariablyModifiedType()) { | |||
15139 | bool SizeIsNegative; | |||
15140 | llvm::APSInt Oversized; | |||
15141 | ||||
15142 | TypeSourceInfo *FixedTInfo = | |||
15143 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | |||
15144 | SizeIsNegative, | |||
15145 | Oversized); | |||
15146 | if (FixedTInfo) { | |||
15147 | Diag(Loc, diag::warn_illegal_constant_array_size); | |||
15148 | TInfo = FixedTInfo; | |||
15149 | T = FixedTInfo->getType(); | |||
15150 | } else { | |||
15151 | if (SizeIsNegative) | |||
15152 | Diag(Loc, diag::err_typecheck_negative_array_size); | |||
15153 | else if (Oversized.getBoolValue()) | |||
15154 | Diag(Loc, diag::err_array_too_large) | |||
15155 | << Oversized.toString(10); | |||
15156 | else | |||
15157 | Diag(Loc, diag::err_typecheck_field_variable_size); | |||
15158 | InvalidDecl = true; | |||
15159 | } | |||
15160 | } | |||
15161 | ||||
15162 | // Fields can not have abstract class types | |||
15163 | if (!InvalidDecl && RequireNonAbstractType(Loc, T, | |||
15164 | diag::err_abstract_type_in_decl, | |||
15165 | AbstractFieldType)) | |||
15166 | InvalidDecl = true; | |||
15167 | ||||
15168 | bool ZeroWidth = false; | |||
15169 | if (InvalidDecl) | |||
15170 | BitWidth = nullptr; | |||
15171 | // If this is declared as a bit-field, check the bit-field. | |||
15172 | if (BitWidth) { | |||
15173 | BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, | |||
15174 | &ZeroWidth).get(); | |||
15175 | if (!BitWidth) { | |||
15176 | InvalidDecl = true; | |||
15177 | BitWidth = nullptr; | |||
15178 | ZeroWidth = false; | |||
15179 | } | |||
15180 | } | |||
15181 | ||||
15182 | // Check that 'mutable' is consistent with the type of the declaration. | |||
15183 | if (!InvalidDecl && Mutable) { | |||
15184 | unsigned DiagID = 0; | |||
15185 | if (T->isReferenceType()) | |||
15186 | DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference | |||
15187 | : diag::err_mutable_reference; | |||
15188 | else if (T.isConstQualified()) | |||
15189 | DiagID = diag::err_mutable_const; | |||
15190 | ||||
15191 | if (DiagID) { | |||
15192 | SourceLocation ErrLoc = Loc; | |||
15193 | if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) | |||
15194 | ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); | |||
15195 | Diag(ErrLoc, DiagID); | |||
15196 | if (DiagID != diag::ext_mutable_reference) { | |||
15197 | Mutable = false; | |||
15198 | InvalidDecl = true; | |||
15199 | } | |||
15200 | } | |||
15201 | } | |||
15202 | ||||
15203 | // C++11 [class.union]p8 (DR1460): | |||
15204 | // At most one variant member of a union may have a | |||
15205 | // brace-or-equal-initializer. | |||
15206 | if (InitStyle != ICIS_NoInit) | |||
15207 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); | |||
15208 | ||||
15209 | FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, | |||
15210 | BitWidth, Mutable, InitStyle); | |||
15211 | if (InvalidDecl) | |||
15212 | NewFD->setInvalidDecl(); | |||
15213 | ||||
15214 | if (PrevDecl && !isa<TagDecl>(PrevDecl)) { | |||
15215 | Diag(Loc, diag::err_duplicate_member) << II; | |||
15216 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
15217 | NewFD->setInvalidDecl(); | |||
15218 | } | |||
15219 | ||||
15220 | if (!InvalidDecl && getLangOpts().CPlusPlus) { | |||
15221 | if (Record->isUnion()) { | |||
15222 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | |||
15223 | CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
15224 | if (RDecl->getDefinition()) { | |||
15225 | // C++ [class.union]p1: An object of a class with a non-trivial | |||
15226 | // constructor, a non-trivial copy constructor, a non-trivial | |||
15227 | // destructor, or a non-trivial copy assignment operator | |||
15228 | // cannot be a member of a union, nor can an array of such | |||
15229 | // objects. | |||
15230 | if (CheckNontrivialField(NewFD)) | |||
15231 | NewFD->setInvalidDecl(); | |||
15232 | } | |||
15233 | } | |||
15234 | ||||
15235 | // C++ [class.union]p1: If a union contains a member of reference type, | |||
15236 | // the program is ill-formed, except when compiling with MSVC extensions | |||
15237 | // enabled. | |||
15238 | if (EltTy->isReferenceType()) { | |||
15239 | Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? | |||
15240 | diag::ext_union_member_of_reference_type : | |||
15241 | diag::err_union_member_of_reference_type) | |||
15242 | << NewFD->getDeclName() << EltTy; | |||
15243 | if (!getLangOpts().MicrosoftExt) | |||
15244 | NewFD->setInvalidDecl(); | |||
15245 | } | |||
15246 | } | |||
15247 | } | |||
15248 | ||||
15249 | // FIXME: We need to pass in the attributes given an AST | |||
15250 | // representation, not a parser representation. | |||
15251 | if (D) { | |||
15252 | // FIXME: The current scope is almost... but not entirely... correct here. | |||
15253 | ProcessDeclAttributes(getCurScope(), NewFD, *D); | |||
15254 | ||||
15255 | if (NewFD->hasAttrs()) | |||
15256 | CheckAlignasUnderalignment(NewFD); | |||
15257 | } | |||
15258 | ||||
15259 | // In auto-retain/release, infer strong retension for fields of | |||
15260 | // retainable type. | |||
15261 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) | |||
15262 | NewFD->setInvalidDecl(); | |||
15263 | ||||
15264 | if (T.isObjCGCWeak()) | |||
15265 | Diag(Loc, diag::warn_attribute_weak_on_field); | |||
15266 | ||||
15267 | NewFD->setAccess(AS); | |||
15268 | return NewFD; | |||
15269 | } | |||
15270 | ||||
15271 | bool Sema::CheckNontrivialField(FieldDecl *FD) { | |||
15272 | assert(FD)(static_cast <bool> (FD) ? void (0) : __assert_fail ("FD" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15272, __extension__ __PRETTY_FUNCTION__)); | |||
15273 | assert(getLangOpts().CPlusPlus && "valid check only for C++")(static_cast <bool> (getLangOpts().CPlusPlus && "valid check only for C++") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15273, __extension__ __PRETTY_FUNCTION__)); | |||
15274 | ||||
15275 | if (FD->isInvalidDecl() || FD->getType()->isDependentType()) | |||
15276 | return false; | |||
15277 | ||||
15278 | QualType EltTy = Context.getBaseElementType(FD->getType()); | |||
15279 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | |||
15280 | CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
15281 | if (RDecl->getDefinition()) { | |||
15282 | // We check for copy constructors before constructors | |||
15283 | // because otherwise we'll never get complaints about | |||
15284 | // copy constructors. | |||
15285 | ||||
15286 | CXXSpecialMember member = CXXInvalid; | |||
15287 | // We're required to check for any non-trivial constructors. Since the | |||
15288 | // implicit default constructor is suppressed if there are any | |||
15289 | // user-declared constructors, we just need to check that there is a | |||
15290 | // trivial default constructor and a trivial copy constructor. (We don't | |||
15291 | // worry about move constructors here, since this is a C++98 check.) | |||
15292 | if (RDecl->hasNonTrivialCopyConstructor()) | |||
15293 | member = CXXCopyConstructor; | |||
15294 | else if (!RDecl->hasTrivialDefaultConstructor()) | |||
15295 | member = CXXDefaultConstructor; | |||
15296 | else if (RDecl->hasNonTrivialCopyAssignment()) | |||
15297 | member = CXXCopyAssignment; | |||
15298 | else if (RDecl->hasNonTrivialDestructor()) | |||
15299 | member = CXXDestructor; | |||
15300 | ||||
15301 | if (member != CXXInvalid) { | |||
15302 | if (!getLangOpts().CPlusPlus11 && | |||
15303 | getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { | |||
15304 | // Objective-C++ ARC: it is an error to have a non-trivial field of | |||
15305 | // a union. However, system headers in Objective-C programs | |||
15306 | // occasionally have Objective-C lifetime objects within unions, | |||
15307 | // and rather than cause the program to fail, we make those | |||
15308 | // members unavailable. | |||
15309 | SourceLocation Loc = FD->getLocation(); | |||
15310 | if (getSourceManager().isInSystemHeader(Loc)) { | |||
15311 | if (!FD->hasAttr<UnavailableAttr>()) | |||
15312 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", | |||
15313 | UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); | |||
15314 | return false; | |||
15315 | } | |||
15316 | } | |||
15317 | ||||
15318 | Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? | |||
15319 | diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : | |||
15320 | diag::err_illegal_union_or_anon_struct_member) | |||
15321 | << FD->getParent()->isUnion() << FD->getDeclName() << member; | |||
15322 | DiagnoseNontrivial(RDecl, member); | |||
15323 | return !getLangOpts().CPlusPlus11; | |||
15324 | } | |||
15325 | } | |||
15326 | } | |||
15327 | ||||
15328 | return false; | |||
15329 | } | |||
15330 | ||||
15331 | /// TranslateIvarVisibility - Translate visibility from a token ID to an | |||
15332 | /// AST enum value. | |||
15333 | static ObjCIvarDecl::AccessControl | |||
15334 | TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { | |||
15335 | switch (ivarVisibility) { | |||
15336 | default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15336); | |||
15337 | case tok::objc_private: return ObjCIvarDecl::Private; | |||
15338 | case tok::objc_public: return ObjCIvarDecl::Public; | |||
15339 | case tok::objc_protected: return ObjCIvarDecl::Protected; | |||
15340 | case tok::objc_package: return ObjCIvarDecl::Package; | |||
15341 | } | |||
15342 | } | |||
15343 | ||||
15344 | /// ActOnIvar - Each ivar field of an objective-c class is passed into this | |||
15345 | /// in order to create an IvarDecl object for it. | |||
15346 | Decl *Sema::ActOnIvar(Scope *S, | |||
15347 | SourceLocation DeclStart, | |||
15348 | Declarator &D, Expr *BitfieldWidth, | |||
15349 | tok::ObjCKeywordKind Visibility) { | |||
15350 | ||||
15351 | IdentifierInfo *II = D.getIdentifier(); | |||
15352 | Expr *BitWidth = (Expr*)BitfieldWidth; | |||
15353 | SourceLocation Loc = DeclStart; | |||
15354 | if (II) Loc = D.getIdentifierLoc(); | |||
15355 | ||||
15356 | // FIXME: Unnamed fields can be handled in various different ways, for | |||
15357 | // example, unnamed unions inject all members into the struct namespace! | |||
15358 | ||||
15359 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
15360 | QualType T = TInfo->getType(); | |||
15361 | ||||
15362 | if (BitWidth) { | |||
15363 | // 6.7.2.1p3, 6.7.2.1p4 | |||
15364 | BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); | |||
15365 | if (!BitWidth) | |||
15366 | D.setInvalidType(); | |||
15367 | } else { | |||
15368 | // Not a bitfield. | |||
15369 | ||||
15370 | // validate II. | |||
15371 | ||||
15372 | } | |||
15373 | if (T->isReferenceType()) { | |||
15374 | Diag(Loc, diag::err_ivar_reference_type); | |||
15375 | D.setInvalidType(); | |||
15376 | } | |||
15377 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | |||
15378 | // than a variably modified type. | |||
15379 | else if (T->isVariablyModifiedType()) { | |||
15380 | Diag(Loc, diag::err_typecheck_ivar_variable_size); | |||
15381 | D.setInvalidType(); | |||
15382 | } | |||
15383 | ||||
15384 | // Get the visibility (access control) for this ivar. | |||
15385 | ObjCIvarDecl::AccessControl ac = | |||
15386 | Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) | |||
15387 | : ObjCIvarDecl::None; | |||
15388 | // Must set ivar's DeclContext to its enclosing interface. | |||
15389 | ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); | |||
15390 | if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) | |||
15391 | return nullptr; | |||
15392 | ObjCContainerDecl *EnclosingContext; | |||
15393 | if (ObjCImplementationDecl *IMPDecl = | |||
15394 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | |||
15395 | if (LangOpts.ObjCRuntime.isFragile()) { | |||
15396 | // Case of ivar declared in an implementation. Context is that of its class. | |||
15397 | EnclosingContext = IMPDecl->getClassInterface(); | |||
15398 | assert(EnclosingContext && "Implementation has no class interface!")(static_cast <bool> (EnclosingContext && "Implementation has no class interface!" ) ? void (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15398, __extension__ __PRETTY_FUNCTION__)); | |||
15399 | } | |||
15400 | else | |||
15401 | EnclosingContext = EnclosingDecl; | |||
15402 | } else { | |||
15403 | if (ObjCCategoryDecl *CDecl = | |||
15404 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | |||
15405 | if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { | |||
15406 | Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); | |||
15407 | return nullptr; | |||
15408 | } | |||
15409 | } | |||
15410 | EnclosingContext = EnclosingDecl; | |||
15411 | } | |||
15412 | ||||
15413 | // Construct the decl. | |||
15414 | ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, | |||
15415 | DeclStart, Loc, II, T, | |||
15416 | TInfo, ac, (Expr *)BitfieldWidth); | |||
15417 | ||||
15418 | if (II) { | |||
15419 | NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, | |||
15420 | ForVisibleRedeclaration); | |||
15421 | if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) | |||
15422 | && !isa<TagDecl>(PrevDecl)) { | |||
15423 | Diag(Loc, diag::err_duplicate_member) << II; | |||
15424 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
15425 | NewID->setInvalidDecl(); | |||
15426 | } | |||
15427 | } | |||
15428 | ||||
15429 | // Process attributes attached to the ivar. | |||
15430 | ProcessDeclAttributes(S, NewID, D); | |||
15431 | ||||
15432 | if (D.isInvalidType()) | |||
15433 | NewID->setInvalidDecl(); | |||
15434 | ||||
15435 | // In ARC, infer 'retaining' for ivars of retainable type. | |||
15436 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) | |||
15437 | NewID->setInvalidDecl(); | |||
15438 | ||||
15439 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
15440 | NewID->setModulePrivate(); | |||
15441 | ||||
15442 | if (II) { | |||
15443 | // FIXME: When interfaces are DeclContexts, we'll need to add | |||
15444 | // these to the interface. | |||
15445 | S->AddDecl(NewID); | |||
15446 | IdResolver.AddDecl(NewID); | |||
15447 | } | |||
15448 | ||||
15449 | if (LangOpts.ObjCRuntime.isNonFragile() && | |||
15450 | !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) | |||
15451 | Diag(Loc, diag::warn_ivars_in_interface); | |||
15452 | ||||
15453 | return NewID; | |||
15454 | } | |||
15455 | ||||
15456 | /// ActOnLastBitfield - This routine handles synthesized bitfields rules for | |||
15457 | /// class and class extensions. For every class \@interface and class | |||
15458 | /// extension \@interface, if the last ivar is a bitfield of any type, | |||
15459 | /// then add an implicit `char :0` ivar to the end of that interface. | |||
15460 | void Sema::ActOnLastBitfield(SourceLocation DeclLoc, | |||
15461 | SmallVectorImpl<Decl *> &AllIvarDecls) { | |||
15462 | if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) | |||
15463 | return; | |||
15464 | ||||
15465 | Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; | |||
15466 | ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); | |||
15467 | ||||
15468 | if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) | |||
15469 | return; | |||
15470 | ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); | |||
15471 | if (!ID) { | |||
15472 | if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { | |||
15473 | if (!CD->IsClassExtension()) | |||
15474 | return; | |||
15475 | } | |||
15476 | // No need to add this to end of @implementation. | |||
15477 | else | |||
15478 | return; | |||
15479 | } | |||
15480 | // All conditions are met. Add a new bitfield to the tail end of ivars. | |||
15481 | llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); | |||
15482 | Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); | |||
15483 | ||||
15484 | Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), | |||
15485 | DeclLoc, DeclLoc, nullptr, | |||
15486 | Context.CharTy, | |||
15487 | Context.getTrivialTypeSourceInfo(Context.CharTy, | |||
15488 | DeclLoc), | |||
15489 | ObjCIvarDecl::Private, BW, | |||
15490 | true); | |||
15491 | AllIvarDecls.push_back(Ivar); | |||
15492 | } | |||
15493 | ||||
15494 | void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, | |||
15495 | ArrayRef<Decl *> Fields, SourceLocation LBrac, | |||
15496 | SourceLocation RBrac, | |||
15497 | const ParsedAttributesView &Attrs) { | |||
15498 | assert(EnclosingDecl && "missing record or interface decl")(static_cast <bool> (EnclosingDecl && "missing record or interface decl" ) ? void (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15498, __extension__ __PRETTY_FUNCTION__)); | |||
15499 | ||||
15500 | // If this is an Objective-C @implementation or category and we have | |||
15501 | // new fields here we should reset the layout of the interface since | |||
15502 | // it will now change. | |||
15503 | if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { | |||
15504 | ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); | |||
15505 | switch (DC->getKind()) { | |||
15506 | default: break; | |||
15507 | case Decl::ObjCCategory: | |||
15508 | Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); | |||
15509 | break; | |||
15510 | case Decl::ObjCImplementation: | |||
15511 | Context. | |||
15512 | ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); | |||
15513 | break; | |||
15514 | } | |||
15515 | } | |||
15516 | ||||
15517 | RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); | |||
15518 | ||||
15519 | // Start counting up the number of named members; make sure to include | |||
15520 | // members of anonymous structs and unions in the total. | |||
15521 | unsigned NumNamedMembers = 0; | |||
15522 | if (Record) { | |||
15523 | for (const auto *I : Record->decls()) { | |||
15524 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | |||
15525 | if (IFD->getDeclName()) | |||
15526 | ++NumNamedMembers; | |||
15527 | } | |||
15528 | } | |||
15529 | ||||
15530 | // Verify that all the fields are okay. | |||
15531 | SmallVector<FieldDecl*, 32> RecFields; | |||
15532 | ||||
15533 | bool ObjCFieldLifetimeErrReported = false; | |||
15534 | for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); | |||
15535 | i != end; ++i) { | |||
15536 | FieldDecl *FD = cast<FieldDecl>(*i); | |||
15537 | ||||
15538 | // Get the type for the field. | |||
15539 | const Type *FDTy = FD->getType().getTypePtr(); | |||
15540 | ||||
15541 | if (!FD->isAnonymousStructOrUnion()) { | |||
15542 | // Remember all fields written by the user. | |||
15543 | RecFields.push_back(FD); | |||
15544 | } | |||
15545 | ||||
15546 | // If the field is already invalid for some reason, don't emit more | |||
15547 | // diagnostics about it. | |||
15548 | if (FD->isInvalidDecl()) { | |||
15549 | EnclosingDecl->setInvalidDecl(); | |||
15550 | continue; | |||
15551 | } | |||
15552 | ||||
15553 | // C99 6.7.2.1p2: | |||
15554 | // A structure or union shall not contain a member with | |||
15555 | // incomplete or function type (hence, a structure shall not | |||
15556 | // contain an instance of itself, but may contain a pointer to | |||
15557 | // an instance of itself), except that the last member of a | |||
15558 | // structure with more than one named member may have incomplete | |||
15559 | // array type; such a structure (and any union containing, | |||
15560 | // possibly recursively, a member that is such a structure) | |||
15561 | // shall not be a member of a structure or an element of an | |||
15562 | // array. | |||
15563 | bool IsLastField = (i + 1 == Fields.end()); | |||
15564 | if (FDTy->isFunctionType()) { | |||
15565 | // Field declared as a function. | |||
15566 | Diag(FD->getLocation(), diag::err_field_declared_as_function) | |||
15567 | << FD->getDeclName(); | |||
15568 | FD->setInvalidDecl(); | |||
15569 | EnclosingDecl->setInvalidDecl(); | |||
15570 | continue; | |||
15571 | } else if (FDTy->isIncompleteArrayType() && | |||
15572 | (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { | |||
15573 | if (Record) { | |||
15574 | // Flexible array member. | |||
15575 | // Microsoft and g++ is more permissive regarding flexible array. | |||
15576 | // It will accept flexible array in union and also | |||
15577 | // as the sole element of a struct/class. | |||
15578 | unsigned DiagID = 0; | |||
15579 | if (!Record->isUnion() && !IsLastField) { | |||
15580 | Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) | |||
15581 | << FD->getDeclName() << FD->getType() << Record->getTagKind(); | |||
15582 | Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); | |||
15583 | FD->setInvalidDecl(); | |||
15584 | EnclosingDecl->setInvalidDecl(); | |||
15585 | continue; | |||
15586 | } else if (Record->isUnion()) | |||
15587 | DiagID = getLangOpts().MicrosoftExt | |||
15588 | ? diag::ext_flexible_array_union_ms | |||
15589 | : getLangOpts().CPlusPlus | |||
15590 | ? diag::ext_flexible_array_union_gnu | |||
15591 | : diag::err_flexible_array_union; | |||
15592 | else if (NumNamedMembers < 1) | |||
15593 | DiagID = getLangOpts().MicrosoftExt | |||
15594 | ? diag::ext_flexible_array_empty_aggregate_ms | |||
15595 | : getLangOpts().CPlusPlus | |||
15596 | ? diag::ext_flexible_array_empty_aggregate_gnu | |||
15597 | : diag::err_flexible_array_empty_aggregate; | |||
15598 | ||||
15599 | if (DiagID) | |||
15600 | Diag(FD->getLocation(), DiagID) << FD->getDeclName() | |||
15601 | << Record->getTagKind(); | |||
15602 | // While the layout of types that contain virtual bases is not specified | |||
15603 | // by the C++ standard, both the Itanium and Microsoft C++ ABIs place | |||
15604 | // virtual bases after the derived members. This would make a flexible | |||
15605 | // array member declared at the end of an object not adjacent to the end | |||
15606 | // of the type. | |||
15607 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) | |||
15608 | if (RD->getNumVBases() != 0) | |||
15609 | Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) | |||
15610 | << FD->getDeclName() << Record->getTagKind(); | |||
15611 | if (!getLangOpts().C99) | |||
15612 | Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) | |||
15613 | << FD->getDeclName() << Record->getTagKind(); | |||
15614 | ||||
15615 | // If the element type has a non-trivial destructor, we would not | |||
15616 | // implicitly destroy the elements, so disallow it for now. | |||
15617 | // | |||
15618 | // FIXME: GCC allows this. We should probably either implicitly delete | |||
15619 | // the destructor of the containing class, or just allow this. | |||
15620 | QualType BaseElem = Context.getBaseElementType(FD->getType()); | |||
15621 | if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { | |||
15622 | Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) | |||
15623 | << FD->getDeclName() << FD->getType(); | |||
15624 | FD->setInvalidDecl(); | |||
15625 | EnclosingDecl->setInvalidDecl(); | |||
15626 | continue; | |||
15627 | } | |||
15628 | // Okay, we have a legal flexible array member at the end of the struct. | |||
15629 | Record->setHasFlexibleArrayMember(true); | |||
15630 | } else { | |||
15631 | // In ObjCContainerDecl ivars with incomplete array type are accepted, | |||
15632 | // unless they are followed by another ivar. That check is done | |||
15633 | // elsewhere, after synthesized ivars are known. | |||
15634 | } | |||
15635 | } else if (!FDTy->isDependentType() && | |||
15636 | RequireCompleteType(FD->getLocation(), FD->getType(), | |||
15637 | diag::err_field_incomplete)) { | |||
15638 | // Incomplete type | |||
15639 | FD->setInvalidDecl(); | |||
15640 | EnclosingDecl->setInvalidDecl(); | |||
15641 | continue; | |||
15642 | } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { | |||
15643 | if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { | |||
15644 | // A type which contains a flexible array member is considered to be a | |||
15645 | // flexible array member. | |||
15646 | Record->setHasFlexibleArrayMember(true); | |||
15647 | if (!Record->isUnion()) { | |||
15648 | // If this is a struct/class and this is not the last element, reject | |||
15649 | // it. Note that GCC supports variable sized arrays in the middle of | |||
15650 | // structures. | |||
15651 | if (!IsLastField) | |||
15652 | Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) | |||
15653 | << FD->getDeclName() << FD->getType(); | |||
15654 | else { | |||
15655 | // We support flexible arrays at the end of structs in | |||
15656 | // other structs as an extension. | |||
15657 | Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) | |||
15658 | << FD->getDeclName(); | |||
15659 | } | |||
15660 | } | |||
15661 | } | |||
15662 | if (isa<ObjCContainerDecl>(EnclosingDecl) && | |||
15663 | RequireNonAbstractType(FD->getLocation(), FD->getType(), | |||
15664 | diag::err_abstract_type_in_decl, | |||
15665 | AbstractIvarType)) { | |||
15666 | // Ivars can not have abstract class types | |||
15667 | FD->setInvalidDecl(); | |||
15668 | } | |||
15669 | if (Record && FDTTy->getDecl()->hasObjectMember()) | |||
15670 | Record->setHasObjectMember(true); | |||
15671 | if (Record && FDTTy->getDecl()->hasVolatileMember()) | |||
15672 | Record->setHasVolatileMember(true); | |||
15673 | } else if (FDTy->isObjCObjectType()) { | |||
15674 | /// A field cannot be an Objective-c object | |||
15675 | Diag(FD->getLocation(), diag::err_statically_allocated_object) | |||
15676 | << FixItHint::CreateInsertion(FD->getLocation(), "*"); | |||
15677 | QualType T = Context.getObjCObjectPointerType(FD->getType()); | |||
15678 | FD->setType(T); | |||
15679 | } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
15680 | Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { | |||
15681 | // It's an error in ARC or Weak if a field has lifetime. | |||
15682 | // We don't want to report this in a system header, though, | |||
15683 | // so we just make the field unavailable. | |||
15684 | // FIXME: that's really not sufficient; we need to make the type | |||
15685 | // itself invalid to, say, initialize or copy. | |||
15686 | QualType T = FD->getType(); | |||
15687 | if (T.hasNonTrivialObjCLifetime()) { | |||
15688 | SourceLocation loc = FD->getLocation(); | |||
15689 | if (getSourceManager().isInSystemHeader(loc)) { | |||
15690 | if (!FD->hasAttr<UnavailableAttr>()) { | |||
15691 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", | |||
15692 | UnavailableAttr::IR_ARCFieldWithOwnership, loc)); | |||
15693 | } | |||
15694 | } else { | |||
15695 | Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) | |||
15696 | << T->isBlockPointerType() << Record->getTagKind(); | |||
15697 | } | |||
15698 | ObjCFieldLifetimeErrReported = true; | |||
15699 | } | |||
15700 | } else if (getLangOpts().ObjC1 && | |||
15701 | getLangOpts().getGC() != LangOptions::NonGC && | |||
15702 | Record && !Record->hasObjectMember()) { | |||
15703 | if (FD->getType()->isObjCObjectPointerType() || | |||
15704 | FD->getType().isObjCGCStrong()) | |||
15705 | Record->setHasObjectMember(true); | |||
15706 | else if (Context.getAsArrayType(FD->getType())) { | |||
15707 | QualType BaseType = Context.getBaseElementType(FD->getType()); | |||
15708 | if (BaseType->isRecordType() && | |||
15709 | BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) | |||
15710 | Record->setHasObjectMember(true); | |||
15711 | else if (BaseType->isObjCObjectPointerType() || | |||
15712 | BaseType.isObjCGCStrong()) | |||
15713 | Record->setHasObjectMember(true); | |||
15714 | } | |||
15715 | } | |||
15716 | ||||
15717 | if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { | |||
15718 | QualType FT = FD->getType(); | |||
15719 | if (FT.isNonTrivialToPrimitiveDefaultInitialize()) | |||
15720 | Record->setNonTrivialToPrimitiveDefaultInitialize(true); | |||
15721 | QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); | |||
15722 | if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) | |||
15723 | Record->setNonTrivialToPrimitiveCopy(true); | |||
15724 | if (FT.isDestructedType()) { | |||
15725 | Record->setNonTrivialToPrimitiveDestroy(true); | |||
15726 | Record->setParamDestroyedInCallee(true); | |||
15727 | } | |||
15728 | ||||
15729 | if (const auto *RT = FT->getAs<RecordType>()) { | |||
15730 | if (RT->getDecl()->getArgPassingRestrictions() == | |||
15731 | RecordDecl::APK_CanNeverPassInRegs) | |||
15732 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | |||
15733 | } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) | |||
15734 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | |||
15735 | } | |||
15736 | ||||
15737 | if (Record && FD->getType().isVolatileQualified()) | |||
15738 | Record->setHasVolatileMember(true); | |||
15739 | // Keep track of the number of named members. | |||
15740 | if (FD->getIdentifier()) | |||
15741 | ++NumNamedMembers; | |||
15742 | } | |||
15743 | ||||
15744 | // Okay, we successfully defined 'Record'. | |||
15745 | if (Record) { | |||
15746 | bool Completed = false; | |||
15747 | if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { | |||
15748 | if (!CXXRecord->isInvalidDecl()) { | |||
15749 | // Set access bits correctly on the directly-declared conversions. | |||
15750 | for (CXXRecordDecl::conversion_iterator | |||
15751 | I = CXXRecord->conversion_begin(), | |||
15752 | E = CXXRecord->conversion_end(); I != E; ++I) | |||
15753 | I.setAccess((*I)->getAccess()); | |||
15754 | } | |||
15755 | ||||
15756 | if (!CXXRecord->isDependentType()) { | |||
15757 | if (CXXRecord->hasUserDeclaredDestructor()) { | |||
15758 | // Adjust user-defined destructor exception spec. | |||
15759 | if (getLangOpts().CPlusPlus11) | |||
15760 | AdjustDestructorExceptionSpec(CXXRecord, | |||
15761 | CXXRecord->getDestructor()); | |||
15762 | } | |||
15763 | ||||
15764 | // Add any implicitly-declared members to this class. | |||
15765 | AddImplicitlyDeclaredMembersToClass(CXXRecord); | |||
15766 | ||||
15767 | if (!CXXRecord->isInvalidDecl()) { | |||
15768 | // If we have virtual base classes, we may end up finding multiple | |||
15769 | // final overriders for a given virtual function. Check for this | |||
15770 | // problem now. | |||
15771 | if (CXXRecord->getNumVBases()) { | |||
15772 | CXXFinalOverriderMap FinalOverriders; | |||
15773 | CXXRecord->getFinalOverriders(FinalOverriders); | |||
15774 | ||||
15775 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | |||
15776 | MEnd = FinalOverriders.end(); | |||
15777 | M != MEnd; ++M) { | |||
15778 | for (OverridingMethods::iterator SO = M->second.begin(), | |||
15779 | SOEnd = M->second.end(); | |||
15780 | SO != SOEnd; ++SO) { | |||
15781 | assert(SO->second.size() > 0 &&(static_cast <bool> (SO->second.size() > 0 && "Virtual function without overriding functions?") ? void (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15782, __extension__ __PRETTY_FUNCTION__)) | |||
15782 | "Virtual function without overriding functions?")(static_cast <bool> (SO->second.size() > 0 && "Virtual function without overriding functions?") ? void (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15782, __extension__ __PRETTY_FUNCTION__)); | |||
15783 | if (SO->second.size() == 1) | |||
15784 | continue; | |||
15785 | ||||
15786 | // C++ [class.virtual]p2: | |||
15787 | // In a derived class, if a virtual member function of a base | |||
15788 | // class subobject has more than one final overrider the | |||
15789 | // program is ill-formed. | |||
15790 | Diag(Record->getLocation(), diag::err_multiple_final_overriders) | |||
15791 | << (const NamedDecl *)M->first << Record; | |||
15792 | Diag(M->first->getLocation(), | |||
15793 | diag::note_overridden_virtual_function); | |||
15794 | for (OverridingMethods::overriding_iterator | |||
15795 | OM = SO->second.begin(), | |||
15796 | OMEnd = SO->second.end(); | |||
15797 | OM != OMEnd; ++OM) | |||
15798 | Diag(OM->Method->getLocation(), diag::note_final_overrider) | |||
15799 | << (const NamedDecl *)M->first << OM->Method->getParent(); | |||
15800 | ||||
15801 | Record->setInvalidDecl(); | |||
15802 | } | |||
15803 | } | |||
15804 | CXXRecord->completeDefinition(&FinalOverriders); | |||
15805 | Completed = true; | |||
15806 | } | |||
15807 | } | |||
15808 | } | |||
15809 | } | |||
15810 | ||||
15811 | if (!Completed) | |||
15812 | Record->completeDefinition(); | |||
15813 | ||||
15814 | // Handle attributes before checking the layout. | |||
15815 | ProcessDeclAttributeList(S, Record, Attrs); | |||
15816 | ||||
15817 | // We may have deferred checking for a deleted destructor. Check now. | |||
15818 | if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { | |||
15819 | auto *Dtor = CXXRecord->getDestructor(); | |||
15820 | if (Dtor && Dtor->isImplicit() && | |||
15821 | ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { | |||
15822 | CXXRecord->setImplicitDestructorIsDeleted(); | |||
15823 | SetDeclDeleted(Dtor, CXXRecord->getLocation()); | |||
15824 | } | |||
15825 | } | |||
15826 | ||||
15827 | if (Record->hasAttrs()) { | |||
15828 | CheckAlignasUnderalignment(Record); | |||
15829 | ||||
15830 | if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) | |||
15831 | checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), | |||
15832 | IA->getRange(), IA->getBestCase(), | |||
15833 | IA->getSemanticSpelling()); | |||
15834 | } | |||
15835 | ||||
15836 | // Check if the structure/union declaration is a type that can have zero | |||
15837 | // size in C. For C this is a language extension, for C++ it may cause | |||
15838 | // compatibility problems. | |||
15839 | bool CheckForZeroSize; | |||
15840 | if (!getLangOpts().CPlusPlus) { | |||
15841 | CheckForZeroSize = true; | |||
15842 | } else { | |||
15843 | // For C++ filter out types that cannot be referenced in C code. | |||
15844 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); | |||
15845 | CheckForZeroSize = | |||
15846 | CXXRecord->getLexicalDeclContext()->isExternCContext() && | |||
15847 | !CXXRecord->isDependentType() && | |||
15848 | CXXRecord->isCLike(); | |||
15849 | } | |||
15850 | if (CheckForZeroSize) { | |||
15851 | bool ZeroSize = true; | |||
15852 | bool IsEmpty = true; | |||
15853 | unsigned NonBitFields = 0; | |||
15854 | for (RecordDecl::field_iterator I = Record->field_begin(), | |||
15855 | E = Record->field_end(); | |||
15856 | (NonBitFields == 0 || ZeroSize) && I != E; ++I) { | |||
15857 | IsEmpty = false; | |||
15858 | if (I->isUnnamedBitfield()) { | |||
15859 | if (!I->isZeroLengthBitField(Context)) | |||
15860 | ZeroSize = false; | |||
15861 | } else { | |||
15862 | ++NonBitFields; | |||
15863 | QualType FieldType = I->getType(); | |||
15864 | if (FieldType->isIncompleteType() || | |||
15865 | !Context.getTypeSizeInChars(FieldType).isZero()) | |||
15866 | ZeroSize = false; | |||
15867 | } | |||
15868 | } | |||
15869 | ||||
15870 | // Empty structs are an extension in C (C99 6.7.2.1p7). They are | |||
15871 | // allowed in C++, but warn if its declaration is inside | |||
15872 | // extern "C" block. | |||
15873 | if (ZeroSize) { | |||
15874 | Diag(RecLoc, getLangOpts().CPlusPlus ? | |||
15875 | diag::warn_zero_size_struct_union_in_extern_c : | |||
15876 | diag::warn_zero_size_struct_union_compat) | |||
15877 | << IsEmpty << Record->isUnion() << (NonBitFields > 1); | |||
15878 | } | |||
15879 | ||||
15880 | // Structs without named members are extension in C (C99 6.7.2.1p7), | |||
15881 | // but are accepted by GCC. | |||
15882 | if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { | |||
15883 | Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : | |||
15884 | diag::ext_no_named_members_in_struct_union) | |||
15885 | << Record->isUnion(); | |||
15886 | } | |||
15887 | } | |||
15888 | } else { | |||
15889 | ObjCIvarDecl **ClsFields = | |||
15890 | reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); | |||
15891 | if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { | |||
15892 | ID->setEndOfDefinitionLoc(RBrac); | |||
15893 | // Add ivar's to class's DeclContext. | |||
15894 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | |||
15895 | ClsFields[i]->setLexicalDeclContext(ID); | |||
15896 | ID->addDecl(ClsFields[i]); | |||
15897 | } | |||
15898 | // Must enforce the rule that ivars in the base classes may not be | |||
15899 | // duplicates. | |||
15900 | if (ID->getSuperClass()) | |||
15901 | DiagnoseDuplicateIvars(ID, ID->getSuperClass()); | |||
15902 | } else if (ObjCImplementationDecl *IMPDecl = | |||
15903 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | |||
15904 | assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")(static_cast <bool> (IMPDecl && "ActOnFields - missing ObjCImplementationDecl" ) ? void (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15904, __extension__ __PRETTY_FUNCTION__)); | |||
15905 | for (unsigned I = 0, N = RecFields.size(); I != N; ++I) | |||
15906 | // Ivar declared in @implementation never belongs to the implementation. | |||
15907 | // Only it is in implementation's lexical context. | |||
15908 | ClsFields[I]->setLexicalDeclContext(IMPDecl); | |||
15909 | CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); | |||
15910 | IMPDecl->setIvarLBraceLoc(LBrac); | |||
15911 | IMPDecl->setIvarRBraceLoc(RBrac); | |||
15912 | } else if (ObjCCategoryDecl *CDecl = | |||
15913 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | |||
15914 | // case of ivars in class extension; all other cases have been | |||
15915 | // reported as errors elsewhere. | |||
15916 | // FIXME. Class extension does not have a LocEnd field. | |||
15917 | // CDecl->setLocEnd(RBrac); | |||
15918 | // Add ivar's to class extension's DeclContext. | |||
15919 | // Diagnose redeclaration of private ivars. | |||
15920 | ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); | |||
15921 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | |||
15922 | if (IDecl) { | |||
15923 | if (const ObjCIvarDecl *ClsIvar = | |||
15924 | IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { | |||
15925 | Diag(ClsFields[i]->getLocation(), | |||
15926 | diag::err_duplicate_ivar_declaration); | |||
15927 | Diag(ClsIvar->getLocation(), diag::note_previous_definition); | |||
15928 | continue; | |||
15929 | } | |||
15930 | for (const auto *Ext : IDecl->known_extensions()) { | |||
15931 | if (const ObjCIvarDecl *ClsExtIvar | |||
15932 | = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { | |||
15933 | Diag(ClsFields[i]->getLocation(), | |||
15934 | diag::err_duplicate_ivar_declaration); | |||
15935 | Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); | |||
15936 | continue; | |||
15937 | } | |||
15938 | } | |||
15939 | } | |||
15940 | ClsFields[i]->setLexicalDeclContext(CDecl); | |||
15941 | CDecl->addDecl(ClsFields[i]); | |||
15942 | } | |||
15943 | CDecl->setIvarLBraceLoc(LBrac); | |||
15944 | CDecl->setIvarRBraceLoc(RBrac); | |||
15945 | } | |||
15946 | } | |||
15947 | } | |||
15948 | ||||
15949 | /// Determine whether the given integral value is representable within | |||
15950 | /// the given type T. | |||
15951 | static bool isRepresentableIntegerValue(ASTContext &Context, | |||
15952 | llvm::APSInt &Value, | |||
15953 | QualType T) { | |||
15954 | assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(static_cast <bool> ((T->isIntegralType(Context) || T ->isEnumeralType()) && "Integral type required!") ? void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15955, __extension__ __PRETTY_FUNCTION__)) | |||
15955 | "Integral type required!")(static_cast <bool> ((T->isIntegralType(Context) || T ->isEnumeralType()) && "Integral type required!") ? void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15955, __extension__ __PRETTY_FUNCTION__)); | |||
15956 | unsigned BitWidth = Context.getIntWidth(T); | |||
15957 | ||||
15958 | if (Value.isUnsigned() || Value.isNonNegative()) { | |||
15959 | if (T->isSignedIntegerOrEnumerationType()) | |||
15960 | --BitWidth; | |||
15961 | return Value.getActiveBits() <= BitWidth; | |||
15962 | } | |||
15963 | return Value.getMinSignedBits() <= BitWidth; | |||
15964 | } | |||
15965 | ||||
15966 | // Given an integral type, return the next larger integral type | |||
15967 | // (or a NULL type of no such type exists). | |||
15968 | static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { | |||
15969 | // FIXME: Int128/UInt128 support, which also needs to be introduced into | |||
15970 | // enum checking below. | |||
15971 | assert((T->isIntegralType(Context) ||(static_cast <bool> ((T->isIntegralType(Context) || T ->isEnumeralType()) && "Integral type required!") ? void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15972, __extension__ __PRETTY_FUNCTION__)) | |||
15972 | T->isEnumeralType()) && "Integral type required!")(static_cast <bool> ((T->isIntegralType(Context) || T ->isEnumeralType()) && "Integral type required!") ? void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 15972, __extension__ __PRETTY_FUNCTION__)); | |||
15973 | const unsigned NumTypes = 4; | |||
15974 | QualType SignedIntegralTypes[NumTypes] = { | |||
15975 | Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy | |||
15976 | }; | |||
15977 | QualType UnsignedIntegralTypes[NumTypes] = { | |||
15978 | Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, | |||
15979 | Context.UnsignedLongLongTy | |||
15980 | }; | |||
15981 | ||||
15982 | unsigned BitWidth = Context.getTypeSize(T); | |||
15983 | QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes | |||
15984 | : UnsignedIntegralTypes; | |||
15985 | for (unsigned I = 0; I != NumTypes; ++I) | |||
15986 | if (Context.getTypeSize(Types[I]) > BitWidth) | |||
15987 | return Types[I]; | |||
15988 | ||||
15989 | return QualType(); | |||
15990 | } | |||
15991 | ||||
15992 | EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, | |||
15993 | EnumConstantDecl *LastEnumConst, | |||
15994 | SourceLocation IdLoc, | |||
15995 | IdentifierInfo *Id, | |||
15996 | Expr *Val) { | |||
15997 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | |||
15998 | llvm::APSInt EnumVal(IntWidth); | |||
15999 | QualType EltTy; | |||
16000 | ||||
16001 | if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) | |||
16002 | Val = nullptr; | |||
16003 | ||||
16004 | if (Val) | |||
16005 | Val = DefaultLvalueConversion(Val).get(); | |||
16006 | ||||
16007 | if (Val) { | |||
16008 | if (Enum->isDependentType() || Val->isTypeDependent()) | |||
16009 | EltTy = Context.DependentTy; | |||
16010 | else { | |||
16011 | if (getLangOpts().CPlusPlus11 && Enum->isFixed() && | |||
16012 | !getLangOpts().MSVCCompat) { | |||
16013 | // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the | |||
16014 | // constant-expression in the enumerator-definition shall be a converted | |||
16015 | // constant expression of the underlying type. | |||
16016 | EltTy = Enum->getIntegerType(); | |||
16017 | ExprResult Converted = | |||
16018 | CheckConvertedConstantExpression(Val, EltTy, EnumVal, | |||
16019 | CCEK_Enumerator); | |||
16020 | if (Converted.isInvalid()) | |||
16021 | Val = nullptr; | |||
16022 | else | |||
16023 | Val = Converted.get(); | |||
16024 | } else if (!Val->isValueDependent() && | |||
16025 | !(Val = VerifyIntegerConstantExpression(Val, | |||
16026 | &EnumVal).get())) { | |||
16027 | // C99 6.7.2.2p2: Make sure we have an integer constant expression. | |||
16028 | } else { | |||
16029 | if (Enum->isComplete()) { | |||
16030 | EltTy = Enum->getIntegerType(); | |||
16031 | ||||
16032 | // In Obj-C and Microsoft mode, require the enumeration value to be | |||
16033 | // representable in the underlying type of the enumeration. In C++11, | |||
16034 | // we perform a non-narrowing conversion as part of converted constant | |||
16035 | // expression checking. | |||
16036 | if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | |||
16037 | if (getLangOpts().MSVCCompat) { | |||
16038 | Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; | |||
16039 | Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); | |||
16040 | } else | |||
16041 | Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; | |||
16042 | } else | |||
16043 | Val = ImpCastExprToType(Val, EltTy, | |||
16044 | EltTy->isBooleanType() ? | |||
16045 | CK_IntegralToBoolean : CK_IntegralCast) | |||
16046 | .get(); | |||
16047 | } else if (getLangOpts().CPlusPlus) { | |||
16048 | // C++11 [dcl.enum]p5: | |||
16049 | // If the underlying type is not fixed, the type of each enumerator | |||
16050 | // is the type of its initializing value: | |||
16051 | // - If an initializer is specified for an enumerator, the | |||
16052 | // initializing value has the same type as the expression. | |||
16053 | EltTy = Val->getType(); | |||
16054 | } else { | |||
16055 | // C99 6.7.2.2p2: | |||
16056 | // The expression that defines the value of an enumeration constant | |||
16057 | // shall be an integer constant expression that has a value | |||
16058 | // representable as an int. | |||
16059 | ||||
16060 | // Complain if the value is not representable in an int. | |||
16061 | if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) | |||
16062 | Diag(IdLoc, diag::ext_enum_value_not_int) | |||
16063 | << EnumVal.toString(10) << Val->getSourceRange() | |||
16064 | << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); | |||
16065 | else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { | |||
16066 | // Force the type of the expression to 'int'. | |||
16067 | Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); | |||
16068 | } | |||
16069 | EltTy = Val->getType(); | |||
16070 | } | |||
16071 | } | |||
16072 | } | |||
16073 | } | |||
16074 | ||||
16075 | if (!Val) { | |||
16076 | if (Enum->isDependentType()) | |||
16077 | EltTy = Context.DependentTy; | |||
16078 | else if (!LastEnumConst) { | |||
16079 | // C++0x [dcl.enum]p5: | |||
16080 | // If the underlying type is not fixed, the type of each enumerator | |||
16081 | // is the type of its initializing value: | |||
16082 | // - If no initializer is specified for the first enumerator, the | |||
16083 | // initializing value has an unspecified integral type. | |||
16084 | // | |||
16085 | // GCC uses 'int' for its unspecified integral type, as does | |||
16086 | // C99 6.7.2.2p3. | |||
16087 | if (Enum->isFixed()) { | |||
16088 | EltTy = Enum->getIntegerType(); | |||
16089 | } | |||
16090 | else { | |||
16091 | EltTy = Context.IntTy; | |||
16092 | } | |||
16093 | } else { | |||
16094 | // Assign the last value + 1. | |||
16095 | EnumVal = LastEnumConst->getInitVal(); | |||
16096 | ++EnumVal; | |||
16097 | EltTy = LastEnumConst->getType(); | |||
16098 | ||||
16099 | // Check for overflow on increment. | |||
16100 | if (EnumVal < LastEnumConst->getInitVal()) { | |||
16101 | // C++0x [dcl.enum]p5: | |||
16102 | // If the underlying type is not fixed, the type of each enumerator | |||
16103 | // is the type of its initializing value: | |||
16104 | // | |||
16105 | // - Otherwise the type of the initializing value is the same as | |||
16106 | // the type of the initializing value of the preceding enumerator | |||
16107 | // unless the incremented value is not representable in that type, | |||
16108 | // in which case the type is an unspecified integral type | |||
16109 | // sufficient to contain the incremented value. If no such type | |||
16110 | // exists, the program is ill-formed. | |||
16111 | QualType T = getNextLargerIntegralType(Context, EltTy); | |||
16112 | if (T.isNull() || Enum->isFixed()) { | |||
16113 | // There is no integral type larger enough to represent this | |||
16114 | // value. Complain, then allow the value to wrap around. | |||
16115 | EnumVal = LastEnumConst->getInitVal(); | |||
16116 | EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); | |||
16117 | ++EnumVal; | |||
16118 | if (Enum->isFixed()) | |||
16119 | // When the underlying type is fixed, this is ill-formed. | |||
16120 | Diag(IdLoc, diag::err_enumerator_wrapped) | |||
16121 | << EnumVal.toString(10) | |||
16122 | << EltTy; | |||
16123 | else | |||
16124 | Diag(IdLoc, diag::ext_enumerator_increment_too_large) | |||
16125 | << EnumVal.toString(10); | |||
16126 | } else { | |||
16127 | EltTy = T; | |||
16128 | } | |||
16129 | ||||
16130 | // Retrieve the last enumerator's value, extent that type to the | |||
16131 | // type that is supposed to be large enough to represent the incremented | |||
16132 | // value, then increment. | |||
16133 | EnumVal = LastEnumConst->getInitVal(); | |||
16134 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | |||
16135 | EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); | |||
16136 | ++EnumVal; | |||
16137 | ||||
16138 | // If we're not in C++, diagnose the overflow of enumerator values, | |||
16139 | // which in C99 means that the enumerator value is not representable in | |||
16140 | // an int (C99 6.7.2.2p2). However, we support GCC's extension that | |||
16141 | // permits enumerator values that are representable in some larger | |||
16142 | // integral type. | |||
16143 | if (!getLangOpts().CPlusPlus && !T.isNull()) | |||
16144 | Diag(IdLoc, diag::warn_enum_value_overflow); | |||
16145 | } else if (!getLangOpts().CPlusPlus && | |||
16146 | !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | |||
16147 | // Enforce C99 6.7.2.2p2 even when we compute the next value. | |||
16148 | Diag(IdLoc, diag::ext_enum_value_not_int) | |||
16149 | << EnumVal.toString(10) << 1; | |||
16150 | } | |||
16151 | } | |||
16152 | } | |||
16153 | ||||
16154 | if (!EltTy->isDependentType()) { | |||
16155 | // Make the enumerator value match the signedness and size of the | |||
16156 | // enumerator's type. | |||
16157 | EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); | |||
16158 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | |||
16159 | } | |||
16160 | ||||
16161 | return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, | |||
16162 | Val, EnumVal); | |||
16163 | } | |||
16164 | ||||
16165 | Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, | |||
16166 | SourceLocation IILoc) { | |||
16167 | if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || | |||
16168 | !getLangOpts().CPlusPlus) | |||
16169 | return SkipBodyInfo(); | |||
16170 | ||||
16171 | // We have an anonymous enum definition. Look up the first enumerator to | |||
16172 | // determine if we should merge the definition with an existing one and | |||
16173 | // skip the body. | |||
16174 | NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, | |||
16175 | forRedeclarationInCurContext()); | |||
16176 | auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); | |||
16177 | if (!PrevECD) | |||
16178 | return SkipBodyInfo(); | |||
16179 | ||||
16180 | EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); | |||
16181 | NamedDecl *Hidden; | |||
16182 | if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { | |||
16183 | SkipBodyInfo Skip; | |||
16184 | Skip.Previous = Hidden; | |||
16185 | return Skip; | |||
16186 | } | |||
16187 | ||||
16188 | return SkipBodyInfo(); | |||
16189 | } | |||
16190 | ||||
16191 | Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, | |||
16192 | SourceLocation IdLoc, IdentifierInfo *Id, | |||
16193 | const ParsedAttributesView &Attrs, | |||
16194 | SourceLocation EqualLoc, Expr *Val) { | |||
16195 | EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); | |||
16196 | EnumConstantDecl *LastEnumConst = | |||
16197 | cast_or_null<EnumConstantDecl>(lastEnumConst); | |||
16198 | ||||
16199 | // The scope passed in may not be a decl scope. Zip up the scope tree until | |||
16200 | // we find one that is. | |||
16201 | S = getNonFieldDeclScope(S); | |||
16202 | ||||
16203 | // Verify that there isn't already something declared with this name in this | |||
16204 | // scope. | |||
16205 | NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, | |||
16206 | ForVisibleRedeclaration); | |||
16207 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | |||
16208 | // Maybe we will complain about the shadowed template parameter. | |||
16209 | DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); | |||
16210 | // Just pretend that we didn't see the previous declaration. | |||
16211 | PrevDecl = nullptr; | |||
16212 | } | |||
16213 | ||||
16214 | // C++ [class.mem]p15: | |||
16215 | // If T is the name of a class, then each of the following shall have a name | |||
16216 | // different from T: | |||
16217 | // - every enumerator of every member of class T that is an unscoped | |||
16218 | // enumerated type | |||
16219 | if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) | |||
16220 | DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), | |||
16221 | DeclarationNameInfo(Id, IdLoc)); | |||
16222 | ||||
16223 | EnumConstantDecl *New = | |||
16224 | CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); | |||
16225 | if (!New) | |||
16226 | return nullptr; | |||
16227 | ||||
16228 | if (PrevDecl) { | |||
16229 | // When in C++, we may get a TagDecl with the same name; in this case the | |||
16230 | // enum constant will 'hide' the tag. | |||
16231 | assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(static_cast <bool> ((getLangOpts().CPlusPlus || !isa< TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!" ) ? void (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16232, __extension__ __PRETTY_FUNCTION__)) | |||
16232 | "Received TagDecl when not in C++!")(static_cast <bool> ((getLangOpts().CPlusPlus || !isa< TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!" ) ? void (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16232, __extension__ __PRETTY_FUNCTION__)); | |||
16233 | if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { | |||
16234 | if (isa<EnumConstantDecl>(PrevDecl)) | |||
16235 | Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; | |||
16236 | else | |||
16237 | Diag(IdLoc, diag::err_redefinition) << Id; | |||
16238 | notePreviousDefinition(PrevDecl, IdLoc); | |||
16239 | return nullptr; | |||
16240 | } | |||
16241 | } | |||
16242 | ||||
16243 | // Process attributes. | |||
16244 | ProcessDeclAttributeList(S, New, Attrs); | |||
16245 | AddPragmaAttributes(S, New); | |||
16246 | ||||
16247 | // Register this decl in the current scope stack. | |||
16248 | New->setAccess(TheEnumDecl->getAccess()); | |||
16249 | PushOnScopeChains(New, S); | |||
16250 | ||||
16251 | ActOnDocumentableDecl(New); | |||
16252 | ||||
16253 | return New; | |||
16254 | } | |||
16255 | ||||
16256 | // Returns true when the enum initial expression does not trigger the | |||
16257 | // duplicate enum warning. A few common cases are exempted as follows: | |||
16258 | // Element2 = Element1 | |||
16259 | // Element2 = Element1 + 1 | |||
16260 | // Element2 = Element1 - 1 | |||
16261 | // Where Element2 and Element1 are from the same enum. | |||
16262 | static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { | |||
16263 | Expr *InitExpr = ECD->getInitExpr(); | |||
16264 | if (!InitExpr) | |||
16265 | return true; | |||
16266 | InitExpr = InitExpr->IgnoreImpCasts(); | |||
16267 | ||||
16268 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { | |||
16269 | if (!BO->isAdditiveOp()) | |||
16270 | return true; | |||
16271 | IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); | |||
16272 | if (!IL) | |||
16273 | return true; | |||
16274 | if (IL->getValue() != 1) | |||
16275 | return true; | |||
16276 | ||||
16277 | InitExpr = BO->getLHS(); | |||
16278 | } | |||
16279 | ||||
16280 | // This checks if the elements are from the same enum. | |||
16281 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); | |||
16282 | if (!DRE) | |||
16283 | return true; | |||
16284 | ||||
16285 | EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); | |||
16286 | if (!EnumConstant) | |||
16287 | return true; | |||
16288 | ||||
16289 | if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != | |||
16290 | Enum) | |||
16291 | return true; | |||
16292 | ||||
16293 | return false; | |||
16294 | } | |||
16295 | ||||
16296 | // Emits a warning when an element is implicitly set a value that | |||
16297 | // a previous element has already been set to. | |||
16298 | static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, | |||
16299 | EnumDecl *Enum, QualType EnumType) { | |||
16300 | // Avoid anonymous enums | |||
16301 | if (!Enum->getIdentifier()) | |||
16302 | return; | |||
16303 | ||||
16304 | // Only check for small enums. | |||
16305 | if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) | |||
16306 | return; | |||
16307 | ||||
16308 | if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) | |||
16309 | return; | |||
16310 | ||||
16311 | typedef SmallVector<EnumConstantDecl *, 3> ECDVector; | |||
16312 | typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; | |||
16313 | ||||
16314 | typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; | |||
16315 | typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap; | |||
16316 | ||||
16317 | // Use int64_t as a key to avoid needing special handling for DenseMap keys. | |||
16318 | auto EnumConstantToKey = [](const EnumConstantDecl *D) { | |||
16319 | llvm::APSInt Val = D->getInitVal(); | |||
16320 | return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); | |||
16321 | }; | |||
16322 | ||||
16323 | DuplicatesVector DupVector; | |||
16324 | ValueToVectorMap EnumMap; | |||
16325 | ||||
16326 | // Populate the EnumMap with all values represented by enum constants without | |||
16327 | // an initializer. | |||
16328 | for (auto *Element : Elements) { | |||
16329 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); | |||
16330 | ||||
16331 | // Null EnumConstantDecl means a previous diagnostic has been emitted for | |||
16332 | // this constant. Skip this enum since it may be ill-formed. | |||
16333 | if (!ECD) { | |||
16334 | return; | |||
16335 | } | |||
16336 | ||||
16337 | // Constants with initalizers are handled in the next loop. | |||
16338 | if (ECD->getInitExpr()) | |||
16339 | continue; | |||
16340 | ||||
16341 | // Duplicate values are handled in the next loop. | |||
16342 | EnumMap.insert({EnumConstantToKey(ECD), ECD}); | |||
16343 | } | |||
16344 | ||||
16345 | if (EnumMap.size() == 0) | |||
16346 | return; | |||
16347 | ||||
16348 | // Create vectors for any values that has duplicates. | |||
16349 | for (auto *Element : Elements) { | |||
16350 | // The last loop returned if any constant was null. | |||
16351 | EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); | |||
16352 | if (!ValidDuplicateEnum(ECD, Enum)) | |||
16353 | continue; | |||
16354 | ||||
16355 | auto Iter = EnumMap.find(EnumConstantToKey(ECD)); | |||
16356 | if (Iter == EnumMap.end()) | |||
16357 | continue; | |||
16358 | ||||
16359 | DeclOrVector& Entry = Iter->second; | |||
16360 | if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { | |||
16361 | // Ensure constants are different. | |||
16362 | if (D == ECD) | |||
16363 | continue; | |||
16364 | ||||
16365 | // Create new vector and push values onto it. | |||
16366 | auto Vec = llvm::make_unique<ECDVector>(); | |||
16367 | Vec->push_back(D); | |||
16368 | Vec->push_back(ECD); | |||
16369 | ||||
16370 | // Update entry to point to the duplicates vector. | |||
16371 | Entry = Vec.get(); | |||
16372 | ||||
16373 | // Store the vector somewhere we can consult later for quick emission of | |||
16374 | // diagnostics. | |||
16375 | DupVector.emplace_back(std::move(Vec)); | |||
16376 | continue; | |||
16377 | } | |||
16378 | ||||
16379 | ECDVector *Vec = Entry.get<ECDVector*>(); | |||
16380 | // Make sure constants are not added more than once. | |||
16381 | if (*Vec->begin() == ECD) | |||
16382 | continue; | |||
16383 | ||||
16384 | Vec->push_back(ECD); | |||
16385 | } | |||
16386 | ||||
16387 | // Emit diagnostics. | |||
16388 | for (const auto &Vec : DupVector) { | |||
16389 | assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")(static_cast <bool> (Vec->size() > 1 && "ECDVector should have at least 2 elements." ) ? void (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16389, __extension__ __PRETTY_FUNCTION__)); | |||
16390 | ||||
16391 | // Emit warning for one enum constant. | |||
16392 | auto *FirstECD = Vec->front(); | |||
16393 | S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) | |||
16394 | << FirstECD << FirstECD->getInitVal().toString(10) | |||
16395 | << FirstECD->getSourceRange(); | |||
16396 | ||||
16397 | // Emit one note for each of the remaining enum constants with | |||
16398 | // the same value. | |||
16399 | for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) | |||
16400 | S.Diag(ECD->getLocation(), diag::note_duplicate_element) | |||
16401 | << ECD << ECD->getInitVal().toString(10) | |||
16402 | << ECD->getSourceRange(); | |||
16403 | } | |||
16404 | } | |||
16405 | ||||
16406 | bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, | |||
16407 | bool AllowMask) const { | |||
16408 | assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")(static_cast <bool> (ED->isClosedFlag() && "looking for value in non-flag or open enum" ) ? void (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16408, __extension__ __PRETTY_FUNCTION__)); | |||
16409 | assert(ED->isCompleteDefinition() && "expected enum definition")(static_cast <bool> (ED->isCompleteDefinition() && "expected enum definition") ? void (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16409, __extension__ __PRETTY_FUNCTION__)); | |||
16410 | ||||
16411 | auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); | |||
16412 | llvm::APInt &FlagBits = R.first->second; | |||
16413 | ||||
16414 | if (R.second) { | |||
16415 | for (auto *E : ED->enumerators()) { | |||
16416 | const auto &EVal = E->getInitVal(); | |||
16417 | // Only single-bit enumerators introduce new flag values. | |||
16418 | if (EVal.isPowerOf2()) | |||
16419 | FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; | |||
16420 | } | |||
16421 | } | |||
16422 | ||||
16423 | // A value is in a flag enum if either its bits are a subset of the enum's | |||
16424 | // flag bits (the first condition) or we are allowing masks and the same is | |||
16425 | // true of its complement (the second condition). When masks are allowed, we | |||
16426 | // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. | |||
16427 | // | |||
16428 | // While it's true that any value could be used as a mask, the assumption is | |||
16429 | // that a mask will have all of the insignificant bits set. Anything else is | |||
16430 | // likely a logic error. | |||
16431 | llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); | |||
16432 | return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); | |||
16433 | } | |||
16434 | ||||
16435 | void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, | |||
16436 | Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, | |||
16437 | const ParsedAttributesView &Attrs) { | |||
16438 | EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); | |||
16439 | QualType EnumType = Context.getTypeDeclType(Enum); | |||
16440 | ||||
16441 | ProcessDeclAttributeList(S, Enum, Attrs); | |||
16442 | ||||
16443 | if (Enum->isDependentType()) { | |||
16444 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | |||
16445 | EnumConstantDecl *ECD = | |||
16446 | cast_or_null<EnumConstantDecl>(Elements[i]); | |||
16447 | if (!ECD) continue; | |||
16448 | ||||
16449 | ECD->setType(EnumType); | |||
16450 | } | |||
16451 | ||||
16452 | Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); | |||
16453 | return; | |||
16454 | } | |||
16455 | ||||
16456 | // TODO: If the result value doesn't fit in an int, it must be a long or long | |||
16457 | // long value. ISO C does not support this, but GCC does as an extension, | |||
16458 | // emit a warning. | |||
16459 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | |||
16460 | unsigned CharWidth = Context.getTargetInfo().getCharWidth(); | |||
16461 | unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); | |||
16462 | ||||
16463 | // Verify that all the values are okay, compute the size of the values, and | |||
16464 | // reverse the list. | |||
16465 | unsigned NumNegativeBits = 0; | |||
16466 | unsigned NumPositiveBits = 0; | |||
16467 | ||||
16468 | // Keep track of whether all elements have type int. | |||
16469 | bool AllElementsInt = true; | |||
16470 | ||||
16471 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | |||
16472 | EnumConstantDecl *ECD = | |||
16473 | cast_or_null<EnumConstantDecl>(Elements[i]); | |||
16474 | if (!ECD) continue; // Already issued a diagnostic. | |||
16475 | ||||
16476 | const llvm::APSInt &InitVal = ECD->getInitVal(); | |||
16477 | ||||
16478 | // Keep track of the size of positive and negative values. | |||
16479 | if (InitVal.isUnsigned() || InitVal.isNonNegative()) | |||
16480 | NumPositiveBits = std::max(NumPositiveBits, | |||
16481 | (unsigned)InitVal.getActiveBits()); | |||
16482 | else | |||
16483 | NumNegativeBits = std::max(NumNegativeBits, | |||
16484 | (unsigned)InitVal.getMinSignedBits()); | |||
16485 | ||||
16486 | // Keep track of whether every enum element has type int (very commmon). | |||
16487 | if (AllElementsInt) | |||
16488 | AllElementsInt = ECD->getType() == Context.IntTy; | |||
16489 | } | |||
16490 | ||||
16491 | // Figure out the type that should be used for this enum. | |||
16492 | QualType BestType; | |||
16493 | unsigned BestWidth; | |||
16494 | ||||
16495 | // C++0x N3000 [conv.prom]p3: | |||
16496 | // An rvalue of an unscoped enumeration type whose underlying | |||
16497 | // type is not fixed can be converted to an rvalue of the first | |||
16498 | // of the following types that can represent all the values of | |||
16499 | // the enumeration: int, unsigned int, long int, unsigned long | |||
16500 | // int, long long int, or unsigned long long int. | |||
16501 | // C99 6.4.4.3p2: | |||
16502 | // An identifier declared as an enumeration constant has type int. | |||
16503 | // The C99 rule is modified by a gcc extension | |||
16504 | QualType BestPromotionType; | |||
16505 | ||||
16506 | bool Packed = Enum->hasAttr<PackedAttr>(); | |||
16507 | // -fshort-enums is the equivalent to specifying the packed attribute on all | |||
16508 | // enum definitions. | |||
16509 | if (LangOpts.ShortEnums) | |||
16510 | Packed = true; | |||
16511 | ||||
16512 | // If the enum already has a type because it is fixed or dictated by the | |||
16513 | // target, promote that type instead of analyzing the enumerators. | |||
16514 | if (Enum->isComplete()) { | |||
16515 | BestType = Enum->getIntegerType(); | |||
16516 | if (BestType->isPromotableIntegerType()) | |||
16517 | BestPromotionType = Context.getPromotedIntegerType(BestType); | |||
16518 | else | |||
16519 | BestPromotionType = BestType; | |||
16520 | ||||
16521 | BestWidth = Context.getIntWidth(BestType); | |||
16522 | } | |||
16523 | else if (NumNegativeBits) { | |||
16524 | // If there is a negative value, figure out the smallest integer type (of | |||
16525 | // int/long/longlong) that fits. | |||
16526 | // If it's packed, check also if it fits a char or a short. | |||
16527 | if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { | |||
16528 | BestType = Context.SignedCharTy; | |||
16529 | BestWidth = CharWidth; | |||
16530 | } else if (Packed && NumNegativeBits <= ShortWidth && | |||
16531 | NumPositiveBits < ShortWidth) { | |||
16532 | BestType = Context.ShortTy; | |||
16533 | BestWidth = ShortWidth; | |||
16534 | } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { | |||
16535 | BestType = Context.IntTy; | |||
16536 | BestWidth = IntWidth; | |||
16537 | } else { | |||
16538 | BestWidth = Context.getTargetInfo().getLongWidth(); | |||
16539 | ||||
16540 | if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { | |||
16541 | BestType = Context.LongTy; | |||
16542 | } else { | |||
16543 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | |||
16544 | ||||
16545 | if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) | |||
16546 | Diag(Enum->getLocation(), diag::ext_enum_too_large); | |||
16547 | BestType = Context.LongLongTy; | |||
16548 | } | |||
16549 | } | |||
16550 | BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); | |||
16551 | } else { | |||
16552 | // If there is no negative value, figure out the smallest type that fits | |||
16553 | // all of the enumerator values. | |||
16554 | // If it's packed, check also if it fits a char or a short. | |||
16555 | if (Packed && NumPositiveBits <= CharWidth) { | |||
16556 | BestType = Context.UnsignedCharTy; | |||
16557 | BestPromotionType = Context.IntTy; | |||
16558 | BestWidth = CharWidth; | |||
16559 | } else if (Packed && NumPositiveBits <= ShortWidth) { | |||
16560 | BestType = Context.UnsignedShortTy; | |||
16561 | BestPromotionType = Context.IntTy; | |||
16562 | BestWidth = ShortWidth; | |||
16563 | } else if (NumPositiveBits <= IntWidth) { | |||
16564 | BestType = Context.UnsignedIntTy; | |||
16565 | BestWidth = IntWidth; | |||
16566 | BestPromotionType | |||
16567 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | |||
16568 | ? Context.UnsignedIntTy : Context.IntTy; | |||
16569 | } else if (NumPositiveBits <= | |||
16570 | (BestWidth = Context.getTargetInfo().getLongWidth())) { | |||
16571 | BestType = Context.UnsignedLongTy; | |||
16572 | BestPromotionType | |||
16573 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | |||
16574 | ? Context.UnsignedLongTy : Context.LongTy; | |||
16575 | } else { | |||
16576 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | |||
16577 | assert(NumPositiveBits <= BestWidth &&(static_cast <bool> (NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?") ? void (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16578, __extension__ __PRETTY_FUNCTION__)) | |||
16578 | "How could an initializer get larger than ULL?")(static_cast <bool> (NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?") ? void (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16578, __extension__ __PRETTY_FUNCTION__)); | |||
16579 | BestType = Context.UnsignedLongLongTy; | |||
16580 | BestPromotionType | |||
16581 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | |||
16582 | ? Context.UnsignedLongLongTy : Context.LongLongTy; | |||
16583 | } | |||
16584 | } | |||
16585 | ||||
16586 | // Loop over all of the enumerator constants, changing their types to match | |||
16587 | // the type of the enum if needed. | |||
16588 | for (auto *D : Elements) { | |||
16589 | auto *ECD = cast_or_null<EnumConstantDecl>(D); | |||
16590 | if (!ECD) continue; // Already issued a diagnostic. | |||
16591 | ||||
16592 | // Standard C says the enumerators have int type, but we allow, as an | |||
16593 | // extension, the enumerators to be larger than int size. If each | |||
16594 | // enumerator value fits in an int, type it as an int, otherwise type it the | |||
16595 | // same as the enumerator decl itself. This means that in "enum { X = 1U }" | |||
16596 | // that X has type 'int', not 'unsigned'. | |||
16597 | ||||
16598 | // Determine whether the value fits into an int. | |||
16599 | llvm::APSInt InitVal = ECD->getInitVal(); | |||
16600 | ||||
16601 | // If it fits into an integer type, force it. Otherwise force it to match | |||
16602 | // the enum decl type. | |||
16603 | QualType NewTy; | |||
16604 | unsigned NewWidth; | |||
16605 | bool NewSign; | |||
16606 | if (!getLangOpts().CPlusPlus && | |||
16607 | !Enum->isFixed() && | |||
16608 | isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { | |||
16609 | NewTy = Context.IntTy; | |||
16610 | NewWidth = IntWidth; | |||
16611 | NewSign = true; | |||
16612 | } else if (ECD->getType() == BestType) { | |||
16613 | // Already the right type! | |||
16614 | if (getLangOpts().CPlusPlus) | |||
16615 | // C++ [dcl.enum]p4: Following the closing brace of an | |||
16616 | // enum-specifier, each enumerator has the type of its | |||
16617 | // enumeration. | |||
16618 | ECD->setType(EnumType); | |||
16619 | continue; | |||
16620 | } else { | |||
16621 | NewTy = BestType; | |||
16622 | NewWidth = BestWidth; | |||
16623 | NewSign = BestType->isSignedIntegerOrEnumerationType(); | |||
16624 | } | |||
16625 | ||||
16626 | // Adjust the APSInt value. | |||
16627 | InitVal = InitVal.extOrTrunc(NewWidth); | |||
16628 | InitVal.setIsSigned(NewSign); | |||
16629 | ECD->setInitVal(InitVal); | |||
16630 | ||||
16631 | // Adjust the Expr initializer and type. | |||
16632 | if (ECD->getInitExpr() && | |||
16633 | !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) | |||
16634 | ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, | |||
16635 | CK_IntegralCast, | |||
16636 | ECD->getInitExpr(), | |||
16637 | /*base paths*/ nullptr, | |||
16638 | VK_RValue)); | |||
16639 | if (getLangOpts().CPlusPlus) | |||
16640 | // C++ [dcl.enum]p4: Following the closing brace of an | |||
16641 | // enum-specifier, each enumerator has the type of its | |||
16642 | // enumeration. | |||
16643 | ECD->setType(EnumType); | |||
16644 | else | |||
16645 | ECD->setType(NewTy); | |||
16646 | } | |||
16647 | ||||
16648 | Enum->completeDefinition(BestType, BestPromotionType, | |||
16649 | NumPositiveBits, NumNegativeBits); | |||
16650 | ||||
16651 | CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); | |||
16652 | ||||
16653 | if (Enum->isClosedFlag()) { | |||
16654 | for (Decl *D : Elements) { | |||
16655 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); | |||
16656 | if (!ECD) continue; // Already issued a diagnostic. | |||
16657 | ||||
16658 | llvm::APSInt InitVal = ECD->getInitVal(); | |||
16659 | if (InitVal != 0 && !InitVal.isPowerOf2() && | |||
16660 | !IsValueInFlagEnum(Enum, InitVal, true)) | |||
16661 | Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) | |||
16662 | << ECD << Enum; | |||
16663 | } | |||
16664 | } | |||
16665 | ||||
16666 | // Now that the enum type is defined, ensure it's not been underaligned. | |||
16667 | if (Enum->hasAttrs()) | |||
16668 | CheckAlignasUnderalignment(Enum); | |||
16669 | } | |||
16670 | ||||
16671 | Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, | |||
16672 | SourceLocation StartLoc, | |||
16673 | SourceLocation EndLoc) { | |||
16674 | StringLiteral *AsmString = cast<StringLiteral>(expr); | |||
16675 | ||||
16676 | FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, | |||
16677 | AsmString, StartLoc, | |||
16678 | EndLoc); | |||
16679 | CurContext->addDecl(New); | |||
16680 | return New; | |||
16681 | } | |||
16682 | ||||
16683 | static void checkModuleImportContext(Sema &S, Module *M, | |||
16684 | SourceLocation ImportLoc, DeclContext *DC, | |||
16685 | bool FromInclude = false) { | |||
16686 | SourceLocation ExternCLoc; | |||
16687 | ||||
16688 | if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { | |||
16689 | switch (LSD->getLanguage()) { | |||
16690 | case LinkageSpecDecl::lang_c: | |||
16691 | if (ExternCLoc.isInvalid()) | |||
16692 | ExternCLoc = LSD->getLocStart(); | |||
16693 | break; | |||
16694 | case LinkageSpecDecl::lang_cxx: | |||
16695 | break; | |||
16696 | } | |||
16697 | DC = LSD->getParent(); | |||
16698 | } | |||
16699 | ||||
16700 | while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) | |||
16701 | DC = DC->getParent(); | |||
16702 | ||||
16703 | if (!isa<TranslationUnitDecl>(DC)) { | |||
16704 | S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) | |||
16705 | ? diag::ext_module_import_not_at_top_level_noop | |||
16706 | : diag::err_module_import_not_at_top_level_fatal) | |||
16707 | << M->getFullModuleName() << DC; | |||
16708 | S.Diag(cast<Decl>(DC)->getLocStart(), | |||
16709 | diag::note_module_import_not_at_top_level) << DC; | |||
16710 | } else if (!M->IsExternC && ExternCLoc.isValid()) { | |||
16711 | S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) | |||
16712 | << M->getFullModuleName(); | |||
16713 | S.Diag(ExternCLoc, diag::note_extern_c_begins_here); | |||
16714 | } | |||
16715 | } | |||
16716 | ||||
16717 | Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, | |||
16718 | SourceLocation ModuleLoc, | |||
16719 | ModuleDeclKind MDK, | |||
16720 | ModuleIdPath Path) { | |||
16721 | assert(getLangOpts().ModulesTS &&(static_cast <bool> (getLangOpts().ModulesTS && "should only have module decl in modules TS") ? void (0) : __assert_fail ("getLangOpts().ModulesTS && \"should only have module decl in modules TS\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16722, __extension__ __PRETTY_FUNCTION__)) | |||
16722 | "should only have module decl in modules TS")(static_cast <bool> (getLangOpts().ModulesTS && "should only have module decl in modules TS") ? void (0) : __assert_fail ("getLangOpts().ModulesTS && \"should only have module decl in modules TS\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16722, __extension__ __PRETTY_FUNCTION__)); | |||
16723 | ||||
16724 | // A module implementation unit requires that we are not compiling a module | |||
16725 | // of any kind. A module interface unit requires that we are not compiling a | |||
16726 | // module map. | |||
16727 | switch (getLangOpts().getCompilingModule()) { | |||
16728 | case LangOptions::CMK_None: | |||
16729 | // It's OK to compile a module interface as a normal translation unit. | |||
16730 | break; | |||
16731 | ||||
16732 | case LangOptions::CMK_ModuleInterface: | |||
16733 | if (MDK != ModuleDeclKind::Implementation) | |||
16734 | break; | |||
16735 | ||||
16736 | // We were asked to compile a module interface unit but this is a module | |||
16737 | // implementation unit. That indicates the 'export' is missing. | |||
16738 | Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) | |||
16739 | << FixItHint::CreateInsertion(ModuleLoc, "export "); | |||
16740 | MDK = ModuleDeclKind::Interface; | |||
16741 | break; | |||
16742 | ||||
16743 | case LangOptions::CMK_ModuleMap: | |||
16744 | Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); | |||
16745 | return nullptr; | |||
16746 | } | |||
16747 | ||||
16748 | assert(ModuleScopes.size() == 1 && "expected to be at global module scope")(static_cast <bool> (ModuleScopes.size() == 1 && "expected to be at global module scope") ? void (0) : __assert_fail ("ModuleScopes.size() == 1 && \"expected to be at global module scope\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16748, __extension__ __PRETTY_FUNCTION__)); | |||
16749 | ||||
16750 | // FIXME: Most of this work should be done by the preprocessor rather than | |||
16751 | // here, in order to support macro import. | |||
16752 | ||||
16753 | // Only one module-declaration is permitted per source file. | |||
16754 | if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { | |||
16755 | Diag(ModuleLoc, diag::err_module_redeclaration); | |||
16756 | Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), | |||
16757 | diag::note_prev_module_declaration); | |||
16758 | return nullptr; | |||
16759 | } | |||
16760 | ||||
16761 | // Flatten the dots in a module name. Unlike Clang's hierarchical module map | |||
16762 | // modules, the dots here are just another character that can appear in a | |||
16763 | // module name. | |||
16764 | std::string ModuleName; | |||
16765 | for (auto &Piece : Path) { | |||
16766 | if (!ModuleName.empty()) | |||
16767 | ModuleName += "."; | |||
16768 | ModuleName += Piece.first->getName(); | |||
16769 | } | |||
16770 | ||||
16771 | // If a module name was explicitly specified on the command line, it must be | |||
16772 | // correct. | |||
16773 | if (!getLangOpts().CurrentModule.empty() && | |||
16774 | getLangOpts().CurrentModule != ModuleName) { | |||
16775 | Diag(Path.front().second, diag::err_current_module_name_mismatch) | |||
16776 | << SourceRange(Path.front().second, Path.back().second) | |||
16777 | << getLangOpts().CurrentModule; | |||
16778 | return nullptr; | |||
16779 | } | |||
16780 | const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; | |||
16781 | ||||
16782 | auto &Map = PP.getHeaderSearchInfo().getModuleMap(); | |||
16783 | Module *Mod; | |||
16784 | ||||
16785 | switch (MDK) { | |||
16786 | case ModuleDeclKind::Interface: { | |||
16787 | // We can't have parsed or imported a definition of this module or parsed a | |||
16788 | // module map defining it already. | |||
16789 | if (auto *M = Map.findModule(ModuleName)) { | |||
16790 | Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; | |||
16791 | if (M->DefinitionLoc.isValid()) | |||
16792 | Diag(M->DefinitionLoc, diag::note_prev_module_definition); | |||
16793 | else if (const auto *FE = M->getASTFile()) | |||
16794 | Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) | |||
16795 | << FE->getName(); | |||
16796 | Mod = M; | |||
16797 | break; | |||
16798 | } | |||
16799 | ||||
16800 | // Create a Module for the module that we're defining. | |||
16801 | Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, | |||
16802 | ModuleScopes.front().Module); | |||
16803 | assert(Mod && "module creation should not fail")(static_cast <bool> (Mod && "module creation should not fail" ) ? void (0) : __assert_fail ("Mod && \"module creation should not fail\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16803, __extension__ __PRETTY_FUNCTION__)); | |||
16804 | break; | |||
16805 | } | |||
16806 | ||||
16807 | case ModuleDeclKind::Partition: | |||
16808 | // FIXME: Check we are in a submodule of the named module. | |||
16809 | return nullptr; | |||
16810 | ||||
16811 | case ModuleDeclKind::Implementation: | |||
16812 | std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( | |||
16813 | PP.getIdentifierInfo(ModuleName), Path[0].second); | |||
16814 | Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, | |||
16815 | /*IsIncludeDirective=*/false); | |||
16816 | if (!Mod) { | |||
16817 | Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; | |||
16818 | // Create an empty module interface unit for error recovery. | |||
16819 | Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, | |||
16820 | ModuleScopes.front().Module); | |||
16821 | } | |||
16822 | break; | |||
16823 | } | |||
16824 | ||||
16825 | // Switch from the global module to the named module. | |||
16826 | ModuleScopes.back().Module = Mod; | |||
16827 | ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; | |||
16828 | VisibleModules.setVisible(Mod, ModuleLoc); | |||
16829 | ||||
16830 | // From now on, we have an owning module for all declarations we see. | |||
16831 | // However, those declarations are module-private unless explicitly | |||
16832 | // exported. | |||
16833 | auto *TU = Context.getTranslationUnitDecl(); | |||
16834 | TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); | |||
16835 | TU->setLocalOwningModule(Mod); | |||
16836 | ||||
16837 | // FIXME: Create a ModuleDecl. | |||
16838 | return nullptr; | |||
16839 | } | |||
16840 | ||||
16841 | DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, | |||
16842 | SourceLocation ImportLoc, | |||
16843 | ModuleIdPath Path) { | |||
16844 | Module *Mod = | |||
16845 | getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, | |||
16846 | /*IsIncludeDirective=*/false); | |||
16847 | if (!Mod) | |||
16848 | return true; | |||
16849 | ||||
16850 | VisibleModules.setVisible(Mod, ImportLoc); | |||
16851 | ||||
16852 | checkModuleImportContext(*this, Mod, ImportLoc, CurContext); | |||
16853 | ||||
16854 | // FIXME: we should support importing a submodule within a different submodule | |||
16855 | // of the same top-level module. Until we do, make it an error rather than | |||
16856 | // silently ignoring the import. | |||
16857 | // Import-from-implementation is valid in the Modules TS. FIXME: Should we | |||
16858 | // warn on a redundant import of the current module? | |||
16859 | if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && | |||
16860 | (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) | |||
16861 | Diag(ImportLoc, getLangOpts().isCompilingModule() | |||
16862 | ? diag::err_module_self_import | |||
16863 | : diag::err_module_import_in_implementation) | |||
16864 | << Mod->getFullModuleName() << getLangOpts().CurrentModule; | |||
16865 | ||||
16866 | SmallVector<SourceLocation, 2> IdentifierLocs; | |||
16867 | Module *ModCheck = Mod; | |||
16868 | for (unsigned I = 0, N = Path.size(); I != N; ++I) { | |||
16869 | // If we've run out of module parents, just drop the remaining identifiers. | |||
16870 | // We need the length to be consistent. | |||
16871 | if (!ModCheck) | |||
16872 | break; | |||
16873 | ModCheck = ModCheck->Parent; | |||
16874 | ||||
16875 | IdentifierLocs.push_back(Path[I].second); | |||
16876 | } | |||
16877 | ||||
16878 | ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, | |||
16879 | Mod, IdentifierLocs); | |||
16880 | if (!ModuleScopes.empty()) | |||
16881 | Context.addModuleInitializer(ModuleScopes.back().Module, Import); | |||
16882 | CurContext->addDecl(Import); | |||
16883 | ||||
16884 | // Re-export the module if needed. | |||
16885 | if (Import->isExported() && | |||
16886 | !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) | |||
16887 | getCurrentModule()->Exports.emplace_back(Mod, false); | |||
16888 | ||||
16889 | return Import; | |||
16890 | } | |||
16891 | ||||
16892 | void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { | |||
16893 | checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); | |||
16894 | BuildModuleInclude(DirectiveLoc, Mod); | |||
16895 | } | |||
16896 | ||||
16897 | void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { | |||
16898 | // Determine whether we're in the #include buffer for a module. The #includes | |||
16899 | // in that buffer do not qualify as module imports; they're just an | |||
16900 | // implementation detail of us building the module. | |||
16901 | // | |||
16902 | // FIXME: Should we even get ActOnModuleInclude calls for those? | |||
16903 | bool IsInModuleIncludes = | |||
16904 | TUKind == TU_Module && | |||
16905 | getSourceManager().isWrittenInMainFile(DirectiveLoc); | |||
16906 | ||||
16907 | bool ShouldAddImport = !IsInModuleIncludes; | |||
16908 | ||||
16909 | // If this module import was due to an inclusion directive, create an | |||
16910 | // implicit import declaration to capture it in the AST. | |||
16911 | if (ShouldAddImport) { | |||
16912 | TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); | |||
16913 | ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, | |||
16914 | DirectiveLoc, Mod, | |||
16915 | DirectiveLoc); | |||
16916 | if (!ModuleScopes.empty()) | |||
16917 | Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); | |||
16918 | TU->addDecl(ImportD); | |||
16919 | Consumer.HandleImplicitImportDecl(ImportD); | |||
16920 | } | |||
16921 | ||||
16922 | getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); | |||
16923 | VisibleModules.setVisible(Mod, DirectiveLoc); | |||
16924 | } | |||
16925 | ||||
16926 | void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { | |||
16927 | checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); | |||
16928 | ||||
16929 | ModuleScopes.push_back({}); | |||
16930 | ModuleScopes.back().Module = Mod; | |||
16931 | if (getLangOpts().ModulesLocalVisibility) | |||
16932 | ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); | |||
16933 | ||||
16934 | VisibleModules.setVisible(Mod, DirectiveLoc); | |||
16935 | ||||
16936 | // The enclosing context is now part of this module. | |||
16937 | // FIXME: Consider creating a child DeclContext to hold the entities | |||
16938 | // lexically within the module. | |||
16939 | if (getLangOpts().trackLocalOwningModule()) { | |||
16940 | for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { | |||
16941 | cast<Decl>(DC)->setModuleOwnershipKind( | |||
16942 | getLangOpts().ModulesLocalVisibility | |||
16943 | ? Decl::ModuleOwnershipKind::VisibleWhenImported | |||
16944 | : Decl::ModuleOwnershipKind::Visible); | |||
16945 | cast<Decl>(DC)->setLocalOwningModule(Mod); | |||
16946 | } | |||
16947 | } | |||
16948 | } | |||
16949 | ||||
16950 | void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { | |||
16951 | if (getLangOpts().ModulesLocalVisibility) { | |||
16952 | VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); | |||
16953 | // Leaving a module hides namespace names, so our visible namespace cache | |||
16954 | // is now out of date. | |||
16955 | VisibleNamespaceCache.clear(); | |||
16956 | } | |||
16957 | ||||
16958 | assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&(static_cast <bool> (!ModuleScopes.empty() && ModuleScopes .back().Module == Mod && "left the wrong module scope" ) ? void (0) : __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16959, __extension__ __PRETTY_FUNCTION__)) | |||
16959 | "left the wrong module scope")(static_cast <bool> (!ModuleScopes.empty() && ModuleScopes .back().Module == Mod && "left the wrong module scope" ) ? void (0) : __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16959, __extension__ __PRETTY_FUNCTION__)); | |||
16960 | ModuleScopes.pop_back(); | |||
16961 | ||||
16962 | // We got to the end of processing a local module. Create an | |||
16963 | // ImportDecl as we would for an imported module. | |||
16964 | FileID File = getSourceManager().getFileID(EomLoc); | |||
16965 | SourceLocation DirectiveLoc; | |||
16966 | if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { | |||
16967 | // We reached the end of a #included module header. Use the #include loc. | |||
16968 | assert(File != getSourceManager().getMainFileID() &&(static_cast <bool> (File != getSourceManager().getMainFileID () && "end of submodule in main source file") ? void ( 0) : __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16969, __extension__ __PRETTY_FUNCTION__)) | |||
16969 | "end of submodule in main source file")(static_cast <bool> (File != getSourceManager().getMainFileID () && "end of submodule in main source file") ? void ( 0) : __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\"" , "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaDecl.cpp" , 16969, __extension__ __PRETTY_FUNCTION__)); | |||
16970 | DirectiveLoc = getSourceManager().getIncludeLoc(File); | |||
16971 | } else { | |||
16972 | // We reached an EOM pragma. Use the pragma location. | |||
16973 | DirectiveLoc = EomLoc; | |||
16974 | } | |||
16975 | BuildModuleInclude(DirectiveLoc, Mod); | |||
16976 | ||||
16977 | // Any further declarations are in whatever module we returned to. | |||
16978 | if (getLangOpts().trackLocalOwningModule()) { | |||
16979 | // The parser guarantees that this is the same context that we entered | |||
16980 | // the module within. | |||
16981 | for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { | |||
16982 | cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); | |||
16983 | if (!getCurrentModule()) | |||
16984 | cast<Decl>(DC)->setModuleOwnershipKind( | |||
16985 | Decl::ModuleOwnershipKind::Unowned); | |||
16986 | } | |||
16987 | } | |||
16988 | } | |||
16989 | ||||
16990 | void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, | |||
16991 | Module *Mod) { | |||
16992 | // Bail if we're not allowed to implicitly import a module here. | |||
16993 | if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || | |||
16994 | VisibleModules.isVisible(Mod)) | |||
16995 | return; | |||
16996 | ||||
16997 | // Create the implicit import declaration. | |||
16998 | TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); | |||
16999 | ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, | |||
17000 | Loc, Mod, Loc); | |||
17001 | TU->addDecl(ImportD); | |||
17002 | Consumer.HandleImplicitImportDecl(ImportD); | |||
17003 | ||||
17004 | // Make the module visible. | |||
17005 | getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); | |||
17006 | VisibleModules.setVisible(Mod, Loc); | |||
17007 | } | |||
17008 | ||||
17009 | /// We have parsed the start of an export declaration, including the '{' | |||
17010 | /// (if present). | |||
17011 | Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, | |||
17012 | SourceLocation LBraceLoc) { | |||
17013 | ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); | |||
17014 | ||||
17015 | // C++ Modules TS draft: | |||
17016 | // An export-declaration shall appear in the purview of a module other than | |||
17017 | // the global module. | |||
17018 | if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) | |||
17019 | Diag(ExportLoc, diag::err_export_not_in_module_interface); | |||
17020 | ||||
17021 | // An export-declaration [...] shall not contain more than one | |||
17022 | // export keyword. | |||
17023 | // | |||
17024 | // The intent here is that an export-declaration cannot appear within another | |||
17025 | // export-declaration. | |||
17026 | if (D->isExported()) | |||
17027 | Diag(ExportLoc, diag::err_export_within_export); | |||
17028 | ||||
17029 | CurContext->addDecl(D); | |||
17030 | PushDeclContext(S, D); | |||
17031 | D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); | |||
17032 | return D; | |||
17033 | } | |||
17034 | ||||
17035 | /// Complete the definition of an export declaration. | |||
17036 | Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { | |||
17037 | auto *ED = cast<ExportDecl>(D); | |||
17038 | if (RBraceLoc.isValid()) | |||
17039 | ED->setRBraceLoc(RBraceLoc); | |||
17040 | ||||
17041 | // FIXME: Diagnose export of internal-linkage declaration (including | |||
17042 | // anonymous namespace). | |||
17043 | ||||
17044 | PopDeclContext(); | |||
17045 | return D; | |||
17046 | } | |||
17047 | ||||
17048 | void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, | |||
17049 | IdentifierInfo* AliasName, | |||
17050 | SourceLocation PragmaLoc, | |||
17051 | SourceLocation NameLoc, | |||
17052 | SourceLocation AliasNameLoc) { | |||
17053 | NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, | |||
17054 | LookupOrdinaryName); | |||
17055 | AsmLabelAttr *Attr = | |||
17056 | AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); | |||
17057 | ||||
17058 | // If a declaration that: | |||
17059 | // 1) declares a function or a variable | |||
17060 | // 2) has external linkage | |||
17061 | // already exists, add a label attribute to it. | |||
17062 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | |||
17063 | if (isDeclExternC(PrevDecl)) | |||
17064 | PrevDecl->addAttr(Attr); | |||
17065 | else | |||
17066 | Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) | |||
17067 | << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; | |||
17068 | // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. | |||
17069 | } else | |||
17070 | (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); | |||
17071 | } | |||
17072 | ||||
17073 | void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, | |||
17074 | SourceLocation PragmaLoc, | |||
17075 | SourceLocation NameLoc) { | |||
17076 | Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); | |||
17077 | ||||
17078 | if (PrevDecl) { | |||
17079 | PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); | |||
17080 | } else { | |||
17081 | (void)WeakUndeclaredIdentifiers.insert( | |||
17082 | std::pair<IdentifierInfo*,WeakInfo> | |||
17083 | (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); | |||
17084 | } | |||
17085 | } | |||
17086 | ||||
17087 | void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, | |||
17088 | IdentifierInfo* AliasName, | |||
17089 | SourceLocation PragmaLoc, | |||
17090 | SourceLocation NameLoc, | |||
17091 | SourceLocation AliasNameLoc) { | |||
17092 | Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, | |||
17093 | LookupOrdinaryName); | |||
17094 | WeakInfo W = WeakInfo(Name, NameLoc); | |||
17095 | ||||
17096 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | |||
17097 | if (!PrevDecl->hasAttr<AliasAttr>()) | |||
17098 | if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) | |||
17099 | DeclApplyPragmaWeak(TUScope, ND, W); | |||
17100 | } else { | |||
17101 | (void)WeakUndeclaredIdentifiers.insert( | |||
17102 | std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); | |||
17103 | } | |||
17104 | } | |||
17105 | ||||
17106 | Decl *Sema::getObjCDeclContext() const { | |||
17107 | return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); | |||
17108 | } |