File: | tools/clang/lib/Sema/SemaDecl.cpp |
Warning: | line 2175, column 25 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// | ||||
2 | // | ||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||
6 | // | ||||
7 | //===----------------------------------------------------------------------===// | ||||
8 | // | ||||
9 | // This file implements semantic analysis for declarations. | ||||
10 | // | ||||
11 | //===----------------------------------------------------------------------===// | ||||
12 | |||||
13 | #include "TypeLocBuilder.h" | ||||
14 | #include "clang/AST/ASTConsumer.h" | ||||
15 | #include "clang/AST/ASTContext.h" | ||||
16 | #include "clang/AST/ASTLambda.h" | ||||
17 | #include "clang/AST/CXXInheritance.h" | ||||
18 | #include "clang/AST/CharUnits.h" | ||||
19 | #include "clang/AST/CommentDiagnostic.h" | ||||
20 | #include "clang/AST/DeclCXX.h" | ||||
21 | #include "clang/AST/DeclObjC.h" | ||||
22 | #include "clang/AST/DeclTemplate.h" | ||||
23 | #include "clang/AST/EvaluatedExprVisitor.h" | ||||
24 | #include "clang/AST/ExprCXX.h" | ||||
25 | #include "clang/AST/NonTrivialTypeVisitor.h" | ||||
26 | #include "clang/AST/StmtCXX.h" | ||||
27 | #include "clang/Basic/Builtins.h" | ||||
28 | #include "clang/Basic/PartialDiagnostic.h" | ||||
29 | #include "clang/Basic/SourceManager.h" | ||||
30 | #include "clang/Basic/TargetInfo.h" | ||||
31 | #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex | ||||
32 | #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. | ||||
33 | #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex | ||||
34 | #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() | ||||
35 | #include "clang/Sema/CXXFieldCollector.h" | ||||
36 | #include "clang/Sema/DeclSpec.h" | ||||
37 | #include "clang/Sema/DelayedDiagnostic.h" | ||||
38 | #include "clang/Sema/Initialization.h" | ||||
39 | #include "clang/Sema/Lookup.h" | ||||
40 | #include "clang/Sema/ParsedTemplate.h" | ||||
41 | #include "clang/Sema/Scope.h" | ||||
42 | #include "clang/Sema/ScopeInfo.h" | ||||
43 | #include "clang/Sema/SemaInternal.h" | ||||
44 | #include "clang/Sema/Template.h" | ||||
45 | #include "llvm/ADT/SmallString.h" | ||||
46 | #include "llvm/ADT/Triple.h" | ||||
47 | #include <algorithm> | ||||
48 | #include <cstring> | ||||
49 | #include <functional> | ||||
50 | |||||
51 | using namespace clang; | ||||
52 | using namespace sema; | ||||
53 | |||||
54 | Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { | ||||
55 | if (OwnedType) { | ||||
56 | Decl *Group[2] = { OwnedType, Ptr }; | ||||
57 | return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); | ||||
58 | } | ||||
59 | |||||
60 | return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); | ||||
61 | } | ||||
62 | |||||
63 | namespace { | ||||
64 | |||||
65 | class TypeNameValidatorCCC final : public CorrectionCandidateCallback { | ||||
66 | public: | ||||
67 | TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, | ||||
68 | bool AllowTemplates = false, | ||||
69 | bool AllowNonTemplates = true) | ||||
70 | : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), | ||||
71 | AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { | ||||
72 | WantExpressionKeywords = false; | ||||
73 | WantCXXNamedCasts = false; | ||||
74 | WantRemainingKeywords = false; | ||||
75 | } | ||||
76 | |||||
77 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
78 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | ||||
79 | if (!AllowInvalidDecl && ND->isInvalidDecl()) | ||||
80 | return false; | ||||
81 | |||||
82 | if (getAsTypeTemplateDecl(ND)) | ||||
83 | return AllowTemplates; | ||||
84 | |||||
85 | bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); | ||||
86 | if (!IsType) | ||||
87 | return false; | ||||
88 | |||||
89 | if (AllowNonTemplates) | ||||
90 | return true; | ||||
91 | |||||
92 | // An injected-class-name of a class template (specialization) is valid | ||||
93 | // as a template or as a non-template. | ||||
94 | if (AllowTemplates) { | ||||
95 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | ||||
96 | if (!RD || !RD->isInjectedClassName()) | ||||
97 | return false; | ||||
98 | RD = cast<CXXRecordDecl>(RD->getDeclContext()); | ||||
99 | return RD->getDescribedClassTemplate() || | ||||
100 | isa<ClassTemplateSpecializationDecl>(RD); | ||||
101 | } | ||||
102 | |||||
103 | return false; | ||||
104 | } | ||||
105 | |||||
106 | return !WantClassName && candidate.isKeyword(); | ||||
107 | } | ||||
108 | |||||
109 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
110 | return std::make_unique<TypeNameValidatorCCC>(*this); | ||||
111 | } | ||||
112 | |||||
113 | private: | ||||
114 | bool AllowInvalidDecl; | ||||
115 | bool WantClassName; | ||||
116 | bool AllowTemplates; | ||||
117 | bool AllowNonTemplates; | ||||
118 | }; | ||||
119 | |||||
120 | } // end anonymous namespace | ||||
121 | |||||
122 | /// Determine whether the token kind starts a simple-type-specifier. | ||||
123 | bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { | ||||
124 | switch (Kind) { | ||||
125 | // FIXME: Take into account the current language when deciding whether a | ||||
126 | // token kind is a valid type specifier | ||||
127 | case tok::kw_short: | ||||
128 | case tok::kw_long: | ||||
129 | case tok::kw___int64: | ||||
130 | case tok::kw___int128: | ||||
131 | case tok::kw_signed: | ||||
132 | case tok::kw_unsigned: | ||||
133 | case tok::kw_void: | ||||
134 | case tok::kw_char: | ||||
135 | case tok::kw_int: | ||||
136 | case tok::kw_half: | ||||
137 | case tok::kw_float: | ||||
138 | case tok::kw_double: | ||||
139 | case tok::kw__Float16: | ||||
140 | case tok::kw___float128: | ||||
141 | case tok::kw_wchar_t: | ||||
142 | case tok::kw_bool: | ||||
143 | case tok::kw___underlying_type: | ||||
144 | case tok::kw___auto_type: | ||||
145 | return true; | ||||
146 | |||||
147 | case tok::annot_typename: | ||||
148 | case tok::kw_char16_t: | ||||
149 | case tok::kw_char32_t: | ||||
150 | case tok::kw_typeof: | ||||
151 | case tok::annot_decltype: | ||||
152 | case tok::kw_decltype: | ||||
153 | return getLangOpts().CPlusPlus; | ||||
154 | |||||
155 | case tok::kw_char8_t: | ||||
156 | return getLangOpts().Char8; | ||||
157 | |||||
158 | default: | ||||
159 | break; | ||||
160 | } | ||||
161 | |||||
162 | return false; | ||||
163 | } | ||||
164 | |||||
165 | namespace { | ||||
166 | enum class UnqualifiedTypeNameLookupResult { | ||||
167 | NotFound, | ||||
168 | FoundNonType, | ||||
169 | FoundType | ||||
170 | }; | ||||
171 | } // end anonymous namespace | ||||
172 | |||||
173 | /// Tries to perform unqualified lookup of the type decls in bases for | ||||
174 | /// dependent class. | ||||
175 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a | ||||
176 | /// type decl, \a FoundType if only type decls are found. | ||||
177 | static UnqualifiedTypeNameLookupResult | ||||
178 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, | ||||
179 | SourceLocation NameLoc, | ||||
180 | const CXXRecordDecl *RD) { | ||||
181 | if (!RD->hasDefinition()) | ||||
182 | return UnqualifiedTypeNameLookupResult::NotFound; | ||||
183 | // Look for type decls in base classes. | ||||
184 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | ||||
185 | UnqualifiedTypeNameLookupResult::NotFound; | ||||
186 | for (const auto &Base : RD->bases()) { | ||||
187 | const CXXRecordDecl *BaseRD = nullptr; | ||||
188 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) | ||||
189 | BaseRD = BaseTT->getAsCXXRecordDecl(); | ||||
190 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { | ||||
191 | // Look for type decls in dependent base classes that have known primary | ||||
192 | // templates. | ||||
193 | if (!TST || !TST->isDependentType()) | ||||
194 | continue; | ||||
195 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); | ||||
196 | if (!TD) | ||||
197 | continue; | ||||
198 | if (auto *BasePrimaryTemplate = | ||||
199 | dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { | ||||
200 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) | ||||
201 | BaseRD = BasePrimaryTemplate; | ||||
202 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { | ||||
203 | if (const ClassTemplatePartialSpecializationDecl *PS = | ||||
204 | CTD->findPartialSpecialization(Base.getType())) | ||||
205 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) | ||||
206 | BaseRD = PS; | ||||
207 | } | ||||
208 | } | ||||
209 | } | ||||
210 | if (BaseRD) { | ||||
211 | for (NamedDecl *ND : BaseRD->lookup(&II)) { | ||||
212 | if (!isa<TypeDecl>(ND)) | ||||
213 | return UnqualifiedTypeNameLookupResult::FoundNonType; | ||||
214 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | ||||
215 | } | ||||
216 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { | ||||
217 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { | ||||
218 | case UnqualifiedTypeNameLookupResult::FoundNonType: | ||||
219 | return UnqualifiedTypeNameLookupResult::FoundNonType; | ||||
220 | case UnqualifiedTypeNameLookupResult::FoundType: | ||||
221 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | ||||
222 | break; | ||||
223 | case UnqualifiedTypeNameLookupResult::NotFound: | ||||
224 | break; | ||||
225 | } | ||||
226 | } | ||||
227 | } | ||||
228 | } | ||||
229 | |||||
230 | return FoundTypeDecl; | ||||
231 | } | ||||
232 | |||||
233 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, | ||||
234 | const IdentifierInfo &II, | ||||
235 | SourceLocation NameLoc) { | ||||
236 | // Lookup in the parent class template context, if any. | ||||
237 | const CXXRecordDecl *RD = nullptr; | ||||
238 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | ||||
239 | UnqualifiedTypeNameLookupResult::NotFound; | ||||
240 | for (DeclContext *DC = S.CurContext; | ||||
241 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; | ||||
242 | DC = DC->getParent()) { | ||||
243 | // Look for type decls in dependent base classes that have known primary | ||||
244 | // templates. | ||||
245 | RD = dyn_cast<CXXRecordDecl>(DC); | ||||
246 | if (RD && RD->getDescribedClassTemplate()) | ||||
247 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); | ||||
248 | } | ||||
249 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) | ||||
250 | return nullptr; | ||||
251 | |||||
252 | // We found some types in dependent base classes. Recover as if the user | ||||
253 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the | ||||
254 | // lookup during template instantiation. | ||||
255 | S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; | ||||
256 | |||||
257 | ASTContext &Context = S.Context; | ||||
258 | auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, | ||||
259 | cast<Type>(Context.getRecordType(RD))); | ||||
260 | QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); | ||||
261 | |||||
262 | CXXScopeSpec SS; | ||||
263 | SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||
264 | |||||
265 | TypeLocBuilder Builder; | ||||
266 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | ||||
267 | DepTL.setNameLoc(NameLoc); | ||||
268 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
269 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
270 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||
271 | } | ||||
272 | |||||
273 | /// If the identifier refers to a type name within this scope, | ||||
274 | /// return the declaration of that type. | ||||
275 | /// | ||||
276 | /// This routine performs ordinary name lookup of the identifier II | ||||
277 | /// within the given scope, with optional C++ scope specifier SS, to | ||||
278 | /// determine whether the name refers to a type. If so, returns an | ||||
279 | /// opaque pointer (actually a QualType) corresponding to that | ||||
280 | /// type. Otherwise, returns NULL. | ||||
281 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, | ||||
282 | Scope *S, CXXScopeSpec *SS, | ||||
283 | bool isClassName, bool HasTrailingDot, | ||||
284 | ParsedType ObjectTypePtr, | ||||
285 | bool IsCtorOrDtorName, | ||||
286 | bool WantNontrivialTypeSourceInfo, | ||||
287 | bool IsClassTemplateDeductionContext, | ||||
288 | IdentifierInfo **CorrectedII) { | ||||
289 | // FIXME: Consider allowing this outside C++1z mode as an extension. | ||||
290 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && | ||||
291 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && | ||||
292 | !isClassName && !HasTrailingDot; | ||||
293 | |||||
294 | // Determine where we will perform name lookup. | ||||
295 | DeclContext *LookupCtx = nullptr; | ||||
296 | if (ObjectTypePtr) { | ||||
297 | QualType ObjectType = ObjectTypePtr.get(); | ||||
298 | if (ObjectType->isRecordType()) | ||||
299 | LookupCtx = computeDeclContext(ObjectType); | ||||
300 | } else if (SS && SS->isNotEmpty()) { | ||||
301 | LookupCtx = computeDeclContext(*SS, false); | ||||
302 | |||||
303 | if (!LookupCtx) { | ||||
304 | if (isDependentScopeSpecifier(*SS)) { | ||||
305 | // C++ [temp.res]p3: | ||||
306 | // A qualified-id that refers to a type and in which the | ||||
307 | // nested-name-specifier depends on a template-parameter (14.6.2) | ||||
308 | // shall be prefixed by the keyword typename to indicate that the | ||||
309 | // qualified-id denotes a type, forming an | ||||
310 | // elaborated-type-specifier (7.1.5.3). | ||||
311 | // | ||||
312 | // We therefore do not perform any name lookup if the result would | ||||
313 | // refer to a member of an unknown specialization. | ||||
314 | if (!isClassName && !IsCtorOrDtorName) | ||||
315 | return nullptr; | ||||
316 | |||||
317 | // We know from the grammar that this name refers to a type, | ||||
318 | // so build a dependent node to describe the type. | ||||
319 | if (WantNontrivialTypeSourceInfo) | ||||
320 | return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); | ||||
321 | |||||
322 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); | ||||
323 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, | ||||
324 | II, NameLoc); | ||||
325 | return ParsedType::make(T); | ||||
326 | } | ||||
327 | |||||
328 | return nullptr; | ||||
329 | } | ||||
330 | |||||
331 | if (!LookupCtx->isDependentContext() && | ||||
332 | RequireCompleteDeclContext(*SS, LookupCtx)) | ||||
333 | return nullptr; | ||||
334 | } | ||||
335 | |||||
336 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of | ||||
337 | // lookup for class-names. | ||||
338 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : | ||||
339 | LookupOrdinaryName; | ||||
340 | LookupResult Result(*this, &II, NameLoc, Kind); | ||||
341 | if (LookupCtx) { | ||||
342 | // Perform "qualified" name lookup into the declaration context we | ||||
343 | // computed, which is either the type of the base of a member access | ||||
344 | // expression or the declaration context associated with a prior | ||||
345 | // nested-name-specifier. | ||||
346 | LookupQualifiedName(Result, LookupCtx); | ||||
347 | |||||
348 | if (ObjectTypePtr && Result.empty()) { | ||||
349 | // C++ [basic.lookup.classref]p3: | ||||
350 | // If the unqualified-id is ~type-name, the type-name is looked up | ||||
351 | // in the context of the entire postfix-expression. If the type T of | ||||
352 | // the object expression is of a class type C, the type-name is also | ||||
353 | // looked up in the scope of class C. At least one of the lookups shall | ||||
354 | // find a name that refers to (possibly cv-qualified) T. | ||||
355 | LookupName(Result, S); | ||||
356 | } | ||||
357 | } else { | ||||
358 | // Perform unqualified name lookup. | ||||
359 | LookupName(Result, S); | ||||
360 | |||||
361 | // For unqualified lookup in a class template in MSVC mode, look into | ||||
362 | // dependent base classes where the primary class template is known. | ||||
363 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { | ||||
364 | if (ParsedType TypeInBase = | ||||
365 | recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) | ||||
366 | return TypeInBase; | ||||
367 | } | ||||
368 | } | ||||
369 | |||||
370 | NamedDecl *IIDecl = nullptr; | ||||
371 | switch (Result.getResultKind()) { | ||||
372 | case LookupResult::NotFound: | ||||
373 | case LookupResult::NotFoundInCurrentInstantiation: | ||||
374 | if (CorrectedII) { | ||||
375 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, | ||||
376 | AllowDeducedTemplate); | ||||
377 | TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, | ||||
378 | S, SS, CCC, CTK_ErrorRecovery); | ||||
379 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); | ||||
380 | TemplateTy Template; | ||||
381 | bool MemberOfUnknownSpecialization; | ||||
382 | UnqualifiedId TemplateName; | ||||
383 | TemplateName.setIdentifier(NewII, NameLoc); | ||||
384 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); | ||||
385 | CXXScopeSpec NewSS, *NewSSPtr = SS; | ||||
386 | if (SS && NNS) { | ||||
387 | NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||
388 | NewSSPtr = &NewSS; | ||||
389 | } | ||||
390 | if (Correction && (NNS || NewII != &II) && | ||||
391 | // Ignore a correction to a template type as the to-be-corrected | ||||
392 | // identifier is not a template (typo correction for template names | ||||
393 | // is handled elsewhere). | ||||
394 | !(getLangOpts().CPlusPlus && NewSSPtr && | ||||
395 | isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, | ||||
396 | Template, MemberOfUnknownSpecialization))) { | ||||
397 | ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, | ||||
398 | isClassName, HasTrailingDot, ObjectTypePtr, | ||||
399 | IsCtorOrDtorName, | ||||
400 | WantNontrivialTypeSourceInfo, | ||||
401 | IsClassTemplateDeductionContext); | ||||
402 | if (Ty) { | ||||
403 | diagnoseTypo(Correction, | ||||
404 | PDiag(diag::err_unknown_type_or_class_name_suggest) | ||||
405 | << Result.getLookupName() << isClassName); | ||||
406 | if (SS && NNS) | ||||
407 | SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||
408 | *CorrectedII = NewII; | ||||
409 | return Ty; | ||||
410 | } | ||||
411 | } | ||||
412 | } | ||||
413 | // If typo correction failed or was not performed, fall through | ||||
414 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
415 | case LookupResult::FoundOverloaded: | ||||
416 | case LookupResult::FoundUnresolvedValue: | ||||
417 | Result.suppressDiagnostics(); | ||||
418 | return nullptr; | ||||
419 | |||||
420 | case LookupResult::Ambiguous: | ||||
421 | // Recover from type-hiding ambiguities by hiding the type. We'll | ||||
422 | // do the lookup again when looking for an object, and we can | ||||
423 | // diagnose the error then. If we don't do this, then the error | ||||
424 | // about hiding the type will be immediately followed by an error | ||||
425 | // that only makes sense if the identifier was treated like a type. | ||||
426 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { | ||||
427 | Result.suppressDiagnostics(); | ||||
428 | return nullptr; | ||||
429 | } | ||||
430 | |||||
431 | // Look to see if we have a type anywhere in the list of results. | ||||
432 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); | ||||
433 | Res != ResEnd; ++Res) { | ||||
434 | if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || | ||||
435 | (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { | ||||
436 | if (!IIDecl || | ||||
437 | (*Res)->getLocation().getRawEncoding() < | ||||
438 | IIDecl->getLocation().getRawEncoding()) | ||||
439 | IIDecl = *Res; | ||||
440 | } | ||||
441 | } | ||||
442 | |||||
443 | if (!IIDecl) { | ||||
444 | // None of the entities we found is a type, so there is no way | ||||
445 | // to even assume that the result is a type. In this case, don't | ||||
446 | // complain about the ambiguity. The parser will either try to | ||||
447 | // perform this lookup again (e.g., as an object name), which | ||||
448 | // will produce the ambiguity, or will complain that it expected | ||||
449 | // a type name. | ||||
450 | Result.suppressDiagnostics(); | ||||
451 | return nullptr; | ||||
452 | } | ||||
453 | |||||
454 | // We found a type within the ambiguous lookup; diagnose the | ||||
455 | // ambiguity and then return that type. This might be the right | ||||
456 | // answer, or it might not be, but it suppresses any attempt to | ||||
457 | // perform the name lookup again. | ||||
458 | break; | ||||
459 | |||||
460 | case LookupResult::Found: | ||||
461 | IIDecl = Result.getFoundDecl(); | ||||
462 | break; | ||||
463 | } | ||||
464 | |||||
465 | assert(IIDecl && "Didn't find decl")((IIDecl && "Didn't find decl") ? static_cast<void > (0) : __assert_fail ("IIDecl && \"Didn't find decl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 465, __PRETTY_FUNCTION__)); | ||||
466 | |||||
467 | QualType T; | ||||
468 | if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { | ||||
469 | // C++ [class.qual]p2: A lookup that would find the injected-class-name | ||||
470 | // instead names the constructors of the class, except when naming a class. | ||||
471 | // This is ill-formed when we're not actually forming a ctor or dtor name. | ||||
472 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); | ||||
473 | auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); | ||||
474 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && | ||||
475 | FoundRD->isInjectedClassName() && | ||||
476 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) | ||||
477 | Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) | ||||
478 | << &II << /*Type*/1; | ||||
479 | |||||
480 | DiagnoseUseOfDecl(IIDecl, NameLoc); | ||||
481 | |||||
482 | T = Context.getTypeDeclType(TD); | ||||
483 | MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); | ||||
484 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { | ||||
485 | (void)DiagnoseUseOfDecl(IDecl, NameLoc); | ||||
486 | if (!HasTrailingDot) | ||||
487 | T = Context.getObjCInterfaceType(IDecl); | ||||
488 | } else if (AllowDeducedTemplate) { | ||||
489 | if (auto *TD = getAsTypeTemplateDecl(IIDecl)) | ||||
490 | T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), | ||||
491 | QualType(), false); | ||||
492 | } | ||||
493 | |||||
494 | if (T.isNull()) { | ||||
495 | // If it's not plausibly a type, suppress diagnostics. | ||||
496 | Result.suppressDiagnostics(); | ||||
497 | return nullptr; | ||||
498 | } | ||||
499 | |||||
500 | // NOTE: avoid constructing an ElaboratedType(Loc) if this is a | ||||
501 | // constructor or destructor name (in such a case, the scope specifier | ||||
502 | // will be attached to the enclosing Expr or Decl node). | ||||
503 | if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && | ||||
504 | !isa<ObjCInterfaceDecl>(IIDecl)) { | ||||
505 | if (WantNontrivialTypeSourceInfo) { | ||||
506 | // Construct a type with type-source information. | ||||
507 | TypeLocBuilder Builder; | ||||
508 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | ||||
509 | |||||
510 | T = getElaboratedType(ETK_None, *SS, T); | ||||
511 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | ||||
512 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
513 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); | ||||
514 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||
515 | } else { | ||||
516 | T = getElaboratedType(ETK_None, *SS, T); | ||||
517 | } | ||||
518 | } | ||||
519 | |||||
520 | return ParsedType::make(T); | ||||
521 | } | ||||
522 | |||||
523 | // Builds a fake NNS for the given decl context. | ||||
524 | static NestedNameSpecifier * | ||||
525 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { | ||||
526 | for (;; DC = DC->getLookupParent()) { | ||||
527 | DC = DC->getPrimaryContext(); | ||||
528 | auto *ND = dyn_cast<NamespaceDecl>(DC); | ||||
529 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) | ||||
530 | return NestedNameSpecifier::Create(Context, nullptr, ND); | ||||
531 | else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||
532 | return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | ||||
533 | RD->getTypeForDecl()); | ||||
534 | else if (isa<TranslationUnitDecl>(DC)) | ||||
535 | return NestedNameSpecifier::GlobalSpecifier(Context); | ||||
536 | } | ||||
537 | llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 537); | ||||
538 | } | ||||
539 | |||||
540 | /// Find the parent class with dependent bases of the innermost enclosing method | ||||
541 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end | ||||
542 | /// up allowing unqualified dependent type names at class-level, which MSVC | ||||
543 | /// correctly rejects. | ||||
544 | static const CXXRecordDecl * | ||||
545 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { | ||||
546 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { | ||||
547 | DC = DC->getPrimaryContext(); | ||||
548 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||
549 | if (MD->getParent()->hasAnyDependentBases()) | ||||
550 | return MD->getParent(); | ||||
551 | } | ||||
552 | return nullptr; | ||||
553 | } | ||||
554 | |||||
555 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, | ||||
556 | SourceLocation NameLoc, | ||||
557 | bool IsTemplateTypeArg) { | ||||
558 | assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 558, __PRETTY_FUNCTION__)); | ||||
559 | |||||
560 | NestedNameSpecifier *NNS = nullptr; | ||||
561 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { | ||||
562 | // If we weren't able to parse a default template argument, delay lookup | ||||
563 | // until instantiation time by making a non-dependent DependentTypeName. We | ||||
564 | // pretend we saw a NestedNameSpecifier referring to the current scope, and | ||||
565 | // lookup is retried. | ||||
566 | // FIXME: This hurts our diagnostic quality, since we get errors like "no | ||||
567 | // type named 'Foo' in 'current_namespace'" when the user didn't write any | ||||
568 | // name specifiers. | ||||
569 | NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); | ||||
570 | Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; | ||||
571 | } else if (const CXXRecordDecl *RD = | ||||
572 | findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { | ||||
573 | // Build a DependentNameType that will perform lookup into RD at | ||||
574 | // instantiation time. | ||||
575 | NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | ||||
576 | RD->getTypeForDecl()); | ||||
577 | |||||
578 | // Diagnose that this identifier was undeclared, and retry the lookup during | ||||
579 | // template instantiation. | ||||
580 | Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II | ||||
581 | << RD; | ||||
582 | } else { | ||||
583 | // This is not a situation that we should recover from. | ||||
584 | return ParsedType(); | ||||
585 | } | ||||
586 | |||||
587 | QualType T = Context.getDependentNameType(ETK_None, NNS, &II); | ||||
588 | |||||
589 | // Build type location information. We synthesized the qualifier, so we have | ||||
590 | // to build a fake NestedNameSpecifierLoc. | ||||
591 | NestedNameSpecifierLocBuilder NNSLocBuilder; | ||||
592 | NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||
593 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); | ||||
594 | |||||
595 | TypeLocBuilder Builder; | ||||
596 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | ||||
597 | DepTL.setNameLoc(NameLoc); | ||||
598 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
599 | DepTL.setQualifierLoc(QualifierLoc); | ||||
600 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||
601 | } | ||||
602 | |||||
603 | /// isTagName() - This method is called *for error recovery purposes only* | ||||
604 | /// to determine if the specified name is a valid tag name ("struct foo"). If | ||||
605 | /// so, this returns the TST for the tag corresponding to it (TST_enum, | ||||
606 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose | ||||
607 | /// cases in C where the user forgot to specify the tag. | ||||
608 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { | ||||
609 | // Do a tag name lookup in this scope. | ||||
610 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); | ||||
611 | LookupName(R, S, false); | ||||
612 | R.suppressDiagnostics(); | ||||
613 | if (R.getResultKind() == LookupResult::Found) | ||||
614 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { | ||||
615 | switch (TD->getTagKind()) { | ||||
616 | case TTK_Struct: return DeclSpec::TST_struct; | ||||
617 | case TTK_Interface: return DeclSpec::TST_interface; | ||||
618 | case TTK_Union: return DeclSpec::TST_union; | ||||
619 | case TTK_Class: return DeclSpec::TST_class; | ||||
620 | case TTK_Enum: return DeclSpec::TST_enum; | ||||
621 | } | ||||
622 | } | ||||
623 | |||||
624 | return DeclSpec::TST_unspecified; | ||||
625 | } | ||||
626 | |||||
627 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, | ||||
628 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes | ||||
629 | /// then downgrade the missing typename error to a warning. | ||||
630 | /// This is needed for MSVC compatibility; Example: | ||||
631 | /// @code | ||||
632 | /// template<class T> class A { | ||||
633 | /// public: | ||||
634 | /// typedef int TYPE; | ||||
635 | /// }; | ||||
636 | /// template<class T> class B : public A<T> { | ||||
637 | /// public: | ||||
638 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. | ||||
639 | /// }; | ||||
640 | /// @endcode | ||||
641 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { | ||||
642 | if (CurContext->isRecord()) { | ||||
643 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) | ||||
644 | return true; | ||||
645 | |||||
646 | const Type *Ty = SS->getScopeRep()->getAsType(); | ||||
647 | |||||
648 | CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); | ||||
649 | for (const auto &Base : RD->bases()) | ||||
650 | if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) | ||||
651 | return true; | ||||
652 | return S->isFunctionPrototypeScope(); | ||||
653 | } | ||||
654 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); | ||||
655 | } | ||||
656 | |||||
657 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, | ||||
658 | SourceLocation IILoc, | ||||
659 | Scope *S, | ||||
660 | CXXScopeSpec *SS, | ||||
661 | ParsedType &SuggestedType, | ||||
662 | bool IsTemplateName) { | ||||
663 | // Don't report typename errors for editor placeholders. | ||||
664 | if (II->isEditorPlaceholder()) | ||||
665 | return; | ||||
666 | // We don't have anything to suggest (yet). | ||||
667 | SuggestedType = nullptr; | ||||
668 | |||||
669 | // There may have been a typo in the name of the type. Look up typo | ||||
670 | // results, in case we have something that we can suggest. | ||||
671 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, | ||||
672 | /*AllowTemplates=*/IsTemplateName, | ||||
673 | /*AllowNonTemplates=*/!IsTemplateName); | ||||
674 | if (TypoCorrection Corrected = | ||||
675 | CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, | ||||
676 | CCC, CTK_ErrorRecovery)) { | ||||
677 | // FIXME: Support error recovery for the template-name case. | ||||
678 | bool CanRecover = !IsTemplateName; | ||||
679 | if (Corrected.isKeyword()) { | ||||
680 | // We corrected to a keyword. | ||||
681 | diagnoseTypo(Corrected, | ||||
682 | PDiag(IsTemplateName ? diag::err_no_template_suggest | ||||
683 | : diag::err_unknown_typename_suggest) | ||||
684 | << II); | ||||
685 | II = Corrected.getCorrectionAsIdentifierInfo(); | ||||
686 | } else { | ||||
687 | // We found a similarly-named type or interface; suggest that. | ||||
688 | if (!SS || !SS->isSet()) { | ||||
689 | diagnoseTypo(Corrected, | ||||
690 | PDiag(IsTemplateName ? diag::err_no_template_suggest | ||||
691 | : diag::err_unknown_typename_suggest) | ||||
692 | << II, CanRecover); | ||||
693 | } else if (DeclContext *DC = computeDeclContext(*SS, false)) { | ||||
694 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||
695 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||
696 | II->getName().equals(CorrectedStr); | ||||
697 | diagnoseTypo(Corrected, | ||||
698 | PDiag(IsTemplateName | ||||
699 | ? diag::err_no_member_template_suggest | ||||
700 | : diag::err_unknown_nested_typename_suggest) | ||||
701 | << II << DC << DroppedSpecifier << SS->getRange(), | ||||
702 | CanRecover); | ||||
703 | } else { | ||||
704 | llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 704); | ||||
705 | } | ||||
706 | |||||
707 | if (!CanRecover) | ||||
708 | return; | ||||
709 | |||||
710 | CXXScopeSpec tmpSS; | ||||
711 | if (Corrected.getCorrectionSpecifier()) | ||||
712 | tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | ||||
713 | SourceRange(IILoc)); | ||||
714 | // FIXME: Support class template argument deduction here. | ||||
715 | SuggestedType = | ||||
716 | getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, | ||||
717 | tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, | ||||
718 | /*IsCtorOrDtorName=*/false, | ||||
719 | /*WantNontrivialTypeSourceInfo=*/true); | ||||
720 | } | ||||
721 | return; | ||||
722 | } | ||||
723 | |||||
724 | if (getLangOpts().CPlusPlus && !IsTemplateName) { | ||||
725 | // See if II is a class template that the user forgot to pass arguments to. | ||||
726 | UnqualifiedId Name; | ||||
727 | Name.setIdentifier(II, IILoc); | ||||
728 | CXXScopeSpec EmptySS; | ||||
729 | TemplateTy TemplateResult; | ||||
730 | bool MemberOfUnknownSpecialization; | ||||
731 | if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, | ||||
732 | Name, nullptr, true, TemplateResult, | ||||
733 | MemberOfUnknownSpecialization) == TNK_Type_template) { | ||||
734 | diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); | ||||
735 | return; | ||||
736 | } | ||||
737 | } | ||||
738 | |||||
739 | // FIXME: Should we move the logic that tries to recover from a missing tag | ||||
740 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? | ||||
741 | |||||
742 | if (!SS || (!SS->isSet() && !SS->isInvalid())) | ||||
743 | Diag(IILoc, IsTemplateName ? diag::err_no_template | ||||
744 | : diag::err_unknown_typename) | ||||
745 | << II; | ||||
746 | else if (DeclContext *DC = computeDeclContext(*SS, false)) | ||||
747 | Diag(IILoc, IsTemplateName ? diag::err_no_member_template | ||||
748 | : diag::err_typename_nested_not_found) | ||||
749 | << II << DC << SS->getRange(); | ||||
750 | else if (isDependentScopeSpecifier(*SS)) { | ||||
751 | unsigned DiagID = diag::err_typename_missing; | ||||
752 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) | ||||
753 | DiagID = diag::ext_typename_missing; | ||||
754 | |||||
755 | Diag(SS->getRange().getBegin(), DiagID) | ||||
756 | << SS->getScopeRep() << II->getName() | ||||
757 | << SourceRange(SS->getRange().getBegin(), IILoc) | ||||
758 | << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); | ||||
759 | SuggestedType = ActOnTypenameType(S, SourceLocation(), | ||||
760 | *SS, *II, IILoc).get(); | ||||
761 | } else { | ||||
762 | assert(SS && SS->isInvalid() &&((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed" ) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 763, __PRETTY_FUNCTION__)) | ||||
763 | "Invalid scope specifier has already been diagnosed")((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed" ) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 763, __PRETTY_FUNCTION__)); | ||||
764 | } | ||||
765 | } | ||||
766 | |||||
767 | /// Determine whether the given result set contains either a type name | ||||
768 | /// or | ||||
769 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { | ||||
770 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && | ||||
771 | NextToken.is(tok::less); | ||||
772 | |||||
773 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { | ||||
774 | if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) | ||||
775 | return true; | ||||
776 | |||||
777 | if (CheckTemplate && isa<TemplateDecl>(*I)) | ||||
778 | return true; | ||||
779 | } | ||||
780 | |||||
781 | return false; | ||||
782 | } | ||||
783 | |||||
784 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, | ||||
785 | Scope *S, CXXScopeSpec &SS, | ||||
786 | IdentifierInfo *&Name, | ||||
787 | SourceLocation NameLoc) { | ||||
788 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); | ||||
789 | SemaRef.LookupParsedName(R, S, &SS); | ||||
790 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { | ||||
791 | StringRef FixItTagName; | ||||
792 | switch (Tag->getTagKind()) { | ||||
793 | case TTK_Class: | ||||
794 | FixItTagName = "class "; | ||||
795 | break; | ||||
796 | |||||
797 | case TTK_Enum: | ||||
798 | FixItTagName = "enum "; | ||||
799 | break; | ||||
800 | |||||
801 | case TTK_Struct: | ||||
802 | FixItTagName = "struct "; | ||||
803 | break; | ||||
804 | |||||
805 | case TTK_Interface: | ||||
806 | FixItTagName = "__interface "; | ||||
807 | break; | ||||
808 | |||||
809 | case TTK_Union: | ||||
810 | FixItTagName = "union "; | ||||
811 | break; | ||||
812 | } | ||||
813 | |||||
814 | StringRef TagName = FixItTagName.drop_back(); | ||||
815 | SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) | ||||
816 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus | ||||
817 | << FixItHint::CreateInsertion(NameLoc, FixItTagName); | ||||
818 | |||||
819 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); | ||||
820 | I != IEnd; ++I) | ||||
821 | SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) | ||||
822 | << Name << TagName; | ||||
823 | |||||
824 | // Replace lookup results with just the tag decl. | ||||
825 | Result.clear(Sema::LookupTagName); | ||||
826 | SemaRef.LookupParsedName(Result, S, &SS); | ||||
827 | return true; | ||||
828 | } | ||||
829 | |||||
830 | return false; | ||||
831 | } | ||||
832 | |||||
833 | /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. | ||||
834 | static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, | ||||
835 | QualType T, SourceLocation NameLoc) { | ||||
836 | ASTContext &Context = S.Context; | ||||
837 | |||||
838 | TypeLocBuilder Builder; | ||||
839 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | ||||
840 | |||||
841 | T = S.getElaboratedType(ETK_None, SS, T); | ||||
842 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | ||||
843 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | ||||
844 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
845 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||
846 | } | ||||
847 | |||||
848 | Sema::NameClassification | ||||
849 | Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, | ||||
850 | SourceLocation NameLoc, const Token &NextToken, | ||||
851 | bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) { | ||||
852 | DeclarationNameInfo NameInfo(Name, NameLoc); | ||||
853 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||
854 | |||||
855 | if (NextToken.is(tok::coloncolon)) { | ||||
856 | NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); | ||||
857 | BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); | ||||
858 | } else if (getLangOpts().CPlusPlus && SS.isSet() && | ||||
859 | isCurrentClassName(*Name, S, &SS)) { | ||||
860 | // Per [class.qual]p2, this names the constructors of SS, not the | ||||
861 | // injected-class-name. We don't have a classification for that. | ||||
862 | // There's not much point caching this result, since the parser | ||||
863 | // will reject it later. | ||||
864 | return NameClassification::Unknown(); | ||||
865 | } | ||||
866 | |||||
867 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | ||||
868 | LookupParsedName(Result, S, &SS, !CurMethod); | ||||
869 | |||||
870 | // For unqualified lookup in a class template in MSVC mode, look into | ||||
871 | // dependent base classes where the primary class template is known. | ||||
872 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||
873 | if (ParsedType TypeInBase = | ||||
874 | recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) | ||||
875 | return TypeInBase; | ||||
876 | } | ||||
877 | |||||
878 | // Perform lookup for Objective-C instance variables (including automatically | ||||
879 | // synthesized instance variables), if we're in an Objective-C method. | ||||
880 | // FIXME: This lookup really, really needs to be folded in to the normal | ||||
881 | // unqualified lookup mechanism. | ||||
882 | if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { | ||||
883 | ExprResult E = LookupInObjCMethod(Result, S, Name, true); | ||||
884 | if (E.get() || E.isInvalid()) | ||||
885 | return E; | ||||
886 | } | ||||
887 | |||||
888 | bool SecondTry = false; | ||||
889 | bool IsFilteredTemplateName = false; | ||||
890 | |||||
891 | Corrected: | ||||
892 | switch (Result.getResultKind()) { | ||||
893 | case LookupResult::NotFound: | ||||
894 | // If an unqualified-id is followed by a '(', then we have a function | ||||
895 | // call. | ||||
896 | if (!SS.isSet() && NextToken.is(tok::l_paren)) { | ||||
897 | // In C++, this is an ADL-only call. | ||||
898 | // FIXME: Reference? | ||||
899 | if (getLangOpts().CPlusPlus) | ||||
900 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); | ||||
901 | |||||
902 | // C90 6.3.2.2: | ||||
903 | // If the expression that precedes the parenthesized argument list in a | ||||
904 | // function call consists solely of an identifier, and if no | ||||
905 | // declaration is visible for this identifier, the identifier is | ||||
906 | // implicitly declared exactly as if, in the innermost block containing | ||||
907 | // the function call, the declaration | ||||
908 | // | ||||
909 | // extern int identifier (); | ||||
910 | // | ||||
911 | // appeared. | ||||
912 | // | ||||
913 | // We also allow this in C99 as an extension. | ||||
914 | if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { | ||||
915 | Result.addDecl(D); | ||||
916 | Result.resolveKind(); | ||||
917 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); | ||||
918 | } | ||||
919 | } | ||||
920 | |||||
921 | if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) { | ||||
922 | // In C++20 onwards, this could be an ADL-only call to a function | ||||
923 | // template, and we're required to assume that this is a template name. | ||||
924 | // | ||||
925 | // FIXME: Find a way to still do typo correction in this case. | ||||
926 | TemplateName Template = | ||||
927 | Context.getAssumedTemplateName(NameInfo.getName()); | ||||
928 | return NameClassification::UndeclaredTemplate(Template); | ||||
929 | } | ||||
930 | |||||
931 | // In C, we first see whether there is a tag type by the same name, in | ||||
932 | // which case it's likely that the user just forgot to write "enum", | ||||
933 | // "struct", or "union". | ||||
934 | if (!getLangOpts().CPlusPlus && !SecondTry && | ||||
935 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | ||||
936 | break; | ||||
937 | } | ||||
938 | |||||
939 | // Perform typo correction to determine if there is another name that is | ||||
940 | // close to this name. | ||||
941 | if (!SecondTry && CCC) { | ||||
942 | SecondTry = true; | ||||
943 | if (TypoCorrection Corrected = | ||||
944 | CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, | ||||
945 | &SS, *CCC, CTK_ErrorRecovery)) { | ||||
946 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; | ||||
947 | unsigned QualifiedDiag = diag::err_no_member_suggest; | ||||
948 | |||||
949 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); | ||||
950 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); | ||||
951 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||
952 | UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { | ||||
953 | UnqualifiedDiag = diag::err_no_template_suggest; | ||||
954 | QualifiedDiag = diag::err_no_member_template_suggest; | ||||
955 | } else if (UnderlyingFirstDecl && | ||||
956 | (isa<TypeDecl>(UnderlyingFirstDecl) || | ||||
957 | isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || | ||||
958 | isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { | ||||
959 | UnqualifiedDiag = diag::err_unknown_typename_suggest; | ||||
960 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; | ||||
961 | } | ||||
962 | |||||
963 | if (SS.isEmpty()) { | ||||
964 | diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); | ||||
965 | } else {// FIXME: is this even reachable? Test it. | ||||
966 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||
967 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||
968 | Name->getName().equals(CorrectedStr); | ||||
969 | diagnoseTypo(Corrected, PDiag(QualifiedDiag) | ||||
970 | << Name << computeDeclContext(SS, false) | ||||
971 | << DroppedSpecifier << SS.getRange()); | ||||
972 | } | ||||
973 | |||||
974 | // Update the name, so that the caller has the new name. | ||||
975 | Name = Corrected.getCorrectionAsIdentifierInfo(); | ||||
976 | |||||
977 | // Typo correction corrected to a keyword. | ||||
978 | if (Corrected.isKeyword()) | ||||
979 | return Name; | ||||
980 | |||||
981 | // Also update the LookupResult... | ||||
982 | // FIXME: This should probably go away at some point | ||||
983 | Result.clear(); | ||||
984 | Result.setLookupName(Corrected.getCorrection()); | ||||
985 | if (FirstDecl) | ||||
986 | Result.addDecl(FirstDecl); | ||||
987 | |||||
988 | // If we found an Objective-C instance variable, let | ||||
989 | // LookupInObjCMethod build the appropriate expression to | ||||
990 | // reference the ivar. | ||||
991 | // FIXME: This is a gross hack. | ||||
992 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { | ||||
993 | Result.clear(); | ||||
994 | ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); | ||||
995 | return E; | ||||
996 | } | ||||
997 | |||||
998 | goto Corrected; | ||||
999 | } | ||||
1000 | } | ||||
1001 | |||||
1002 | // We failed to correct; just fall through and let the parser deal with it. | ||||
1003 | Result.suppressDiagnostics(); | ||||
1004 | return NameClassification::Unknown(); | ||||
1005 | |||||
1006 | case LookupResult::NotFoundInCurrentInstantiation: { | ||||
1007 | // We performed name lookup into the current instantiation, and there were | ||||
1008 | // dependent bases, so we treat this result the same way as any other | ||||
1009 | // dependent nested-name-specifier. | ||||
1010 | |||||
1011 | // C++ [temp.res]p2: | ||||
1012 | // A name used in a template declaration or definition and that is | ||||
1013 | // dependent on a template-parameter is assumed not to name a type | ||||
1014 | // unless the applicable name lookup finds a type name or the name is | ||||
1015 | // qualified by the keyword typename. | ||||
1016 | // | ||||
1017 | // FIXME: If the next token is '<', we might want to ask the parser to | ||||
1018 | // perform some heroics to see if we actually have a | ||||
1019 | // template-argument-list, which would indicate a missing 'template' | ||||
1020 | // keyword here. | ||||
1021 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
1022 | NameInfo, IsAddressOfOperand, | ||||
1023 | /*TemplateArgs=*/nullptr); | ||||
1024 | } | ||||
1025 | |||||
1026 | case LookupResult::Found: | ||||
1027 | case LookupResult::FoundOverloaded: | ||||
1028 | case LookupResult::FoundUnresolvedValue: | ||||
1029 | break; | ||||
1030 | |||||
1031 | case LookupResult::Ambiguous: | ||||
1032 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||
1033 | hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, | ||||
1034 | /*AllowDependent=*/false)) { | ||||
1035 | // C++ [temp.local]p3: | ||||
1036 | // A lookup that finds an injected-class-name (10.2) can result in an | ||||
1037 | // ambiguity in certain cases (for example, if it is found in more than | ||||
1038 | // one base class). If all of the injected-class-names that are found | ||||
1039 | // refer to specializations of the same class template, and if the name | ||||
1040 | // is followed by a template-argument-list, the reference refers to the | ||||
1041 | // class template itself and not a specialization thereof, and is not | ||||
1042 | // ambiguous. | ||||
1043 | // | ||||
1044 | // This filtering can make an ambiguous result into an unambiguous one, | ||||
1045 | // so try again after filtering out template names. | ||||
1046 | FilterAcceptableTemplateNames(Result); | ||||
1047 | if (!Result.isAmbiguous()) { | ||||
1048 | IsFilteredTemplateName = true; | ||||
1049 | break; | ||||
1050 | } | ||||
1051 | } | ||||
1052 | |||||
1053 | // Diagnose the ambiguity and return an error. | ||||
1054 | return NameClassification::Error(); | ||||
1055 | } | ||||
1056 | |||||
1057 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||
1058 | (IsFilteredTemplateName || | ||||
1059 | hasAnyAcceptableTemplateNames( | ||||
1060 | Result, /*AllowFunctionTemplates=*/true, | ||||
1061 | /*AllowDependent=*/false, | ||||
1062 | /*AllowNonTemplateFunctions*/ !SS.isSet() && | ||||
1063 | getLangOpts().CPlusPlus2a))) { | ||||
1064 | // C++ [temp.names]p3: | ||||
1065 | // After name lookup (3.4) finds that a name is a template-name or that | ||||
1066 | // an operator-function-id or a literal- operator-id refers to a set of | ||||
1067 | // overloaded functions any member of which is a function template if | ||||
1068 | // this is followed by a <, the < is always taken as the delimiter of a | ||||
1069 | // template-argument-list and never as the less-than operator. | ||||
1070 | // C++2a [temp.names]p2: | ||||
1071 | // A name is also considered to refer to a template if it is an | ||||
1072 | // unqualified-id followed by a < and name lookup finds either one | ||||
1073 | // or more functions or finds nothing. | ||||
1074 | if (!IsFilteredTemplateName) | ||||
1075 | FilterAcceptableTemplateNames(Result); | ||||
1076 | |||||
1077 | bool IsFunctionTemplate; | ||||
1078 | bool IsVarTemplate; | ||||
1079 | TemplateName Template; | ||||
1080 | if (Result.end() - Result.begin() > 1) { | ||||
1081 | IsFunctionTemplate = true; | ||||
1082 | Template = Context.getOverloadedTemplateName(Result.begin(), | ||||
1083 | Result.end()); | ||||
1084 | } else if (!Result.empty()) { | ||||
1085 | auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( | ||||
1086 | *Result.begin(), /*AllowFunctionTemplates=*/true, | ||||
1087 | /*AllowDependent=*/false)); | ||||
1088 | IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); | ||||
1089 | IsVarTemplate = isa<VarTemplateDecl>(TD); | ||||
1090 | |||||
1091 | if (SS.isSet() && !SS.isInvalid()) | ||||
1092 | Template = | ||||
1093 | Context.getQualifiedTemplateName(SS.getScopeRep(), | ||||
1094 | /*TemplateKeyword=*/false, TD); | ||||
1095 | else | ||||
1096 | Template = TemplateName(TD); | ||||
1097 | } else { | ||||
1098 | // All results were non-template functions. This is a function template | ||||
1099 | // name. | ||||
1100 | IsFunctionTemplate = true; | ||||
1101 | Template = Context.getAssumedTemplateName(NameInfo.getName()); | ||||
1102 | } | ||||
1103 | |||||
1104 | if (IsFunctionTemplate) { | ||||
1105 | // Function templates always go through overload resolution, at which | ||||
1106 | // point we'll perform the various checks (e.g., accessibility) we need | ||||
1107 | // to based on which function we selected. | ||||
1108 | Result.suppressDiagnostics(); | ||||
1109 | |||||
1110 | return NameClassification::FunctionTemplate(Template); | ||||
1111 | } | ||||
1112 | |||||
1113 | return IsVarTemplate ? NameClassification::VarTemplate(Template) | ||||
1114 | : NameClassification::TypeTemplate(Template); | ||||
1115 | } | ||||
1116 | |||||
1117 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); | ||||
1118 | if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { | ||||
1119 | DiagnoseUseOfDecl(Type, NameLoc); | ||||
1120 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | ||||
1121 | QualType T = Context.getTypeDeclType(Type); | ||||
1122 | if (SS.isNotEmpty()) | ||||
1123 | return buildNestedType(*this, SS, T, NameLoc); | ||||
1124 | return ParsedType::make(T); | ||||
1125 | } | ||||
1126 | |||||
1127 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); | ||||
1128 | if (!Class) { | ||||
1129 | // FIXME: It's unfortunate that we don't have a Type node for handling this. | ||||
1130 | if (ObjCCompatibleAliasDecl *Alias = | ||||
1131 | dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) | ||||
1132 | Class = Alias->getClassInterface(); | ||||
1133 | } | ||||
1134 | |||||
1135 | if (Class) { | ||||
1136 | DiagnoseUseOfDecl(Class, NameLoc); | ||||
1137 | |||||
1138 | if (NextToken.is(tok::period)) { | ||||
1139 | // Interface. <something> is parsed as a property reference expression. | ||||
1140 | // Just return "unknown" as a fall-through for now. | ||||
1141 | Result.suppressDiagnostics(); | ||||
1142 | return NameClassification::Unknown(); | ||||
1143 | } | ||||
1144 | |||||
1145 | QualType T = Context.getObjCInterfaceType(Class); | ||||
1146 | return ParsedType::make(T); | ||||
1147 | } | ||||
1148 | |||||
1149 | // We can have a type template here if we're classifying a template argument. | ||||
1150 | if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && | ||||
1151 | !isa<VarTemplateDecl>(FirstDecl)) | ||||
1152 | return NameClassification::TypeTemplate( | ||||
1153 | TemplateName(cast<TemplateDecl>(FirstDecl))); | ||||
1154 | |||||
1155 | // Check for a tag type hidden by a non-type decl in a few cases where it | ||||
1156 | // seems likely a type is wanted instead of the non-type that was found. | ||||
1157 | bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); | ||||
1158 | if ((NextToken.is(tok::identifier) || | ||||
1159 | (NextIsOp && | ||||
1160 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && | ||||
1161 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | ||||
1162 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); | ||||
1163 | DiagnoseUseOfDecl(Type, NameLoc); | ||||
1164 | QualType T = Context.getTypeDeclType(Type); | ||||
1165 | if (SS.isNotEmpty()) | ||||
1166 | return buildNestedType(*this, SS, T, NameLoc); | ||||
1167 | return ParsedType::make(T); | ||||
1168 | } | ||||
1169 | |||||
1170 | if (FirstDecl->isCXXClassMember()) | ||||
1171 | return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, | ||||
1172 | nullptr, S); | ||||
1173 | |||||
1174 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | ||||
1175 | return BuildDeclarationNameExpr(SS, Result, ADL); | ||||
1176 | } | ||||
1177 | |||||
1178 | Sema::TemplateNameKindForDiagnostics | ||||
1179 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { | ||||
1180 | auto *TD = Name.getAsTemplateDecl(); | ||||
1181 | if (!TD) | ||||
1182 | return TemplateNameKindForDiagnostics::DependentTemplate; | ||||
1183 | if (isa<ClassTemplateDecl>(TD)) | ||||
1184 | return TemplateNameKindForDiagnostics::ClassTemplate; | ||||
1185 | if (isa<FunctionTemplateDecl>(TD)) | ||||
1186 | return TemplateNameKindForDiagnostics::FunctionTemplate; | ||||
1187 | if (isa<VarTemplateDecl>(TD)) | ||||
1188 | return TemplateNameKindForDiagnostics::VarTemplate; | ||||
1189 | if (isa<TypeAliasTemplateDecl>(TD)) | ||||
1190 | return TemplateNameKindForDiagnostics::AliasTemplate; | ||||
1191 | if (isa<TemplateTemplateParmDecl>(TD)) | ||||
1192 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; | ||||
1193 | if (isa<ConceptDecl>(TD)) | ||||
1194 | return TemplateNameKindForDiagnostics::Concept; | ||||
1195 | return TemplateNameKindForDiagnostics::DependentTemplate; | ||||
1196 | } | ||||
1197 | |||||
1198 | // Determines the context to return to after temporarily entering a | ||||
1199 | // context. This depends in an unnecessarily complicated way on the | ||||
1200 | // exact ordering of callbacks from the parser. | ||||
1201 | DeclContext *Sema::getContainingDC(DeclContext *DC) { | ||||
1202 | |||||
1203 | // Functions defined inline within classes aren't parsed until we've | ||||
1204 | // finished parsing the top-level class, so the top-level class is | ||||
1205 | // the context we'll need to return to. | ||||
1206 | // A Lambda call operator whose parent is a class must not be treated | ||||
1207 | // as an inline member function. A Lambda can be used legally | ||||
1208 | // either as an in-class member initializer or a default argument. These | ||||
1209 | // are parsed once the class has been marked complete and so the containing | ||||
1210 | // context would be the nested class (when the lambda is defined in one); | ||||
1211 | // If the class is not complete, then the lambda is being used in an | ||||
1212 | // ill-formed fashion (such as to specify the width of a bit-field, or | ||||
1213 | // in an array-bound) - in which case we still want to return the | ||||
1214 | // lexically containing DC (which could be a nested class). | ||||
1215 | if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { | ||||
1216 | DC = DC->getLexicalParent(); | ||||
1217 | |||||
1218 | // A function not defined within a class will always return to its | ||||
1219 | // lexical context. | ||||
1220 | if (!isa<CXXRecordDecl>(DC)) | ||||
1221 | return DC; | ||||
1222 | |||||
1223 | // A C++ inline method/friend is parsed *after* the topmost class | ||||
1224 | // it was declared in is fully parsed ("complete"); the topmost | ||||
1225 | // class is the context we need to return to. | ||||
1226 | while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) | ||||
1227 | DC = RD; | ||||
1228 | |||||
1229 | // Return the declaration context of the topmost class the inline method is | ||||
1230 | // declared in. | ||||
1231 | return DC; | ||||
1232 | } | ||||
1233 | |||||
1234 | return DC->getLexicalParent(); | ||||
1235 | } | ||||
1236 | |||||
1237 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { | ||||
1238 | assert(getContainingDC(DC) == CurContext &&((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1239, __PRETTY_FUNCTION__)) | ||||
1239 | "The next DeclContext should be lexically contained in the current one.")((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1239, __PRETTY_FUNCTION__)); | ||||
1240 | CurContext = DC; | ||||
1241 | S->setEntity(DC); | ||||
1242 | } | ||||
1243 | |||||
1244 | void Sema::PopDeclContext() { | ||||
1245 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1245, __PRETTY_FUNCTION__)); | ||||
1246 | |||||
1247 | CurContext = getContainingDC(CurContext); | ||||
1248 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1248, __PRETTY_FUNCTION__)); | ||||
1249 | } | ||||
1250 | |||||
1251 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, | ||||
1252 | Decl *D) { | ||||
1253 | // Unlike PushDeclContext, the context to which we return is not necessarily | ||||
1254 | // the containing DC of TD, because the new context will be some pre-existing | ||||
1255 | // TagDecl definition instead of a fresh one. | ||||
1256 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); | ||||
1257 | CurContext = cast<TagDecl>(D)->getDefinition(); | ||||
1258 | assert(CurContext && "skipping definition of undefined tag")((CurContext && "skipping definition of undefined tag" ) ? static_cast<void> (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1258, __PRETTY_FUNCTION__)); | ||||
1259 | // Start lookups from the parent of the current context; we don't want to look | ||||
1260 | // into the pre-existing complete definition. | ||||
1261 | S->setEntity(CurContext->getLookupParent()); | ||||
1262 | return Result; | ||||
1263 | } | ||||
1264 | |||||
1265 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { | ||||
1266 | CurContext = static_cast<decltype(CurContext)>(Context); | ||||
1267 | } | ||||
1268 | |||||
1269 | /// EnterDeclaratorContext - Used when we must lookup names in the context | ||||
1270 | /// of a declarator's nested name specifier. | ||||
1271 | /// | ||||
1272 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { | ||||
1273 | // C++0x [basic.lookup.unqual]p13: | ||||
1274 | // A name used in the definition of a static data member of class | ||||
1275 | // X (after the qualified-id of the static member) is looked up as | ||||
1276 | // if the name was used in a member function of X. | ||||
1277 | // C++0x [basic.lookup.unqual]p14: | ||||
1278 | // If a variable member of a namespace is defined outside of the | ||||
1279 | // scope of its namespace then any name used in the definition of | ||||
1280 | // the variable member (after the declarator-id) is looked up as | ||||
1281 | // if the definition of the variable member occurred in its | ||||
1282 | // namespace. | ||||
1283 | // Both of these imply that we should push a scope whose context | ||||
1284 | // is the semantic context of the declaration. We can't use | ||||
1285 | // PushDeclContext here because that context is not necessarily | ||||
1286 | // lexically contained in the current context. Fortunately, | ||||
1287 | // the containing scope should have the appropriate information. | ||||
1288 | |||||
1289 | assert(!S->getEntity() && "scope already has entity")((!S->getEntity() && "scope already has entity") ? static_cast<void> (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1289, __PRETTY_FUNCTION__)); | ||||
1290 | |||||
1291 | #ifndef NDEBUG | ||||
1292 | Scope *Ancestor = S->getParent(); | ||||
1293 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | ||||
1294 | assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((Ancestor->getEntity() == CurContext && "ancestor context mismatch" ) ? static_cast<void> (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1294, __PRETTY_FUNCTION__)); | ||||
1295 | #endif | ||||
1296 | |||||
1297 | CurContext = DC; | ||||
1298 | S->setEntity(DC); | ||||
1299 | } | ||||
1300 | |||||
1301 | void Sema::ExitDeclaratorContext(Scope *S) { | ||||
1302 | assert(S->getEntity() == CurContext && "Context imbalance!")((S->getEntity() == CurContext && "Context imbalance!" ) ? static_cast<void> (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1302, __PRETTY_FUNCTION__)); | ||||
1303 | |||||
1304 | // Switch back to the lexical context. The safety of this is | ||||
1305 | // enforced by an assert in EnterDeclaratorContext. | ||||
1306 | Scope *Ancestor = S->getParent(); | ||||
1307 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | ||||
1308 | CurContext = Ancestor->getEntity(); | ||||
1309 | |||||
1310 | // We don't need to do anything with the scope, which is going to | ||||
1311 | // disappear. | ||||
1312 | } | ||||
1313 | |||||
1314 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { | ||||
1315 | // We assume that the caller has already called | ||||
1316 | // ActOnReenterTemplateScope so getTemplatedDecl() works. | ||||
1317 | FunctionDecl *FD = D->getAsFunction(); | ||||
1318 | if (!FD) | ||||
1319 | return; | ||||
1320 | |||||
1321 | // Same implementation as PushDeclContext, but enters the context | ||||
1322 | // from the lexical parent, rather than the top-level class. | ||||
1323 | assert(CurContext == FD->getLexicalParent() &&((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1324, __PRETTY_FUNCTION__)) | ||||
1324 | "The next DeclContext should be lexically contained in the current one.")((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1324, __PRETTY_FUNCTION__)); | ||||
1325 | CurContext = FD; | ||||
1326 | S->setEntity(CurContext); | ||||
1327 | |||||
1328 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { | ||||
1329 | ParmVarDecl *Param = FD->getParamDecl(P); | ||||
1330 | // If the parameter has an identifier, then add it to the scope | ||||
1331 | if (Param->getIdentifier()) { | ||||
1332 | S->AddDecl(Param); | ||||
1333 | IdResolver.AddDecl(Param); | ||||
1334 | } | ||||
1335 | } | ||||
1336 | } | ||||
1337 | |||||
1338 | void Sema::ActOnExitFunctionContext() { | ||||
1339 | // Same implementation as PopDeclContext, but returns to the lexical parent, | ||||
1340 | // rather than the top-level class. | ||||
1341 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1341, __PRETTY_FUNCTION__)); | ||||
1342 | CurContext = CurContext->getLexicalParent(); | ||||
1343 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1343, __PRETTY_FUNCTION__)); | ||||
1344 | } | ||||
1345 | |||||
1346 | /// Determine whether we allow overloading of the function | ||||
1347 | /// PrevDecl with another declaration. | ||||
1348 | /// | ||||
1349 | /// This routine determines whether overloading is possible, not | ||||
1350 | /// whether some new function is actually an overload. It will return | ||||
1351 | /// true in C++ (where we can always provide overloads) or, as an | ||||
1352 | /// extension, in C when the previous function is already an | ||||
1353 | /// overloaded function declaration or has the "overloadable" | ||||
1354 | /// attribute. | ||||
1355 | static bool AllowOverloadingOfFunction(LookupResult &Previous, | ||||
1356 | ASTContext &Context, | ||||
1357 | const FunctionDecl *New) { | ||||
1358 | if (Context.getLangOpts().CPlusPlus) | ||||
1359 | return true; | ||||
1360 | |||||
1361 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) | ||||
1362 | return true; | ||||
1363 | |||||
1364 | return Previous.getResultKind() == LookupResult::Found && | ||||
1365 | (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || | ||||
1366 | New->hasAttr<OverloadableAttr>()); | ||||
1367 | } | ||||
1368 | |||||
1369 | /// Add this decl to the scope shadowed decl chains. | ||||
1370 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { | ||||
1371 | // Move up the scope chain until we find the nearest enclosing | ||||
1372 | // non-transparent context. The declaration will be introduced into this | ||||
1373 | // scope. | ||||
1374 | while (S->getEntity() && S->getEntity()->isTransparentContext()) | ||||
1375 | S = S->getParent(); | ||||
1376 | |||||
1377 | // Add scoped declarations into their context, so that they can be | ||||
1378 | // found later. Declarations without a context won't be inserted | ||||
1379 | // into any context. | ||||
1380 | if (AddToContext) | ||||
1381 | CurContext->addDecl(D); | ||||
1382 | |||||
1383 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they | ||||
1384 | // are function-local declarations. | ||||
1385 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && | ||||
1386 | !D->getDeclContext()->getRedeclContext()->Equals( | ||||
1387 | D->getLexicalDeclContext()->getRedeclContext()) && | ||||
1388 | !D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||
1389 | return; | ||||
1390 | |||||
1391 | // Template instantiations should also not be pushed into scope. | ||||
1392 | if (isa<FunctionDecl>(D) && | ||||
1393 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) | ||||
1394 | return; | ||||
1395 | |||||
1396 | // If this replaces anything in the current scope, | ||||
1397 | IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), | ||||
1398 | IEnd = IdResolver.end(); | ||||
1399 | for (; I != IEnd; ++I) { | ||||
1400 | if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { | ||||
1401 | S->RemoveDecl(*I); | ||||
1402 | IdResolver.RemoveDecl(*I); | ||||
1403 | |||||
1404 | // Should only need to replace one decl. | ||||
1405 | break; | ||||
1406 | } | ||||
1407 | } | ||||
1408 | |||||
1409 | S->AddDecl(D); | ||||
1410 | |||||
1411 | if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { | ||||
1412 | // Implicitly-generated labels may end up getting generated in an order that | ||||
1413 | // isn't strictly lexical, which breaks name lookup. Be careful to insert | ||||
1414 | // the label at the appropriate place in the identifier chain. | ||||
1415 | for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { | ||||
1416 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); | ||||
1417 | if (IDC == CurContext) { | ||||
1418 | if (!S->isDeclScope(*I)) | ||||
1419 | continue; | ||||
1420 | } else if (IDC->Encloses(CurContext)) | ||||
1421 | break; | ||||
1422 | } | ||||
1423 | |||||
1424 | IdResolver.InsertDeclAfter(I, D); | ||||
1425 | } else { | ||||
1426 | IdResolver.AddDecl(D); | ||||
1427 | } | ||||
1428 | } | ||||
1429 | |||||
1430 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, | ||||
1431 | bool AllowInlineNamespace) { | ||||
1432 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); | ||||
1433 | } | ||||
1434 | |||||
1435 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { | ||||
1436 | DeclContext *TargetDC = DC->getPrimaryContext(); | ||||
1437 | do { | ||||
1438 | if (DeclContext *ScopeDC = S->getEntity()) | ||||
1439 | if (ScopeDC->getPrimaryContext() == TargetDC) | ||||
1440 | return S; | ||||
1441 | } while ((S = S->getParent())); | ||||
1442 | |||||
1443 | return nullptr; | ||||
1444 | } | ||||
1445 | |||||
1446 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, | ||||
1447 | DeclContext*, | ||||
1448 | ASTContext&); | ||||
1449 | |||||
1450 | /// Filters out lookup results that don't fall within the given scope | ||||
1451 | /// as determined by isDeclInScope. | ||||
1452 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, | ||||
1453 | bool ConsiderLinkage, | ||||
1454 | bool AllowInlineNamespace) { | ||||
1455 | LookupResult::Filter F = R.makeFilter(); | ||||
1456 | while (F.hasNext()) { | ||||
1457 | NamedDecl *D = F.next(); | ||||
1458 | |||||
1459 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) | ||||
1460 | continue; | ||||
1461 | |||||
1462 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) | ||||
1463 | continue; | ||||
1464 | |||||
1465 | F.erase(); | ||||
1466 | } | ||||
1467 | |||||
1468 | F.done(); | ||||
1469 | } | ||||
1470 | |||||
1471 | /// We've determined that \p New is a redeclaration of \p Old. Check that they | ||||
1472 | /// have compatible owning modules. | ||||
1473 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { | ||||
1474 | // FIXME: The Modules TS is not clear about how friend declarations are | ||||
1475 | // to be treated. It's not meaningful to have different owning modules for | ||||
1476 | // linkage in redeclarations of the same entity, so for now allow the | ||||
1477 | // redeclaration and change the owning modules to match. | ||||
1478 | if (New->getFriendObjectKind() && | ||||
1479 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { | ||||
1480 | New->setLocalOwningModule(Old->getOwningModule()); | ||||
1481 | makeMergedDefinitionVisible(New); | ||||
1482 | return false; | ||||
1483 | } | ||||
1484 | |||||
1485 | Module *NewM = New->getOwningModule(); | ||||
1486 | Module *OldM = Old->getOwningModule(); | ||||
1487 | |||||
1488 | if (NewM && NewM->Kind == Module::PrivateModuleFragment) | ||||
1489 | NewM = NewM->Parent; | ||||
1490 | if (OldM && OldM->Kind == Module::PrivateModuleFragment) | ||||
1491 | OldM = OldM->Parent; | ||||
1492 | |||||
1493 | if (NewM == OldM) | ||||
1494 | return false; | ||||
1495 | |||||
1496 | bool NewIsModuleInterface = NewM && NewM->isModulePurview(); | ||||
1497 | bool OldIsModuleInterface = OldM && OldM->isModulePurview(); | ||||
1498 | if (NewIsModuleInterface || OldIsModuleInterface) { | ||||
1499 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: | ||||
1500 | // if a declaration of D [...] appears in the purview of a module, all | ||||
1501 | // other such declarations shall appear in the purview of the same module | ||||
1502 | Diag(New->getLocation(), diag::err_mismatched_owning_module) | ||||
1503 | << New | ||||
1504 | << NewIsModuleInterface | ||||
1505 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "") | ||||
1506 | << OldIsModuleInterface | ||||
1507 | << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); | ||||
1508 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
1509 | New->setInvalidDecl(); | ||||
1510 | return true; | ||||
1511 | } | ||||
1512 | |||||
1513 | return false; | ||||
1514 | } | ||||
1515 | |||||
1516 | static bool isUsingDecl(NamedDecl *D) { | ||||
1517 | return isa<UsingShadowDecl>(D) || | ||||
1518 | isa<UnresolvedUsingTypenameDecl>(D) || | ||||
1519 | isa<UnresolvedUsingValueDecl>(D); | ||||
1520 | } | ||||
1521 | |||||
1522 | /// Removes using shadow declarations from the lookup results. | ||||
1523 | static void RemoveUsingDecls(LookupResult &R) { | ||||
1524 | LookupResult::Filter F = R.makeFilter(); | ||||
1525 | while (F.hasNext()) | ||||
1526 | if (isUsingDecl(F.next())) | ||||
1527 | F.erase(); | ||||
1528 | |||||
1529 | F.done(); | ||||
1530 | } | ||||
1531 | |||||
1532 | /// Check for this common pattern: | ||||
1533 | /// @code | ||||
1534 | /// class S { | ||||
1535 | /// S(const S&); // DO NOT IMPLEMENT | ||||
1536 | /// void operator=(const S&); // DO NOT IMPLEMENT | ||||
1537 | /// }; | ||||
1538 | /// @endcode | ||||
1539 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { | ||||
1540 | // FIXME: Should check for private access too but access is set after we get | ||||
1541 | // the decl here. | ||||
1542 | if (D->doesThisDeclarationHaveABody()) | ||||
1543 | return false; | ||||
1544 | |||||
1545 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) | ||||
1546 | return CD->isCopyConstructor(); | ||||
1547 | return D->isCopyAssignmentOperator(); | ||||
1548 | } | ||||
1549 | |||||
1550 | // We need this to handle | ||||
1551 | // | ||||
1552 | // typedef struct { | ||||
1553 | // void *foo() { return 0; } | ||||
1554 | // } A; | ||||
1555 | // | ||||
1556 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' | ||||
1557 | // for example. If 'A', foo will have external linkage. If we have '*A', | ||||
1558 | // foo will have no linkage. Since we can't know until we get to the end | ||||
1559 | // of the typedef, this function finds out if D might have non-external linkage. | ||||
1560 | // Callers should verify at the end of the TU if it D has external linkage or | ||||
1561 | // not. | ||||
1562 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { | ||||
1563 | const DeclContext *DC = D->getDeclContext(); | ||||
1564 | while (!DC->isTranslationUnit()) { | ||||
1565 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ | ||||
1566 | if (!RD->hasNameForLinkage()) | ||||
1567 | return true; | ||||
1568 | } | ||||
1569 | DC = DC->getParent(); | ||||
1570 | } | ||||
1571 | |||||
1572 | return !D->isExternallyVisible(); | ||||
1573 | } | ||||
1574 | |||||
1575 | // FIXME: This needs to be refactored; some other isInMainFile users want | ||||
1576 | // these semantics. | ||||
1577 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { | ||||
1578 | if (S.TUKind != TU_Complete) | ||||
1579 | return false; | ||||
1580 | return S.SourceMgr.isInMainFile(Loc); | ||||
1581 | } | ||||
1582 | |||||
1583 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { | ||||
1584 | assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1584, __PRETTY_FUNCTION__)); | ||||
1585 | |||||
1586 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) | ||||
1587 | return false; | ||||
1588 | |||||
1589 | // Ignore all entities declared within templates, and out-of-line definitions | ||||
1590 | // of members of class templates. | ||||
1591 | if (D->getDeclContext()->isDependentContext() || | ||||
1592 | D->getLexicalDeclContext()->isDependentContext()) | ||||
1593 | return false; | ||||
1594 | |||||
1595 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
1596 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | ||||
1597 | return false; | ||||
1598 | // A non-out-of-line declaration of a member specialization was implicitly | ||||
1599 | // instantiated; it's the out-of-line declaration that we're interested in. | ||||
1600 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | ||||
1601 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) | ||||
1602 | return false; | ||||
1603 | |||||
1604 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||
1605 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) | ||||
1606 | return false; | ||||
1607 | } else { | ||||
1608 | // 'static inline' functions are defined in headers; don't warn. | ||||
1609 | if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) | ||||
1610 | return false; | ||||
1611 | } | ||||
1612 | |||||
1613 | if (FD->doesThisDeclarationHaveABody() && | ||||
1614 | Context.DeclMustBeEmitted(FD)) | ||||
1615 | return false; | ||||
1616 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
1617 | // Constants and utility variables are defined in headers with internal | ||||
1618 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker | ||||
1619 | // like "inline".) | ||||
1620 | if (!isMainFileLoc(*this, VD->getLocation())) | ||||
1621 | return false; | ||||
1622 | |||||
1623 | if (Context.DeclMustBeEmitted(VD)) | ||||
1624 | return false; | ||||
1625 | |||||
1626 | if (VD->isStaticDataMember() && | ||||
1627 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | ||||
1628 | return false; | ||||
1629 | if (VD->isStaticDataMember() && | ||||
1630 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | ||||
1631 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) | ||||
1632 | return false; | ||||
1633 | |||||
1634 | if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) | ||||
1635 | return false; | ||||
1636 | } else { | ||||
1637 | return false; | ||||
1638 | } | ||||
1639 | |||||
1640 | // Only warn for unused decls internal to the translation unit. | ||||
1641 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function | ||||
1642 | // for inline functions defined in the main source file, for instance. | ||||
1643 | return mightHaveNonExternalLinkage(D); | ||||
1644 | } | ||||
1645 | |||||
1646 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { | ||||
1647 | if (!D) | ||||
1648 | return; | ||||
1649 | |||||
1650 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
1651 | const FunctionDecl *First = FD->getFirstDecl(); | ||||
1652 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | ||||
1653 | return; // First should already be in the vector. | ||||
1654 | } | ||||
1655 | |||||
1656 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
1657 | const VarDecl *First = VD->getFirstDecl(); | ||||
1658 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | ||||
1659 | return; // First should already be in the vector. | ||||
1660 | } | ||||
1661 | |||||
1662 | if (ShouldWarnIfUnusedFileScopedDecl(D)) | ||||
1663 | UnusedFileScopedDecls.push_back(D); | ||||
1664 | } | ||||
1665 | |||||
1666 | static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { | ||||
1667 | if (D->isInvalidDecl()) | ||||
1668 | return false; | ||||
1669 | |||||
1670 | bool Referenced = false; | ||||
1671 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) { | ||||
1672 | // For a decomposition declaration, warn if none of the bindings are | ||||
1673 | // referenced, instead of if the variable itself is referenced (which | ||||
1674 | // it is, by the bindings' expressions). | ||||
1675 | for (auto *BD : DD->bindings()) { | ||||
1676 | if (BD->isReferenced()) { | ||||
1677 | Referenced = true; | ||||
1678 | break; | ||||
1679 | } | ||||
1680 | } | ||||
1681 | } else if (!D->getDeclName()) { | ||||
1682 | return false; | ||||
1683 | } else if (D->isReferenced() || D->isUsed()) { | ||||
1684 | Referenced = true; | ||||
1685 | } | ||||
1686 | |||||
1687 | if (Referenced || D->hasAttr<UnusedAttr>() || | ||||
1688 | D->hasAttr<ObjCPreciseLifetimeAttr>()) | ||||
1689 | return false; | ||||
1690 | |||||
1691 | if (isa<LabelDecl>(D)) | ||||
1692 | return true; | ||||
1693 | |||||
1694 | // Except for labels, we only care about unused decls that are local to | ||||
1695 | // functions. | ||||
1696 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); | ||||
1697 | if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) | ||||
1698 | // For dependent types, the diagnostic is deferred. | ||||
1699 | WithinFunction = | ||||
1700 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); | ||||
1701 | if (!WithinFunction) | ||||
1702 | return false; | ||||
1703 | |||||
1704 | if (isa<TypedefNameDecl>(D)) | ||||
1705 | return true; | ||||
1706 | |||||
1707 | // White-list anything that isn't a local variable. | ||||
1708 | if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) | ||||
1709 | return false; | ||||
1710 | |||||
1711 | // Types of valid local variables should be complete, so this should succeed. | ||||
1712 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
1713 | |||||
1714 | // White-list anything with an __attribute__((unused)) type. | ||||
1715 | const auto *Ty = VD->getType().getTypePtr(); | ||||
1716 | |||||
1717 | // Only look at the outermost level of typedef. | ||||
1718 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { | ||||
1719 | if (TT->getDecl()->hasAttr<UnusedAttr>()) | ||||
1720 | return false; | ||||
1721 | } | ||||
1722 | |||||
1723 | // If we failed to complete the type for some reason, or if the type is | ||||
1724 | // dependent, don't diagnose the variable. | ||||
1725 | if (Ty->isIncompleteType() || Ty->isDependentType()) | ||||
1726 | return false; | ||||
1727 | |||||
1728 | // Look at the element type to ensure that the warning behaviour is | ||||
1729 | // consistent for both scalars and arrays. | ||||
1730 | Ty = Ty->getBaseElementTypeUnsafe(); | ||||
1731 | |||||
1732 | if (const TagType *TT = Ty->getAs<TagType>()) { | ||||
1733 | const TagDecl *Tag = TT->getDecl(); | ||||
1734 | if (Tag->hasAttr<UnusedAttr>()) | ||||
1735 | return false; | ||||
1736 | |||||
1737 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { | ||||
1738 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) | ||||
1739 | return false; | ||||
1740 | |||||
1741 | if (const Expr *Init = VD->getInit()) { | ||||
1742 | if (const ExprWithCleanups *Cleanups = | ||||
1743 | dyn_cast<ExprWithCleanups>(Init)) | ||||
1744 | Init = Cleanups->getSubExpr(); | ||||
1745 | const CXXConstructExpr *Construct = | ||||
1746 | dyn_cast<CXXConstructExpr>(Init); | ||||
1747 | if (Construct && !Construct->isElidable()) { | ||||
1748 | CXXConstructorDecl *CD = Construct->getConstructor(); | ||||
1749 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && | ||||
1750 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) | ||||
1751 | return false; | ||||
1752 | } | ||||
1753 | } | ||||
1754 | } | ||||
1755 | } | ||||
1756 | |||||
1757 | // TODO: __attribute__((unused)) templates? | ||||
1758 | } | ||||
1759 | |||||
1760 | return true; | ||||
1761 | } | ||||
1762 | |||||
1763 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, | ||||
1764 | FixItHint &Hint) { | ||||
1765 | if (isa<LabelDecl>(D)) { | ||||
1766 | SourceLocation AfterColon = Lexer::findLocationAfterToken( | ||||
1767 | D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), | ||||
1768 | true); | ||||
1769 | if (AfterColon.isInvalid()) | ||||
1770 | return; | ||||
1771 | Hint = FixItHint::CreateRemoval( | ||||
1772 | CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); | ||||
1773 | } | ||||
1774 | } | ||||
1775 | |||||
1776 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { | ||||
1777 | if (D->getTypeForDecl()->isDependentType()) | ||||
1778 | return; | ||||
1779 | |||||
1780 | for (auto *TmpD : D->decls()) { | ||||
1781 | if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) | ||||
1782 | DiagnoseUnusedDecl(T); | ||||
1783 | else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) | ||||
1784 | DiagnoseUnusedNestedTypedefs(R); | ||||
1785 | } | ||||
1786 | } | ||||
1787 | |||||
1788 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used | ||||
1789 | /// unless they are marked attr(unused). | ||||
1790 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { | ||||
1791 | if (!ShouldDiagnoseUnusedDecl(D)) | ||||
1792 | return; | ||||
1793 | |||||
1794 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { | ||||
1795 | // typedefs can be referenced later on, so the diagnostics are emitted | ||||
1796 | // at end-of-translation-unit. | ||||
1797 | UnusedLocalTypedefNameCandidates.insert(TD); | ||||
1798 | return; | ||||
1799 | } | ||||
1800 | |||||
1801 | FixItHint Hint; | ||||
1802 | GenerateFixForUnusedDecl(D, Context, Hint); | ||||
1803 | |||||
1804 | unsigned DiagID; | ||||
1805 | if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) | ||||
1806 | DiagID = diag::warn_unused_exception_param; | ||||
1807 | else if (isa<LabelDecl>(D)) | ||||
1808 | DiagID = diag::warn_unused_label; | ||||
1809 | else | ||||
1810 | DiagID = diag::warn_unused_variable; | ||||
1811 | |||||
1812 | Diag(D->getLocation(), DiagID) << D << Hint; | ||||
1813 | } | ||||
1814 | |||||
1815 | static void CheckPoppedLabel(LabelDecl *L, Sema &S) { | ||||
1816 | // Verify that we have no forward references left. If so, there was a goto | ||||
1817 | // or address of a label taken, but no definition of it. Label fwd | ||||
1818 | // definitions are indicated with a null substmt which is also not a resolved | ||||
1819 | // MS inline assembly label name. | ||||
1820 | bool Diagnose = false; | ||||
1821 | if (L->isMSAsmLabel()) | ||||
1822 | Diagnose = !L->isResolvedMSAsmLabel(); | ||||
1823 | else | ||||
1824 | Diagnose = L->getStmt() == nullptr; | ||||
1825 | if (Diagnose) | ||||
1826 | S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); | ||||
1827 | } | ||||
1828 | |||||
1829 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { | ||||
1830 | S->mergeNRVOIntoParent(); | ||||
1831 | |||||
1832 | if (S->decl_empty()) return; | ||||
1833 | assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope )) && "Scope shouldn't contain decls!") ? static_cast <void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1834, __PRETTY_FUNCTION__)) | ||||
1834 | "Scope shouldn't contain decls!")(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope )) && "Scope shouldn't contain decls!") ? static_cast <void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1834, __PRETTY_FUNCTION__)); | ||||
1835 | |||||
1836 | for (auto *TmpD : S->decls()) { | ||||
1837 | assert(TmpD && "This decl didn't get pushed??")((TmpD && "This decl didn't get pushed??") ? static_cast <void> (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1837, __PRETTY_FUNCTION__)); | ||||
1838 | |||||
1839 | assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?" ) ? static_cast<void> (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1839, __PRETTY_FUNCTION__)); | ||||
1840 | NamedDecl *D = cast<NamedDecl>(TmpD); | ||||
1841 | |||||
1842 | // Diagnose unused variables in this scope. | ||||
1843 | if (!S->hasUnrecoverableErrorOccurred()) { | ||||
1844 | DiagnoseUnusedDecl(D); | ||||
1845 | if (const auto *RD = dyn_cast<RecordDecl>(D)) | ||||
1846 | DiagnoseUnusedNestedTypedefs(RD); | ||||
1847 | } | ||||
1848 | |||||
1849 | if (!D->getDeclName()) continue; | ||||
1850 | |||||
1851 | // If this was a forward reference to a label, verify it was defined. | ||||
1852 | if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) | ||||
1853 | CheckPoppedLabel(LD, *this); | ||||
1854 | |||||
1855 | // Remove this name from our lexical scope, and warn on it if we haven't | ||||
1856 | // already. | ||||
1857 | IdResolver.RemoveDecl(D); | ||||
1858 | auto ShadowI = ShadowingDecls.find(D); | ||||
1859 | if (ShadowI != ShadowingDecls.end()) { | ||||
1860 | if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { | ||||
1861 | Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) | ||||
1862 | << D << FD << FD->getParent(); | ||||
1863 | Diag(FD->getLocation(), diag::note_previous_declaration); | ||||
1864 | } | ||||
1865 | ShadowingDecls.erase(ShadowI); | ||||
1866 | } | ||||
1867 | } | ||||
1868 | } | ||||
1869 | |||||
1870 | /// Look for an Objective-C class in the translation unit. | ||||
1871 | /// | ||||
1872 | /// \param Id The name of the Objective-C class we're looking for. If | ||||
1873 | /// typo-correction fixes this name, the Id will be updated | ||||
1874 | /// to the fixed name. | ||||
1875 | /// | ||||
1876 | /// \param IdLoc The location of the name in the translation unit. | ||||
1877 | /// | ||||
1878 | /// \param DoTypoCorrection If true, this routine will attempt typo correction | ||||
1879 | /// if there is no class with the given name. | ||||
1880 | /// | ||||
1881 | /// \returns The declaration of the named Objective-C class, or NULL if the | ||||
1882 | /// class could not be found. | ||||
1883 | ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, | ||||
1884 | SourceLocation IdLoc, | ||||
1885 | bool DoTypoCorrection) { | ||||
1886 | // The third "scope" argument is 0 since we aren't enabling lazy built-in | ||||
1887 | // creation from this context. | ||||
1888 | NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); | ||||
1889 | |||||
1890 | if (!IDecl && DoTypoCorrection) { | ||||
1891 | // Perform typo correction at the given location, but only if we | ||||
1892 | // find an Objective-C class name. | ||||
1893 | DeclFilterCCC<ObjCInterfaceDecl> CCC{}; | ||||
1894 | if (TypoCorrection C = | ||||
1895 | CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, | ||||
1896 | TUScope, nullptr, CCC, CTK_ErrorRecovery)) { | ||||
1897 | diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); | ||||
1898 | IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); | ||||
1899 | Id = IDecl->getIdentifier(); | ||||
1900 | } | ||||
1901 | } | ||||
1902 | ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); | ||||
1903 | // This routine must always return a class definition, if any. | ||||
1904 | if (Def && Def->getDefinition()) | ||||
1905 | Def = Def->getDefinition(); | ||||
1906 | return Def; | ||||
1907 | } | ||||
1908 | |||||
1909 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting | ||||
1910 | /// from S, where a non-field would be declared. This routine copes | ||||
1911 | /// with the difference between C and C++ scoping rules in structs and | ||||
1912 | /// unions. For example, the following code is well-formed in C but | ||||
1913 | /// ill-formed in C++: | ||||
1914 | /// @code | ||||
1915 | /// struct S6 { | ||||
1916 | /// enum { BAR } e; | ||||
1917 | /// }; | ||||
1918 | /// | ||||
1919 | /// void test_S6() { | ||||
1920 | /// struct S6 a; | ||||
1921 | /// a.e = BAR; | ||||
1922 | /// } | ||||
1923 | /// @endcode | ||||
1924 | /// For the declaration of BAR, this routine will return a different | ||||
1925 | /// scope. The scope S will be the scope of the unnamed enumeration | ||||
1926 | /// within S6. In C++, this routine will return the scope associated | ||||
1927 | /// with S6, because the enumeration's scope is a transparent | ||||
1928 | /// context but structures can contain non-field names. In C, this | ||||
1929 | /// routine will return the translation unit scope, since the | ||||
1930 | /// enumeration's scope is a transparent context and structures cannot | ||||
1931 | /// contain non-field names. | ||||
1932 | Scope *Sema::getNonFieldDeclScope(Scope *S) { | ||||
1933 | while (((S->getFlags() & Scope::DeclScope) == 0) || | ||||
1934 | (S->getEntity() && S->getEntity()->isTransparentContext()) || | ||||
1935 | (S->isClassScope() && !getLangOpts().CPlusPlus)) | ||||
1936 | S = S->getParent(); | ||||
1937 | return S; | ||||
1938 | } | ||||
1939 | |||||
1940 | /// Looks up the declaration of "struct objc_super" and | ||||
1941 | /// saves it for later use in building builtin declaration of | ||||
1942 | /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such | ||||
1943 | /// pre-existing declaration exists no action takes place. | ||||
1944 | static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, | ||||
1945 | IdentifierInfo *II) { | ||||
1946 | if (!II->isStr("objc_msgSendSuper")) | ||||
1947 | return; | ||||
1948 | ASTContext &Context = ThisSema.Context; | ||||
1949 | |||||
1950 | LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), | ||||
1951 | SourceLocation(), Sema::LookupTagName); | ||||
1952 | ThisSema.LookupName(Result, S); | ||||
1953 | if (Result.getResultKind() == LookupResult::Found) | ||||
1954 | if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) | ||||
1955 | Context.setObjCSuperType(Context.getTagDeclType(TD)); | ||||
1956 | } | ||||
1957 | |||||
1958 | static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, | ||||
1959 | ASTContext::GetBuiltinTypeError Error) { | ||||
1960 | switch (Error) { | ||||
1961 | case ASTContext::GE_None: | ||||
1962 | return ""; | ||||
1963 | case ASTContext::GE_Missing_type: | ||||
1964 | return BuiltinInfo.getHeaderName(ID); | ||||
1965 | case ASTContext::GE_Missing_stdio: | ||||
1966 | return "stdio.h"; | ||||
1967 | case ASTContext::GE_Missing_setjmp: | ||||
1968 | return "setjmp.h"; | ||||
1969 | case ASTContext::GE_Missing_ucontext: | ||||
1970 | return "ucontext.h"; | ||||
1971 | } | ||||
1972 | llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 1972); | ||||
1973 | } | ||||
1974 | |||||
1975 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at | ||||
1976 | /// file scope. lazily create a decl for it. ForRedeclaration is true | ||||
1977 | /// if we're creating this built-in in anticipation of redeclaring the | ||||
1978 | /// built-in. | ||||
1979 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, | ||||
1980 | Scope *S, bool ForRedeclaration, | ||||
1981 | SourceLocation Loc) { | ||||
1982 | LookupPredefedObjCSuperType(*this, S, II); | ||||
1983 | |||||
1984 | ASTContext::GetBuiltinTypeError Error; | ||||
1985 | QualType R = Context.GetBuiltinType(ID, Error); | ||||
1986 | if (Error) { | ||||
1987 | if (!ForRedeclaration) | ||||
1988 | return nullptr; | ||||
1989 | |||||
1990 | // If we have a builtin without an associated type we should not emit a | ||||
1991 | // warning when we were not able to find a type for it. | ||||
1992 | if (Error == ASTContext::GE_Missing_type) | ||||
1993 | return nullptr; | ||||
1994 | |||||
1995 | // If we could not find a type for setjmp it is because the jmp_buf type was | ||||
1996 | // not defined prior to the setjmp declaration. | ||||
1997 | if (Error == ASTContext::GE_Missing_setjmp) { | ||||
1998 | Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) | ||||
1999 | << Context.BuiltinInfo.getName(ID); | ||||
2000 | return nullptr; | ||||
2001 | } | ||||
2002 | |||||
2003 | // Generally, we emit a warning that the declaration requires the | ||||
2004 | // appropriate header. | ||||
2005 | Diag(Loc, diag::warn_implicit_decl_requires_sysheader) | ||||
2006 | << getHeaderName(Context.BuiltinInfo, ID, Error) | ||||
2007 | << Context.BuiltinInfo.getName(ID); | ||||
2008 | return nullptr; | ||||
2009 | } | ||||
2010 | |||||
2011 | if (!ForRedeclaration && | ||||
2012 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || | ||||
2013 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { | ||||
2014 | Diag(Loc, diag::ext_implicit_lib_function_decl) | ||||
2015 | << Context.BuiltinInfo.getName(ID) << R; | ||||
2016 | if (Context.BuiltinInfo.getHeaderName(ID) && | ||||
2017 | !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) | ||||
2018 | Diag(Loc, diag::note_include_header_or_declare) | ||||
2019 | << Context.BuiltinInfo.getHeaderName(ID) | ||||
2020 | << Context.BuiltinInfo.getName(ID); | ||||
2021 | } | ||||
2022 | |||||
2023 | if (R.isNull()) | ||||
2024 | return nullptr; | ||||
2025 | |||||
2026 | DeclContext *Parent = Context.getTranslationUnitDecl(); | ||||
2027 | if (getLangOpts().CPlusPlus) { | ||||
2028 | LinkageSpecDecl *CLinkageDecl = | ||||
2029 | LinkageSpecDecl::Create(Context, Parent, Loc, Loc, | ||||
2030 | LinkageSpecDecl::lang_c, false); | ||||
2031 | CLinkageDecl->setImplicit(); | ||||
2032 | Parent->addDecl(CLinkageDecl); | ||||
2033 | Parent = CLinkageDecl; | ||||
2034 | } | ||||
2035 | |||||
2036 | FunctionDecl *New = FunctionDecl::Create(Context, | ||||
2037 | Parent, | ||||
2038 | Loc, Loc, II, R, /*TInfo=*/nullptr, | ||||
2039 | SC_Extern, | ||||
2040 | false, | ||||
2041 | R->isFunctionProtoType()); | ||||
2042 | New->setImplicit(); | ||||
2043 | |||||
2044 | // Create Decl objects for each parameter, adding them to the | ||||
2045 | // FunctionDecl. | ||||
2046 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { | ||||
2047 | SmallVector<ParmVarDecl*, 16> Params; | ||||
2048 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||
2049 | ParmVarDecl *parm = | ||||
2050 | ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), | ||||
2051 | nullptr, FT->getParamType(i), /*TInfo=*/nullptr, | ||||
2052 | SC_None, nullptr); | ||||
2053 | parm->setScopeInfo(0, i); | ||||
2054 | Params.push_back(parm); | ||||
2055 | } | ||||
2056 | New->setParams(Params); | ||||
2057 | } | ||||
2058 | |||||
2059 | AddKnownFunctionAttributes(New); | ||||
2060 | RegisterLocallyScopedExternCDecl(New, S); | ||||
2061 | |||||
2062 | // TUScope is the translation-unit scope to insert this function into. | ||||
2063 | // FIXME: This is hideous. We need to teach PushOnScopeChains to | ||||
2064 | // relate Scopes to DeclContexts, and probably eliminate CurContext | ||||
2065 | // entirely, but we're not there yet. | ||||
2066 | DeclContext *SavedContext = CurContext; | ||||
2067 | CurContext = Parent; | ||||
2068 | PushOnScopeChains(New, TUScope); | ||||
2069 | CurContext = SavedContext; | ||||
2070 | return New; | ||||
2071 | } | ||||
2072 | |||||
2073 | /// Typedef declarations don't have linkage, but they still denote the same | ||||
2074 | /// entity if their types are the same. | ||||
2075 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's | ||||
2076 | /// isSameEntity. | ||||
2077 | static void filterNonConflictingPreviousTypedefDecls(Sema &S, | ||||
2078 | TypedefNameDecl *Decl, | ||||
2079 | LookupResult &Previous) { | ||||
2080 | // This is only interesting when modules are enabled. | ||||
2081 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) | ||||
2082 | return; | ||||
2083 | |||||
2084 | // Empty sets are uninteresting. | ||||
2085 | if (Previous.empty()) | ||||
2086 | return; | ||||
2087 | |||||
2088 | LookupResult::Filter Filter = Previous.makeFilter(); | ||||
2089 | while (Filter.hasNext()) { | ||||
2090 | NamedDecl *Old = Filter.next(); | ||||
2091 | |||||
2092 | // Non-hidden declarations are never ignored. | ||||
2093 | if (S.isVisible(Old)) | ||||
2094 | continue; | ||||
2095 | |||||
2096 | // Declarations of the same entity are not ignored, even if they have | ||||
2097 | // different linkages. | ||||
2098 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | ||||
2099 | if (S.Context.hasSameType(OldTD->getUnderlyingType(), | ||||
2100 | Decl->getUnderlyingType())) | ||||
2101 | continue; | ||||
2102 | |||||
2103 | // If both declarations give a tag declaration a typedef name for linkage | ||||
2104 | // purposes, then they declare the same entity. | ||||
2105 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && | ||||
2106 | Decl->getAnonDeclWithTypedefName()) | ||||
2107 | continue; | ||||
2108 | } | ||||
2109 | |||||
2110 | Filter.erase(); | ||||
2111 | } | ||||
2112 | |||||
2113 | Filter.done(); | ||||
2114 | } | ||||
2115 | |||||
2116 | bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { | ||||
2117 | QualType OldType; | ||||
2118 | if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) | ||||
2119 | OldType = OldTypedef->getUnderlyingType(); | ||||
2120 | else | ||||
2121 | OldType = Context.getTypeDeclType(Old); | ||||
2122 | QualType NewType = New->getUnderlyingType(); | ||||
2123 | |||||
2124 | if (NewType->isVariablyModifiedType()) { | ||||
2125 | // Must not redefine a typedef with a variably-modified type. | ||||
2126 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | ||||
2127 | Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) | ||||
2128 | << Kind << NewType; | ||||
2129 | if (Old->getLocation().isValid()) | ||||
2130 | notePreviousDefinition(Old, New->getLocation()); | ||||
2131 | New->setInvalidDecl(); | ||||
2132 | return true; | ||||
2133 | } | ||||
2134 | |||||
2135 | if (OldType != NewType && | ||||
2136 | !OldType->isDependentType() && | ||||
2137 | !NewType->isDependentType() && | ||||
2138 | !Context.hasSameType(OldType, NewType)) { | ||||
2139 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | ||||
2140 | Diag(New->getLocation(), diag::err_redefinition_different_typedef) | ||||
2141 | << Kind << NewType << OldType; | ||||
2142 | if (Old->getLocation().isValid()) | ||||
2143 | notePreviousDefinition(Old, New->getLocation()); | ||||
2144 | New->setInvalidDecl(); | ||||
2145 | return true; | ||||
2146 | } | ||||
2147 | return false; | ||||
2148 | } | ||||
2149 | |||||
2150 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the | ||||
2151 | /// same name and scope as a previous declaration 'Old'. Figure out | ||||
2152 | /// how to resolve this situation, merging decls or emitting | ||||
2153 | /// diagnostics as appropriate. If there was an error, set New to be invalid. | ||||
2154 | /// | ||||
2155 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, | ||||
2156 | LookupResult &OldDecls) { | ||||
2157 | // If the new decl is known invalid already, don't bother doing any | ||||
2158 | // merging checks. | ||||
2159 | if (New->isInvalidDecl()) return; | ||||
2160 | |||||
2161 | // Allow multiple definitions for ObjC built-in typedefs. | ||||
2162 | // FIXME: Verify the underlying types are equivalent! | ||||
2163 | if (getLangOpts().ObjC) { | ||||
2164 | const IdentifierInfo *TypeID = New->getIdentifier(); | ||||
2165 | switch (TypeID->getLength()) { | ||||
2166 | default: break; | ||||
2167 | case 2: | ||||
2168 | { | ||||
2169 | if (!TypeID->isStr("id")) | ||||
2170 | break; | ||||
2171 | QualType T = New->getUnderlyingType(); | ||||
2172 | if (!T->isPointerType()) | ||||
2173 | break; | ||||
2174 | if (!T->isVoidPointerType()) { | ||||
2175 | QualType PT = T->getAs<PointerType>()->getPointeeType(); | ||||
| |||||
2176 | if (!PT->isStructureType()) | ||||
2177 | break; | ||||
2178 | } | ||||
2179 | Context.setObjCIdRedefinitionType(T); | ||||
2180 | // Install the built-in type for 'id', ignoring the current definition. | ||||
2181 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); | ||||
2182 | return; | ||||
2183 | } | ||||
2184 | case 5: | ||||
2185 | if (!TypeID->isStr("Class")) | ||||
2186 | break; | ||||
2187 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); | ||||
2188 | // Install the built-in type for 'Class', ignoring the current definition. | ||||
2189 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); | ||||
2190 | return; | ||||
2191 | case 3: | ||||
2192 | if (!TypeID->isStr("SEL")) | ||||
2193 | break; | ||||
2194 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); | ||||
2195 | // Install the built-in type for 'SEL', ignoring the current definition. | ||||
2196 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); | ||||
2197 | return; | ||||
2198 | } | ||||
2199 | // Fall through - the typedef name was not a builtin type. | ||||
2200 | } | ||||
2201 | |||||
2202 | // Verify the old decl was also a type. | ||||
2203 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); | ||||
2204 | if (!Old) { | ||||
2205 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||
2206 | << New->getDeclName(); | ||||
2207 | |||||
2208 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); | ||||
2209 | if (OldD->getLocation().isValid()) | ||||
2210 | notePreviousDefinition(OldD, New->getLocation()); | ||||
2211 | |||||
2212 | return New->setInvalidDecl(); | ||||
2213 | } | ||||
2214 | |||||
2215 | // If the old declaration is invalid, just give up here. | ||||
2216 | if (Old->isInvalidDecl()) | ||||
2217 | return New->setInvalidDecl(); | ||||
2218 | |||||
2219 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | ||||
2220 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); | ||||
2221 | auto *NewTag = New->getAnonDeclWithTypedefName(); | ||||
2222 | NamedDecl *Hidden = nullptr; | ||||
2223 | if (OldTag && NewTag && | ||||
2224 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && | ||||
2225 | !hasVisibleDefinition(OldTag, &Hidden)) { | ||||
2226 | // There is a definition of this tag, but it is not visible. Use it | ||||
2227 | // instead of our tag. | ||||
2228 | New->setTypeForDecl(OldTD->getTypeForDecl()); | ||||
2229 | if (OldTD->isModed()) | ||||
2230 | New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), | ||||
2231 | OldTD->getUnderlyingType()); | ||||
2232 | else | ||||
2233 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); | ||||
2234 | |||||
2235 | // Make the old tag definition visible. | ||||
2236 | makeMergedDefinitionVisible(Hidden); | ||||
2237 | |||||
2238 | // If this was an unscoped enumeration, yank all of its enumerators | ||||
2239 | // out of the scope. | ||||
2240 | if (isa<EnumDecl>(NewTag)) { | ||||
2241 | Scope *EnumScope = getNonFieldDeclScope(S); | ||||
2242 | for (auto *D : NewTag->decls()) { | ||||
2243 | auto *ED = cast<EnumConstantDecl>(D); | ||||
2244 | assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0 ) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 2244, __PRETTY_FUNCTION__)); | ||||
2245 | EnumScope->RemoveDecl(ED); | ||||
2246 | IdResolver.RemoveDecl(ED); | ||||
2247 | ED->getLexicalDeclContext()->removeDecl(ED); | ||||
2248 | } | ||||
2249 | } | ||||
2250 | } | ||||
2251 | } | ||||
2252 | |||||
2253 | // If the typedef types are not identical, reject them in all languages and | ||||
2254 | // with any extensions enabled. | ||||
2255 | if (isIncompatibleTypedef(Old, New)) | ||||
2256 | return; | ||||
2257 | |||||
2258 | // The types match. Link up the redeclaration chain and merge attributes if | ||||
2259 | // the old declaration was a typedef. | ||||
2260 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { | ||||
2261 | New->setPreviousDecl(Typedef); | ||||
2262 | mergeDeclAttributes(New, Old); | ||||
2263 | } | ||||
2264 | |||||
2265 | if (getLangOpts().MicrosoftExt) | ||||
2266 | return; | ||||
2267 | |||||
2268 | if (getLangOpts().CPlusPlus) { | ||||
2269 | // C++ [dcl.typedef]p2: | ||||
2270 | // In a given non-class scope, a typedef specifier can be used to | ||||
2271 | // redefine the name of any type declared in that scope to refer | ||||
2272 | // to the type to which it already refers. | ||||
2273 | if (!isa<CXXRecordDecl>(CurContext)) | ||||
2274 | return; | ||||
2275 | |||||
2276 | // C++0x [dcl.typedef]p4: | ||||
2277 | // In a given class scope, a typedef specifier can be used to redefine | ||||
2278 | // any class-name declared in that scope that is not also a typedef-name | ||||
2279 | // to refer to the type to which it already refers. | ||||
2280 | // | ||||
2281 | // This wording came in via DR424, which was a correction to the | ||||
2282 | // wording in DR56, which accidentally banned code like: | ||||
2283 | // | ||||
2284 | // struct S { | ||||
2285 | // typedef struct A { } A; | ||||
2286 | // }; | ||||
2287 | // | ||||
2288 | // in the C++03 standard. We implement the C++0x semantics, which | ||||
2289 | // allow the above but disallow | ||||
2290 | // | ||||
2291 | // struct S { | ||||
2292 | // typedef int I; | ||||
2293 | // typedef int I; | ||||
2294 | // }; | ||||
2295 | // | ||||
2296 | // since that was the intent of DR56. | ||||
2297 | if (!isa<TypedefNameDecl>(Old)) | ||||
2298 | return; | ||||
2299 | |||||
2300 | Diag(New->getLocation(), diag::err_redefinition) | ||||
2301 | << New->getDeclName(); | ||||
2302 | notePreviousDefinition(Old, New->getLocation()); | ||||
2303 | return New->setInvalidDecl(); | ||||
2304 | } | ||||
2305 | |||||
2306 | // Modules always permit redefinition of typedefs, as does C11. | ||||
2307 | if (getLangOpts().Modules || getLangOpts().C11) | ||||
2308 | return; | ||||
2309 | |||||
2310 | // If we have a redefinition of a typedef in C, emit a warning. This warning | ||||
2311 | // is normally mapped to an error, but can be controlled with | ||||
2312 | // -Wtypedef-redefinition. If either the original or the redefinition is | ||||
2313 | // in a system header, don't emit this for compatibility with GCC. | ||||
2314 | if (getDiagnostics().getSuppressSystemWarnings() && | ||||
2315 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). | ||||
2316 | (Old->isImplicit() || | ||||
2317 | Context.getSourceManager().isInSystemHeader(Old->getLocation()) || | ||||
2318 | Context.getSourceManager().isInSystemHeader(New->getLocation()))) | ||||
2319 | return; | ||||
2320 | |||||
2321 | Diag(New->getLocation(), diag::ext_redefinition_of_typedef) | ||||
2322 | << New->getDeclName(); | ||||
2323 | notePreviousDefinition(Old, New->getLocation()); | ||||
2324 | } | ||||
2325 | |||||
2326 | /// DeclhasAttr - returns true if decl Declaration already has the target | ||||
2327 | /// attribute. | ||||
2328 | static bool DeclHasAttr(const Decl *D, const Attr *A) { | ||||
2329 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); | ||||
2330 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); | ||||
2331 | for (const auto *i : D->attrs()) | ||||
2332 | if (i->getKind() == A->getKind()) { | ||||
2333 | if (Ann) { | ||||
2334 | if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) | ||||
2335 | return true; | ||||
2336 | continue; | ||||
2337 | } | ||||
2338 | // FIXME: Don't hardcode this check | ||||
2339 | if (OA && isa<OwnershipAttr>(i)) | ||||
2340 | return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); | ||||
2341 | return true; | ||||
2342 | } | ||||
2343 | |||||
2344 | return false; | ||||
2345 | } | ||||
2346 | |||||
2347 | static bool isAttributeTargetADefinition(Decl *D) { | ||||
2348 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||
2349 | return VD->isThisDeclarationADefinition(); | ||||
2350 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) | ||||
2351 | return TD->isCompleteDefinition() || TD->isBeingDefined(); | ||||
2352 | return true; | ||||
2353 | } | ||||
2354 | |||||
2355 | /// Merge alignment attributes from \p Old to \p New, taking into account the | ||||
2356 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. | ||||
2357 | /// | ||||
2358 | /// \return \c true if any attributes were added to \p New. | ||||
2359 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { | ||||
2360 | // Look for alignas attributes on Old, and pick out whichever attribute | ||||
2361 | // specifies the strictest alignment requirement. | ||||
2362 | AlignedAttr *OldAlignasAttr = nullptr; | ||||
2363 | AlignedAttr *OldStrictestAlignAttr = nullptr; | ||||
2364 | unsigned OldAlign = 0; | ||||
2365 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { | ||||
2366 | // FIXME: We have no way of representing inherited dependent alignments | ||||
2367 | // in a case like: | ||||
2368 | // template<int A, int B> struct alignas(A) X; | ||||
2369 | // template<int A, int B> struct alignas(B) X {}; | ||||
2370 | // For now, we just ignore any alignas attributes which are not on the | ||||
2371 | // definition in such a case. | ||||
2372 | if (I->isAlignmentDependent()) | ||||
2373 | return false; | ||||
2374 | |||||
2375 | if (I->isAlignas()) | ||||
2376 | OldAlignasAttr = I; | ||||
2377 | |||||
2378 | unsigned Align = I->getAlignment(S.Context); | ||||
2379 | if (Align > OldAlign) { | ||||
2380 | OldAlign = Align; | ||||
2381 | OldStrictestAlignAttr = I; | ||||
2382 | } | ||||
2383 | } | ||||
2384 | |||||
2385 | // Look for alignas attributes on New. | ||||
2386 | AlignedAttr *NewAlignasAttr = nullptr; | ||||
2387 | unsigned NewAlign = 0; | ||||
2388 | for (auto *I : New->specific_attrs<AlignedAttr>()) { | ||||
2389 | if (I->isAlignmentDependent()) | ||||
2390 | return false; | ||||
2391 | |||||
2392 | if (I->isAlignas()) | ||||
2393 | NewAlignasAttr = I; | ||||
2394 | |||||
2395 | unsigned Align = I->getAlignment(S.Context); | ||||
2396 | if (Align > NewAlign) | ||||
2397 | NewAlign = Align; | ||||
2398 | } | ||||
2399 | |||||
2400 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { | ||||
2401 | // Both declarations have 'alignas' attributes. We require them to match. | ||||
2402 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but | ||||
2403 | // fall short. (If two declarations both have alignas, they must both match | ||||
2404 | // every definition, and so must match each other if there is a definition.) | ||||
2405 | |||||
2406 | // If either declaration only contains 'alignas(0)' specifiers, then it | ||||
2407 | // specifies the natural alignment for the type. | ||||
2408 | if (OldAlign == 0 || NewAlign == 0) { | ||||
2409 | QualType Ty; | ||||
2410 | if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) | ||||
2411 | Ty = VD->getType(); | ||||
2412 | else | ||||
2413 | Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); | ||||
2414 | |||||
2415 | if (OldAlign == 0) | ||||
2416 | OldAlign = S.Context.getTypeAlign(Ty); | ||||
2417 | if (NewAlign == 0) | ||||
2418 | NewAlign = S.Context.getTypeAlign(Ty); | ||||
2419 | } | ||||
2420 | |||||
2421 | if (OldAlign != NewAlign) { | ||||
2422 | S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) | ||||
2423 | << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() | ||||
2424 | << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); | ||||
2425 | S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); | ||||
2426 | } | ||||
2427 | } | ||||
2428 | |||||
2429 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { | ||||
2430 | // C++11 [dcl.align]p6: | ||||
2431 | // if any declaration of an entity has an alignment-specifier, | ||||
2432 | // every defining declaration of that entity shall specify an | ||||
2433 | // equivalent alignment. | ||||
2434 | // C11 6.7.5/7: | ||||
2435 | // If the definition of an object does not have an alignment | ||||
2436 | // specifier, any other declaration of that object shall also | ||||
2437 | // have no alignment specifier. | ||||
2438 | S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) | ||||
2439 | << OldAlignasAttr; | ||||
2440 | S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) | ||||
2441 | << OldAlignasAttr; | ||||
2442 | } | ||||
2443 | |||||
2444 | bool AnyAdded = false; | ||||
2445 | |||||
2446 | // Ensure we have an attribute representing the strictest alignment. | ||||
2447 | if (OldAlign > NewAlign) { | ||||
2448 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); | ||||
2449 | Clone->setInherited(true); | ||||
2450 | New->addAttr(Clone); | ||||
2451 | AnyAdded = true; | ||||
2452 | } | ||||
2453 | |||||
2454 | // Ensure we have an alignas attribute if the old declaration had one. | ||||
2455 | if (OldAlignasAttr && !NewAlignasAttr && | ||||
2456 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { | ||||
2457 | AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); | ||||
2458 | Clone->setInherited(true); | ||||
2459 | New->addAttr(Clone); | ||||
2460 | AnyAdded = true; | ||||
2461 | } | ||||
2462 | |||||
2463 | return AnyAdded; | ||||
2464 | } | ||||
2465 | |||||
2466 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, | ||||
2467 | const InheritableAttr *Attr, | ||||
2468 | Sema::AvailabilityMergeKind AMK) { | ||||
2469 | // This function copies an attribute Attr from a previous declaration to the | ||||
2470 | // new declaration D if the new declaration doesn't itself have that attribute | ||||
2471 | // yet or if that attribute allows duplicates. | ||||
2472 | // If you're adding a new attribute that requires logic different from | ||||
2473 | // "use explicit attribute on decl if present, else use attribute from | ||||
2474 | // previous decl", for example if the attribute needs to be consistent | ||||
2475 | // between redeclarations, you need to call a custom merge function here. | ||||
2476 | InheritableAttr *NewAttr = nullptr; | ||||
2477 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) | ||||
2478 | NewAttr = S.mergeAvailabilityAttr( | ||||
2479 | D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), | ||||
2480 | AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), | ||||
2481 | AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, | ||||
2482 | AA->getPriority()); | ||||
2483 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) | ||||
2484 | NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); | ||||
2485 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) | ||||
2486 | NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); | ||||
2487 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) | ||||
2488 | NewAttr = S.mergeDLLImportAttr(D, *ImportA); | ||||
2489 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) | ||||
2490 | NewAttr = S.mergeDLLExportAttr(D, *ExportA); | ||||
2491 | else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) | ||||
2492 | NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), | ||||
2493 | FA->getFirstArg()); | ||||
2494 | else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) | ||||
2495 | NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); | ||||
2496 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) | ||||
2497 | NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); | ||||
2498 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) | ||||
2499 | NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), | ||||
2500 | IA->getSemanticSpelling()); | ||||
2501 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) | ||||
2502 | NewAttr = S.mergeAlwaysInlineAttr(D, *AA, | ||||
2503 | &S.Context.Idents.get(AA->getSpelling())); | ||||
2504 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && | ||||
2505 | (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || | ||||
2506 | isa<CUDAGlobalAttr>(Attr))) { | ||||
2507 | // CUDA target attributes are part of function signature for | ||||
2508 | // overloading purposes and must not be merged. | ||||
2509 | return false; | ||||
2510 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) | ||||
2511 | NewAttr = S.mergeMinSizeAttr(D, *MA); | ||||
2512 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) | ||||
2513 | NewAttr = S.mergeOptimizeNoneAttr(D, *OA); | ||||
2514 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) | ||||
2515 | NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); | ||||
2516 | else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) | ||||
2517 | NewAttr = S.mergeCommonAttr(D, *CommonA); | ||||
2518 | else if (isa<AlignedAttr>(Attr)) | ||||
2519 | // AlignedAttrs are handled separately, because we need to handle all | ||||
2520 | // such attributes on a declaration at the same time. | ||||
2521 | NewAttr = nullptr; | ||||
2522 | else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && | ||||
2523 | (AMK == Sema::AMK_Override || | ||||
2524 | AMK == Sema::AMK_ProtocolImplementation)) | ||||
2525 | NewAttr = nullptr; | ||||
2526 | else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) | ||||
2527 | NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid()); | ||||
2528 | else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) | ||||
2529 | NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); | ||||
2530 | else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) | ||||
2531 | NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); | ||||
2532 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) | ||||
2533 | NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); | ||||
2534 | |||||
2535 | if (NewAttr) { | ||||
2536 | NewAttr->setInherited(true); | ||||
2537 | D->addAttr(NewAttr); | ||||
2538 | if (isa<MSInheritanceAttr>(NewAttr)) | ||||
2539 | S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); | ||||
2540 | return true; | ||||
2541 | } | ||||
2542 | |||||
2543 | return false; | ||||
2544 | } | ||||
2545 | |||||
2546 | static const NamedDecl *getDefinition(const Decl *D) { | ||||
2547 | if (const TagDecl *TD = dyn_cast<TagDecl>(D)) | ||||
2548 | return TD->getDefinition(); | ||||
2549 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||
2550 | const VarDecl *Def = VD->getDefinition(); | ||||
2551 | if (Def) | ||||
2552 | return Def; | ||||
2553 | return VD->getActingDefinition(); | ||||
2554 | } | ||||
2555 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) | ||||
2556 | return FD->getDefinition(); | ||||
2557 | return nullptr; | ||||
2558 | } | ||||
2559 | |||||
2560 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { | ||||
2561 | for (const auto *Attribute : D->attrs()) | ||||
2562 | if (Attribute->getKind() == Kind) | ||||
2563 | return true; | ||||
2564 | return false; | ||||
2565 | } | ||||
2566 | |||||
2567 | /// checkNewAttributesAfterDef - If we already have a definition, check that | ||||
2568 | /// there are no new attributes in this declaration. | ||||
2569 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { | ||||
2570 | if (!New->hasAttrs()) | ||||
2571 | return; | ||||
2572 | |||||
2573 | const NamedDecl *Def = getDefinition(Old); | ||||
2574 | if (!Def || Def == New) | ||||
2575 | return; | ||||
2576 | |||||
2577 | AttrVec &NewAttributes = New->getAttrs(); | ||||
2578 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { | ||||
2579 | const Attr *NewAttribute = NewAttributes[I]; | ||||
2580 | |||||
2581 | if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { | ||||
2582 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { | ||||
2583 | Sema::SkipBodyInfo SkipBody; | ||||
2584 | S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); | ||||
2585 | |||||
2586 | // If we're skipping this definition, drop the "alias" attribute. | ||||
2587 | if (SkipBody.ShouldSkip) { | ||||
2588 | NewAttributes.erase(NewAttributes.begin() + I); | ||||
2589 | --E; | ||||
2590 | continue; | ||||
2591 | } | ||||
2592 | } else { | ||||
2593 | VarDecl *VD = cast<VarDecl>(New); | ||||
2594 | unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == | ||||
2595 | VarDecl::TentativeDefinition | ||||
2596 | ? diag::err_alias_after_tentative | ||||
2597 | : diag::err_redefinition; | ||||
2598 | S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); | ||||
2599 | if (Diag == diag::err_redefinition) | ||||
2600 | S.notePreviousDefinition(Def, VD->getLocation()); | ||||
2601 | else | ||||
2602 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||
2603 | VD->setInvalidDecl(); | ||||
2604 | } | ||||
2605 | ++I; | ||||
2606 | continue; | ||||
2607 | } | ||||
2608 | |||||
2609 | if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { | ||||
2610 | // Tentative definitions are only interesting for the alias check above. | ||||
2611 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { | ||||
2612 | ++I; | ||||
2613 | continue; | ||||
2614 | } | ||||
2615 | } | ||||
2616 | |||||
2617 | if (hasAttribute(Def, NewAttribute->getKind())) { | ||||
2618 | ++I; | ||||
2619 | continue; // regular attr merging will take care of validating this. | ||||
2620 | } | ||||
2621 | |||||
2622 | if (isa<C11NoReturnAttr>(NewAttribute)) { | ||||
2623 | // C's _Noreturn is allowed to be added to a function after it is defined. | ||||
2624 | ++I; | ||||
2625 | continue; | ||||
2626 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { | ||||
2627 | if (AA->isAlignas()) { | ||||
2628 | // C++11 [dcl.align]p6: | ||||
2629 | // if any declaration of an entity has an alignment-specifier, | ||||
2630 | // every defining declaration of that entity shall specify an | ||||
2631 | // equivalent alignment. | ||||
2632 | // C11 6.7.5/7: | ||||
2633 | // If the definition of an object does not have an alignment | ||||
2634 | // specifier, any other declaration of that object shall also | ||||
2635 | // have no alignment specifier. | ||||
2636 | S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) | ||||
2637 | << AA; | ||||
2638 | S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) | ||||
2639 | << AA; | ||||
2640 | NewAttributes.erase(NewAttributes.begin() + I); | ||||
2641 | --E; | ||||
2642 | continue; | ||||
2643 | } | ||||
2644 | } else if (isa<SelectAnyAttr>(NewAttribute) && | ||||
2645 | cast<VarDecl>(New)->isInline() && | ||||
2646 | !cast<VarDecl>(New)->isInlineSpecified()) { | ||||
2647 | // Don't warn about applying selectany to implicitly inline variables. | ||||
2648 | // Older compilers and language modes would require the use of selectany | ||||
2649 | // to make such variables inline, and it would have no effect if we | ||||
2650 | // honored it. | ||||
2651 | ++I; | ||||
2652 | continue; | ||||
2653 | } | ||||
2654 | |||||
2655 | S.Diag(NewAttribute->getLocation(), | ||||
2656 | diag::warn_attribute_precede_definition); | ||||
2657 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||
2658 | NewAttributes.erase(NewAttributes.begin() + I); | ||||
2659 | --E; | ||||
2660 | } | ||||
2661 | } | ||||
2662 | |||||
2663 | static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, | ||||
2664 | const ConstInitAttr *CIAttr, | ||||
2665 | bool AttrBeforeInit) { | ||||
2666 | SourceLocation InsertLoc = InitDecl->getInnerLocStart(); | ||||
2667 | |||||
2668 | // Figure out a good way to write this specifier on the old declaration. | ||||
2669 | // FIXME: We should just use the spelling of CIAttr, but we don't preserve | ||||
2670 | // enough of the attribute list spelling information to extract that without | ||||
2671 | // heroics. | ||||
2672 | std::string SuitableSpelling; | ||||
2673 | if (S.getLangOpts().CPlusPlus2a) | ||||
2674 | SuitableSpelling = | ||||
2675 | S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}); | ||||
2676 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | ||||
2677 | SuitableSpelling = S.PP.getLastMacroWithSpelling( | ||||
2678 | InsertLoc, | ||||
2679 | {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"), | ||||
2680 | tok::coloncolon, | ||||
2681 | S.PP.getIdentifierInfo("require_constant_initialization"), | ||||
2682 | tok::r_square, tok::r_square}); | ||||
2683 | if (SuitableSpelling.empty()) | ||||
2684 | SuitableSpelling = S.PP.getLastMacroWithSpelling( | ||||
2685 | InsertLoc, | ||||
2686 | {tok::kw___attribute, tok::l_paren, tok::r_paren, | ||||
2687 | S.PP.getIdentifierInfo("require_constant_initialization"), | ||||
2688 | tok::r_paren, tok::r_paren}); | ||||
2689 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a) | ||||
2690 | SuitableSpelling = "constinit"; | ||||
2691 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | ||||
2692 | SuitableSpelling = "[[clang::require_constant_initialization]]"; | ||||
2693 | if (SuitableSpelling.empty()) | ||||
2694 | SuitableSpelling = "__attribute__((require_constant_initialization))"; | ||||
2695 | SuitableSpelling += " "; | ||||
2696 | |||||
2697 | if (AttrBeforeInit) { | ||||
2698 | // extern constinit int a; | ||||
2699 | // int a = 0; // error (missing 'constinit'), accepted as extension | ||||
2700 | assert(CIAttr->isConstinit() && "should not diagnose this for attribute")((CIAttr->isConstinit() && "should not diagnose this for attribute" ) ? static_cast<void> (0) : __assert_fail ("CIAttr->isConstinit() && \"should not diagnose this for attribute\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 2700, __PRETTY_FUNCTION__)); | ||||
2701 | S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) | ||||
2702 | << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | ||||
2703 | S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); | ||||
2704 | } else { | ||||
2705 | // int a = 0; | ||||
2706 | // constinit extern int a; // error (missing 'constinit') | ||||
2707 | S.Diag(CIAttr->getLocation(), | ||||
2708 | CIAttr->isConstinit() ? diag::err_constinit_added_too_late | ||||
2709 | : diag::warn_require_const_init_added_too_late) | ||||
2710 | << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); | ||||
2711 | S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) | ||||
2712 | << CIAttr->isConstinit() | ||||
2713 | << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | ||||
2714 | } | ||||
2715 | } | ||||
2716 | |||||
2717 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. | ||||
2718 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, | ||||
2719 | AvailabilityMergeKind AMK) { | ||||
2720 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { | ||||
2721 | UsedAttr *NewAttr = OldAttr->clone(Context); | ||||
2722 | NewAttr->setInherited(true); | ||||
2723 | New->addAttr(NewAttr); | ||||
2724 | } | ||||
2725 | |||||
2726 | if (!Old->hasAttrs() && !New->hasAttrs()) | ||||
2727 | return; | ||||
2728 | |||||
2729 | // [dcl.constinit]p1: | ||||
2730 | // If the [constinit] specifier is applied to any declaration of a | ||||
2731 | // variable, it shall be applied to the initializing declaration. | ||||
2732 | const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); | ||||
2733 | const auto *NewConstInit = New->getAttr<ConstInitAttr>(); | ||||
2734 | if (bool(OldConstInit) != bool(NewConstInit)) { | ||||
2735 | const auto *OldVD = cast<VarDecl>(Old); | ||||
2736 | auto *NewVD = cast<VarDecl>(New); | ||||
2737 | |||||
2738 | // Find the initializing declaration. Note that we might not have linked | ||||
2739 | // the new declaration into the redeclaration chain yet. | ||||
2740 | const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); | ||||
2741 | if (!InitDecl && | ||||
2742 | (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) | ||||
2743 | InitDecl = NewVD; | ||||
2744 | |||||
2745 | if (InitDecl == NewVD) { | ||||
2746 | // This is the initializing declaration. If it would inherit 'constinit', | ||||
2747 | // that's ill-formed. (Note that we do not apply this to the attribute | ||||
2748 | // form). | ||||
2749 | if (OldConstInit && OldConstInit->isConstinit()) | ||||
2750 | diagnoseMissingConstinit(*this, NewVD, OldConstInit, | ||||
2751 | /*AttrBeforeInit=*/true); | ||||
2752 | } else if (NewConstInit) { | ||||
2753 | // This is the first time we've been told that this declaration should | ||||
2754 | // have a constant initializer. If we already saw the initializing | ||||
2755 | // declaration, this is too late. | ||||
2756 | if (InitDecl && InitDecl != NewVD) { | ||||
2757 | diagnoseMissingConstinit(*this, InitDecl, NewConstInit, | ||||
2758 | /*AttrBeforeInit=*/false); | ||||
2759 | NewVD->dropAttr<ConstInitAttr>(); | ||||
2760 | } | ||||
2761 | } | ||||
2762 | } | ||||
2763 | |||||
2764 | // Attributes declared post-definition are currently ignored. | ||||
2765 | checkNewAttributesAfterDef(*this, New, Old); | ||||
2766 | |||||
2767 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { | ||||
2768 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { | ||||
2769 | if (!OldA->isEquivalent(NewA)) { | ||||
2770 | // This redeclaration changes __asm__ label. | ||||
2771 | Diag(New->getLocation(), diag::err_different_asm_label); | ||||
2772 | Diag(OldA->getLocation(), diag::note_previous_declaration); | ||||
2773 | } | ||||
2774 | } else if (Old->isUsed()) { | ||||
2775 | // This redeclaration adds an __asm__ label to a declaration that has | ||||
2776 | // already been ODR-used. | ||||
2777 | Diag(New->getLocation(), diag::err_late_asm_label_name) | ||||
2778 | << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); | ||||
2779 | } | ||||
2780 | } | ||||
2781 | |||||
2782 | // Re-declaration cannot add abi_tag's. | ||||
2783 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { | ||||
2784 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { | ||||
2785 | for (const auto &NewTag : NewAbiTagAttr->tags()) { | ||||
2786 | if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), | ||||
2787 | NewTag) == OldAbiTagAttr->tags_end()) { | ||||
2788 | Diag(NewAbiTagAttr->getLocation(), | ||||
2789 | diag::err_new_abi_tag_on_redeclaration) | ||||
2790 | << NewTag; | ||||
2791 | Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); | ||||
2792 | } | ||||
2793 | } | ||||
2794 | } else { | ||||
2795 | Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); | ||||
2796 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
2797 | } | ||||
2798 | } | ||||
2799 | |||||
2800 | // This redeclaration adds a section attribute. | ||||
2801 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { | ||||
2802 | if (auto *VD = dyn_cast<VarDecl>(New)) { | ||||
2803 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { | ||||
2804 | Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); | ||||
2805 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
2806 | } | ||||
2807 | } | ||||
2808 | } | ||||
2809 | |||||
2810 | // Redeclaration adds code-seg attribute. | ||||
2811 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); | ||||
2812 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && | ||||
2813 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { | ||||
2814 | Diag(New->getLocation(), diag::warn_mismatched_section) | ||||
2815 | << 0 /*codeseg*/; | ||||
2816 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
2817 | } | ||||
2818 | |||||
2819 | if (!Old->hasAttrs()) | ||||
2820 | return; | ||||
2821 | |||||
2822 | bool foundAny = New->hasAttrs(); | ||||
2823 | |||||
2824 | // Ensure that any moving of objects within the allocated map is done before | ||||
2825 | // we process them. | ||||
2826 | if (!foundAny) New->setAttrs(AttrVec()); | ||||
2827 | |||||
2828 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { | ||||
2829 | // Ignore deprecated/unavailable/availability attributes if requested. | ||||
2830 | AvailabilityMergeKind LocalAMK = AMK_None; | ||||
2831 | if (isa<DeprecatedAttr>(I) || | ||||
2832 | isa<UnavailableAttr>(I) || | ||||
2833 | isa<AvailabilityAttr>(I)) { | ||||
2834 | switch (AMK) { | ||||
2835 | case AMK_None: | ||||
2836 | continue; | ||||
2837 | |||||
2838 | case AMK_Redeclaration: | ||||
2839 | case AMK_Override: | ||||
2840 | case AMK_ProtocolImplementation: | ||||
2841 | LocalAMK = AMK; | ||||
2842 | break; | ||||
2843 | } | ||||
2844 | } | ||||
2845 | |||||
2846 | // Already handled. | ||||
2847 | if (isa<UsedAttr>(I)) | ||||
2848 | continue; | ||||
2849 | |||||
2850 | if (mergeDeclAttribute(*this, New, I, LocalAMK)) | ||||
2851 | foundAny = true; | ||||
2852 | } | ||||
2853 | |||||
2854 | if (mergeAlignedAttrs(*this, New, Old)) | ||||
2855 | foundAny = true; | ||||
2856 | |||||
2857 | if (!foundAny) New->dropAttrs(); | ||||
2858 | } | ||||
2859 | |||||
2860 | /// mergeParamDeclAttributes - Copy attributes from the old parameter | ||||
2861 | /// to the new one. | ||||
2862 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, | ||||
2863 | const ParmVarDecl *oldDecl, | ||||
2864 | Sema &S) { | ||||
2865 | // C++11 [dcl.attr.depend]p2: | ||||
2866 | // The first declaration of a function shall specify the | ||||
2867 | // carries_dependency attribute for its declarator-id if any declaration | ||||
2868 | // of the function specifies the carries_dependency attribute. | ||||
2869 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); | ||||
2870 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { | ||||
2871 | S.Diag(CDA->getLocation(), | ||||
2872 | diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; | ||||
2873 | // Find the first declaration of the parameter. | ||||
2874 | // FIXME: Should we build redeclaration chains for function parameters? | ||||
2875 | const FunctionDecl *FirstFD = | ||||
2876 | cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); | ||||
2877 | const ParmVarDecl *FirstVD = | ||||
2878 | FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); | ||||
2879 | S.Diag(FirstVD->getLocation(), | ||||
2880 | diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; | ||||
2881 | } | ||||
2882 | |||||
2883 | if (!oldDecl->hasAttrs()) | ||||
2884 | return; | ||||
2885 | |||||
2886 | bool foundAny = newDecl->hasAttrs(); | ||||
2887 | |||||
2888 | // Ensure that any moving of objects within the allocated map is | ||||
2889 | // done before we process them. | ||||
2890 | if (!foundAny) newDecl->setAttrs(AttrVec()); | ||||
2891 | |||||
2892 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { | ||||
2893 | if (!DeclHasAttr(newDecl, I)) { | ||||
2894 | InheritableAttr *newAttr = | ||||
2895 | cast<InheritableParamAttr>(I->clone(S.Context)); | ||||
2896 | newAttr->setInherited(true); | ||||
2897 | newDecl->addAttr(newAttr); | ||||
2898 | foundAny = true; | ||||
2899 | } | ||||
2900 | } | ||||
2901 | |||||
2902 | if (!foundAny) newDecl->dropAttrs(); | ||||
2903 | } | ||||
2904 | |||||
2905 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, | ||||
2906 | const ParmVarDecl *OldParam, | ||||
2907 | Sema &S) { | ||||
2908 | if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { | ||||
2909 | if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { | ||||
2910 | if (*Oldnullability != *Newnullability) { | ||||
2911 | S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) | ||||
2912 | << DiagNullabilityKind( | ||||
2913 | *Newnullability, | ||||
2914 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | ||||
2915 | != 0)) | ||||
2916 | << DiagNullabilityKind( | ||||
2917 | *Oldnullability, | ||||
2918 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | ||||
2919 | != 0)); | ||||
2920 | S.Diag(OldParam->getLocation(), diag::note_previous_declaration); | ||||
2921 | } | ||||
2922 | } else { | ||||
2923 | QualType NewT = NewParam->getType(); | ||||
2924 | NewT = S.Context.getAttributedType( | ||||
2925 | AttributedType::getNullabilityAttrKind(*Oldnullability), | ||||
2926 | NewT, NewT); | ||||
2927 | NewParam->setType(NewT); | ||||
2928 | } | ||||
2929 | } | ||||
2930 | } | ||||
2931 | |||||
2932 | namespace { | ||||
2933 | |||||
2934 | /// Used in MergeFunctionDecl to keep track of function parameters in | ||||
2935 | /// C. | ||||
2936 | struct GNUCompatibleParamWarning { | ||||
2937 | ParmVarDecl *OldParm; | ||||
2938 | ParmVarDecl *NewParm; | ||||
2939 | QualType PromotedType; | ||||
2940 | }; | ||||
2941 | |||||
2942 | } // end anonymous namespace | ||||
2943 | |||||
2944 | /// getSpecialMember - get the special member enum for a method. | ||||
2945 | Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { | ||||
2946 | if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { | ||||
2947 | if (Ctor->isDefaultConstructor()) | ||||
2948 | return Sema::CXXDefaultConstructor; | ||||
2949 | |||||
2950 | if (Ctor->isCopyConstructor()) | ||||
2951 | return Sema::CXXCopyConstructor; | ||||
2952 | |||||
2953 | if (Ctor->isMoveConstructor()) | ||||
2954 | return Sema::CXXMoveConstructor; | ||||
2955 | } else if (isa<CXXDestructorDecl>(MD)) { | ||||
2956 | return Sema::CXXDestructor; | ||||
2957 | } else if (MD->isCopyAssignmentOperator()) { | ||||
2958 | return Sema::CXXCopyAssignment; | ||||
2959 | } else if (MD->isMoveAssignmentOperator()) { | ||||
2960 | return Sema::CXXMoveAssignment; | ||||
2961 | } | ||||
2962 | |||||
2963 | return Sema::CXXInvalid; | ||||
2964 | } | ||||
2965 | |||||
2966 | // Determine whether the previous declaration was a definition, implicit | ||||
2967 | // declaration, or a declaration. | ||||
2968 | template <typename T> | ||||
2969 | static std::pair<diag::kind, SourceLocation> | ||||
2970 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { | ||||
2971 | diag::kind PrevDiag; | ||||
2972 | SourceLocation OldLocation = Old->getLocation(); | ||||
2973 | if (Old->isThisDeclarationADefinition()) | ||||
2974 | PrevDiag = diag::note_previous_definition; | ||||
2975 | else if (Old->isImplicit()) { | ||||
2976 | PrevDiag = diag::note_previous_implicit_declaration; | ||||
2977 | if (OldLocation.isInvalid()) | ||||
2978 | OldLocation = New->getLocation(); | ||||
2979 | } else | ||||
2980 | PrevDiag = diag::note_previous_declaration; | ||||
2981 | return std::make_pair(PrevDiag, OldLocation); | ||||
2982 | } | ||||
2983 | |||||
2984 | /// canRedefineFunction - checks if a function can be redefined. Currently, | ||||
2985 | /// only extern inline functions can be redefined, and even then only in | ||||
2986 | /// GNU89 mode. | ||||
2987 | static bool canRedefineFunction(const FunctionDecl *FD, | ||||
2988 | const LangOptions& LangOpts) { | ||||
2989 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && | ||||
2990 | !LangOpts.CPlusPlus && | ||||
2991 | FD->isInlineSpecified() && | ||||
2992 | FD->getStorageClass() == SC_Extern); | ||||
2993 | } | ||||
2994 | |||||
2995 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { | ||||
2996 | const AttributedType *AT = T->getAs<AttributedType>(); | ||||
2997 | while (AT && !AT->isCallingConv()) | ||||
2998 | AT = AT->getModifiedType()->getAs<AttributedType>(); | ||||
2999 | return AT; | ||||
3000 | } | ||||
3001 | |||||
3002 | template <typename T> | ||||
3003 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { | ||||
3004 | const DeclContext *DC = Old->getDeclContext(); | ||||
3005 | if (DC->isRecord()) | ||||
3006 | return false; | ||||
3007 | |||||
3008 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); | ||||
3009 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) | ||||
3010 | return true; | ||||
3011 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) | ||||
3012 | return true; | ||||
3013 | return false; | ||||
3014 | } | ||||
3015 | |||||
3016 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } | ||||
3017 | static bool isExternC(VarTemplateDecl *) { return false; } | ||||
3018 | |||||
3019 | /// Check whether a redeclaration of an entity introduced by a | ||||
3020 | /// using-declaration is valid, given that we know it's not an overload | ||||
3021 | /// (nor a hidden tag declaration). | ||||
3022 | template<typename ExpectedDecl> | ||||
3023 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, | ||||
3024 | ExpectedDecl *New) { | ||||
3025 | // C++11 [basic.scope.declarative]p4: | ||||
3026 | // Given a set of declarations in a single declarative region, each of | ||||
3027 | // which specifies the same unqualified name, | ||||
3028 | // -- they shall all refer to the same entity, or all refer to functions | ||||
3029 | // and function templates; or | ||||
3030 | // -- exactly one declaration shall declare a class name or enumeration | ||||
3031 | // name that is not a typedef name and the other declarations shall all | ||||
3032 | // refer to the same variable or enumerator, or all refer to functions | ||||
3033 | // and function templates; in this case the class name or enumeration | ||||
3034 | // name is hidden (3.3.10). | ||||
3035 | |||||
3036 | // C++11 [namespace.udecl]p14: | ||||
3037 | // If a function declaration in namespace scope or block scope has the | ||||
3038 | // same name and the same parameter-type-list as a function introduced | ||||
3039 | // by a using-declaration, and the declarations do not declare the same | ||||
3040 | // function, the program is ill-formed. | ||||
3041 | |||||
3042 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); | ||||
3043 | if (Old && | ||||
3044 | !Old->getDeclContext()->getRedeclContext()->Equals( | ||||
3045 | New->getDeclContext()->getRedeclContext()) && | ||||
3046 | !(isExternC(Old) && isExternC(New))) | ||||
3047 | Old = nullptr; | ||||
3048 | |||||
3049 | if (!Old) { | ||||
3050 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); | ||||
3051 | S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); | ||||
3052 | S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; | ||||
3053 | return true; | ||||
3054 | } | ||||
3055 | return false; | ||||
3056 | } | ||||
3057 | |||||
3058 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, | ||||
3059 | const FunctionDecl *B) { | ||||
3060 | assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast <void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 3060, __PRETTY_FUNCTION__)); | ||||
3061 | |||||
3062 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { | ||||
3063 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); | ||||
3064 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); | ||||
3065 | if (AttrA == AttrB) | ||||
3066 | return true; | ||||
3067 | return AttrA && AttrB && AttrA->getType() == AttrB->getType() && | ||||
3068 | AttrA->isDynamic() == AttrB->isDynamic(); | ||||
3069 | }; | ||||
3070 | |||||
3071 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); | ||||
3072 | } | ||||
3073 | |||||
3074 | /// If necessary, adjust the semantic declaration context for a qualified | ||||
3075 | /// declaration to name the correct inline namespace within the qualifier. | ||||
3076 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, | ||||
3077 | DeclaratorDecl *OldD) { | ||||
3078 | // The only case where we need to update the DeclContext is when | ||||
3079 | // redeclaration lookup for a qualified name finds a declaration | ||||
3080 | // in an inline namespace within the context named by the qualifier: | ||||
3081 | // | ||||
3082 | // inline namespace N { int f(); } | ||||
3083 | // int ::f(); // Sema DC needs adjusting from :: to N::. | ||||
3084 | // | ||||
3085 | // For unqualified declarations, the semantic context *can* change | ||||
3086 | // along the redeclaration chain (for local extern declarations, | ||||
3087 | // extern "C" declarations, and friend declarations in particular). | ||||
3088 | if (!NewD->getQualifier()) | ||||
3089 | return; | ||||
3090 | |||||
3091 | // NewD is probably already in the right context. | ||||
3092 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); | ||||
3093 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); | ||||
3094 | if (NamedDC->Equals(SemaDC)) | ||||
3095 | return; | ||||
3096 | |||||
3097 | assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 3099, __PRETTY_FUNCTION__)) | ||||
3098 | NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 3099, __PRETTY_FUNCTION__)) | ||||
3099 | "unexpected context for redeclaration")(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 3099, __PRETTY_FUNCTION__)); | ||||
3100 | |||||
3101 | auto *LexDC = NewD->getLexicalDeclContext(); | ||||
3102 | auto FixSemaDC = [=](NamedDecl *D) { | ||||
3103 | if (!D) | ||||
3104 | return; | ||||
3105 | D->setDeclContext(SemaDC); | ||||
3106 | D->setLexicalDeclContext(LexDC); | ||||
3107 | }; | ||||
3108 | |||||
3109 | FixSemaDC(NewD); | ||||
3110 | if (auto *FD = dyn_cast<FunctionDecl>(NewD)) | ||||
3111 | FixSemaDC(FD->getDescribedFunctionTemplate()); | ||||
3112 | else if (auto *VD = dyn_cast<VarDecl>(NewD)) | ||||
3113 | FixSemaDC(VD->getDescribedVarTemplate()); | ||||
3114 | } | ||||
3115 | |||||
3116 | /// MergeFunctionDecl - We just parsed a function 'New' from | ||||
3117 | /// declarator D which has the same name and scope as a previous | ||||
3118 | /// declaration 'Old'. Figure out how to resolve this situation, | ||||
3119 | /// merging decls or emitting diagnostics as appropriate. | ||||
3120 | /// | ||||
3121 | /// In C++, New and Old must be declarations that are not | ||||
3122 | /// overloaded. Use IsOverload to determine whether New and Old are | ||||
3123 | /// overloaded, and to select the Old declaration that New should be | ||||
3124 | /// merged with. | ||||
3125 | /// | ||||
3126 | /// Returns true if there was an error, false otherwise. | ||||
3127 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, | ||||
3128 | Scope *S, bool MergeTypeWithOld) { | ||||
3129 | // Verify the old decl was also a function. | ||||
3130 | FunctionDecl *Old = OldD->getAsFunction(); | ||||
3131 | if (!Old) { | ||||
3132 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { | ||||
3133 | if (New->getFriendObjectKind()) { | ||||
3134 | Diag(New->getLocation(), diag::err_using_decl_friend); | ||||
3135 | Diag(Shadow->getTargetDecl()->getLocation(), | ||||
3136 | diag::note_using_decl_target); | ||||
3137 | Diag(Shadow->getUsingDecl()->getLocation(), | ||||
3138 | diag::note_using_decl) << 0; | ||||
3139 | return true; | ||||
3140 | } | ||||
3141 | |||||
3142 | // Check whether the two declarations might declare the same function. | ||||
3143 | if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) | ||||
3144 | return true; | ||||
3145 | OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); | ||||
3146 | } else { | ||||
3147 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||
3148 | << New->getDeclName(); | ||||
3149 | notePreviousDefinition(OldD, New->getLocation()); | ||||
3150 | return true; | ||||
3151 | } | ||||
3152 | } | ||||
3153 | |||||
3154 | // If the old declaration is invalid, just give up here. | ||||
3155 | if (Old->isInvalidDecl()) | ||||
3156 | return true; | ||||
3157 | |||||
3158 | // Disallow redeclaration of some builtins. | ||||
3159 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { | ||||
3160 | Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); | ||||
3161 | Diag(Old->getLocation(), diag::note_previous_builtin_declaration) | ||||
3162 | << Old << Old->getType(); | ||||
3163 | return true; | ||||
3164 | } | ||||
3165 | |||||
3166 | diag::kind PrevDiag; | ||||
3167 | SourceLocation OldLocation; | ||||
3168 | std::tie(PrevDiag, OldLocation) = | ||||
3169 | getNoteDiagForInvalidRedeclaration(Old, New); | ||||
3170 | |||||
3171 | // Don't complain about this if we're in GNU89 mode and the old function | ||||
3172 | // is an extern inline function. | ||||
3173 | // Don't complain about specializations. They are not supposed to have | ||||
3174 | // storage classes. | ||||
3175 | if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && | ||||
3176 | New->getStorageClass() == SC_Static && | ||||
3177 | Old->hasExternalFormalLinkage() && | ||||
3178 | !New->getTemplateSpecializationInfo() && | ||||
3179 | !canRedefineFunction(Old, getLangOpts())) { | ||||
3180 | if (getLangOpts().MicrosoftExt) { | ||||
3181 | Diag(New->getLocation(), diag::ext_static_non_static) << New; | ||||
3182 | Diag(OldLocation, PrevDiag); | ||||
3183 | } else { | ||||
3184 | Diag(New->getLocation(), diag::err_static_non_static) << New; | ||||
3185 | Diag(OldLocation, PrevDiag); | ||||
3186 | return true; | ||||
3187 | } | ||||
3188 | } | ||||
3189 | |||||
3190 | if (New->hasAttr<InternalLinkageAttr>() && | ||||
3191 | !Old->hasAttr<InternalLinkageAttr>()) { | ||||
3192 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | ||||
3193 | << New->getDeclName(); | ||||
3194 | notePreviousDefinition(Old, New->getLocation()); | ||||
3195 | New->dropAttr<InternalLinkageAttr>(); | ||||
3196 | } | ||||
3197 | |||||
3198 | if (CheckRedeclarationModuleOwnership(New, Old)) | ||||
3199 | return true; | ||||
3200 | |||||
3201 | if (!getLangOpts().CPlusPlus) { | ||||
3202 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); | ||||
3203 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { | ||||
3204 | Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) | ||||
3205 | << New << OldOvl; | ||||
3206 | |||||
3207 | // Try our best to find a decl that actually has the overloadable | ||||
3208 | // attribute for the note. In most cases (e.g. programs with only one | ||||
3209 | // broken declaration/definition), this won't matter. | ||||
3210 | // | ||||
3211 | // FIXME: We could do this if we juggled some extra state in | ||||
3212 | // OverloadableAttr, rather than just removing it. | ||||
3213 | const Decl *DiagOld = Old; | ||||
3214 | if (OldOvl) { | ||||
3215 | auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { | ||||
3216 | const auto *A = D->getAttr<OverloadableAttr>(); | ||||
3217 | return A && !A->isImplicit(); | ||||
3218 | }); | ||||
3219 | // If we've implicitly added *all* of the overloadable attrs to this | ||||
3220 | // chain, emitting a "previous redecl" note is pointless. | ||||
3221 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; | ||||
3222 | } | ||||
3223 | |||||
3224 | if (DiagOld) | ||||
3225 | Diag(DiagOld->getLocation(), | ||||
3226 | diag::note_attribute_overloadable_prev_overload) | ||||
3227 | << OldOvl; | ||||
3228 | |||||
3229 | if (OldOvl) | ||||
3230 | New->addAttr(OverloadableAttr::CreateImplicit(Context)); | ||||
3231 | else | ||||
3232 | New->dropAttr<OverloadableAttr>(); | ||||
3233 | } | ||||
3234 | } | ||||
3235 | |||||
3236 | // If a function is first declared with a calling convention, but is later | ||||
3237 | // declared or defined without one, all following decls assume the calling | ||||
3238 | // convention of the first. | ||||
3239 | // | ||||
3240 | // It's OK if a function is first declared without a calling convention, | ||||
3241 | // but is later declared or defined with the default calling convention. | ||||
3242 | // | ||||
3243 | // To test if either decl has an explicit calling convention, we look for | ||||
3244 | // AttributedType sugar nodes on the type as written. If they are missing or | ||||
3245 | // were canonicalized away, we assume the calling convention was implicit. | ||||
3246 | // | ||||
3247 | // Note also that we DO NOT return at this point, because we still have | ||||
3248 | // other tests to run. | ||||
3249 | QualType OldQType = Context.getCanonicalType(Old->getType()); | ||||
3250 | QualType NewQType = Context.getCanonicalType(New->getType()); | ||||
3251 | const FunctionType *OldType = cast<FunctionType>(OldQType); | ||||
3252 | const FunctionType *NewType = cast<FunctionType>(NewQType); | ||||
3253 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | ||||
3254 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | ||||
3255 | bool RequiresAdjustment = false; | ||||
3256 | |||||
3257 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { | ||||
3258 | FunctionDecl *First = Old->getFirstDecl(); | ||||
3259 | const FunctionType *FT = | ||||
3260 | First->getType().getCanonicalType()->castAs<FunctionType>(); | ||||
3261 | FunctionType::ExtInfo FI = FT->getExtInfo(); | ||||
3262 | bool NewCCExplicit = getCallingConvAttributedType(New->getType()); | ||||
3263 | if (!NewCCExplicit) { | ||||
3264 | // Inherit the CC from the previous declaration if it was specified | ||||
3265 | // there but not here. | ||||
3266 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | ||||
3267 | RequiresAdjustment = true; | ||||
3268 | } else if (New->getBuiltinID()) { | ||||
3269 | // Calling Conventions on a Builtin aren't really useful and setting a | ||||
3270 | // default calling convention and cdecl'ing some builtin redeclarations is | ||||
3271 | // common, so warn and ignore the calling convention on the redeclaration. | ||||
3272 | Diag(New->getLocation(), diag::warn_cconv_unsupported) | ||||
3273 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | ||||
3274 | << (int)CallingConventionIgnoredReason::BuiltinFunction; | ||||
3275 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | ||||
3276 | RequiresAdjustment = true; | ||||
3277 | } else { | ||||
3278 | // Calling conventions aren't compatible, so complain. | ||||
3279 | bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); | ||||
3280 | Diag(New->getLocation(), diag::err_cconv_change) | ||||
3281 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | ||||
3282 | << !FirstCCExplicit | ||||
3283 | << (!FirstCCExplicit ? "" : | ||||
3284 | FunctionType::getNameForCallConv(FI.getCC())); | ||||
3285 | |||||
3286 | // Put the note on the first decl, since it is the one that matters. | ||||
3287 | Diag(First->getLocation(), diag::note_previous_declaration); | ||||
3288 | return true; | ||||
3289 | } | ||||
3290 | } | ||||
3291 | |||||
3292 | // FIXME: diagnose the other way around? | ||||
3293 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { | ||||
3294 | NewTypeInfo = NewTypeInfo.withNoReturn(true); | ||||
3295 | RequiresAdjustment = true; | ||||
3296 | } | ||||
3297 | |||||
3298 | // Merge regparm attribute. | ||||
3299 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || | ||||
3300 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { | ||||
3301 | if (NewTypeInfo.getHasRegParm()) { | ||||
3302 | Diag(New->getLocation(), diag::err_regparm_mismatch) | ||||
3303 | << NewType->getRegParmType() | ||||
3304 | << OldType->getRegParmType(); | ||||
3305 | Diag(OldLocation, diag::note_previous_declaration); | ||||
3306 | return true; | ||||
3307 | } | ||||
3308 | |||||
3309 | NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); | ||||
3310 | RequiresAdjustment = true; | ||||
3311 | } | ||||
3312 | |||||
3313 | // Merge ns_returns_retained attribute. | ||||
3314 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { | ||||
3315 | if (NewTypeInfo.getProducesResult()) { | ||||
3316 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) | ||||
3317 | << "'ns_returns_retained'"; | ||||
3318 | Diag(OldLocation, diag::note_previous_declaration); | ||||
3319 | return true; | ||||
3320 | } | ||||
3321 | |||||
3322 | NewTypeInfo = NewTypeInfo.withProducesResult(true); | ||||
3323 | RequiresAdjustment = true; | ||||
3324 | } | ||||
3325 | |||||
3326 | if (OldTypeInfo.getNoCallerSavedRegs() != | ||||
3327 | NewTypeInfo.getNoCallerSavedRegs()) { | ||||
3328 | if (NewTypeInfo.getNoCallerSavedRegs()) { | ||||
3329 | AnyX86NoCallerSavedRegistersAttr *Attr = | ||||
3330 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); | ||||
3331 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; | ||||
3332 | Diag(OldLocation, diag::note_previous_declaration); | ||||
3333 | return true; | ||||
3334 | } | ||||
3335 | |||||
3336 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); | ||||
3337 | RequiresAdjustment = true; | ||||
3338 | } | ||||
3339 | |||||
3340 | if (RequiresAdjustment) { | ||||
3341 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); | ||||
3342 | AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); | ||||
3343 | New->setType(QualType(AdjustedType, 0)); | ||||
3344 | NewQType = Context.getCanonicalType(New->getType()); | ||||
3345 | } | ||||
3346 | |||||
3347 | // If this redeclaration makes the function inline, we may need to add it to | ||||
3348 | // UndefinedButUsed. | ||||
3349 | if (!Old->isInlined() && New->isInlined() && | ||||
3350 | !New->hasAttr<GNUInlineAttr>() && | ||||
3351 | !getLangOpts().GNUInline && | ||||
3352 | Old->isUsed(false) && | ||||
3353 | !Old->isDefined() && !New->isThisDeclarationADefinition()) | ||||
3354 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | ||||
3355 | SourceLocation())); | ||||
3356 | |||||
3357 | // If this redeclaration makes it newly gnu_inline, we don't want to warn | ||||
3358 | // about it. | ||||
3359 | if (New->hasAttr<GNUInlineAttr>() && | ||||
3360 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { | ||||
3361 | UndefinedButUsed.erase(Old->getCanonicalDecl()); | ||||
3362 | } | ||||
3363 | |||||
3364 | // If pass_object_size params don't match up perfectly, this isn't a valid | ||||
3365 | // redeclaration. | ||||
3366 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && | ||||
3367 | !hasIdenticalPassObjectSizeAttrs(Old, New)) { | ||||
3368 | Diag(New->getLocation(), diag::err_different_pass_object_size_params) | ||||
3369 | << New->getDeclName(); | ||||
3370 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||
3371 | return true; | ||||
3372 | } | ||||
3373 | |||||
3374 | if (getLangOpts().CPlusPlus) { | ||||
3375 | // C++1z [over.load]p2 | ||||
3376 | // Certain function declarations cannot be overloaded: | ||||
3377 | // -- Function declarations that differ only in the return type, | ||||
3378 | // the exception specification, or both cannot be overloaded. | ||||
3379 | |||||
3380 | // Check the exception specifications match. This may recompute the type of | ||||
3381 | // both Old and New if it resolved exception specifications, so grab the | ||||
3382 | // types again after this. Because this updates the type, we do this before | ||||
3383 | // any of the other checks below, which may update the "de facto" NewQType | ||||
3384 | // but do not necessarily update the type of New. | ||||
3385 | if (CheckEquivalentExceptionSpec(Old, New)) | ||||
3386 | return true; | ||||
3387 | OldQType = Context.getCanonicalType(Old->getType()); | ||||
3388 | NewQType = Context.getCanonicalType(New->getType()); | ||||
3389 | |||||
3390 | // Go back to the type source info to compare the declared return types, | ||||
3391 | // per C++1y [dcl.type.auto]p13: | ||||
3392 | // Redeclarations or specializations of a function or function template | ||||
3393 | // with a declared return type that uses a placeholder type shall also | ||||
3394 | // use that placeholder, not a deduced type. | ||||
3395 | QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); | ||||
3396 | QualType NewDeclaredReturnType = New->getDeclaredReturnType(); | ||||
3397 | if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && | ||||
3398 | canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, | ||||
3399 | OldDeclaredReturnType)) { | ||||
3400 | QualType ResQT; | ||||
3401 | if (NewDeclaredReturnType->isObjCObjectPointerType() && | ||||
3402 | OldDeclaredReturnType->isObjCObjectPointerType()) | ||||
3403 | // FIXME: This does the wrong thing for a deduced return type. | ||||
3404 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); | ||||
3405 | if (ResQT.isNull()) { | ||||
3406 | if (New->isCXXClassMember() && New->isOutOfLine()) | ||||
3407 | Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) | ||||
3408 | << New << New->getReturnTypeSourceRange(); | ||||
3409 | else | ||||
3410 | Diag(New->getLocation(), diag::err_ovl_diff_return_type) | ||||
3411 | << New->getReturnTypeSourceRange(); | ||||
3412 | Diag(OldLocation, PrevDiag) << Old << Old->getType() | ||||
3413 | << Old->getReturnTypeSourceRange(); | ||||
3414 | return true; | ||||
3415 | } | ||||
3416 | else | ||||
3417 | NewQType = ResQT; | ||||
3418 | } | ||||
3419 | |||||
3420 | QualType OldReturnType = OldType->getReturnType(); | ||||
3421 | QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); | ||||
3422 | if (OldReturnType != NewReturnType) { | ||||
3423 | // If this function has a deduced return type and has already been | ||||
3424 | // defined, copy the deduced value from the old declaration. | ||||
3425 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); | ||||
3426 | if (OldAT && OldAT->isDeduced()) { | ||||
3427 | New->setType( | ||||
3428 | SubstAutoType(New->getType(), | ||||
3429 | OldAT->isDependentType() ? Context.DependentTy | ||||
3430 | : OldAT->getDeducedType())); | ||||
3431 | NewQType = Context.getCanonicalType( | ||||
3432 | SubstAutoType(NewQType, | ||||
3433 | OldAT->isDependentType() ? Context.DependentTy | ||||
3434 | : OldAT->getDeducedType())); | ||||
3435 | } | ||||
3436 | } | ||||
3437 | |||||
3438 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); | ||||
3439 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); | ||||
3440 | if (OldMethod && NewMethod) { | ||||
3441 | // Preserve triviality. | ||||
3442 | NewMethod->setTrivial(OldMethod->isTrivial()); | ||||
3443 | |||||
3444 | // MSVC allows explicit template specialization at class scope: | ||||
3445 | // 2 CXXMethodDecls referring to the same function will be injected. | ||||
3446 | // We don't want a redeclaration error. | ||||
3447 | bool IsClassScopeExplicitSpecialization = | ||||
3448 | OldMethod->isFunctionTemplateSpecialization() && | ||||
3449 | NewMethod->isFunctionTemplateSpecialization(); | ||||
3450 | bool isFriend = NewMethod->getFriendObjectKind(); | ||||
3451 | |||||
3452 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && | ||||
3453 | !IsClassScopeExplicitSpecialization) { | ||||
3454 | // -- Member function declarations with the same name and the | ||||
3455 | // same parameter types cannot be overloaded if any of them | ||||
3456 | // is a static member function declaration. | ||||
3457 | if (OldMethod->isStatic() != NewMethod->isStatic()) { | ||||
3458 | Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); | ||||
3459 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||
3460 | return true; | ||||
3461 | } | ||||
3462 | |||||
3463 | // C++ [class.mem]p1: | ||||
3464 | // [...] A member shall not be declared twice in the | ||||
3465 | // member-specification, except that a nested class or member | ||||
3466 | // class template can be declared and then later defined. | ||||
3467 | if (!inTemplateInstantiation()) { | ||||
3468 | unsigned NewDiag; | ||||
3469 | if (isa<CXXConstructorDecl>(OldMethod)) | ||||
3470 | NewDiag = diag::err_constructor_redeclared; | ||||
3471 | else if (isa<CXXDestructorDecl>(NewMethod)) | ||||
3472 | NewDiag = diag::err_destructor_redeclared; | ||||
3473 | else if (isa<CXXConversionDecl>(NewMethod)) | ||||
3474 | NewDiag = diag::err_conv_function_redeclared; | ||||
3475 | else | ||||
3476 | NewDiag = diag::err_member_redeclared; | ||||
3477 | |||||
3478 | Diag(New->getLocation(), NewDiag); | ||||
3479 | } else { | ||||
3480 | Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) | ||||
3481 | << New << New->getType(); | ||||
3482 | } | ||||
3483 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||
3484 | return true; | ||||
3485 | |||||
3486 | // Complain if this is an explicit declaration of a special | ||||
3487 | // member that was initially declared implicitly. | ||||
3488 | // | ||||
3489 | // As an exception, it's okay to befriend such methods in order | ||||
3490 | // to permit the implicit constructor/destructor/operator calls. | ||||
3491 | } else if (OldMethod->isImplicit()) { | ||||
3492 | if (isFriend) { | ||||
3493 | NewMethod->setImplicit(); | ||||
3494 | } else { | ||||
3495 | Diag(NewMethod->getLocation(), | ||||
3496 | diag::err_definition_of_implicitly_declared_member) | ||||
3497 | << New << getSpecialMember(OldMethod); | ||||
3498 | return true; | ||||
3499 | } | ||||
3500 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { | ||||
3501 | Diag(NewMethod->getLocation(), | ||||
3502 | diag::err_definition_of_explicitly_defaulted_member) | ||||
3503 | << getSpecialMember(OldMethod); | ||||
3504 | return true; | ||||
3505 | } | ||||
3506 | } | ||||
3507 | |||||
3508 | // C++11 [dcl.attr.noreturn]p1: | ||||
3509 | // The first declaration of a function shall specify the noreturn | ||||
3510 | // attribute if any declaration of that function specifies the noreturn | ||||
3511 | // attribute. | ||||
3512 | const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); | ||||
3513 | if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { | ||||
3514 | Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); | ||||
3515 | Diag(Old->getFirstDecl()->getLocation(), | ||||
3516 | diag::note_noreturn_missing_first_decl); | ||||
3517 | } | ||||
3518 | |||||
3519 | // C++11 [dcl.attr.depend]p2: | ||||
3520 | // The first declaration of a function shall specify the | ||||
3521 | // carries_dependency attribute for its declarator-id if any declaration | ||||
3522 | // of the function specifies the carries_dependency attribute. | ||||
3523 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); | ||||
3524 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { | ||||
3525 | Diag(CDA->getLocation(), | ||||
3526 | diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; | ||||
3527 | Diag(Old->getFirstDecl()->getLocation(), | ||||
3528 | diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; | ||||
3529 | } | ||||
3530 | |||||
3531 | // (C++98 8.3.5p3): | ||||
3532 | // All declarations for a function shall agree exactly in both the | ||||
3533 | // return type and the parameter-type-list. | ||||
3534 | // We also want to respect all the extended bits except noreturn. | ||||
3535 | |||||
3536 | // noreturn should now match unless the old type info didn't have it. | ||||
3537 | QualType OldQTypeForComparison = OldQType; | ||||
3538 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { | ||||
3539 | auto *OldType = OldQType->castAs<FunctionProtoType>(); | ||||
3540 | const FunctionType *OldTypeForComparison | ||||
3541 | = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); | ||||
3542 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); | ||||
3543 | assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void> (0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 3543, __PRETTY_FUNCTION__)); | ||||
3544 | } | ||||
3545 | |||||
3546 | if (haveIncompatibleLanguageLinkages(Old, New)) { | ||||
3547 | // As a special case, retain the language linkage from previous | ||||
3548 | // declarations of a friend function as an extension. | ||||
3549 | // | ||||
3550 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC | ||||
3551 | // and is useful because there's otherwise no way to specify language | ||||
3552 | // linkage within class scope. | ||||
3553 | // | ||||
3554 | // Check cautiously as the friend object kind isn't yet complete. | ||||
3555 | if (New->getFriendObjectKind() != Decl::FOK_None) { | ||||
3556 | Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; | ||||
3557 | Diag(OldLocation, PrevDiag); | ||||
3558 | } else { | ||||
3559 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | ||||
3560 | Diag(OldLocation, PrevDiag); | ||||
3561 | return true; | ||||
3562 | } | ||||
3563 | } | ||||
3564 | |||||
3565 | // If the function types are compatible, merge the declarations. Ignore the | ||||
3566 | // exception specifier because it was already checked above in | ||||
3567 | // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics | ||||
3568 | // about incompatible types under -fms-compatibility. | ||||
3569 | if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, | ||||
3570 | NewQType)) | ||||
3571 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||
3572 | |||||
3573 | // If the types are imprecise (due to dependent constructs in friends or | ||||
3574 | // local extern declarations), it's OK if they differ. We'll check again | ||||
3575 | // during instantiation. | ||||
3576 | if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) | ||||
3577 | return false; | ||||
3578 | |||||
3579 | // Fall through for conflicting redeclarations and redefinitions. | ||||
3580 | } | ||||
3581 | |||||
3582 | // C: Function types need to be compatible, not identical. This handles | ||||
3583 | // duplicate function decls like "void f(int); void f(enum X);" properly. | ||||
3584 | if (!getLangOpts().CPlusPlus && | ||||
3585 | Context.typesAreCompatible(OldQType, NewQType)) { | ||||
3586 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); | ||||
3587 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); | ||||
3588 | const FunctionProtoType *OldProto = nullptr; | ||||
3589 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && | ||||
3590 | (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { | ||||
3591 | // The old declaration provided a function prototype, but the | ||||
3592 | // new declaration does not. Merge in the prototype. | ||||
3593 | assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((!OldProto->hasExceptionSpec() && "Exception spec in C" ) ? static_cast<void> (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 3593, __PRETTY_FUNCTION__)); | ||||
3594 | SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); | ||||
3595 | NewQType = | ||||
3596 | Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, | ||||
3597 | OldProto->getExtProtoInfo()); | ||||
3598 | New->setType(NewQType); | ||||
3599 | New->setHasInheritedPrototype(); | ||||
3600 | |||||
3601 | // Synthesize parameters with the same types. | ||||
3602 | SmallVector<ParmVarDecl*, 16> Params; | ||||
3603 | for (const auto &ParamType : OldProto->param_types()) { | ||||
3604 | ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), | ||||
3605 | SourceLocation(), nullptr, | ||||
3606 | ParamType, /*TInfo=*/nullptr, | ||||
3607 | SC_None, nullptr); | ||||
3608 | Param->setScopeInfo(0, Params.size()); | ||||
3609 | Param->setImplicit(); | ||||
3610 | Params.push_back(Param); | ||||
3611 | } | ||||
3612 | |||||
3613 | New->setParams(Params); | ||||
3614 | } | ||||
3615 | |||||
3616 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||
3617 | } | ||||
3618 | |||||
3619 | // GNU C permits a K&R definition to follow a prototype declaration | ||||
3620 | // if the declared types of the parameters in the K&R definition | ||||
3621 | // match the types in the prototype declaration, even when the | ||||
3622 | // promoted types of the parameters from the K&R definition differ | ||||
3623 | // from the types in the prototype. GCC then keeps the types from | ||||
3624 | // the prototype. | ||||
3625 | // | ||||
3626 | // If a variadic prototype is followed by a non-variadic K&R definition, | ||||
3627 | // the K&R definition becomes variadic. This is sort of an edge case, but | ||||
3628 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and | ||||
3629 | // C99 6.9.1p8. | ||||
3630 | if (!getLangOpts().CPlusPlus && | ||||
3631 | Old->hasPrototype() && !New->hasPrototype() && | ||||
3632 | New->getType()->getAs<FunctionProtoType>() && | ||||
3633 | Old->getNumParams() == New->getNumParams()) { | ||||
3634 | SmallVector<QualType, 16> ArgTypes; | ||||
3635 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; | ||||
3636 | const FunctionProtoType *OldProto | ||||
3637 | = Old->getType()->getAs<FunctionProtoType>(); | ||||
3638 | const FunctionProtoType *NewProto | ||||
3639 | = New->getType()->getAs<FunctionProtoType>(); | ||||
3640 | |||||
3641 | // Determine whether this is the GNU C extension. | ||||
3642 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), | ||||
3643 | NewProto->getReturnType()); | ||||
3644 | bool LooseCompatible = !MergedReturn.isNull(); | ||||
3645 | for (unsigned Idx = 0, End = Old->getNumParams(); | ||||
3646 | LooseCompatible && Idx != End; ++Idx) { | ||||
3647 | ParmVarDecl *OldParm = Old->getParamDecl(Idx); | ||||
3648 | ParmVarDecl *NewParm = New->getParamDecl(Idx); | ||||
3649 | if (Context.typesAreCompatible(OldParm->getType(), | ||||
3650 | NewProto->getParamType(Idx))) { | ||||
3651 | ArgTypes.push_back(NewParm->getType()); | ||||
3652 | } else if (Context.typesAreCompatible(OldParm->getType(), | ||||
3653 | NewParm->getType(), | ||||
3654 | /*CompareUnqualified=*/true)) { | ||||
3655 | GNUCompatibleParamWarning Warn = { OldParm, NewParm, | ||||
3656 | NewProto->getParamType(Idx) }; | ||||
3657 | Warnings.push_back(Warn); | ||||
3658 | ArgTypes.push_back(NewParm->getType()); | ||||
3659 | } else | ||||
3660 | LooseCompatible = false; | ||||
3661 | } | ||||
3662 | |||||
3663 | if (LooseCompatible) { | ||||
3664 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { | ||||
3665 | Diag(Warnings[Warn].NewParm->getLocation(), | ||||
3666 | diag::ext_param_promoted_not_compatible_with_prototype) | ||||
3667 | << Warnings[Warn].PromotedType | ||||
3668 | << Warnings[Warn].OldParm->getType(); | ||||
3669 | if (Warnings[Warn].OldParm->getLocation().isValid()) | ||||
3670 | Diag(Warnings[Warn].OldParm->getLocation(), | ||||
3671 | diag::note_previous_declaration); | ||||
3672 | } | ||||
3673 | |||||
3674 | if (MergeTypeWithOld) | ||||
3675 | New->setType(Context.getFunctionType(MergedReturn, ArgTypes, | ||||
3676 | OldProto->getExtProtoInfo())); | ||||
3677 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||
3678 | } | ||||
3679 | |||||
3680 | // Fall through to diagnose conflicting types. | ||||
3681 | } | ||||
3682 | |||||
3683 | // A function that has already been declared has been redeclared or | ||||
3684 | // defined with a different type; show an appropriate diagnostic. | ||||
3685 | |||||
3686 | // If the previous declaration was an implicitly-generated builtin | ||||
3687 | // declaration, then at the very least we should use a specialized note. | ||||
3688 | unsigned BuiltinID; | ||||
3689 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { | ||||
3690 | // If it's actually a library-defined builtin function like 'malloc' | ||||
3691 | // or 'printf', just warn about the incompatible redeclaration. | ||||
3692 | if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { | ||||
3693 | Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; | ||||
3694 | Diag(OldLocation, diag::note_previous_builtin_declaration) | ||||
3695 | << Old << Old->getType(); | ||||
3696 | |||||
3697 | // If this is a global redeclaration, just forget hereafter | ||||
3698 | // about the "builtin-ness" of the function. | ||||
3699 | // | ||||
3700 | // Doing this for local extern declarations is problematic. If | ||||
3701 | // the builtin declaration remains visible, a second invalid | ||||
3702 | // local declaration will produce a hard error; if it doesn't | ||||
3703 | // remain visible, a single bogus local redeclaration (which is | ||||
3704 | // actually only a warning) could break all the downstream code. | ||||
3705 | if (!New->getLexicalDeclContext()->isFunctionOrMethod()) | ||||
3706 | New->getIdentifier()->revertBuiltin(); | ||||
3707 | |||||
3708 | return false; | ||||
3709 | } | ||||
3710 | |||||
3711 | PrevDiag = diag::note_previous_builtin_declaration; | ||||
3712 | } | ||||
3713 | |||||
3714 | Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); | ||||
3715 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||
3716 | return true; | ||||
3717 | } | ||||
3718 | |||||
3719 | /// Completes the merge of two function declarations that are | ||||
3720 | /// known to be compatible. | ||||
3721 | /// | ||||
3722 | /// This routine handles the merging of attributes and other | ||||
3723 | /// properties of function declarations from the old declaration to | ||||
3724 | /// the new declaration, once we know that New is in fact a | ||||
3725 | /// redeclaration of Old. | ||||
3726 | /// | ||||
3727 | /// \returns false | ||||
3728 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, | ||||
3729 | Scope *S, bool MergeTypeWithOld) { | ||||
3730 | // Merge the attributes | ||||
3731 | mergeDeclAttributes(New, Old); | ||||
3732 | |||||
3733 | // Merge "pure" flag. | ||||
3734 | if (Old->isPure()) | ||||
3735 | New->setPure(); | ||||
3736 | |||||
3737 | // Merge "used" flag. | ||||
3738 | if (Old->getMostRecentDecl()->isUsed(false)) | ||||
3739 | New->setIsUsed(); | ||||
3740 | |||||
3741 | // Merge attributes from the parameters. These can mismatch with K&R | ||||
3742 | // declarations. | ||||
3743 | if (New->getNumParams() == Old->getNumParams()) | ||||
3744 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { | ||||
3745 | ParmVarDecl *NewParam = New->getParamDecl(i); | ||||
3746 | ParmVarDecl *OldParam = Old->getParamDecl(i); | ||||
3747 | mergeParamDeclAttributes(NewParam, OldParam, *this); | ||||
3748 | mergeParamDeclTypes(NewParam, OldParam, *this); | ||||
3749 | } | ||||
3750 | |||||
3751 | if (getLangOpts().CPlusPlus) | ||||
3752 | return MergeCXXFunctionDecl(New, Old, S); | ||||
3753 | |||||
3754 | // Merge the function types so the we get the composite types for the return | ||||
3755 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl | ||||
3756 | // was visible. | ||||
3757 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); | ||||
3758 | if (!Merged.isNull() && MergeTypeWithOld) | ||||
3759 | New->setType(Merged); | ||||
3760 | |||||
3761 | return false; | ||||
3762 | } | ||||
3763 | |||||
3764 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, | ||||
3765 | ObjCMethodDecl *oldMethod) { | ||||
3766 | // Merge the attributes, including deprecated/unavailable | ||||
3767 | AvailabilityMergeKind MergeKind = | ||||
3768 | isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) | ||||
3769 | ? AMK_ProtocolImplementation | ||||
3770 | : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration | ||||
3771 | : AMK_Override; | ||||
3772 | |||||
3773 | mergeDeclAttributes(newMethod, oldMethod, MergeKind); | ||||
3774 | |||||
3775 | // Merge attributes from the parameters. | ||||
3776 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), | ||||
3777 | oe = oldMethod->param_end(); | ||||
3778 | for (ObjCMethodDecl::param_iterator | ||||
3779 | ni = newMethod->param_begin(), ne = newMethod->param_end(); | ||||
3780 | ni != ne && oi != oe; ++ni, ++oi) | ||||
3781 | mergeParamDeclAttributes(*ni, *oi, *this); | ||||
3782 | |||||
3783 | CheckObjCMethodOverride(newMethod, oldMethod); | ||||
3784 | } | ||||
3785 | |||||
3786 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { | ||||
3787 | assert(!S.Context.hasSameType(New->getType(), Old->getType()))((!S.Context.hasSameType(New->getType(), Old->getType() )) ? static_cast<void> (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 3787, __PRETTY_FUNCTION__)); | ||||
3788 | |||||
3789 | S.Diag(New->getLocation(), New->isThisDeclarationADefinition() | ||||
3790 | ? diag::err_redefinition_different_type | ||||
3791 | : diag::err_redeclaration_different_type) | ||||
3792 | << New->getDeclName() << New->getType() << Old->getType(); | ||||
3793 | |||||
3794 | diag::kind PrevDiag; | ||||
3795 | SourceLocation OldLocation; | ||||
3796 | std::tie(PrevDiag, OldLocation) | ||||
3797 | = getNoteDiagForInvalidRedeclaration(Old, New); | ||||
3798 | S.Diag(OldLocation, PrevDiag); | ||||
3799 | New->setInvalidDecl(); | ||||
3800 | } | ||||
3801 | |||||
3802 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and | ||||
3803 | /// scope as a previous declaration 'Old'. Figure out how to merge their types, | ||||
3804 | /// emitting diagnostics as appropriate. | ||||
3805 | /// | ||||
3806 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back | ||||
3807 | /// to here in AddInitializerToDecl. We can't check them before the initializer | ||||
3808 | /// is attached. | ||||
3809 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, | ||||
3810 | bool MergeTypeWithOld) { | ||||
3811 | if (New->isInvalidDecl() || Old->isInvalidDecl()) | ||||
3812 | return; | ||||
3813 | |||||
3814 | QualType MergedT; | ||||
3815 | if (getLangOpts().CPlusPlus) { | ||||
3816 | if (New->getType()->isUndeducedType()) { | ||||
3817 | // We don't know what the new type is until the initializer is attached. | ||||
3818 | return; | ||||
3819 | } else if (Context.hasSameType(New->getType(), Old->getType())) { | ||||
3820 | // These could still be something that needs exception specs checked. | ||||
3821 | return MergeVarDeclExceptionSpecs(New, Old); | ||||
3822 | } | ||||
3823 | // C++ [basic.link]p10: | ||||
3824 | // [...] the types specified by all declarations referring to a given | ||||
3825 | // object or function shall be identical, except that declarations for an | ||||
3826 | // array object can specify array types that differ by the presence or | ||||
3827 | // absence of a major array bound (8.3.4). | ||||
3828 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { | ||||
3829 | const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); | ||||
3830 | const ArrayType *NewArray = Context.getAsArrayType(New->getType()); | ||||
3831 | |||||
3832 | // We are merging a variable declaration New into Old. If it has an array | ||||
3833 | // bound, and that bound differs from Old's bound, we should diagnose the | ||||
3834 | // mismatch. | ||||
3835 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { | ||||
3836 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; | ||||
3837 | PrevVD = PrevVD->getPreviousDecl()) { | ||||
3838 | const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); | ||||
3839 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) | ||||
3840 | continue; | ||||
3841 | |||||
3842 | if (!Context.hasSameType(NewArray, PrevVDTy)) | ||||
3843 | return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); | ||||
3844 | } | ||||
3845 | } | ||||
3846 | |||||
3847 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { | ||||
3848 | if (Context.hasSameType(OldArray->getElementType(), | ||||
3849 | NewArray->getElementType())) | ||||
3850 | MergedT = New->getType(); | ||||
3851 | } | ||||
3852 | // FIXME: Check visibility. New is hidden but has a complete type. If New | ||||
3853 | // has no array bound, it should not inherit one from Old, if Old is not | ||||
3854 | // visible. | ||||
3855 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { | ||||
3856 | if (Context.hasSameType(OldArray->getElementType(), | ||||
3857 | NewArray->getElementType())) | ||||
3858 | MergedT = Old->getType(); | ||||
3859 | } | ||||
3860 | } | ||||
3861 | else if (New->getType()->isObjCObjectPointerType() && | ||||
3862 | Old->getType()->isObjCObjectPointerType()) { | ||||
3863 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), | ||||
3864 | Old->getType()); | ||||
3865 | } | ||||
3866 | } else { | ||||
3867 | // C 6.2.7p2: | ||||
3868 | // All declarations that refer to the same object or function shall have | ||||
3869 | // compatible type. | ||||
3870 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); | ||||
3871 | } | ||||
3872 | if (MergedT.isNull()) { | ||||
3873 | // It's OK if we couldn't merge types if either type is dependent, for a | ||||
3874 | // block-scope variable. In other cases (static data members of class | ||||
3875 | // templates, variable templates, ...), we require the types to be | ||||
3876 | // equivalent. | ||||
3877 | // FIXME: The C++ standard doesn't say anything about this. | ||||
3878 | if ((New->getType()->isDependentType() || | ||||
3879 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { | ||||
3880 | // If the old type was dependent, we can't merge with it, so the new type | ||||
3881 | // becomes dependent for now. We'll reproduce the original type when we | ||||
3882 | // instantiate the TypeSourceInfo for the variable. | ||||
3883 | if (!New->getType()->isDependentType() && MergeTypeWithOld) | ||||
3884 | New->setType(Context.DependentTy); | ||||
3885 | return; | ||||
3886 | } | ||||
3887 | return diagnoseVarDeclTypeMismatch(*this, New, Old); | ||||
3888 | } | ||||
3889 | |||||
3890 | // Don't actually update the type on the new declaration if the old | ||||
3891 | // declaration was an extern declaration in a different scope. | ||||
3892 | if (MergeTypeWithOld) | ||||
3893 | New->setType(MergedT); | ||||
3894 | } | ||||
3895 | |||||
3896 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, | ||||
3897 | LookupResult &Previous) { | ||||
3898 | // C11 6.2.7p4: | ||||
3899 | // For an identifier with internal or external linkage declared | ||||
3900 | // in a scope in which a prior declaration of that identifier is | ||||
3901 | // visible, if the prior declaration specifies internal or | ||||
3902 | // external linkage, the type of the identifier at the later | ||||
3903 | // declaration becomes the composite type. | ||||
3904 | // | ||||
3905 | // If the variable isn't visible, we do not merge with its type. | ||||
3906 | if (Previous.isShadowed()) | ||||
3907 | return false; | ||||
3908 | |||||
3909 | if (S.getLangOpts().CPlusPlus) { | ||||
3910 | // C++11 [dcl.array]p3: | ||||
3911 | // If there is a preceding declaration of the entity in the same | ||||
3912 | // scope in which the bound was specified, an omitted array bound | ||||
3913 | // is taken to be the same as in that earlier declaration. | ||||
3914 | return NewVD->isPreviousDeclInSameBlockScope() || | ||||
3915 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && | ||||
3916 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); | ||||
3917 | } else { | ||||
3918 | // If the old declaration was function-local, don't merge with its | ||||
3919 | // type unless we're in the same function. | ||||
3920 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || | ||||
3921 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); | ||||
3922 | } | ||||
3923 | } | ||||
3924 | |||||
3925 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name | ||||
3926 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this | ||||
3927 | /// situation, merging decls or emitting diagnostics as appropriate. | ||||
3928 | /// | ||||
3929 | /// Tentative definition rules (C99 6.9.2p2) are checked by | ||||
3930 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative | ||||
3931 | /// definitions here, since the initializer hasn't been attached. | ||||
3932 | /// | ||||
3933 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { | ||||
3934 | // If the new decl is already invalid, don't do any other checking. | ||||
3935 | if (New->isInvalidDecl()) | ||||
3936 | return; | ||||
3937 | |||||
3938 | if (!shouldLinkPossiblyHiddenDecl(Previous, New)) | ||||
3939 | return; | ||||
3940 | |||||
3941 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); | ||||
3942 | |||||
3943 | // Verify the old decl was also a variable or variable template. | ||||
3944 | VarDecl *Old = nullptr; | ||||
3945 | VarTemplateDecl *OldTemplate = nullptr; | ||||
3946 | if (Previous.isSingleResult()) { | ||||
3947 | if (NewTemplate) { | ||||
3948 | OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); | ||||
3949 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; | ||||
3950 | |||||
3951 | if (auto *Shadow = | ||||
3952 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | ||||
3953 | if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) | ||||
3954 | return New->setInvalidDecl(); | ||||
3955 | } else { | ||||
3956 | Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); | ||||
3957 | |||||
3958 | if (auto *Shadow = | ||||
3959 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | ||||
3960 | if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) | ||||
3961 | return New->setInvalidDecl(); | ||||
3962 | } | ||||
3963 | } | ||||
3964 | if (!Old) { | ||||
3965 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||
3966 | << New->getDeclName(); | ||||
3967 | notePreviousDefinition(Previous.getRepresentativeDecl(), | ||||
3968 | New->getLocation()); | ||||
3969 | return New->setInvalidDecl(); | ||||
3970 | } | ||||
3971 | |||||
3972 | // Ensure the template parameters are compatible. | ||||
3973 | if (NewTemplate && | ||||
3974 | !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), | ||||
3975 | OldTemplate->getTemplateParameters(), | ||||
3976 | /*Complain=*/true, TPL_TemplateMatch)) | ||||
3977 | return New->setInvalidDecl(); | ||||
3978 | |||||
3979 | // C++ [class.mem]p1: | ||||
3980 | // A member shall not be declared twice in the member-specification [...] | ||||
3981 | // | ||||
3982 | // Here, we need only consider static data members. | ||||
3983 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { | ||||
3984 | Diag(New->getLocation(), diag::err_duplicate_member) | ||||
3985 | << New->getIdentifier(); | ||||
3986 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
3987 | New->setInvalidDecl(); | ||||
3988 | } | ||||
3989 | |||||
3990 | mergeDeclAttributes(New, Old); | ||||
3991 | // Warn if an already-declared variable is made a weak_import in a subsequent | ||||
3992 | // declaration | ||||
3993 | if (New->hasAttr<WeakImportAttr>() && | ||||
3994 | Old->getStorageClass() == SC_None && | ||||
3995 | !Old->hasAttr<WeakImportAttr>()) { | ||||
3996 | Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); | ||||
3997 | notePreviousDefinition(Old, New->getLocation()); | ||||
3998 | // Remove weak_import attribute on new declaration. | ||||
3999 | New->dropAttr<WeakImportAttr>(); | ||||
4000 | } | ||||
4001 | |||||
4002 | if (New->hasAttr<InternalLinkageAttr>() && | ||||
4003 | !Old->hasAttr<InternalLinkageAttr>()) { | ||||
4004 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | ||||
4005 | << New->getDeclName(); | ||||
4006 | notePreviousDefinition(Old, New->getLocation()); | ||||
4007 | New->dropAttr<InternalLinkageAttr>(); | ||||
4008 | } | ||||
4009 | |||||
4010 | // Merge the types. | ||||
4011 | VarDecl *MostRecent = Old->getMostRecentDecl(); | ||||
4012 | if (MostRecent != Old) { | ||||
4013 | MergeVarDeclTypes(New, MostRecent, | ||||
4014 | mergeTypeWithPrevious(*this, New, MostRecent, Previous)); | ||||
4015 | if (New->isInvalidDecl()) | ||||
4016 | return; | ||||
4017 | } | ||||
4018 | |||||
4019 | MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); | ||||
4020 | if (New->isInvalidDecl()) | ||||
4021 | return; | ||||
4022 | |||||
4023 | diag::kind PrevDiag; | ||||
4024 | SourceLocation OldLocation; | ||||
4025 | std::tie(PrevDiag, OldLocation) = | ||||
4026 | getNoteDiagForInvalidRedeclaration(Old, New); | ||||
4027 | |||||
4028 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. | ||||
4029 | if (New->getStorageClass() == SC_Static && | ||||
4030 | !New->isStaticDataMember() && | ||||
4031 | Old->hasExternalFormalLinkage()) { | ||||
4032 | if (getLangOpts().MicrosoftExt) { | ||||
4033 | Diag(New->getLocation(), diag::ext_static_non_static) | ||||
4034 | << New->getDeclName(); | ||||
4035 | Diag(OldLocation, PrevDiag); | ||||
4036 | } else { | ||||
4037 | Diag(New->getLocation(), diag::err_static_non_static) | ||||
4038 | << New->getDeclName(); | ||||
4039 | Diag(OldLocation, PrevDiag); | ||||
4040 | return New->setInvalidDecl(); | ||||
4041 | } | ||||
4042 | } | ||||
4043 | // C99 6.2.2p4: | ||||
4044 | // For an identifier declared with the storage-class specifier | ||||
4045 | // extern in a scope in which a prior declaration of that | ||||
4046 | // identifier is visible,23) if the prior declaration specifies | ||||
4047 | // internal or external linkage, the linkage of the identifier at | ||||
4048 | // the later declaration is the same as the linkage specified at | ||||
4049 | // the prior declaration. If no prior declaration is visible, or | ||||
4050 | // if the prior declaration specifies no linkage, then the | ||||
4051 | // identifier has external linkage. | ||||
4052 | if (New->hasExternalStorage() && Old->hasLinkage()) | ||||
4053 | /* Okay */; | ||||
4054 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && | ||||
4055 | !New->isStaticDataMember() && | ||||
4056 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { | ||||
4057 | Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); | ||||
4058 | Diag(OldLocation, PrevDiag); | ||||
4059 | return New->setInvalidDecl(); | ||||
4060 | } | ||||
4061 | |||||
4062 | // Check if extern is followed by non-extern and vice-versa. | ||||
4063 | if (New->hasExternalStorage() && | ||||
4064 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { | ||||
4065 | Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); | ||||
4066 | Diag(OldLocation, PrevDiag); | ||||
4067 | return New->setInvalidDecl(); | ||||
4068 | } | ||||
4069 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && | ||||
4070 | !New->hasExternalStorage()) { | ||||
4071 | Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); | ||||
4072 | Diag(OldLocation, PrevDiag); | ||||
4073 | return New->setInvalidDecl(); | ||||
4074 | } | ||||
4075 | |||||
4076 | if (CheckRedeclarationModuleOwnership(New, Old)) | ||||
4077 | return; | ||||
4078 | |||||
4079 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. | ||||
4080 | |||||
4081 | // FIXME: The test for external storage here seems wrong? We still | ||||
4082 | // need to check for mismatches. | ||||
4083 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && | ||||
4084 | // Don't complain about out-of-line definitions of static members. | ||||
4085 | !(Old->getLexicalDeclContext()->isRecord() && | ||||
4086 | !New->getLexicalDeclContext()->isRecord())) { | ||||
4087 | Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); | ||||
4088 | Diag(OldLocation, PrevDiag); | ||||
4089 | return New->setInvalidDecl(); | ||||
4090 | } | ||||
4091 | |||||
4092 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { | ||||
4093 | if (VarDecl *Def = Old->getDefinition()) { | ||||
4094 | // C++1z [dcl.fcn.spec]p4: | ||||
4095 | // If the definition of a variable appears in a translation unit before | ||||
4096 | // its first declaration as inline, the program is ill-formed. | ||||
4097 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; | ||||
4098 | Diag(Def->getLocation(), diag::note_previous_definition); | ||||
4099 | } | ||||
4100 | } | ||||
4101 | |||||
4102 | // If this redeclaration makes the variable inline, we may need to add it to | ||||
4103 | // UndefinedButUsed. | ||||
4104 | if (!Old->isInline() && New->isInline() && Old->isUsed(false) && | ||||
4105 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) | ||||
4106 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | ||||
4107 | SourceLocation())); | ||||
4108 | |||||
4109 | if (New->getTLSKind() != Old->getTLSKind()) { | ||||
4110 | if (!Old->getTLSKind()) { | ||||
4111 | Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); | ||||
4112 | Diag(OldLocation, PrevDiag); | ||||
4113 | } else if (!New->getTLSKind()) { | ||||
4114 | Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); | ||||
4115 | Diag(OldLocation, PrevDiag); | ||||
4116 | } else { | ||||
4117 | // Do not allow redeclaration to change the variable between requiring | ||||
4118 | // static and dynamic initialization. | ||||
4119 | // FIXME: GCC allows this, but uses the TLS keyword on the first | ||||
4120 | // declaration to determine the kind. Do we need to be compatible here? | ||||
4121 | Diag(New->getLocation(), diag::err_thread_thread_different_kind) | ||||
4122 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); | ||||
4123 | Diag(OldLocation, PrevDiag); | ||||
4124 | } | ||||
4125 | } | ||||
4126 | |||||
4127 | // C++ doesn't have tentative definitions, so go right ahead and check here. | ||||
4128 | if (getLangOpts().CPlusPlus && | ||||
4129 | New->isThisDeclarationADefinition() == VarDecl::Definition) { | ||||
4130 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && | ||||
4131 | Old->getCanonicalDecl()->isConstexpr()) { | ||||
4132 | // This definition won't be a definition any more once it's been merged. | ||||
4133 | Diag(New->getLocation(), | ||||
4134 | diag::warn_deprecated_redundant_constexpr_static_def); | ||||
4135 | } else if (VarDecl *Def = Old->getDefinition()) { | ||||
4136 | if (checkVarDeclRedefinition(Def, New)) | ||||
4137 | return; | ||||
4138 | } | ||||
4139 | } | ||||
4140 | |||||
4141 | if (haveIncompatibleLanguageLinkages(Old, New)) { | ||||
4142 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | ||||
4143 | Diag(OldLocation, PrevDiag); | ||||
4144 | New->setInvalidDecl(); | ||||
4145 | return; | ||||
4146 | } | ||||
4147 | |||||
4148 | // Merge "used" flag. | ||||
4149 | if (Old->getMostRecentDecl()->isUsed(false)) | ||||
4150 | New->setIsUsed(); | ||||
4151 | |||||
4152 | // Keep a chain of previous declarations. | ||||
4153 | New->setPreviousDecl(Old); | ||||
4154 | if (NewTemplate) | ||||
4155 | NewTemplate->setPreviousDecl(OldTemplate); | ||||
4156 | adjustDeclContextForDeclaratorDecl(New, Old); | ||||
4157 | |||||
4158 | // Inherit access appropriately. | ||||
4159 | New->setAccess(Old->getAccess()); | ||||
4160 | if (NewTemplate) | ||||
4161 | NewTemplate->setAccess(New->getAccess()); | ||||
4162 | |||||
4163 | if (Old->isInline()) | ||||
4164 | New->setImplicitlyInline(); | ||||
4165 | } | ||||
4166 | |||||
4167 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { | ||||
4168 | SourceManager &SrcMgr = getSourceManager(); | ||||
4169 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); | ||||
4170 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); | ||||
4171 | auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); | ||||
4172 | auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); | ||||
4173 | auto &HSI = PP.getHeaderSearchInfo(); | ||||
4174 | StringRef HdrFilename = | ||||
4175 | SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); | ||||
4176 | |||||
4177 | auto noteFromModuleOrInclude = [&](Module *Mod, | ||||
4178 | SourceLocation IncLoc) -> bool { | ||||
4179 | // Redefinition errors with modules are common with non modular mapped | ||||
4180 | // headers, example: a non-modular header H in module A that also gets | ||||
4181 | // included directly in a TU. Pointing twice to the same header/definition | ||||
4182 | // is confusing, try to get better diagnostics when modules is on. | ||||
4183 | if (IncLoc.isValid()) { | ||||
4184 | if (Mod) { | ||||
4185 | Diag(IncLoc, diag::note_redefinition_modules_same_file) | ||||
4186 | << HdrFilename.str() << Mod->getFullModuleName(); | ||||
4187 | if (!Mod->DefinitionLoc.isInvalid()) | ||||
4188 | Diag(Mod->DefinitionLoc, diag::note_defined_here) | ||||
4189 | << Mod->getFullModuleName(); | ||||
4190 | } else { | ||||
4191 | Diag(IncLoc, diag::note_redefinition_include_same_file) | ||||
4192 | << HdrFilename.str(); | ||||
4193 | } | ||||
4194 | return true; | ||||
4195 | } | ||||
4196 | |||||
4197 | return false; | ||||
4198 | }; | ||||
4199 | |||||
4200 | // Is it the same file and same offset? Provide more information on why | ||||
4201 | // this leads to a redefinition error. | ||||
4202 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { | ||||
4203 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); | ||||
4204 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); | ||||
4205 | bool EmittedDiag = | ||||
4206 | noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); | ||||
4207 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); | ||||
4208 | |||||
4209 | // If the header has no guards, emit a note suggesting one. | ||||
4210 | if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) | ||||
4211 | Diag(Old->getLocation(), diag::note_use_ifdef_guards); | ||||
4212 | |||||
4213 | if (EmittedDiag) | ||||
4214 | return; | ||||
4215 | } | ||||
4216 | |||||
4217 | // Redefinition coming from different files or couldn't do better above. | ||||
4218 | if (Old->getLocation().isValid()) | ||||
4219 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||
4220 | } | ||||
4221 | |||||
4222 | /// We've just determined that \p Old and \p New both appear to be definitions | ||||
4223 | /// of the same variable. Either diagnose or fix the problem. | ||||
4224 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { | ||||
4225 | if (!hasVisibleDefinition(Old) && | ||||
4226 | (New->getFormalLinkage() == InternalLinkage || | ||||
4227 | New->isInline() || | ||||
4228 | New->getDescribedVarTemplate() || | ||||
4229 | New->getNumTemplateParameterLists() || | ||||
4230 | New->getDeclContext()->isDependentContext())) { | ||||
4231 | // The previous definition is hidden, and multiple definitions are | ||||
4232 | // permitted (in separate TUs). Demote this to a declaration. | ||||
4233 | New->demoteThisDefinitionToDeclaration(); | ||||
4234 | |||||
4235 | // Make the canonical definition visible. | ||||
4236 | if (auto *OldTD = Old->getDescribedVarTemplate()) | ||||
4237 | makeMergedDefinitionVisible(OldTD); | ||||
4238 | makeMergedDefinitionVisible(Old); | ||||
4239 | return false; | ||||
4240 | } else { | ||||
4241 | Diag(New->getLocation(), diag::err_redefinition) << New; | ||||
4242 | notePreviousDefinition(Old, New->getLocation()); | ||||
4243 | New->setInvalidDecl(); | ||||
4244 | return true; | ||||
4245 | } | ||||
4246 | } | ||||
4247 | |||||
4248 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | ||||
4249 | /// no declarator (e.g. "struct foo;") is parsed. | ||||
4250 | Decl * | ||||
4251 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | ||||
4252 | RecordDecl *&AnonRecord) { | ||||
4253 | return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, | ||||
4254 | AnonRecord); | ||||
4255 | } | ||||
4256 | |||||
4257 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to | ||||
4258 | // disambiguate entities defined in different scopes. | ||||
4259 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks | ||||
4260 | // compatibility. | ||||
4261 | // We will pick our mangling number depending on which version of MSVC is being | ||||
4262 | // targeted. | ||||
4263 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { | ||||
4264 | return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) | ||||
4265 | ? S->getMSCurManglingNumber() | ||||
4266 | : S->getMSLastManglingNumber(); | ||||
4267 | } | ||||
4268 | |||||
4269 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { | ||||
4270 | if (!Context.getLangOpts().CPlusPlus) | ||||
4271 | return; | ||||
4272 | |||||
4273 | if (isa<CXXRecordDecl>(Tag->getParent())) { | ||||
4274 | // If this tag is the direct child of a class, number it if | ||||
4275 | // it is anonymous. | ||||
4276 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) | ||||
4277 | return; | ||||
4278 | MangleNumberingContext &MCtx = | ||||
4279 | Context.getManglingNumberContext(Tag->getParent()); | ||||
4280 | Context.setManglingNumber( | ||||
4281 | Tag, MCtx.getManglingNumber( | ||||
4282 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | ||||
4283 | return; | ||||
4284 | } | ||||
4285 | |||||
4286 | // If this tag isn't a direct child of a class, number it if it is local. | ||||
4287 | Decl *ManglingContextDecl; | ||||
4288 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( | ||||
4289 | Tag->getDeclContext(), ManglingContextDecl)) { | ||||
4290 | Context.setManglingNumber( | ||||
4291 | Tag, MCtx->getManglingNumber( | ||||
4292 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | ||||
4293 | } | ||||
4294 | } | ||||
4295 | |||||
4296 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, | ||||
4297 | TypedefNameDecl *NewTD) { | ||||
4298 | if (TagFromDeclSpec->isInvalidDecl()) | ||||
4299 | return; | ||||
4300 | |||||
4301 | // Do nothing if the tag already has a name for linkage purposes. | ||||
4302 | if (TagFromDeclSpec->hasNameForLinkage()) | ||||
4303 | return; | ||||
4304 | |||||
4305 | // A well-formed anonymous tag must always be a TUK_Definition. | ||||
4306 | assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast <void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4306, __PRETTY_FUNCTION__)); | ||||
4307 | |||||
4308 | // The type must match the tag exactly; no qualifiers allowed. | ||||
4309 | if (!Context.hasSameType(NewTD->getUnderlyingType(), | ||||
4310 | Context.getTagDeclType(TagFromDeclSpec))) { | ||||
4311 | if (getLangOpts().CPlusPlus) | ||||
4312 | Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); | ||||
4313 | return; | ||||
4314 | } | ||||
4315 | |||||
4316 | // If we've already computed linkage for the anonymous tag, then | ||||
4317 | // adding a typedef name for the anonymous decl can change that | ||||
4318 | // linkage, which might be a serious problem. Diagnose this as | ||||
4319 | // unsupported and ignore the typedef name. TODO: we should | ||||
4320 | // pursue this as a language defect and establish a formal rule | ||||
4321 | // for how to handle it. | ||||
4322 | if (TagFromDeclSpec->hasLinkageBeenComputed()) { | ||||
4323 | Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); | ||||
4324 | |||||
4325 | SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); | ||||
4326 | tagLoc = getLocForEndOfToken(tagLoc); | ||||
4327 | |||||
4328 | llvm::SmallString<40> textToInsert; | ||||
4329 | textToInsert += ' '; | ||||
4330 | textToInsert += NewTD->getIdentifier()->getName(); | ||||
4331 | Diag(tagLoc, diag::note_typedef_changes_linkage) | ||||
4332 | << FixItHint::CreateInsertion(tagLoc, textToInsert); | ||||
4333 | return; | ||||
4334 | } | ||||
4335 | |||||
4336 | // Otherwise, set this is the anon-decl typedef for the tag. | ||||
4337 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); | ||||
4338 | } | ||||
4339 | |||||
4340 | static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { | ||||
4341 | switch (T) { | ||||
4342 | case DeclSpec::TST_class: | ||||
4343 | return 0; | ||||
4344 | case DeclSpec::TST_struct: | ||||
4345 | return 1; | ||||
4346 | case DeclSpec::TST_interface: | ||||
4347 | return 2; | ||||
4348 | case DeclSpec::TST_union: | ||||
4349 | return 3; | ||||
4350 | case DeclSpec::TST_enum: | ||||
4351 | return 4; | ||||
4352 | default: | ||||
4353 | llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4353); | ||||
4354 | } | ||||
4355 | } | ||||
4356 | |||||
4357 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | ||||
4358 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template | ||||
4359 | /// parameters to cope with template friend declarations. | ||||
4360 | Decl * | ||||
4361 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | ||||
4362 | MultiTemplateParamsArg TemplateParams, | ||||
4363 | bool IsExplicitInstantiation, | ||||
4364 | RecordDecl *&AnonRecord) { | ||||
4365 | Decl *TagD = nullptr; | ||||
4366 | TagDecl *Tag = nullptr; | ||||
4367 | if (DS.getTypeSpecType() == DeclSpec::TST_class || | ||||
4368 | DS.getTypeSpecType() == DeclSpec::TST_struct || | ||||
4369 | DS.getTypeSpecType() == DeclSpec::TST_interface || | ||||
4370 | DS.getTypeSpecType() == DeclSpec::TST_union || | ||||
4371 | DS.getTypeSpecType() == DeclSpec::TST_enum) { | ||||
4372 | TagD = DS.getRepAsDecl(); | ||||
4373 | |||||
4374 | if (!TagD) // We probably had an error | ||||
4375 | return nullptr; | ||||
4376 | |||||
4377 | // Note that the above type specs guarantee that the | ||||
4378 | // type rep is a Decl, whereas in many of the others | ||||
4379 | // it's a Type. | ||||
4380 | if (isa<TagDecl>(TagD)) | ||||
4381 | Tag = cast<TagDecl>(TagD); | ||||
4382 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) | ||||
4383 | Tag = CTD->getTemplatedDecl(); | ||||
4384 | } | ||||
4385 | |||||
4386 | if (Tag) { | ||||
4387 | handleTagNumbering(Tag, S); | ||||
4388 | Tag->setFreeStanding(); | ||||
4389 | if (Tag->isInvalidDecl()) | ||||
4390 | return Tag; | ||||
4391 | } | ||||
4392 | |||||
4393 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | ||||
4394 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object | ||||
4395 | // or incomplete types shall not be restrict-qualified." | ||||
4396 | if (TypeQuals & DeclSpec::TQ_restrict) | ||||
4397 | Diag(DS.getRestrictSpecLoc(), | ||||
4398 | diag::err_typecheck_invalid_restrict_not_pointer_noarg) | ||||
4399 | << DS.getSourceRange(); | ||||
4400 | } | ||||
4401 | |||||
4402 | if (DS.isInlineSpecified()) | ||||
4403 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | ||||
4404 | << getLangOpts().CPlusPlus17; | ||||
4405 | |||||
4406 | if (DS.hasConstexprSpecifier()) { | ||||
4407 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations | ||||
4408 | // and definitions of functions and variables. | ||||
4409 | // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to | ||||
4410 | // the declaration of a function or function template | ||||
4411 | if (Tag) | ||||
4412 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) | ||||
4413 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) | ||||
4414 | << DS.getConstexprSpecifier(); | ||||
4415 | else | ||||
4416 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) | ||||
4417 | << DS.getConstexprSpecifier(); | ||||
4418 | // Don't emit warnings after this error. | ||||
4419 | return TagD; | ||||
4420 | } | ||||
4421 | |||||
4422 | DiagnoseFunctionSpecifiers(DS); | ||||
4423 | |||||
4424 | if (DS.isFriendSpecified()) { | ||||
4425 | // If we're dealing with a decl but not a TagDecl, assume that | ||||
4426 | // whatever routines created it handled the friendship aspect. | ||||
4427 | if (TagD && !Tag) | ||||
4428 | return nullptr; | ||||
4429 | return ActOnFriendTypeDecl(S, DS, TemplateParams); | ||||
4430 | } | ||||
4431 | |||||
4432 | const CXXScopeSpec &SS = DS.getTypeSpecScope(); | ||||
4433 | bool IsExplicitSpecialization = | ||||
4434 | !TemplateParams.empty() && TemplateParams.back()->size() == 0; | ||||
4435 | if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && | ||||
4436 | !IsExplicitInstantiation && !IsExplicitSpecialization && | ||||
4437 | !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { | ||||
4438 | // Per C++ [dcl.type.elab]p1, a class declaration cannot have a | ||||
4439 | // nested-name-specifier unless it is an explicit instantiation | ||||
4440 | // or an explicit specialization. | ||||
4441 | // | ||||
4442 | // FIXME: We allow class template partial specializations here too, per the | ||||
4443 | // obvious intent of DR1819. | ||||
4444 | // | ||||
4445 | // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. | ||||
4446 | Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) | ||||
4447 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); | ||||
4448 | return nullptr; | ||||
4449 | } | ||||
4450 | |||||
4451 | // Track whether this decl-specifier declares anything. | ||||
4452 | bool DeclaresAnything = true; | ||||
4453 | |||||
4454 | // Handle anonymous struct definitions. | ||||
4455 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { | ||||
4456 | if (!Record->getDeclName() && Record->isCompleteDefinition() && | ||||
4457 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { | ||||
4458 | if (getLangOpts().CPlusPlus || | ||||
4459 | Record->getDeclContext()->isRecord()) { | ||||
4460 | // If CurContext is a DeclContext that can contain statements, | ||||
4461 | // RecursiveASTVisitor won't visit the decls that | ||||
4462 | // BuildAnonymousStructOrUnion() will put into CurContext. | ||||
4463 | // Also store them here so that they can be part of the | ||||
4464 | // DeclStmt that gets created in this case. | ||||
4465 | // FIXME: Also return the IndirectFieldDecls created by | ||||
4466 | // BuildAnonymousStructOr union, for the same reason? | ||||
4467 | if (CurContext->isFunctionOrMethod()) | ||||
4468 | AnonRecord = Record; | ||||
4469 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, | ||||
4470 | Context.getPrintingPolicy()); | ||||
4471 | } | ||||
4472 | |||||
4473 | DeclaresAnything = false; | ||||
4474 | } | ||||
4475 | } | ||||
4476 | |||||
4477 | // C11 6.7.2.1p2: | ||||
4478 | // A struct-declaration that does not declare an anonymous structure or | ||||
4479 | // anonymous union shall contain a struct-declarator-list. | ||||
4480 | // | ||||
4481 | // This rule also existed in C89 and C99; the grammar for struct-declaration | ||||
4482 | // did not permit a struct-declaration without a struct-declarator-list. | ||||
4483 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && | ||||
4484 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { | ||||
4485 | // Check for Microsoft C extension: anonymous struct/union member. | ||||
4486 | // Handle 2 kinds of anonymous struct/union: | ||||
4487 | // struct STRUCT; | ||||
4488 | // union UNION; | ||||
4489 | // and | ||||
4490 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. | ||||
4491 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. | ||||
4492 | if ((Tag && Tag->getDeclName()) || | ||||
4493 | DS.getTypeSpecType() == DeclSpec::TST_typename) { | ||||
4494 | RecordDecl *Record = nullptr; | ||||
4495 | if (Tag) | ||||
4496 | Record = dyn_cast<RecordDecl>(Tag); | ||||
4497 | else if (const RecordType *RT = | ||||
4498 | DS.getRepAsType().get()->getAsStructureType()) | ||||
4499 | Record = RT->getDecl(); | ||||
4500 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) | ||||
4501 | Record = UT->getDecl(); | ||||
4502 | |||||
4503 | if (Record && getLangOpts().MicrosoftExt) { | ||||
4504 | Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) | ||||
4505 | << Record->isUnion() << DS.getSourceRange(); | ||||
4506 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); | ||||
4507 | } | ||||
4508 | |||||
4509 | DeclaresAnything = false; | ||||
4510 | } | ||||
4511 | } | ||||
4512 | |||||
4513 | // Skip all the checks below if we have a type error. | ||||
4514 | if (DS.getTypeSpecType() == DeclSpec::TST_error || | ||||
4515 | (TagD && TagD->isInvalidDecl())) | ||||
4516 | return TagD; | ||||
4517 | |||||
4518 | if (getLangOpts().CPlusPlus && | ||||
4519 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) | ||||
4520 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) | ||||
4521 | if (Enum->enumerator_begin() == Enum->enumerator_end() && | ||||
4522 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) | ||||
4523 | DeclaresAnything = false; | ||||
4524 | |||||
4525 | if (!DS.isMissingDeclaratorOk()) { | ||||
4526 | // Customize diagnostic for a typedef missing a name. | ||||
4527 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||
4528 | Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) | ||||
4529 | << DS.getSourceRange(); | ||||
4530 | else | ||||
4531 | DeclaresAnything = false; | ||||
4532 | } | ||||
4533 | |||||
4534 | if (DS.isModulePrivateSpecified() && | ||||
4535 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) | ||||
4536 | Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) | ||||
4537 | << Tag->getTagKind() | ||||
4538 | << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); | ||||
4539 | |||||
4540 | ActOnDocumentableDecl(TagD); | ||||
4541 | |||||
4542 | // C 6.7/2: | ||||
4543 | // A declaration [...] shall declare at least a declarator [...], a tag, | ||||
4544 | // or the members of an enumeration. | ||||
4545 | // C++ [dcl.dcl]p3: | ||||
4546 | // [If there are no declarators], and except for the declaration of an | ||||
4547 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | ||||
4548 | // names into the program, or shall redeclare a name introduced by a | ||||
4549 | // previous declaration. | ||||
4550 | if (!DeclaresAnything) { | ||||
4551 | // In C, we allow this as a (popular) extension / bug. Don't bother | ||||
4552 | // producing further diagnostics for redundant qualifiers after this. | ||||
4553 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | ||||
4554 | return TagD; | ||||
4555 | } | ||||
4556 | |||||
4557 | // C++ [dcl.stc]p1: | ||||
4558 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the | ||||
4559 | // init-declarator-list of the declaration shall not be empty. | ||||
4560 | // C++ [dcl.fct.spec]p1: | ||||
4561 | // If a cv-qualifier appears in a decl-specifier-seq, the | ||||
4562 | // init-declarator-list of the declaration shall not be empty. | ||||
4563 | // | ||||
4564 | // Spurious qualifiers here appear to be valid in C. | ||||
4565 | unsigned DiagID = diag::warn_standalone_specifier; | ||||
4566 | if (getLangOpts().CPlusPlus) | ||||
4567 | DiagID = diag::ext_standalone_specifier; | ||||
4568 | |||||
4569 | // Note that a linkage-specification sets a storage class, but | ||||
4570 | // 'extern "C" struct foo;' is actually valid and not theoretically | ||||
4571 | // useless. | ||||
4572 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { | ||||
4573 | if (SCS == DeclSpec::SCS_mutable) | ||||
4574 | // Since mutable is not a viable storage class specifier in C, there is | ||||
4575 | // no reason to treat it as an extension. Instead, diagnose as an error. | ||||
4576 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); | ||||
4577 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) | ||||
4578 | Diag(DS.getStorageClassSpecLoc(), DiagID) | ||||
4579 | << DeclSpec::getSpecifierName(SCS); | ||||
4580 | } | ||||
4581 | |||||
4582 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | ||||
4583 | Diag(DS.getThreadStorageClassSpecLoc(), DiagID) | ||||
4584 | << DeclSpec::getSpecifierName(TSCS); | ||||
4585 | if (DS.getTypeQualifiers()) { | ||||
4586 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||
4587 | Diag(DS.getConstSpecLoc(), DiagID) << "const"; | ||||
4588 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||
4589 | Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; | ||||
4590 | // Restrict is covered above. | ||||
4591 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||
4592 | Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; | ||||
4593 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||
4594 | Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; | ||||
4595 | } | ||||
4596 | |||||
4597 | // Warn about ignored type attributes, for example: | ||||
4598 | // __attribute__((aligned)) struct A; | ||||
4599 | // Attributes should be placed after tag to apply to type declaration. | ||||
4600 | if (!DS.getAttributes().empty()) { | ||||
4601 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); | ||||
4602 | if (TypeSpecType == DeclSpec::TST_class || | ||||
4603 | TypeSpecType == DeclSpec::TST_struct || | ||||
4604 | TypeSpecType == DeclSpec::TST_interface || | ||||
4605 | TypeSpecType == DeclSpec::TST_union || | ||||
4606 | TypeSpecType == DeclSpec::TST_enum) { | ||||
4607 | for (const ParsedAttr &AL : DS.getAttributes()) | ||||
4608 | Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) | ||||
4609 | << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); | ||||
4610 | } | ||||
4611 | } | ||||
4612 | |||||
4613 | return TagD; | ||||
4614 | } | ||||
4615 | |||||
4616 | /// We are trying to inject an anonymous member into the given scope; | ||||
4617 | /// check if there's an existing declaration that can't be overloaded. | ||||
4618 | /// | ||||
4619 | /// \return true if this is a forbidden redeclaration | ||||
4620 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, | ||||
4621 | Scope *S, | ||||
4622 | DeclContext *Owner, | ||||
4623 | DeclarationName Name, | ||||
4624 | SourceLocation NameLoc, | ||||
4625 | bool IsUnion) { | ||||
4626 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, | ||||
4627 | Sema::ForVisibleRedeclaration); | ||||
4628 | if (!SemaRef.LookupName(R, S)) return false; | ||||
4629 | |||||
4630 | // Pick a representative declaration. | ||||
4631 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); | ||||
4632 | assert(PrevDecl && "Expected a non-null Decl")((PrevDecl && "Expected a non-null Decl") ? static_cast <void> (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4632, __PRETTY_FUNCTION__)); | ||||
4633 | |||||
4634 | if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) | ||||
4635 | return false; | ||||
4636 | |||||
4637 | SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) | ||||
4638 | << IsUnion << Name; | ||||
4639 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||
4640 | |||||
4641 | return true; | ||||
4642 | } | ||||
4643 | |||||
4644 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the | ||||
4645 | /// anonymous struct or union AnonRecord into the owning context Owner | ||||
4646 | /// and scope S. This routine will be invoked just after we realize | ||||
4647 | /// that an unnamed union or struct is actually an anonymous union or | ||||
4648 | /// struct, e.g., | ||||
4649 | /// | ||||
4650 | /// @code | ||||
4651 | /// union { | ||||
4652 | /// int i; | ||||
4653 | /// float f; | ||||
4654 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and | ||||
4655 | /// // f into the surrounding scope.x | ||||
4656 | /// @endcode | ||||
4657 | /// | ||||
4658 | /// This routine is recursive, injecting the names of nested anonymous | ||||
4659 | /// structs/unions into the owning context and scope as well. | ||||
4660 | static bool | ||||
4661 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, | ||||
4662 | RecordDecl *AnonRecord, AccessSpecifier AS, | ||||
4663 | SmallVectorImpl<NamedDecl *> &Chaining) { | ||||
4664 | bool Invalid = false; | ||||
4665 | |||||
4666 | // Look every FieldDecl and IndirectFieldDecl with a name. | ||||
4667 | for (auto *D : AnonRecord->decls()) { | ||||
4668 | if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && | ||||
4669 | cast<NamedDecl>(D)->getDeclName()) { | ||||
4670 | ValueDecl *VD = cast<ValueDecl>(D); | ||||
4671 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), | ||||
4672 | VD->getLocation(), | ||||
4673 | AnonRecord->isUnion())) { | ||||
4674 | // C++ [class.union]p2: | ||||
4675 | // The names of the members of an anonymous union shall be | ||||
4676 | // distinct from the names of any other entity in the | ||||
4677 | // scope in which the anonymous union is declared. | ||||
4678 | Invalid = true; | ||||
4679 | } else { | ||||
4680 | // C++ [class.union]p2: | ||||
4681 | // For the purpose of name lookup, after the anonymous union | ||||
4682 | // definition, the members of the anonymous union are | ||||
4683 | // considered to have been defined in the scope in which the | ||||
4684 | // anonymous union is declared. | ||||
4685 | unsigned OldChainingSize = Chaining.size(); | ||||
4686 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) | ||||
4687 | Chaining.append(IF->chain_begin(), IF->chain_end()); | ||||
4688 | else | ||||
4689 | Chaining.push_back(VD); | ||||
4690 | |||||
4691 | assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4691, __PRETTY_FUNCTION__)); | ||||
4692 | NamedDecl **NamedChain = | ||||
4693 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; | ||||
4694 | for (unsigned i = 0; i < Chaining.size(); i++) | ||||
4695 | NamedChain[i] = Chaining[i]; | ||||
4696 | |||||
4697 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( | ||||
4698 | SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), | ||||
4699 | VD->getType(), {NamedChain, Chaining.size()}); | ||||
4700 | |||||
4701 | for (const auto *Attr : VD->attrs()) | ||||
4702 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); | ||||
4703 | |||||
4704 | IndirectField->setAccess(AS); | ||||
4705 | IndirectField->setImplicit(); | ||||
4706 | SemaRef.PushOnScopeChains(IndirectField, S); | ||||
4707 | |||||
4708 | // That includes picking up the appropriate access specifier. | ||||
4709 | if (AS != AS_none) IndirectField->setAccess(AS); | ||||
4710 | |||||
4711 | Chaining.resize(OldChainingSize); | ||||
4712 | } | ||||
4713 | } | ||||
4714 | } | ||||
4715 | |||||
4716 | return Invalid; | ||||
4717 | } | ||||
4718 | |||||
4719 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to | ||||
4720 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: | ||||
4721 | /// illegal input values are mapped to SC_None. | ||||
4722 | static StorageClass | ||||
4723 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { | ||||
4724 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); | ||||
4725 | assert(StorageClassSpec != DeclSpec::SCS_typedef &&((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4726, __PRETTY_FUNCTION__)) | ||||
4726 | "Parser allowed 'typedef' as storage class VarDecl.")((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4726, __PRETTY_FUNCTION__)); | ||||
4727 | switch (StorageClassSpec) { | ||||
4728 | case DeclSpec::SCS_unspecified: return SC_None; | ||||
4729 | case DeclSpec::SCS_extern: | ||||
4730 | if (DS.isExternInLinkageSpec()) | ||||
4731 | return SC_None; | ||||
4732 | return SC_Extern; | ||||
4733 | case DeclSpec::SCS_static: return SC_Static; | ||||
4734 | case DeclSpec::SCS_auto: return SC_Auto; | ||||
4735 | case DeclSpec::SCS_register: return SC_Register; | ||||
4736 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | ||||
4737 | // Illegal SCSs map to None: error reporting is up to the caller. | ||||
4738 | case DeclSpec::SCS_mutable: // Fall through. | ||||
4739 | case DeclSpec::SCS_typedef: return SC_None; | ||||
4740 | } | ||||
4741 | llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4741); | ||||
4742 | } | ||||
4743 | |||||
4744 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { | ||||
4745 | assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void> (0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4745, __PRETTY_FUNCTION__)); | ||||
4746 | |||||
4747 | for (const auto *I : Record->decls()) { | ||||
4748 | const auto *FD = dyn_cast<FieldDecl>(I); | ||||
4749 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | ||||
4750 | FD = IFD->getAnonField(); | ||||
4751 | if (FD && FD->hasInClassInitializer()) | ||||
4752 | return FD->getLocation(); | ||||
4753 | } | ||||
4754 | |||||
4755 | llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4755); | ||||
4756 | } | ||||
4757 | |||||
4758 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | ||||
4759 | SourceLocation DefaultInitLoc) { | ||||
4760 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | ||||
4761 | return; | ||||
4762 | |||||
4763 | S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); | ||||
4764 | S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; | ||||
4765 | } | ||||
4766 | |||||
4767 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | ||||
4768 | CXXRecordDecl *AnonUnion) { | ||||
4769 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | ||||
4770 | return; | ||||
4771 | |||||
4772 | checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); | ||||
4773 | } | ||||
4774 | |||||
4775 | /// BuildAnonymousStructOrUnion - Handle the declaration of an | ||||
4776 | /// anonymous structure or union. Anonymous unions are a C++ feature | ||||
4777 | /// (C++ [class.union]) and a C11 feature; anonymous structures | ||||
4778 | /// are a C11 feature and GNU C++ extension. | ||||
4779 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, | ||||
4780 | AccessSpecifier AS, | ||||
4781 | RecordDecl *Record, | ||||
4782 | const PrintingPolicy &Policy) { | ||||
4783 | DeclContext *Owner = Record->getDeclContext(); | ||||
4784 | |||||
4785 | // Diagnose whether this anonymous struct/union is an extension. | ||||
4786 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) | ||||
4787 | Diag(Record->getLocation(), diag::ext_anonymous_union); | ||||
4788 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) | ||||
4789 | Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); | ||||
4790 | else if (!Record->isUnion() && !getLangOpts().C11) | ||||
4791 | Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); | ||||
4792 | |||||
4793 | // C and C++ require different kinds of checks for anonymous | ||||
4794 | // structs/unions. | ||||
4795 | bool Invalid = false; | ||||
4796 | if (getLangOpts().CPlusPlus) { | ||||
4797 | const char *PrevSpec = nullptr; | ||||
4798 | if (Record->isUnion()) { | ||||
4799 | // C++ [class.union]p6: | ||||
4800 | // C++17 [class.union.anon]p2: | ||||
4801 | // Anonymous unions declared in a named namespace or in the | ||||
4802 | // global namespace shall be declared static. | ||||
4803 | unsigned DiagID; | ||||
4804 | DeclContext *OwnerScope = Owner->getRedeclContext(); | ||||
4805 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && | ||||
4806 | (OwnerScope->isTranslationUnit() || | ||||
4807 | (OwnerScope->isNamespace() && | ||||
4808 | !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { | ||||
4809 | Diag(Record->getLocation(), diag::err_anonymous_union_not_static) | ||||
4810 | << FixItHint::CreateInsertion(Record->getLocation(), "static "); | ||||
4811 | |||||
4812 | // Recover by adding 'static'. | ||||
4813 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), | ||||
4814 | PrevSpec, DiagID, Policy); | ||||
4815 | } | ||||
4816 | // C++ [class.union]p6: | ||||
4817 | // A storage class is not allowed in a declaration of an | ||||
4818 | // anonymous union in a class scope. | ||||
4819 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && | ||||
4820 | isa<RecordDecl>(Owner)) { | ||||
4821 | Diag(DS.getStorageClassSpecLoc(), | ||||
4822 | diag::err_anonymous_union_with_storage_spec) | ||||
4823 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||
4824 | |||||
4825 | // Recover by removing the storage specifier. | ||||
4826 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, | ||||
4827 | SourceLocation(), | ||||
4828 | PrevSpec, DiagID, Context.getPrintingPolicy()); | ||||
4829 | } | ||||
4830 | } | ||||
4831 | |||||
4832 | // Ignore const/volatile/restrict qualifiers. | ||||
4833 | if (DS.getTypeQualifiers()) { | ||||
4834 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||
4835 | Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) | ||||
4836 | << Record->isUnion() << "const" | ||||
4837 | << FixItHint::CreateRemoval(DS.getConstSpecLoc()); | ||||
4838 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||
4839 | Diag(DS.getVolatileSpecLoc(), | ||||
4840 | diag::ext_anonymous_struct_union_qualified) | ||||
4841 | << Record->isUnion() << "volatile" | ||||
4842 | << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); | ||||
4843 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) | ||||
4844 | Diag(DS.getRestrictSpecLoc(), | ||||
4845 | diag::ext_anonymous_struct_union_qualified) | ||||
4846 | << Record->isUnion() << "restrict" | ||||
4847 | << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); | ||||
4848 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||
4849 | Diag(DS.getAtomicSpecLoc(), | ||||
4850 | diag::ext_anonymous_struct_union_qualified) | ||||
4851 | << Record->isUnion() << "_Atomic" | ||||
4852 | << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); | ||||
4853 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||
4854 | Diag(DS.getUnalignedSpecLoc(), | ||||
4855 | diag::ext_anonymous_struct_union_qualified) | ||||
4856 | << Record->isUnion() << "__unaligned" | ||||
4857 | << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); | ||||
4858 | |||||
4859 | DS.ClearTypeQualifiers(); | ||||
4860 | } | ||||
4861 | |||||
4862 | // C++ [class.union]p2: | ||||
4863 | // The member-specification of an anonymous union shall only | ||||
4864 | // define non-static data members. [Note: nested types and | ||||
4865 | // functions cannot be declared within an anonymous union. ] | ||||
4866 | for (auto *Mem : Record->decls()) { | ||||
4867 | if (auto *FD = dyn_cast<FieldDecl>(Mem)) { | ||||
4868 | // C++ [class.union]p3: | ||||
4869 | // An anonymous union shall not have private or protected | ||||
4870 | // members (clause 11). | ||||
4871 | assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0 ) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4871, __PRETTY_FUNCTION__)); | ||||
4872 | if (FD->getAccess() != AS_public) { | ||||
4873 | Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) | ||||
4874 | << Record->isUnion() << (FD->getAccess() == AS_protected); | ||||
4875 | Invalid = true; | ||||
4876 | } | ||||
4877 | |||||
4878 | // C++ [class.union]p1 | ||||
4879 | // An object of a class with a non-trivial constructor, a non-trivial | ||||
4880 | // copy constructor, a non-trivial destructor, or a non-trivial copy | ||||
4881 | // assignment operator cannot be a member of a union, nor can an | ||||
4882 | // array of such objects. | ||||
4883 | if (CheckNontrivialField(FD)) | ||||
4884 | Invalid = true; | ||||
4885 | } else if (Mem->isImplicit()) { | ||||
4886 | // Any implicit members are fine. | ||||
4887 | } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { | ||||
4888 | // This is a type that showed up in an | ||||
4889 | // elaborated-type-specifier inside the anonymous struct or | ||||
4890 | // union, but which actually declares a type outside of the | ||||
4891 | // anonymous struct or union. It's okay. | ||||
4892 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { | ||||
4893 | if (!MemRecord->isAnonymousStructOrUnion() && | ||||
4894 | MemRecord->getDeclName()) { | ||||
4895 | // Visual C++ allows type definition in anonymous struct or union. | ||||
4896 | if (getLangOpts().MicrosoftExt) | ||||
4897 | Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) | ||||
4898 | << Record->isUnion(); | ||||
4899 | else { | ||||
4900 | // This is a nested type declaration. | ||||
4901 | Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) | ||||
4902 | << Record->isUnion(); | ||||
4903 | Invalid = true; | ||||
4904 | } | ||||
4905 | } else { | ||||
4906 | // This is an anonymous type definition within another anonymous type. | ||||
4907 | // This is a popular extension, provided by Plan9, MSVC and GCC, but | ||||
4908 | // not part of standard C++. | ||||
4909 | Diag(MemRecord->getLocation(), | ||||
4910 | diag::ext_anonymous_record_with_anonymous_type) | ||||
4911 | << Record->isUnion(); | ||||
4912 | } | ||||
4913 | } else if (isa<AccessSpecDecl>(Mem)) { | ||||
4914 | // Any access specifier is fine. | ||||
4915 | } else if (isa<StaticAssertDecl>(Mem)) { | ||||
4916 | // In C++1z, static_assert declarations are also fine. | ||||
4917 | } else { | ||||
4918 | // We have something that isn't a non-static data | ||||
4919 | // member. Complain about it. | ||||
4920 | unsigned DK = diag::err_anonymous_record_bad_member; | ||||
4921 | if (isa<TypeDecl>(Mem)) | ||||
4922 | DK = diag::err_anonymous_record_with_type; | ||||
4923 | else if (isa<FunctionDecl>(Mem)) | ||||
4924 | DK = diag::err_anonymous_record_with_function; | ||||
4925 | else if (isa<VarDecl>(Mem)) | ||||
4926 | DK = diag::err_anonymous_record_with_static; | ||||
4927 | |||||
4928 | // Visual C++ allows type definition in anonymous struct or union. | ||||
4929 | if (getLangOpts().MicrosoftExt && | ||||
4930 | DK == diag::err_anonymous_record_with_type) | ||||
4931 | Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) | ||||
4932 | << Record->isUnion(); | ||||
4933 | else { | ||||
4934 | Diag(Mem->getLocation(), DK) << Record->isUnion(); | ||||
4935 | Invalid = true; | ||||
4936 | } | ||||
4937 | } | ||||
4938 | } | ||||
4939 | |||||
4940 | // C++11 [class.union]p8 (DR1460): | ||||
4941 | // At most one variant member of a union may have a | ||||
4942 | // brace-or-equal-initializer. | ||||
4943 | if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && | ||||
4944 | Owner->isRecord()) | ||||
4945 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), | ||||
4946 | cast<CXXRecordDecl>(Record)); | ||||
4947 | } | ||||
4948 | |||||
4949 | if (!Record->isUnion() && !Owner->isRecord()) { | ||||
4950 | Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) | ||||
4951 | << getLangOpts().CPlusPlus; | ||||
4952 | Invalid = true; | ||||
4953 | } | ||||
4954 | |||||
4955 | // C++ [dcl.dcl]p3: | ||||
4956 | // [If there are no declarators], and except for the declaration of an | ||||
4957 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | ||||
4958 | // names into the program | ||||
4959 | // C++ [class.mem]p2: | ||||
4960 | // each such member-declaration shall either declare at least one member | ||||
4961 | // name of the class or declare at least one unnamed bit-field | ||||
4962 | // | ||||
4963 | // For C this is an error even for a named struct, and is diagnosed elsewhere. | ||||
4964 | if (getLangOpts().CPlusPlus && Record->field_empty()) | ||||
4965 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | ||||
4966 | |||||
4967 | // Mock up a declarator. | ||||
4968 | Declarator Dc(DS, DeclaratorContext::MemberContext); | ||||
4969 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | ||||
4970 | assert(TInfo && "couldn't build declarator info for anonymous struct/union")((TInfo && "couldn't build declarator info for anonymous struct/union" ) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 4970, __PRETTY_FUNCTION__)); | ||||
4971 | |||||
4972 | // Create a declaration for this anonymous struct/union. | ||||
4973 | NamedDecl *Anon = nullptr; | ||||
4974 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { | ||||
4975 | Anon = FieldDecl::Create( | ||||
4976 | Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), | ||||
4977 | /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, | ||||
4978 | /*BitWidth=*/nullptr, /*Mutable=*/false, | ||||
4979 | /*InitStyle=*/ICIS_NoInit); | ||||
4980 | Anon->setAccess(AS); | ||||
4981 | if (getLangOpts().CPlusPlus) | ||||
4982 | FieldCollector->Add(cast<FieldDecl>(Anon)); | ||||
4983 | } else { | ||||
4984 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); | ||||
4985 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); | ||||
4986 | if (SCSpec == DeclSpec::SCS_mutable) { | ||||
4987 | // mutable can only appear on non-static class members, so it's always | ||||
4988 | // an error here | ||||
4989 | Diag(Record->getLocation(), diag::err_mutable_nonmember); | ||||
4990 | Invalid = true; | ||||
4991 | SC = SC_None; | ||||
4992 | } | ||||
4993 | |||||
4994 | Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), | ||||
4995 | Record->getLocation(), /*IdentifierInfo=*/nullptr, | ||||
4996 | Context.getTypeDeclType(Record), TInfo, SC); | ||||
4997 | |||||
4998 | // Default-initialize the implicit variable. This initialization will be | ||||
4999 | // trivial in almost all cases, except if a union member has an in-class | ||||
5000 | // initializer: | ||||
5001 | // union { int n = 0; }; | ||||
5002 | ActOnUninitializedDecl(Anon); | ||||
5003 | } | ||||
5004 | Anon->setImplicit(); | ||||
5005 | |||||
5006 | // Mark this as an anonymous struct/union type. | ||||
5007 | Record->setAnonymousStructOrUnion(true); | ||||
5008 | |||||
5009 | // Add the anonymous struct/union object to the current | ||||
5010 | // context. We'll be referencing this object when we refer to one of | ||||
5011 | // its members. | ||||
5012 | Owner->addDecl(Anon); | ||||
5013 | |||||
5014 | // Inject the members of the anonymous struct/union into the owning | ||||
5015 | // context and into the identifier resolver chain for name lookup | ||||
5016 | // purposes. | ||||
5017 | SmallVector<NamedDecl*, 2> Chain; | ||||
5018 | Chain.push_back(Anon); | ||||
5019 | |||||
5020 | if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) | ||||
5021 | Invalid = true; | ||||
5022 | |||||
5023 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { | ||||
5024 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | ||||
5025 | Decl *ManglingContextDecl; | ||||
5026 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( | ||||
5027 | NewVD->getDeclContext(), ManglingContextDecl)) { | ||||
5028 | Context.setManglingNumber( | ||||
5029 | NewVD, MCtx->getManglingNumber( | ||||
5030 | NewVD, getMSManglingNumber(getLangOpts(), S))); | ||||
5031 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | ||||
5032 | } | ||||
5033 | } | ||||
5034 | } | ||||
5035 | |||||
5036 | if (Invalid) | ||||
5037 | Anon->setInvalidDecl(); | ||||
5038 | |||||
5039 | return Anon; | ||||
5040 | } | ||||
5041 | |||||
5042 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an | ||||
5043 | /// Microsoft C anonymous structure. | ||||
5044 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx | ||||
5045 | /// Example: | ||||
5046 | /// | ||||
5047 | /// struct A { int a; }; | ||||
5048 | /// struct B { struct A; int b; }; | ||||
5049 | /// | ||||
5050 | /// void foo() { | ||||
5051 | /// B var; | ||||
5052 | /// var.a = 3; | ||||
5053 | /// } | ||||
5054 | /// | ||||
5055 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, | ||||
5056 | RecordDecl *Record) { | ||||
5057 | assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void > (0) : __assert_fail ("Record && \"expected a record!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 5057, __PRETTY_FUNCTION__)); | ||||
5058 | |||||
5059 | // Mock up a declarator. | ||||
5060 | Declarator Dc(DS, DeclaratorContext::TypeNameContext); | ||||
5061 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | ||||
5062 | assert(TInfo && "couldn't build declarator info for anonymous struct")((TInfo && "couldn't build declarator info for anonymous struct" ) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 5062, __PRETTY_FUNCTION__)); | ||||
5063 | |||||
5064 | auto *ParentDecl = cast<RecordDecl>(CurContext); | ||||
5065 | QualType RecTy = Context.getTypeDeclType(Record); | ||||
5066 | |||||
5067 | // Create a declaration for this anonymous struct. | ||||
5068 | NamedDecl *Anon = | ||||
5069 | FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), | ||||
5070 | /*IdentifierInfo=*/nullptr, RecTy, TInfo, | ||||
5071 | /*BitWidth=*/nullptr, /*Mutable=*/false, | ||||
5072 | /*InitStyle=*/ICIS_NoInit); | ||||
5073 | Anon->setImplicit(); | ||||
5074 | |||||
5075 | // Add the anonymous struct object to the current context. | ||||
5076 | CurContext->addDecl(Anon); | ||||
5077 | |||||
5078 | // Inject the members of the anonymous struct into the current | ||||
5079 | // context and into the identifier resolver chain for name lookup | ||||
5080 | // purposes. | ||||
5081 | SmallVector<NamedDecl*, 2> Chain; | ||||
5082 | Chain.push_back(Anon); | ||||
5083 | |||||
5084 | RecordDecl *RecordDef = Record->getDefinition(); | ||||
5085 | if (RequireCompleteType(Anon->getLocation(), RecTy, | ||||
5086 | diag::err_field_incomplete) || | ||||
5087 | InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, | ||||
5088 | AS_none, Chain)) { | ||||
5089 | Anon->setInvalidDecl(); | ||||
5090 | ParentDecl->setInvalidDecl(); | ||||
5091 | } | ||||
5092 | |||||
5093 | return Anon; | ||||
5094 | } | ||||
5095 | |||||
5096 | /// GetNameForDeclarator - Determine the full declaration name for the | ||||
5097 | /// given Declarator. | ||||
5098 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { | ||||
5099 | return GetNameFromUnqualifiedId(D.getName()); | ||||
5100 | } | ||||
5101 | |||||
5102 | /// Retrieves the declaration name from a parsed unqualified-id. | ||||
5103 | DeclarationNameInfo | ||||
5104 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { | ||||
5105 | DeclarationNameInfo NameInfo; | ||||
5106 | NameInfo.setLoc(Name.StartLocation); | ||||
5107 | |||||
5108 | switch (Name.getKind()) { | ||||
5109 | |||||
5110 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||
5111 | case UnqualifiedIdKind::IK_Identifier: | ||||
5112 | NameInfo.setName(Name.Identifier); | ||||
5113 | return NameInfo; | ||||
5114 | |||||
5115 | case UnqualifiedIdKind::IK_DeductionGuideName: { | ||||
5116 | // C++ [temp.deduct.guide]p3: | ||||
5117 | // The simple-template-id shall name a class template specialization. | ||||
5118 | // The template-name shall be the same identifier as the template-name | ||||
5119 | // of the simple-template-id. | ||||
5120 | // These together intend to imply that the template-name shall name a | ||||
5121 | // class template. | ||||
5122 | // FIXME: template<typename T> struct X {}; | ||||
5123 | // template<typename T> using Y = X<T>; | ||||
5124 | // Y(int) -> Y<int>; | ||||
5125 | // satisfies these rules but does not name a class template. | ||||
5126 | TemplateName TN = Name.TemplateName.get().get(); | ||||
5127 | auto *Template = TN.getAsTemplateDecl(); | ||||
5128 | if (!Template || !isa<ClassTemplateDecl>(Template)) { | ||||
5129 | Diag(Name.StartLocation, | ||||
5130 | diag::err_deduction_guide_name_not_class_template) | ||||
5131 | << (int)getTemplateNameKindForDiagnostics(TN) << TN; | ||||
5132 | if (Template) | ||||
5133 | Diag(Template->getLocation(), diag::note_template_decl_here); | ||||
5134 | return DeclarationNameInfo(); | ||||
5135 | } | ||||
5136 | |||||
5137 | NameInfo.setName( | ||||
5138 | Context.DeclarationNames.getCXXDeductionGuideName(Template)); | ||||
5139 | return NameInfo; | ||||
5140 | } | ||||
5141 | |||||
5142 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||
5143 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( | ||||
5144 | Name.OperatorFunctionId.Operator)); | ||||
5145 | NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc | ||||
5146 | = Name.OperatorFunctionId.SymbolLocations[0]; | ||||
5147 | NameInfo.getInfo().CXXOperatorName.EndOpNameLoc | ||||
5148 | = Name.EndLocation.getRawEncoding(); | ||||
5149 | return NameInfo; | ||||
5150 | |||||
5151 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||
5152 | NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( | ||||
5153 | Name.Identifier)); | ||||
5154 | NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); | ||||
5155 | return NameInfo; | ||||
5156 | |||||
5157 | case UnqualifiedIdKind::IK_ConversionFunctionId: { | ||||
5158 | TypeSourceInfo *TInfo; | ||||
5159 | QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); | ||||
5160 | if (Ty.isNull()) | ||||
5161 | return DeclarationNameInfo(); | ||||
5162 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( | ||||
5163 | Context.getCanonicalType(Ty))); | ||||
5164 | NameInfo.setNamedTypeInfo(TInfo); | ||||
5165 | return NameInfo; | ||||
5166 | } | ||||
5167 | |||||
5168 | case UnqualifiedIdKind::IK_ConstructorName: { | ||||
5169 | TypeSourceInfo *TInfo; | ||||
5170 | QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); | ||||
5171 | if (Ty.isNull()) | ||||
5172 | return DeclarationNameInfo(); | ||||
5173 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | ||||
5174 | Context.getCanonicalType(Ty))); | ||||
5175 | NameInfo.setNamedTypeInfo(TInfo); | ||||
5176 | return NameInfo; | ||||
5177 | } | ||||
5178 | |||||
5179 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { | ||||
5180 | // In well-formed code, we can only have a constructor | ||||
5181 | // template-id that refers to the current context, so go there | ||||
5182 | // to find the actual type being constructed. | ||||
5183 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); | ||||
5184 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) | ||||
5185 | return DeclarationNameInfo(); | ||||
5186 | |||||
5187 | // Determine the type of the class being constructed. | ||||
5188 | QualType CurClassType = Context.getTypeDeclType(CurClass); | ||||
5189 | |||||
5190 | // FIXME: Check two things: that the template-id names the same type as | ||||
5191 | // CurClassType, and that the template-id does not occur when the name | ||||
5192 | // was qualified. | ||||
5193 | |||||
5194 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | ||||
5195 | Context.getCanonicalType(CurClassType))); | ||||
5196 | // FIXME: should we retrieve TypeSourceInfo? | ||||
5197 | NameInfo.setNamedTypeInfo(nullptr); | ||||
5198 | return NameInfo; | ||||
5199 | } | ||||
5200 | |||||
5201 | case UnqualifiedIdKind::IK_DestructorName: { | ||||
5202 | TypeSourceInfo *TInfo; | ||||
5203 | QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); | ||||
5204 | if (Ty.isNull()) | ||||
5205 | return DeclarationNameInfo(); | ||||
5206 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( | ||||
5207 | Context.getCanonicalType(Ty))); | ||||
5208 | NameInfo.setNamedTypeInfo(TInfo); | ||||
5209 | return NameInfo; | ||||
5210 | } | ||||
5211 | |||||
5212 | case UnqualifiedIdKind::IK_TemplateId: { | ||||
5213 | TemplateName TName = Name.TemplateId->Template.get(); | ||||
5214 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; | ||||
5215 | return Context.getNameForTemplate(TName, TNameLoc); | ||||
5216 | } | ||||
5217 | |||||
5218 | } // switch (Name.getKind()) | ||||
5219 | |||||
5220 | llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 5220); | ||||
5221 | } | ||||
5222 | |||||
5223 | static QualType getCoreType(QualType Ty) { | ||||
5224 | do { | ||||
5225 | if (Ty->isPointerType() || Ty->isReferenceType()) | ||||
5226 | Ty = Ty->getPointeeType(); | ||||
5227 | else if (Ty->isArrayType()) | ||||
5228 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); | ||||
5229 | else | ||||
5230 | return Ty.withoutLocalFastQualifiers(); | ||||
5231 | } while (true); | ||||
5232 | } | ||||
5233 | |||||
5234 | /// hasSimilarParameters - Determine whether the C++ functions Declaration | ||||
5235 | /// and Definition have "nearly" matching parameters. This heuristic is | ||||
5236 | /// used to improve diagnostics in the case where an out-of-line function | ||||
5237 | /// definition doesn't match any declaration within the class or namespace. | ||||
5238 | /// Also sets Params to the list of indices to the parameters that differ | ||||
5239 | /// between the declaration and the definition. If hasSimilarParameters | ||||
5240 | /// returns true and Params is empty, then all of the parameters match. | ||||
5241 | static bool hasSimilarParameters(ASTContext &Context, | ||||
5242 | FunctionDecl *Declaration, | ||||
5243 | FunctionDecl *Definition, | ||||
5244 | SmallVectorImpl<unsigned> &Params) { | ||||
5245 | Params.clear(); | ||||
5246 | if (Declaration->param_size() != Definition->param_size()) | ||||
5247 | return false; | ||||
5248 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { | ||||
5249 | QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); | ||||
5250 | QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); | ||||
5251 | |||||
5252 | // The parameter types are identical | ||||
5253 | if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) | ||||
5254 | continue; | ||||
5255 | |||||
5256 | QualType DeclParamBaseTy = getCoreType(DeclParamTy); | ||||
5257 | QualType DefParamBaseTy = getCoreType(DefParamTy); | ||||
5258 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); | ||||
5259 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); | ||||
5260 | |||||
5261 | if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || | ||||
5262 | (DeclTyName && DeclTyName == DefTyName)) | ||||
5263 | Params.push_back(Idx); | ||||
5264 | else // The two parameters aren't even close | ||||
5265 | return false; | ||||
5266 | } | ||||
5267 | |||||
5268 | return true; | ||||
5269 | } | ||||
5270 | |||||
5271 | /// NeedsRebuildingInCurrentInstantiation - Checks whether the given | ||||
5272 | /// declarator needs to be rebuilt in the current instantiation. | ||||
5273 | /// Any bits of declarator which appear before the name are valid for | ||||
5274 | /// consideration here. That's specifically the type in the decl spec | ||||
5275 | /// and the base type in any member-pointer chunks. | ||||
5276 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, | ||||
5277 | DeclarationName Name) { | ||||
5278 | // The types we specifically need to rebuild are: | ||||
5279 | // - typenames, typeofs, and decltypes | ||||
5280 | // - types which will become injected class names | ||||
5281 | // Of course, we also need to rebuild any type referencing such a | ||||
5282 | // type. It's safest to just say "dependent", but we call out a | ||||
5283 | // few cases here. | ||||
5284 | |||||
5285 | DeclSpec &DS = D.getMutableDeclSpec(); | ||||
5286 | switch (DS.getTypeSpecType()) { | ||||
5287 | case DeclSpec::TST_typename: | ||||
5288 | case DeclSpec::TST_typeofType: | ||||
5289 | case DeclSpec::TST_underlyingType: | ||||
5290 | case DeclSpec::TST_atomic: { | ||||
5291 | // Grab the type from the parser. | ||||
5292 | TypeSourceInfo *TSI = nullptr; | ||||
5293 | QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); | ||||
5294 | if (T.isNull() || !T->isDependentType()) break; | ||||
5295 | |||||
5296 | // Make sure there's a type source info. This isn't really much | ||||
5297 | // of a waste; most dependent types should have type source info | ||||
5298 | // attached already. | ||||
5299 | if (!TSI) | ||||
5300 | TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); | ||||
5301 | |||||
5302 | // Rebuild the type in the current instantiation. | ||||
5303 | TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); | ||||
5304 | if (!TSI) return true; | ||||
5305 | |||||
5306 | // Store the new type back in the decl spec. | ||||
5307 | ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); | ||||
5308 | DS.UpdateTypeRep(LocType); | ||||
5309 | break; | ||||
5310 | } | ||||
5311 | |||||
5312 | case DeclSpec::TST_decltype: | ||||
5313 | case DeclSpec::TST_typeofExpr: { | ||||
5314 | Expr *E = DS.getRepAsExpr(); | ||||
5315 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); | ||||
5316 | if (Result.isInvalid()) return true; | ||||
5317 | DS.UpdateExprRep(Result.get()); | ||||
5318 | break; | ||||
5319 | } | ||||
5320 | |||||
5321 | default: | ||||
5322 | // Nothing to do for these decl specs. | ||||
5323 | break; | ||||
5324 | } | ||||
5325 | |||||
5326 | // It doesn't matter what order we do this in. | ||||
5327 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | ||||
5328 | DeclaratorChunk &Chunk = D.getTypeObject(I); | ||||
5329 | |||||
5330 | // The only type information in the declarator which can come | ||||
5331 | // before the declaration name is the base type of a member | ||||
5332 | // pointer. | ||||
5333 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) | ||||
5334 | continue; | ||||
5335 | |||||
5336 | // Rebuild the scope specifier in-place. | ||||
5337 | CXXScopeSpec &SS = Chunk.Mem.Scope(); | ||||
5338 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) | ||||
5339 | return true; | ||||
5340 | } | ||||
5341 | |||||
5342 | return false; | ||||
5343 | } | ||||
5344 | |||||
5345 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { | ||||
5346 | D.setFunctionDefinitionKind(FDK_Declaration); | ||||
5347 | Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); | ||||
5348 | |||||
5349 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && | ||||
5350 | Dcl && Dcl->getDeclContext()->isFileContext()) | ||||
5351 | Dcl->setTopLevelDeclInObjCContainer(); | ||||
5352 | |||||
5353 | if (getLangOpts().OpenCL) | ||||
5354 | setCurrentOpenCLExtensionForDecl(Dcl); | ||||
5355 | |||||
5356 | return Dcl; | ||||
5357 | } | ||||
5358 | |||||
5359 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: | ||||
5360 | /// If T is the name of a class, then each of the following shall have a | ||||
5361 | /// name different from T: | ||||
5362 | /// - every static data member of class T; | ||||
5363 | /// - every member function of class T | ||||
5364 | /// - every member of class T that is itself a type; | ||||
5365 | /// \returns true if the declaration name violates these rules. | ||||
5366 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, | ||||
5367 | DeclarationNameInfo NameInfo) { | ||||
5368 | DeclarationName Name = NameInfo.getName(); | ||||
5369 | |||||
5370 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); | ||||
5371 | while (Record && Record->isAnonymousStructOrUnion()) | ||||
5372 | Record = dyn_cast<CXXRecordDecl>(Record->getParent()); | ||||
5373 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { | ||||
5374 | Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; | ||||
5375 | return true; | ||||
5376 | } | ||||
5377 | |||||
5378 | return false; | ||||
5379 | } | ||||
5380 | |||||
5381 | /// Diagnose a declaration whose declarator-id has the given | ||||
5382 | /// nested-name-specifier. | ||||
5383 | /// | ||||
5384 | /// \param SS The nested-name-specifier of the declarator-id. | ||||
5385 | /// | ||||
5386 | /// \param DC The declaration context to which the nested-name-specifier | ||||
5387 | /// resolves. | ||||
5388 | /// | ||||
5389 | /// \param Name The name of the entity being declared. | ||||
5390 | /// | ||||
5391 | /// \param Loc The location of the name of the entity being declared. | ||||
5392 | /// | ||||
5393 | /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus | ||||
5394 | /// we're declaring an explicit / partial specialization / instantiation. | ||||
5395 | /// | ||||
5396 | /// \returns true if we cannot safely recover from this error, false otherwise. | ||||
5397 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, | ||||
5398 | DeclarationName Name, | ||||
5399 | SourceLocation Loc, bool IsTemplateId) { | ||||
5400 | DeclContext *Cur = CurContext; | ||||
5401 | while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) | ||||
5402 | Cur = Cur->getParent(); | ||||
5403 | |||||
5404 | // If the user provided a superfluous scope specifier that refers back to the | ||||
5405 | // class in which the entity is already declared, diagnose and ignore it. | ||||
5406 | // | ||||
5407 | // class X { | ||||
5408 | // void X::f(); | ||||
5409 | // }; | ||||
5410 | // | ||||
5411 | // Note, it was once ill-formed to give redundant qualification in all | ||||
5412 | // contexts, but that rule was removed by DR482. | ||||
5413 | if (Cur->Equals(DC)) { | ||||
5414 | if (Cur->isRecord()) { | ||||
5415 | Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification | ||||
5416 | : diag::err_member_extra_qualification) | ||||
5417 | << Name << FixItHint::CreateRemoval(SS.getRange()); | ||||
5418 | SS.clear(); | ||||
5419 | } else { | ||||
5420 | Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; | ||||
5421 | } | ||||
5422 | return false; | ||||
5423 | } | ||||
5424 | |||||
5425 | // Check whether the qualifying scope encloses the scope of the original | ||||
5426 | // declaration. For a template-id, we perform the checks in | ||||
5427 | // CheckTemplateSpecializationScope. | ||||
5428 | if (!Cur->Encloses(DC) && !IsTemplateId) { | ||||
5429 | if (Cur->isRecord()) | ||||
5430 | Diag(Loc, diag::err_member_qualification) | ||||
5431 | << Name << SS.getRange(); | ||||
5432 | else if (isa<TranslationUnitDecl>(DC)) | ||||
5433 | Diag(Loc, diag::err_invalid_declarator_global_scope) | ||||
5434 | << Name << SS.getRange(); | ||||
5435 | else if (isa<FunctionDecl>(Cur)) | ||||
5436 | Diag(Loc, diag::err_invalid_declarator_in_function) | ||||
5437 | << Name << SS.getRange(); | ||||
5438 | else if (isa<BlockDecl>(Cur)) | ||||
5439 | Diag(Loc, diag::err_invalid_declarator_in_block) | ||||
5440 | << Name << SS.getRange(); | ||||
5441 | else | ||||
5442 | Diag(Loc, diag::err_invalid_declarator_scope) | ||||
5443 | << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); | ||||
5444 | |||||
5445 | return true; | ||||
5446 | } | ||||
5447 | |||||
5448 | if (Cur->isRecord()) { | ||||
5449 | // Cannot qualify members within a class. | ||||
5450 | Diag(Loc, diag::err_member_qualification) | ||||
5451 | << Name << SS.getRange(); | ||||
5452 | SS.clear(); | ||||
5453 | |||||
5454 | // C++ constructors and destructors with incorrect scopes can break | ||||
5455 | // our AST invariants by having the wrong underlying types. If | ||||
5456 | // that's the case, then drop this declaration entirely. | ||||
5457 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || | ||||
5458 | Name.getNameKind() == DeclarationName::CXXDestructorName) && | ||||
5459 | !Context.hasSameType(Name.getCXXNameType(), | ||||
5460 | Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) | ||||
5461 | return true; | ||||
5462 | |||||
5463 | return false; | ||||
5464 | } | ||||
5465 | |||||
5466 | // C++11 [dcl.meaning]p1: | ||||
5467 | // [...] "The nested-name-specifier of the qualified declarator-id shall | ||||
5468 | // not begin with a decltype-specifer" | ||||
5469 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); | ||||
5470 | while (SpecLoc.getPrefix()) | ||||
5471 | SpecLoc = SpecLoc.getPrefix(); | ||||
5472 | if (dyn_cast_or_null<DecltypeType>( | ||||
5473 | SpecLoc.getNestedNameSpecifier()->getAsType())) | ||||
5474 | Diag(Loc, diag::err_decltype_in_declarator) | ||||
5475 | << SpecLoc.getTypeLoc().getSourceRange(); | ||||
5476 | |||||
5477 | return false; | ||||
5478 | } | ||||
5479 | |||||
5480 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, | ||||
5481 | MultiTemplateParamsArg TemplateParamLists) { | ||||
5482 | // TODO: consider using NameInfo for diagnostic. | ||||
5483 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||
5484 | DeclarationName Name = NameInfo.getName(); | ||||
5485 | |||||
5486 | // All of these full declarators require an identifier. If it doesn't have | ||||
5487 | // one, the ParsedFreeStandingDeclSpec action should be used. | ||||
5488 | if (D.isDecompositionDeclarator()) { | ||||
5489 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); | ||||
5490 | } else if (!Name) { | ||||
5491 | if (!D.isInvalidType()) // Reject this if we think it is valid. | ||||
5492 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) | ||||
5493 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); | ||||
5494 | return nullptr; | ||||
5495 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) | ||||
5496 | return nullptr; | ||||
5497 | |||||
5498 | // The scope passed in may not be a decl scope. Zip up the scope tree until | ||||
5499 | // we find one that is. | ||||
5500 | while ((S->getFlags() & Scope::DeclScope) == 0 || | ||||
5501 | (S->getFlags() & Scope::TemplateParamScope) != 0) | ||||
5502 | S = S->getParent(); | ||||
5503 | |||||
5504 | DeclContext *DC = CurContext; | ||||
5505 | if (D.getCXXScopeSpec().isInvalid()) | ||||
5506 | D.setInvalidType(); | ||||
5507 | else if (D.getCXXScopeSpec().isSet()) { | ||||
5508 | if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), | ||||
5509 | UPPC_DeclarationQualifier)) | ||||
5510 | return nullptr; | ||||
5511 | |||||
5512 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); | ||||
5513 | DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); | ||||
5514 | if (!DC || isa<EnumDecl>(DC)) { | ||||
5515 | // If we could not compute the declaration context, it's because the | ||||
5516 | // declaration context is dependent but does not refer to a class, | ||||
5517 | // class template, or class template partial specialization. Complain | ||||
5518 | // and return early, to avoid the coming semantic disaster. | ||||
5519 | Diag(D.getIdentifierLoc(), | ||||
5520 | diag::err_template_qualified_declarator_no_match) | ||||
5521 | << D.getCXXScopeSpec().getScopeRep() | ||||
5522 | << D.getCXXScopeSpec().getRange(); | ||||
5523 | return nullptr; | ||||
5524 | } | ||||
5525 | bool IsDependentContext = DC->isDependentContext(); | ||||
5526 | |||||
5527 | if (!IsDependentContext && | ||||
5528 | RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) | ||||
5529 | return nullptr; | ||||
5530 | |||||
5531 | // If a class is incomplete, do not parse entities inside it. | ||||
5532 | if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { | ||||
5533 | Diag(D.getIdentifierLoc(), | ||||
5534 | diag::err_member_def_undefined_record) | ||||
5535 | << Name << DC << D.getCXXScopeSpec().getRange(); | ||||
5536 | return nullptr; | ||||
5537 | } | ||||
5538 | if (!D.getDeclSpec().isFriendSpecified()) { | ||||
5539 | if (diagnoseQualifiedDeclaration( | ||||
5540 | D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), | ||||
5541 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { | ||||
5542 | if (DC->isRecord()) | ||||
5543 | return nullptr; | ||||
5544 | |||||
5545 | D.setInvalidType(); | ||||
5546 | } | ||||
5547 | } | ||||
5548 | |||||
5549 | // Check whether we need to rebuild the type of the given | ||||
5550 | // declaration in the current instantiation. | ||||
5551 | if (EnteringContext && IsDependentContext && | ||||
5552 | TemplateParamLists.size() != 0) { | ||||
5553 | ContextRAII SavedContext(*this, DC); | ||||
5554 | if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) | ||||
5555 | D.setInvalidType(); | ||||
5556 | } | ||||
5557 | } | ||||
5558 | |||||
5559 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||
5560 | QualType R = TInfo->getType(); | ||||
5561 | |||||
5562 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||
5563 | UPPC_DeclarationType)) | ||||
5564 | D.setInvalidType(); | ||||
5565 | |||||
5566 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
5567 | forRedeclarationInCurContext()); | ||||
5568 | |||||
5569 | // See if this is a redefinition of a variable in the same scope. | ||||
5570 | if (!D.getCXXScopeSpec().isSet()) { | ||||
5571 | bool IsLinkageLookup = false; | ||||
5572 | bool CreateBuiltins = false; | ||||
5573 | |||||
5574 | // If the declaration we're planning to build will be a function | ||||
5575 | // or object with linkage, then look for another declaration with | ||||
5576 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). | ||||
5577 | // | ||||
5578 | // If the declaration we're planning to build will be declared with | ||||
5579 | // external linkage in the translation unit, create any builtin with | ||||
5580 | // the same name. | ||||
5581 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||
5582 | /* Do nothing*/; | ||||
5583 | else if (CurContext->isFunctionOrMethod() && | ||||
5584 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || | ||||
5585 | R->isFunctionType())) { | ||||
5586 | IsLinkageLookup = true; | ||||
5587 | CreateBuiltins = | ||||
5588 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); | ||||
5589 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && | ||||
5590 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) | ||||
5591 | CreateBuiltins = true; | ||||
5592 | |||||
5593 | if (IsLinkageLookup
| ||||
5594 | Previous.clear(LookupRedeclarationWithLinkage); | ||||
5595 | Previous.setRedeclarationKind(ForExternalRedeclaration); | ||||
5596 | } | ||||
5597 | |||||
5598 | LookupName(Previous, S, CreateBuiltins); | ||||
5599 | } else { // Something like "int foo::x;" | ||||
5600 | LookupQualifiedName(Previous, DC); | ||||
5601 | |||||
5602 | // C++ [dcl.meaning]p1: | ||||
5603 | // When the declarator-id is qualified, the declaration shall refer to a | ||||
5604 | // previously declared member of the class or namespace to which the | ||||
5605 | // qualifier refers (or, in the case of a namespace, of an element of the | ||||
5606 | // inline namespace set of that namespace (7.3.1)) or to a specialization | ||||
5607 | // thereof; [...] | ||||
5608 | // | ||||
5609 | // Note that we already checked the context above, and that we do not have | ||||
5610 | // enough information to make sure that Previous contains the declaration | ||||
5611 | // we want to match. For example, given: | ||||
5612 | // | ||||
5613 | // class X { | ||||
5614 | // void f(); | ||||
5615 | // void f(float); | ||||
5616 | // }; | ||||
5617 | // | ||||
5618 | // void X::f(int) { } // ill-formed | ||||
5619 | // | ||||
5620 | // In this case, Previous will point to the overload set | ||||
5621 | // containing the two f's declared in X, but neither of them | ||||
5622 | // matches. | ||||
5623 | |||||
5624 | // C++ [dcl.meaning]p1: | ||||
5625 | // [...] the member shall not merely have been introduced by a | ||||
5626 | // using-declaration in the scope of the class or namespace nominated by | ||||
5627 | // the nested-name-specifier of the declarator-id. | ||||
5628 | RemoveUsingDecls(Previous); | ||||
5629 | } | ||||
5630 | |||||
5631 | if (Previous.isSingleResult() && | ||||
5632 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||
5633 | // Maybe we will complain about the shadowed template parameter. | ||||
5634 | if (!D.isInvalidType()) | ||||
5635 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | ||||
5636 | Previous.getFoundDecl()); | ||||
5637 | |||||
5638 | // Just pretend that we didn't see the previous declaration. | ||||
5639 | Previous.clear(); | ||||
5640 | } | ||||
5641 | |||||
5642 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) | ||||
5643 | // Forget that the previous declaration is the injected-class-name. | ||||
5644 | Previous.clear(); | ||||
5645 | |||||
5646 | // In C++, the previous declaration we find might be a tag type | ||||
5647 | // (class or enum). In this case, the new declaration will hide the | ||||
5648 | // tag type. Note that this applies to functions, function templates, and | ||||
5649 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. | ||||
5650 | if (Previous.isSingleTagDecl() && | ||||
5651 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | ||||
5652 | (TemplateParamLists.size() == 0 || R->isFunctionType())) | ||||
5653 | Previous.clear(); | ||||
5654 | |||||
5655 | // Check that there are no default arguments other than in the parameters | ||||
5656 | // of a function declaration (C++ only). | ||||
5657 | if (getLangOpts().CPlusPlus) | ||||
5658 | CheckExtraCXXDefaultArguments(D); | ||||
5659 | |||||
5660 | NamedDecl *New; | ||||
5661 | |||||
5662 | bool AddToScope = true; | ||||
5663 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { | ||||
5664 | if (TemplateParamLists.size()) { | ||||
5665 | Diag(D.getIdentifierLoc(), diag::err_template_typedef); | ||||
5666 | return nullptr; | ||||
5667 | } | ||||
5668 | |||||
5669 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); | ||||
5670 | } else if (R->isFunctionType()) { | ||||
5671 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, | ||||
5672 | TemplateParamLists, | ||||
5673 | AddToScope); | ||||
5674 | } else { | ||||
5675 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, | ||||
5676 | AddToScope); | ||||
5677 | } | ||||
5678 | |||||
5679 | if (!New) | ||||
5680 | return nullptr; | ||||
5681 | |||||
5682 | // If this has an identifier and is not a function template specialization, | ||||
5683 | // add it to the scope stack. | ||||
5684 | if (New->getDeclName() && AddToScope) | ||||
5685 | PushOnScopeChains(New, S); | ||||
5686 | |||||
5687 | if (isInOpenMPDeclareTargetContext()) | ||||
5688 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | ||||
5689 | |||||
5690 | return New; | ||||
5691 | } | ||||
5692 | |||||
5693 | /// Helper method to turn variable array types into constant array | ||||
5694 | /// types in certain situations which would otherwise be errors (for | ||||
5695 | /// GCC compatibility). | ||||
5696 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, | ||||
5697 | ASTContext &Context, | ||||
5698 | bool &SizeIsNegative, | ||||
5699 | llvm::APSInt &Oversized) { | ||||
5700 | // This method tries to turn a variable array into a constant | ||||
5701 | // array even when the size isn't an ICE. This is necessary | ||||
5702 | // for compatibility with code that depends on gcc's buggy | ||||
5703 | // constant expression folding, like struct {char x[(int)(char*)2];} | ||||
5704 | SizeIsNegative = false; | ||||
5705 | Oversized = 0; | ||||
5706 | |||||
5707 | if (T->isDependentType()) | ||||
5708 | return QualType(); | ||||
5709 | |||||
5710 | QualifierCollector Qs; | ||||
5711 | const Type *Ty = Qs.strip(T); | ||||
5712 | |||||
5713 | if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { | ||||
5714 | QualType Pointee = PTy->getPointeeType(); | ||||
5715 | QualType FixedType = | ||||
5716 | TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, | ||||
5717 | Oversized); | ||||
5718 | if (FixedType.isNull()) return FixedType; | ||||
5719 | FixedType = Context.getPointerType(FixedType); | ||||
5720 | return Qs.apply(Context, FixedType); | ||||
5721 | } | ||||
5722 | if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { | ||||
5723 | QualType Inner = PTy->getInnerType(); | ||||
5724 | QualType FixedType = | ||||
5725 | TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, | ||||
5726 | Oversized); | ||||
5727 | if (FixedType.isNull()) return FixedType; | ||||
5728 | FixedType = Context.getParenType(FixedType); | ||||
5729 | return Qs.apply(Context, FixedType); | ||||
5730 | } | ||||
5731 | |||||
5732 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); | ||||
5733 | if (!VLATy) | ||||
5734 | return QualType(); | ||||
5735 | // FIXME: We should probably handle this case | ||||
5736 | if (VLATy->getElementType()->isVariablyModifiedType()) | ||||
5737 | return QualType(); | ||||
5738 | |||||
5739 | Expr::EvalResult Result; | ||||
5740 | if (!VLATy->getSizeExpr() || | ||||
5741 | !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) | ||||
5742 | return QualType(); | ||||
5743 | |||||
5744 | llvm::APSInt Res = Result.Val.getInt(); | ||||
5745 | |||||
5746 | // Check whether the array size is negative. | ||||
5747 | if (Res.isSigned() && Res.isNegative()) { | ||||
5748 | SizeIsNegative = true; | ||||
5749 | return QualType(); | ||||
5750 | } | ||||
5751 | |||||
5752 | // Check whether the array is too large to be addressed. | ||||
5753 | unsigned ActiveSizeBits | ||||
5754 | = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), | ||||
5755 | Res); | ||||
5756 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | ||||
5757 | Oversized = Res; | ||||
5758 | return QualType(); | ||||
5759 | } | ||||
5760 | |||||
5761 | return Context.getConstantArrayType(VLATy->getElementType(), | ||||
5762 | Res, ArrayType::Normal, 0); | ||||
5763 | } | ||||
5764 | |||||
5765 | static void | ||||
5766 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { | ||||
5767 | SrcTL = SrcTL.getUnqualifiedLoc(); | ||||
5768 | DstTL = DstTL.getUnqualifiedLoc(); | ||||
5769 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { | ||||
5770 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); | ||||
5771 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), | ||||
5772 | DstPTL.getPointeeLoc()); | ||||
5773 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); | ||||
5774 | return; | ||||
5775 | } | ||||
5776 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { | ||||
5777 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); | ||||
5778 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), | ||||
5779 | DstPTL.getInnerLoc()); | ||||
5780 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); | ||||
5781 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); | ||||
5782 | return; | ||||
5783 | } | ||||
5784 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); | ||||
5785 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); | ||||
5786 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); | ||||
5787 | TypeLoc DstElemTL = DstATL.getElementLoc(); | ||||
5788 | DstElemTL.initializeFullCopy(SrcElemTL); | ||||
5789 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); | ||||
5790 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); | ||||
5791 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); | ||||
5792 | } | ||||
5793 | |||||
5794 | /// Helper method to turn variable array types into constant array | ||||
5795 | /// types in certain situations which would otherwise be errors (for | ||||
5796 | /// GCC compatibility). | ||||
5797 | static TypeSourceInfo* | ||||
5798 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, | ||||
5799 | ASTContext &Context, | ||||
5800 | bool &SizeIsNegative, | ||||
5801 | llvm::APSInt &Oversized) { | ||||
5802 | QualType FixedTy | ||||
5803 | = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, | ||||
5804 | SizeIsNegative, Oversized); | ||||
5805 | if (FixedTy.isNull()) | ||||
5806 | return nullptr; | ||||
5807 | TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); | ||||
5808 | FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), | ||||
5809 | FixedTInfo->getTypeLoc()); | ||||
5810 | return FixedTInfo; | ||||
5811 | } | ||||
5812 | |||||
5813 | /// Register the given locally-scoped extern "C" declaration so | ||||
5814 | /// that it can be found later for redeclarations. We include any extern "C" | ||||
5815 | /// declaration that is not visible in the translation unit here, not just | ||||
5816 | /// function-scope declarations. | ||||
5817 | void | ||||
5818 | Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { | ||||
5819 | if (!getLangOpts().CPlusPlus && | ||||
5820 | ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) | ||||
5821 | // Don't need to track declarations in the TU in C. | ||||
5822 | return; | ||||
5823 | |||||
5824 | // Note that we have a locally-scoped external with this name. | ||||
5825 | Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); | ||||
5826 | } | ||||
5827 | |||||
5828 | NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { | ||||
5829 | // FIXME: We can have multiple results via __attribute__((overloadable)). | ||||
5830 | auto Result = Context.getExternCContextDecl()->lookup(Name); | ||||
5831 | return Result.empty() ? nullptr : *Result.begin(); | ||||
5832 | } | ||||
5833 | |||||
5834 | /// Diagnose function specifiers on a declaration of an identifier that | ||||
5835 | /// does not identify a function. | ||||
5836 | void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { | ||||
5837 | // FIXME: We should probably indicate the identifier in question to avoid | ||||
5838 | // confusion for constructs like "virtual int a(), b;" | ||||
5839 | if (DS.isVirtualSpecified()) | ||||
5840 | Diag(DS.getVirtualSpecLoc(), | ||||
5841 | diag::err_virtual_non_function); | ||||
5842 | |||||
5843 | if (DS.hasExplicitSpecifier()) | ||||
5844 | Diag(DS.getExplicitSpecLoc(), | ||||
5845 | diag::err_explicit_non_function); | ||||
5846 | |||||
5847 | if (DS.isNoreturnSpecified()) | ||||
5848 | Diag(DS.getNoreturnSpecLoc(), | ||||
5849 | diag::err_noreturn_non_function); | ||||
5850 | } | ||||
5851 | |||||
5852 | NamedDecl* | ||||
5853 | Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, | ||||
5854 | TypeSourceInfo *TInfo, LookupResult &Previous) { | ||||
5855 | // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). | ||||
5856 | if (D.getCXXScopeSpec().isSet()) { | ||||
5857 | Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) | ||||
5858 | << D.getCXXScopeSpec().getRange(); | ||||
5859 | D.setInvalidType(); | ||||
5860 | // Pretend we didn't see the scope specifier. | ||||
5861 | DC = CurContext; | ||||
5862 | Previous.clear(); | ||||
5863 | } | ||||
5864 | |||||
5865 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||
5866 | |||||
5867 | if (D.getDeclSpec().isInlineSpecified()) | ||||
5868 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||
5869 | << getLangOpts().CPlusPlus17; | ||||
5870 | if (D.getDeclSpec().hasConstexprSpecifier()) | ||||
5871 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) | ||||
5872 | << 1 << D.getDeclSpec().getConstexprSpecifier(); | ||||
5873 | |||||
5874 | if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { | ||||
5875 | if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) | ||||
5876 | Diag(D.getName().StartLocation, | ||||
5877 | diag::err_deduction_guide_invalid_specifier) | ||||
5878 | << "typedef"; | ||||
5879 | else | ||||
5880 | Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) | ||||
5881 | << D.getName().getSourceRange(); | ||||
5882 | return nullptr; | ||||
5883 | } | ||||
5884 | |||||
5885 | TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); | ||||
5886 | if (!NewTD) return nullptr; | ||||
5887 | |||||
5888 | // Handle attributes prior to checking for duplicates in MergeVarDecl | ||||
5889 | ProcessDeclAttributes(S, NewTD, D); | ||||
5890 | |||||
5891 | CheckTypedefForVariablyModifiedType(S, NewTD); | ||||
5892 | |||||
5893 | bool Redeclaration = D.isRedeclaration(); | ||||
5894 | NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); | ||||
5895 | D.setRedeclaration(Redeclaration); | ||||
5896 | return ND; | ||||
5897 | } | ||||
5898 | |||||
5899 | void | ||||
5900 | Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { | ||||
5901 | // C99 6.7.7p2: If a typedef name specifies a variably modified type | ||||
5902 | // then it shall have block scope. | ||||
5903 | // Note that variably modified types must be fixed before merging the decl so | ||||
5904 | // that redeclarations will match. | ||||
5905 | TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); | ||||
5906 | QualType T = TInfo->getType(); | ||||
5907 | if (T->isVariablyModifiedType()) { | ||||
5908 | setFunctionHasBranchProtectedScope(); | ||||
5909 | |||||
5910 | if (S->getFnParent() == nullptr) { | ||||
5911 | bool SizeIsNegative; | ||||
5912 | llvm::APSInt Oversized; | ||||
5913 | TypeSourceInfo *FixedTInfo = | ||||
5914 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | ||||
5915 | SizeIsNegative, | ||||
5916 | Oversized); | ||||
5917 | if (FixedTInfo) { | ||||
5918 | Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); | ||||
5919 | NewTD->setTypeSourceInfo(FixedTInfo); | ||||
5920 | } else { | ||||
5921 | if (SizeIsNegative) | ||||
5922 | Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); | ||||
5923 | else if (T->isVariableArrayType()) | ||||
5924 | Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); | ||||
5925 | else if (Oversized.getBoolValue()) | ||||
5926 | Diag(NewTD->getLocation(), diag::err_array_too_large) | ||||
5927 | << Oversized.toString(10); | ||||
5928 | else | ||||
5929 | Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); | ||||
5930 | NewTD->setInvalidDecl(); | ||||
5931 | } | ||||
5932 | } | ||||
5933 | } | ||||
5934 | } | ||||
5935 | |||||
5936 | /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which | ||||
5937 | /// declares a typedef-name, either using the 'typedef' type specifier or via | ||||
5938 | /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. | ||||
5939 | NamedDecl* | ||||
5940 | Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, | ||||
5941 | LookupResult &Previous, bool &Redeclaration) { | ||||
5942 | |||||
5943 | // Find the shadowed declaration before filtering for scope. | ||||
5944 | NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); | ||||
5945 | |||||
5946 | // Merge the decl with the existing one if appropriate. If the decl is | ||||
5947 | // in an outer scope, it isn't the same thing. | ||||
5948 | FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, | ||||
5949 | /*AllowInlineNamespace*/false); | ||||
5950 | filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); | ||||
5951 | if (!Previous.empty()) { | ||||
5952 | Redeclaration = true; | ||||
5953 | MergeTypedefNameDecl(S, NewTD, Previous); | ||||
5954 | } else { | ||||
5955 | inferGslPointerAttribute(NewTD); | ||||
5956 | } | ||||
5957 | |||||
5958 | if (ShadowedDecl && !Redeclaration) | ||||
5959 | CheckShadow(NewTD, ShadowedDecl, Previous); | ||||
5960 | |||||
5961 | // If this is the C FILE type, notify the AST context. | ||||
5962 | if (IdentifierInfo *II = NewTD->getIdentifier()) | ||||
5963 | if (!NewTD->isInvalidDecl() && | ||||
5964 | NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||
5965 | if (II->isStr("FILE")) | ||||
5966 | Context.setFILEDecl(NewTD); | ||||
5967 | else if (II->isStr("jmp_buf")) | ||||
5968 | Context.setjmp_bufDecl(NewTD); | ||||
5969 | else if (II->isStr("sigjmp_buf")) | ||||
5970 | Context.setsigjmp_bufDecl(NewTD); | ||||
5971 | else if (II->isStr("ucontext_t")) | ||||
5972 | Context.setucontext_tDecl(NewTD); | ||||
5973 | } | ||||
5974 | |||||
5975 | return NewTD; | ||||
5976 | } | ||||
5977 | |||||
5978 | /// Determines whether the given declaration is an out-of-scope | ||||
5979 | /// previous declaration. | ||||
5980 | /// | ||||
5981 | /// This routine should be invoked when name lookup has found a | ||||
5982 | /// previous declaration (PrevDecl) that is not in the scope where a | ||||
5983 | /// new declaration by the same name is being introduced. If the new | ||||
5984 | /// declaration occurs in a local scope, previous declarations with | ||||
5985 | /// linkage may still be considered previous declarations (C99 | ||||
5986 | /// 6.2.2p4-5, C++ [basic.link]p6). | ||||
5987 | /// | ||||
5988 | /// \param PrevDecl the previous declaration found by name | ||||
5989 | /// lookup | ||||
5990 | /// | ||||
5991 | /// \param DC the context in which the new declaration is being | ||||
5992 | /// declared. | ||||
5993 | /// | ||||
5994 | /// \returns true if PrevDecl is an out-of-scope previous declaration | ||||
5995 | /// for a new delcaration with the same name. | ||||
5996 | static bool | ||||
5997 | isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, | ||||
5998 | ASTContext &Context) { | ||||
5999 | if (!PrevDecl) | ||||
6000 | return false; | ||||
6001 | |||||
6002 | if (!PrevDecl->hasLinkage()) | ||||
6003 | return false; | ||||
6004 | |||||
6005 | if (Context.getLangOpts().CPlusPlus) { | ||||
6006 | // C++ [basic.link]p6: | ||||
6007 | // If there is a visible declaration of an entity with linkage | ||||
6008 | // having the same name and type, ignoring entities declared | ||||
6009 | // outside the innermost enclosing namespace scope, the block | ||||
6010 | // scope declaration declares that same entity and receives the | ||||
6011 | // linkage of the previous declaration. | ||||
6012 | DeclContext *OuterContext = DC->getRedeclContext(); | ||||
6013 | if (!OuterContext->isFunctionOrMethod()) | ||||
6014 | // This rule only applies to block-scope declarations. | ||||
6015 | return false; | ||||
6016 | |||||
6017 | DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); | ||||
6018 | if (PrevOuterContext->isRecord()) | ||||
6019 | // We found a member function: ignore it. | ||||
6020 | return false; | ||||
6021 | |||||
6022 | // Find the innermost enclosing namespace for the new and | ||||
6023 | // previous declarations. | ||||
6024 | OuterContext = OuterContext->getEnclosingNamespaceContext(); | ||||
6025 | PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); | ||||
6026 | |||||
6027 | // The previous declaration is in a different namespace, so it | ||||
6028 | // isn't the same function. | ||||
6029 | if (!OuterContext->Equals(PrevOuterContext)) | ||||
6030 | return false; | ||||
6031 | } | ||||
6032 | |||||
6033 | return true; | ||||
6034 | } | ||||
6035 | |||||
6036 | static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { | ||||
6037 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | ||||
6038 | if (!SS.isSet()) return; | ||||
6039 | DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); | ||||
6040 | } | ||||
6041 | |||||
6042 | bool Sema::inferObjCARCLifetime(ValueDecl *decl) { | ||||
6043 | QualType type = decl->getType(); | ||||
6044 | Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); | ||||
6045 | if (lifetime == Qualifiers::OCL_Autoreleasing) { | ||||
6046 | // Various kinds of declaration aren't allowed to be __autoreleasing. | ||||
6047 | unsigned kind = -1U; | ||||
6048 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | ||||
6049 | if (var->hasAttr<BlocksAttr>()) | ||||
6050 | kind = 0; // __block | ||||
6051 | else if (!var->hasLocalStorage()) | ||||
6052 | kind = 1; // global | ||||
6053 | } else if (isa<ObjCIvarDecl>(decl)) { | ||||
6054 | kind = 3; // ivar | ||||
6055 | } else if (isa<FieldDecl>(decl)) { | ||||
6056 | kind = 2; // field | ||||
6057 | } | ||||
6058 | |||||
6059 | if (kind != -1U) { | ||||
6060 | Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) | ||||
6061 | << kind; | ||||
6062 | } | ||||
6063 | } else if (lifetime == Qualifiers::OCL_None) { | ||||
6064 | // Try to infer lifetime. | ||||
6065 | if (!type->isObjCLifetimeType()) | ||||
6066 | return false; | ||||
6067 | |||||
6068 | lifetime = type->getObjCARCImplicitLifetime(); | ||||
6069 | type = Context.getLifetimeQualifiedType(type, lifetime); | ||||
6070 | decl->setType(type); | ||||
6071 | } | ||||
6072 | |||||
6073 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | ||||
6074 | // Thread-local variables cannot have lifetime. | ||||
6075 | if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && | ||||
6076 | var->getTLSKind()) { | ||||
6077 | Diag(var->getLocation(), diag::err_arc_thread_ownership) | ||||
6078 | << var->getType(); | ||||
6079 | return true; | ||||
6080 | } | ||||
6081 | } | ||||
6082 | |||||
6083 | return false; | ||||
6084 | } | ||||
6085 | |||||
6086 | static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { | ||||
6087 | // Ensure that an auto decl is deduced otherwise the checks below might cache | ||||
6088 | // the wrong linkage. | ||||
6089 | assert(S.ParsingInitForAutoVars.count(&ND) == 0)((S.ParsingInitForAutoVars.count(&ND) == 0) ? static_cast <void> (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6089, __PRETTY_FUNCTION__)); | ||||
6090 | |||||
6091 | // 'weak' only applies to declarations with external linkage. | ||||
6092 | if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { | ||||
6093 | if (!ND.isExternallyVisible()) { | ||||
6094 | S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); | ||||
6095 | ND.dropAttr<WeakAttr>(); | ||||
6096 | } | ||||
6097 | } | ||||
6098 | if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { | ||||
6099 | if (ND.isExternallyVisible()) { | ||||
6100 | S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); | ||||
6101 | ND.dropAttr<WeakRefAttr>(); | ||||
6102 | ND.dropAttr<AliasAttr>(); | ||||
6103 | } | ||||
6104 | } | ||||
6105 | |||||
6106 | if (auto *VD = dyn_cast<VarDecl>(&ND)) { | ||||
6107 | if (VD->hasInit()) { | ||||
6108 | if (const auto *Attr = VD->getAttr<AliasAttr>()) { | ||||
6109 | assert(VD->isThisDeclarationADefinition() &&((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible () && "Broken AliasAttr handled late!") ? static_cast <void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6110, __PRETTY_FUNCTION__)) | ||||
6110 | !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible () && "Broken AliasAttr handled late!") ? static_cast <void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6110, __PRETTY_FUNCTION__)); | ||||
6111 | S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; | ||||
6112 | VD->dropAttr<AliasAttr>(); | ||||
6113 | } | ||||
6114 | } | ||||
6115 | } | ||||
6116 | |||||
6117 | // 'selectany' only applies to externally visible variable declarations. | ||||
6118 | // It does not apply to functions. | ||||
6119 | if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { | ||||
6120 | if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { | ||||
6121 | S.Diag(Attr->getLocation(), | ||||
6122 | diag::err_attribute_selectany_non_extern_data); | ||||
6123 | ND.dropAttr<SelectAnyAttr>(); | ||||
6124 | } | ||||
6125 | } | ||||
6126 | |||||
6127 | if (const InheritableAttr *Attr = getDLLAttr(&ND)) { | ||||
6128 | auto *VD = dyn_cast<VarDecl>(&ND); | ||||
6129 | bool IsAnonymousNS = false; | ||||
6130 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | ||||
6131 | if (VD) { | ||||
6132 | const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); | ||||
6133 | while (NS && !IsAnonymousNS) { | ||||
6134 | IsAnonymousNS = NS->isAnonymousNamespace(); | ||||
6135 | NS = dyn_cast<NamespaceDecl>(NS->getParent()); | ||||
6136 | } | ||||
6137 | } | ||||
6138 | // dll attributes require external linkage. Static locals may have external | ||||
6139 | // linkage but still cannot be explicitly imported or exported. | ||||
6140 | // In Microsoft mode, a variable defined in anonymous namespace must have | ||||
6141 | // external linkage in order to be exported. | ||||
6142 | bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; | ||||
6143 | if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || | ||||
6144 | (!AnonNSInMicrosoftMode && | ||||
6145 | (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { | ||||
6146 | S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) | ||||
6147 | << &ND << Attr; | ||||
6148 | ND.setInvalidDecl(); | ||||
6149 | } | ||||
6150 | } | ||||
6151 | |||||
6152 | // Virtual functions cannot be marked as 'notail'. | ||||
6153 | if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) | ||||
6154 | if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) | ||||
6155 | if (MD->isVirtual()) { | ||||
6156 | S.Diag(ND.getLocation(), | ||||
6157 | diag::err_invalid_attribute_on_virtual_function) | ||||
6158 | << Attr; | ||||
6159 | ND.dropAttr<NotTailCalledAttr>(); | ||||
6160 | } | ||||
6161 | |||||
6162 | // Check the attributes on the function type, if any. | ||||
6163 | if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { | ||||
6164 | // Don't declare this variable in the second operand of the for-statement; | ||||
6165 | // GCC miscompiles that by ending its lifetime before evaluating the | ||||
6166 | // third operand. See gcc.gnu.org/PR86769. | ||||
6167 | AttributedTypeLoc ATL; | ||||
6168 | for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); | ||||
6169 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | ||||
6170 | TL = ATL.getModifiedLoc()) { | ||||
6171 | // The [[lifetimebound]] attribute can be applied to the implicit object | ||||
6172 | // parameter of a non-static member function (other than a ctor or dtor) | ||||
6173 | // by applying it to the function type. | ||||
6174 | if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { | ||||
6175 | const auto *MD = dyn_cast<CXXMethodDecl>(FD); | ||||
6176 | if (!MD || MD->isStatic()) { | ||||
6177 | S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) | ||||
6178 | << !MD << A->getRange(); | ||||
6179 | } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { | ||||
6180 | S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) | ||||
6181 | << isa<CXXDestructorDecl>(MD) << A->getRange(); | ||||
6182 | } | ||||
6183 | } | ||||
6184 | } | ||||
6185 | } | ||||
6186 | } | ||||
6187 | |||||
6188 | static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, | ||||
6189 | NamedDecl *NewDecl, | ||||
6190 | bool IsSpecialization, | ||||
6191 | bool IsDefinition) { | ||||
6192 | if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) | ||||
6193 | return; | ||||
6194 | |||||
6195 | bool IsTemplate = false; | ||||
6196 | if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { | ||||
6197 | OldDecl = OldTD->getTemplatedDecl(); | ||||
6198 | IsTemplate = true; | ||||
6199 | if (!IsSpecialization) | ||||
6200 | IsDefinition = false; | ||||
6201 | } | ||||
6202 | if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { | ||||
6203 | NewDecl = NewTD->getTemplatedDecl(); | ||||
6204 | IsTemplate = true; | ||||
6205 | } | ||||
6206 | |||||
6207 | if (!OldDecl || !NewDecl) | ||||
6208 | return; | ||||
6209 | |||||
6210 | const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); | ||||
6211 | const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); | ||||
6212 | const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); | ||||
6213 | const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); | ||||
6214 | |||||
6215 | // dllimport and dllexport are inheritable attributes so we have to exclude | ||||
6216 | // inherited attribute instances. | ||||
6217 | bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || | ||||
6218 | (NewExportAttr && !NewExportAttr->isInherited()); | ||||
6219 | |||||
6220 | // A redeclaration is not allowed to add a dllimport or dllexport attribute, | ||||
6221 | // the only exception being explicit specializations. | ||||
6222 | // Implicitly generated declarations are also excluded for now because there | ||||
6223 | // is no other way to switch these to use dllimport or dllexport. | ||||
6224 | bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; | ||||
6225 | |||||
6226 | if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { | ||||
6227 | // Allow with a warning for free functions and global variables. | ||||
6228 | bool JustWarn = false; | ||||
6229 | if (!OldDecl->isCXXClassMember()) { | ||||
6230 | auto *VD = dyn_cast<VarDecl>(OldDecl); | ||||
6231 | if (VD && !VD->getDescribedVarTemplate()) | ||||
6232 | JustWarn = true; | ||||
6233 | auto *FD = dyn_cast<FunctionDecl>(OldDecl); | ||||
6234 | if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) | ||||
6235 | JustWarn = true; | ||||
6236 | } | ||||
6237 | |||||
6238 | // We cannot change a declaration that's been used because IR has already | ||||
6239 | // been emitted. Dllimported functions will still work though (modulo | ||||
6240 | // address equality) as they can use the thunk. | ||||
6241 | if (OldDecl->isUsed()) | ||||
6242 | if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) | ||||
6243 | JustWarn = false; | ||||
6244 | |||||
6245 | unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration | ||||
6246 | : diag::err_attribute_dll_redeclaration; | ||||
6247 | S.Diag(NewDecl->getLocation(), DiagID) | ||||
6248 | << NewDecl | ||||
6249 | << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); | ||||
6250 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||
6251 | if (!JustWarn) { | ||||
6252 | NewDecl->setInvalidDecl(); | ||||
6253 | return; | ||||
6254 | } | ||||
6255 | } | ||||
6256 | |||||
6257 | // A redeclaration is not allowed to drop a dllimport attribute, the only | ||||
6258 | // exceptions being inline function definitions (except for function | ||||
6259 | // templates), local extern declarations, qualified friend declarations or | ||||
6260 | // special MSVC extension: in the last case, the declaration is treated as if | ||||
6261 | // it were marked dllexport. | ||||
6262 | bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; | ||||
6263 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | ||||
6264 | if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { | ||||
6265 | // Ignore static data because out-of-line definitions are diagnosed | ||||
6266 | // separately. | ||||
6267 | IsStaticDataMember = VD->isStaticDataMember(); | ||||
6268 | IsDefinition = VD->isThisDeclarationADefinition(S.Context) != | ||||
6269 | VarDecl::DeclarationOnly; | ||||
6270 | } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { | ||||
6271 | IsInline = FD->isInlined(); | ||||
6272 | IsQualifiedFriend = FD->getQualifier() && | ||||
6273 | FD->getFriendObjectKind() == Decl::FOK_Declared; | ||||
6274 | } | ||||
6275 | |||||
6276 | if (OldImportAttr && !HasNewAttr && | ||||
6277 | (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && | ||||
6278 | !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { | ||||
6279 | if (IsMicrosoft && IsDefinition) { | ||||
6280 | S.Diag(NewDecl->getLocation(), | ||||
6281 | diag::warn_redeclaration_without_import_attribute) | ||||
6282 | << NewDecl; | ||||
6283 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||
6284 | NewDecl->dropAttr<DLLImportAttr>(); | ||||
6285 | NewDecl->addAttr( | ||||
6286 | DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); | ||||
6287 | } else { | ||||
6288 | S.Diag(NewDecl->getLocation(), | ||||
6289 | diag::warn_redeclaration_without_attribute_prev_attribute_ignored) | ||||
6290 | << NewDecl << OldImportAttr; | ||||
6291 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||
6292 | S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); | ||||
6293 | OldDecl->dropAttr<DLLImportAttr>(); | ||||
6294 | NewDecl->dropAttr<DLLImportAttr>(); | ||||
6295 | } | ||||
6296 | } else if (IsInline && OldImportAttr && !IsMicrosoft) { | ||||
6297 | // In MinGW, seeing a function declared inline drops the dllimport | ||||
6298 | // attribute. | ||||
6299 | OldDecl->dropAttr<DLLImportAttr>(); | ||||
6300 | NewDecl->dropAttr<DLLImportAttr>(); | ||||
6301 | S.Diag(NewDecl->getLocation(), | ||||
6302 | diag::warn_dllimport_dropped_from_inline_function) | ||||
6303 | << NewDecl << OldImportAttr; | ||||
6304 | } | ||||
6305 | |||||
6306 | // A specialization of a class template member function is processed here | ||||
6307 | // since it's a redeclaration. If the parent class is dllexport, the | ||||
6308 | // specialization inherits that attribute. This doesn't happen automatically | ||||
6309 | // since the parent class isn't instantiated until later. | ||||
6310 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { | ||||
6311 | if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && | ||||
6312 | !NewImportAttr && !NewExportAttr) { | ||||
6313 | if (const DLLExportAttr *ParentExportAttr = | ||||
6314 | MD->getParent()->getAttr<DLLExportAttr>()) { | ||||
6315 | DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); | ||||
6316 | NewAttr->setInherited(true); | ||||
6317 | NewDecl->addAttr(NewAttr); | ||||
6318 | } | ||||
6319 | } | ||||
6320 | } | ||||
6321 | } | ||||
6322 | |||||
6323 | /// Given that we are within the definition of the given function, | ||||
6324 | /// will that definition behave like C99's 'inline', where the | ||||
6325 | /// definition is discarded except for optimization purposes? | ||||
6326 | static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { | ||||
6327 | // Try to avoid calling GetGVALinkageForFunction. | ||||
6328 | |||||
6329 | // All cases of this require the 'inline' keyword. | ||||
6330 | if (!FD->isInlined()) return false; | ||||
6331 | |||||
6332 | // This is only possible in C++ with the gnu_inline attribute. | ||||
6333 | if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) | ||||
6334 | return false; | ||||
6335 | |||||
6336 | // Okay, go ahead and call the relatively-more-expensive function. | ||||
6337 | return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; | ||||
6338 | } | ||||
6339 | |||||
6340 | /// Determine whether a variable is extern "C" prior to attaching | ||||
6341 | /// an initializer. We can't just call isExternC() here, because that | ||||
6342 | /// will also compute and cache whether the declaration is externally | ||||
6343 | /// visible, which might change when we attach the initializer. | ||||
6344 | /// | ||||
6345 | /// This can only be used if the declaration is known to not be a | ||||
6346 | /// redeclaration of an internal linkage declaration. | ||||
6347 | /// | ||||
6348 | /// For instance: | ||||
6349 | /// | ||||
6350 | /// auto x = []{}; | ||||
6351 | /// | ||||
6352 | /// Attaching the initializer here makes this declaration not externally | ||||
6353 | /// visible, because its type has internal linkage. | ||||
6354 | /// | ||||
6355 | /// FIXME: This is a hack. | ||||
6356 | template<typename T> | ||||
6357 | static bool isIncompleteDeclExternC(Sema &S, const T *D) { | ||||
6358 | if (S.getLangOpts().CPlusPlus) { | ||||
6359 | // In C++, the overloadable attribute negates the effects of extern "C". | ||||
6360 | if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) | ||||
6361 | return false; | ||||
6362 | |||||
6363 | // So do CUDA's host/device attributes. | ||||
6364 | if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || | ||||
6365 | D->template hasAttr<CUDAHostAttr>())) | ||||
6366 | return false; | ||||
6367 | } | ||||
6368 | return D->isExternC(); | ||||
6369 | } | ||||
6370 | |||||
6371 | static bool shouldConsiderLinkage(const VarDecl *VD) { | ||||
6372 | const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); | ||||
6373 | if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || | ||||
6374 | isa<OMPDeclareMapperDecl>(DC)) | ||||
6375 | return VD->hasExternalStorage(); | ||||
6376 | if (DC->isFileContext()) | ||||
6377 | return true; | ||||
6378 | if (DC->isRecord()) | ||||
6379 | return false; | ||||
6380 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6380); | ||||
6381 | } | ||||
6382 | |||||
6383 | static bool shouldConsiderLinkage(const FunctionDecl *FD) { | ||||
6384 | const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); | ||||
6385 | if (DC->isFileContext() || DC->isFunctionOrMethod() || | ||||
6386 | isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) | ||||
6387 | return true; | ||||
6388 | if (DC->isRecord()) | ||||
6389 | return false; | ||||
6390 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6390); | ||||
6391 | } | ||||
6392 | |||||
6393 | static bool hasParsedAttr(Scope *S, const Declarator &PD, | ||||
6394 | ParsedAttr::Kind Kind) { | ||||
6395 | // Check decl attributes on the DeclSpec. | ||||
6396 | if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) | ||||
6397 | return true; | ||||
6398 | |||||
6399 | // Walk the declarator structure, checking decl attributes that were in a type | ||||
6400 | // position to the decl itself. | ||||
6401 | for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { | ||||
6402 | if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) | ||||
6403 | return true; | ||||
6404 | } | ||||
6405 | |||||
6406 | // Finally, check attributes on the decl itself. | ||||
6407 | return PD.getAttributes().hasAttribute(Kind); | ||||
6408 | } | ||||
6409 | |||||
6410 | /// Adjust the \c DeclContext for a function or variable that might be a | ||||
6411 | /// function-local external declaration. | ||||
6412 | bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { | ||||
6413 | if (!DC->isFunctionOrMethod()) | ||||
6414 | return false; | ||||
6415 | |||||
6416 | // If this is a local extern function or variable declared within a function | ||||
6417 | // template, don't add it into the enclosing namespace scope until it is | ||||
6418 | // instantiated; it might have a dependent type right now. | ||||
6419 | if (DC->isDependentContext()) | ||||
6420 | return true; | ||||
6421 | |||||
6422 | // C++11 [basic.link]p7: | ||||
6423 | // When a block scope declaration of an entity with linkage is not found to | ||||
6424 | // refer to some other declaration, then that entity is a member of the | ||||
6425 | // innermost enclosing namespace. | ||||
6426 | // | ||||
6427 | // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a | ||||
6428 | // semantically-enclosing namespace, not a lexically-enclosing one. | ||||
6429 | while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) | ||||
6430 | DC = DC->getParent(); | ||||
6431 | return true; | ||||
6432 | } | ||||
6433 | |||||
6434 | /// Returns true if given declaration has external C language linkage. | ||||
6435 | static bool isDeclExternC(const Decl *D) { | ||||
6436 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) | ||||
6437 | return FD->isExternC(); | ||||
6438 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||
6439 | return VD->isExternC(); | ||||
6440 | |||||
6441 | llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6441); | ||||
6442 | } | ||||
6443 | |||||
6444 | NamedDecl *Sema::ActOnVariableDeclarator( | ||||
6445 | Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, | ||||
6446 | LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, | ||||
6447 | bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { | ||||
6448 | QualType R = TInfo->getType(); | ||||
6449 | DeclarationName Name = GetNameForDeclarator(D).getName(); | ||||
6450 | |||||
6451 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||
6452 | |||||
6453 | if (D.isDecompositionDeclarator()) { | ||||
6454 | // Take the name of the first declarator as our name for diagnostic | ||||
6455 | // purposes. | ||||
6456 | auto &Decomp = D.getDecompositionDeclarator(); | ||||
6457 | if (!Decomp.bindings().empty()) { | ||||
6458 | II = Decomp.bindings()[0].Name; | ||||
6459 | Name = II; | ||||
6460 | } | ||||
6461 | } else if (!II) { | ||||
6462 | Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; | ||||
6463 | return nullptr; | ||||
6464 | } | ||||
6465 | |||||
6466 | if (getLangOpts().OpenCL) { | ||||
6467 | // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. | ||||
6468 | // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function | ||||
6469 | // argument. | ||||
6470 | if (R->isImageType() || R->isPipeType()) { | ||||
6471 | Diag(D.getIdentifierLoc(), | ||||
6472 | diag::err_opencl_type_can_only_be_used_as_function_parameter) | ||||
6473 | << R; | ||||
6474 | D.setInvalidType(); | ||||
6475 | return nullptr; | ||||
6476 | } | ||||
6477 | |||||
6478 | // OpenCL v1.2 s6.9.r: | ||||
6479 | // The event type cannot be used to declare a program scope variable. | ||||
6480 | // OpenCL v2.0 s6.9.q: | ||||
6481 | // The clk_event_t and reserve_id_t types cannot be declared in program scope. | ||||
6482 | if (NULL__null == S->getParent()) { | ||||
6483 | if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { | ||||
6484 | Diag(D.getIdentifierLoc(), | ||||
6485 | diag::err_invalid_type_for_program_scope_var) << R; | ||||
6486 | D.setInvalidType(); | ||||
6487 | return nullptr; | ||||
6488 | } | ||||
6489 | } | ||||
6490 | |||||
6491 | // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. | ||||
6492 | QualType NR = R; | ||||
6493 | while (NR->isPointerType()) { | ||||
6494 | if (NR->isFunctionPointerType()) { | ||||
6495 | Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); | ||||
6496 | D.setInvalidType(); | ||||
6497 | break; | ||||
6498 | } | ||||
6499 | NR = NR->getPointeeType(); | ||||
6500 | } | ||||
6501 | |||||
6502 | if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { | ||||
6503 | // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and | ||||
6504 | // half array type (unless the cl_khr_fp16 extension is enabled). | ||||
6505 | if (Context.getBaseElementType(R)->isHalfType()) { | ||||
6506 | Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; | ||||
6507 | D.setInvalidType(); | ||||
6508 | } | ||||
6509 | } | ||||
6510 | |||||
6511 | if (R->isSamplerT()) { | ||||
6512 | // OpenCL v1.2 s6.9.b p4: | ||||
6513 | // The sampler type cannot be used with the __local and __global address | ||||
6514 | // space qualifiers. | ||||
6515 | if (R.getAddressSpace() == LangAS::opencl_local || | ||||
6516 | R.getAddressSpace() == LangAS::opencl_global) { | ||||
6517 | Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); | ||||
6518 | } | ||||
6519 | |||||
6520 | // OpenCL v1.2 s6.12.14.1: | ||||
6521 | // A global sampler must be declared with either the constant address | ||||
6522 | // space qualifier or with the const qualifier. | ||||
6523 | if (DC->isTranslationUnit() && | ||||
6524 | !(R.getAddressSpace() == LangAS::opencl_constant || | ||||
6525 | R.isConstQualified())) { | ||||
6526 | Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); | ||||
6527 | D.setInvalidType(); | ||||
6528 | } | ||||
6529 | } | ||||
6530 | |||||
6531 | // OpenCL v1.2 s6.9.r: | ||||
6532 | // The event type cannot be used with the __local, __constant and __global | ||||
6533 | // address space qualifiers. | ||||
6534 | if (R->isEventT()) { | ||||
6535 | if (R.getAddressSpace() != LangAS::opencl_private) { | ||||
6536 | Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); | ||||
6537 | D.setInvalidType(); | ||||
6538 | } | ||||
6539 | } | ||||
6540 | |||||
6541 | // C++ for OpenCL does not allow the thread_local storage qualifier. | ||||
6542 | // OpenCL C does not support thread_local either, and | ||||
6543 | // also reject all other thread storage class specifiers. | ||||
6544 | DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); | ||||
6545 | if (TSC != TSCS_unspecified) { | ||||
6546 | bool IsCXX = getLangOpts().OpenCLCPlusPlus; | ||||
6547 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
6548 | diag::err_opencl_unknown_type_specifier) | ||||
6549 | << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() | ||||
6550 | << DeclSpec::getSpecifierName(TSC) << 1; | ||||
6551 | D.setInvalidType(); | ||||
6552 | return nullptr; | ||||
6553 | } | ||||
6554 | } | ||||
6555 | |||||
6556 | DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); | ||||
6557 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); | ||||
6558 | |||||
6559 | // dllimport globals without explicit storage class are treated as extern. We | ||||
6560 | // have to change the storage class this early to get the right DeclContext. | ||||
6561 | if (SC == SC_None && !DC->isRecord() && | ||||
6562 | hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && | ||||
6563 | !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) | ||||
6564 | SC = SC_Extern; | ||||
6565 | |||||
6566 | DeclContext *OriginalDC = DC; | ||||
6567 | bool IsLocalExternDecl = SC == SC_Extern && | ||||
6568 | adjustContextForLocalExternDecl(DC); | ||||
6569 | |||||
6570 | if (SCSpec == DeclSpec::SCS_mutable) { | ||||
6571 | // mutable can only appear on non-static class members, so it's always | ||||
6572 | // an error here | ||||
6573 | Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); | ||||
6574 | D.setInvalidType(); | ||||
6575 | SC = SC_None; | ||||
6576 | } | ||||
6577 | |||||
6578 | if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && | ||||
6579 | !D.getAsmLabel() && !getSourceManager().isInSystemMacro( | ||||
6580 | D.getDeclSpec().getStorageClassSpecLoc())) { | ||||
6581 | // In C++11, the 'register' storage class specifier is deprecated. | ||||
6582 | // Suppress the warning in system macros, it's used in macros in some | ||||
6583 | // popular C system headers, such as in glibc's htonl() macro. | ||||
6584 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
6585 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | ||||
6586 | : diag::warn_deprecated_register) | ||||
6587 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||
6588 | } | ||||
6589 | |||||
6590 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||
6591 | |||||
6592 | if (!DC->isRecord() && S->getFnParent() == nullptr) { | ||||
6593 | // C99 6.9p2: The storage-class specifiers auto and register shall not | ||||
6594 | // appear in the declaration specifiers in an external declaration. | ||||
6595 | // Global Register+Asm is a GNU extension we support. | ||||
6596 | if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { | ||||
6597 | Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); | ||||
6598 | D.setInvalidType(); | ||||
6599 | } | ||||
6600 | } | ||||
6601 | |||||
6602 | bool IsMemberSpecialization = false; | ||||
6603 | bool IsVariableTemplateSpecialization = false; | ||||
6604 | bool IsPartialSpecialization = false; | ||||
6605 | bool IsVariableTemplate = false; | ||||
6606 | VarDecl *NewVD = nullptr; | ||||
6607 | VarTemplateDecl *NewTemplate = nullptr; | ||||
6608 | TemplateParameterList *TemplateParams = nullptr; | ||||
6609 | if (!getLangOpts().CPlusPlus) { | ||||
6610 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), | ||||
6611 | II, R, TInfo, SC); | ||||
6612 | |||||
6613 | if (R->getContainedDeducedType()) | ||||
6614 | ParsingInitForAutoVars.insert(NewVD); | ||||
6615 | |||||
6616 | if (D.isInvalidType()) | ||||
6617 | NewVD->setInvalidDecl(); | ||||
6618 | |||||
6619 | if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && | ||||
6620 | NewVD->hasLocalStorage()) | ||||
6621 | checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), | ||||
6622 | NTCUC_AutoVar, NTCUK_Destruct); | ||||
6623 | } else { | ||||
6624 | bool Invalid = false; | ||||
6625 | |||||
6626 | if (DC->isRecord() && !CurContext->isRecord()) { | ||||
6627 | // This is an out-of-line definition of a static data member. | ||||
6628 | switch (SC) { | ||||
6629 | case SC_None: | ||||
6630 | break; | ||||
6631 | case SC_Static: | ||||
6632 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
6633 | diag::err_static_out_of_line) | ||||
6634 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||
6635 | break; | ||||
6636 | case SC_Auto: | ||||
6637 | case SC_Register: | ||||
6638 | case SC_Extern: | ||||
6639 | // [dcl.stc] p2: The auto or register specifiers shall be applied only | ||||
6640 | // to names of variables declared in a block or to function parameters. | ||||
6641 | // [dcl.stc] p6: The extern specifier cannot be used in the declaration | ||||
6642 | // of class members | ||||
6643 | |||||
6644 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
6645 | diag::err_storage_class_for_static_member) | ||||
6646 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||
6647 | break; | ||||
6648 | case SC_PrivateExtern: | ||||
6649 | llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6649); | ||||
6650 | } | ||||
6651 | } | ||||
6652 | |||||
6653 | if (SC == SC_Static && CurContext->isRecord()) { | ||||
6654 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { | ||||
6655 | if (RD->isLocalClass()) | ||||
6656 | Diag(D.getIdentifierLoc(), | ||||
6657 | diag::err_static_data_member_not_allowed_in_local_class) | ||||
6658 | << Name << RD->getDeclName(); | ||||
6659 | |||||
6660 | // C++98 [class.union]p1: If a union contains a static data member, | ||||
6661 | // the program is ill-formed. C++11 drops this restriction. | ||||
6662 | if (RD->isUnion()) | ||||
6663 | Diag(D.getIdentifierLoc(), | ||||
6664 | getLangOpts().CPlusPlus11 | ||||
6665 | ? diag::warn_cxx98_compat_static_data_member_in_union | ||||
6666 | : diag::ext_static_data_member_in_union) << Name; | ||||
6667 | // We conservatively disallow static data members in anonymous structs. | ||||
6668 | else if (!RD->getDeclName()) | ||||
6669 | Diag(D.getIdentifierLoc(), | ||||
6670 | diag::err_static_data_member_not_allowed_in_anon_struct) | ||||
6671 | << Name << RD->isUnion(); | ||||
6672 | } | ||||
6673 | } | ||||
6674 | |||||
6675 | // Match up the template parameter lists with the scope specifier, then | ||||
6676 | // determine whether we have a template or a template specialization. | ||||
6677 | TemplateParams = MatchTemplateParametersToScopeSpecifier( | ||||
6678 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | ||||
6679 | D.getCXXScopeSpec(), | ||||
6680 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | ||||
6681 | ? D.getName().TemplateId | ||||
6682 | : nullptr, | ||||
6683 | TemplateParamLists, | ||||
6684 | /*never a friend*/ false, IsMemberSpecialization, Invalid); | ||||
6685 | |||||
6686 | if (TemplateParams) { | ||||
6687 | if (!TemplateParams->size() && | ||||
6688 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | ||||
6689 | // There is an extraneous 'template<>' for this variable. Complain | ||||
6690 | // about it, but allow the declaration of the variable. | ||||
6691 | Diag(TemplateParams->getTemplateLoc(), | ||||
6692 | diag::err_template_variable_noparams) | ||||
6693 | << II | ||||
6694 | << SourceRange(TemplateParams->getTemplateLoc(), | ||||
6695 | TemplateParams->getRAngleLoc()); | ||||
6696 | TemplateParams = nullptr; | ||||
6697 | } else { | ||||
6698 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||
6699 | // This is an explicit specialization or a partial specialization. | ||||
6700 | // FIXME: Check that we can declare a specialization here. | ||||
6701 | IsVariableTemplateSpecialization = true; | ||||
6702 | IsPartialSpecialization = TemplateParams->size() > 0; | ||||
6703 | } else { // if (TemplateParams->size() > 0) | ||||
6704 | // This is a template declaration. | ||||
6705 | IsVariableTemplate = true; | ||||
6706 | |||||
6707 | // Check that we can declare a template here. | ||||
6708 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||
6709 | return nullptr; | ||||
6710 | |||||
6711 | // Only C++1y supports variable templates (N3651). | ||||
6712 | Diag(D.getIdentifierLoc(), | ||||
6713 | getLangOpts().CPlusPlus14 | ||||
6714 | ? diag::warn_cxx11_compat_variable_template | ||||
6715 | : diag::ext_variable_template); | ||||
6716 | } | ||||
6717 | } | ||||
6718 | } else { | ||||
6719 | assert((Invalid ||(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6721, __PRETTY_FUNCTION__)) | ||||
6720 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6721, __PRETTY_FUNCTION__)) | ||||
6721 | "should have a 'template<>' for this decl")(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6721, __PRETTY_FUNCTION__)); | ||||
6722 | } | ||||
6723 | |||||
6724 | if (IsVariableTemplateSpecialization) { | ||||
6725 | SourceLocation TemplateKWLoc = | ||||
6726 | TemplateParamLists.size() > 0 | ||||
6727 | ? TemplateParamLists[0]->getTemplateLoc() | ||||
6728 | : SourceLocation(); | ||||
6729 | DeclResult Res = ActOnVarTemplateSpecialization( | ||||
6730 | S, D, TInfo, TemplateKWLoc, TemplateParams, SC, | ||||
6731 | IsPartialSpecialization); | ||||
6732 | if (Res.isInvalid()) | ||||
6733 | return nullptr; | ||||
6734 | NewVD = cast<VarDecl>(Res.get()); | ||||
6735 | AddToScope = false; | ||||
6736 | } else if (D.isDecompositionDeclarator()) { | ||||
6737 | NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), | ||||
6738 | D.getIdentifierLoc(), R, TInfo, SC, | ||||
6739 | Bindings); | ||||
6740 | } else | ||||
6741 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), | ||||
6742 | D.getIdentifierLoc(), II, R, TInfo, SC); | ||||
6743 | |||||
6744 | // If this is supposed to be a variable template, create it as such. | ||||
6745 | if (IsVariableTemplate) { | ||||
6746 | NewTemplate = | ||||
6747 | VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, | ||||
6748 | TemplateParams, NewVD); | ||||
6749 | NewVD->setDescribedVarTemplate(NewTemplate); | ||||
6750 | } | ||||
6751 | |||||
6752 | // If this decl has an auto type in need of deduction, make a note of the | ||||
6753 | // Decl so we can diagnose uses of it in its own initializer. | ||||
6754 | if (R->getContainedDeducedType()) | ||||
6755 | ParsingInitForAutoVars.insert(NewVD); | ||||
6756 | |||||
6757 | if (D.isInvalidType() || Invalid) { | ||||
6758 | NewVD->setInvalidDecl(); | ||||
6759 | if (NewTemplate) | ||||
6760 | NewTemplate->setInvalidDecl(); | ||||
6761 | } | ||||
6762 | |||||
6763 | SetNestedNameSpecifier(*this, NewVD, D); | ||||
6764 | |||||
6765 | // If we have any template parameter lists that don't directly belong to | ||||
6766 | // the variable (matching the scope specifier), store them. | ||||
6767 | unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; | ||||
6768 | if (TemplateParamLists.size() > VDTemplateParamLists) | ||||
6769 | NewVD->setTemplateParameterListsInfo( | ||||
6770 | Context, TemplateParamLists.drop_back(VDTemplateParamLists)); | ||||
6771 | } | ||||
6772 | |||||
6773 | if (D.getDeclSpec().isInlineSpecified()) { | ||||
6774 | if (!getLangOpts().CPlusPlus) { | ||||
6775 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||
6776 | << 0; | ||||
6777 | } else if (CurContext->isFunctionOrMethod()) { | ||||
6778 | // 'inline' is not allowed on block scope variable declaration. | ||||
6779 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||
6780 | diag::err_inline_declaration_block_scope) << Name | ||||
6781 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | ||||
6782 | } else { | ||||
6783 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||
6784 | getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable | ||||
6785 | : diag::ext_inline_variable); | ||||
6786 | NewVD->setInlineSpecified(); | ||||
6787 | } | ||||
6788 | } | ||||
6789 | |||||
6790 | // Set the lexical context. If the declarator has a C++ scope specifier, the | ||||
6791 | // lexical context will be different from the semantic context. | ||||
6792 | NewVD->setLexicalDeclContext(CurContext); | ||||
6793 | if (NewTemplate) | ||||
6794 | NewTemplate->setLexicalDeclContext(CurContext); | ||||
6795 | |||||
6796 | if (IsLocalExternDecl) { | ||||
6797 | if (D.isDecompositionDeclarator()) | ||||
6798 | for (auto *B : Bindings) | ||||
6799 | B->setLocalExternDecl(); | ||||
6800 | else | ||||
6801 | NewVD->setLocalExternDecl(); | ||||
6802 | } | ||||
6803 | |||||
6804 | bool EmitTLSUnsupportedError = false; | ||||
6805 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { | ||||
6806 | // C++11 [dcl.stc]p4: | ||||
6807 | // When thread_local is applied to a variable of block scope the | ||||
6808 | // storage-class-specifier static is implied if it does not appear | ||||
6809 | // explicitly. | ||||
6810 | // Core issue: 'static' is not implied if the variable is declared | ||||
6811 | // 'extern'. | ||||
6812 | if (NewVD->hasLocalStorage() && | ||||
6813 | (SCSpec != DeclSpec::SCS_unspecified || | ||||
6814 | TSCS != DeclSpec::TSCS_thread_local || | ||||
6815 | !DC->isFunctionOrMethod())) | ||||
6816 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
6817 | diag::err_thread_non_global) | ||||
6818 | << DeclSpec::getSpecifierName(TSCS); | ||||
6819 | else if (!Context.getTargetInfo().isTLSSupported()) { | ||||
6820 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { | ||||
6821 | // Postpone error emission until we've collected attributes required to | ||||
6822 | // figure out whether it's a host or device variable and whether the | ||||
6823 | // error should be ignored. | ||||
6824 | EmitTLSUnsupportedError = true; | ||||
6825 | // We still need to mark the variable as TLS so it shows up in AST with | ||||
6826 | // proper storage class for other tools to use even if we're not going | ||||
6827 | // to emit any code for it. | ||||
6828 | NewVD->setTSCSpec(TSCS); | ||||
6829 | } else | ||||
6830 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
6831 | diag::err_thread_unsupported); | ||||
6832 | } else | ||||
6833 | NewVD->setTSCSpec(TSCS); | ||||
6834 | } | ||||
6835 | |||||
6836 | switch (D.getDeclSpec().getConstexprSpecifier()) { | ||||
6837 | case CSK_unspecified: | ||||
6838 | break; | ||||
6839 | |||||
6840 | case CSK_consteval: | ||||
6841 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||
6842 | diag::err_constexpr_wrong_decl_kind) | ||||
6843 | << D.getDeclSpec().getConstexprSpecifier(); | ||||
6844 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
6845 | |||||
6846 | case CSK_constexpr: | ||||
6847 | NewVD->setConstexpr(true); | ||||
6848 | // C++1z [dcl.spec.constexpr]p1: | ||||
6849 | // A static data member declared with the constexpr specifier is | ||||
6850 | // implicitly an inline variable. | ||||
6851 | if (NewVD->isStaticDataMember() && | ||||
6852 | (getLangOpts().CPlusPlus17 || | ||||
6853 | Context.getTargetInfo().getCXXABI().isMicrosoft())) | ||||
6854 | NewVD->setImplicitlyInline(); | ||||
6855 | break; | ||||
6856 | |||||
6857 | case CSK_constinit: | ||||
6858 | if (!NewVD->hasGlobalStorage()) | ||||
6859 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||
6860 | diag::err_constinit_local_variable); | ||||
6861 | else | ||||
6862 | NewVD->addAttr(ConstInitAttr::Create( | ||||
6863 | Context, D.getDeclSpec().getConstexprSpecLoc(), | ||||
6864 | AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); | ||||
6865 | break; | ||||
6866 | } | ||||
6867 | |||||
6868 | // C99 6.7.4p3 | ||||
6869 | // An inline definition of a function with external linkage shall | ||||
6870 | // not contain a definition of a modifiable object with static or | ||||
6871 | // thread storage duration... | ||||
6872 | // We only apply this when the function is required to be defined | ||||
6873 | // elsewhere, i.e. when the function is not 'extern inline'. Note | ||||
6874 | // that a local variable with thread storage duration still has to | ||||
6875 | // be marked 'static'. Also note that it's possible to get these | ||||
6876 | // semantics in C++ using __attribute__((gnu_inline)). | ||||
6877 | if (SC == SC_Static && S->getFnParent() != nullptr && | ||||
6878 | !NewVD->getType().isConstQualified()) { | ||||
6879 | FunctionDecl *CurFD = getCurFunctionDecl(); | ||||
6880 | if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { | ||||
6881 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
6882 | diag::warn_static_local_in_extern_inline); | ||||
6883 | MaybeSuggestAddingStaticToDecl(CurFD); | ||||
6884 | } | ||||
6885 | } | ||||
6886 | |||||
6887 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||
6888 | if (IsVariableTemplateSpecialization) | ||||
6889 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | ||||
6890 | << (IsPartialSpecialization ? 1 : 0) | ||||
6891 | << FixItHint::CreateRemoval( | ||||
6892 | D.getDeclSpec().getModulePrivateSpecLoc()); | ||||
6893 | else if (IsMemberSpecialization) | ||||
6894 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | ||||
6895 | << 2 | ||||
6896 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||
6897 | else if (NewVD->hasLocalStorage()) | ||||
6898 | Diag(NewVD->getLocation(), diag::err_module_private_local) | ||||
6899 | << 0 << NewVD->getDeclName() | ||||
6900 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||
6901 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||
6902 | else { | ||||
6903 | NewVD->setModulePrivate(); | ||||
6904 | if (NewTemplate) | ||||
6905 | NewTemplate->setModulePrivate(); | ||||
6906 | for (auto *B : Bindings) | ||||
6907 | B->setModulePrivate(); | ||||
6908 | } | ||||
6909 | } | ||||
6910 | |||||
6911 | // Handle attributes prior to checking for duplicates in MergeVarDecl | ||||
6912 | ProcessDeclAttributes(S, NewVD, D); | ||||
6913 | |||||
6914 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { | ||||
6915 | if (EmitTLSUnsupportedError && | ||||
6916 | ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || | ||||
6917 | (getLangOpts().OpenMPIsDevice && | ||||
6918 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) | ||||
6919 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
6920 | diag::err_thread_unsupported); | ||||
6921 | // CUDA B.2.5: "__shared__ and __constant__ variables have implied static | ||||
6922 | // storage [duration]." | ||||
6923 | if (SC == SC_None && S->getFnParent() != nullptr && | ||||
6924 | (NewVD->hasAttr<CUDASharedAttr>() || | ||||
6925 | NewVD->hasAttr<CUDAConstantAttr>())) { | ||||
6926 | NewVD->setStorageClass(SC_Static); | ||||
6927 | } | ||||
6928 | } | ||||
6929 | |||||
6930 | // Ensure that dllimport globals without explicit storage class are treated as | ||||
6931 | // extern. The storage class is set above using parsed attributes. Now we can | ||||
6932 | // check the VarDecl itself. | ||||
6933 | assert(!NewVD->hasAttr<DLLImportAttr>() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6935, __PRETTY_FUNCTION__)) | ||||
6934 | NewVD->getAttr<DLLImportAttr>()->isInherited() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6935, __PRETTY_FUNCTION__)) | ||||
6935 | NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 6935, __PRETTY_FUNCTION__)); | ||||
6936 | |||||
6937 | // In auto-retain/release, infer strong retension for variables of | ||||
6938 | // retainable type. | ||||
6939 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) | ||||
6940 | NewVD->setInvalidDecl(); | ||||
6941 | |||||
6942 | // Handle GNU asm-label extension (encoded as an attribute). | ||||
6943 | if (Expr *E = (Expr*)D.getAsmLabel()) { | ||||
6944 | // The parser guarantees this is a string. | ||||
6945 | StringLiteral *SE = cast<StringLiteral>(E); | ||||
6946 | StringRef Label = SE->getString(); | ||||
6947 | if (S->getFnParent() != nullptr) { | ||||
6948 | switch (SC) { | ||||
6949 | case SC_None: | ||||
6950 | case SC_Auto: | ||||
6951 | Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; | ||||
6952 | break; | ||||
6953 | case SC_Register: | ||||
6954 | // Local Named register | ||||
6955 | if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && | ||||
6956 | DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) | ||||
6957 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | ||||
6958 | break; | ||||
6959 | case SC_Static: | ||||
6960 | case SC_Extern: | ||||
6961 | case SC_PrivateExtern: | ||||
6962 | break; | ||||
6963 | } | ||||
6964 | } else if (SC == SC_Register) { | ||||
6965 | // Global Named register | ||||
6966 | if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { | ||||
6967 | const auto &TI = Context.getTargetInfo(); | ||||
6968 | bool HasSizeMismatch; | ||||
6969 | |||||
6970 | if (!TI.isValidGCCRegisterName(Label)) | ||||
6971 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | ||||
6972 | else if (!TI.validateGlobalRegisterVariable(Label, | ||||
6973 | Context.getTypeSize(R), | ||||
6974 | HasSizeMismatch)) | ||||
6975 | Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; | ||||
6976 | else if (HasSizeMismatch) | ||||
6977 | Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; | ||||
6978 | } | ||||
6979 | |||||
6980 | if (!R->isIntegralType(Context) && !R->isPointerType()) { | ||||
6981 | Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); | ||||
6982 | NewVD->setInvalidDecl(true); | ||||
6983 | } | ||||
6984 | } | ||||
6985 | |||||
6986 | NewVD->addAttr(::new (Context) AsmLabelAttr( | ||||
6987 | Context, SE->getStrTokenLoc(0), Label, /*IsLiteralLabel=*/true)); | ||||
6988 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | ||||
6989 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | ||||
6990 | ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); | ||||
6991 | if (I != ExtnameUndeclaredIdentifiers.end()) { | ||||
6992 | if (isDeclExternC(NewVD)) { | ||||
6993 | NewVD->addAttr(I->second); | ||||
6994 | ExtnameUndeclaredIdentifiers.erase(I); | ||||
6995 | } else | ||||
6996 | Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) | ||||
6997 | << /*Variable*/1 << NewVD; | ||||
6998 | } | ||||
6999 | } | ||||
7000 | |||||
7001 | // Find the shadowed declaration before filtering for scope. | ||||
7002 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() | ||||
7003 | ? getShadowedDeclaration(NewVD, Previous) | ||||
7004 | : nullptr; | ||||
7005 | |||||
7006 | // Don't consider existing declarations that are in a different | ||||
7007 | // scope and are out-of-semantic-context declarations (if the new | ||||
7008 | // declaration has linkage). | ||||
7009 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), | ||||
7010 | D.getCXXScopeSpec().isNotEmpty() || | ||||
7011 | IsMemberSpecialization || | ||||
7012 | IsVariableTemplateSpecialization); | ||||
7013 | |||||
7014 | // Check whether the previous declaration is in the same block scope. This | ||||
7015 | // affects whether we merge types with it, per C++11 [dcl.array]p3. | ||||
7016 | if (getLangOpts().CPlusPlus && | ||||
7017 | NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) | ||||
7018 | NewVD->setPreviousDeclInSameBlockScope( | ||||
7019 | Previous.isSingleResult() && !Previous.isShadowed() && | ||||
7020 | isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); | ||||
7021 | |||||
7022 | if (!getLangOpts().CPlusPlus) { | ||||
7023 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | ||||
7024 | } else { | ||||
7025 | // If this is an explicit specialization of a static data member, check it. | ||||
7026 | if (IsMemberSpecialization && !NewVD->isInvalidDecl() && | ||||
7027 | CheckMemberSpecialization(NewVD, Previous)) | ||||
7028 | NewVD->setInvalidDecl(); | ||||
7029 | |||||
7030 | // Merge the decl with the existing one if appropriate. | ||||
7031 | if (!Previous.empty()) { | ||||
7032 | if (Previous.isSingleResult() && | ||||
7033 | isa<FieldDecl>(Previous.getFoundDecl()) && | ||||
7034 | D.getCXXScopeSpec().isSet()) { | ||||
7035 | // The user tried to define a non-static data member | ||||
7036 | // out-of-line (C++ [dcl.meaning]p1). | ||||
7037 | Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) | ||||
7038 | << D.getCXXScopeSpec().getRange(); | ||||
7039 | Previous.clear(); | ||||
7040 | NewVD->setInvalidDecl(); | ||||
7041 | } | ||||
7042 | } else if (D.getCXXScopeSpec().isSet()) { | ||||
7043 | // No previous declaration in the qualifying scope. | ||||
7044 | Diag(D.getIdentifierLoc(), diag::err_no_member) | ||||
7045 | << Name << computeDeclContext(D.getCXXScopeSpec(), true) | ||||
7046 | << D.getCXXScopeSpec().getRange(); | ||||
7047 | NewVD->setInvalidDecl(); | ||||
7048 | } | ||||
7049 | |||||
7050 | if (!IsVariableTemplateSpecialization) | ||||
7051 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | ||||
7052 | |||||
7053 | if (NewTemplate) { | ||||
7054 | VarTemplateDecl *PrevVarTemplate = | ||||
7055 | NewVD->getPreviousDecl() | ||||
7056 | ? NewVD->getPreviousDecl()->getDescribedVarTemplate() | ||||
7057 | : nullptr; | ||||
7058 | |||||
7059 | // Check the template parameter list of this declaration, possibly | ||||
7060 | // merging in the template parameter list from the previous variable | ||||
7061 | // template declaration. | ||||
7062 | if (CheckTemplateParameterList( | ||||
7063 | TemplateParams, | ||||
7064 | PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() | ||||
7065 | : nullptr, | ||||
7066 | (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && | ||||
7067 | DC->isDependentContext()) | ||||
7068 | ? TPC_ClassTemplateMember | ||||
7069 | : TPC_VarTemplate)) | ||||
7070 | NewVD->setInvalidDecl(); | ||||
7071 | |||||
7072 | // If we are providing an explicit specialization of a static variable | ||||
7073 | // template, make a note of that. | ||||
7074 | if (PrevVarTemplate && | ||||
7075 | PrevVarTemplate->getInstantiatedFromMemberTemplate()) | ||||
7076 | PrevVarTemplate->setMemberSpecialization(); | ||||
7077 | } | ||||
7078 | } | ||||
7079 | |||||
7080 | // Diagnose shadowed variables iff this isn't a redeclaration. | ||||
7081 | if (ShadowedDecl && !D.isRedeclaration()) | ||||
7082 | CheckShadow(NewVD, ShadowedDecl, Previous); | ||||
7083 | |||||
7084 | ProcessPragmaWeak(S, NewVD); | ||||
7085 | |||||
7086 | // If this is the first declaration of an extern C variable, update | ||||
7087 | // the map of such variables. | ||||
7088 | if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && | ||||
7089 | isIncompleteDeclExternC(*this, NewVD)) | ||||
7090 | RegisterLocallyScopedExternCDecl(NewVD, S); | ||||
7091 | |||||
7092 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | ||||
7093 | Decl *ManglingContextDecl; | ||||
7094 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( | ||||
7095 | NewVD->getDeclContext(), ManglingContextDecl)) { | ||||
7096 | Context.setManglingNumber( | ||||
7097 | NewVD, MCtx->getManglingNumber( | ||||
7098 | NewVD, getMSManglingNumber(getLangOpts(), S))); | ||||
7099 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | ||||
7100 | } | ||||
7101 | } | ||||
7102 | |||||
7103 | // Special handling of variable named 'main'. | ||||
7104 | if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && | ||||
7105 | NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && | ||||
7106 | !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { | ||||
7107 | |||||
7108 | // C++ [basic.start.main]p3 | ||||
7109 | // A program that declares a variable main at global scope is ill-formed. | ||||
7110 | if (getLangOpts().CPlusPlus) | ||||
7111 | Diag(D.getBeginLoc(), diag::err_main_global_variable); | ||||
7112 | |||||
7113 | // In C, and external-linkage variable named main results in undefined | ||||
7114 | // behavior. | ||||
7115 | else if (NewVD->hasExternalFormalLinkage()) | ||||
7116 | Diag(D.getBeginLoc(), diag::warn_main_redefined); | ||||
7117 | } | ||||
7118 | |||||
7119 | if (D.isRedeclaration() && !Previous.empty()) { | ||||
7120 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | ||||
7121 | checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, | ||||
7122 | D.isFunctionDefinition()); | ||||
7123 | } | ||||
7124 | |||||
7125 | if (NewTemplate) { | ||||
7126 | if (NewVD->isInvalidDecl()) | ||||
7127 | NewTemplate->setInvalidDecl(); | ||||
7128 | ActOnDocumentableDecl(NewTemplate); | ||||
7129 | return NewTemplate; | ||||
7130 | } | ||||
7131 | |||||
7132 | if (IsMemberSpecialization && !NewVD->isInvalidDecl()) | ||||
7133 | CompleteMemberSpecialization(NewVD, Previous); | ||||
7134 | |||||
7135 | return NewVD; | ||||
7136 | } | ||||
7137 | |||||
7138 | /// Enum describing the %select options in diag::warn_decl_shadow. | ||||
7139 | enum ShadowedDeclKind { | ||||
7140 | SDK_Local, | ||||
7141 | SDK_Global, | ||||
7142 | SDK_StaticMember, | ||||
7143 | SDK_Field, | ||||
7144 | SDK_Typedef, | ||||
7145 | SDK_Using | ||||
7146 | }; | ||||
7147 | |||||
7148 | /// Determine what kind of declaration we're shadowing. | ||||
7149 | static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, | ||||
7150 | const DeclContext *OldDC) { | ||||
7151 | if (isa<TypeAliasDecl>(ShadowedDecl)) | ||||
7152 | return SDK_Using; | ||||
7153 | else if (isa<TypedefDecl>(ShadowedDecl)) | ||||
7154 | return SDK_Typedef; | ||||
7155 | else if (isa<RecordDecl>(OldDC)) | ||||
7156 | return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; | ||||
7157 | |||||
7158 | return OldDC->isFileContext() ? SDK_Global : SDK_Local; | ||||
7159 | } | ||||
7160 | |||||
7161 | /// Return the location of the capture if the given lambda captures the given | ||||
7162 | /// variable \p VD, or an invalid source location otherwise. | ||||
7163 | static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, | ||||
7164 | const VarDecl *VD) { | ||||
7165 | for (const Capture &Capture : LSI->Captures) { | ||||
7166 | if (Capture.isVariableCapture() && Capture.getVariable() == VD) | ||||
7167 | return Capture.getLocation(); | ||||
7168 | } | ||||
7169 | return SourceLocation(); | ||||
7170 | } | ||||
7171 | |||||
7172 | static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, | ||||
7173 | const LookupResult &R) { | ||||
7174 | // Only diagnose if we're shadowing an unambiguous field or variable. | ||||
7175 | if (R.getResultKind() != LookupResult::Found) | ||||
7176 | return false; | ||||
7177 | |||||
7178 | // Return false if warning is ignored. | ||||
7179 | return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); | ||||
7180 | } | ||||
7181 | |||||
7182 | /// Return the declaration shadowed by the given variable \p D, or null | ||||
7183 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||
7184 | NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, | ||||
7185 | const LookupResult &R) { | ||||
7186 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||
7187 | return nullptr; | ||||
7188 | |||||
7189 | // Don't diagnose declarations at file scope. | ||||
7190 | if (D->hasGlobalStorage()) | ||||
7191 | return nullptr; | ||||
7192 | |||||
7193 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||
7194 | return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) | ||||
7195 | ? ShadowedDecl | ||||
7196 | : nullptr; | ||||
7197 | } | ||||
7198 | |||||
7199 | /// Return the declaration shadowed by the given typedef \p D, or null | ||||
7200 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||
7201 | NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, | ||||
7202 | const LookupResult &R) { | ||||
7203 | // Don't warn if typedef declaration is part of a class | ||||
7204 | if (D->getDeclContext()->isRecord()) | ||||
7205 | return nullptr; | ||||
7206 | |||||
7207 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||
7208 | return nullptr; | ||||
7209 | |||||
7210 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||
7211 | return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; | ||||
7212 | } | ||||
7213 | |||||
7214 | /// Diagnose variable or built-in function shadowing. Implements | ||||
7215 | /// -Wshadow. | ||||
7216 | /// | ||||
7217 | /// This method is called whenever a VarDecl is added to a "useful" | ||||
7218 | /// scope. | ||||
7219 | /// | ||||
7220 | /// \param ShadowedDecl the declaration that is shadowed by the given variable | ||||
7221 | /// \param R the lookup of the name | ||||
7222 | /// | ||||
7223 | void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, | ||||
7224 | const LookupResult &R) { | ||||
7225 | DeclContext *NewDC = D->getDeclContext(); | ||||
7226 | |||||
7227 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { | ||||
7228 | // Fields are not shadowed by variables in C++ static methods. | ||||
7229 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) | ||||
7230 | if (MD->isStatic()) | ||||
7231 | return; | ||||
7232 | |||||
7233 | // Fields shadowed by constructor parameters are a special case. Usually | ||||
7234 | // the constructor initializes the field with the parameter. | ||||
7235 | if (isa<CXXConstructorDecl>(NewDC)) | ||||
7236 | if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { | ||||
7237 | // Remember that this was shadowed so we can either warn about its | ||||
7238 | // modification or its existence depending on warning settings. | ||||
7239 | ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); | ||||
7240 | return; | ||||
7241 | } | ||||
7242 | } | ||||
7243 | |||||
7244 | if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) | ||||
7245 | if (shadowedVar->isExternC()) { | ||||
7246 | // For shadowing external vars, make sure that we point to the global | ||||
7247 | // declaration, not a locally scoped extern declaration. | ||||
7248 | for (auto I : shadowedVar->redecls()) | ||||
7249 | if (I->isFileVarDecl()) { | ||||
7250 | ShadowedDecl = I; | ||||
7251 | break; | ||||
7252 | } | ||||
7253 | } | ||||
7254 | |||||
7255 | DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); | ||||
7256 | |||||
7257 | unsigned WarningDiag = diag::warn_decl_shadow; | ||||
7258 | SourceLocation CaptureLoc; | ||||
7259 | if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && | ||||
7260 | isa<CXXMethodDecl>(NewDC)) { | ||||
7261 | if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { | ||||
7262 | if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { | ||||
7263 | if (RD->getLambdaCaptureDefault() == LCD_None) { | ||||
7264 | // Try to avoid warnings for lambdas with an explicit capture list. | ||||
7265 | const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); | ||||
7266 | // Warn only when the lambda captures the shadowed decl explicitly. | ||||
7267 | CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); | ||||
7268 | if (CaptureLoc.isInvalid()) | ||||
7269 | WarningDiag = diag::warn_decl_shadow_uncaptured_local; | ||||
7270 | } else { | ||||
7271 | // Remember that this was shadowed so we can avoid the warning if the | ||||
7272 | // shadowed decl isn't captured and the warning settings allow it. | ||||
7273 | cast<LambdaScopeInfo>(getCurFunction()) | ||||
7274 | ->ShadowingDecls.push_back( | ||||
7275 | {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); | ||||
7276 | return; | ||||
7277 | } | ||||
7278 | } | ||||
7279 | |||||
7280 | if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { | ||||
7281 | // A variable can't shadow a local variable in an enclosing scope, if | ||||
7282 | // they are separated by a non-capturing declaration context. | ||||
7283 | for (DeclContext *ParentDC = NewDC; | ||||
7284 | ParentDC && !ParentDC->Equals(OldDC); | ||||
7285 | ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { | ||||
7286 | // Only block literals, captured statements, and lambda expressions | ||||
7287 | // can capture; other scopes don't. | ||||
7288 | if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && | ||||
7289 | !isLambdaCallOperator(ParentDC)) { | ||||
7290 | return; | ||||
7291 | } | ||||
7292 | } | ||||
7293 | } | ||||
7294 | } | ||||
7295 | } | ||||
7296 | |||||
7297 | // Only warn about certain kinds of shadowing for class members. | ||||
7298 | if (NewDC && NewDC->isRecord()) { | ||||
7299 | // In particular, don't warn about shadowing non-class members. | ||||
7300 | if (!OldDC->isRecord()) | ||||
7301 | return; | ||||
7302 | |||||
7303 | // TODO: should we warn about static data members shadowing | ||||
7304 | // static data members from base classes? | ||||
7305 | |||||
7306 | // TODO: don't diagnose for inaccessible shadowed members. | ||||
7307 | // This is hard to do perfectly because we might friend the | ||||
7308 | // shadowing context, but that's just a false negative. | ||||
7309 | } | ||||
7310 | |||||
7311 | |||||
7312 | DeclarationName Name = R.getLookupName(); | ||||
7313 | |||||
7314 | // Emit warning and note. | ||||
7315 | if (getSourceManager().isInSystemMacro(R.getNameLoc())) | ||||
7316 | return; | ||||
7317 | ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); | ||||
7318 | Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; | ||||
7319 | if (!CaptureLoc.isInvalid()) | ||||
7320 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | ||||
7321 | << Name << /*explicitly*/ 1; | ||||
7322 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||
7323 | } | ||||
7324 | |||||
7325 | /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD | ||||
7326 | /// when these variables are captured by the lambda. | ||||
7327 | void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { | ||||
7328 | for (const auto &Shadow : LSI->ShadowingDecls) { | ||||
7329 | const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; | ||||
7330 | // Try to avoid the warning when the shadowed decl isn't captured. | ||||
7331 | SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); | ||||
7332 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | ||||
7333 | Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() | ||||
7334 | ? diag::warn_decl_shadow_uncaptured_local | ||||
7335 | : diag::warn_decl_shadow) | ||||
7336 | << Shadow.VD->getDeclName() | ||||
7337 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; | ||||
7338 | if (!CaptureLoc.isInvalid()) | ||||
7339 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | ||||
7340 | << Shadow.VD->getDeclName() << /*explicitly*/ 0; | ||||
7341 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||
7342 | } | ||||
7343 | } | ||||
7344 | |||||
7345 | /// Check -Wshadow without the advantage of a previous lookup. | ||||
7346 | void Sema::CheckShadow(Scope *S, VarDecl *D) { | ||||
7347 | if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) | ||||
7348 | return; | ||||
7349 | |||||
7350 | LookupResult R(*this, D->getDeclName(), D->getLocation(), | ||||
7351 | Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); | ||||
7352 | LookupName(R, S); | ||||
7353 | if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) | ||||
7354 | CheckShadow(D, ShadowedDecl, R); | ||||
7355 | } | ||||
7356 | |||||
7357 | /// Check if 'E', which is an expression that is about to be modified, refers | ||||
7358 | /// to a constructor parameter that shadows a field. | ||||
7359 | void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { | ||||
7360 | // Quickly ignore expressions that can't be shadowing ctor parameters. | ||||
7361 | if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) | ||||
7362 | return; | ||||
7363 | E = E->IgnoreParenImpCasts(); | ||||
7364 | auto *DRE = dyn_cast<DeclRefExpr>(E); | ||||
7365 | if (!DRE) | ||||
7366 | return; | ||||
7367 | const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); | ||||
7368 | auto I = ShadowingDecls.find(D); | ||||
7369 | if (I == ShadowingDecls.end()) | ||||
7370 | return; | ||||
7371 | const NamedDecl *ShadowedDecl = I->second; | ||||
7372 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | ||||
7373 | Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; | ||||
7374 | Diag(D->getLocation(), diag::note_var_declared_here) << D; | ||||
7375 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||
7376 | |||||
7377 | // Avoid issuing multiple warnings about the same decl. | ||||
7378 | ShadowingDecls.erase(I); | ||||
7379 | } | ||||
7380 | |||||
7381 | /// Check for conflict between this global or extern "C" declaration and | ||||
7382 | /// previous global or extern "C" declarations. This is only used in C++. | ||||
7383 | template<typename T> | ||||
7384 | static bool checkGlobalOrExternCConflict( | ||||
7385 | Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { | ||||
7386 | assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"" ) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 7386, __PRETTY_FUNCTION__)); | ||||
7387 | NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); | ||||
7388 | |||||
7389 | if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { | ||||
7390 | // The common case: this global doesn't conflict with any extern "C" | ||||
7391 | // declaration. | ||||
7392 | return false; | ||||
7393 | } | ||||
7394 | |||||
7395 | if (Prev) { | ||||
7396 | if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { | ||||
7397 | // Both the old and new declarations have C language linkage. This is a | ||||
7398 | // redeclaration. | ||||
7399 | Previous.clear(); | ||||
7400 | Previous.addDecl(Prev); | ||||
7401 | return true; | ||||
7402 | } | ||||
7403 | |||||
7404 | // This is a global, non-extern "C" declaration, and there is a previous | ||||
7405 | // non-global extern "C" declaration. Diagnose if this is a variable | ||||
7406 | // declaration. | ||||
7407 | if (!isa<VarDecl>(ND)) | ||||
7408 | return false; | ||||
7409 | } else { | ||||
7410 | // The declaration is extern "C". Check for any declaration in the | ||||
7411 | // translation unit which might conflict. | ||||
7412 | if (IsGlobal) { | ||||
7413 | // We have already performed the lookup into the translation unit. | ||||
7414 | IsGlobal = false; | ||||
7415 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||
7416 | I != E; ++I) { | ||||
7417 | if (isa<VarDecl>(*I)) { | ||||
7418 | Prev = *I; | ||||
7419 | break; | ||||
7420 | } | ||||
7421 | } | ||||
7422 | } else { | ||||
7423 | DeclContext::lookup_result R = | ||||
7424 | S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); | ||||
7425 | for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); | ||||
7426 | I != E; ++I) { | ||||
7427 | if (isa<VarDecl>(*I)) { | ||||
7428 | Prev = *I; | ||||
7429 | break; | ||||
7430 | } | ||||
7431 | // FIXME: If we have any other entity with this name in global scope, | ||||
7432 | // the declaration is ill-formed, but that is a defect: it breaks the | ||||
7433 | // 'stat' hack, for instance. Only variables can have mangled name | ||||
7434 | // clashes with extern "C" declarations, so only they deserve a | ||||
7435 | // diagnostic. | ||||
7436 | } | ||||
7437 | } | ||||
7438 | |||||
7439 | if (!Prev) | ||||
7440 | return false; | ||||
7441 | } | ||||
7442 | |||||
7443 | // Use the first declaration's location to ensure we point at something which | ||||
7444 | // is lexically inside an extern "C" linkage-spec. | ||||
7445 | assert(Prev && "should have found a previous declaration to diagnose")((Prev && "should have found a previous declaration to diagnose" ) ? static_cast<void> (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 7445, __PRETTY_FUNCTION__)); | ||||
7446 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) | ||||
7447 | Prev = FD->getFirstDecl(); | ||||
7448 | else | ||||
7449 | Prev = cast<VarDecl>(Prev)->getFirstDecl(); | ||||
7450 | |||||
7451 | S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) | ||||
7452 | << IsGlobal << ND; | ||||
7453 | S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) | ||||
7454 | << IsGlobal; | ||||
7455 | return false; | ||||
7456 | } | ||||
7457 | |||||
7458 | /// Apply special rules for handling extern "C" declarations. Returns \c true | ||||
7459 | /// if we have found that this is a redeclaration of some prior entity. | ||||
7460 | /// | ||||
7461 | /// Per C++ [dcl.link]p6: | ||||
7462 | /// Two declarations [for a function or variable] with C language linkage | ||||
7463 | /// with the same name that appear in different scopes refer to the same | ||||
7464 | /// [entity]. An entity with C language linkage shall not be declared with | ||||
7465 | /// the same name as an entity in global scope. | ||||
7466 | template<typename T> | ||||
7467 | static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, | ||||
7468 | LookupResult &Previous) { | ||||
7469 | if (!S.getLangOpts().CPlusPlus) { | ||||
7470 | // In C, when declaring a global variable, look for a corresponding 'extern' | ||||
7471 | // variable declared in function scope. We don't need this in C++, because | ||||
7472 | // we find local extern decls in the surrounding file-scope DeclContext. | ||||
7473 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||
7474 | if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { | ||||
7475 | Previous.clear(); | ||||
7476 | Previous.addDecl(Prev); | ||||
7477 | return true; | ||||
7478 | } | ||||
7479 | } | ||||
7480 | return false; | ||||
7481 | } | ||||
7482 | |||||
7483 | // A declaration in the translation unit can conflict with an extern "C" | ||||
7484 | // declaration. | ||||
7485 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) | ||||
7486 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); | ||||
7487 | |||||
7488 | // An extern "C" declaration can conflict with a declaration in the | ||||
7489 | // translation unit or can be a redeclaration of an extern "C" declaration | ||||
7490 | // in another scope. | ||||
7491 | if (isIncompleteDeclExternC(S,ND)) | ||||
7492 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); | ||||
7493 | |||||
7494 | // Neither global nor extern "C": nothing to do. | ||||
7495 | return false; | ||||
7496 | } | ||||
7497 | |||||
7498 | void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { | ||||
7499 | // If the decl is already known invalid, don't check it. | ||||
7500 | if (NewVD->isInvalidDecl()) | ||||
7501 | return; | ||||
7502 | |||||
7503 | QualType T = NewVD->getType(); | ||||
7504 | |||||
7505 | // Defer checking an 'auto' type until its initializer is attached. | ||||
7506 | if (T->isUndeducedType()) | ||||
7507 | return; | ||||
7508 | |||||
7509 | if (NewVD->hasAttrs()) | ||||
7510 | CheckAlignasUnderalignment(NewVD); | ||||
7511 | |||||
7512 | if (T->isObjCObjectType()) { | ||||
7513 | Diag(NewVD->getLocation(), diag::err_statically_allocated_object) | ||||
7514 | << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); | ||||
7515 | T = Context.getObjCObjectPointerType(T); | ||||
7516 | NewVD->setType(T); | ||||
7517 | } | ||||
7518 | |||||
7519 | // Emit an error if an address space was applied to decl with local storage. | ||||
7520 | // This includes arrays of objects with address space qualifiers, but not | ||||
7521 | // automatic variables that point to other address spaces. | ||||
7522 | // ISO/IEC TR 18037 S5.1.2 | ||||
7523 | if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && | ||||
7524 | T.getAddressSpace() != LangAS::Default) { | ||||
7525 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; | ||||
7526 | NewVD->setInvalidDecl(); | ||||
7527 | return; | ||||
7528 | } | ||||
7529 | |||||
7530 | // OpenCL v1.2 s6.8 - The static qualifier is valid only in program | ||||
7531 | // scope. | ||||
7532 | if (getLangOpts().OpenCLVersion == 120 && | ||||
7533 | !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && | ||||
7534 | NewVD->isStaticLocal()) { | ||||
7535 | Diag(NewVD->getLocation(), diag::err_static_function_scope); | ||||
7536 | NewVD->setInvalidDecl(); | ||||
7537 | return; | ||||
7538 | } | ||||
7539 | |||||
7540 | if (getLangOpts().OpenCL) { | ||||
7541 | // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. | ||||
7542 | if (NewVD->hasAttr<BlocksAttr>()) { | ||||
7543 | Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); | ||||
7544 | return; | ||||
7545 | } | ||||
7546 | |||||
7547 | if (T->isBlockPointerType()) { | ||||
7548 | // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and | ||||
7549 | // can't use 'extern' storage class. | ||||
7550 | if (!T.isConstQualified()) { | ||||
7551 | Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) | ||||
7552 | << 0 /*const*/; | ||||
7553 | NewVD->setInvalidDecl(); | ||||
7554 | return; | ||||
7555 | } | ||||
7556 | if (NewVD->hasExternalStorage()) { | ||||
7557 | Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); | ||||
7558 | NewVD->setInvalidDecl(); | ||||
7559 | return; | ||||
7560 | } | ||||
7561 | } | ||||
7562 | // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the | ||||
7563 | // __constant address space. | ||||
7564 | // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static | ||||
7565 | // variables inside a function can also be declared in the global | ||||
7566 | // address space. | ||||
7567 | // C++ for OpenCL inherits rule from OpenCL C v2.0. | ||||
7568 | // FIXME: Adding local AS in C++ for OpenCL might make sense. | ||||
7569 | if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || | ||||
7570 | NewVD->hasExternalStorage()) { | ||||
7571 | if (!T->isSamplerT() && | ||||
7572 | !(T.getAddressSpace() == LangAS::opencl_constant || | ||||
7573 | (T.getAddressSpace() == LangAS::opencl_global && | ||||
7574 | (getLangOpts().OpenCLVersion == 200 || | ||||
7575 | getLangOpts().OpenCLCPlusPlus)))) { | ||||
7576 | int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; | ||||
7577 | if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) | ||||
7578 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | ||||
7579 | << Scope << "global or constant"; | ||||
7580 | else | ||||
7581 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | ||||
7582 | << Scope << "constant"; | ||||
7583 | NewVD->setInvalidDecl(); | ||||
7584 | return; | ||||
7585 | } | ||||
7586 | } else { | ||||
7587 | if (T.getAddressSpace() == LangAS::opencl_global) { | ||||
7588 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||
7589 | << 1 /*is any function*/ << "global"; | ||||
7590 | NewVD->setInvalidDecl(); | ||||
7591 | return; | ||||
7592 | } | ||||
7593 | if (T.getAddressSpace() == LangAS::opencl_constant || | ||||
7594 | T.getAddressSpace() == LangAS::opencl_local) { | ||||
7595 | FunctionDecl *FD = getCurFunctionDecl(); | ||||
7596 | // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables | ||||
7597 | // in functions. | ||||
7598 | if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { | ||||
7599 | if (T.getAddressSpace() == LangAS::opencl_constant) | ||||
7600 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||
7601 | << 0 /*non-kernel only*/ << "constant"; | ||||
7602 | else | ||||
7603 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||
7604 | << 0 /*non-kernel only*/ << "local"; | ||||
7605 | NewVD->setInvalidDecl(); | ||||
7606 | return; | ||||
7607 | } | ||||
7608 | // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be | ||||
7609 | // in the outermost scope of a kernel function. | ||||
7610 | if (FD && FD->hasAttr<OpenCLKernelAttr>()) { | ||||
7611 | if (!getCurScope()->isFunctionScope()) { | ||||
7612 | if (T.getAddressSpace() == LangAS::opencl_constant) | ||||
7613 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | ||||
7614 | << "constant"; | ||||
7615 | else | ||||
7616 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | ||||
7617 | << "local"; | ||||
7618 | NewVD->setInvalidDecl(); | ||||
7619 | return; | ||||
7620 | } | ||||
7621 | } | ||||
7622 | } else if (T.getAddressSpace() != LangAS::opencl_private && | ||||
7623 | // If we are parsing a template we didn't deduce an addr | ||||
7624 | // space yet. | ||||
7625 | T.getAddressSpace() != LangAS::Default) { | ||||
7626 | // Do not allow other address spaces on automatic variable. | ||||
7627 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; | ||||
7628 | NewVD->setInvalidDecl(); | ||||
7629 | return; | ||||
7630 | } | ||||
7631 | } | ||||
7632 | } | ||||
7633 | |||||
7634 | if (NewVD->hasLocalStorage() && T.isObjCGCWeak() | ||||
7635 | && !NewVD->hasAttr<BlocksAttr>()) { | ||||
7636 | if (getLangOpts().getGC() != LangOptions::NonGC) | ||||
7637 | Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); | ||||
7638 | else { | ||||
7639 | assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> ( 0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 7639, __PRETTY_FUNCTION__)); | ||||
7640 | Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); | ||||
7641 | } | ||||
7642 | } | ||||
7643 | |||||
7644 | bool isVM = T->isVariablyModifiedType(); | ||||
7645 | if (isVM || NewVD->hasAttr<CleanupAttr>() || | ||||
7646 | NewVD->hasAttr<BlocksAttr>()) | ||||
7647 | setFunctionHasBranchProtectedScope(); | ||||
7648 | |||||
7649 | if ((isVM && NewVD->hasLinkage()) || | ||||
7650 | (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { | ||||
7651 | bool SizeIsNegative; | ||||
7652 | llvm::APSInt Oversized; | ||||
7653 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( | ||||
7654 | NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); | ||||
7655 | QualType FixedT; | ||||
7656 | if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) | ||||
7657 | FixedT = FixedTInfo->getType(); | ||||
7658 | else if (FixedTInfo) { | ||||
7659 | // Type and type-as-written are canonically different. We need to fix up | ||||
7660 | // both types separately. | ||||
7661 | FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, | ||||
7662 | Oversized); | ||||
7663 | } | ||||
7664 | if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { | ||||
7665 | const VariableArrayType *VAT = Context.getAsVariableArrayType(T); | ||||
7666 | // FIXME: This won't give the correct result for | ||||
7667 | // int a[10][n]; | ||||
7668 | SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); | ||||
7669 | |||||
7670 | if (NewVD->isFileVarDecl()) | ||||
7671 | Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) | ||||
7672 | << SizeRange; | ||||
7673 | else if (NewVD->isStaticLocal()) | ||||
7674 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) | ||||
7675 | << SizeRange; | ||||
7676 | else | ||||
7677 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) | ||||
7678 | << SizeRange; | ||||
7679 | NewVD->setInvalidDecl(); | ||||
7680 | return; | ||||
7681 | } | ||||
7682 | |||||
7683 | if (!FixedTInfo) { | ||||
7684 | if (NewVD->isFileVarDecl()) | ||||
7685 | Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); | ||||
7686 | else | ||||
7687 | Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); | ||||
7688 | NewVD->setInvalidDecl(); | ||||
7689 | return; | ||||
7690 | } | ||||
7691 | |||||
7692 | Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); | ||||
7693 | NewVD->setType(FixedT); | ||||
7694 | NewVD->setTypeSourceInfo(FixedTInfo); | ||||
7695 | } | ||||
7696 | |||||
7697 | if (T->isVoidType()) { | ||||
7698 | // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names | ||||
7699 | // of objects and functions. | ||||
7700 | if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { | ||||
7701 | Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) | ||||
7702 | << T; | ||||
7703 | NewVD->setInvalidDecl(); | ||||
7704 | return; | ||||
7705 | } | ||||
7706 | } | ||||
7707 | |||||
7708 | if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { | ||||
7709 | Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); | ||||
7710 | NewVD->setInvalidDecl(); | ||||
7711 | return; | ||||
7712 | } | ||||
7713 | |||||
7714 | if (isVM && NewVD->hasAttr<BlocksAttr>()) { | ||||
7715 | Diag(NewVD->getLocation(), diag::err_block_on_vm); | ||||
7716 | NewVD->setInvalidDecl(); | ||||
7717 | return; | ||||
7718 | } | ||||
7719 | |||||
7720 | if (NewVD->isConstexpr() && !T->isDependentType() && | ||||
7721 | RequireLiteralType(NewVD->getLocation(), T, | ||||
7722 | diag::err_constexpr_var_non_literal)) { | ||||
7723 | NewVD->setInvalidDecl(); | ||||
7724 | return; | ||||
7725 | } | ||||
7726 | } | ||||
7727 | |||||
7728 | /// Perform semantic checking on a newly-created variable | ||||
7729 | /// declaration. | ||||
7730 | /// | ||||
7731 | /// This routine performs all of the type-checking required for a | ||||
7732 | /// variable declaration once it has been built. It is used both to | ||||
7733 | /// check variables after they have been parsed and their declarators | ||||
7734 | /// have been translated into a declaration, and to check variables | ||||
7735 | /// that have been instantiated from a template. | ||||
7736 | /// | ||||
7737 | /// Sets NewVD->isInvalidDecl() if an error was encountered. | ||||
7738 | /// | ||||
7739 | /// Returns true if the variable declaration is a redeclaration. | ||||
7740 | bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { | ||||
7741 | CheckVariableDeclarationType(NewVD); | ||||
7742 | |||||
7743 | // If the decl is already known invalid, don't check it. | ||||
7744 | if (NewVD->isInvalidDecl()) | ||||
7745 | return false; | ||||
7746 | |||||
7747 | // If we did not find anything by this name, look for a non-visible | ||||
7748 | // extern "C" declaration with the same name. | ||||
7749 | if (Previous.empty() && | ||||
7750 | checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) | ||||
7751 | Previous.setShadowed(); | ||||
7752 | |||||
7753 | if (!Previous.empty()) { | ||||
7754 | MergeVarDecl(NewVD, Previous); | ||||
7755 | return true; | ||||
7756 | } | ||||
7757 | return false; | ||||
7758 | } | ||||
7759 | |||||
7760 | namespace { | ||||
7761 | struct FindOverriddenMethod { | ||||
7762 | Sema *S; | ||||
7763 | CXXMethodDecl *Method; | ||||
7764 | |||||
7765 | /// Member lookup function that determines whether a given C++ | ||||
7766 | /// method overrides a method in a base class, to be used with | ||||
7767 | /// CXXRecordDecl::lookupInBases(). | ||||
7768 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | ||||
7769 | RecordDecl *BaseRecord = | ||||
7770 | Specifier->getType()->getAs<RecordType>()->getDecl(); | ||||
7771 | |||||
7772 | DeclarationName Name = Method->getDeclName(); | ||||
7773 | |||||
7774 | // FIXME: Do we care about other names here too? | ||||
7775 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||
7776 | // We really want to find the base class destructor here. | ||||
7777 | QualType T = S->Context.getTypeDeclType(BaseRecord); | ||||
7778 | CanQualType CT = S->Context.getCanonicalType(T); | ||||
7779 | |||||
7780 | Name = S->Context.DeclarationNames.getCXXDestructorName(CT); | ||||
7781 | } | ||||
7782 | |||||
7783 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); | ||||
7784 | Path.Decls = Path.Decls.slice(1)) { | ||||
7785 | NamedDecl *D = Path.Decls.front(); | ||||
7786 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||
7787 | if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) | ||||
7788 | return true; | ||||
7789 | } | ||||
7790 | } | ||||
7791 | |||||
7792 | return false; | ||||
7793 | } | ||||
7794 | }; | ||||
7795 | |||||
7796 | enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; | ||||
7797 | } // end anonymous namespace | ||||
7798 | |||||
7799 | /// Report an error regarding overriding, along with any relevant | ||||
7800 | /// overridden methods. | ||||
7801 | /// | ||||
7802 | /// \param DiagID the primary error to report. | ||||
7803 | /// \param MD the overriding method. | ||||
7804 | /// \param OEK which overrides to include as notes. | ||||
7805 | static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, | ||||
7806 | OverrideErrorKind OEK = OEK_All) { | ||||
7807 | S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); | ||||
7808 | for (const CXXMethodDecl *O : MD->overridden_methods()) { | ||||
7809 | // This check (& the OEK parameter) could be replaced by a predicate, but | ||||
7810 | // without lambdas that would be overkill. This is still nicer than writing | ||||
7811 | // out the diag loop 3 times. | ||||
7812 | if ((OEK == OEK_All) || | ||||
7813 | (OEK == OEK_NonDeleted && !O->isDeleted()) || | ||||
7814 | (OEK == OEK_Deleted && O->isDeleted())) | ||||
7815 | S.Diag(O->getLocation(), diag::note_overridden_virtual_function); | ||||
7816 | } | ||||
7817 | } | ||||
7818 | |||||
7819 | /// AddOverriddenMethods - See if a method overrides any in the base classes, | ||||
7820 | /// and if so, check that it's a valid override and remember it. | ||||
7821 | bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { | ||||
7822 | // Look for methods in base classes that this method might override. | ||||
7823 | CXXBasePaths Paths; | ||||
7824 | FindOverriddenMethod FOM; | ||||
7825 | FOM.Method = MD; | ||||
7826 | FOM.S = this; | ||||
7827 | bool hasDeletedOverridenMethods = false; | ||||
7828 | bool hasNonDeletedOverridenMethods = false; | ||||
7829 | bool AddedAny = false; | ||||
7830 | if (DC->lookupInBases(FOM, Paths)) { | ||||
7831 | for (auto *I : Paths.found_decls()) { | ||||
7832 | if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { | ||||
7833 | MD->addOverriddenMethod(OldMD->getCanonicalDecl()); | ||||
7834 | if (!CheckOverridingFunctionReturnType(MD, OldMD) && | ||||
7835 | !CheckOverridingFunctionAttributes(MD, OldMD) && | ||||
7836 | !CheckOverridingFunctionExceptionSpec(MD, OldMD) && | ||||
7837 | !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { | ||||
7838 | hasDeletedOverridenMethods |= OldMD->isDeleted(); | ||||
7839 | hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); | ||||
7840 | AddedAny = true; | ||||
7841 | } | ||||
7842 | } | ||||
7843 | } | ||||
7844 | } | ||||
7845 | |||||
7846 | if (hasDeletedOverridenMethods && !MD->isDeleted()) { | ||||
7847 | ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); | ||||
7848 | } | ||||
7849 | if (hasNonDeletedOverridenMethods && MD->isDeleted()) { | ||||
7850 | ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); | ||||
7851 | } | ||||
7852 | |||||
7853 | return AddedAny; | ||||
7854 | } | ||||
7855 | |||||
7856 | namespace { | ||||
7857 | // Struct for holding all of the extra arguments needed by | ||||
7858 | // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. | ||||
7859 | struct ActOnFDArgs { | ||||
7860 | Scope *S; | ||||
7861 | Declarator &D; | ||||
7862 | MultiTemplateParamsArg TemplateParamLists; | ||||
7863 | bool AddToScope; | ||||
7864 | }; | ||||
7865 | } // end anonymous namespace | ||||
7866 | |||||
7867 | namespace { | ||||
7868 | |||||
7869 | // Callback to only accept typo corrections that have a non-zero edit distance. | ||||
7870 | // Also only accept corrections that have the same parent decl. | ||||
7871 | class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { | ||||
7872 | public: | ||||
7873 | DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, | ||||
7874 | CXXRecordDecl *Parent) | ||||
7875 | : Context(Context), OriginalFD(TypoFD), | ||||
7876 | ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} | ||||
7877 | |||||
7878 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
7879 | if (candidate.getEditDistance() == 0) | ||||
7880 | return false; | ||||
7881 | |||||
7882 | SmallVector<unsigned, 1> MismatchedParams; | ||||
7883 | for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), | ||||
7884 | CDeclEnd = candidate.end(); | ||||
7885 | CDecl != CDeclEnd; ++CDecl) { | ||||
7886 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | ||||
7887 | |||||
7888 | if (FD && !FD->hasBody() && | ||||
7889 | hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { | ||||
7890 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||
7891 | CXXRecordDecl *Parent = MD->getParent(); | ||||
7892 | if (Parent && Parent->getCanonicalDecl() == ExpectedParent) | ||||
7893 | return true; | ||||
7894 | } else if (!ExpectedParent) { | ||||
7895 | return true; | ||||
7896 | } | ||||
7897 | } | ||||
7898 | } | ||||
7899 | |||||
7900 | return false; | ||||
7901 | } | ||||
7902 | |||||
7903 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
7904 | return std::make_unique<DifferentNameValidatorCCC>(*this); | ||||
7905 | } | ||||
7906 | |||||
7907 | private: | ||||
7908 | ASTContext &Context; | ||||
7909 | FunctionDecl *OriginalFD; | ||||
7910 | CXXRecordDecl *ExpectedParent; | ||||
7911 | }; | ||||
7912 | |||||
7913 | } // end anonymous namespace | ||||
7914 | |||||
7915 | void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { | ||||
7916 | TypoCorrectedFunctionDefinitions.insert(F); | ||||
7917 | } | ||||
7918 | |||||
7919 | /// Generate diagnostics for an invalid function redeclaration. | ||||
7920 | /// | ||||
7921 | /// This routine handles generating the diagnostic messages for an invalid | ||||
7922 | /// function redeclaration, including finding possible similar declarations | ||||
7923 | /// or performing typo correction if there are no previous declarations with | ||||
7924 | /// the same name. | ||||
7925 | /// | ||||
7926 | /// Returns a NamedDecl iff typo correction was performed and substituting in | ||||
7927 | /// the new declaration name does not cause new errors. | ||||
7928 | static NamedDecl *DiagnoseInvalidRedeclaration( | ||||
7929 | Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, | ||||
7930 | ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { | ||||
7931 | DeclarationName Name = NewFD->getDeclName(); | ||||
7932 | DeclContext *NewDC = NewFD->getDeclContext(); | ||||
7933 | SmallVector<unsigned, 1> MismatchedParams; | ||||
7934 | SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; | ||||
7935 | TypoCorrection Correction; | ||||
7936 | bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); | ||||
7937 | unsigned DiagMsg = | ||||
7938 | IsLocalFriend ? diag::err_no_matching_local_friend : | ||||
7939 | NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : | ||||
7940 | diag::err_member_decl_does_not_match; | ||||
7941 | LookupResult Prev(SemaRef, Name, NewFD->getLocation(), | ||||
7942 | IsLocalFriend ? Sema::LookupLocalFriendName | ||||
7943 | : Sema::LookupOrdinaryName, | ||||
7944 | Sema::ForVisibleRedeclaration); | ||||
7945 | |||||
7946 | NewFD->setInvalidDecl(); | ||||
7947 | if (IsLocalFriend) | ||||
7948 | SemaRef.LookupName(Prev, S); | ||||
7949 | else | ||||
7950 | SemaRef.LookupQualifiedName(Prev, NewDC); | ||||
7951 | assert(!Prev.isAmbiguous() &&((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 7952, __PRETTY_FUNCTION__)) | ||||
7952 | "Cannot have an ambiguity in previous-declaration lookup")((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 7952, __PRETTY_FUNCTION__)); | ||||
7953 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | ||||
7954 | DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, | ||||
7955 | MD ? MD->getParent() : nullptr); | ||||
7956 | if (!Prev.empty()) { | ||||
7957 | for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); | ||||
7958 | Func != FuncEnd; ++Func) { | ||||
7959 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); | ||||
7960 | if (FD && | ||||
7961 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | ||||
7962 | // Add 1 to the index so that 0 can mean the mismatch didn't | ||||
7963 | // involve a parameter | ||||
7964 | unsigned ParamNum = | ||||
7965 | MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; | ||||
7966 | NearMatches.push_back(std::make_pair(FD, ParamNum)); | ||||
7967 | } | ||||
7968 | } | ||||
7969 | // If the qualified name lookup yielded nothing, try typo correction | ||||
7970 | } else if ((Correction = SemaRef.CorrectTypo( | ||||
7971 | Prev.getLookupNameInfo(), Prev.getLookupKind(), S, | ||||
7972 | &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, | ||||
7973 | IsLocalFriend ? nullptr : NewDC))) { | ||||
7974 | // Set up everything for the call to ActOnFunctionDeclarator | ||||
7975 | ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), | ||||
7976 | ExtraArgs.D.getIdentifierLoc()); | ||||
7977 | Previous.clear(); | ||||
7978 | Previous.setLookupName(Correction.getCorrection()); | ||||
7979 | for (TypoCorrection::decl_iterator CDecl = Correction.begin(), | ||||
7980 | CDeclEnd = Correction.end(); | ||||
7981 | CDecl != CDeclEnd; ++CDecl) { | ||||
7982 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | ||||
7983 | if (FD && !FD->hasBody() && | ||||
7984 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | ||||
7985 | Previous.addDecl(FD); | ||||
7986 | } | ||||
7987 | } | ||||
7988 | bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); | ||||
7989 | |||||
7990 | NamedDecl *Result; | ||||
7991 | // Retry building the function declaration with the new previous | ||||
7992 | // declarations, and with errors suppressed. | ||||
7993 | { | ||||
7994 | // Trap errors. | ||||
7995 | Sema::SFINAETrap Trap(SemaRef); | ||||
7996 | |||||
7997 | // TODO: Refactor ActOnFunctionDeclarator so that we can call only the | ||||
7998 | // pieces need to verify the typo-corrected C++ declaration and hopefully | ||||
7999 | // eliminate the need for the parameter pack ExtraArgs. | ||||
8000 | Result = SemaRef.ActOnFunctionDeclarator( | ||||
8001 | ExtraArgs.S, ExtraArgs.D, | ||||
8002 | Correction.getCorrectionDecl()->getDeclContext(), | ||||
8003 | NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, | ||||
8004 | ExtraArgs.AddToScope); | ||||
8005 | |||||
8006 | if (Trap.hasErrorOccurred()) | ||||
8007 | Result = nullptr; | ||||
8008 | } | ||||
8009 | |||||
8010 | if (Result) { | ||||
8011 | // Determine which correction we picked. | ||||
8012 | Decl *Canonical = Result->getCanonicalDecl(); | ||||
8013 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||
8014 | I != E; ++I) | ||||
8015 | if ((*I)->getCanonicalDecl() == Canonical) | ||||
8016 | Correction.setCorrectionDecl(*I); | ||||
8017 | |||||
8018 | // Let Sema know about the correction. | ||||
8019 | SemaRef.MarkTypoCorrectedFunctionDefinition(Result); | ||||
8020 | SemaRef.diagnoseTypo( | ||||
8021 | Correction, | ||||
8022 | SemaRef.PDiag(IsLocalFriend | ||||
8023 | ? diag::err_no_matching_local_friend_suggest | ||||
8024 | : diag::err_member_decl_does_not_match_suggest) | ||||
8025 | << Name << NewDC << IsDefinition); | ||||
8026 | return Result; | ||||
8027 | } | ||||
8028 | |||||
8029 | // Pretend the typo correction never occurred | ||||
8030 | ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), | ||||
8031 | ExtraArgs.D.getIdentifierLoc()); | ||||
8032 | ExtraArgs.D.setRedeclaration(wasRedeclaration); | ||||
8033 | Previous.clear(); | ||||
8034 | Previous.setLookupName(Name); | ||||
8035 | } | ||||
8036 | |||||
8037 | SemaRef.Diag(NewFD->getLocation(), DiagMsg) | ||||
8038 | << Name << NewDC << IsDefinition << NewFD->getLocation(); | ||||
8039 | |||||
8040 | bool NewFDisConst = false; | ||||
8041 | if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) | ||||
8042 | NewFDisConst = NewMD->isConst(); | ||||
8043 | |||||
8044 | for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator | ||||
8045 | NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); | ||||
8046 | NearMatch != NearMatchEnd; ++NearMatch) { | ||||
8047 | FunctionDecl *FD = NearMatch->first; | ||||
8048 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||
8049 | bool FDisConst = MD && MD->isConst(); | ||||
8050 | bool IsMember = MD || !IsLocalFriend; | ||||
8051 | |||||
8052 | // FIXME: These notes are poorly worded for the local friend case. | ||||
8053 | if (unsigned Idx = NearMatch->second) { | ||||
8054 | ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); | ||||
8055 | SourceLocation Loc = FDParam->getTypeSpecStartLoc(); | ||||
8056 | if (Loc.isInvalid()) Loc = FD->getLocation(); | ||||
8057 | SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match | ||||
8058 | : diag::note_local_decl_close_param_match) | ||||
8059 | << Idx << FDParam->getType() | ||||
8060 | << NewFD->getParamDecl(Idx - 1)->getType(); | ||||
8061 | } else if (FDisConst != NewFDisConst) { | ||||
8062 | SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) | ||||
8063 | << NewFDisConst << FD->getSourceRange().getEnd(); | ||||
8064 | } else | ||||
8065 | SemaRef.Diag(FD->getLocation(), | ||||
8066 | IsMember ? diag::note_member_def_close_match | ||||
8067 | : diag::note_local_decl_close_match); | ||||
8068 | } | ||||
8069 | return nullptr; | ||||
8070 | } | ||||
8071 | |||||
8072 | static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { | ||||
8073 | switch (D.getDeclSpec().getStorageClassSpec()) { | ||||
8074 | default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8074); | ||||
8075 | case DeclSpec::SCS_auto: | ||||
8076 | case DeclSpec::SCS_register: | ||||
8077 | case DeclSpec::SCS_mutable: | ||||
8078 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
8079 | diag::err_typecheck_sclass_func); | ||||
8080 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||
8081 | D.setInvalidType(); | ||||
8082 | break; | ||||
8083 | case DeclSpec::SCS_unspecified: break; | ||||
8084 | case DeclSpec::SCS_extern: | ||||
8085 | if (D.getDeclSpec().isExternInLinkageSpec()) | ||||
8086 | return SC_None; | ||||
8087 | return SC_Extern; | ||||
8088 | case DeclSpec::SCS_static: { | ||||
8089 | if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { | ||||
8090 | // C99 6.7.1p5: | ||||
8091 | // The declaration of an identifier for a function that has | ||||
8092 | // block scope shall have no explicit storage-class specifier | ||||
8093 | // other than extern | ||||
8094 | // See also (C++ [dcl.stc]p4). | ||||
8095 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
8096 | diag::err_static_block_func); | ||||
8097 | break; | ||||
8098 | } else | ||||
8099 | return SC_Static; | ||||
8100 | } | ||||
8101 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | ||||
8102 | } | ||||
8103 | |||||
8104 | // No explicit storage class has already been returned | ||||
8105 | return SC_None; | ||||
8106 | } | ||||
8107 | |||||
8108 | static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, | ||||
8109 | DeclContext *DC, QualType &R, | ||||
8110 | TypeSourceInfo *TInfo, | ||||
8111 | StorageClass SC, | ||||
8112 | bool &IsVirtualOkay) { | ||||
8113 | DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); | ||||
8114 | DeclarationName Name = NameInfo.getName(); | ||||
8115 | |||||
8116 | FunctionDecl *NewFD = nullptr; | ||||
8117 | bool isInline = D.getDeclSpec().isInlineSpecified(); | ||||
8118 | |||||
8119 | if (!SemaRef.getLangOpts().CPlusPlus) { | ||||
8120 | // Determine whether the function was written with a | ||||
8121 | // prototype. This true when: | ||||
8122 | // - there is a prototype in the declarator, or | ||||
8123 | // - the type R of the function is some kind of typedef or other non- | ||||
8124 | // attributed reference to a type name (which eventually refers to a | ||||
8125 | // function type). | ||||
8126 | bool HasPrototype = | ||||
8127 | (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || | ||||
8128 | (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); | ||||
8129 | |||||
8130 | NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, | ||||
8131 | R, TInfo, SC, isInline, HasPrototype, | ||||
8132 | CSK_unspecified); | ||||
8133 | if (D.isInvalidType()) | ||||
8134 | NewFD->setInvalidDecl(); | ||||
8135 | |||||
8136 | return NewFD; | ||||
8137 | } | ||||
8138 | |||||
8139 | ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); | ||||
8140 | |||||
8141 | ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); | ||||
8142 | if (ConstexprKind == CSK_constinit) { | ||||
8143 | SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||
8144 | diag::err_constexpr_wrong_decl_kind) | ||||
8145 | << ConstexprKind; | ||||
8146 | ConstexprKind = CSK_unspecified; | ||||
8147 | D.getMutableDeclSpec().ClearConstexprSpec(); | ||||
8148 | } | ||||
8149 | |||||
8150 | // Check that the return type is not an abstract class type. | ||||
8151 | // For record types, this is done by the AbstractClassUsageDiagnoser once | ||||
8152 | // the class has been completely parsed. | ||||
8153 | if (!DC->isRecord() && | ||||
8154 | SemaRef.RequireNonAbstractType( | ||||
8155 | D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), | ||||
8156 | diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) | ||||
8157 | D.setInvalidType(); | ||||
8158 | |||||
8159 | if (Name.getNameKind() == DeclarationName::CXXConstructorName) { | ||||
8160 | // This is a C++ constructor declaration. | ||||
8161 | assert(DC->isRecord() &&((DC->isRecord() && "Constructors can only be declared in a member context" ) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8162, __PRETTY_FUNCTION__)) | ||||
8162 | "Constructors can only be declared in a member context")((DC->isRecord() && "Constructors can only be declared in a member context" ) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8162, __PRETTY_FUNCTION__)); | ||||
8163 | |||||
8164 | R = SemaRef.CheckConstructorDeclarator(D, R, SC); | ||||
8165 | return CXXConstructorDecl::Create( | ||||
8166 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||
8167 | TInfo, ExplicitSpecifier, isInline, | ||||
8168 | /*isImplicitlyDeclared=*/false, ConstexprKind); | ||||
8169 | |||||
8170 | } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||
8171 | // This is a C++ destructor declaration. | ||||
8172 | if (DC->isRecord()) { | ||||
8173 | R = SemaRef.CheckDestructorDeclarator(D, R, SC); | ||||
8174 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); | ||||
8175 | CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( | ||||
8176 | SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, | ||||
8177 | isInline, | ||||
8178 | /*isImplicitlyDeclared=*/false, ConstexprKind); | ||||
8179 | |||||
8180 | // If the destructor needs an implicit exception specification, set it | ||||
8181 | // now. FIXME: It'd be nice to be able to create the right type to start | ||||
8182 | // with, but the type needs to reference the destructor declaration. | ||||
8183 | if (SemaRef.getLangOpts().CPlusPlus11) | ||||
8184 | SemaRef.AdjustDestructorExceptionSpec(NewDD); | ||||
8185 | |||||
8186 | IsVirtualOkay = true; | ||||
8187 | return NewDD; | ||||
8188 | |||||
8189 | } else { | ||||
8190 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); | ||||
8191 | D.setInvalidType(); | ||||
8192 | |||||
8193 | // Create a FunctionDecl to satisfy the function definition parsing | ||||
8194 | // code path. | ||||
8195 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | ||||
8196 | D.getIdentifierLoc(), Name, R, TInfo, SC, | ||||
8197 | isInline, | ||||
8198 | /*hasPrototype=*/true, ConstexprKind); | ||||
8199 | } | ||||
8200 | |||||
8201 | } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||
8202 | if (!DC->isRecord()) { | ||||
8203 | SemaRef.Diag(D.getIdentifierLoc(), | ||||
8204 | diag::err_conv_function_not_member); | ||||
8205 | return nullptr; | ||||
8206 | } | ||||
8207 | |||||
8208 | SemaRef.CheckConversionDeclarator(D, R, SC); | ||||
8209 | IsVirtualOkay = true; | ||||
8210 | return CXXConversionDecl::Create( | ||||
8211 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||
8212 | TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation()); | ||||
8213 | |||||
8214 | } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { | ||||
8215 | SemaRef.CheckDeductionGuideDeclarator(D, R, SC); | ||||
8216 | |||||
8217 | return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | ||||
8218 | ExplicitSpecifier, NameInfo, R, TInfo, | ||||
8219 | D.getEndLoc()); | ||||
8220 | } else if (DC->isRecord()) { | ||||
8221 | // If the name of the function is the same as the name of the record, | ||||
8222 | // then this must be an invalid constructor that has a return type. | ||||
8223 | // (The parser checks for a return type and makes the declarator a | ||||
8224 | // constructor if it has no return type). | ||||
8225 | if (Name.getAsIdentifierInfo() && | ||||
8226 | Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ | ||||
8227 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) | ||||
8228 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | ||||
8229 | << SourceRange(D.getIdentifierLoc()); | ||||
8230 | return nullptr; | ||||
8231 | } | ||||
8232 | |||||
8233 | // This is a C++ method declaration. | ||||
8234 | CXXMethodDecl *Ret = CXXMethodDecl::Create( | ||||
8235 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||
8236 | TInfo, SC, isInline, ConstexprKind, SourceLocation()); | ||||
8237 | IsVirtualOkay = !Ret->isStatic(); | ||||
8238 | return Ret; | ||||
8239 | } else { | ||||
8240 | bool isFriend = | ||||
8241 | SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); | ||||
8242 | if (!isFriend && SemaRef.CurContext->isRecord()) | ||||
8243 | return nullptr; | ||||
8244 | |||||
8245 | // Determine whether the function was written with a | ||||
8246 | // prototype. This true when: | ||||
8247 | // - we're in C++ (where every function has a prototype), | ||||
8248 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, | ||||
8249 | R, TInfo, SC, isInline, true /*HasPrototype*/, | ||||
8250 | ConstexprKind); | ||||
8251 | } | ||||
8252 | } | ||||
8253 | |||||
8254 | enum OpenCLParamType { | ||||
8255 | ValidKernelParam, | ||||
8256 | PtrPtrKernelParam, | ||||
8257 | PtrKernelParam, | ||||
8258 | InvalidAddrSpacePtrKernelParam, | ||||
8259 | InvalidKernelParam, | ||||
8260 | RecordKernelParam | ||||
8261 | }; | ||||
8262 | |||||
8263 | static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { | ||||
8264 | // Size dependent types are just typedefs to normal integer types | ||||
8265 | // (e.g. unsigned long), so we cannot distinguish them from other typedefs to | ||||
8266 | // integers other than by their names. | ||||
8267 | StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; | ||||
8268 | |||||
8269 | // Remove typedefs one by one until we reach a typedef | ||||
8270 | // for a size dependent type. | ||||
8271 | QualType DesugaredTy = Ty; | ||||
8272 | do { | ||||
8273 | ArrayRef<StringRef> Names(SizeTypeNames); | ||||
8274 | auto Match = llvm::find(Names, DesugaredTy.getAsString()); | ||||
8275 | if (Names.end() != Match) | ||||
8276 | return true; | ||||
8277 | |||||
8278 | Ty = DesugaredTy; | ||||
8279 | DesugaredTy = Ty.getSingleStepDesugaredType(C); | ||||
8280 | } while (DesugaredTy != Ty); | ||||
8281 | |||||
8282 | return false; | ||||
8283 | } | ||||
8284 | |||||
8285 | static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { | ||||
8286 | if (PT->isPointerType()) { | ||||
8287 | QualType PointeeType = PT->getPointeeType(); | ||||
8288 | if (PointeeType->isPointerType()) | ||||
8289 | return PtrPtrKernelParam; | ||||
8290 | if (PointeeType.getAddressSpace() == LangAS::opencl_generic || | ||||
8291 | PointeeType.getAddressSpace() == LangAS::opencl_private || | ||||
8292 | PointeeType.getAddressSpace() == LangAS::Default) | ||||
8293 | return InvalidAddrSpacePtrKernelParam; | ||||
8294 | return PtrKernelParam; | ||||
8295 | } | ||||
8296 | |||||
8297 | // OpenCL v1.2 s6.9.k: | ||||
8298 | // Arguments to kernel functions in a program cannot be declared with the | ||||
8299 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | ||||
8300 | // uintptr_t or a struct and/or union that contain fields declared to be one | ||||
8301 | // of these built-in scalar types. | ||||
8302 | if (isOpenCLSizeDependentType(S.getASTContext(), PT)) | ||||
8303 | return InvalidKernelParam; | ||||
8304 | |||||
8305 | if (PT->isImageType()) | ||||
8306 | return PtrKernelParam; | ||||
8307 | |||||
8308 | if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) | ||||
8309 | return InvalidKernelParam; | ||||
8310 | |||||
8311 | // OpenCL extension spec v1.2 s9.5: | ||||
8312 | // This extension adds support for half scalar and vector types as built-in | ||||
8313 | // types that can be used for arithmetic operations, conversions etc. | ||||
8314 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) | ||||
8315 | return InvalidKernelParam; | ||||
8316 | |||||
8317 | if (PT->isRecordType()) | ||||
8318 | return RecordKernelParam; | ||||
8319 | |||||
8320 | // Look into an array argument to check if it has a forbidden type. | ||||
8321 | if (PT->isArrayType()) { | ||||
8322 | const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); | ||||
8323 | // Call ourself to check an underlying type of an array. Since the | ||||
8324 | // getPointeeOrArrayElementType returns an innermost type which is not an | ||||
8325 | // array, this recursive call only happens once. | ||||
8326 | return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); | ||||
8327 | } | ||||
8328 | |||||
8329 | return ValidKernelParam; | ||||
8330 | } | ||||
8331 | |||||
8332 | static void checkIsValidOpenCLKernelParameter( | ||||
8333 | Sema &S, | ||||
8334 | Declarator &D, | ||||
8335 | ParmVarDecl *Param, | ||||
8336 | llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { | ||||
8337 | QualType PT = Param->getType(); | ||||
8338 | |||||
8339 | // Cache the valid types we encounter to avoid rechecking structs that are | ||||
8340 | // used again | ||||
8341 | if (ValidTypes.count(PT.getTypePtr())) | ||||
8342 | return; | ||||
8343 | |||||
8344 | switch (getOpenCLKernelParameterType(S, PT)) { | ||||
8345 | case PtrPtrKernelParam: | ||||
8346 | // OpenCL v1.2 s6.9.a: | ||||
8347 | // A kernel function argument cannot be declared as a | ||||
8348 | // pointer to a pointer type. | ||||
8349 | S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); | ||||
8350 | D.setInvalidType(); | ||||
8351 | return; | ||||
8352 | |||||
8353 | case InvalidAddrSpacePtrKernelParam: | ||||
8354 | // OpenCL v1.0 s6.5: | ||||
8355 | // __kernel function arguments declared to be a pointer of a type can point | ||||
8356 | // to one of the following address spaces only : __global, __local or | ||||
8357 | // __constant. | ||||
8358 | S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); | ||||
8359 | D.setInvalidType(); | ||||
8360 | return; | ||||
8361 | |||||
8362 | // OpenCL v1.2 s6.9.k: | ||||
8363 | // Arguments to kernel functions in a program cannot be declared with the | ||||
8364 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | ||||
8365 | // uintptr_t or a struct and/or union that contain fields declared to be | ||||
8366 | // one of these built-in scalar types. | ||||
8367 | |||||
8368 | case InvalidKernelParam: | ||||
8369 | // OpenCL v1.2 s6.8 n: | ||||
8370 | // A kernel function argument cannot be declared | ||||
8371 | // of event_t type. | ||||
8372 | // Do not diagnose half type since it is diagnosed as invalid argument | ||||
8373 | // type for any function elsewhere. | ||||
8374 | if (!PT->isHalfType()) { | ||||
8375 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | ||||
8376 | |||||
8377 | // Explain what typedefs are involved. | ||||
8378 | const TypedefType *Typedef = nullptr; | ||||
8379 | while ((Typedef = PT->getAs<TypedefType>())) { | ||||
8380 | SourceLocation Loc = Typedef->getDecl()->getLocation(); | ||||
8381 | // SourceLocation may be invalid for a built-in type. | ||||
8382 | if (Loc.isValid()) | ||||
8383 | S.Diag(Loc, diag::note_entity_declared_at) << PT; | ||||
8384 | PT = Typedef->desugar(); | ||||
8385 | } | ||||
8386 | } | ||||
8387 | |||||
8388 | D.setInvalidType(); | ||||
8389 | return; | ||||
8390 | |||||
8391 | case PtrKernelParam: | ||||
8392 | case ValidKernelParam: | ||||
8393 | ValidTypes.insert(PT.getTypePtr()); | ||||
8394 | return; | ||||
8395 | |||||
8396 | case RecordKernelParam: | ||||
8397 | break; | ||||
8398 | } | ||||
8399 | |||||
8400 | // Track nested structs we will inspect | ||||
8401 | SmallVector<const Decl *, 4> VisitStack; | ||||
8402 | |||||
8403 | // Track where we are in the nested structs. Items will migrate from | ||||
8404 | // VisitStack to HistoryStack as we do the DFS for bad field. | ||||
8405 | SmallVector<const FieldDecl *, 4> HistoryStack; | ||||
8406 | HistoryStack.push_back(nullptr); | ||||
8407 | |||||
8408 | // At this point we already handled everything except of a RecordType or | ||||
8409 | // an ArrayType of a RecordType. | ||||
8410 | assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(((PT->isArrayType() || PT->isRecordType()) && "Unexpected type." ) ? static_cast<void> (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8410, __PRETTY_FUNCTION__)); | ||||
8411 | const RecordType *RecTy = | ||||
8412 | PT->getPointeeOrArrayElementType()->getAs<RecordType>(); | ||||
8413 | const RecordDecl *OrigRecDecl = RecTy->getDecl(); | ||||
8414 | |||||
8415 | VisitStack.push_back(RecTy->getDecl()); | ||||
8416 | assert(VisitStack.back() && "First decl null?")((VisitStack.back() && "First decl null?") ? static_cast <void> (0) : __assert_fail ("VisitStack.back() && \"First decl null?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8416, __PRETTY_FUNCTION__)); | ||||
8417 | |||||
8418 | do { | ||||
8419 | const Decl *Next = VisitStack.pop_back_val(); | ||||
8420 | if (!Next) { | ||||
8421 | assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail ("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8421, __PRETTY_FUNCTION__)); | ||||
8422 | // Found a marker, we have gone up a level | ||||
8423 | if (const FieldDecl *Hist = HistoryStack.pop_back_val()) | ||||
8424 | ValidTypes.insert(Hist->getType().getTypePtr()); | ||||
8425 | |||||
8426 | continue; | ||||
8427 | } | ||||
8428 | |||||
8429 | // Adds everything except the original parameter declaration (which is not a | ||||
8430 | // field itself) to the history stack. | ||||
8431 | const RecordDecl *RD; | ||||
8432 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { | ||||
8433 | HistoryStack.push_back(Field); | ||||
8434 | |||||
8435 | QualType FieldTy = Field->getType(); | ||||
8436 | // Other field types (known to be valid or invalid) are handled while we | ||||
8437 | // walk around RecordDecl::fields(). | ||||
8438 | assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8439, __PRETTY_FUNCTION__)) | ||||
8439 | "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8439, __PRETTY_FUNCTION__)); | ||||
8440 | const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); | ||||
8441 | |||||
8442 | RD = FieldRecTy->castAs<RecordType>()->getDecl(); | ||||
8443 | } else { | ||||
8444 | RD = cast<RecordDecl>(Next); | ||||
8445 | } | ||||
8446 | |||||
8447 | // Add a null marker so we know when we've gone back up a level | ||||
8448 | VisitStack.push_back(nullptr); | ||||
8449 | |||||
8450 | for (const auto *FD : RD->fields()) { | ||||
8451 | QualType QT = FD->getType(); | ||||
8452 | |||||
8453 | if (ValidTypes.count(QT.getTypePtr())) | ||||
8454 | continue; | ||||
8455 | |||||
8456 | OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); | ||||
8457 | if (ParamType == ValidKernelParam) | ||||
8458 | continue; | ||||
8459 | |||||
8460 | if (ParamType == RecordKernelParam) { | ||||
8461 | VisitStack.push_back(FD); | ||||
8462 | continue; | ||||
8463 | } | ||||
8464 | |||||
8465 | // OpenCL v1.2 s6.9.p: | ||||
8466 | // Arguments to kernel functions that are declared to be a struct or union | ||||
8467 | // do not allow OpenCL objects to be passed as elements of the struct or | ||||
8468 | // union. | ||||
8469 | if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || | ||||
8470 | ParamType == InvalidAddrSpacePtrKernelParam) { | ||||
8471 | S.Diag(Param->getLocation(), | ||||
8472 | diag::err_record_with_pointers_kernel_param) | ||||
8473 | << PT->isUnionType() | ||||
8474 | << PT; | ||||
8475 | } else { | ||||
8476 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | ||||
8477 | } | ||||
8478 | |||||
8479 | S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) | ||||
8480 | << OrigRecDecl->getDeclName(); | ||||
8481 | |||||
8482 | // We have an error, now let's go back up through history and show where | ||||
8483 | // the offending field came from | ||||
8484 | for (ArrayRef<const FieldDecl *>::const_iterator | ||||
8485 | I = HistoryStack.begin() + 1, | ||||
8486 | E = HistoryStack.end(); | ||||
8487 | I != E; ++I) { | ||||
8488 | const FieldDecl *OuterField = *I; | ||||
8489 | S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) | ||||
8490 | << OuterField->getType(); | ||||
8491 | } | ||||
8492 | |||||
8493 | S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) | ||||
8494 | << QT->isPointerType() | ||||
8495 | << QT; | ||||
8496 | D.setInvalidType(); | ||||
8497 | return; | ||||
8498 | } | ||||
8499 | } while (!VisitStack.empty()); | ||||
8500 | } | ||||
8501 | |||||
8502 | /// Find the DeclContext in which a tag is implicitly declared if we see an | ||||
8503 | /// elaborated type specifier in the specified context, and lookup finds | ||||
8504 | /// nothing. | ||||
8505 | static DeclContext *getTagInjectionContext(DeclContext *DC) { | ||||
8506 | while (!DC->isFileContext() && !DC->isFunctionOrMethod()) | ||||
8507 | DC = DC->getParent(); | ||||
8508 | return DC; | ||||
8509 | } | ||||
8510 | |||||
8511 | /// Find the Scope in which a tag is implicitly declared if we see an | ||||
8512 | /// elaborated type specifier in the specified context, and lookup finds | ||||
8513 | /// nothing. | ||||
8514 | static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { | ||||
8515 | while (S->isClassScope() || | ||||
8516 | (LangOpts.CPlusPlus && | ||||
8517 | S->isFunctionPrototypeScope()) || | ||||
8518 | ((S->getFlags() & Scope::DeclScope) == 0) || | ||||
8519 | (S->getEntity() && S->getEntity()->isTransparentContext())) | ||||
8520 | S = S->getParent(); | ||||
8521 | return S; | ||||
8522 | } | ||||
8523 | |||||
8524 | NamedDecl* | ||||
8525 | Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, | ||||
8526 | TypeSourceInfo *TInfo, LookupResult &Previous, | ||||
8527 | MultiTemplateParamsArg TemplateParamLists, | ||||
8528 | bool &AddToScope) { | ||||
8529 | QualType R = TInfo->getType(); | ||||
8530 | |||||
8531 | assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("R->isFunctionType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8531, __PRETTY_FUNCTION__)); | ||||
8532 | |||||
8533 | // TODO: consider using NameInfo for diagnostic. | ||||
8534 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||
8535 | DeclarationName Name = NameInfo.getName(); | ||||
8536 | StorageClass SC = getFunctionStorageClass(*this, D); | ||||
8537 | |||||
8538 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | ||||
8539 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
8540 | diag::err_invalid_thread) | ||||
8541 | << DeclSpec::getSpecifierName(TSCS); | ||||
8542 | |||||
8543 | if (D.isFirstDeclarationOfMember()) | ||||
8544 | adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), | ||||
8545 | D.getIdentifierLoc()); | ||||
8546 | |||||
8547 | bool isFriend = false; | ||||
8548 | FunctionTemplateDecl *FunctionTemplate = nullptr; | ||||
8549 | bool isMemberSpecialization = false; | ||||
8550 | bool isFunctionTemplateSpecialization = false; | ||||
8551 | |||||
8552 | bool isDependentClassScopeExplicitSpecialization = false; | ||||
8553 | bool HasExplicitTemplateArgs = false; | ||||
8554 | TemplateArgumentListInfo TemplateArgs; | ||||
8555 | |||||
8556 | bool isVirtualOkay = false; | ||||
8557 | |||||
8558 | DeclContext *OriginalDC = DC; | ||||
8559 | bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); | ||||
8560 | |||||
8561 | FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, | ||||
8562 | isVirtualOkay); | ||||
8563 | if (!NewFD) return nullptr; | ||||
8564 | |||||
8565 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) | ||||
8566 | NewFD->setTopLevelDeclInObjCContainer(); | ||||
8567 | |||||
8568 | // Set the lexical context. If this is a function-scope declaration, or has a | ||||
8569 | // C++ scope specifier, or is the object of a friend declaration, the lexical | ||||
8570 | // context will be different from the semantic context. | ||||
8571 | NewFD->setLexicalDeclContext(CurContext); | ||||
8572 | |||||
8573 | if (IsLocalExternDecl) | ||||
8574 | NewFD->setLocalExternDecl(); | ||||
8575 | |||||
8576 | if (getLangOpts().CPlusPlus) { | ||||
8577 | bool isInline = D.getDeclSpec().isInlineSpecified(); | ||||
8578 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | ||||
8579 | bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); | ||||
8580 | isFriend = D.getDeclSpec().isFriendSpecified(); | ||||
8581 | if (isFriend && !isInline && D.isFunctionDefinition()) { | ||||
8582 | // C++ [class.friend]p5 | ||||
8583 | // A function can be defined in a friend declaration of a | ||||
8584 | // class . . . . Such a function is implicitly inline. | ||||
8585 | NewFD->setImplicitlyInline(); | ||||
8586 | } | ||||
8587 | |||||
8588 | // If this is a method defined in an __interface, and is not a constructor | ||||
8589 | // or an overloaded operator, then set the pure flag (isVirtual will already | ||||
8590 | // return true). | ||||
8591 | if (const CXXRecordDecl *Parent = | ||||
8592 | dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { | ||||
8593 | if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) | ||||
8594 | NewFD->setPure(true); | ||||
8595 | |||||
8596 | // C++ [class.union]p2 | ||||
8597 | // A union can have member functions, but not virtual functions. | ||||
8598 | if (isVirtual && Parent->isUnion()) | ||||
8599 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); | ||||
8600 | } | ||||
8601 | |||||
8602 | SetNestedNameSpecifier(*this, NewFD, D); | ||||
8603 | isMemberSpecialization = false; | ||||
8604 | isFunctionTemplateSpecialization = false; | ||||
8605 | if (D.isInvalidType()) | ||||
8606 | NewFD->setInvalidDecl(); | ||||
8607 | |||||
8608 | // Match up the template parameter lists with the scope specifier, then | ||||
8609 | // determine whether we have a template or a template specialization. | ||||
8610 | bool Invalid = false; | ||||
8611 | if (TemplateParameterList *TemplateParams = | ||||
8612 | MatchTemplateParametersToScopeSpecifier( | ||||
8613 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | ||||
8614 | D.getCXXScopeSpec(), | ||||
8615 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | ||||
8616 | ? D.getName().TemplateId | ||||
8617 | : nullptr, | ||||
8618 | TemplateParamLists, isFriend, isMemberSpecialization, | ||||
8619 | Invalid)) { | ||||
8620 | if (TemplateParams->size() > 0) { | ||||
8621 | // This is a function template | ||||
8622 | |||||
8623 | // Check that we can declare a template here. | ||||
8624 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||
8625 | NewFD->setInvalidDecl(); | ||||
8626 | |||||
8627 | // A destructor cannot be a template. | ||||
8628 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||
8629 | Diag(NewFD->getLocation(), diag::err_destructor_template); | ||||
8630 | NewFD->setInvalidDecl(); | ||||
8631 | } | ||||
8632 | |||||
8633 | // If we're adding a template to a dependent context, we may need to | ||||
8634 | // rebuilding some of the types used within the template parameter list, | ||||
8635 | // now that we know what the current instantiation is. | ||||
8636 | if (DC->isDependentContext()) { | ||||
8637 | ContextRAII SavedContext(*this, DC); | ||||
8638 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) | ||||
8639 | Invalid = true; | ||||
8640 | } | ||||
8641 | |||||
8642 | FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, | ||||
8643 | NewFD->getLocation(), | ||||
8644 | Name, TemplateParams, | ||||
8645 | NewFD); | ||||
8646 | FunctionTemplate->setLexicalDeclContext(CurContext); | ||||
8647 | NewFD->setDescribedFunctionTemplate(FunctionTemplate); | ||||
8648 | |||||
8649 | // For source fidelity, store the other template param lists. | ||||
8650 | if (TemplateParamLists.size() > 1) { | ||||
8651 | NewFD->setTemplateParameterListsInfo(Context, | ||||
8652 | TemplateParamLists.drop_back(1)); | ||||
8653 | } | ||||
8654 | } else { | ||||
8655 | // This is a function template specialization. | ||||
8656 | isFunctionTemplateSpecialization = true; | ||||
8657 | // For source fidelity, store all the template param lists. | ||||
8658 | if (TemplateParamLists.size() > 0) | ||||
8659 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | ||||
8660 | |||||
8661 | // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". | ||||
8662 | if (isFriend) { | ||||
8663 | // We want to remove the "template<>", found here. | ||||
8664 | SourceRange RemoveRange = TemplateParams->getSourceRange(); | ||||
8665 | |||||
8666 | // If we remove the template<> and the name is not a | ||||
8667 | // template-id, we're actually silently creating a problem: | ||||
8668 | // the friend declaration will refer to an untemplated decl, | ||||
8669 | // and clearly the user wants a template specialization. So | ||||
8670 | // we need to insert '<>' after the name. | ||||
8671 | SourceLocation InsertLoc; | ||||
8672 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | ||||
8673 | InsertLoc = D.getName().getSourceRange().getEnd(); | ||||
8674 | InsertLoc = getLocForEndOfToken(InsertLoc); | ||||
8675 | } | ||||
8676 | |||||
8677 | Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) | ||||
8678 | << Name << RemoveRange | ||||
8679 | << FixItHint::CreateRemoval(RemoveRange) | ||||
8680 | << FixItHint::CreateInsertion(InsertLoc, "<>"); | ||||
8681 | } | ||||
8682 | } | ||||
8683 | } else { | ||||
8684 | // All template param lists were matched against the scope specifier: | ||||
8685 | // this is NOT (an explicit specialization of) a template. | ||||
8686 | if (TemplateParamLists.size() > 0) | ||||
8687 | // For source fidelity, store all the template param lists. | ||||
8688 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | ||||
8689 | } | ||||
8690 | |||||
8691 | if (Invalid) { | ||||
8692 | NewFD->setInvalidDecl(); | ||||
8693 | if (FunctionTemplate) | ||||
8694 | FunctionTemplate->setInvalidDecl(); | ||||
8695 | } | ||||
8696 | |||||
8697 | // C++ [dcl.fct.spec]p5: | ||||
8698 | // The virtual specifier shall only be used in declarations of | ||||
8699 | // nonstatic class member functions that appear within a | ||||
8700 | // member-specification of a class declaration; see 10.3. | ||||
8701 | // | ||||
8702 | if (isVirtual && !NewFD->isInvalidDecl()) { | ||||
8703 | if (!isVirtualOkay) { | ||||
8704 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||
8705 | diag::err_virtual_non_function); | ||||
8706 | } else if (!CurContext->isRecord()) { | ||||
8707 | // 'virtual' was specified outside of the class. | ||||
8708 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||
8709 | diag::err_virtual_out_of_class) | ||||
8710 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | ||||
8711 | } else if (NewFD->getDescribedFunctionTemplate()) { | ||||
8712 | // C++ [temp.mem]p3: | ||||
8713 | // A member function template shall not be virtual. | ||||
8714 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||
8715 | diag::err_virtual_member_function_template) | ||||
8716 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | ||||
8717 | } else { | ||||
8718 | // Okay: Add virtual to the method. | ||||
8719 | NewFD->setVirtualAsWritten(true); | ||||
8720 | } | ||||
8721 | |||||
8722 | if (getLangOpts().CPlusPlus14 && | ||||
8723 | NewFD->getReturnType()->isUndeducedType()) | ||||
8724 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); | ||||
8725 | } | ||||
8726 | |||||
8727 | if (getLangOpts().CPlusPlus14 && | ||||
8728 | (NewFD->isDependentContext() || | ||||
8729 | (isFriend && CurContext->isDependentContext())) && | ||||
8730 | NewFD->getReturnType()->isUndeducedType()) { | ||||
8731 | // If the function template is referenced directly (for instance, as a | ||||
8732 | // member of the current instantiation), pretend it has a dependent type. | ||||
8733 | // This is not really justified by the standard, but is the only sane | ||||
8734 | // thing to do. | ||||
8735 | // FIXME: For a friend function, we have not marked the function as being | ||||
8736 | // a friend yet, so 'isDependentContext' on the FD doesn't work. | ||||
8737 | const FunctionProtoType *FPT = | ||||
8738 | NewFD->getType()->castAs<FunctionProtoType>(); | ||||
8739 | QualType Result = | ||||
8740 | SubstAutoType(FPT->getReturnType(), Context.DependentTy); | ||||
8741 | NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), | ||||
8742 | FPT->getExtProtoInfo())); | ||||
8743 | } | ||||
8744 | |||||
8745 | // C++ [dcl.fct.spec]p3: | ||||
8746 | // The inline specifier shall not appear on a block scope function | ||||
8747 | // declaration. | ||||
8748 | if (isInline && !NewFD->isInvalidDecl()) { | ||||
8749 | if (CurContext->isFunctionOrMethod()) { | ||||
8750 | // 'inline' is not allowed on block scope function declaration. | ||||
8751 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||
8752 | diag::err_inline_declaration_block_scope) << Name | ||||
8753 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | ||||
8754 | } | ||||
8755 | } | ||||
8756 | |||||
8757 | // C++ [dcl.fct.spec]p6: | ||||
8758 | // The explicit specifier shall be used only in the declaration of a | ||||
8759 | // constructor or conversion function within its class definition; | ||||
8760 | // see 12.3.1 and 12.3.2. | ||||
8761 | if (hasExplicit && !NewFD->isInvalidDecl() && | ||||
8762 | !isa<CXXDeductionGuideDecl>(NewFD)) { | ||||
8763 | if (!CurContext->isRecord()) { | ||||
8764 | // 'explicit' was specified outside of the class. | ||||
8765 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | ||||
8766 | diag::err_explicit_out_of_class) | ||||
8767 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | ||||
8768 | } else if (!isa<CXXConstructorDecl>(NewFD) && | ||||
8769 | !isa<CXXConversionDecl>(NewFD)) { | ||||
8770 | // 'explicit' was specified on a function that wasn't a constructor | ||||
8771 | // or conversion function. | ||||
8772 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | ||||
8773 | diag::err_explicit_non_ctor_or_conv_function) | ||||
8774 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | ||||
8775 | } | ||||
8776 | } | ||||
8777 | |||||
8778 | if (ConstexprSpecKind ConstexprKind = | ||||
8779 | D.getDeclSpec().getConstexprSpecifier()) { | ||||
8780 | // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors | ||||
8781 | // are implicitly inline. | ||||
8782 | NewFD->setImplicitlyInline(); | ||||
8783 | |||||
8784 | // C++11 [dcl.constexpr]p3: functions declared constexpr are required to | ||||
8785 | // be either constructors or to return a literal type. Therefore, | ||||
8786 | // destructors cannot be declared constexpr. | ||||
8787 | if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) { | ||||
8788 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) | ||||
8789 | << ConstexprKind; | ||||
8790 | } | ||||
8791 | } | ||||
8792 | |||||
8793 | // If __module_private__ was specified, mark the function accordingly. | ||||
8794 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||
8795 | if (isFunctionTemplateSpecialization) { | ||||
8796 | SourceLocation ModulePrivateLoc | ||||
8797 | = D.getDeclSpec().getModulePrivateSpecLoc(); | ||||
8798 | Diag(ModulePrivateLoc, diag::err_module_private_specialization) | ||||
8799 | << 0 | ||||
8800 | << FixItHint::CreateRemoval(ModulePrivateLoc); | ||||
8801 | } else { | ||||
8802 | NewFD->setModulePrivate(); | ||||
8803 | if (FunctionTemplate) | ||||
8804 | FunctionTemplate->setModulePrivate(); | ||||
8805 | } | ||||
8806 | } | ||||
8807 | |||||
8808 | if (isFriend) { | ||||
8809 | if (FunctionTemplate) { | ||||
8810 | FunctionTemplate->setObjectOfFriendDecl(); | ||||
8811 | FunctionTemplate->setAccess(AS_public); | ||||
8812 | } | ||||
8813 | NewFD->setObjectOfFriendDecl(); | ||||
8814 | NewFD->setAccess(AS_public); | ||||
8815 | } | ||||
8816 | |||||
8817 | // If a function is defined as defaulted or deleted, mark it as such now. | ||||
8818 | // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function | ||||
8819 | // definition kind to FDK_Definition. | ||||
8820 | switch (D.getFunctionDefinitionKind()) { | ||||
8821 | case FDK_Declaration: | ||||
8822 | case FDK_Definition: | ||||
8823 | break; | ||||
8824 | |||||
8825 | case FDK_Defaulted: | ||||
8826 | NewFD->setDefaulted(); | ||||
8827 | break; | ||||
8828 | |||||
8829 | case FDK_Deleted: | ||||
8830 | NewFD->setDeletedAsWritten(); | ||||
8831 | break; | ||||
8832 | } | ||||
8833 | |||||
8834 | if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && | ||||
8835 | D.isFunctionDefinition()) { | ||||
8836 | // C++ [class.mfct]p2: | ||||
8837 | // A member function may be defined (8.4) in its class definition, in | ||||
8838 | // which case it is an inline member function (7.1.2) | ||||
8839 | NewFD->setImplicitlyInline(); | ||||
8840 | } | ||||
8841 | |||||
8842 | if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && | ||||
8843 | !CurContext->isRecord()) { | ||||
8844 | // C++ [class.static]p1: | ||||
8845 | // A data or function member of a class may be declared static | ||||
8846 | // in a class definition, in which case it is a static member of | ||||
8847 | // the class. | ||||
8848 | |||||
8849 | // Complain about the 'static' specifier if it's on an out-of-line | ||||
8850 | // member function definition. | ||||
8851 | |||||
8852 | // MSVC permits the use of a 'static' storage specifier on an out-of-line | ||||
8853 | // member function template declaration and class member template | ||||
8854 | // declaration (MSVC versions before 2015), warn about this. | ||||
8855 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||
8856 | ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | ||||
8857 | cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || | ||||
8858 | (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) | ||||
8859 | ? diag::ext_static_out_of_line : diag::err_static_out_of_line) | ||||
8860 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||
8861 | } | ||||
8862 | |||||
8863 | // C++11 [except.spec]p15: | ||||
8864 | // A deallocation function with no exception-specification is treated | ||||
8865 | // as if it were specified with noexcept(true). | ||||
8866 | const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); | ||||
8867 | if ((Name.getCXXOverloadedOperator() == OO_Delete || | ||||
8868 | Name.getCXXOverloadedOperator() == OO_Array_Delete) && | ||||
8869 | getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) | ||||
8870 | NewFD->setType(Context.getFunctionType( | ||||
8871 | FPT->getReturnType(), FPT->getParamTypes(), | ||||
8872 | FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); | ||||
8873 | } | ||||
8874 | |||||
8875 | // Filter out previous declarations that don't match the scope. | ||||
8876 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), | ||||
8877 | D.getCXXScopeSpec().isNotEmpty() || | ||||
8878 | isMemberSpecialization || | ||||
8879 | isFunctionTemplateSpecialization); | ||||
8880 | |||||
8881 | // Handle GNU asm-label extension (encoded as an attribute). | ||||
8882 | if (Expr *E = (Expr*) D.getAsmLabel()) { | ||||
8883 | // The parser guarantees this is a string. | ||||
8884 | StringLiteral *SE = cast<StringLiteral>(E); | ||||
8885 | NewFD->addAttr(::new (Context) | ||||
8886 | AsmLabelAttr(Context, SE->getStrTokenLoc(0), | ||||
8887 | SE->getString(), /*IsLiteralLabel=*/true)); | ||||
8888 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | ||||
8889 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | ||||
8890 | ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); | ||||
8891 | if (I != ExtnameUndeclaredIdentifiers.end()) { | ||||
8892 | if (isDeclExternC(NewFD)) { | ||||
8893 | NewFD->addAttr(I->second); | ||||
8894 | ExtnameUndeclaredIdentifiers.erase(I); | ||||
8895 | } else | ||||
8896 | Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) | ||||
8897 | << /*Variable*/0 << NewFD; | ||||
8898 | } | ||||
8899 | } | ||||
8900 | |||||
8901 | // Copy the parameter declarations from the declarator D to the function | ||||
8902 | // declaration NewFD, if they are available. First scavenge them into Params. | ||||
8903 | SmallVector<ParmVarDecl*, 16> Params; | ||||
8904 | unsigned FTIIdx; | ||||
8905 | if (D.isFunctionDeclarator(FTIIdx)) { | ||||
8906 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; | ||||
8907 | |||||
8908 | // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs | ||||
8909 | // function that takes no arguments, not a function that takes a | ||||
8910 | // single void argument. | ||||
8911 | // We let through "const void" here because Sema::GetTypeForDeclarator | ||||
8912 | // already checks for that case. | ||||
8913 | if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { | ||||
8914 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | ||||
8915 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | ||||
8916 | assert(Param->getDeclContext() != NewFD && "Was set before ?")((Param->getDeclContext() != NewFD && "Was set before ?" ) ? static_cast<void> (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8916, __PRETTY_FUNCTION__)); | ||||
8917 | Param->setDeclContext(NewFD); | ||||
8918 | Params.push_back(Param); | ||||
8919 | |||||
8920 | if (Param->isInvalidDecl()) | ||||
8921 | NewFD->setInvalidDecl(); | ||||
8922 | } | ||||
8923 | } | ||||
8924 | |||||
8925 | if (!getLangOpts().CPlusPlus) { | ||||
8926 | // In C, find all the tag declarations from the prototype and move them | ||||
8927 | // into the function DeclContext. Remove them from the surrounding tag | ||||
8928 | // injection context of the function, which is typically but not always | ||||
8929 | // the TU. | ||||
8930 | DeclContext *PrototypeTagContext = | ||||
8931 | getTagInjectionContext(NewFD->getLexicalDeclContext()); | ||||
8932 | for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { | ||||
8933 | auto *TD = dyn_cast<TagDecl>(NonParmDecl); | ||||
8934 | |||||
8935 | // We don't want to reparent enumerators. Look at their parent enum | ||||
8936 | // instead. | ||||
8937 | if (!TD) { | ||||
8938 | if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) | ||||
8939 | TD = cast<EnumDecl>(ECD->getDeclContext()); | ||||
8940 | } | ||||
8941 | if (!TD) | ||||
8942 | continue; | ||||
8943 | DeclContext *TagDC = TD->getLexicalDeclContext(); | ||||
8944 | if (!TagDC->containsDecl(TD)) | ||||
8945 | continue; | ||||
8946 | TagDC->removeDecl(TD); | ||||
8947 | TD->setDeclContext(NewFD); | ||||
8948 | NewFD->addDecl(TD); | ||||
8949 | |||||
8950 | // Preserve the lexical DeclContext if it is not the surrounding tag | ||||
8951 | // injection context of the FD. In this example, the semantic context of | ||||
8952 | // E will be f and the lexical context will be S, while both the | ||||
8953 | // semantic and lexical contexts of S will be f: | ||||
8954 | // void f(struct S { enum E { a } f; } s); | ||||
8955 | if (TagDC != PrototypeTagContext) | ||||
8956 | TD->setLexicalDeclContext(TagDC); | ||||
8957 | } | ||||
8958 | } | ||||
8959 | } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { | ||||
8960 | // When we're declaring a function with a typedef, typeof, etc as in the | ||||
8961 | // following example, we'll need to synthesize (unnamed) | ||||
8962 | // parameters for use in the declaration. | ||||
8963 | // | ||||
8964 | // @code | ||||
8965 | // typedef void fn(int); | ||||
8966 | // fn f; | ||||
8967 | // @endcode | ||||
8968 | |||||
8969 | // Synthesize a parameter for each argument type. | ||||
8970 | for (const auto &AI : FT->param_types()) { | ||||
8971 | ParmVarDecl *Param = | ||||
8972 | BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); | ||||
8973 | Param->setScopeInfo(0, Params.size()); | ||||
8974 | Params.push_back(Param); | ||||
8975 | } | ||||
8976 | } else { | ||||
8977 | assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&((R->isFunctionNoProtoType() && NewFD->getNumParams () == 0 && "Should not need args for typedef of non-prototype fn" ) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8978, __PRETTY_FUNCTION__)) | ||||
8978 | "Should not need args for typedef of non-prototype fn")((R->isFunctionNoProtoType() && NewFD->getNumParams () == 0 && "Should not need args for typedef of non-prototype fn" ) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 8978, __PRETTY_FUNCTION__)); | ||||
8979 | } | ||||
8980 | |||||
8981 | // Finally, we know we have the right number of parameters, install them. | ||||
8982 | NewFD->setParams(Params); | ||||
8983 | |||||
8984 | if (D.getDeclSpec().isNoreturnSpecified()) | ||||
8985 | NewFD->addAttr(C11NoReturnAttr::Create(Context, | ||||
8986 | D.getDeclSpec().getNoreturnSpecLoc(), | ||||
8987 | AttributeCommonInfo::AS_Keyword)); | ||||
8988 | |||||
8989 | // Functions returning a variably modified type violate C99 6.7.5.2p2 | ||||
8990 | // because all functions have linkage. | ||||
8991 | if (!NewFD->isInvalidDecl() && | ||||
8992 | NewFD->getReturnType()->isVariablyModifiedType()) { | ||||
8993 | Diag(NewFD->getLocation(), diag::err_vm_func_decl); | ||||
8994 | NewFD->setInvalidDecl(); | ||||
8995 | } | ||||
8996 | |||||
8997 | // Apply an implicit SectionAttr if '#pragma clang section text' is active | ||||
8998 | if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && | ||||
8999 | !NewFD->hasAttr<SectionAttr>()) | ||||
9000 | NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( | ||||
9001 | Context, PragmaClangTextSection.SectionName, | ||||
9002 | PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); | ||||
9003 | |||||
9004 | // Apply an implicit SectionAttr if #pragma code_seg is active. | ||||
9005 | if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && | ||||
9006 | !NewFD->hasAttr<SectionAttr>()) { | ||||
9007 | NewFD->addAttr(SectionAttr::CreateImplicit( | ||||
9008 | Context, CodeSegStack.CurrentValue->getString(), | ||||
9009 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||
9010 | SectionAttr::Declspec_allocate)); | ||||
9011 | if (UnifySection(CodeSegStack.CurrentValue->getString(), | ||||
9012 | ASTContext::PSF_Implicit | ASTContext::PSF_Execute | | ||||
9013 | ASTContext::PSF_Read, | ||||
9014 | NewFD)) | ||||
9015 | NewFD->dropAttr<SectionAttr>(); | ||||
9016 | } | ||||
9017 | |||||
9018 | // Apply an implicit CodeSegAttr from class declspec or | ||||
9019 | // apply an implicit SectionAttr from #pragma code_seg if active. | ||||
9020 | if (!NewFD->hasAttr<CodeSegAttr>()) { | ||||
9021 | if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, | ||||
9022 | D.isFunctionDefinition())) { | ||||
9023 | NewFD->addAttr(SAttr); | ||||
9024 | } | ||||
9025 | } | ||||
9026 | |||||
9027 | // Handle attributes. | ||||
9028 | ProcessDeclAttributes(S, NewFD, D); | ||||
9029 | |||||
9030 | if (getLangOpts().OpenCL) { | ||||
9031 | // OpenCL v1.1 s6.5: Using an address space qualifier in a function return | ||||
9032 | // type declaration will generate a compilation error. | ||||
9033 | LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); | ||||
9034 | if (AddressSpace != LangAS::Default) { | ||||
9035 | Diag(NewFD->getLocation(), | ||||
9036 | diag::err_opencl_return_value_with_address_space); | ||||
9037 | NewFD->setInvalidDecl(); | ||||
9038 | } | ||||
9039 | } | ||||
9040 | |||||
9041 | if (!getLangOpts().CPlusPlus) { | ||||
9042 | // Perform semantic checking on the function declaration. | ||||
9043 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | ||||
9044 | CheckMain(NewFD, D.getDeclSpec()); | ||||
9045 | |||||
9046 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | ||||
9047 | CheckMSVCRTEntryPoint(NewFD); | ||||
9048 | |||||
9049 | if (!NewFD->isInvalidDecl()) | ||||
9050 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | ||||
9051 | isMemberSpecialization)); | ||||
9052 | else if (!Previous.empty()) | ||||
9053 | // Recover gracefully from an invalid redeclaration. | ||||
9054 | D.setRedeclaration(true); | ||||
9055 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9057, __PRETTY_FUNCTION__)) | ||||
9056 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9057, __PRETTY_FUNCTION__)) | ||||
9057 | "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9057, __PRETTY_FUNCTION__)); | ||||
9058 | |||||
9059 | // Diagnose no-prototype function declarations with calling conventions that | ||||
9060 | // don't support variadic calls. Only do this in C and do it after merging | ||||
9061 | // possibly prototyped redeclarations. | ||||
9062 | const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); | ||||
9063 | if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { | ||||
9064 | CallingConv CC = FT->getExtInfo().getCC(); | ||||
9065 | if (!supportsVariadicCall(CC)) { | ||||
9066 | // Windows system headers sometimes accidentally use stdcall without | ||||
9067 | // (void) parameters, so we relax this to a warning. | ||||
9068 | int DiagID = | ||||
9069 | CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; | ||||
9070 | Diag(NewFD->getLocation(), DiagID) | ||||
9071 | << FunctionType::getNameForCallConv(CC); | ||||
9072 | } | ||||
9073 | } | ||||
9074 | |||||
9075 | if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||
9076 | NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
9077 | checkNonTrivialCUnion(NewFD->getReturnType(), | ||||
9078 | NewFD->getReturnTypeSourceRange().getBegin(), | ||||
9079 | NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); | ||||
9080 | } else { | ||||
9081 | // C++11 [replacement.functions]p3: | ||||
9082 | // The program's definitions shall not be specified as inline. | ||||
9083 | // | ||||
9084 | // N.B. We diagnose declarations instead of definitions per LWG issue 2340. | ||||
9085 | // | ||||
9086 | // Suppress the diagnostic if the function is __attribute__((used)), since | ||||
9087 | // that forces an external definition to be emitted. | ||||
9088 | if (D.getDeclSpec().isInlineSpecified() && | ||||
9089 | NewFD->isReplaceableGlobalAllocationFunction() && | ||||
9090 | !NewFD->hasAttr<UsedAttr>()) | ||||
9091 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||
9092 | diag::ext_operator_new_delete_declared_inline) | ||||
9093 | << NewFD->getDeclName(); | ||||
9094 | |||||
9095 | // If the declarator is a template-id, translate the parser's template | ||||
9096 | // argument list into our AST format. | ||||
9097 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||
9098 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; | ||||
9099 | TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); | ||||
9100 | TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); | ||||
9101 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | ||||
9102 | TemplateId->NumArgs); | ||||
9103 | translateTemplateArguments(TemplateArgsPtr, | ||||
9104 | TemplateArgs); | ||||
9105 | |||||
9106 | HasExplicitTemplateArgs = true; | ||||
9107 | |||||
9108 | if (NewFD->isInvalidDecl()) { | ||||
9109 | HasExplicitTemplateArgs = false; | ||||
9110 | } else if (FunctionTemplate) { | ||||
9111 | // Function template with explicit template arguments. | ||||
9112 | Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) | ||||
9113 | << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); | ||||
9114 | |||||
9115 | HasExplicitTemplateArgs = false; | ||||
9116 | } else { | ||||
9117 | assert((isFunctionTemplateSpecialization ||(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9119, __PRETTY_FUNCTION__)) | ||||
9118 | D.getDeclSpec().isFriendSpecified()) &&(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9119, __PRETTY_FUNCTION__)) | ||||
9119 | "should have a 'template<>' for this decl")(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9119, __PRETTY_FUNCTION__)); | ||||
9120 | // "friend void foo<>(int);" is an implicit specialization decl. | ||||
9121 | isFunctionTemplateSpecialization = true; | ||||
9122 | } | ||||
9123 | } else if (isFriend && isFunctionTemplateSpecialization) { | ||||
9124 | // This combination is only possible in a recovery case; the user | ||||
9125 | // wrote something like: | ||||
9126 | // template <> friend void foo(int); | ||||
9127 | // which we're recovering from as if the user had written: | ||||
9128 | // friend void foo<>(int); | ||||
9129 | // Go ahead and fake up a template id. | ||||
9130 | HasExplicitTemplateArgs = true; | ||||
9131 | TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); | ||||
9132 | TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); | ||||
9133 | } | ||||
9134 | |||||
9135 | // We do not add HD attributes to specializations here because | ||||
9136 | // they may have different constexpr-ness compared to their | ||||
9137 | // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, | ||||
9138 | // may end up with different effective targets. Instead, a | ||||
9139 | // specialization inherits its target attributes from its template | ||||
9140 | // in the CheckFunctionTemplateSpecialization() call below. | ||||
9141 | if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) | ||||
9142 | maybeAddCUDAHostDeviceAttrs(NewFD, Previous); | ||||
9143 | |||||
9144 | // If it's a friend (and only if it's a friend), it's possible | ||||
9145 | // that either the specialized function type or the specialized | ||||
9146 | // template is dependent, and therefore matching will fail. In | ||||
9147 | // this case, don't check the specialization yet. | ||||
9148 | bool InstantiationDependent = false; | ||||
9149 | if (isFunctionTemplateSpecialization && isFriend && | ||||
9150 | (NewFD->getType()->isDependentType() || DC->isDependentContext() || | ||||
9151 | TemplateSpecializationType::anyDependentTemplateArguments( | ||||
9152 | TemplateArgs, | ||||
9153 | InstantiationDependent))) { | ||||
9154 | assert(HasExplicitTemplateArgs &&((HasExplicitTemplateArgs && "friend function specialization without template args" ) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9155, __PRETTY_FUNCTION__)) | ||||
9155 | "friend function specialization without template args")((HasExplicitTemplateArgs && "friend function specialization without template args" ) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9155, __PRETTY_FUNCTION__)); | ||||
9156 | if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, | ||||
9157 | Previous)) | ||||
9158 | NewFD->setInvalidDecl(); | ||||
9159 | } else if (isFunctionTemplateSpecialization) { | ||||
9160 | if (CurContext->isDependentContext() && CurContext->isRecord() | ||||
9161 | && !isFriend) { | ||||
9162 | isDependentClassScopeExplicitSpecialization = true; | ||||
9163 | } else if (!NewFD->isInvalidDecl() && | ||||
9164 | CheckFunctionTemplateSpecialization( | ||||
9165 | NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), | ||||
9166 | Previous)) | ||||
9167 | NewFD->setInvalidDecl(); | ||||
9168 | |||||
9169 | // C++ [dcl.stc]p1: | ||||
9170 | // A storage-class-specifier shall not be specified in an explicit | ||||
9171 | // specialization (14.7.3) | ||||
9172 | FunctionTemplateSpecializationInfo *Info = | ||||
9173 | NewFD->getTemplateSpecializationInfo(); | ||||
9174 | if (Info && SC != SC_None) { | ||||
9175 | if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) | ||||
9176 | Diag(NewFD->getLocation(), | ||||
9177 | diag::err_explicit_specialization_inconsistent_storage_class) | ||||
9178 | << SC | ||||
9179 | << FixItHint::CreateRemoval( | ||||
9180 | D.getDeclSpec().getStorageClassSpecLoc()); | ||||
9181 | |||||
9182 | else | ||||
9183 | Diag(NewFD->getLocation(), | ||||
9184 | diag::ext_explicit_specialization_storage_class) | ||||
9185 | << FixItHint::CreateRemoval( | ||||
9186 | D.getDeclSpec().getStorageClassSpecLoc()); | ||||
9187 | } | ||||
9188 | } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { | ||||
9189 | if (CheckMemberSpecialization(NewFD, Previous)) | ||||
9190 | NewFD->setInvalidDecl(); | ||||
9191 | } | ||||
9192 | |||||
9193 | // Perform semantic checking on the function declaration. | ||||
9194 | if (!isDependentClassScopeExplicitSpecialization) { | ||||
9195 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | ||||
9196 | CheckMain(NewFD, D.getDeclSpec()); | ||||
9197 | |||||
9198 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | ||||
9199 | CheckMSVCRTEntryPoint(NewFD); | ||||
9200 | |||||
9201 | if (!NewFD->isInvalidDecl()) | ||||
9202 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | ||||
9203 | isMemberSpecialization)); | ||||
9204 | else if (!Previous.empty()) | ||||
9205 | // Recover gracefully from an invalid redeclaration. | ||||
9206 | D.setRedeclaration(true); | ||||
9207 | } | ||||
9208 | |||||
9209 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9211, __PRETTY_FUNCTION__)) | ||||
9210 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9211, __PRETTY_FUNCTION__)) | ||||
9211 | "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9211, __PRETTY_FUNCTION__)); | ||||
9212 | |||||
9213 | NamedDecl *PrincipalDecl = (FunctionTemplate | ||||
9214 | ? cast<NamedDecl>(FunctionTemplate) | ||||
9215 | : NewFD); | ||||
9216 | |||||
9217 | if (isFriend && NewFD->getPreviousDecl()) { | ||||
9218 | AccessSpecifier Access = AS_public; | ||||
9219 | if (!NewFD->isInvalidDecl()) | ||||
9220 | Access = NewFD->getPreviousDecl()->getAccess(); | ||||
9221 | |||||
9222 | NewFD->setAccess(Access); | ||||
9223 | if (FunctionTemplate) FunctionTemplate->setAccess(Access); | ||||
9224 | } | ||||
9225 | |||||
9226 | if (NewFD->isOverloadedOperator() && !DC->isRecord() && | ||||
9227 | PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) | ||||
9228 | PrincipalDecl->setNonMemberOperator(); | ||||
9229 | |||||
9230 | // If we have a function template, check the template parameter | ||||
9231 | // list. This will check and merge default template arguments. | ||||
9232 | if (FunctionTemplate) { | ||||
9233 | FunctionTemplateDecl *PrevTemplate = | ||||
9234 | FunctionTemplate->getPreviousDecl(); | ||||
9235 | CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), | ||||
9236 | PrevTemplate ? PrevTemplate->getTemplateParameters() | ||||
9237 | : nullptr, | ||||
9238 | D.getDeclSpec().isFriendSpecified() | ||||
9239 | ? (D.isFunctionDefinition() | ||||
9240 | ? TPC_FriendFunctionTemplateDefinition | ||||
9241 | : TPC_FriendFunctionTemplate) | ||||
9242 | : (D.getCXXScopeSpec().isSet() && | ||||
9243 | DC && DC->isRecord() && | ||||
9244 | DC->isDependentContext()) | ||||
9245 | ? TPC_ClassTemplateMember | ||||
9246 | : TPC_FunctionTemplate); | ||||
9247 | } | ||||
9248 | |||||
9249 | if (NewFD->isInvalidDecl()) { | ||||
9250 | // Ignore all the rest of this. | ||||
9251 | } else if (!D.isRedeclaration()) { | ||||
9252 | struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, | ||||
9253 | AddToScope }; | ||||
9254 | // Fake up an access specifier if it's supposed to be a class member. | ||||
9255 | if (isa<CXXRecordDecl>(NewFD->getDeclContext())) | ||||
9256 | NewFD->setAccess(AS_public); | ||||
9257 | |||||
9258 | // Qualified decls generally require a previous declaration. | ||||
9259 | if (D.getCXXScopeSpec().isSet()) { | ||||
9260 | // ...with the major exception of templated-scope or | ||||
9261 | // dependent-scope friend declarations. | ||||
9262 | |||||
9263 | // TODO: we currently also suppress this check in dependent | ||||
9264 | // contexts because (1) the parameter depth will be off when | ||||
9265 | // matching friend templates and (2) we might actually be | ||||
9266 | // selecting a friend based on a dependent factor. But there | ||||
9267 | // are situations where these conditions don't apply and we | ||||
9268 | // can actually do this check immediately. | ||||
9269 | // | ||||
9270 | // Unless the scope is dependent, it's always an error if qualified | ||||
9271 | // redeclaration lookup found nothing at all. Diagnose that now; | ||||
9272 | // nothing will diagnose that error later. | ||||
9273 | if (isFriend && | ||||
9274 | (D.getCXXScopeSpec().getScopeRep()->isDependent() || | ||||
9275 | (!Previous.empty() && CurContext->isDependentContext()))) { | ||||
9276 | // ignore these | ||||
9277 | } else { | ||||
9278 | // The user tried to provide an out-of-line definition for a | ||||
9279 | // function that is a member of a class or namespace, but there | ||||
9280 | // was no such member function declared (C++ [class.mfct]p2, | ||||
9281 | // C++ [namespace.memdef]p2). For example: | ||||
9282 | // | ||||
9283 | // class X { | ||||
9284 | // void f() const; | ||||
9285 | // }; | ||||
9286 | // | ||||
9287 | // void X::f() { } // ill-formed | ||||
9288 | // | ||||
9289 | // Complain about this problem, and attempt to suggest close | ||||
9290 | // matches (e.g., those that differ only in cv-qualifiers and | ||||
9291 | // whether the parameter types are references). | ||||
9292 | |||||
9293 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | ||||
9294 | *this, Previous, NewFD, ExtraArgs, false, nullptr)) { | ||||
9295 | AddToScope = ExtraArgs.AddToScope; | ||||
9296 | return Result; | ||||
9297 | } | ||||
9298 | } | ||||
9299 | |||||
9300 | // Unqualified local friend declarations are required to resolve | ||||
9301 | // to something. | ||||
9302 | } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { | ||||
9303 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | ||||
9304 | *this, Previous, NewFD, ExtraArgs, true, S)) { | ||||
9305 | AddToScope = ExtraArgs.AddToScope; | ||||
9306 | return Result; | ||||
9307 | } | ||||
9308 | } | ||||
9309 | } else if (!D.isFunctionDefinition() && | ||||
9310 | isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && | ||||
9311 | !isFriend && !isFunctionTemplateSpecialization && | ||||
9312 | !isMemberSpecialization) { | ||||
9313 | // An out-of-line member function declaration must also be a | ||||
9314 | // definition (C++ [class.mfct]p2). | ||||
9315 | // Note that this is not the case for explicit specializations of | ||||
9316 | // function templates or member functions of class templates, per | ||||
9317 | // C++ [temp.expl.spec]p2. We also allow these declarations as an | ||||
9318 | // extension for compatibility with old SWIG code which likes to | ||||
9319 | // generate them. | ||||
9320 | Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) | ||||
9321 | << D.getCXXScopeSpec().getRange(); | ||||
9322 | } | ||||
9323 | } | ||||
9324 | |||||
9325 | ProcessPragmaWeak(S, NewFD); | ||||
9326 | checkAttributesAfterMerging(*this, *NewFD); | ||||
9327 | |||||
9328 | AddKnownFunctionAttributes(NewFD); | ||||
9329 | |||||
9330 | if (NewFD->hasAttr<OverloadableAttr>() && | ||||
9331 | !NewFD->getType()->getAs<FunctionProtoType>()) { | ||||
9332 | Diag(NewFD->getLocation(), | ||||
9333 | diag::err_attribute_overloadable_no_prototype) | ||||
9334 | << NewFD; | ||||
9335 | |||||
9336 | // Turn this into a variadic function with no parameters. | ||||
9337 | const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); | ||||
9338 | FunctionProtoType::ExtProtoInfo EPI( | ||||
9339 | Context.getDefaultCallingConvention(true, false)); | ||||
9340 | EPI.Variadic = true; | ||||
9341 | EPI.ExtInfo = FT->getExtInfo(); | ||||
9342 | |||||
9343 | QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); | ||||
9344 | NewFD->setType(R); | ||||
9345 | } | ||||
9346 | |||||
9347 | // If there's a #pragma GCC visibility in scope, and this isn't a class | ||||
9348 | // member, set the visibility of this function. | ||||
9349 | if (!DC->isRecord() && NewFD->isExternallyVisible()) | ||||
9350 | AddPushedVisibilityAttribute(NewFD); | ||||
9351 | |||||
9352 | // If there's a #pragma clang arc_cf_code_audited in scope, consider | ||||
9353 | // marking the function. | ||||
9354 | AddCFAuditedAttribute(NewFD); | ||||
9355 | |||||
9356 | // If this is a function definition, check if we have to apply optnone due to | ||||
9357 | // a pragma. | ||||
9358 | if(D.isFunctionDefinition()) | ||||
9359 | AddRangeBasedOptnone(NewFD); | ||||
9360 | |||||
9361 | // If this is the first declaration of an extern C variable, update | ||||
9362 | // the map of such variables. | ||||
9363 | if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && | ||||
9364 | isIncompleteDeclExternC(*this, NewFD)) | ||||
9365 | RegisterLocallyScopedExternCDecl(NewFD, S); | ||||
9366 | |||||
9367 | // Set this FunctionDecl's range up to the right paren. | ||||
9368 | NewFD->setRangeEnd(D.getSourceRange().getEnd()); | ||||
9369 | |||||
9370 | if (D.isRedeclaration() && !Previous.empty()) { | ||||
9371 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | ||||
9372 | checkDLLAttributeRedeclaration(*this, Prev, NewFD, | ||||
9373 | isMemberSpecialization || | ||||
9374 | isFunctionTemplateSpecialization, | ||||
9375 | D.isFunctionDefinition()); | ||||
9376 | } | ||||
9377 | |||||
9378 | if (getLangOpts().CUDA) { | ||||
9379 | IdentifierInfo *II = NewFD->getIdentifier(); | ||||
9380 | if (II && II->isStr(getCudaConfigureFuncName()) && | ||||
9381 | !NewFD->isInvalidDecl() && | ||||
9382 | NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||
9383 | if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) | ||||
9384 | Diag(NewFD->getLocation(), diag::err_config_scalar_return) | ||||
9385 | << getCudaConfigureFuncName(); | ||||
9386 | Context.setcudaConfigureCallDecl(NewFD); | ||||
9387 | } | ||||
9388 | |||||
9389 | // Variadic functions, other than a *declaration* of printf, are not allowed | ||||
9390 | // in device-side CUDA code, unless someone passed | ||||
9391 | // -fcuda-allow-variadic-functions. | ||||
9392 | if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && | ||||
9393 | (NewFD->hasAttr<CUDADeviceAttr>() || | ||||
9394 | NewFD->hasAttr<CUDAGlobalAttr>()) && | ||||
9395 | !(II && II->isStr("printf") && NewFD->isExternC() && | ||||
9396 | !D.isFunctionDefinition())) { | ||||
9397 | Diag(NewFD->getLocation(), diag::err_variadic_device_fn); | ||||
9398 | } | ||||
9399 | } | ||||
9400 | |||||
9401 | MarkUnusedFileScopedDecl(NewFD); | ||||
9402 | |||||
9403 | |||||
9404 | |||||
9405 | if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { | ||||
9406 | // OpenCL v1.2 s6.8 static is invalid for kernel functions. | ||||
9407 | if ((getLangOpts().OpenCLVersion >= 120) | ||||
9408 | && (SC == SC_Static)) { | ||||
9409 | Diag(D.getIdentifierLoc(), diag::err_static_kernel); | ||||
9410 | D.setInvalidType(); | ||||
9411 | } | ||||
9412 | |||||
9413 | // OpenCL v1.2, s6.9 -- Kernels can only have return type void. | ||||
9414 | if (!NewFD->getReturnType()->isVoidType()) { | ||||
9415 | SourceRange RTRange = NewFD->getReturnTypeSourceRange(); | ||||
9416 | Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) | ||||
9417 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") | ||||
9418 | : FixItHint()); | ||||
9419 | D.setInvalidType(); | ||||
9420 | } | ||||
9421 | |||||
9422 | llvm::SmallPtrSet<const Type *, 16> ValidTypes; | ||||
9423 | for (auto Param : NewFD->parameters()) | ||||
9424 | checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); | ||||
9425 | |||||
9426 | if (getLangOpts().OpenCLCPlusPlus) { | ||||
9427 | if (DC->isRecord()) { | ||||
9428 | Diag(D.getIdentifierLoc(), diag::err_method_kernel); | ||||
9429 | D.setInvalidType(); | ||||
9430 | } | ||||
9431 | if (FunctionTemplate) { | ||||
9432 | Diag(D.getIdentifierLoc(), diag::err_template_kernel); | ||||
9433 | D.setInvalidType(); | ||||
9434 | } | ||||
9435 | } | ||||
9436 | } | ||||
9437 | |||||
9438 | if (getLangOpts().CPlusPlus) { | ||||
9439 | if (FunctionTemplate) { | ||||
9440 | if (NewFD->isInvalidDecl()) | ||||
9441 | FunctionTemplate->setInvalidDecl(); | ||||
9442 | return FunctionTemplate; | ||||
9443 | } | ||||
9444 | |||||
9445 | if (isMemberSpecialization && !NewFD->isInvalidDecl()) | ||||
9446 | CompleteMemberSpecialization(NewFD, Previous); | ||||
9447 | } | ||||
9448 | |||||
9449 | for (const ParmVarDecl *Param : NewFD->parameters()) { | ||||
9450 | QualType PT = Param->getType(); | ||||
9451 | |||||
9452 | // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value | ||||
9453 | // types. | ||||
9454 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { | ||||
9455 | if(const PipeType *PipeTy = PT->getAs<PipeType>()) { | ||||
9456 | QualType ElemTy = PipeTy->getElementType(); | ||||
9457 | if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { | ||||
9458 | Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); | ||||
9459 | D.setInvalidType(); | ||||
9460 | } | ||||
9461 | } | ||||
9462 | } | ||||
9463 | } | ||||
9464 | |||||
9465 | // Here we have an function template explicit specialization at class scope. | ||||
9466 | // The actual specialization will be postponed to template instatiation | ||||
9467 | // time via the ClassScopeFunctionSpecializationDecl node. | ||||
9468 | if (isDependentClassScopeExplicitSpecialization) { | ||||
9469 | ClassScopeFunctionSpecializationDecl *NewSpec = | ||||
9470 | ClassScopeFunctionSpecializationDecl::Create( | ||||
9471 | Context, CurContext, NewFD->getLocation(), | ||||
9472 | cast<CXXMethodDecl>(NewFD), | ||||
9473 | HasExplicitTemplateArgs, TemplateArgs); | ||||
9474 | CurContext->addDecl(NewSpec); | ||||
9475 | AddToScope = false; | ||||
9476 | } | ||||
9477 | |||||
9478 | // Diagnose availability attributes. Availability cannot be used on functions | ||||
9479 | // that are run during load/unload. | ||||
9480 | if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { | ||||
9481 | if (NewFD->hasAttr<ConstructorAttr>()) { | ||||
9482 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | ||||
9483 | << 1; | ||||
9484 | NewFD->dropAttr<AvailabilityAttr>(); | ||||
9485 | } | ||||
9486 | if (NewFD->hasAttr<DestructorAttr>()) { | ||||
9487 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | ||||
9488 | << 2; | ||||
9489 | NewFD->dropAttr<AvailabilityAttr>(); | ||||
9490 | } | ||||
9491 | } | ||||
9492 | |||||
9493 | return NewFD; | ||||
9494 | } | ||||
9495 | |||||
9496 | /// Return a CodeSegAttr from a containing class. The Microsoft docs say | ||||
9497 | /// when __declspec(code_seg) "is applied to a class, all member functions of | ||||
9498 | /// the class and nested classes -- this includes compiler-generated special | ||||
9499 | /// member functions -- are put in the specified segment." | ||||
9500 | /// The actual behavior is a little more complicated. The Microsoft compiler | ||||
9501 | /// won't check outer classes if there is an active value from #pragma code_seg. | ||||
9502 | /// The CodeSeg is always applied from the direct parent but only from outer | ||||
9503 | /// classes when the #pragma code_seg stack is empty. See: | ||||
9504 | /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer | ||||
9505 | /// available since MS has removed the page. | ||||
9506 | static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { | ||||
9507 | const auto *Method = dyn_cast<CXXMethodDecl>(FD); | ||||
9508 | if (!Method) | ||||
9509 | return nullptr; | ||||
9510 | const CXXRecordDecl *Parent = Method->getParent(); | ||||
9511 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | ||||
9512 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | ||||
9513 | NewAttr->setImplicit(true); | ||||
9514 | return NewAttr; | ||||
9515 | } | ||||
9516 | |||||
9517 | // The Microsoft compiler won't check outer classes for the CodeSeg | ||||
9518 | // when the #pragma code_seg stack is active. | ||||
9519 | if (S.CodeSegStack.CurrentValue) | ||||
9520 | return nullptr; | ||||
9521 | |||||
9522 | while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { | ||||
9523 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | ||||
9524 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | ||||
9525 | NewAttr->setImplicit(true); | ||||
9526 | return NewAttr; | ||||
9527 | } | ||||
9528 | } | ||||
9529 | return nullptr; | ||||
9530 | } | ||||
9531 | |||||
9532 | /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a | ||||
9533 | /// containing class. Otherwise it will return implicit SectionAttr if the | ||||
9534 | /// function is a definition and there is an active value on CodeSegStack | ||||
9535 | /// (from the current #pragma code-seg value). | ||||
9536 | /// | ||||
9537 | /// \param FD Function being declared. | ||||
9538 | /// \param IsDefinition Whether it is a definition or just a declarartion. | ||||
9539 | /// \returns A CodeSegAttr or SectionAttr to apply to the function or | ||||
9540 | /// nullptr if no attribute should be added. | ||||
9541 | Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, | ||||
9542 | bool IsDefinition) { | ||||
9543 | if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) | ||||
9544 | return A; | ||||
9545 | if (!FD->hasAttr<SectionAttr>() && IsDefinition && | ||||
9546 | CodeSegStack.CurrentValue) | ||||
9547 | return SectionAttr::CreateImplicit( | ||||
9548 | getASTContext(), CodeSegStack.CurrentValue->getString(), | ||||
9549 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||
9550 | SectionAttr::Declspec_allocate); | ||||
9551 | return nullptr; | ||||
9552 | } | ||||
9553 | |||||
9554 | /// Determines if we can perform a correct type check for \p D as a | ||||
9555 | /// redeclaration of \p PrevDecl. If not, we can generally still perform a | ||||
9556 | /// best-effort check. | ||||
9557 | /// | ||||
9558 | /// \param NewD The new declaration. | ||||
9559 | /// \param OldD The old declaration. | ||||
9560 | /// \param NewT The portion of the type of the new declaration to check. | ||||
9561 | /// \param OldT The portion of the type of the old declaration to check. | ||||
9562 | bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, | ||||
9563 | QualType NewT, QualType OldT) { | ||||
9564 | if (!NewD->getLexicalDeclContext()->isDependentContext()) | ||||
9565 | return true; | ||||
9566 | |||||
9567 | // For dependently-typed local extern declarations and friends, we can't | ||||
9568 | // perform a correct type check in general until instantiation: | ||||
9569 | // | ||||
9570 | // int f(); | ||||
9571 | // template<typename T> void g() { T f(); } | ||||
9572 | // | ||||
9573 | // (valid if g() is only instantiated with T = int). | ||||
9574 | if (NewT->isDependentType() && | ||||
9575 | (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) | ||||
9576 | return false; | ||||
9577 | |||||
9578 | // Similarly, if the previous declaration was a dependent local extern | ||||
9579 | // declaration, we don't really know its type yet. | ||||
9580 | if (OldT->isDependentType() && OldD->isLocalExternDecl()) | ||||
9581 | return false; | ||||
9582 | |||||
9583 | return true; | ||||
9584 | } | ||||
9585 | |||||
9586 | /// Checks if the new declaration declared in dependent context must be | ||||
9587 | /// put in the same redeclaration chain as the specified declaration. | ||||
9588 | /// | ||||
9589 | /// \param D Declaration that is checked. | ||||
9590 | /// \param PrevDecl Previous declaration found with proper lookup method for the | ||||
9591 | /// same declaration name. | ||||
9592 | /// \returns True if D must be added to the redeclaration chain which PrevDecl | ||||
9593 | /// belongs to. | ||||
9594 | /// | ||||
9595 | bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { | ||||
9596 | if (!D->getLexicalDeclContext()->isDependentContext()) | ||||
9597 | return true; | ||||
9598 | |||||
9599 | // Don't chain dependent friend function definitions until instantiation, to | ||||
9600 | // permit cases like | ||||
9601 | // | ||||
9602 | // void func(); | ||||
9603 | // template<typename T> class C1 { friend void func() {} }; | ||||
9604 | // template<typename T> class C2 { friend void func() {} }; | ||||
9605 | // | ||||
9606 | // ... which is valid if only one of C1 and C2 is ever instantiated. | ||||
9607 | // | ||||
9608 | // FIXME: This need only apply to function definitions. For now, we proxy | ||||
9609 | // this by checking for a file-scope function. We do not want this to apply | ||||
9610 | // to friend declarations nominating member functions, because that gets in | ||||
9611 | // the way of access checks. | ||||
9612 | if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) | ||||
9613 | return false; | ||||
9614 | |||||
9615 | auto *VD = dyn_cast<ValueDecl>(D); | ||||
9616 | auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); | ||||
9617 | return !VD || !PrevVD || | ||||
9618 | canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), | ||||
9619 | PrevVD->getType()); | ||||
9620 | } | ||||
9621 | |||||
9622 | /// Check the target attribute of the function for MultiVersion | ||||
9623 | /// validity. | ||||
9624 | /// | ||||
9625 | /// Returns true if there was an error, false otherwise. | ||||
9626 | static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { | ||||
9627 | const auto *TA = FD->getAttr<TargetAttr>(); | ||||
9628 | assert(TA && "MultiVersion Candidate requires a target attribute")((TA && "MultiVersion Candidate requires a target attribute" ) ? static_cast<void> (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9628, __PRETTY_FUNCTION__)); | ||||
9629 | TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); | ||||
9630 | const TargetInfo &TargetInfo = S.Context.getTargetInfo(); | ||||
9631 | enum ErrType { Feature = 0, Architecture = 1 }; | ||||
9632 | |||||
9633 | if (!ParseInfo.Architecture.empty() && | ||||
9634 | !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { | ||||
9635 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||
9636 | << Architecture << ParseInfo.Architecture; | ||||
9637 | return true; | ||||
9638 | } | ||||
9639 | |||||
9640 | for (const auto &Feat : ParseInfo.Features) { | ||||
9641 | auto BareFeat = StringRef{Feat}.substr(1); | ||||
9642 | if (Feat[0] == '-') { | ||||
9643 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||
9644 | << Feature << ("no-" + BareFeat).str(); | ||||
9645 | return true; | ||||
9646 | } | ||||
9647 | |||||
9648 | if (!TargetInfo.validateCpuSupports(BareFeat) || | ||||
9649 | !TargetInfo.isValidFeatureName(BareFeat)) { | ||||
9650 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||
9651 | << Feature << BareFeat; | ||||
9652 | return true; | ||||
9653 | } | ||||
9654 | } | ||||
9655 | return false; | ||||
9656 | } | ||||
9657 | |||||
9658 | static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, | ||||
9659 | MultiVersionKind MVType) { | ||||
9660 | for (const Attr *A : FD->attrs()) { | ||||
9661 | switch (A->getKind()) { | ||||
9662 | case attr::CPUDispatch: | ||||
9663 | case attr::CPUSpecific: | ||||
9664 | if (MVType != MultiVersionKind::CPUDispatch && | ||||
9665 | MVType != MultiVersionKind::CPUSpecific) | ||||
9666 | return true; | ||||
9667 | break; | ||||
9668 | case attr::Target: | ||||
9669 | if (MVType != MultiVersionKind::Target) | ||||
9670 | return true; | ||||
9671 | break; | ||||
9672 | default: | ||||
9673 | return true; | ||||
9674 | } | ||||
9675 | } | ||||
9676 | return false; | ||||
9677 | } | ||||
9678 | |||||
9679 | bool Sema::areMultiversionVariantFunctionsCompatible( | ||||
9680 | const FunctionDecl *OldFD, const FunctionDecl *NewFD, | ||||
9681 | const PartialDiagnostic &NoProtoDiagID, | ||||
9682 | const PartialDiagnosticAt &NoteCausedDiagIDAt, | ||||
9683 | const PartialDiagnosticAt &NoSupportDiagIDAt, | ||||
9684 | const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, | ||||
9685 | bool ConstexprSupported) { | ||||
9686 | enum DoesntSupport { | ||||
9687 | FuncTemplates = 0, | ||||
9688 | VirtFuncs = 1, | ||||
9689 | DeducedReturn = 2, | ||||
9690 | Constructors = 3, | ||||
9691 | Destructors = 4, | ||||
9692 | DeletedFuncs = 5, | ||||
9693 | DefaultedFuncs = 6, | ||||
9694 | ConstexprFuncs = 7, | ||||
9695 | ConstevalFuncs = 8, | ||||
9696 | }; | ||||
9697 | enum Different { | ||||
9698 | CallingConv = 0, | ||||
9699 | ReturnType = 1, | ||||
9700 | ConstexprSpec = 2, | ||||
9701 | InlineSpec = 3, | ||||
9702 | StorageClass = 4, | ||||
9703 | Linkage = 5, | ||||
9704 | }; | ||||
9705 | |||||
9706 | if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { | ||||
9707 | Diag(OldFD->getLocation(), NoProtoDiagID); | ||||
9708 | Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); | ||||
9709 | return true; | ||||
9710 | } | ||||
9711 | |||||
9712 | if (!NewFD->getType()->getAs<FunctionProtoType>()) | ||||
9713 | return Diag(NewFD->getLocation(), NoProtoDiagID); | ||||
9714 | |||||
9715 | if (!TemplatesSupported && | ||||
9716 | NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) | ||||
9717 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||
9718 | << FuncTemplates; | ||||
9719 | |||||
9720 | if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { | ||||
9721 | if (NewCXXFD->isVirtual()) | ||||
9722 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||
9723 | << VirtFuncs; | ||||
9724 | |||||
9725 | if (isa<CXXConstructorDecl>(NewCXXFD)) | ||||
9726 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||
9727 | << Constructors; | ||||
9728 | |||||
9729 | if (isa<CXXDestructorDecl>(NewCXXFD)) | ||||
9730 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||
9731 | << Destructors; | ||||
9732 | } | ||||
9733 | |||||
9734 | if (NewFD->isDeleted()) | ||||
9735 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||
9736 | << DeletedFuncs; | ||||
9737 | |||||
9738 | if (NewFD->isDefaulted()) | ||||
9739 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||
9740 | << DefaultedFuncs; | ||||
9741 | |||||
9742 | if (!ConstexprSupported && NewFD->isConstexpr()) | ||||
9743 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||
9744 | << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); | ||||
9745 | |||||
9746 | QualType NewQType = Context.getCanonicalType(NewFD->getType()); | ||||
9747 | const auto *NewType = cast<FunctionType>(NewQType); | ||||
9748 | QualType NewReturnType = NewType->getReturnType(); | ||||
9749 | |||||
9750 | if (NewReturnType->isUndeducedType()) | ||||
9751 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||
9752 | << DeducedReturn; | ||||
9753 | |||||
9754 | // Ensure the return type is identical. | ||||
9755 | if (OldFD) { | ||||
9756 | QualType OldQType = Context.getCanonicalType(OldFD->getType()); | ||||
9757 | const auto *OldType = cast<FunctionType>(OldQType); | ||||
9758 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | ||||
9759 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | ||||
9760 | |||||
9761 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) | ||||
9762 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; | ||||
9763 | |||||
9764 | QualType OldReturnType = OldType->getReturnType(); | ||||
9765 | |||||
9766 | if (OldReturnType != NewReturnType) | ||||
9767 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; | ||||
9768 | |||||
9769 | if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) | ||||
9770 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; | ||||
9771 | |||||
9772 | if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) | ||||
9773 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; | ||||
9774 | |||||
9775 | if (OldFD->getStorageClass() != NewFD->getStorageClass()) | ||||
9776 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; | ||||
9777 | |||||
9778 | if (OldFD->isExternC() != NewFD->isExternC()) | ||||
9779 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; | ||||
9780 | |||||
9781 | if (CheckEquivalentExceptionSpec( | ||||
9782 | OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), | ||||
9783 | NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) | ||||
9784 | return true; | ||||
9785 | } | ||||
9786 | return false; | ||||
9787 | } | ||||
9788 | |||||
9789 | static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, | ||||
9790 | const FunctionDecl *NewFD, | ||||
9791 | bool CausesMV, | ||||
9792 | MultiVersionKind MVType) { | ||||
9793 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | ||||
9794 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | ||||
9795 | if (OldFD) | ||||
9796 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||
9797 | return true; | ||||
9798 | } | ||||
9799 | |||||
9800 | bool IsCPUSpecificCPUDispatchMVType = | ||||
9801 | MVType == MultiVersionKind::CPUDispatch || | ||||
9802 | MVType == MultiVersionKind::CPUSpecific; | ||||
9803 | |||||
9804 | // For now, disallow all other attributes. These should be opt-in, but | ||||
9805 | // an analysis of all of them is a future FIXME. | ||||
9806 | if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { | ||||
9807 | S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) | ||||
9808 | << IsCPUSpecificCPUDispatchMVType; | ||||
9809 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||
9810 | return true; | ||||
9811 | } | ||||
9812 | |||||
9813 | if (HasNonMultiVersionAttributes(NewFD, MVType)) | ||||
9814 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) | ||||
9815 | << IsCPUSpecificCPUDispatchMVType; | ||||
9816 | |||||
9817 | // Only allow transition to MultiVersion if it hasn't been used. | ||||
9818 | if (OldFD && CausesMV && OldFD->isUsed(false)) | ||||
9819 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); | ||||
9820 | |||||
9821 | return S.areMultiversionVariantFunctionsCompatible( | ||||
9822 | OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), | ||||
9823 | PartialDiagnosticAt(NewFD->getLocation(), | ||||
9824 | S.PDiag(diag::note_multiversioning_caused_here)), | ||||
9825 | PartialDiagnosticAt(NewFD->getLocation(), | ||||
9826 | S.PDiag(diag::err_multiversion_doesnt_support) | ||||
9827 | << IsCPUSpecificCPUDispatchMVType), | ||||
9828 | PartialDiagnosticAt(NewFD->getLocation(), | ||||
9829 | S.PDiag(diag::err_multiversion_diff)), | ||||
9830 | /*TemplatesSupported=*/false, | ||||
9831 | /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType); | ||||
9832 | } | ||||
9833 | |||||
9834 | /// Check the validity of a multiversion function declaration that is the | ||||
9835 | /// first of its kind. Also sets the multiversion'ness' of the function itself. | ||||
9836 | /// | ||||
9837 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||
9838 | /// | ||||
9839 | /// Returns true if there was an error, false otherwise. | ||||
9840 | static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, | ||||
9841 | MultiVersionKind MVType, | ||||
9842 | const TargetAttr *TA) { | ||||
9843 | assert(MVType != MultiVersionKind::None &&((MVType != MultiVersionKind::None && "Function lacks multiversion attribute" ) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9844, __PRETTY_FUNCTION__)) | ||||
9844 | "Function lacks multiversion attribute")((MVType != MultiVersionKind::None && "Function lacks multiversion attribute" ) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 9844, __PRETTY_FUNCTION__)); | ||||
9845 | |||||
9846 | // Target only causes MV if it is default, otherwise this is a normal | ||||
9847 | // function. | ||||
9848 | if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) | ||||
9849 | return false; | ||||
9850 | |||||
9851 | if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { | ||||
9852 | FD->setInvalidDecl(); | ||||
9853 | return true; | ||||
9854 | } | ||||
9855 | |||||
9856 | if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { | ||||
9857 | FD->setInvalidDecl(); | ||||
9858 | return true; | ||||
9859 | } | ||||
9860 | |||||
9861 | FD->setIsMultiVersion(); | ||||
9862 | return false; | ||||
9863 | } | ||||
9864 | |||||
9865 | static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { | ||||
9866 | for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { | ||||
9867 | if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) | ||||
9868 | return true; | ||||
9869 | } | ||||
9870 | |||||
9871 | return false; | ||||
9872 | } | ||||
9873 | |||||
9874 | static bool CheckTargetCausesMultiVersioning( | ||||
9875 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, | ||||
9876 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | ||||
9877 | LookupResult &Previous) { | ||||
9878 | const auto *OldTA = OldFD->getAttr<TargetAttr>(); | ||||
9879 | TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); | ||||
9880 | // Sort order doesn't matter, it just needs to be consistent. | ||||
9881 | llvm::sort(NewParsed.Features); | ||||
9882 | |||||
9883 | // If the old decl is NOT MultiVersioned yet, and we don't cause that | ||||
9884 | // to change, this is a simple redeclaration. | ||||
9885 | if (!NewTA->isDefaultVersion() && | ||||
9886 | (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) | ||||
9887 | return false; | ||||
9888 | |||||
9889 | // Otherwise, this decl causes MultiVersioning. | ||||
9890 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | ||||
9891 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | ||||
9892 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||
9893 | NewFD->setInvalidDecl(); | ||||
9894 | return true; | ||||
9895 | } | ||||
9896 | |||||
9897 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, | ||||
9898 | MultiVersionKind::Target)) { | ||||
9899 | NewFD->setInvalidDecl(); | ||||
9900 | return true; | ||||
9901 | } | ||||
9902 | |||||
9903 | if (CheckMultiVersionValue(S, NewFD)) { | ||||
9904 | NewFD->setInvalidDecl(); | ||||
9905 | return true; | ||||
9906 | } | ||||
9907 | |||||
9908 | // If this is 'default', permit the forward declaration. | ||||
9909 | if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { | ||||
9910 | Redeclaration = true; | ||||
9911 | OldDecl = OldFD; | ||||
9912 | OldFD->setIsMultiVersion(); | ||||
9913 | NewFD->setIsMultiVersion(); | ||||
9914 | return false; | ||||
9915 | } | ||||
9916 | |||||
9917 | if (CheckMultiVersionValue(S, OldFD)) { | ||||
9918 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||
9919 | NewFD->setInvalidDecl(); | ||||
9920 | return true; | ||||
9921 | } | ||||
9922 | |||||
9923 | TargetAttr::ParsedTargetAttr OldParsed = | ||||
9924 | OldTA->parse(std::less<std::string>()); | ||||
9925 | |||||
9926 | if (OldParsed == NewParsed) { | ||||
9927 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | ||||
9928 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||
9929 | NewFD->setInvalidDecl(); | ||||
9930 | return true; | ||||
9931 | } | ||||
9932 | |||||
9933 | for (const auto *FD : OldFD->redecls()) { | ||||
9934 | const auto *CurTA = FD->getAttr<TargetAttr>(); | ||||
9935 | // We allow forward declarations before ANY multiversioning attributes, but | ||||
9936 | // nothing after the fact. | ||||
9937 | if (PreviousDeclsHaveMultiVersionAttribute(FD) && | ||||
9938 | (!CurTA || CurTA->isInherited())) { | ||||
9939 | S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) | ||||
9940 | << 0; | ||||
9941 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||
9942 | NewFD->setInvalidDecl(); | ||||
9943 | return true; | ||||
9944 | } | ||||
9945 | } | ||||
9946 | |||||
9947 | OldFD->setIsMultiVersion(); | ||||
9948 | NewFD->setIsMultiVersion(); | ||||
9949 | Redeclaration = false; | ||||
9950 | MergeTypeWithPrevious = false; | ||||
9951 | OldDecl = nullptr; | ||||
9952 | Previous.clear(); | ||||
9953 | return false; | ||||
9954 | } | ||||
9955 | |||||
9956 | /// Check the validity of a new function declaration being added to an existing | ||||
9957 | /// multiversioned declaration collection. | ||||
9958 | static bool CheckMultiVersionAdditionalDecl( | ||||
9959 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, | ||||
9960 | MultiVersionKind NewMVType, const TargetAttr *NewTA, | ||||
9961 | const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, | ||||
9962 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | ||||
9963 | LookupResult &Previous) { | ||||
9964 | |||||
9965 | MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); | ||||
9966 | // Disallow mixing of multiversioning types. | ||||
9967 | if ((OldMVType == MultiVersionKind::Target && | ||||
9968 | NewMVType != MultiVersionKind::Target) || | ||||
9969 | (NewMVType == MultiVersionKind::Target && | ||||
9970 | OldMVType != MultiVersionKind::Target)) { | ||||
9971 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | ||||
9972 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||
9973 | NewFD->setInvalidDecl(); | ||||
9974 | return true; | ||||
9975 | } | ||||
9976 | |||||
9977 | TargetAttr::ParsedTargetAttr NewParsed; | ||||
9978 | if (NewTA) { | ||||
9979 | NewParsed = NewTA->parse(); | ||||
9980 | llvm::sort(NewParsed.Features); | ||||
9981 | } | ||||
9982 | |||||
9983 | bool UseMemberUsingDeclRules = | ||||
9984 | S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); | ||||
9985 | |||||
9986 | // Next, check ALL non-overloads to see if this is a redeclaration of a | ||||
9987 | // previous member of the MultiVersion set. | ||||
9988 | for (NamedDecl *ND : Previous) { | ||||
9989 | FunctionDecl *CurFD = ND->getAsFunction(); | ||||
9990 | if (!CurFD) | ||||
9991 | continue; | ||||
9992 | if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) | ||||
9993 | continue; | ||||
9994 | |||||
9995 | if (NewMVType == MultiVersionKind::Target) { | ||||
9996 | const auto *CurTA = CurFD->getAttr<TargetAttr>(); | ||||
9997 | if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { | ||||
9998 | NewFD->setIsMultiVersion(); | ||||
9999 | Redeclaration = true; | ||||
10000 | OldDecl = ND; | ||||
10001 | return false; | ||||
10002 | } | ||||
10003 | |||||
10004 | TargetAttr::ParsedTargetAttr CurParsed = | ||||
10005 | CurTA->parse(std::less<std::string>()); | ||||
10006 | if (CurParsed == NewParsed) { | ||||
10007 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | ||||
10008 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||
10009 | NewFD->setInvalidDecl(); | ||||
10010 | return true; | ||||
10011 | } | ||||
10012 | } else { | ||||
10013 | const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); | ||||
10014 | const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); | ||||
10015 | // Handle CPUDispatch/CPUSpecific versions. | ||||
10016 | // Only 1 CPUDispatch function is allowed, this will make it go through | ||||
10017 | // the redeclaration errors. | ||||
10018 | if (NewMVType == MultiVersionKind::CPUDispatch && | ||||
10019 | CurFD->hasAttr<CPUDispatchAttr>()) { | ||||
10020 | if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && | ||||
10021 | std::equal( | ||||
10022 | CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), | ||||
10023 | NewCPUDisp->cpus_begin(), | ||||
10024 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | ||||
10025 | return Cur->getName() == New->getName(); | ||||
10026 | })) { | ||||
10027 | NewFD->setIsMultiVersion(); | ||||
10028 | Redeclaration = true; | ||||
10029 | OldDecl = ND; | ||||
10030 | return false; | ||||
10031 | } | ||||
10032 | |||||
10033 | // If the declarations don't match, this is an error condition. | ||||
10034 | S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); | ||||
10035 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||
10036 | NewFD->setInvalidDecl(); | ||||
10037 | return true; | ||||
10038 | } | ||||
10039 | if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { | ||||
10040 | |||||
10041 | if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && | ||||
10042 | std::equal( | ||||
10043 | CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), | ||||
10044 | NewCPUSpec->cpus_begin(), | ||||
10045 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | ||||
10046 | return Cur->getName() == New->getName(); | ||||
10047 | })) { | ||||
10048 | NewFD->setIsMultiVersion(); | ||||
10049 | Redeclaration = true; | ||||
10050 | OldDecl = ND; | ||||
10051 | return false; | ||||
10052 | } | ||||
10053 | |||||
10054 | // Only 1 version of CPUSpecific is allowed for each CPU. | ||||
10055 | for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { | ||||
10056 | for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { | ||||
10057 | if (CurII == NewII) { | ||||
10058 | S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) | ||||
10059 | << NewII; | ||||
10060 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||
10061 | NewFD->setInvalidDecl(); | ||||
10062 | return true; | ||||
10063 | } | ||||
10064 | } | ||||
10065 | } | ||||
10066 | } | ||||
10067 | // If the two decls aren't the same MVType, there is no possible error | ||||
10068 | // condition. | ||||
10069 | } | ||||
10070 | } | ||||
10071 | |||||
10072 | // Else, this is simply a non-redecl case. Checking the 'value' is only | ||||
10073 | // necessary in the Target case, since The CPUSpecific/Dispatch cases are | ||||
10074 | // handled in the attribute adding step. | ||||
10075 | if (NewMVType == MultiVersionKind::Target && | ||||
10076 | CheckMultiVersionValue(S, NewFD)) { | ||||
10077 | NewFD->setInvalidDecl(); | ||||
10078 | return true; | ||||
10079 | } | ||||
10080 | |||||
10081 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, | ||||
10082 | !OldFD->isMultiVersion(), NewMVType)) { | ||||
10083 | NewFD->setInvalidDecl(); | ||||
10084 | return true; | ||||
10085 | } | ||||
10086 | |||||
10087 | // Permit forward declarations in the case where these two are compatible. | ||||
10088 | if (!OldFD->isMultiVersion()) { | ||||
10089 | OldFD->setIsMultiVersion(); | ||||
10090 | NewFD->setIsMultiVersion(); | ||||
10091 | Redeclaration = true; | ||||
10092 | OldDecl = OldFD; | ||||
10093 | return false; | ||||
10094 | } | ||||
10095 | |||||
10096 | NewFD->setIsMultiVersion(); | ||||
10097 | Redeclaration = false; | ||||
10098 | MergeTypeWithPrevious = false; | ||||
10099 | OldDecl = nullptr; | ||||
10100 | Previous.clear(); | ||||
10101 | return false; | ||||
10102 | } | ||||
10103 | |||||
10104 | |||||
10105 | /// Check the validity of a mulitversion function declaration. | ||||
10106 | /// Also sets the multiversion'ness' of the function itself. | ||||
10107 | /// | ||||
10108 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||
10109 | /// | ||||
10110 | /// Returns true if there was an error, false otherwise. | ||||
10111 | static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, | ||||
10112 | bool &Redeclaration, NamedDecl *&OldDecl, | ||||
10113 | bool &MergeTypeWithPrevious, | ||||
10114 | LookupResult &Previous) { | ||||
10115 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); | ||||
10116 | const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); | ||||
10117 | const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); | ||||
10118 | |||||
10119 | // Mixing Multiversioning types is prohibited. | ||||
10120 | if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || | ||||
10121 | (NewCPUDisp && NewCPUSpec)) { | ||||
10122 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | ||||
10123 | NewFD->setInvalidDecl(); | ||||
10124 | return true; | ||||
10125 | } | ||||
10126 | |||||
10127 | MultiVersionKind MVType = NewFD->getMultiVersionKind(); | ||||
10128 | |||||
10129 | // Main isn't allowed to become a multiversion function, however it IS | ||||
10130 | // permitted to have 'main' be marked with the 'target' optimization hint. | ||||
10131 | if (NewFD->isMain()) { | ||||
10132 | if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || | ||||
10133 | MVType == MultiVersionKind::CPUDispatch || | ||||
10134 | MVType == MultiVersionKind::CPUSpecific) { | ||||
10135 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); | ||||
10136 | NewFD->setInvalidDecl(); | ||||
10137 | return true; | ||||
10138 | } | ||||
10139 | return false; | ||||
10140 | } | ||||
10141 | |||||
10142 | if (!OldDecl || !OldDecl->getAsFunction() || | ||||
10143 | OldDecl->getDeclContext()->getRedeclContext() != | ||||
10144 | NewFD->getDeclContext()->getRedeclContext()) { | ||||
10145 | // If there's no previous declaration, AND this isn't attempting to cause | ||||
10146 | // multiversioning, this isn't an error condition. | ||||
10147 | if (MVType == MultiVersionKind::None) | ||||
10148 | return false; | ||||
10149 | return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); | ||||
10150 | } | ||||
10151 | |||||
10152 | FunctionDecl *OldFD = OldDecl->getAsFunction(); | ||||
10153 | |||||
10154 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) | ||||
10155 | return false; | ||||
10156 | |||||
10157 | if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { | ||||
10158 | S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) | ||||
10159 | << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); | ||||
10160 | NewFD->setInvalidDecl(); | ||||
10161 | return true; | ||||
10162 | } | ||||
10163 | |||||
10164 | // Handle the target potentially causes multiversioning case. | ||||
10165 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) | ||||
10166 | return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, | ||||
10167 | Redeclaration, OldDecl, | ||||
10168 | MergeTypeWithPrevious, Previous); | ||||
10169 | |||||
10170 | // At this point, we have a multiversion function decl (in OldFD) AND an | ||||
10171 | // appropriate attribute in the current function decl. Resolve that these are | ||||
10172 | // still compatible with previous declarations. | ||||
10173 | return CheckMultiVersionAdditionalDecl( | ||||
10174 | S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, | ||||
10175 | OldDecl, MergeTypeWithPrevious, Previous); | ||||
10176 | } | ||||
10177 | |||||
10178 | /// Perform semantic checking of a new function declaration. | ||||
10179 | /// | ||||
10180 | /// Performs semantic analysis of the new function declaration | ||||
10181 | /// NewFD. This routine performs all semantic checking that does not | ||||
10182 | /// require the actual declarator involved in the declaration, and is | ||||
10183 | /// used both for the declaration of functions as they are parsed | ||||
10184 | /// (called via ActOnDeclarator) and for the declaration of functions | ||||
10185 | /// that have been instantiated via C++ template instantiation (called | ||||
10186 | /// via InstantiateDecl). | ||||
10187 | /// | ||||
10188 | /// \param IsMemberSpecialization whether this new function declaration is | ||||
10189 | /// a member specialization (that replaces any definition provided by the | ||||
10190 | /// previous declaration). | ||||
10191 | /// | ||||
10192 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||
10193 | /// | ||||
10194 | /// \returns true if the function declaration is a redeclaration. | ||||
10195 | bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, | ||||
10196 | LookupResult &Previous, | ||||
10197 | bool IsMemberSpecialization) { | ||||
10198 | assert(!NewFD->getReturnType()->isVariablyModifiedType() &&((!NewFD->getReturnType()->isVariablyModifiedType() && "Variably modified return types are not handled here") ? static_cast <void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10199, __PRETTY_FUNCTION__)) | ||||
10199 | "Variably modified return types are not handled here")((!NewFD->getReturnType()->isVariablyModifiedType() && "Variably modified return types are not handled here") ? static_cast <void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10199, __PRETTY_FUNCTION__)); | ||||
10200 | |||||
10201 | // Determine whether the type of this function should be merged with | ||||
10202 | // a previous visible declaration. This never happens for functions in C++, | ||||
10203 | // and always happens in C if the previous declaration was visible. | ||||
10204 | bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && | ||||
10205 | !Previous.isShadowed(); | ||||
10206 | |||||
10207 | bool Redeclaration = false; | ||||
10208 | NamedDecl *OldDecl = nullptr; | ||||
10209 | bool MayNeedOverloadableChecks = false; | ||||
10210 | |||||
10211 | // Merge or overload the declaration with an existing declaration of | ||||
10212 | // the same name, if appropriate. | ||||
10213 | if (!Previous.empty()) { | ||||
10214 | // Determine whether NewFD is an overload of PrevDecl or | ||||
10215 | // a declaration that requires merging. If it's an overload, | ||||
10216 | // there's no more work to do here; we'll just add the new | ||||
10217 | // function to the scope. | ||||
10218 | if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { | ||||
10219 | NamedDecl *Candidate = Previous.getRepresentativeDecl(); | ||||
10220 | if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { | ||||
10221 | Redeclaration = true; | ||||
10222 | OldDecl = Candidate; | ||||
10223 | } | ||||
10224 | } else { | ||||
10225 | MayNeedOverloadableChecks = true; | ||||
10226 | switch (CheckOverload(S, NewFD, Previous, OldDecl, | ||||
10227 | /*NewIsUsingDecl*/ false)) { | ||||
10228 | case Ovl_Match: | ||||
10229 | Redeclaration = true; | ||||
10230 | break; | ||||
10231 | |||||
10232 | case Ovl_NonFunction: | ||||
10233 | Redeclaration = true; | ||||
10234 | break; | ||||
10235 | |||||
10236 | case Ovl_Overload: | ||||
10237 | Redeclaration = false; | ||||
10238 | break; | ||||
10239 | } | ||||
10240 | } | ||||
10241 | } | ||||
10242 | |||||
10243 | // Check for a previous extern "C" declaration with this name. | ||||
10244 | if (!Redeclaration && | ||||
10245 | checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { | ||||
10246 | if (!Previous.empty()) { | ||||
10247 | // This is an extern "C" declaration with the same name as a previous | ||||
10248 | // declaration, and thus redeclares that entity... | ||||
10249 | Redeclaration = true; | ||||
10250 | OldDecl = Previous.getFoundDecl(); | ||||
10251 | MergeTypeWithPrevious = false; | ||||
10252 | |||||
10253 | // ... except in the presence of __attribute__((overloadable)). | ||||
10254 | if (OldDecl->hasAttr<OverloadableAttr>() || | ||||
10255 | NewFD->hasAttr<OverloadableAttr>()) { | ||||
10256 | if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { | ||||
10257 | MayNeedOverloadableChecks = true; | ||||
10258 | Redeclaration = false; | ||||
10259 | OldDecl = nullptr; | ||||
10260 | } | ||||
10261 | } | ||||
10262 | } | ||||
10263 | } | ||||
10264 | |||||
10265 | if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, | ||||
10266 | MergeTypeWithPrevious, Previous)) | ||||
10267 | return Redeclaration; | ||||
10268 | |||||
10269 | // C++11 [dcl.constexpr]p8: | ||||
10270 | // A constexpr specifier for a non-static member function that is not | ||||
10271 | // a constructor declares that member function to be const. | ||||
10272 | // | ||||
10273 | // This needs to be delayed until we know whether this is an out-of-line | ||||
10274 | // definition of a static member function. | ||||
10275 | // | ||||
10276 | // This rule is not present in C++1y, so we produce a backwards | ||||
10277 | // compatibility warning whenever it happens in C++11. | ||||
10278 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | ||||
10279 | if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && | ||||
10280 | !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && | ||||
10281 | !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { | ||||
10282 | CXXMethodDecl *OldMD = nullptr; | ||||
10283 | if (OldDecl) | ||||
10284 | OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); | ||||
10285 | if (!OldMD || !OldMD->isStatic()) { | ||||
10286 | const FunctionProtoType *FPT = | ||||
10287 | MD->getType()->castAs<FunctionProtoType>(); | ||||
10288 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||
10289 | EPI.TypeQuals.addConst(); | ||||
10290 | MD->setType(Context.getFunctionType(FPT->getReturnType(), | ||||
10291 | FPT->getParamTypes(), EPI)); | ||||
10292 | |||||
10293 | // Warn that we did this, if we're not performing template instantiation. | ||||
10294 | // In that case, we'll have warned already when the template was defined. | ||||
10295 | if (!inTemplateInstantiation()) { | ||||
10296 | SourceLocation AddConstLoc; | ||||
10297 | if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() | ||||
10298 | .IgnoreParens().getAs<FunctionTypeLoc>()) | ||||
10299 | AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); | ||||
10300 | |||||
10301 | Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) | ||||
10302 | << FixItHint::CreateInsertion(AddConstLoc, " const"); | ||||
10303 | } | ||||
10304 | } | ||||
10305 | } | ||||
10306 | |||||
10307 | if (Redeclaration) { | ||||
10308 | // NewFD and OldDecl represent declarations that need to be | ||||
10309 | // merged. | ||||
10310 | if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { | ||||
10311 | NewFD->setInvalidDecl(); | ||||
10312 | return Redeclaration; | ||||
10313 | } | ||||
10314 | |||||
10315 | Previous.clear(); | ||||
10316 | Previous.addDecl(OldDecl); | ||||
10317 | |||||
10318 | if (FunctionTemplateDecl *OldTemplateDecl = | ||||
10319 | dyn_cast<FunctionTemplateDecl>(OldDecl)) { | ||||
10320 | auto *OldFD = OldTemplateDecl->getTemplatedDecl(); | ||||
10321 | FunctionTemplateDecl *NewTemplateDecl | ||||
10322 | = NewFD->getDescribedFunctionTemplate(); | ||||
10323 | assert(NewTemplateDecl && "Template/non-template mismatch")((NewTemplateDecl && "Template/non-template mismatch" ) ? static_cast<void> (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10323, __PRETTY_FUNCTION__)); | ||||
10324 | |||||
10325 | // The call to MergeFunctionDecl above may have created some state in | ||||
10326 | // NewTemplateDecl that needs to be merged with OldTemplateDecl before we | ||||
10327 | // can add it as a redeclaration. | ||||
10328 | NewTemplateDecl->mergePrevDecl(OldTemplateDecl); | ||||
10329 | |||||
10330 | NewFD->setPreviousDeclaration(OldFD); | ||||
10331 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | ||||
10332 | if (NewFD->isCXXClassMember()) { | ||||
10333 | NewFD->setAccess(OldTemplateDecl->getAccess()); | ||||
10334 | NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); | ||||
10335 | } | ||||
10336 | |||||
10337 | // If this is an explicit specialization of a member that is a function | ||||
10338 | // template, mark it as a member specialization. | ||||
10339 | if (IsMemberSpecialization && | ||||
10340 | NewTemplateDecl->getInstantiatedFromMemberTemplate()) { | ||||
10341 | NewTemplateDecl->setMemberSpecialization(); | ||||
10342 | assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast <void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10342, __PRETTY_FUNCTION__)); | ||||
10343 | // Explicit specializations of a member template do not inherit deleted | ||||
10344 | // status from the parent member template that they are specializing. | ||||
10345 | if (OldFD->isDeleted()) { | ||||
10346 | // FIXME: This assert will not hold in the presence of modules. | ||||
10347 | assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void > (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10347, __PRETTY_FUNCTION__)); | ||||
10348 | // FIXME: We need an update record for this AST mutation. | ||||
10349 | OldFD->setDeletedAsWritten(false); | ||||
10350 | } | ||||
10351 | } | ||||
10352 | |||||
10353 | } else { | ||||
10354 | if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { | ||||
10355 | auto *OldFD = cast<FunctionDecl>(OldDecl); | ||||
10356 | // This needs to happen first so that 'inline' propagates. | ||||
10357 | NewFD->setPreviousDeclaration(OldFD); | ||||
10358 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | ||||
10359 | if (NewFD->isCXXClassMember()) | ||||
10360 | NewFD->setAccess(OldFD->getAccess()); | ||||
10361 | } | ||||
10362 | } | ||||
10363 | } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && | ||||
10364 | !NewFD->getAttr<OverloadableAttr>()) { | ||||
10365 | assert((Previous.empty() ||(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10370, __PRETTY_FUNCTION__)) | ||||
10366 | llvm::any_of(Previous,(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10370, __PRETTY_FUNCTION__)) | ||||
10367 | [](const NamedDecl *ND) {(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10370, __PRETTY_FUNCTION__)) | ||||
10368 | return ND->hasAttr<OverloadableAttr>();(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10370, __PRETTY_FUNCTION__)) | ||||
10369 | })) &&(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10370, __PRETTY_FUNCTION__)) | ||||
10370 | "Non-redecls shouldn't happen without overloadable present")(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10370, __PRETTY_FUNCTION__)); | ||||
10371 | |||||
10372 | auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { | ||||
10373 | const auto *FD = dyn_cast<FunctionDecl>(ND); | ||||
10374 | return FD && !FD->hasAttr<OverloadableAttr>(); | ||||
10375 | }); | ||||
10376 | |||||
10377 | if (OtherUnmarkedIter != Previous.end()) { | ||||
10378 | Diag(NewFD->getLocation(), | ||||
10379 | diag::err_attribute_overloadable_multiple_unmarked_overloads); | ||||
10380 | Diag((*OtherUnmarkedIter)->getLocation(), | ||||
10381 | diag::note_attribute_overloadable_prev_overload) | ||||
10382 | << false; | ||||
10383 | |||||
10384 | NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); | ||||
10385 | } | ||||
10386 | } | ||||
10387 | |||||
10388 | // Semantic checking for this function declaration (in isolation). | ||||
10389 | |||||
10390 | if (getLangOpts().CPlusPlus) { | ||||
10391 | // C++-specific checks. | ||||
10392 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { | ||||
10393 | CheckConstructor(Constructor); | ||||
10394 | } else if (CXXDestructorDecl *Destructor = | ||||
10395 | dyn_cast<CXXDestructorDecl>(NewFD)) { | ||||
10396 | CXXRecordDecl *Record = Destructor->getParent(); | ||||
10397 | QualType ClassType = Context.getTypeDeclType(Record); | ||||
10398 | |||||
10399 | // FIXME: Shouldn't we be able to perform this check even when the class | ||||
10400 | // type is dependent? Both gcc and edg can handle that. | ||||
10401 | if (!ClassType->isDependentType()) { | ||||
10402 | DeclarationName Name | ||||
10403 | = Context.DeclarationNames.getCXXDestructorName( | ||||
10404 | Context.getCanonicalType(ClassType)); | ||||
10405 | if (NewFD->getDeclName() != Name) { | ||||
10406 | Diag(NewFD->getLocation(), diag::err_destructor_name); | ||||
10407 | NewFD->setInvalidDecl(); | ||||
10408 | return Redeclaration; | ||||
10409 | } | ||||
10410 | } | ||||
10411 | } else if (CXXConversionDecl *Conversion | ||||
10412 | = dyn_cast<CXXConversionDecl>(NewFD)) { | ||||
10413 | ActOnConversionDeclarator(Conversion); | ||||
10414 | } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { | ||||
10415 | if (auto *TD = Guide->getDescribedFunctionTemplate()) | ||||
10416 | CheckDeductionGuideTemplate(TD); | ||||
10417 | |||||
10418 | // A deduction guide is not on the list of entities that can be | ||||
10419 | // explicitly specialized. | ||||
10420 | if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) | ||||
10421 | Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) | ||||
10422 | << /*explicit specialization*/ 1; | ||||
10423 | } | ||||
10424 | |||||
10425 | // Find any virtual functions that this function overrides. | ||||
10426 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { | ||||
10427 | if (!Method->isFunctionTemplateSpecialization() && | ||||
10428 | !Method->getDescribedFunctionTemplate() && | ||||
10429 | Method->isCanonicalDecl()) { | ||||
10430 | if (AddOverriddenMethods(Method->getParent(), Method)) { | ||||
10431 | // If the function was marked as "static", we have a problem. | ||||
10432 | if (NewFD->getStorageClass() == SC_Static) { | ||||
10433 | ReportOverrides(*this, diag::err_static_overrides_virtual, Method); | ||||
10434 | } | ||||
10435 | } | ||||
10436 | } | ||||
10437 | |||||
10438 | if (Method->isStatic()) | ||||
10439 | checkThisInStaticMemberFunctionType(Method); | ||||
10440 | } | ||||
10441 | |||||
10442 | // Extra checking for C++ overloaded operators (C++ [over.oper]). | ||||
10443 | if (NewFD->isOverloadedOperator() && | ||||
10444 | CheckOverloadedOperatorDeclaration(NewFD)) { | ||||
10445 | NewFD->setInvalidDecl(); | ||||
10446 | return Redeclaration; | ||||
10447 | } | ||||
10448 | |||||
10449 | // Extra checking for C++0x literal operators (C++0x [over.literal]). | ||||
10450 | if (NewFD->getLiteralIdentifier() && | ||||
10451 | CheckLiteralOperatorDeclaration(NewFD)) { | ||||
10452 | NewFD->setInvalidDecl(); | ||||
10453 | return Redeclaration; | ||||
10454 | } | ||||
10455 | |||||
10456 | // In C++, check default arguments now that we have merged decls. Unless | ||||
10457 | // the lexical context is the class, because in this case this is done | ||||
10458 | // during delayed parsing anyway. | ||||
10459 | if (!CurContext->isRecord()) | ||||
10460 | CheckCXXDefaultArguments(NewFD); | ||||
10461 | |||||
10462 | // If this function declares a builtin function, check the type of this | ||||
10463 | // declaration against the expected type for the builtin. | ||||
10464 | if (unsigned BuiltinID = NewFD->getBuiltinID()) { | ||||
10465 | ASTContext::GetBuiltinTypeError Error; | ||||
10466 | LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); | ||||
10467 | QualType T = Context.GetBuiltinType(BuiltinID, Error); | ||||
10468 | // If the type of the builtin differs only in its exception | ||||
10469 | // specification, that's OK. | ||||
10470 | // FIXME: If the types do differ in this way, it would be better to | ||||
10471 | // retain the 'noexcept' form of the type. | ||||
10472 | if (!T.isNull() && | ||||
10473 | !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, | ||||
10474 | NewFD->getType())) | ||||
10475 | // The type of this function differs from the type of the builtin, | ||||
10476 | // so forget about the builtin entirely. | ||||
10477 | Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); | ||||
10478 | } | ||||
10479 | |||||
10480 | // If this function is declared as being extern "C", then check to see if | ||||
10481 | // the function returns a UDT (class, struct, or union type) that is not C | ||||
10482 | // compatible, and if it does, warn the user. | ||||
10483 | // But, issue any diagnostic on the first declaration only. | ||||
10484 | if (Previous.empty() && NewFD->isExternC()) { | ||||
10485 | QualType R = NewFD->getReturnType(); | ||||
10486 | if (R->isIncompleteType() && !R->isVoidType()) | ||||
10487 | Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) | ||||
10488 | << NewFD << R; | ||||
10489 | else if (!R.isPODType(Context) && !R->isVoidType() && | ||||
10490 | !R->isObjCObjectPointerType()) | ||||
10491 | Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; | ||||
10492 | } | ||||
10493 | |||||
10494 | // C++1z [dcl.fct]p6: | ||||
10495 | // [...] whether the function has a non-throwing exception-specification | ||||
10496 | // [is] part of the function type | ||||
10497 | // | ||||
10498 | // This results in an ABI break between C++14 and C++17 for functions whose | ||||
10499 | // declared type includes an exception-specification in a parameter or | ||||
10500 | // return type. (Exception specifications on the function itself are OK in | ||||
10501 | // most cases, and exception specifications are not permitted in most other | ||||
10502 | // contexts where they could make it into a mangling.) | ||||
10503 | if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { | ||||
10504 | auto HasNoexcept = [&](QualType T) -> bool { | ||||
10505 | // Strip off declarator chunks that could be between us and a function | ||||
10506 | // type. We don't need to look far, exception specifications are very | ||||
10507 | // restricted prior to C++17. | ||||
10508 | if (auto *RT = T->getAs<ReferenceType>()) | ||||
10509 | T = RT->getPointeeType(); | ||||
10510 | else if (T->isAnyPointerType()) | ||||
10511 | T = T->getPointeeType(); | ||||
10512 | else if (auto *MPT = T->getAs<MemberPointerType>()) | ||||
10513 | T = MPT->getPointeeType(); | ||||
10514 | if (auto *FPT = T->getAs<FunctionProtoType>()) | ||||
10515 | if (FPT->isNothrow()) | ||||
10516 | return true; | ||||
10517 | return false; | ||||
10518 | }; | ||||
10519 | |||||
10520 | auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); | ||||
10521 | bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); | ||||
10522 | for (QualType T : FPT->param_types()) | ||||
10523 | AnyNoexcept |= HasNoexcept(T); | ||||
10524 | if (AnyNoexcept) | ||||
10525 | Diag(NewFD->getLocation(), | ||||
10526 | diag::warn_cxx17_compat_exception_spec_in_signature) | ||||
10527 | << NewFD; | ||||
10528 | } | ||||
10529 | |||||
10530 | if (!Redeclaration && LangOpts.CUDA) | ||||
10531 | checkCUDATargetOverload(NewFD, Previous); | ||||
10532 | } | ||||
10533 | return Redeclaration; | ||||
10534 | } | ||||
10535 | |||||
10536 | void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { | ||||
10537 | // C++11 [basic.start.main]p3: | ||||
10538 | // A program that [...] declares main to be inline, static or | ||||
10539 | // constexpr is ill-formed. | ||||
10540 | // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall | ||||
10541 | // appear in a declaration of main. | ||||
10542 | // static main is not an error under C99, but we should warn about it. | ||||
10543 | // We accept _Noreturn main as an extension. | ||||
10544 | if (FD->getStorageClass() == SC_Static) | ||||
10545 | Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus | ||||
10546 | ? diag::err_static_main : diag::warn_static_main) | ||||
10547 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||
10548 | if (FD->isInlineSpecified()) | ||||
10549 | Diag(DS.getInlineSpecLoc(), diag::err_inline_main) | ||||
10550 | << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); | ||||
10551 | if (DS.isNoreturnSpecified()) { | ||||
10552 | SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); | ||||
10553 | SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); | ||||
10554 | Diag(NoreturnLoc, diag::ext_noreturn_main); | ||||
10555 | Diag(NoreturnLoc, diag::note_main_remove_noreturn) | ||||
10556 | << FixItHint::CreateRemoval(NoreturnRange); | ||||
10557 | } | ||||
10558 | if (FD->isConstexpr()) { | ||||
10559 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) | ||||
10560 | << FD->isConsteval() | ||||
10561 | << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); | ||||
10562 | FD->setConstexprKind(CSK_unspecified); | ||||
10563 | } | ||||
10564 | |||||
10565 | if (getLangOpts().OpenCL) { | ||||
10566 | Diag(FD->getLocation(), diag::err_opencl_no_main) | ||||
10567 | << FD->hasAttr<OpenCLKernelAttr>(); | ||||
10568 | FD->setInvalidDecl(); | ||||
10569 | return; | ||||
10570 | } | ||||
10571 | |||||
10572 | QualType T = FD->getType(); | ||||
10573 | assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10573, __PRETTY_FUNCTION__)); | ||||
10574 | const FunctionType* FT = T->castAs<FunctionType>(); | ||||
10575 | |||||
10576 | // Set default calling convention for main() | ||||
10577 | if (FT->getCallConv() != CC_C) { | ||||
10578 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); | ||||
10579 | FD->setType(QualType(FT, 0)); | ||||
10580 | T = Context.getCanonicalType(FD->getType()); | ||||
10581 | } | ||||
10582 | |||||
10583 | if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { | ||||
10584 | // In C with GNU extensions we allow main() to have non-integer return | ||||
10585 | // type, but we should warn about the extension, and we disable the | ||||
10586 | // implicit-return-zero rule. | ||||
10587 | |||||
10588 | // GCC in C mode accepts qualified 'int'. | ||||
10589 | if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) | ||||
10590 | FD->setHasImplicitReturnZero(true); | ||||
10591 | else { | ||||
10592 | Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); | ||||
10593 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | ||||
10594 | if (RTRange.isValid()) | ||||
10595 | Diag(RTRange.getBegin(), diag::note_main_change_return_type) | ||||
10596 | << FixItHint::CreateReplacement(RTRange, "int"); | ||||
10597 | } | ||||
10598 | } else { | ||||
10599 | // In C and C++, main magically returns 0 if you fall off the end; | ||||
10600 | // set the flag which tells us that. | ||||
10601 | // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. | ||||
10602 | |||||
10603 | // All the standards say that main() should return 'int'. | ||||
10604 | if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) | ||||
10605 | FD->setHasImplicitReturnZero(true); | ||||
10606 | else { | ||||
10607 | // Otherwise, this is just a flat-out error. | ||||
10608 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | ||||
10609 | Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) | ||||
10610 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") | ||||
10611 | : FixItHint()); | ||||
10612 | FD->setInvalidDecl(true); | ||||
10613 | } | ||||
10614 | } | ||||
10615 | |||||
10616 | // Treat protoless main() as nullary. | ||||
10617 | if (isa<FunctionNoProtoType>(FT)) return; | ||||
10618 | |||||
10619 | const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); | ||||
10620 | unsigned nparams = FTP->getNumParams(); | ||||
10621 | assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10621, __PRETTY_FUNCTION__)); | ||||
10622 | |||||
10623 | bool HasExtraParameters = (nparams > 3); | ||||
10624 | |||||
10625 | if (FTP->isVariadic()) { | ||||
10626 | Diag(FD->getLocation(), diag::ext_variadic_main); | ||||
10627 | // FIXME: if we had information about the location of the ellipsis, we | ||||
10628 | // could add a FixIt hint to remove it as a parameter. | ||||
10629 | } | ||||
10630 | |||||
10631 | // Darwin passes an undocumented fourth argument of type char**. If | ||||
10632 | // other platforms start sprouting these, the logic below will start | ||||
10633 | // getting shifty. | ||||
10634 | if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) | ||||
10635 | HasExtraParameters = false; | ||||
10636 | |||||
10637 | if (HasExtraParameters) { | ||||
10638 | Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; | ||||
10639 | FD->setInvalidDecl(true); | ||||
10640 | nparams = 3; | ||||
10641 | } | ||||
10642 | |||||
10643 | // FIXME: a lot of the following diagnostics would be improved | ||||
10644 | // if we had some location information about types. | ||||
10645 | |||||
10646 | QualType CharPP = | ||||
10647 | Context.getPointerType(Context.getPointerType(Context.CharTy)); | ||||
10648 | QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; | ||||
10649 | |||||
10650 | for (unsigned i = 0; i < nparams; ++i) { | ||||
10651 | QualType AT = FTP->getParamType(i); | ||||
10652 | |||||
10653 | bool mismatch = true; | ||||
10654 | |||||
10655 | if (Context.hasSameUnqualifiedType(AT, Expected[i])) | ||||
10656 | mismatch = false; | ||||
10657 | else if (Expected[i] == CharPP) { | ||||
10658 | // As an extension, the following forms are okay: | ||||
10659 | // char const ** | ||||
10660 | // char const * const * | ||||
10661 | // char * const * | ||||
10662 | |||||
10663 | QualifierCollector qs; | ||||
10664 | const PointerType* PT; | ||||
10665 | if ((PT = qs.strip(AT)->getAs<PointerType>()) && | ||||
10666 | (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && | ||||
10667 | Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), | ||||
10668 | Context.CharTy)) { | ||||
10669 | qs.removeConst(); | ||||
10670 | mismatch = !qs.empty(); | ||||
10671 | } | ||||
10672 | } | ||||
10673 | |||||
10674 | if (mismatch) { | ||||
10675 | Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; | ||||
10676 | // TODO: suggest replacing given type with expected type | ||||
10677 | FD->setInvalidDecl(true); | ||||
10678 | } | ||||
10679 | } | ||||
10680 | |||||
10681 | if (nparams == 1 && !FD->isInvalidDecl()) { | ||||
10682 | Diag(FD->getLocation(), diag::warn_main_one_arg); | ||||
10683 | } | ||||
10684 | |||||
10685 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | ||||
10686 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | ||||
10687 | FD->setInvalidDecl(); | ||||
10688 | } | ||||
10689 | } | ||||
10690 | |||||
10691 | void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { | ||||
10692 | QualType T = FD->getType(); | ||||
10693 | assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 10693, __PRETTY_FUNCTION__)); | ||||
10694 | const FunctionType *FT = T->castAs<FunctionType>(); | ||||
10695 | |||||
10696 | // Set an implicit return of 'zero' if the function can return some integral, | ||||
10697 | // enumeration, pointer or nullptr type. | ||||
10698 | if (FT->getReturnType()->isIntegralOrEnumerationType() || | ||||
10699 | FT->getReturnType()->isAnyPointerType() || | ||||
10700 | FT->getReturnType()->isNullPtrType()) | ||||
10701 | // DllMain is exempt because a return value of zero means it failed. | ||||
10702 | if (FD->getName() != "DllMain") | ||||
10703 | FD->setHasImplicitReturnZero(true); | ||||
10704 | |||||
10705 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | ||||
10706 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | ||||
10707 | FD->setInvalidDecl(); | ||||
10708 | } | ||||
10709 | } | ||||
10710 | |||||
10711 | bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { | ||||
10712 | // FIXME: Need strict checking. In C89, we need to check for | ||||
10713 | // any assignment, increment, decrement, function-calls, or | ||||
10714 | // commas outside of a sizeof. In C99, it's the same list, | ||||
10715 | // except that the aforementioned are allowed in unevaluated | ||||
10716 | // expressions. Everything else falls under the | ||||
10717 | // "may accept other forms of constant expressions" exception. | ||||
10718 | // (We never end up here for C++, so the constant expression | ||||
10719 | // rules there don't matter.) | ||||
10720 | const Expr *Culprit; | ||||
10721 | if (Init->isConstantInitializer(Context, false, &Culprit)) | ||||
10722 | return false; | ||||
10723 | Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) | ||||
10724 | << Culprit->getSourceRange(); | ||||
10725 | return true; | ||||
10726 | } | ||||
10727 | |||||
10728 | namespace { | ||||
10729 | // Visits an initialization expression to see if OrigDecl is evaluated in | ||||
10730 | // its own initialization and throws a warning if it does. | ||||
10731 | class SelfReferenceChecker | ||||
10732 | : public EvaluatedExprVisitor<SelfReferenceChecker> { | ||||
10733 | Sema &S; | ||||
10734 | Decl *OrigDecl; | ||||
10735 | bool isRecordType; | ||||
10736 | bool isPODType; | ||||
10737 | bool isReferenceType; | ||||
10738 | |||||
10739 | bool isInitList; | ||||
10740 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | ||||
10741 | |||||
10742 | public: | ||||
10743 | typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; | ||||
10744 | |||||
10745 | SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), | ||||
10746 | S(S), OrigDecl(OrigDecl) { | ||||
10747 | isPODType = false; | ||||
10748 | isRecordType = false; | ||||
10749 | isReferenceType = false; | ||||
10750 | isInitList = false; | ||||
10751 | if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { | ||||
10752 | isPODType = VD->getType().isPODType(S.Context); | ||||
10753 | isRecordType = VD->getType()->isRecordType(); | ||||
10754 | isReferenceType = VD->getType()->isReferenceType(); | ||||
10755 | } | ||||
10756 | } | ||||
10757 | |||||
10758 | // For most expressions, just call the visitor. For initializer lists, | ||||
10759 | // track the index of the field being initialized since fields are | ||||
10760 | // initialized in order allowing use of previously initialized fields. | ||||
10761 | void CheckExpr(Expr *E) { | ||||
10762 | InitListExpr *InitList = dyn_cast<InitListExpr>(E); | ||||
10763 | if (!InitList) { | ||||
10764 | Visit(E); | ||||
10765 | return; | ||||
10766 | } | ||||
10767 | |||||
10768 | // Track and increment the index here. | ||||
10769 | isInitList = true; | ||||
10770 | InitFieldIndex.push_back(0); | ||||
10771 | for (auto Child : InitList->children()) { | ||||
10772 | CheckExpr(cast<Expr>(Child)); | ||||
10773 | ++InitFieldIndex.back(); | ||||
10774 | } | ||||
10775 | InitFieldIndex.pop_back(); | ||||
10776 | } | ||||
10777 | |||||
10778 | // Returns true if MemberExpr is checked and no further checking is needed. | ||||
10779 | // Returns false if additional checking is required. | ||||
10780 | bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { | ||||
10781 | llvm::SmallVector<FieldDecl*, 4> Fields; | ||||
10782 | Expr *Base = E; | ||||
10783 | bool ReferenceField = false; | ||||
10784 | |||||
10785 | // Get the field members used. | ||||
10786 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||
10787 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | ||||
10788 | if (!FD) | ||||
10789 | return false; | ||||
10790 | Fields.push_back(FD); | ||||
10791 | if (FD->getType()->isReferenceType()) | ||||
10792 | ReferenceField = true; | ||||
10793 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||
10794 | } | ||||
10795 | |||||
10796 | // Keep checking only if the base Decl is the same. | ||||
10797 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); | ||||
10798 | if (!DRE || DRE->getDecl() != OrigDecl) | ||||
10799 | return false; | ||||
10800 | |||||
10801 | // A reference field can be bound to an unininitialized field. | ||||
10802 | if (CheckReference && !ReferenceField) | ||||
10803 | return true; | ||||
10804 | |||||
10805 | // Convert FieldDecls to their index number. | ||||
10806 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | ||||
10807 | for (const FieldDecl *I : llvm::reverse(Fields)) | ||||
10808 | UsedFieldIndex.push_back(I->getFieldIndex()); | ||||
10809 | |||||
10810 | // See if a warning is needed by checking the first difference in index | ||||
10811 | // numbers. If field being used has index less than the field being | ||||
10812 | // initialized, then the use is safe. | ||||
10813 | for (auto UsedIter = UsedFieldIndex.begin(), | ||||
10814 | UsedEnd = UsedFieldIndex.end(), | ||||
10815 | OrigIter = InitFieldIndex.begin(), | ||||
10816 | OrigEnd = InitFieldIndex.end(); | ||||
10817 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | ||||
10818 | if (*UsedIter < *OrigIter) | ||||
10819 | return true; | ||||
10820 | if (*UsedIter > *OrigIter) | ||||
10821 | break; | ||||
10822 | } | ||||
10823 | |||||
10824 | // TODO: Add a different warning which will print the field names. | ||||
10825 | HandleDeclRefExpr(DRE); | ||||
10826 | return true; | ||||
10827 | } | ||||
10828 | |||||
10829 | // For most expressions, the cast is directly above the DeclRefExpr. | ||||
10830 | // For conditional operators, the cast can be outside the conditional | ||||
10831 | // operator if both expressions are DeclRefExpr's. | ||||
10832 | void HandleValue(Expr *E) { | ||||
10833 | E = E->IgnoreParens(); | ||||
10834 | if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { | ||||
10835 | HandleDeclRefExpr(DRE); | ||||
10836 | return; | ||||
10837 | } | ||||
10838 | |||||
10839 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | ||||
10840 | Visit(CO->getCond()); | ||||
10841 | HandleValue(CO->getTrueExpr()); | ||||
10842 | HandleValue(CO->getFalseExpr()); | ||||
10843 | return; | ||||
10844 | } | ||||
10845 | |||||
10846 | if (BinaryConditionalOperator *BCO = | ||||
10847 | dyn_cast<BinaryConditionalOperator>(E)) { | ||||
10848 | Visit(BCO->getCond()); | ||||
10849 | HandleValue(BCO->getFalseExpr()); | ||||
10850 | return; | ||||
10851 | } | ||||
10852 | |||||
10853 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | ||||
10854 | HandleValue(OVE->getSourceExpr()); | ||||
10855 | return; | ||||
10856 | } | ||||
10857 | |||||
10858 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | ||||
10859 | if (BO->getOpcode() == BO_Comma) { | ||||
10860 | Visit(BO->getLHS()); | ||||
10861 | HandleValue(BO->getRHS()); | ||||
10862 | return; | ||||
10863 | } | ||||
10864 | } | ||||
10865 | |||||
10866 | if (isa<MemberExpr>(E)) { | ||||
10867 | if (isInitList) { | ||||
10868 | if (CheckInitListMemberExpr(cast<MemberExpr>(E), | ||||
10869 | false /*CheckReference*/)) | ||||
10870 | return; | ||||
10871 | } | ||||
10872 | |||||
10873 | Expr *Base = E->IgnoreParenImpCasts(); | ||||
10874 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||
10875 | // Check for static member variables and don't warn on them. | ||||
10876 | if (!isa<FieldDecl>(ME->getMemberDecl())) | ||||
10877 | return; | ||||
10878 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||
10879 | } | ||||
10880 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) | ||||
10881 | HandleDeclRefExpr(DRE); | ||||
10882 | return; | ||||
10883 | } | ||||
10884 | |||||
10885 | Visit(E); | ||||
10886 | } | ||||
10887 | |||||
10888 | // Reference types not handled in HandleValue are handled here since all | ||||
10889 | // uses of references are bad, not just r-value uses. | ||||
10890 | void VisitDeclRefExpr(DeclRefExpr *E) { | ||||
10891 | if (isReferenceType) | ||||
10892 | HandleDeclRefExpr(E); | ||||
10893 | } | ||||
10894 | |||||
10895 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||
10896 | if (E->getCastKind() == CK_LValueToRValue) { | ||||
10897 | HandleValue(E->getSubExpr()); | ||||
10898 | return; | ||||
10899 | } | ||||
10900 | |||||
10901 | Inherited::VisitImplicitCastExpr(E); | ||||
10902 | } | ||||
10903 | |||||
10904 | void VisitMemberExpr(MemberExpr *E) { | ||||
10905 | if (isInitList) { | ||||
10906 | if (CheckInitListMemberExpr(E, true /*CheckReference*/)) | ||||
10907 | return; | ||||
10908 | } | ||||
10909 | |||||
10910 | // Don't warn on arrays since they can be treated as pointers. | ||||
10911 | if (E->getType()->canDecayToPointerType()) return; | ||||
10912 | |||||
10913 | // Warn when a non-static method call is followed by non-static member | ||||
10914 | // field accesses, which is followed by a DeclRefExpr. | ||||
10915 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); | ||||
10916 | bool Warn = (MD && !MD->isStatic()); | ||||
10917 | Expr *Base = E->getBase()->IgnoreParenImpCasts(); | ||||
10918 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||
10919 | if (!isa<FieldDecl>(ME->getMemberDecl())) | ||||
10920 | Warn = false; | ||||
10921 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||
10922 | } | ||||
10923 | |||||
10924 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { | ||||
10925 | if (Warn) | ||||
10926 | HandleDeclRefExpr(DRE); | ||||
10927 | return; | ||||
10928 | } | ||||
10929 | |||||
10930 | // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. | ||||
10931 | // Visit that expression. | ||||
10932 | Visit(Base); | ||||
10933 | } | ||||
10934 | |||||
10935 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||
10936 | Expr *Callee = E->getCallee(); | ||||
10937 | |||||
10938 | if (isa<UnresolvedLookupExpr>(Callee)) | ||||
10939 | return Inherited::VisitCXXOperatorCallExpr(E); | ||||
10940 | |||||
10941 | Visit(Callee); | ||||
10942 | for (auto Arg: E->arguments()) | ||||
10943 | HandleValue(Arg->IgnoreParenImpCasts()); | ||||
10944 | } | ||||
10945 | |||||
10946 | void VisitUnaryOperator(UnaryOperator *E) { | ||||
10947 | // For POD record types, addresses of its own members are well-defined. | ||||
10948 | if (E->getOpcode() == UO_AddrOf && isRecordType && | ||||
10949 | isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { | ||||
10950 | if (!isPODType) | ||||
10951 | HandleValue(E->getSubExpr()); | ||||
10952 | return; | ||||
10953 | } | ||||
10954 | |||||
10955 | if (E->isIncrementDecrementOp()) { | ||||
10956 | HandleValue(E->getSubExpr()); | ||||
10957 | return; | ||||
10958 | } | ||||
10959 | |||||
10960 | Inherited::VisitUnaryOperator(E); | ||||
10961 | } | ||||
10962 | |||||
10963 | void VisitObjCMessageExpr(ObjCMessageExpr *E) {} | ||||
10964 | |||||
10965 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | ||||
10966 | if (E->getConstructor()->isCopyConstructor()) { | ||||
10967 | Expr *ArgExpr = E->getArg(0); | ||||
10968 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | ||||
10969 | if (ILE->getNumInits() == 1) | ||||
10970 | ArgExpr = ILE->getInit(0); | ||||
10971 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | ||||
10972 | if (ICE->getCastKind() == CK_NoOp) | ||||
10973 | ArgExpr = ICE->getSubExpr(); | ||||
10974 | HandleValue(ArgExpr); | ||||
10975 | return; | ||||
10976 | } | ||||
10977 | Inherited::VisitCXXConstructExpr(E); | ||||
10978 | } | ||||
10979 | |||||
10980 | void VisitCallExpr(CallExpr *E) { | ||||
10981 | // Treat std::move as a use. | ||||
10982 | if (E->isCallToStdMove()) { | ||||
10983 | HandleValue(E->getArg(0)); | ||||
10984 | return; | ||||
10985 | } | ||||
10986 | |||||
10987 | Inherited::VisitCallExpr(E); | ||||
10988 | } | ||||
10989 | |||||
10990 | void VisitBinaryOperator(BinaryOperator *E) { | ||||
10991 | if (E->isCompoundAssignmentOp()) { | ||||
10992 | HandleValue(E->getLHS()); | ||||
10993 | Visit(E->getRHS()); | ||||
10994 | return; | ||||
10995 | } | ||||
10996 | |||||
10997 | Inherited::VisitBinaryOperator(E); | ||||
10998 | } | ||||
10999 | |||||
11000 | // A custom visitor for BinaryConditionalOperator is needed because the | ||||
11001 | // regular visitor would check the condition and true expression separately | ||||
11002 | // but both point to the same place giving duplicate diagnostics. | ||||
11003 | void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { | ||||
11004 | Visit(E->getCond()); | ||||
11005 | Visit(E->getFalseExpr()); | ||||
11006 | } | ||||
11007 | |||||
11008 | void HandleDeclRefExpr(DeclRefExpr *DRE) { | ||||
11009 | Decl* ReferenceDecl = DRE->getDecl(); | ||||
11010 | if (OrigDecl != ReferenceDecl) return; | ||||
11011 | unsigned diag; | ||||
11012 | if (isReferenceType) { | ||||
11013 | diag = diag::warn_uninit_self_reference_in_reference_init; | ||||
11014 | } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { | ||||
11015 | diag = diag::warn_static_self_reference_in_init; | ||||
11016 | } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || | ||||
11017 | isa<NamespaceDecl>(OrigDecl->getDeclContext()) || | ||||
11018 | DRE->getDecl()->getType()->isRecordType()) { | ||||
11019 | diag = diag::warn_uninit_self_reference_in_init; | ||||
11020 | } else { | ||||
11021 | // Local variables will be handled by the CFG analysis. | ||||
11022 | return; | ||||
11023 | } | ||||
11024 | |||||
11025 | S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, | ||||
11026 | S.PDiag(diag) | ||||
11027 | << DRE->getDecl() << OrigDecl->getLocation() | ||||
11028 | << DRE->getSourceRange()); | ||||
11029 | } | ||||
11030 | }; | ||||
11031 | |||||
11032 | /// CheckSelfReference - Warns if OrigDecl is used in expression E. | ||||
11033 | static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, | ||||
11034 | bool DirectInit) { | ||||
11035 | // Parameters arguments are occassionially constructed with itself, | ||||
11036 | // for instance, in recursive functions. Skip them. | ||||
11037 | if (isa<ParmVarDecl>(OrigDecl)) | ||||
11038 | return; | ||||
11039 | |||||
11040 | E = E->IgnoreParens(); | ||||
11041 | |||||
11042 | // Skip checking T a = a where T is not a record or reference type. | ||||
11043 | // Doing so is a way to silence uninitialized warnings. | ||||
11044 | if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) | ||||
11045 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||
11046 | if (ICE->getCastKind() == CK_LValueToRValue) | ||||
11047 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) | ||||
11048 | if (DRE->getDecl() == OrigDecl) | ||||
11049 | return; | ||||
11050 | |||||
11051 | SelfReferenceChecker(S, OrigDecl).CheckExpr(E); | ||||
11052 | } | ||||
11053 | } // end anonymous namespace | ||||
11054 | |||||
11055 | namespace { | ||||
11056 | // Simple wrapper to add the name of a variable or (if no variable is | ||||
11057 | // available) a DeclarationName into a diagnostic. | ||||
11058 | struct VarDeclOrName { | ||||
11059 | VarDecl *VDecl; | ||||
11060 | DeclarationName Name; | ||||
11061 | |||||
11062 | friend const Sema::SemaDiagnosticBuilder & | ||||
11063 | operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { | ||||
11064 | return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; | ||||
11065 | } | ||||
11066 | }; | ||||
11067 | } // end anonymous namespace | ||||
11068 | |||||
11069 | QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, | ||||
11070 | DeclarationName Name, QualType Type, | ||||
11071 | TypeSourceInfo *TSI, | ||||
11072 | SourceRange Range, bool DirectInit, | ||||
11073 | Expr *Init) { | ||||
11074 | bool IsInitCapture = !VDecl; | ||||
11075 | assert((!VDecl || !VDecl->isInitCapture()) &&(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization" ) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11076, __PRETTY_FUNCTION__)) | ||||
11076 | "init captures are expected to be deduced prior to initialization")(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization" ) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11076, __PRETTY_FUNCTION__)); | ||||
11077 | |||||
11078 | VarDeclOrName VN{VDecl, Name}; | ||||
11079 | |||||
11080 | DeducedType *Deduced = Type->getContainedDeducedType(); | ||||
11081 | assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")((Deduced && "deduceVarTypeFromInitializer for non-deduced type" ) ? static_cast<void> (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11081, __PRETTY_FUNCTION__)); | ||||
11082 | |||||
11083 | // C++11 [dcl.spec.auto]p3 | ||||
11084 | if (!Init) { | ||||
11085 | assert(VDecl && "no init for init capture deduction?")((VDecl && "no init for init capture deduction?") ? static_cast <void> (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11085, __PRETTY_FUNCTION__)); | ||||
11086 | |||||
11087 | // Except for class argument deduction, and then for an initializing | ||||
11088 | // declaration only, i.e. no static at class scope or extern. | ||||
11089 | if (!isa<DeducedTemplateSpecializationType>(Deduced) || | ||||
11090 | VDecl->hasExternalStorage() || | ||||
11091 | VDecl->isStaticDataMember()) { | ||||
11092 | Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) | ||||
11093 | << VDecl->getDeclName() << Type; | ||||
11094 | return QualType(); | ||||
11095 | } | ||||
11096 | } | ||||
11097 | |||||
11098 | ArrayRef<Expr*> DeduceInits; | ||||
11099 | if (Init) | ||||
11100 | DeduceInits = Init; | ||||
11101 | |||||
11102 | if (DirectInit) { | ||||
11103 | if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) | ||||
11104 | DeduceInits = PL->exprs(); | ||||
11105 | } | ||||
11106 | |||||
11107 | if (isa<DeducedTemplateSpecializationType>(Deduced)) { | ||||
11108 | assert(VDecl && "non-auto type for init capture deduction?")((VDecl && "non-auto type for init capture deduction?" ) ? static_cast<void> (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11108, __PRETTY_FUNCTION__)); | ||||
11109 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | ||||
11110 | InitializationKind Kind = InitializationKind::CreateForInit( | ||||
11111 | VDecl->getLocation(), DirectInit, Init); | ||||
11112 | // FIXME: Initialization should not be taking a mutable list of inits. | ||||
11113 | SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); | ||||
11114 | return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, | ||||
11115 | InitsCopy); | ||||
11116 | } | ||||
11117 | |||||
11118 | if (DirectInit) { | ||||
11119 | if (auto *IL = dyn_cast<InitListExpr>(Init)) | ||||
11120 | DeduceInits = IL->inits(); | ||||
11121 | } | ||||
11122 | |||||
11123 | // Deduction only works if we have exactly one source expression. | ||||
11124 | if (DeduceInits.empty()) { | ||||
11125 | // It isn't possible to write this directly, but it is possible to | ||||
11126 | // end up in this situation with "auto x(some_pack...);" | ||||
11127 | Diag(Init->getBeginLoc(), IsInitCapture | ||||
11128 | ? diag::err_init_capture_no_expression | ||||
11129 | : diag::err_auto_var_init_no_expression) | ||||
11130 | << VN << Type << Range; | ||||
11131 | return QualType(); | ||||
11132 | } | ||||
11133 | |||||
11134 | if (DeduceInits.size() > 1) { | ||||
11135 | Diag(DeduceInits[1]->getBeginLoc(), | ||||
11136 | IsInitCapture ? diag::err_init_capture_multiple_expressions | ||||
11137 | : diag::err_auto_var_init_multiple_expressions) | ||||
11138 | << VN << Type << Range; | ||||
11139 | return QualType(); | ||||
11140 | } | ||||
11141 | |||||
11142 | Expr *DeduceInit = DeduceInits[0]; | ||||
11143 | if (DirectInit && isa<InitListExpr>(DeduceInit)) { | ||||
11144 | Diag(Init->getBeginLoc(), IsInitCapture | ||||
11145 | ? diag::err_init_capture_paren_braces | ||||
11146 | : diag::err_auto_var_init_paren_braces) | ||||
11147 | << isa<InitListExpr>(Init) << VN << Type << Range; | ||||
11148 | return QualType(); | ||||
11149 | } | ||||
11150 | |||||
11151 | // Expressions default to 'id' when we're in a debugger. | ||||
11152 | bool DefaultedAnyToId = false; | ||||
11153 | if (getLangOpts().DebuggerCastResultToId && | ||||
11154 | Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { | ||||
11155 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | ||||
11156 | if (Result.isInvalid()) { | ||||
11157 | return QualType(); | ||||
11158 | } | ||||
11159 | Init = Result.get(); | ||||
11160 | DefaultedAnyToId = true; | ||||
11161 | } | ||||
11162 | |||||
11163 | // C++ [dcl.decomp]p1: | ||||
11164 | // If the assignment-expression [...] has array type A and no ref-qualifier | ||||
11165 | // is present, e has type cv A | ||||
11166 | if (VDecl && isa<DecompositionDecl>(VDecl) && | ||||
11167 | Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && | ||||
11168 | DeduceInit->getType()->isConstantArrayType()) | ||||
11169 | return Context.getQualifiedType(DeduceInit->getType(), | ||||
11170 | Type.getQualifiers()); | ||||
11171 | |||||
11172 | QualType DeducedType; | ||||
11173 | if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { | ||||
11174 | if (!IsInitCapture) | ||||
11175 | DiagnoseAutoDeductionFailure(VDecl, DeduceInit); | ||||
11176 | else if (isa<InitListExpr>(Init)) | ||||
11177 | Diag(Range.getBegin(), | ||||
11178 | diag::err_init_capture_deduction_failure_from_init_list) | ||||
11179 | << VN | ||||
11180 | << (DeduceInit->getType().isNull() ? TSI->getType() | ||||
11181 | : DeduceInit->getType()) | ||||
11182 | << DeduceInit->getSourceRange(); | ||||
11183 | else | ||||
11184 | Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) | ||||
11185 | << VN << TSI->getType() | ||||
11186 | << (DeduceInit->getType().isNull() ? TSI->getType() | ||||
11187 | : DeduceInit->getType()) | ||||
11188 | << DeduceInit->getSourceRange(); | ||||
11189 | } | ||||
11190 | |||||
11191 | // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using | ||||
11192 | // 'id' instead of a specific object type prevents most of our usual | ||||
11193 | // checks. | ||||
11194 | // We only want to warn outside of template instantiations, though: | ||||
11195 | // inside a template, the 'id' could have come from a parameter. | ||||
11196 | if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && | ||||
11197 | !DeducedType.isNull() && DeducedType->isObjCIdType()) { | ||||
11198 | SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); | ||||
11199 | Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; | ||||
11200 | } | ||||
11201 | |||||
11202 | return DeducedType; | ||||
11203 | } | ||||
11204 | |||||
11205 | bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, | ||||
11206 | Expr *Init) { | ||||
11207 | QualType DeducedType = deduceVarTypeFromInitializer( | ||||
11208 | VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), | ||||
11209 | VDecl->getSourceRange(), DirectInit, Init); | ||||
11210 | if (DeducedType.isNull()) { | ||||
11211 | VDecl->setInvalidDecl(); | ||||
11212 | return true; | ||||
11213 | } | ||||
11214 | |||||
11215 | VDecl->setType(DeducedType); | ||||
11216 | assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) : __assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11216, __PRETTY_FUNCTION__)); | ||||
11217 | |||||
11218 | // In ARC, infer lifetime. | ||||
11219 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) | ||||
11220 | VDecl->setInvalidDecl(); | ||||
11221 | |||||
11222 | // If this is a redeclaration, check that the type we just deduced matches | ||||
11223 | // the previously declared type. | ||||
11224 | if (VarDecl *Old = VDecl->getPreviousDecl()) { | ||||
11225 | // We never need to merge the type, because we cannot form an incomplete | ||||
11226 | // array of auto, nor deduce such a type. | ||||
11227 | MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); | ||||
11228 | } | ||||
11229 | |||||
11230 | // Check the deduced type is valid for a variable declaration. | ||||
11231 | CheckVariableDeclarationType(VDecl); | ||||
11232 | return VDecl->isInvalidDecl(); | ||||
11233 | } | ||||
11234 | |||||
11235 | void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, | ||||
11236 | SourceLocation Loc) { | ||||
11237 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | ||||
11238 | Init = CE->getSubExpr(); | ||||
11239 | |||||
11240 | QualType InitType = Init->getType(); | ||||
11241 | assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11243, __PRETTY_FUNCTION__)) | ||||
11242 | InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11243, __PRETTY_FUNCTION__)) | ||||
11243 | "shouldn't be called if type doesn't have a non-trivial C struct")(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11243, __PRETTY_FUNCTION__)); | ||||
11244 | if (auto *ILE = dyn_cast<InitListExpr>(Init)) { | ||||
11245 | for (auto I : ILE->inits()) { | ||||
11246 | if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && | ||||
11247 | !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
11248 | continue; | ||||
11249 | SourceLocation SL = I->getExprLoc(); | ||||
11250 | checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); | ||||
11251 | } | ||||
11252 | return; | ||||
11253 | } | ||||
11254 | |||||
11255 | if (isa<ImplicitValueInitExpr>(Init)) { | ||||
11256 | if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||
11257 | checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, | ||||
11258 | NTCUK_Init); | ||||
11259 | } else { | ||||
11260 | // Assume all other explicit initializers involving copying some existing | ||||
11261 | // object. | ||||
11262 | // TODO: ignore any explicit initializers where we can guarantee | ||||
11263 | // copy-elision. | ||||
11264 | if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) | ||||
11265 | checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); | ||||
11266 | } | ||||
11267 | } | ||||
11268 | |||||
11269 | namespace { | ||||
11270 | |||||
11271 | bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { | ||||
11272 | // Ignore unavailable fields. A field can be marked as unavailable explicitly | ||||
11273 | // in the source code or implicitly by the compiler if it is in a union | ||||
11274 | // defined in a system header and has non-trivial ObjC ownership | ||||
11275 | // qualifications. We don't want those fields to participate in determining | ||||
11276 | // whether the containing union is non-trivial. | ||||
11277 | return FD->hasAttr<UnavailableAttr>(); | ||||
11278 | } | ||||
11279 | |||||
11280 | struct DiagNonTrivalCUnionDefaultInitializeVisitor | ||||
11281 | : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, | ||||
11282 | void> { | ||||
11283 | using Super = | ||||
11284 | DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, | ||||
11285 | void>; | ||||
11286 | |||||
11287 | DiagNonTrivalCUnionDefaultInitializeVisitor( | ||||
11288 | QualType OrigTy, SourceLocation OrigLoc, | ||||
11289 | Sema::NonTrivialCUnionContext UseContext, Sema &S) | ||||
11290 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||
11291 | |||||
11292 | void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, | ||||
11293 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||
11294 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||
11295 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||
11296 | InNonTrivialUnion); | ||||
11297 | return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); | ||||
11298 | } | ||||
11299 | |||||
11300 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||
11301 | bool InNonTrivialUnion) { | ||||
11302 | if (InNonTrivialUnion) | ||||
11303 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||
11304 | << 1 << 0 << QT << FD->getName(); | ||||
11305 | } | ||||
11306 | |||||
11307 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||
11308 | if (InNonTrivialUnion) | ||||
11309 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||
11310 | << 1 << 0 << QT << FD->getName(); | ||||
11311 | } | ||||
11312 | |||||
11313 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||
11314 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||
11315 | if (RD->isUnion()) { | ||||
11316 | if (OrigLoc.isValid()) { | ||||
11317 | bool IsUnion = false; | ||||
11318 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||
11319 | IsUnion = OrigRD->isUnion(); | ||||
11320 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||
11321 | << 0 << OrigTy << IsUnion << UseContext; | ||||
11322 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||
11323 | OrigLoc = SourceLocation(); | ||||
11324 | } | ||||
11325 | InNonTrivialUnion = true; | ||||
11326 | } | ||||
11327 | |||||
11328 | if (InNonTrivialUnion) | ||||
11329 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||
11330 | << 0 << 0 << QT.getUnqualifiedType() << ""; | ||||
11331 | |||||
11332 | for (const FieldDecl *FD : RD->fields()) | ||||
11333 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||
11334 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||
11335 | } | ||||
11336 | |||||
11337 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||
11338 | |||||
11339 | // The non-trivial C union type or the struct/union type that contains a | ||||
11340 | // non-trivial C union. | ||||
11341 | QualType OrigTy; | ||||
11342 | SourceLocation OrigLoc; | ||||
11343 | Sema::NonTrivialCUnionContext UseContext; | ||||
11344 | Sema &S; | ||||
11345 | }; | ||||
11346 | |||||
11347 | struct DiagNonTrivalCUnionDestructedTypeVisitor | ||||
11348 | : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { | ||||
11349 | using Super = | ||||
11350 | DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; | ||||
11351 | |||||
11352 | DiagNonTrivalCUnionDestructedTypeVisitor( | ||||
11353 | QualType OrigTy, SourceLocation OrigLoc, | ||||
11354 | Sema::NonTrivialCUnionContext UseContext, Sema &S) | ||||
11355 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||
11356 | |||||
11357 | void visitWithKind(QualType::DestructionKind DK, QualType QT, | ||||
11358 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||
11359 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||
11360 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||
11361 | InNonTrivialUnion); | ||||
11362 | return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); | ||||
11363 | } | ||||
11364 | |||||
11365 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||
11366 | bool InNonTrivialUnion) { | ||||
11367 | if (InNonTrivialUnion) | ||||
11368 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||
11369 | << 1 << 1 << QT << FD->getName(); | ||||
11370 | } | ||||
11371 | |||||
11372 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||
11373 | if (InNonTrivialUnion) | ||||
11374 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||
11375 | << 1 << 1 << QT << FD->getName(); | ||||
11376 | } | ||||
11377 | |||||
11378 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||
11379 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||
11380 | if (RD->isUnion()) { | ||||
11381 | if (OrigLoc.isValid()) { | ||||
11382 | bool IsUnion = false; | ||||
11383 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||
11384 | IsUnion = OrigRD->isUnion(); | ||||
11385 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||
11386 | << 1 << OrigTy << IsUnion << UseContext; | ||||
11387 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||
11388 | OrigLoc = SourceLocation(); | ||||
11389 | } | ||||
11390 | InNonTrivialUnion = true; | ||||
11391 | } | ||||
11392 | |||||
11393 | if (InNonTrivialUnion) | ||||
11394 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||
11395 | << 0 << 1 << QT.getUnqualifiedType() << ""; | ||||
11396 | |||||
11397 | for (const FieldDecl *FD : RD->fields()) | ||||
11398 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||
11399 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||
11400 | } | ||||
11401 | |||||
11402 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||
11403 | void visitCXXDestructor(QualType QT, const FieldDecl *FD, | ||||
11404 | bool InNonTrivialUnion) {} | ||||
11405 | |||||
11406 | // The non-trivial C union type or the struct/union type that contains a | ||||
11407 | // non-trivial C union. | ||||
11408 | QualType OrigTy; | ||||
11409 | SourceLocation OrigLoc; | ||||
11410 | Sema::NonTrivialCUnionContext UseContext; | ||||
11411 | Sema &S; | ||||
11412 | }; | ||||
11413 | |||||
11414 | struct DiagNonTrivalCUnionCopyVisitor | ||||
11415 | : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { | ||||
11416 | using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; | ||||
11417 | |||||
11418 | DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, | ||||
11419 | Sema::NonTrivialCUnionContext UseContext, | ||||
11420 | Sema &S) | ||||
11421 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||
11422 | |||||
11423 | void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, | ||||
11424 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||
11425 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||
11426 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||
11427 | InNonTrivialUnion); | ||||
11428 | return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); | ||||
11429 | } | ||||
11430 | |||||
11431 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||
11432 | bool InNonTrivialUnion) { | ||||
11433 | if (InNonTrivialUnion) | ||||
11434 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||
11435 | << 1 << 2 << QT << FD->getName(); | ||||
11436 | } | ||||
11437 | |||||
11438 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||
11439 | if (InNonTrivialUnion) | ||||
11440 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||
11441 | << 1 << 2 << QT << FD->getName(); | ||||
11442 | } | ||||
11443 | |||||
11444 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||
11445 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||
11446 | if (RD->isUnion()) { | ||||
11447 | if (OrigLoc.isValid()) { | ||||
11448 | bool IsUnion = false; | ||||
11449 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||
11450 | IsUnion = OrigRD->isUnion(); | ||||
11451 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||
11452 | << 2 << OrigTy << IsUnion << UseContext; | ||||
11453 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||
11454 | OrigLoc = SourceLocation(); | ||||
11455 | } | ||||
11456 | InNonTrivialUnion = true; | ||||
11457 | } | ||||
11458 | |||||
11459 | if (InNonTrivialUnion) | ||||
11460 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||
11461 | << 0 << 2 << QT.getUnqualifiedType() << ""; | ||||
11462 | |||||
11463 | for (const FieldDecl *FD : RD->fields()) | ||||
11464 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||
11465 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||
11466 | } | ||||
11467 | |||||
11468 | void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, | ||||
11469 | const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||
11470 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||
11471 | void visitVolatileTrivial(QualType QT, const FieldDecl *FD, | ||||
11472 | bool InNonTrivialUnion) {} | ||||
11473 | |||||
11474 | // The non-trivial C union type or the struct/union type that contains a | ||||
11475 | // non-trivial C union. | ||||
11476 | QualType OrigTy; | ||||
11477 | SourceLocation OrigLoc; | ||||
11478 | Sema::NonTrivialCUnionContext UseContext; | ||||
11479 | Sema &S; | ||||
11480 | }; | ||||
11481 | |||||
11482 | } // namespace | ||||
11483 | |||||
11484 | void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, | ||||
11485 | NonTrivialCUnionContext UseContext, | ||||
11486 | unsigned NonTrivialKind) { | ||||
11487 | assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11490, __PRETTY_FUNCTION__)) | ||||
11488 | QT.hasNonTrivialToPrimitiveDestructCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11490, __PRETTY_FUNCTION__)) | ||||
11489 | QT.hasNonTrivialToPrimitiveCopyCUnion()) &&(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11490, __PRETTY_FUNCTION__)) | ||||
11490 | "shouldn't be called if type doesn't have a non-trivial C union")(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11490, __PRETTY_FUNCTION__)); | ||||
11491 | |||||
11492 | if ((NonTrivialKind & NTCUK_Init) && | ||||
11493 | QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||
11494 | DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) | ||||
11495 | .visit(QT, nullptr, false); | ||||
11496 | if ((NonTrivialKind & NTCUK_Destruct) && | ||||
11497 | QT.hasNonTrivialToPrimitiveDestructCUnion()) | ||||
11498 | DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) | ||||
11499 | .visit(QT, nullptr, false); | ||||
11500 | if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) | ||||
11501 | DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) | ||||
11502 | .visit(QT, nullptr, false); | ||||
11503 | } | ||||
11504 | |||||
11505 | /// AddInitializerToDecl - Adds the initializer Init to the | ||||
11506 | /// declaration dcl. If DirectInit is true, this is C++ direct | ||||
11507 | /// initialization rather than copy initialization. | ||||
11508 | void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { | ||||
11509 | // If there is no declaration, there was an error parsing it. Just ignore | ||||
11510 | // the initializer. | ||||
11511 | if (!RealDecl || RealDecl->isInvalidDecl()) { | ||||
11512 | CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); | ||||
11513 | return; | ||||
11514 | } | ||||
11515 | |||||
11516 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { | ||||
11517 | // Pure-specifiers are handled in ActOnPureSpecifier. | ||||
11518 | Diag(Method->getLocation(), diag::err_member_function_initialization) | ||||
11519 | << Method->getDeclName() << Init->getSourceRange(); | ||||
11520 | Method->setInvalidDecl(); | ||||
11521 | return; | ||||
11522 | } | ||||
11523 | |||||
11524 | VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); | ||||
11525 | if (!VDecl) { | ||||
11526 | assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")((!isa<FieldDecl>(RealDecl) && "field init shouldn't get here" ) ? static_cast<void> (0) : __assert_fail ("!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11526, __PRETTY_FUNCTION__)); | ||||
11527 | Diag(RealDecl->getLocation(), diag::err_illegal_initializer); | ||||
11528 | RealDecl->setInvalidDecl(); | ||||
11529 | return; | ||||
11530 | } | ||||
11531 | |||||
11532 | // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. | ||||
11533 | if (VDecl->getType()->isUndeducedType()) { | ||||
11534 | // Attempt typo correction early so that the type of the init expression can | ||||
11535 | // be deduced based on the chosen correction if the original init contains a | ||||
11536 | // TypoExpr. | ||||
11537 | ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); | ||||
11538 | if (!Res.isUsable()) { | ||||
11539 | RealDecl->setInvalidDecl(); | ||||
11540 | return; | ||||
11541 | } | ||||
11542 | Init = Res.get(); | ||||
11543 | |||||
11544 | if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) | ||||
11545 | return; | ||||
11546 | } | ||||
11547 | |||||
11548 | // dllimport cannot be used on variable definitions. | ||||
11549 | if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { | ||||
11550 | Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); | ||||
11551 | VDecl->setInvalidDecl(); | ||||
11552 | return; | ||||
11553 | } | ||||
11554 | |||||
11555 | if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { | ||||
11556 | // C99 6.7.8p5. C++ has no such restriction, but that is a defect. | ||||
11557 | Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); | ||||
11558 | VDecl->setInvalidDecl(); | ||||
11559 | return; | ||||
11560 | } | ||||
11561 | |||||
11562 | if (!VDecl->getType()->isDependentType()) { | ||||
11563 | // A definition must end up with a complete type, which means it must be | ||||
11564 | // complete with the restriction that an array type might be completed by | ||||
11565 | // the initializer; note that later code assumes this restriction. | ||||
11566 | QualType BaseDeclType = VDecl->getType(); | ||||
11567 | if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) | ||||
11568 | BaseDeclType = Array->getElementType(); | ||||
11569 | if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, | ||||
11570 | diag::err_typecheck_decl_incomplete_type)) { | ||||
11571 | RealDecl->setInvalidDecl(); | ||||
11572 | return; | ||||
11573 | } | ||||
11574 | |||||
11575 | // The variable can not have an abstract class type. | ||||
11576 | if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), | ||||
11577 | diag::err_abstract_type_in_decl, | ||||
11578 | AbstractVariableType)) | ||||
11579 | VDecl->setInvalidDecl(); | ||||
11580 | } | ||||
11581 | |||||
11582 | // If adding the initializer will turn this declaration into a definition, | ||||
11583 | // and we already have a definition for this variable, diagnose or otherwise | ||||
11584 | // handle the situation. | ||||
11585 | VarDecl *Def; | ||||
11586 | if ((Def = VDecl->getDefinition()) && Def != VDecl && | ||||
11587 | (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && | ||||
11588 | !VDecl->isThisDeclarationADemotedDefinition() && | ||||
11589 | checkVarDeclRedefinition(Def, VDecl)) | ||||
11590 | return; | ||||
11591 | |||||
11592 | if (getLangOpts().CPlusPlus) { | ||||
11593 | // C++ [class.static.data]p4 | ||||
11594 | // If a static data member is of const integral or const | ||||
11595 | // enumeration type, its declaration in the class definition can | ||||
11596 | // specify a constant-initializer which shall be an integral | ||||
11597 | // constant expression (5.19). In that case, the member can appear | ||||
11598 | // in integral constant expressions. The member shall still be | ||||
11599 | // defined in a namespace scope if it is used in the program and the | ||||
11600 | // namespace scope definition shall not contain an initializer. | ||||
11601 | // | ||||
11602 | // We already performed a redefinition check above, but for static | ||||
11603 | // data members we also need to check whether there was an in-class | ||||
11604 | // declaration with an initializer. | ||||
11605 | if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { | ||||
11606 | Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) | ||||
11607 | << VDecl->getDeclName(); | ||||
11608 | Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), | ||||
11609 | diag::note_previous_initializer) | ||||
11610 | << 0; | ||||
11611 | return; | ||||
11612 | } | ||||
11613 | |||||
11614 | if (VDecl->hasLocalStorage()) | ||||
11615 | setFunctionHasBranchProtectedScope(); | ||||
11616 | |||||
11617 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { | ||||
11618 | VDecl->setInvalidDecl(); | ||||
11619 | return; | ||||
11620 | } | ||||
11621 | } | ||||
11622 | |||||
11623 | // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside | ||||
11624 | // a kernel function cannot be initialized." | ||||
11625 | if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { | ||||
11626 | Diag(VDecl->getLocation(), diag::err_local_cant_init); | ||||
11627 | VDecl->setInvalidDecl(); | ||||
11628 | return; | ||||
11629 | } | ||||
11630 | |||||
11631 | // Get the decls type and save a reference for later, since | ||||
11632 | // CheckInitializerTypes may change it. | ||||
11633 | QualType DclT = VDecl->getType(), SavT = DclT; | ||||
11634 | |||||
11635 | // Expressions default to 'id' when we're in a debugger | ||||
11636 | // and we are assigning it to a variable of Objective-C pointer type. | ||||
11637 | if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && | ||||
11638 | Init->getType() == Context.UnknownAnyTy) { | ||||
11639 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | ||||
11640 | if (Result.isInvalid()) { | ||||
11641 | VDecl->setInvalidDecl(); | ||||
11642 | return; | ||||
11643 | } | ||||
11644 | Init = Result.get(); | ||||
11645 | } | ||||
11646 | |||||
11647 | // Perform the initialization. | ||||
11648 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); | ||||
11649 | if (!VDecl->isInvalidDecl()) { | ||||
11650 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | ||||
11651 | InitializationKind Kind = InitializationKind::CreateForInit( | ||||
11652 | VDecl->getLocation(), DirectInit, Init); | ||||
11653 | |||||
11654 | MultiExprArg Args = Init; | ||||
11655 | if (CXXDirectInit) | ||||
11656 | Args = MultiExprArg(CXXDirectInit->getExprs(), | ||||
11657 | CXXDirectInit->getNumExprs()); | ||||
11658 | |||||
11659 | // Try to correct any TypoExprs in the initialization arguments. | ||||
11660 | for (size_t Idx = 0; Idx < Args.size(); ++Idx) { | ||||
11661 | ExprResult Res = CorrectDelayedTyposInExpr( | ||||
11662 | Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { | ||||
11663 | InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); | ||||
11664 | return Init.Failed() ? ExprError() : E; | ||||
11665 | }); | ||||
11666 | if (Res.isInvalid()) { | ||||
11667 | VDecl->setInvalidDecl(); | ||||
11668 | } else if (Res.get() != Args[Idx]) { | ||||
11669 | Args[Idx] = Res.get(); | ||||
11670 | } | ||||
11671 | } | ||||
11672 | if (VDecl->isInvalidDecl()) | ||||
11673 | return; | ||||
11674 | |||||
11675 | InitializationSequence InitSeq(*this, Entity, Kind, Args, | ||||
11676 | /*TopLevelOfInitList=*/false, | ||||
11677 | /*TreatUnavailableAsInvalid=*/false); | ||||
11678 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); | ||||
11679 | if (Result.isInvalid()) { | ||||
11680 | VDecl->setInvalidDecl(); | ||||
11681 | return; | ||||
11682 | } | ||||
11683 | |||||
11684 | Init = Result.getAs<Expr>(); | ||||
11685 | } | ||||
11686 | |||||
11687 | // Check for self-references within variable initializers. | ||||
11688 | // Variables declared within a function/method body (except for references) | ||||
11689 | // are handled by a dataflow analysis. | ||||
11690 | // This is undefined behavior in C++, but valid in C. | ||||
11691 | if (getLangOpts().CPlusPlus) { | ||||
11692 | if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || | ||||
11693 | VDecl->getType()->isReferenceType()) { | ||||
11694 | CheckSelfReference(*this, RealDecl, Init, DirectInit); | ||||
11695 | } | ||||
11696 | } | ||||
11697 | |||||
11698 | // If the type changed, it means we had an incomplete type that was | ||||
11699 | // completed by the initializer. For example: | ||||
11700 | // int ary[] = { 1, 3, 5 }; | ||||
11701 | // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. | ||||
11702 | if (!VDecl->isInvalidDecl() && (DclT != SavT)) | ||||
11703 | VDecl->setType(DclT); | ||||
11704 | |||||
11705 | if (!VDecl->isInvalidDecl()) { | ||||
11706 | checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); | ||||
11707 | |||||
11708 | if (VDecl->hasAttr<BlocksAttr>()) | ||||
11709 | checkRetainCycles(VDecl, Init); | ||||
11710 | |||||
11711 | // It is safe to assign a weak reference into a strong variable. | ||||
11712 | // Although this code can still have problems: | ||||
11713 | // id x = self.weakProp; | ||||
11714 | // id y = self.weakProp; | ||||
11715 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | ||||
11716 | // paths through the function. This should be revisited if | ||||
11717 | // -Wrepeated-use-of-weak is made flow-sensitive. | ||||
11718 | if (FunctionScopeInfo *FSI = getCurFunction()) | ||||
11719 | if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || | ||||
11720 | VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && | ||||
11721 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | ||||
11722 | Init->getBeginLoc())) | ||||
11723 | FSI->markSafeWeakUse(Init); | ||||
11724 | } | ||||
11725 | |||||
11726 | // The initialization is usually a full-expression. | ||||
11727 | // | ||||
11728 | // FIXME: If this is a braced initialization of an aggregate, it is not | ||||
11729 | // an expression, and each individual field initializer is a separate | ||||
11730 | // full-expression. For instance, in: | ||||
11731 | // | ||||
11732 | // struct Temp { ~Temp(); }; | ||||
11733 | // struct S { S(Temp); }; | ||||
11734 | // struct T { S a, b; } t = { Temp(), Temp() } | ||||
11735 | // | ||||
11736 | // we should destroy the first Temp before constructing the second. | ||||
11737 | ExprResult Result = | ||||
11738 | ActOnFinishFullExpr(Init, VDecl->getLocation(), | ||||
11739 | /*DiscardedValue*/ false, VDecl->isConstexpr()); | ||||
11740 | if (Result.isInvalid()) { | ||||
11741 | VDecl->setInvalidDecl(); | ||||
11742 | return; | ||||
11743 | } | ||||
11744 | Init = Result.get(); | ||||
11745 | |||||
11746 | // Attach the initializer to the decl. | ||||
11747 | VDecl->setInit(Init); | ||||
11748 | |||||
11749 | if (VDecl->isLocalVarDecl()) { | ||||
11750 | // Don't check the initializer if the declaration is malformed. | ||||
11751 | if (VDecl->isInvalidDecl()) { | ||||
11752 | // do nothing | ||||
11753 | |||||
11754 | // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. | ||||
11755 | // This is true even in C++ for OpenCL. | ||||
11756 | } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { | ||||
11757 | CheckForConstantInitializer(Init, DclT); | ||||
11758 | |||||
11759 | // Otherwise, C++ does not restrict the initializer. | ||||
11760 | } else if (getLangOpts().CPlusPlus) { | ||||
11761 | // do nothing | ||||
11762 | |||||
11763 | // C99 6.7.8p4: All the expressions in an initializer for an object that has | ||||
11764 | // static storage duration shall be constant expressions or string literals. | ||||
11765 | } else if (VDecl->getStorageClass() == SC_Static) { | ||||
11766 | CheckForConstantInitializer(Init, DclT); | ||||
11767 | |||||
11768 | // C89 is stricter than C99 for aggregate initializers. | ||||
11769 | // C89 6.5.7p3: All the expressions [...] in an initializer list | ||||
11770 | // for an object that has aggregate or union type shall be | ||||
11771 | // constant expressions. | ||||
11772 | } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && | ||||
11773 | isa<InitListExpr>(Init)) { | ||||
11774 | const Expr *Culprit; | ||||
11775 | if (!Init->isConstantInitializer(Context, false, &Culprit)) { | ||||
11776 | Diag(Culprit->getExprLoc(), | ||||
11777 | diag::ext_aggregate_init_not_constant) | ||||
11778 | << Culprit->getSourceRange(); | ||||
11779 | } | ||||
11780 | } | ||||
11781 | |||||
11782 | if (auto *E = dyn_cast<ExprWithCleanups>(Init)) | ||||
11783 | if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) | ||||
11784 | if (VDecl->hasLocalStorage()) | ||||
11785 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | ||||
11786 | } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && | ||||
11787 | VDecl->getLexicalDeclContext()->isRecord()) { | ||||
11788 | // This is an in-class initialization for a static data member, e.g., | ||||
11789 | // | ||||
11790 | // struct S { | ||||
11791 | // static const int value = 17; | ||||
11792 | // }; | ||||
11793 | |||||
11794 | // C++ [class.mem]p4: | ||||
11795 | // A member-declarator can contain a constant-initializer only | ||||
11796 | // if it declares a static member (9.4) of const integral or | ||||
11797 | // const enumeration type, see 9.4.2. | ||||
11798 | // | ||||
11799 | // C++11 [class.static.data]p3: | ||||
11800 | // If a non-volatile non-inline const static data member is of integral | ||||
11801 | // or enumeration type, its declaration in the class definition can | ||||
11802 | // specify a brace-or-equal-initializer in which every initializer-clause | ||||
11803 | // that is an assignment-expression is a constant expression. A static | ||||
11804 | // data member of literal type can be declared in the class definition | ||||
11805 | // with the constexpr specifier; if so, its declaration shall specify a | ||||
11806 | // brace-or-equal-initializer in which every initializer-clause that is | ||||
11807 | // an assignment-expression is a constant expression. | ||||
11808 | |||||
11809 | // Do nothing on dependent types. | ||||
11810 | if (DclT->isDependentType()) { | ||||
11811 | |||||
11812 | // Allow any 'static constexpr' members, whether or not they are of literal | ||||
11813 | // type. We separately check that every constexpr variable is of literal | ||||
11814 | // type. | ||||
11815 | } else if (VDecl->isConstexpr()) { | ||||
11816 | |||||
11817 | // Require constness. | ||||
11818 | } else if (!DclT.isConstQualified()) { | ||||
11819 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) | ||||
11820 | << Init->getSourceRange(); | ||||
11821 | VDecl->setInvalidDecl(); | ||||
11822 | |||||
11823 | // We allow integer constant expressions in all cases. | ||||
11824 | } else if (DclT->isIntegralOrEnumerationType()) { | ||||
11825 | // Check whether the expression is a constant expression. | ||||
11826 | SourceLocation Loc; | ||||
11827 | if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) | ||||
11828 | // In C++11, a non-constexpr const static data member with an | ||||
11829 | // in-class initializer cannot be volatile. | ||||
11830 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); | ||||
11831 | else if (Init->isValueDependent()) | ||||
11832 | ; // Nothing to check. | ||||
11833 | else if (Init->isIntegerConstantExpr(Context, &Loc)) | ||||
11834 | ; // Ok, it's an ICE! | ||||
11835 | else if (Init->getType()->isScopedEnumeralType() && | ||||
11836 | Init->isCXX11ConstantExpr(Context)) | ||||
11837 | ; // Ok, it is a scoped-enum constant expression. | ||||
11838 | else if (Init->isEvaluatable(Context)) { | ||||
11839 | // If we can constant fold the initializer through heroics, accept it, | ||||
11840 | // but report this as a use of an extension for -pedantic. | ||||
11841 | Diag(Loc, diag::ext_in_class_initializer_non_constant) | ||||
11842 | << Init->getSourceRange(); | ||||
11843 | } else { | ||||
11844 | // Otherwise, this is some crazy unknown case. Report the issue at the | ||||
11845 | // location provided by the isIntegerConstantExpr failed check. | ||||
11846 | Diag(Loc, diag::err_in_class_initializer_non_constant) | ||||
11847 | << Init->getSourceRange(); | ||||
11848 | VDecl->setInvalidDecl(); | ||||
11849 | } | ||||
11850 | |||||
11851 | // We allow foldable floating-point constants as an extension. | ||||
11852 | } else if (DclT->isFloatingType()) { // also permits complex, which is ok | ||||
11853 | // In C++98, this is a GNU extension. In C++11, it is not, but we support | ||||
11854 | // it anyway and provide a fixit to add the 'constexpr'. | ||||
11855 | if (getLangOpts().CPlusPlus11) { | ||||
11856 | Diag(VDecl->getLocation(), | ||||
11857 | diag::ext_in_class_initializer_float_type_cxx11) | ||||
11858 | << DclT << Init->getSourceRange(); | ||||
11859 | Diag(VDecl->getBeginLoc(), | ||||
11860 | diag::note_in_class_initializer_float_type_cxx11) | ||||
11861 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | ||||
11862 | } else { | ||||
11863 | Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) | ||||
11864 | << DclT << Init->getSourceRange(); | ||||
11865 | |||||
11866 | if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { | ||||
11867 | Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) | ||||
11868 | << Init->getSourceRange(); | ||||
11869 | VDecl->setInvalidDecl(); | ||||
11870 | } | ||||
11871 | } | ||||
11872 | |||||
11873 | // Suggest adding 'constexpr' in C++11 for literal types. | ||||
11874 | } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { | ||||
11875 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) | ||||
11876 | << DclT << Init->getSourceRange() | ||||
11877 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | ||||
11878 | VDecl->setConstexpr(true); | ||||
11879 | |||||
11880 | } else { | ||||
11881 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) | ||||
11882 | << DclT << Init->getSourceRange(); | ||||
11883 | VDecl->setInvalidDecl(); | ||||
11884 | } | ||||
11885 | } else if (VDecl->isFileVarDecl()) { | ||||
11886 | // In C, extern is typically used to avoid tentative definitions when | ||||
11887 | // declaring variables in headers, but adding an intializer makes it a | ||||
11888 | // definition. This is somewhat confusing, so GCC and Clang both warn on it. | ||||
11889 | // In C++, extern is often used to give implictly static const variables | ||||
11890 | // external linkage, so don't warn in that case. If selectany is present, | ||||
11891 | // this might be header code intended for C and C++ inclusion, so apply the | ||||
11892 | // C++ rules. | ||||
11893 | if (VDecl->getStorageClass() == SC_Extern && | ||||
11894 | ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || | ||||
11895 | !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && | ||||
11896 | !(getLangOpts().CPlusPlus && VDecl->isExternC()) && | ||||
11897 | !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) | ||||
11898 | Diag(VDecl->getLocation(), diag::warn_extern_init); | ||||
11899 | |||||
11900 | // In Microsoft C++ mode, a const variable defined in namespace scope has | ||||
11901 | // external linkage by default if the variable is declared with | ||||
11902 | // __declspec(dllexport). | ||||
11903 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | ||||
11904 | getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && | ||||
11905 | VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) | ||||
11906 | VDecl->setStorageClass(SC_Extern); | ||||
11907 | |||||
11908 | // C99 6.7.8p4. All file scoped initializers need to be constant. | ||||
11909 | if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) | ||||
11910 | CheckForConstantInitializer(Init, DclT); | ||||
11911 | } | ||||
11912 | |||||
11913 | QualType InitType = Init->getType(); | ||||
11914 | if (!InitType.isNull() && | ||||
11915 | (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||
11916 | InitType.hasNonTrivialToPrimitiveCopyCUnion())) | ||||
11917 | checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); | ||||
11918 | |||||
11919 | // We will represent direct-initialization similarly to copy-initialization: | ||||
11920 | // int x(1); -as-> int x = 1; | ||||
11921 | // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); | ||||
11922 | // | ||||
11923 | // Clients that want to distinguish between the two forms, can check for | ||||
11924 | // direct initializer using VarDecl::getInitStyle(). | ||||
11925 | // A major benefit is that clients that don't particularly care about which | ||||
11926 | // exactly form was it (like the CodeGen) can handle both cases without | ||||
11927 | // special case code. | ||||
11928 | |||||
11929 | // C++ 8.5p11: | ||||
11930 | // The form of initialization (using parentheses or '=') is generally | ||||
11931 | // insignificant, but does matter when the entity being initialized has a | ||||
11932 | // class type. | ||||
11933 | if (CXXDirectInit) { | ||||
11934 | assert(DirectInit && "Call-style initializer must be direct init.")((DirectInit && "Call-style initializer must be direct init." ) ? static_cast<void> (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 11934, __PRETTY_FUNCTION__)); | ||||
11935 | VDecl->setInitStyle(VarDecl::CallInit); | ||||
11936 | } else if (DirectInit) { | ||||
11937 | // This must be list-initialization. No other way is direct-initialization. | ||||
11938 | VDecl->setInitStyle(VarDecl::ListInit); | ||||
11939 | } | ||||
11940 | |||||
11941 | CheckCompleteVariableDeclaration(VDecl); | ||||
11942 | } | ||||
11943 | |||||
11944 | /// ActOnInitializerError - Given that there was an error parsing an | ||||
11945 | /// initializer for the given declaration, try to return to some form | ||||
11946 | /// of sanity. | ||||
11947 | void Sema::ActOnInitializerError(Decl *D) { | ||||
11948 | // Our main concern here is re-establishing invariants like "a | ||||
11949 | // variable's type is either dependent or complete". | ||||
11950 | if (!D || D->isInvalidDecl()) return; | ||||
11951 | |||||
11952 | VarDecl *VD = dyn_cast<VarDecl>(D); | ||||
11953 | if (!VD) return; | ||||
11954 | |||||
11955 | // Bindings are not usable if we can't make sense of the initializer. | ||||
11956 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) | ||||
11957 | for (auto *BD : DD->bindings()) | ||||
11958 | BD->setInvalidDecl(); | ||||
11959 | |||||
11960 | // Auto types are meaningless if we can't make sense of the initializer. | ||||
11961 | if (ParsingInitForAutoVars.count(D)) { | ||||
11962 | D->setInvalidDecl(); | ||||
11963 | return; | ||||
11964 | } | ||||
11965 | |||||
11966 | QualType Ty = VD->getType(); | ||||
11967 | if (Ty->isDependentType()) return; | ||||
11968 | |||||
11969 | // Require a complete type. | ||||
11970 | if (RequireCompleteType(VD->getLocation(), | ||||
11971 | Context.getBaseElementType(Ty), | ||||
11972 | diag::err_typecheck_decl_incomplete_type)) { | ||||
11973 | VD->setInvalidDecl(); | ||||
11974 | return; | ||||
11975 | } | ||||
11976 | |||||
11977 | // Require a non-abstract type. | ||||
11978 | if (RequireNonAbstractType(VD->getLocation(), Ty, | ||||
11979 | diag::err_abstract_type_in_decl, | ||||
11980 | AbstractVariableType)) { | ||||
11981 | VD->setInvalidDecl(); | ||||
11982 | return; | ||||
11983 | } | ||||
11984 | |||||
11985 | // Don't bother complaining about constructors or destructors, | ||||
11986 | // though. | ||||
11987 | } | ||||
11988 | |||||
11989 | void Sema::ActOnUninitializedDecl(Decl *RealDecl) { | ||||
11990 | // If there is no declaration, there was an error parsing it. Just ignore it. | ||||
11991 | if (!RealDecl) | ||||
11992 | return; | ||||
11993 | |||||
11994 | if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { | ||||
11995 | QualType Type = Var->getType(); | ||||
11996 | |||||
11997 | // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. | ||||
11998 | if (isa<DecompositionDecl>(RealDecl)) { | ||||
11999 | Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; | ||||
12000 | Var->setInvalidDecl(); | ||||
12001 | return; | ||||
12002 | } | ||||
12003 | |||||
12004 | if (Type->isUndeducedType() && | ||||
12005 | DeduceVariableDeclarationType(Var, false, nullptr)) | ||||
12006 | return; | ||||
12007 | |||||
12008 | // C++11 [class.static.data]p3: A static data member can be declared with | ||||
12009 | // the constexpr specifier; if so, its declaration shall specify | ||||
12010 | // a brace-or-equal-initializer. | ||||
12011 | // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to | ||||
12012 | // the definition of a variable [...] or the declaration of a static data | ||||
12013 | // member. | ||||
12014 | if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && | ||||
12015 | !Var->isThisDeclarationADemotedDefinition()) { | ||||
12016 | if (Var->isStaticDataMember()) { | ||||
12017 | // C++1z removes the relevant rule; the in-class declaration is always | ||||
12018 | // a definition there. | ||||
12019 | if (!getLangOpts().CPlusPlus17 && | ||||
12020 | !Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
12021 | Diag(Var->getLocation(), | ||||
12022 | diag::err_constexpr_static_mem_var_requires_init) | ||||
12023 | << Var->getDeclName(); | ||||
12024 | Var->setInvalidDecl(); | ||||
12025 | return; | ||||
12026 | } | ||||
12027 | } else { | ||||
12028 | Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); | ||||
12029 | Var->setInvalidDecl(); | ||||
12030 | return; | ||||
12031 | } | ||||
12032 | } | ||||
12033 | |||||
12034 | // OpenCL v1.1 s6.5.3: variables declared in the constant address space must | ||||
12035 | // be initialized. | ||||
12036 | if (!Var->isInvalidDecl() && | ||||
12037 | Var->getType().getAddressSpace() == LangAS::opencl_constant && | ||||
12038 | Var->getStorageClass() != SC_Extern && !Var->getInit()) { | ||||
12039 | Diag(Var->getLocation(), diag::err_opencl_constant_no_init); | ||||
12040 | Var->setInvalidDecl(); | ||||
12041 | return; | ||||
12042 | } | ||||
12043 | |||||
12044 | VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); | ||||
12045 | if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && | ||||
12046 | Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||
12047 | checkNonTrivialCUnion(Var->getType(), Var->getLocation(), | ||||
12048 | NTCUC_DefaultInitializedObject, NTCUK_Init); | ||||
12049 | |||||
12050 | |||||
12051 | switch (DefKind) { | ||||
12052 | case VarDecl::Definition: | ||||
12053 | if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) | ||||
12054 | break; | ||||
12055 | |||||
12056 | // We have an out-of-line definition of a static data member | ||||
12057 | // that has an in-class initializer, so we type-check this like | ||||
12058 | // a declaration. | ||||
12059 | // | ||||
12060 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
12061 | |||||
12062 | case VarDecl::DeclarationOnly: | ||||
12063 | // It's only a declaration. | ||||
12064 | |||||
12065 | // Block scope. C99 6.7p7: If an identifier for an object is | ||||
12066 | // declared with no linkage (C99 6.2.2p6), the type for the | ||||
12067 | // object shall be complete. | ||||
12068 | if (!Type->isDependentType() && Var->isLocalVarDecl() && | ||||
12069 | !Var->hasLinkage() && !Var->isInvalidDecl() && | ||||
12070 | RequireCompleteType(Var->getLocation(), Type, | ||||
12071 | diag::err_typecheck_decl_incomplete_type)) | ||||
12072 | Var->setInvalidDecl(); | ||||
12073 | |||||
12074 | // Make sure that the type is not abstract. | ||||
12075 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | ||||
12076 | RequireNonAbstractType(Var->getLocation(), Type, | ||||
12077 | diag::err_abstract_type_in_decl, | ||||
12078 | AbstractVariableType)) | ||||
12079 | Var->setInvalidDecl(); | ||||
12080 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | ||||
12081 | Var->getStorageClass() == SC_PrivateExtern) { | ||||
12082 | Diag(Var->getLocation(), diag::warn_private_extern); | ||||
12083 | Diag(Var->getLocation(), diag::note_private_extern); | ||||
12084 | } | ||||
12085 | |||||
12086 | return; | ||||
12087 | |||||
12088 | case VarDecl::TentativeDefinition: | ||||
12089 | // File scope. C99 6.9.2p2: A declaration of an identifier for an | ||||
12090 | // object that has file scope without an initializer, and without a | ||||
12091 | // storage-class specifier or with the storage-class specifier "static", | ||||
12092 | // constitutes a tentative definition. Note: A tentative definition with | ||||
12093 | // external linkage is valid (C99 6.2.2p5). | ||||
12094 | if (!Var->isInvalidDecl()) { | ||||
12095 | if (const IncompleteArrayType *ArrayT | ||||
12096 | = Context.getAsIncompleteArrayType(Type)) { | ||||
12097 | if (RequireCompleteType(Var->getLocation(), | ||||
12098 | ArrayT->getElementType(), | ||||
12099 | diag::err_illegal_decl_array_incomplete_type)) | ||||
12100 | Var->setInvalidDecl(); | ||||
12101 | } else if (Var->getStorageClass() == SC_Static) { | ||||
12102 | // C99 6.9.2p3: If the declaration of an identifier for an object is | ||||
12103 | // a tentative definition and has internal linkage (C99 6.2.2p3), the | ||||
12104 | // declared type shall not be an incomplete type. | ||||
12105 | // NOTE: code such as the following | ||||
12106 | // static struct s; | ||||
12107 | // struct s { int a; }; | ||||
12108 | // is accepted by gcc. Hence here we issue a warning instead of | ||||
12109 | // an error and we do not invalidate the static declaration. | ||||
12110 | // NOTE: to avoid multiple warnings, only check the first declaration. | ||||
12111 | if (Var->isFirstDecl()) | ||||
12112 | RequireCompleteType(Var->getLocation(), Type, | ||||
12113 | diag::ext_typecheck_decl_incomplete_type); | ||||
12114 | } | ||||
12115 | } | ||||
12116 | |||||
12117 | // Record the tentative definition; we're done. | ||||
12118 | if (!Var->isInvalidDecl()) | ||||
12119 | TentativeDefinitions.push_back(Var); | ||||
12120 | return; | ||||
12121 | } | ||||
12122 | |||||
12123 | // Provide a specific diagnostic for uninitialized variable | ||||
12124 | // definitions with incomplete array type. | ||||
12125 | if (Type->isIncompleteArrayType()) { | ||||
12126 | Diag(Var->getLocation(), | ||||
12127 | diag::err_typecheck_incomplete_array_needs_initializer); | ||||
12128 | Var->setInvalidDecl(); | ||||
12129 | return; | ||||
12130 | } | ||||
12131 | |||||
12132 | // Provide a specific diagnostic for uninitialized variable | ||||
12133 | // definitions with reference type. | ||||
12134 | if (Type->isReferenceType()) { | ||||
12135 | Diag(Var->getLocation(), diag::err_reference_var_requires_init) | ||||
12136 | << Var->getDeclName() | ||||
12137 | << SourceRange(Var->getLocation(), Var->getLocation()); | ||||
12138 | Var->setInvalidDecl(); | ||||
12139 | return; | ||||
12140 | } | ||||
12141 | |||||
12142 | // Do not attempt to type-check the default initializer for a | ||||
12143 | // variable with dependent type. | ||||
12144 | if (Type->isDependentType()) | ||||
12145 | return; | ||||
12146 | |||||
12147 | if (Var->isInvalidDecl()) | ||||
12148 | return; | ||||
12149 | |||||
12150 | if (!Var->hasAttr<AliasAttr>()) { | ||||
12151 | if (RequireCompleteType(Var->getLocation(), | ||||
12152 | Context.getBaseElementType(Type), | ||||
12153 | diag::err_typecheck_decl_incomplete_type)) { | ||||
12154 | Var->setInvalidDecl(); | ||||
12155 | return; | ||||
12156 | } | ||||
12157 | } else { | ||||
12158 | return; | ||||
12159 | } | ||||
12160 | |||||
12161 | // The variable can not have an abstract class type. | ||||
12162 | if (RequireNonAbstractType(Var->getLocation(), Type, | ||||
12163 | diag::err_abstract_type_in_decl, | ||||
12164 | AbstractVariableType)) { | ||||
12165 | Var->setInvalidDecl(); | ||||
12166 | return; | ||||
12167 | } | ||||
12168 | |||||
12169 | // Check for jumps past the implicit initializer. C++0x | ||||
12170 | // clarifies that this applies to a "variable with automatic | ||||
12171 | // storage duration", not a "local variable". | ||||
12172 | // C++11 [stmt.dcl]p3 | ||||
12173 | // A program that jumps from a point where a variable with automatic | ||||
12174 | // storage duration is not in scope to a point where it is in scope is | ||||
12175 | // ill-formed unless the variable has scalar type, class type with a | ||||
12176 | // trivial default constructor and a trivial destructor, a cv-qualified | ||||
12177 | // version of one of these types, or an array of one of the preceding | ||||
12178 | // types and is declared without an initializer. | ||||
12179 | if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { | ||||
12180 | if (const RecordType *Record | ||||
12181 | = Context.getBaseElementType(Type)->getAs<RecordType>()) { | ||||
12182 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); | ||||
12183 | // Mark the function (if we're in one) for further checking even if the | ||||
12184 | // looser rules of C++11 do not require such checks, so that we can | ||||
12185 | // diagnose incompatibilities with C++98. | ||||
12186 | if (!CXXRecord->isPOD()) | ||||
12187 | setFunctionHasBranchProtectedScope(); | ||||
12188 | } | ||||
12189 | } | ||||
12190 | // In OpenCL, we can't initialize objects in the __local address space, | ||||
12191 | // even implicitly, so don't synthesize an implicit initializer. | ||||
12192 | if (getLangOpts().OpenCL && | ||||
12193 | Var->getType().getAddressSpace() == LangAS::opencl_local) | ||||
12194 | return; | ||||
12195 | // C++03 [dcl.init]p9: | ||||
12196 | // If no initializer is specified for an object, and the | ||||
12197 | // object is of (possibly cv-qualified) non-POD class type (or | ||||
12198 | // array thereof), the object shall be default-initialized; if | ||||
12199 | // the object is of const-qualified type, the underlying class | ||||
12200 | // type shall have a user-declared default | ||||
12201 | // constructor. Otherwise, if no initializer is specified for | ||||
12202 | // a non- static object, the object and its subobjects, if | ||||
12203 | // any, have an indeterminate initial value); if the object | ||||
12204 | // or any of its subobjects are of const-qualified type, the | ||||
12205 | // program is ill-formed. | ||||
12206 | // C++0x [dcl.init]p11: | ||||
12207 | // If no initializer is specified for an object, the object is | ||||
12208 | // default-initialized; [...]. | ||||
12209 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); | ||||
12210 | InitializationKind Kind | ||||
12211 | = InitializationKind::CreateDefault(Var->getLocation()); | ||||
12212 | |||||
12213 | InitializationSequence InitSeq(*this, Entity, Kind, None); | ||||
12214 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); | ||||
12215 | if (Init.isInvalid()) | ||||
12216 | Var->setInvalidDecl(); | ||||
12217 | else if (Init.get()) { | ||||
12218 | Var->setInit(MaybeCreateExprWithCleanups(Init.get())); | ||||
12219 | // This is important for template substitution. | ||||
12220 | Var->setInitStyle(VarDecl::CallInit); | ||||
12221 | } | ||||
12222 | |||||
12223 | CheckCompleteVariableDeclaration(Var); | ||||
12224 | } | ||||
12225 | } | ||||
12226 | |||||
12227 | void Sema::ActOnCXXForRangeDecl(Decl *D) { | ||||
12228 | // If there is no declaration, there was an error parsing it. Ignore it. | ||||
12229 | if (!D) | ||||
12230 | return; | ||||
12231 | |||||
12232 | VarDecl *VD = dyn_cast<VarDecl>(D); | ||||
12233 | if (!VD) { | ||||
12234 | Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); | ||||
12235 | D->setInvalidDecl(); | ||||
12236 | return; | ||||
12237 | } | ||||
12238 | |||||
12239 | VD->setCXXForRangeDecl(true); | ||||
12240 | |||||
12241 | // for-range-declaration cannot be given a storage class specifier. | ||||
12242 | int Error = -1; | ||||
12243 | switch (VD->getStorageClass()) { | ||||
12244 | case SC_None: | ||||
12245 | break; | ||||
12246 | case SC_Extern: | ||||
12247 | Error = 0; | ||||
12248 | break; | ||||
12249 | case SC_Static: | ||||
12250 | Error = 1; | ||||
12251 | break; | ||||
12252 | case SC_PrivateExtern: | ||||
12253 | Error = 2; | ||||
12254 | break; | ||||
12255 | case SC_Auto: | ||||
12256 | Error = 3; | ||||
12257 | break; | ||||
12258 | case SC_Register: | ||||
12259 | Error = 4; | ||||
12260 | break; | ||||
12261 | } | ||||
12262 | if (Error != -1) { | ||||
12263 | Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) | ||||
12264 | << VD->getDeclName() << Error; | ||||
12265 | D->setInvalidDecl(); | ||||
12266 | } | ||||
12267 | } | ||||
12268 | |||||
12269 | StmtResult | ||||
12270 | Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, | ||||
12271 | IdentifierInfo *Ident, | ||||
12272 | ParsedAttributes &Attrs, | ||||
12273 | SourceLocation AttrEnd) { | ||||
12274 | // C++1y [stmt.iter]p1: | ||||
12275 | // A range-based for statement of the form | ||||
12276 | // for ( for-range-identifier : for-range-initializer ) statement | ||||
12277 | // is equivalent to | ||||
12278 | // for ( auto&& for-range-identifier : for-range-initializer ) statement | ||||
12279 | DeclSpec DS(Attrs.getPool().getFactory()); | ||||
12280 | |||||
12281 | const char *PrevSpec; | ||||
12282 | unsigned DiagID; | ||||
12283 | DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, | ||||
12284 | getPrintingPolicy()); | ||||
12285 | |||||
12286 | Declarator D(DS, DeclaratorContext::ForContext); | ||||
12287 | D.SetIdentifier(Ident, IdentLoc); | ||||
12288 | D.takeAttributes(Attrs, AttrEnd); | ||||
12289 | |||||
12290 | D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), | ||||
12291 | IdentLoc); | ||||
12292 | Decl *Var = ActOnDeclarator(S, D); | ||||
12293 | cast<VarDecl>(Var)->setCXXForRangeDecl(true); | ||||
12294 | FinalizeDeclaration(Var); | ||||
12295 | return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, | ||||
12296 | AttrEnd.isValid() ? AttrEnd : IdentLoc); | ||||
12297 | } | ||||
12298 | |||||
12299 | void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { | ||||
12300 | if (var->isInvalidDecl()) return; | ||||
12301 | |||||
12302 | if (getLangOpts().OpenCL) { | ||||
12303 | // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an | ||||
12304 | // initialiser | ||||
12305 | if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && | ||||
12306 | !var->hasInit()) { | ||||
12307 | Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) | ||||
12308 | << 1 /*Init*/; | ||||
12309 | var->setInvalidDecl(); | ||||
12310 | return; | ||||
12311 | } | ||||
12312 | } | ||||
12313 | |||||
12314 | // In Objective-C, don't allow jumps past the implicit initialization of a | ||||
12315 | // local retaining variable. | ||||
12316 | if (getLangOpts().ObjC && | ||||
12317 | var->hasLocalStorage()) { | ||||
12318 | switch (var->getType().getObjCLifetime()) { | ||||
12319 | case Qualifiers::OCL_None: | ||||
12320 | case Qualifiers::OCL_ExplicitNone: | ||||
12321 | case Qualifiers::OCL_Autoreleasing: | ||||
12322 | break; | ||||
12323 | |||||
12324 | case Qualifiers::OCL_Weak: | ||||
12325 | case Qualifiers::OCL_Strong: | ||||
12326 | setFunctionHasBranchProtectedScope(); | ||||
12327 | break; | ||||
12328 | } | ||||
12329 | } | ||||
12330 | |||||
12331 | if (var->hasLocalStorage() && | ||||
12332 | var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||
12333 | setFunctionHasBranchProtectedScope(); | ||||
12334 | |||||
12335 | // Warn about externally-visible variables being defined without a | ||||
12336 | // prior declaration. We only want to do this for global | ||||
12337 | // declarations, but we also specifically need to avoid doing it for | ||||
12338 | // class members because the linkage of an anonymous class can | ||||
12339 | // change if it's later given a typedef name. | ||||
12340 | if (var->isThisDeclarationADefinition() && | ||||
12341 | var->getDeclContext()->getRedeclContext()->isFileContext() && | ||||
12342 | var->isExternallyVisible() && var->hasLinkage() && | ||||
12343 | !var->isInline() && !var->getDescribedVarTemplate() && | ||||
12344 | !isTemplateInstantiation(var->getTemplateSpecializationKind()) && | ||||
12345 | !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, | ||||
12346 | var->getLocation())) { | ||||
12347 | // Find a previous declaration that's not a definition. | ||||
12348 | VarDecl *prev = var->getPreviousDecl(); | ||||
12349 | while (prev && prev->isThisDeclarationADefinition()) | ||||
12350 | prev = prev->getPreviousDecl(); | ||||
12351 | |||||
12352 | if (!prev) { | ||||
12353 | Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; | ||||
12354 | Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) | ||||
12355 | << /* variable */ 0; | ||||
12356 | } | ||||
12357 | } | ||||
12358 | |||||
12359 | // Cache the result of checking for constant initialization. | ||||
12360 | Optional<bool> CacheHasConstInit; | ||||
12361 | const Expr *CacheCulprit = nullptr; | ||||
12362 | auto checkConstInit = [&]() mutable { | ||||
12363 | if (!CacheHasConstInit) | ||||
12364 | CacheHasConstInit = var->getInit()->isConstantInitializer( | ||||
12365 | Context, var->getType()->isReferenceType(), &CacheCulprit); | ||||
12366 | return *CacheHasConstInit; | ||||
12367 | }; | ||||
12368 | |||||
12369 | if (var->getTLSKind() == VarDecl::TLS_Static) { | ||||
12370 | if (var->getType().isDestructedType()) { | ||||
12371 | // GNU C++98 edits for __thread, [basic.start.term]p3: | ||||
12372 | // The type of an object with thread storage duration shall not | ||||
12373 | // have a non-trivial destructor. | ||||
12374 | Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); | ||||
12375 | if (getLangOpts().CPlusPlus11) | ||||
12376 | Diag(var->getLocation(), diag::note_use_thread_local); | ||||
12377 | } else if (getLangOpts().CPlusPlus && var->hasInit()) { | ||||
12378 | if (!checkConstInit()) { | ||||
12379 | // GNU C++98 edits for __thread, [basic.start.init]p4: | ||||
12380 | // An object of thread storage duration shall not require dynamic | ||||
12381 | // initialization. | ||||
12382 | // FIXME: Need strict checking here. | ||||
12383 | Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) | ||||
12384 | << CacheCulprit->getSourceRange(); | ||||
12385 | if (getLangOpts().CPlusPlus11) | ||||
12386 | Diag(var->getLocation(), diag::note_use_thread_local); | ||||
12387 | } | ||||
12388 | } | ||||
12389 | } | ||||
12390 | |||||
12391 | // Apply section attributes and pragmas to global variables. | ||||
12392 | bool GlobalStorage = var->hasGlobalStorage(); | ||||
12393 | if (GlobalStorage && var->isThisDeclarationADefinition() && | ||||
12394 | !inTemplateInstantiation()) { | ||||
12395 | PragmaStack<StringLiteral *> *Stack = nullptr; | ||||
12396 | int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; | ||||
12397 | if (var->getType().isConstQualified()) | ||||
12398 | Stack = &ConstSegStack; | ||||
12399 | else if (!var->getInit()) { | ||||
12400 | Stack = &BSSSegStack; | ||||
12401 | SectionFlags |= ASTContext::PSF_Write; | ||||
12402 | } else { | ||||
12403 | Stack = &DataSegStack; | ||||
12404 | SectionFlags |= ASTContext::PSF_Write; | ||||
12405 | } | ||||
12406 | if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) | ||||
12407 | var->addAttr(SectionAttr::CreateImplicit( | ||||
12408 | Context, Stack->CurrentValue->getString(), | ||||
12409 | Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||
12410 | SectionAttr::Declspec_allocate)); | ||||
12411 | if (const SectionAttr *SA = var->getAttr<SectionAttr>()) | ||||
12412 | if (UnifySection(SA->getName(), SectionFlags, var)) | ||||
12413 | var->dropAttr<SectionAttr>(); | ||||
12414 | |||||
12415 | // Apply the init_seg attribute if this has an initializer. If the | ||||
12416 | // initializer turns out to not be dynamic, we'll end up ignoring this | ||||
12417 | // attribute. | ||||
12418 | if (CurInitSeg && var->getInit()) | ||||
12419 | var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), | ||||
12420 | CurInitSegLoc, | ||||
12421 | AttributeCommonInfo::AS_Pragma)); | ||||
12422 | } | ||||
12423 | |||||
12424 | // All the following checks are C++ only. | ||||
12425 | if (!getLangOpts().CPlusPlus) { | ||||
12426 | // If this variable must be emitted, add it as an initializer for the | ||||
12427 | // current module. | ||||
12428 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | ||||
12429 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | ||||
12430 | return; | ||||
12431 | } | ||||
12432 | |||||
12433 | if (auto *DD = dyn_cast<DecompositionDecl>(var)) | ||||
12434 | CheckCompleteDecompositionDeclaration(DD); | ||||
12435 | |||||
12436 | QualType type = var->getType(); | ||||
12437 | if (type->isDependentType()) return; | ||||
12438 | |||||
12439 | if (var->hasAttr<BlocksAttr>()) | ||||
12440 | getCurFunction()->addByrefBlockVar(var); | ||||
12441 | |||||
12442 | Expr *Init = var->getInit(); | ||||
12443 | bool IsGlobal = GlobalStorage && !var->isStaticLocal(); | ||||
12444 | QualType baseType = Context.getBaseElementType(type); | ||||
12445 | |||||
12446 | if (Init && !Init->isValueDependent()) { | ||||
12447 | if (var->isConstexpr()) { | ||||
12448 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
12449 | if (!var->evaluateValue(Notes) || !var->isInitICE()) { | ||||
12450 | SourceLocation DiagLoc = var->getLocation(); | ||||
12451 | // If the note doesn't add any useful information other than a source | ||||
12452 | // location, fold it into the primary diagnostic. | ||||
12453 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | ||||
12454 | diag::note_invalid_subexpr_in_const_expr) { | ||||
12455 | DiagLoc = Notes[0].first; | ||||
12456 | Notes.clear(); | ||||
12457 | } | ||||
12458 | Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) | ||||
12459 | << var << Init->getSourceRange(); | ||||
12460 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) | ||||
12461 | Diag(Notes[I].first, Notes[I].second); | ||||
12462 | } | ||||
12463 | } else if (var->mightBeUsableInConstantExpressions(Context)) { | ||||
12464 | // Check whether the initializer of a const variable of integral or | ||||
12465 | // enumeration type is an ICE now, since we can't tell whether it was | ||||
12466 | // initialized by a constant expression if we check later. | ||||
12467 | var->checkInitIsICE(); | ||||
12468 | } | ||||
12469 | |||||
12470 | // Don't emit further diagnostics about constexpr globals since they | ||||
12471 | // were just diagnosed. | ||||
12472 | if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { | ||||
12473 | // FIXME: Need strict checking in C++03 here. | ||||
12474 | bool DiagErr = getLangOpts().CPlusPlus11 | ||||
12475 | ? !var->checkInitIsICE() : !checkConstInit(); | ||||
12476 | if (DiagErr) { | ||||
12477 | auto *Attr = var->getAttr<ConstInitAttr>(); | ||||
12478 | Diag(var->getLocation(), diag::err_require_constant_init_failed) | ||||
12479 | << Init->getSourceRange(); | ||||
12480 | Diag(Attr->getLocation(), | ||||
12481 | diag::note_declared_required_constant_init_here) | ||||
12482 | << Attr->getRange() << Attr->isConstinit(); | ||||
12483 | if (getLangOpts().CPlusPlus11) { | ||||
12484 | APValue Value; | ||||
12485 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
12486 | Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); | ||||
12487 | for (auto &it : Notes) | ||||
12488 | Diag(it.first, it.second); | ||||
12489 | } else { | ||||
12490 | Diag(CacheCulprit->getExprLoc(), | ||||
12491 | diag::note_invalid_subexpr_in_const_expr) | ||||
12492 | << CacheCulprit->getSourceRange(); | ||||
12493 | } | ||||
12494 | } | ||||
12495 | } | ||||
12496 | else if (!var->isConstexpr() && IsGlobal && | ||||
12497 | !getDiagnostics().isIgnored(diag::warn_global_constructor, | ||||
12498 | var->getLocation())) { | ||||
12499 | // Warn about globals which don't have a constant initializer. Don't | ||||
12500 | // warn about globals with a non-trivial destructor because we already | ||||
12501 | // warned about them. | ||||
12502 | CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); | ||||
12503 | if (!(RD && !RD->hasTrivialDestructor())) { | ||||
12504 | if (!checkConstInit()) | ||||
12505 | Diag(var->getLocation(), diag::warn_global_constructor) | ||||
12506 | << Init->getSourceRange(); | ||||
12507 | } | ||||
12508 | } | ||||
12509 | } | ||||
12510 | |||||
12511 | // Require the destructor. | ||||
12512 | if (const RecordType *recordType = baseType->getAs<RecordType>()) | ||||
12513 | FinalizeVarWithDestructor(var, recordType); | ||||
12514 | |||||
12515 | // If this variable must be emitted, add it as an initializer for the current | ||||
12516 | // module. | ||||
12517 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | ||||
12518 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | ||||
12519 | } | ||||
12520 | |||||
12521 | /// Determines if a variable's alignment is dependent. | ||||
12522 | static bool hasDependentAlignment(VarDecl *VD) { | ||||
12523 | if (VD->getType()->isDependentType()) | ||||
12524 | return true; | ||||
12525 | for (auto *I : VD->specific_attrs<AlignedAttr>()) | ||||
12526 | if (I->isAlignmentDependent()) | ||||
12527 | return true; | ||||
12528 | return false; | ||||
12529 | } | ||||
12530 | |||||
12531 | /// Check if VD needs to be dllexport/dllimport due to being in a | ||||
12532 | /// dllexport/import function. | ||||
12533 | void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { | ||||
12534 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 12534, __PRETTY_FUNCTION__)); | ||||
12535 | |||||
12536 | auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | ||||
12537 | |||||
12538 | // Find outermost function when VD is in lambda function. | ||||
12539 | while (FD && !getDLLAttr(FD) && | ||||
12540 | !FD->hasAttr<DLLExportStaticLocalAttr>() && | ||||
12541 | !FD->hasAttr<DLLImportStaticLocalAttr>()) { | ||||
12542 | FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); | ||||
12543 | } | ||||
12544 | |||||
12545 | if (!FD) | ||||
12546 | return; | ||||
12547 | |||||
12548 | // Static locals inherit dll attributes from their function. | ||||
12549 | if (Attr *A = getDLLAttr(FD)) { | ||||
12550 | auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); | ||||
12551 | NewAttr->setInherited(true); | ||||
12552 | VD->addAttr(NewAttr); | ||||
12553 | } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { | ||||
12554 | auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); | ||||
12555 | NewAttr->setInherited(true); | ||||
12556 | VD->addAttr(NewAttr); | ||||
12557 | |||||
12558 | // Export this function to enforce exporting this static variable even | ||||
12559 | // if it is not used in this compilation unit. | ||||
12560 | if (!FD->hasAttr<DLLExportAttr>()) | ||||
12561 | FD->addAttr(NewAttr); | ||||
12562 | |||||
12563 | } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { | ||||
12564 | auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); | ||||
12565 | NewAttr->setInherited(true); | ||||
12566 | VD->addAttr(NewAttr); | ||||
12567 | } | ||||
12568 | } | ||||
12569 | |||||
12570 | /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform | ||||
12571 | /// any semantic actions necessary after any initializer has been attached. | ||||
12572 | void Sema::FinalizeDeclaration(Decl *ThisDecl) { | ||||
12573 | // Note that we are no longer parsing the initializer for this declaration. | ||||
12574 | ParsingInitForAutoVars.erase(ThisDecl); | ||||
12575 | |||||
12576 | VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); | ||||
12577 | if (!VD) | ||||
12578 | return; | ||||
12579 | |||||
12580 | // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active | ||||
12581 | if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && | ||||
12582 | !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { | ||||
12583 | if (PragmaClangBSSSection.Valid) | ||||
12584 | VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( | ||||
12585 | Context, PragmaClangBSSSection.SectionName, | ||||
12586 | PragmaClangBSSSection.PragmaLocation, | ||||
12587 | AttributeCommonInfo::AS_Pragma)); | ||||
12588 | if (PragmaClangDataSection.Valid) | ||||
12589 | VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( | ||||
12590 | Context, PragmaClangDataSection.SectionName, | ||||
12591 | PragmaClangDataSection.PragmaLocation, | ||||
12592 | AttributeCommonInfo::AS_Pragma)); | ||||
12593 | if (PragmaClangRodataSection.Valid) | ||||
12594 | VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( | ||||
12595 | Context, PragmaClangRodataSection.SectionName, | ||||
12596 | PragmaClangRodataSection.PragmaLocation, | ||||
12597 | AttributeCommonInfo::AS_Pragma)); | ||||
12598 | } | ||||
12599 | |||||
12600 | if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { | ||||
12601 | for (auto *BD : DD->bindings()) { | ||||
12602 | FinalizeDeclaration(BD); | ||||
12603 | } | ||||
12604 | } | ||||
12605 | |||||
12606 | checkAttributesAfterMerging(*this, *VD); | ||||
12607 | |||||
12608 | // Perform TLS alignment check here after attributes attached to the variable | ||||
12609 | // which may affect the alignment have been processed. Only perform the check | ||||
12610 | // if the target has a maximum TLS alignment (zero means no constraints). | ||||
12611 | if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { | ||||
12612 | // Protect the check so that it's not performed on dependent types and | ||||
12613 | // dependent alignments (we can't determine the alignment in that case). | ||||
12614 | if (VD->getTLSKind() && !hasDependentAlignment(VD) && | ||||
12615 | !VD->isInvalidDecl()) { | ||||
12616 | CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); | ||||
12617 | if (Context.getDeclAlign(VD) > MaxAlignChars) { | ||||
12618 | Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) | ||||
12619 | << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD | ||||
12620 | << (unsigned)MaxAlignChars.getQuantity(); | ||||
12621 | } | ||||
12622 | } | ||||
12623 | } | ||||
12624 | |||||
12625 | if (VD->isStaticLocal()) { | ||||
12626 | CheckStaticLocalForDllExport(VD); | ||||
12627 | |||||
12628 | if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { | ||||
12629 | // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ | ||||
12630 | // function, only __shared__ variables or variables without any device | ||||
12631 | // memory qualifiers may be declared with static storage class. | ||||
12632 | // Note: It is unclear how a function-scope non-const static variable | ||||
12633 | // without device memory qualifier is implemented, therefore only static | ||||
12634 | // const variable without device memory qualifier is allowed. | ||||
12635 | [&]() { | ||||
12636 | if (!getLangOpts().CUDA) | ||||
12637 | return; | ||||
12638 | if (VD->hasAttr<CUDASharedAttr>()) | ||||
12639 | return; | ||||
12640 | if (VD->getType().isConstQualified() && | ||||
12641 | !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) | ||||
12642 | return; | ||||
12643 | if (CUDADiagIfDeviceCode(VD->getLocation(), | ||||
12644 | diag::err_device_static_local_var) | ||||
12645 | << CurrentCUDATarget()) | ||||
12646 | VD->setInvalidDecl(); | ||||
12647 | }(); | ||||
12648 | } | ||||
12649 | } | ||||
12650 | |||||
12651 | // Perform check for initializers of device-side global variables. | ||||
12652 | // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA | ||||
12653 | // 7.5). We must also apply the same checks to all __shared__ | ||||
12654 | // variables whether they are local or not. CUDA also allows | ||||
12655 | // constant initializers for __constant__ and __device__ variables. | ||||
12656 | if (getLangOpts().CUDA) | ||||
12657 | checkAllowedCUDAInitializer(VD); | ||||
12658 | |||||
12659 | // Grab the dllimport or dllexport attribute off of the VarDecl. | ||||
12660 | const InheritableAttr *DLLAttr = getDLLAttr(VD); | ||||
12661 | |||||
12662 | // Imported static data members cannot be defined out-of-line. | ||||
12663 | if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { | ||||
12664 | if (VD->isStaticDataMember() && VD->isOutOfLine() && | ||||
12665 | VD->isThisDeclarationADefinition()) { | ||||
12666 | // We allow definitions of dllimport class template static data members | ||||
12667 | // with a warning. | ||||
12668 | CXXRecordDecl *Context = | ||||
12669 | cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); | ||||
12670 | bool IsClassTemplateMember = | ||||
12671 | isa<ClassTemplatePartialSpecializationDecl>(Context) || | ||||
12672 | Context->getDescribedClassTemplate(); | ||||
12673 | |||||
12674 | Diag(VD->getLocation(), | ||||
12675 | IsClassTemplateMember | ||||
12676 | ? diag::warn_attribute_dllimport_static_field_definition | ||||
12677 | : diag::err_attribute_dllimport_static_field_definition); | ||||
12678 | Diag(IA->getLocation(), diag::note_attribute); | ||||
12679 | if (!IsClassTemplateMember) | ||||
12680 | VD->setInvalidDecl(); | ||||
12681 | } | ||||
12682 | } | ||||
12683 | |||||
12684 | // dllimport/dllexport variables cannot be thread local, their TLS index | ||||
12685 | // isn't exported with the variable. | ||||
12686 | if (DLLAttr && VD->getTLSKind()) { | ||||
12687 | auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | ||||
12688 | if (F && getDLLAttr(F)) { | ||||
12689 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 12689, __PRETTY_FUNCTION__)); | ||||
12690 | // But if this is a static local in a dlimport/dllexport function, the | ||||
12691 | // function will never be inlined, which means the var would never be | ||||
12692 | // imported, so having it marked import/export is safe. | ||||
12693 | } else { | ||||
12694 | Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD | ||||
12695 | << DLLAttr; | ||||
12696 | VD->setInvalidDecl(); | ||||
12697 | } | ||||
12698 | } | ||||
12699 | |||||
12700 | if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { | ||||
12701 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { | ||||
12702 | Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; | ||||
12703 | VD->dropAttr<UsedAttr>(); | ||||
12704 | } | ||||
12705 | } | ||||
12706 | |||||
12707 | const DeclContext *DC = VD->getDeclContext(); | ||||
12708 | // If there's a #pragma GCC visibility in scope, and this isn't a class | ||||
12709 | // member, set the visibility of this variable. | ||||
12710 | if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) | ||||
12711 | AddPushedVisibilityAttribute(VD); | ||||
12712 | |||||
12713 | // FIXME: Warn on unused var template partial specializations. | ||||
12714 | if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) | ||||
12715 | MarkUnusedFileScopedDecl(VD); | ||||
12716 | |||||
12717 | // Now we have parsed the initializer and can update the table of magic | ||||
12718 | // tag values. | ||||
12719 | if (!VD->hasAttr<TypeTagForDatatypeAttr>() || | ||||
12720 | !VD->getType()->isIntegralOrEnumerationType()) | ||||
12721 | return; | ||||
12722 | |||||
12723 | for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { | ||||
12724 | const Expr *MagicValueExpr = VD->getInit(); | ||||
12725 | if (!MagicValueExpr) { | ||||
12726 | continue; | ||||
12727 | } | ||||
12728 | llvm::APSInt MagicValueInt; | ||||
12729 | if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { | ||||
12730 | Diag(I->getRange().getBegin(), | ||||
12731 | diag::err_type_tag_for_datatype_not_ice) | ||||
12732 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | ||||
12733 | continue; | ||||
12734 | } | ||||
12735 | if (MagicValueInt.getActiveBits() > 64) { | ||||
12736 | Diag(I->getRange().getBegin(), | ||||
12737 | diag::err_type_tag_for_datatype_too_large) | ||||
12738 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | ||||
12739 | continue; | ||||
12740 | } | ||||
12741 | uint64_t MagicValue = MagicValueInt.getZExtValue(); | ||||
12742 | RegisterTypeTagForDatatype(I->getArgumentKind(), | ||||
12743 | MagicValue, | ||||
12744 | I->getMatchingCType(), | ||||
12745 | I->getLayoutCompatible(), | ||||
12746 | I->getMustBeNull()); | ||||
12747 | } | ||||
12748 | } | ||||
12749 | |||||
12750 | static bool hasDeducedAuto(DeclaratorDecl *DD) { | ||||
12751 | auto *VD = dyn_cast<VarDecl>(DD); | ||||
12752 | return VD && !VD->getType()->hasAutoForTrailingReturnType(); | ||||
12753 | } | ||||
12754 | |||||
12755 | Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, | ||||
12756 | ArrayRef<Decl *> Group) { | ||||
12757 | SmallVector<Decl*, 8> Decls; | ||||
12758 | |||||
12759 | if (DS.isTypeSpecOwned()) | ||||
12760 | Decls.push_back(DS.getRepAsDecl()); | ||||
12761 | |||||
12762 | DeclaratorDecl *FirstDeclaratorInGroup = nullptr; | ||||
12763 | DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; | ||||
12764 | bool DiagnosedMultipleDecomps = false; | ||||
12765 | DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; | ||||
12766 | bool DiagnosedNonDeducedAuto = false; | ||||
12767 | |||||
12768 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | ||||
12769 | if (Decl *D = Group[i]) { | ||||
12770 | // For declarators, there are some additional syntactic-ish checks we need | ||||
12771 | // to perform. | ||||
12772 | if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { | ||||
12773 | if (!FirstDeclaratorInGroup) | ||||
12774 | FirstDeclaratorInGroup = DD; | ||||
12775 | if (!FirstDecompDeclaratorInGroup) | ||||
12776 | FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); | ||||
12777 | if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && | ||||
12778 | !hasDeducedAuto(DD)) | ||||
12779 | FirstNonDeducedAutoInGroup = DD; | ||||
12780 | |||||
12781 | if (FirstDeclaratorInGroup != DD) { | ||||
12782 | // A decomposition declaration cannot be combined with any other | ||||
12783 | // declaration in the same group. | ||||
12784 | if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { | ||||
12785 | Diag(FirstDecompDeclaratorInGroup->getLocation(), | ||||
12786 | diag::err_decomp_decl_not_alone) | ||||
12787 | << FirstDeclaratorInGroup->getSourceRange() | ||||
12788 | << DD->getSourceRange(); | ||||
12789 | DiagnosedMultipleDecomps = true; | ||||
12790 | } | ||||
12791 | |||||
12792 | // A declarator that uses 'auto' in any way other than to declare a | ||||
12793 | // variable with a deduced type cannot be combined with any other | ||||
12794 | // declarator in the same group. | ||||
12795 | if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { | ||||
12796 | Diag(FirstNonDeducedAutoInGroup->getLocation(), | ||||
12797 | diag::err_auto_non_deduced_not_alone) | ||||
12798 | << FirstNonDeducedAutoInGroup->getType() | ||||
12799 | ->hasAutoForTrailingReturnType() | ||||
12800 | << FirstDeclaratorInGroup->getSourceRange() | ||||
12801 | << DD->getSourceRange(); | ||||
12802 | DiagnosedNonDeducedAuto = true; | ||||
12803 | } | ||||
12804 | } | ||||
12805 | } | ||||
12806 | |||||
12807 | Decls.push_back(D); | ||||
12808 | } | ||||
12809 | } | ||||
12810 | |||||
12811 | if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { | ||||
12812 | if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { | ||||
12813 | handleTagNumbering(Tag, S); | ||||
12814 | if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && | ||||
12815 | getLangOpts().CPlusPlus) | ||||
12816 | Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); | ||||
12817 | } | ||||
12818 | } | ||||
12819 | |||||
12820 | return BuildDeclaratorGroup(Decls); | ||||
12821 | } | ||||
12822 | |||||
12823 | /// BuildDeclaratorGroup - convert a list of declarations into a declaration | ||||
12824 | /// group, performing any necessary semantic checking. | ||||
12825 | Sema::DeclGroupPtrTy | ||||
12826 | Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { | ||||
12827 | // C++14 [dcl.spec.auto]p7: (DR1347) | ||||
12828 | // If the type that replaces the placeholder type is not the same in each | ||||
12829 | // deduction, the program is ill-formed. | ||||
12830 | if (Group.size() > 1) { | ||||
12831 | QualType Deduced; | ||||
12832 | VarDecl *DeducedDecl = nullptr; | ||||
12833 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | ||||
12834 | VarDecl *D = dyn_cast<VarDecl>(Group[i]); | ||||
12835 | if (!D || D->isInvalidDecl()) | ||||
12836 | break; | ||||
12837 | DeducedType *DT = D->getType()->getContainedDeducedType(); | ||||
12838 | if (!DT || DT->getDeducedType().isNull()) | ||||
12839 | continue; | ||||
12840 | if (Deduced.isNull()) { | ||||
12841 | Deduced = DT->getDeducedType(); | ||||
12842 | DeducedDecl = D; | ||||
12843 | } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { | ||||
12844 | auto *AT = dyn_cast<AutoType>(DT); | ||||
12845 | Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), | ||||
12846 | diag::err_auto_different_deductions) | ||||
12847 | << (AT ? (unsigned)AT->getKeyword() : 3) | ||||
12848 | << Deduced << DeducedDecl->getDeclName() | ||||
12849 | << DT->getDeducedType() << D->getDeclName() | ||||
12850 | << DeducedDecl->getInit()->getSourceRange() | ||||
12851 | << D->getInit()->getSourceRange(); | ||||
12852 | D->setInvalidDecl(); | ||||
12853 | break; | ||||
12854 | } | ||||
12855 | } | ||||
12856 | } | ||||
12857 | |||||
12858 | ActOnDocumentableDecls(Group); | ||||
12859 | |||||
12860 | return DeclGroupPtrTy::make( | ||||
12861 | DeclGroupRef::Create(Context, Group.data(), Group.size())); | ||||
12862 | } | ||||
12863 | |||||
12864 | void Sema::ActOnDocumentableDecl(Decl *D) { | ||||
12865 | ActOnDocumentableDecls(D); | ||||
12866 | } | ||||
12867 | |||||
12868 | void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { | ||||
12869 | // Don't parse the comment if Doxygen diagnostics are ignored. | ||||
12870 | if (Group.empty() || !Group[0]) | ||||
12871 | return; | ||||
12872 | |||||
12873 | if (Diags.isIgnored(diag::warn_doc_param_not_found, | ||||
12874 | Group[0]->getLocation()) && | ||||
12875 | Diags.isIgnored(diag::warn_unknown_comment_command_name, | ||||
12876 | Group[0]->getLocation())) | ||||
12877 | return; | ||||
12878 | |||||
12879 | if (Group.size() >= 2) { | ||||
12880 | // This is a decl group. Normally it will contain only declarations | ||||
12881 | // produced from declarator list. But in case we have any definitions or | ||||
12882 | // additional declaration references: | ||||
12883 | // 'typedef struct S {} S;' | ||||
12884 | // 'typedef struct S *S;' | ||||
12885 | // 'struct S *pS;' | ||||
12886 | // FinalizeDeclaratorGroup adds these as separate declarations. | ||||
12887 | Decl *MaybeTagDecl = Group[0]; | ||||
12888 | if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { | ||||
12889 | Group = Group.slice(1); | ||||
12890 | } | ||||
12891 | } | ||||
12892 | |||||
12893 | // FIMXE: We assume every Decl in the group is in the same file. | ||||
12894 | // This is false when preprocessor constructs the group from decls in | ||||
12895 | // different files (e. g. macros or #include). | ||||
12896 | Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); | ||||
12897 | } | ||||
12898 | |||||
12899 | /// Common checks for a parameter-declaration that should apply to both function | ||||
12900 | /// parameters and non-type template parameters. | ||||
12901 | void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { | ||||
12902 | // Check that there are no default arguments inside the type of this | ||||
12903 | // parameter. | ||||
12904 | if (getLangOpts().CPlusPlus) | ||||
12905 | CheckExtraCXXDefaultArguments(D); | ||||
12906 | |||||
12907 | // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). | ||||
12908 | if (D.getCXXScopeSpec().isSet()) { | ||||
12909 | Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) | ||||
12910 | << D.getCXXScopeSpec().getRange(); | ||||
12911 | } | ||||
12912 | |||||
12913 | // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a | ||||
12914 | // simple identifier except [...irrelevant cases...]. | ||||
12915 | switch (D.getName().getKind()) { | ||||
12916 | case UnqualifiedIdKind::IK_Identifier: | ||||
12917 | break; | ||||
12918 | |||||
12919 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||
12920 | case UnqualifiedIdKind::IK_ConversionFunctionId: | ||||
12921 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||
12922 | case UnqualifiedIdKind::IK_ConstructorName: | ||||
12923 | case UnqualifiedIdKind::IK_DestructorName: | ||||
12924 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||
12925 | case UnqualifiedIdKind::IK_DeductionGuideName: | ||||
12926 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) | ||||
12927 | << GetNameForDeclarator(D).getName(); | ||||
12928 | break; | ||||
12929 | |||||
12930 | case UnqualifiedIdKind::IK_TemplateId: | ||||
12931 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | ||||
12932 | // GetNameForDeclarator would not produce a useful name in this case. | ||||
12933 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); | ||||
12934 | break; | ||||
12935 | } | ||||
12936 | } | ||||
12937 | |||||
12938 | /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() | ||||
12939 | /// to introduce parameters into function prototype scope. | ||||
12940 | Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { | ||||
12941 | const DeclSpec &DS = D.getDeclSpec(); | ||||
12942 | |||||
12943 | // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. | ||||
12944 | |||||
12945 | // C++03 [dcl.stc]p2 also permits 'auto'. | ||||
12946 | StorageClass SC = SC_None; | ||||
12947 | if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { | ||||
12948 | SC = SC_Register; | ||||
12949 | // In C++11, the 'register' storage class specifier is deprecated. | ||||
12950 | // In C++17, it is not allowed, but we tolerate it as an extension. | ||||
12951 | if (getLangOpts().CPlusPlus11) { | ||||
12952 | Diag(DS.getStorageClassSpecLoc(), | ||||
12953 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | ||||
12954 | : diag::warn_deprecated_register) | ||||
12955 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||
12956 | } | ||||
12957 | } else if (getLangOpts().CPlusPlus && | ||||
12958 | DS.getStorageClassSpec() == DeclSpec::SCS_auto) { | ||||
12959 | SC = SC_Auto; | ||||
12960 | } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { | ||||
12961 | Diag(DS.getStorageClassSpecLoc(), | ||||
12962 | diag::err_invalid_storage_class_in_func_decl); | ||||
12963 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||
12964 | } | ||||
12965 | |||||
12966 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | ||||
12967 | Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) | ||||
12968 | << DeclSpec::getSpecifierName(TSCS); | ||||
12969 | if (DS.isInlineSpecified()) | ||||
12970 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | ||||
12971 | << getLangOpts().CPlusPlus17; | ||||
12972 | if (DS.hasConstexprSpecifier()) | ||||
12973 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) | ||||
12974 | << 0 << D.getDeclSpec().getConstexprSpecifier(); | ||||
12975 | |||||
12976 | DiagnoseFunctionSpecifiers(DS); | ||||
12977 | |||||
12978 | CheckFunctionOrTemplateParamDeclarator(S, D); | ||||
12979 | |||||
12980 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||
12981 | QualType parmDeclType = TInfo->getType(); | ||||
12982 | |||||
12983 | // Check for redeclaration of parameters, e.g. int foo(int x, int x); | ||||
12984 | IdentifierInfo *II = D.getIdentifier(); | ||||
12985 | if (II) { | ||||
12986 | LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, | ||||
12987 | ForVisibleRedeclaration); | ||||
12988 | LookupName(R, S); | ||||
12989 | if (R.isSingleResult()) { | ||||
12990 | NamedDecl *PrevDecl = R.getFoundDecl(); | ||||
12991 | if (PrevDecl->isTemplateParameter()) { | ||||
12992 | // Maybe we will complain about the shadowed template parameter. | ||||
12993 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | ||||
12994 | // Just pretend that we didn't see the previous declaration. | ||||
12995 | PrevDecl = nullptr; | ||||
12996 | } else if (S->isDeclScope(PrevDecl)) { | ||||
12997 | Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; | ||||
12998 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||
12999 | |||||
13000 | // Recover by removing the name | ||||
13001 | II = nullptr; | ||||
13002 | D.SetIdentifier(nullptr, D.getIdentifierLoc()); | ||||
13003 | D.setInvalidType(true); | ||||
13004 | } | ||||
13005 | } | ||||
13006 | } | ||||
13007 | |||||
13008 | // Temporarily put parameter variables in the translation unit, not | ||||
13009 | // the enclosing context. This prevents them from accidentally | ||||
13010 | // looking like class members in C++. | ||||
13011 | ParmVarDecl *New = | ||||
13012 | CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), | ||||
13013 | D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); | ||||
13014 | |||||
13015 | if (D.isInvalidType()) | ||||
13016 | New->setInvalidDecl(); | ||||
13017 | |||||
13018 | assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void> (0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13018, __PRETTY_FUNCTION__)); | ||||
13019 | assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast< void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13019, __PRETTY_FUNCTION__)); | ||||
13020 | New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, | ||||
13021 | S->getNextFunctionPrototypeIndex()); | ||||
13022 | |||||
13023 | // Add the parameter declaration into this scope. | ||||
13024 | S->AddDecl(New); | ||||
13025 | if (II) | ||||
13026 | IdResolver.AddDecl(New); | ||||
13027 | |||||
13028 | ProcessDeclAttributes(S, New, D); | ||||
13029 | |||||
13030 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||
13031 | Diag(New->getLocation(), diag::err_module_private_local) | ||||
13032 | << 1 << New->getDeclName() | ||||
13033 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||
13034 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||
13035 | |||||
13036 | if (New->hasAttr<BlocksAttr>()) { | ||||
13037 | Diag(New->getLocation(), diag::err_block_on_nonlocal); | ||||
13038 | } | ||||
13039 | return New; | ||||
13040 | } | ||||
13041 | |||||
13042 | /// Synthesizes a variable for a parameter arising from a | ||||
13043 | /// typedef. | ||||
13044 | ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, | ||||
13045 | SourceLocation Loc, | ||||
13046 | QualType T) { | ||||
13047 | /* FIXME: setting StartLoc == Loc. | ||||
13048 | Would it be worth to modify callers so as to provide proper source | ||||
13049 | location for the unnamed parameters, embedding the parameter's type? */ | ||||
13050 | ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, | ||||
13051 | T, Context.getTrivialTypeSourceInfo(T, Loc), | ||||
13052 | SC_None, nullptr); | ||||
13053 | Param->setImplicit(); | ||||
13054 | return Param; | ||||
13055 | } | ||||
13056 | |||||
13057 | void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { | ||||
13058 | // Don't diagnose unused-parameter errors in template instantiations; we | ||||
13059 | // will already have done so in the template itself. | ||||
13060 | if (inTemplateInstantiation()) | ||||
13061 | return; | ||||
13062 | |||||
13063 | for (const ParmVarDecl *Parameter : Parameters) { | ||||
13064 | if (!Parameter->isReferenced() && Parameter->getDeclName() && | ||||
13065 | !Parameter->hasAttr<UnusedAttr>()) { | ||||
13066 | Diag(Parameter->getLocation(), diag::warn_unused_parameter) | ||||
13067 | << Parameter->getDeclName(); | ||||
13068 | } | ||||
13069 | } | ||||
13070 | } | ||||
13071 | |||||
13072 | void Sema::DiagnoseSizeOfParametersAndReturnValue( | ||||
13073 | ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { | ||||
13074 | if (LangOpts.NumLargeByValueCopy == 0) // No check. | ||||
13075 | return; | ||||
13076 | |||||
13077 | // Warn if the return value is pass-by-value and larger than the specified | ||||
13078 | // threshold. | ||||
13079 | if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { | ||||
13080 | unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); | ||||
13081 | if (Size > LangOpts.NumLargeByValueCopy) | ||||
13082 | Diag(D->getLocation(), diag::warn_return_value_size) | ||||
13083 | << D->getDeclName() << Size; | ||||
13084 | } | ||||
13085 | |||||
13086 | // Warn if any parameter is pass-by-value and larger than the specified | ||||
13087 | // threshold. | ||||
13088 | for (const ParmVarDecl *Parameter : Parameters) { | ||||
13089 | QualType T = Parameter->getType(); | ||||
13090 | if (T->isDependentType() || !T.isPODType(Context)) | ||||
13091 | continue; | ||||
13092 | unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); | ||||
13093 | if (Size > LangOpts.NumLargeByValueCopy) | ||||
13094 | Diag(Parameter->getLocation(), diag::warn_parameter_size) | ||||
13095 | << Parameter->getDeclName() << Size; | ||||
13096 | } | ||||
13097 | } | ||||
13098 | |||||
13099 | ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, | ||||
13100 | SourceLocation NameLoc, IdentifierInfo *Name, | ||||
13101 | QualType T, TypeSourceInfo *TSInfo, | ||||
13102 | StorageClass SC) { | ||||
13103 | // In ARC, infer a lifetime qualifier for appropriate parameter types. | ||||
13104 | if (getLangOpts().ObjCAutoRefCount && | ||||
13105 | T.getObjCLifetime() == Qualifiers::OCL_None && | ||||
13106 | T->isObjCLifetimeType()) { | ||||
13107 | |||||
13108 | Qualifiers::ObjCLifetime lifetime; | ||||
13109 | |||||
13110 | // Special cases for arrays: | ||||
13111 | // - if it's const, use __unsafe_unretained | ||||
13112 | // - otherwise, it's an error | ||||
13113 | if (T->isArrayType()) { | ||||
13114 | if (!T.isConstQualified()) { | ||||
13115 | if (DelayedDiagnostics.shouldDelayDiagnostics()) | ||||
13116 | DelayedDiagnostics.add( | ||||
13117 | sema::DelayedDiagnostic::makeForbiddenType( | ||||
13118 | NameLoc, diag::err_arc_array_param_no_ownership, T, false)); | ||||
13119 | else | ||||
13120 | Diag(NameLoc, diag::err_arc_array_param_no_ownership) | ||||
13121 | << TSInfo->getTypeLoc().getSourceRange(); | ||||
13122 | } | ||||
13123 | lifetime = Qualifiers::OCL_ExplicitNone; | ||||
13124 | } else { | ||||
13125 | lifetime = T->getObjCARCImplicitLifetime(); | ||||
13126 | } | ||||
13127 | T = Context.getLifetimeQualifiedType(T, lifetime); | ||||
13128 | } | ||||
13129 | |||||
13130 | ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, | ||||
13131 | Context.getAdjustedParameterType(T), | ||||
13132 | TSInfo, SC, nullptr); | ||||
13133 | |||||
13134 | // Make a note if we created a new pack in the scope of a lambda, so that | ||||
13135 | // we know that references to that pack must also be expanded within the | ||||
13136 | // lambda scope. | ||||
13137 | if (New->isParameterPack()) | ||||
13138 | if (auto *LSI = getEnclosingLambda()) | ||||
13139 | LSI->LocalPacks.push_back(New); | ||||
13140 | |||||
13141 | if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||
13142 | New->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||
13143 | checkNonTrivialCUnion(New->getType(), New->getLocation(), | ||||
13144 | NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); | ||||
13145 | |||||
13146 | // Parameters can not be abstract class types. | ||||
13147 | // For record types, this is done by the AbstractClassUsageDiagnoser once | ||||
13148 | // the class has been completely parsed. | ||||
13149 | if (!CurContext->isRecord() && | ||||
13150 | RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, | ||||
13151 | AbstractParamType)) | ||||
13152 | New->setInvalidDecl(); | ||||
13153 | |||||
13154 | // Parameter declarators cannot be interface types. All ObjC objects are | ||||
13155 | // passed by reference. | ||||
13156 | if (T->isObjCObjectType()) { | ||||
13157 | SourceLocation TypeEndLoc = | ||||
13158 | getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); | ||||
13159 | Diag(NameLoc, | ||||
13160 | diag::err_object_cannot_be_passed_returned_by_value) << 1 << T | ||||
13161 | << FixItHint::CreateInsertion(TypeEndLoc, "*"); | ||||
13162 | T = Context.getObjCObjectPointerType(T); | ||||
13163 | New->setType(T); | ||||
13164 | } | ||||
13165 | |||||
13166 | // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage | ||||
13167 | // duration shall not be qualified by an address-space qualifier." | ||||
13168 | // Since all parameters have automatic store duration, they can not have | ||||
13169 | // an address space. | ||||
13170 | if (T.getAddressSpace() != LangAS::Default && | ||||
13171 | // OpenCL allows function arguments declared to be an array of a type | ||||
13172 | // to be qualified with an address space. | ||||
13173 | !(getLangOpts().OpenCL && | ||||
13174 | (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { | ||||
13175 | Diag(NameLoc, diag::err_arg_with_address_space); | ||||
13176 | New->setInvalidDecl(); | ||||
13177 | } | ||||
13178 | |||||
13179 | return New; | ||||
13180 | } | ||||
13181 | |||||
13182 | void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, | ||||
13183 | SourceLocation LocAfterDecls) { | ||||
13184 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | ||||
13185 | |||||
13186 | // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' | ||||
13187 | // for a K&R function. | ||||
13188 | if (!FTI.hasPrototype) { | ||||
13189 | for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { | ||||
13190 | --i; | ||||
13191 | if (FTI.Params[i].Param == nullptr) { | ||||
13192 | SmallString<256> Code; | ||||
13193 | llvm::raw_svector_ostream(Code) | ||||
13194 | << " int " << FTI.Params[i].Ident->getName() << ";\n"; | ||||
13195 | Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) | ||||
13196 | << FTI.Params[i].Ident | ||||
13197 | << FixItHint::CreateInsertion(LocAfterDecls, Code); | ||||
13198 | |||||
13199 | // Implicitly declare the argument as type 'int' for lack of a better | ||||
13200 | // type. | ||||
13201 | AttributeFactory attrs; | ||||
13202 | DeclSpec DS(attrs); | ||||
13203 | const char* PrevSpec; // unused | ||||
13204 | unsigned DiagID; // unused | ||||
13205 | DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, | ||||
13206 | DiagID, Context.getPrintingPolicy()); | ||||
13207 | // Use the identifier location for the type source range. | ||||
13208 | DS.SetRangeStart(FTI.Params[i].IdentLoc); | ||||
13209 | DS.SetRangeEnd(FTI.Params[i].IdentLoc); | ||||
13210 | Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); | ||||
13211 | ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); | ||||
13212 | FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); | ||||
13213 | } | ||||
13214 | } | ||||
13215 | } | ||||
13216 | } | ||||
13217 | |||||
13218 | Decl * | ||||
13219 | Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, | ||||
13220 | MultiTemplateParamsArg TemplateParameterLists, | ||||
13221 | SkipBodyInfo *SkipBody) { | ||||
13222 | assert(getCurFunctionDecl() == nullptr && "Function parsing confused")((getCurFunctionDecl() == nullptr && "Function parsing confused" ) ? static_cast<void> (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13222, __PRETTY_FUNCTION__)); | ||||
| |||||
13223 | assert(D.isFunctionDeclarator() && "Not a function declarator!")((D.isFunctionDeclarator() && "Not a function declarator!" ) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13223, __PRETTY_FUNCTION__)); | ||||
13224 | Scope *ParentScope = FnBodyScope->getParent(); | ||||
13225 | |||||
13226 | D.setFunctionDefinitionKind(FDK_Definition); | ||||
13227 | Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); | ||||
13228 | return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); | ||||
13229 | } | ||||
13230 | |||||
13231 | void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { | ||||
13232 | Consumer.HandleInlineFunctionDefinition(D); | ||||
13233 | } | ||||
13234 | |||||
13235 | static bool | ||||
13236 | ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, | ||||
13237 | const FunctionDecl *&PossiblePrototype) { | ||||
13238 | // Don't warn about invalid declarations. | ||||
13239 | if (FD->isInvalidDecl()) | ||||
13240 | return false; | ||||
13241 | |||||
13242 | // Or declarations that aren't global. | ||||
13243 | if (!FD->isGlobal()) | ||||
13244 | return false; | ||||
13245 | |||||
13246 | // Don't warn about C++ member functions. | ||||
13247 | if (isa<CXXMethodDecl>(FD)) | ||||
13248 | return false; | ||||
13249 | |||||
13250 | // Don't warn about 'main'. | ||||
13251 | if (FD->isMain()) | ||||
13252 | return false; | ||||
13253 | |||||
13254 | // Don't warn about inline functions. | ||||
13255 | if (FD->isInlined()) | ||||
13256 | return false; | ||||
13257 | |||||
13258 | // Don't warn about function templates. | ||||
13259 | if (FD->getDescribedFunctionTemplate()) | ||||
13260 | return false; | ||||
13261 | |||||
13262 | // Don't warn about function template specializations. | ||||
13263 | if (FD->isFunctionTemplateSpecialization()) | ||||
13264 | return false; | ||||
13265 | |||||
13266 | // Don't warn for OpenCL kernels. | ||||
13267 | if (FD->hasAttr<OpenCLKernelAttr>()) | ||||
13268 | return false; | ||||
13269 | |||||
13270 | // Don't warn on explicitly deleted functions. | ||||
13271 | if (FD->isDeleted()) | ||||
13272 | return false; | ||||
13273 | |||||
13274 | for (const FunctionDecl *Prev = FD->getPreviousDecl(); | ||||
13275 | Prev; Prev = Prev->getPreviousDecl()) { | ||||
13276 | // Ignore any declarations that occur in function or method | ||||
13277 | // scope, because they aren't visible from the header. | ||||
13278 | if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) | ||||
13279 | continue; | ||||
13280 | |||||
13281 | PossiblePrototype = Prev; | ||||
13282 | return Prev->getType()->isFunctionNoProtoType(); | ||||
13283 | } | ||||
13284 | |||||
13285 | return true; | ||||
13286 | } | ||||
13287 | |||||
13288 | void | ||||
13289 | Sema::CheckForFunctionRedefinition(FunctionDecl *FD, | ||||
13290 | const FunctionDecl *EffectiveDefinition, | ||||
13291 | SkipBodyInfo *SkipBody) { | ||||
13292 | const FunctionDecl *Definition = EffectiveDefinition; | ||||
13293 | if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { | ||||
13294 | // If this is a friend function defined in a class template, it does not | ||||
13295 | // have a body until it is used, nevertheless it is a definition, see | ||||
13296 | // [temp.inst]p2: | ||||
13297 | // | ||||
13298 | // ... for the purpose of determining whether an instantiated redeclaration | ||||
13299 | // is valid according to [basic.def.odr] and [class.mem], a declaration that | ||||
13300 | // corresponds to a definition in the template is considered to be a | ||||
13301 | // definition. | ||||
13302 | // | ||||
13303 | // The following code must produce redefinition error: | ||||
13304 | // | ||||
13305 | // template<typename T> struct C20 { friend void func_20() {} }; | ||||
13306 | // C20<int> c20i; | ||||
13307 | // void func_20() {} | ||||
13308 | // | ||||
13309 | for (auto I : FD->redecls()) { | ||||
13310 | if (I != FD && !I->isInvalidDecl() && | ||||
13311 | I->getFriendObjectKind() != Decl::FOK_None) { | ||||
13312 | if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { | ||||
13313 | if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { | ||||
13314 | // A merged copy of the same function, instantiated as a member of | ||||
13315 | // the same class, is OK. | ||||
13316 | if (declaresSameEntity(OrigFD, Original) && | ||||
13317 | declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), | ||||
13318 | cast<Decl>(FD->getLexicalDeclContext()))) | ||||
13319 | continue; | ||||
13320 | } | ||||
13321 | |||||
13322 | if (Original->isThisDeclarationADefinition()) { | ||||
13323 | Definition = I; | ||||
13324 | break; | ||||
13325 | } | ||||
13326 | } | ||||
13327 | } | ||||
13328 | } | ||||
13329 | } | ||||
13330 | |||||
13331 | if (!Definition) | ||||
13332 | // Similar to friend functions a friend function template may be a | ||||
13333 | // definition and do not have a body if it is instantiated in a class | ||||
13334 | // template. | ||||
13335 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { | ||||
13336 | for (auto I : FTD->redecls()) { | ||||
13337 | auto D = cast<FunctionTemplateDecl>(I); | ||||
13338 | if (D != FTD) { | ||||
13339 | assert(!D->isThisDeclarationADefinition() &&((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13340, __PRETTY_FUNCTION__)) | ||||
13340 | "More than one definition in redeclaration chain")((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13340, __PRETTY_FUNCTION__)); | ||||
13341 | if (D->getFriendObjectKind() != Decl::FOK_None) | ||||
13342 | if (FunctionTemplateDecl *FT = | ||||
13343 | D->getInstantiatedFromMemberTemplate()) { | ||||
13344 | if (FT->isThisDeclarationADefinition()) { | ||||
13345 | Definition = D->getTemplatedDecl(); | ||||
13346 | break; | ||||
13347 | } | ||||
13348 | } | ||||
13349 | } | ||||
13350 | } | ||||
13351 | } | ||||
13352 | |||||
13353 | if (!Definition) | ||||
13354 | return; | ||||
13355 | |||||
13356 | if (canRedefineFunction(Definition, getLangOpts())) | ||||
13357 | return; | ||||
13358 | |||||
13359 | // Don't emit an error when this is redefinition of a typo-corrected | ||||
13360 | // definition. | ||||
13361 | if (TypoCorrectedFunctionDefinitions.count(Definition)) | ||||
13362 | return; | ||||
13363 | |||||
13364 | // If we don't have a visible definition of the function, and it's inline or | ||||
13365 | // a template, skip the new definition. | ||||
13366 | if (SkipBody && !hasVisibleDefinition(Definition) && | ||||
13367 | (Definition->getFormalLinkage() == InternalLinkage || | ||||
13368 | Definition->isInlined() || | ||||
13369 | Definition->getDescribedFunctionTemplate() || | ||||
13370 | Definition->getNumTemplateParameterLists())) { | ||||
13371 | SkipBody->ShouldSkip = true; | ||||
13372 | SkipBody->Previous = const_cast<FunctionDecl*>(Definition); | ||||
13373 | if (auto *TD = Definition->getDescribedFunctionTemplate()) | ||||
13374 | makeMergedDefinitionVisible(TD); | ||||
13375 | makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); | ||||
13376 | return; | ||||
13377 | } | ||||
13378 | |||||
13379 | if (getLangOpts().GNUMode && Definition->isInlineSpecified() && | ||||
13380 | Definition->getStorageClass() == SC_Extern) | ||||
13381 | Diag(FD->getLocation(), diag::err_redefinition_extern_inline) | ||||
13382 | << FD->getDeclName() << getLangOpts().CPlusPlus; | ||||
13383 | else | ||||
13384 | Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); | ||||
13385 | |||||
13386 | Diag(Definition->getLocation(), diag::note_previous_definition); | ||||
13387 | FD->setInvalidDecl(); | ||||
13388 | } | ||||
13389 | |||||
13390 | static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, | ||||
13391 | Sema &S) { | ||||
13392 | CXXRecordDecl *const LambdaClass = CallOperator->getParent(); | ||||
13393 | |||||
13394 | LambdaScopeInfo *LSI = S.PushLambdaScope(); | ||||
13395 | LSI->CallOperator = CallOperator; | ||||
13396 | LSI->Lambda = LambdaClass; | ||||
13397 | LSI->ReturnType = CallOperator->getReturnType(); | ||||
13398 | const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); | ||||
13399 | |||||
13400 | if (LCD == LCD_None) | ||||
13401 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; | ||||
13402 | else if (LCD == LCD_ByCopy) | ||||
13403 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; | ||||
13404 | else if (LCD == LCD_ByRef) | ||||
13405 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; | ||||
13406 | DeclarationNameInfo DNI = CallOperator->getNameInfo(); | ||||
13407 | |||||
13408 | LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); | ||||
13409 | LSI->Mutable = !CallOperator->isConst(); | ||||
13410 | |||||
13411 | // Add the captures to the LSI so they can be noted as already | ||||
13412 | // captured within tryCaptureVar. | ||||
13413 | auto I = LambdaClass->field_begin(); | ||||
13414 | for (const auto &C : LambdaClass->captures()) { | ||||
13415 | if (C.capturesVariable()) { | ||||
13416 | VarDecl *VD = C.getCapturedVar(); | ||||
13417 | if (VD->isInitCapture()) | ||||
13418 | S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); | ||||
13419 | QualType CaptureType = VD->getType(); | ||||
13420 | const bool ByRef = C.getCaptureKind() == LCK_ByRef; | ||||
13421 | LSI->addCapture(VD, /*IsBlock*/false, ByRef, | ||||
13422 | /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), | ||||
13423 | /*EllipsisLoc*/C.isPackExpansion() | ||||
13424 | ? C.getEllipsisLoc() : SourceLocation(), | ||||
13425 | CaptureType, /*Invalid*/false); | ||||
13426 | |||||
13427 | } else if (C.capturesThis()) { | ||||
13428 | LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), | ||||
13429 | C.getCaptureKind() == LCK_StarThis); | ||||
13430 | } else { | ||||
13431 | LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), | ||||
13432 | I->getType()); | ||||
13433 | } | ||||
13434 | ++I; | ||||
13435 | } | ||||
13436 | } | ||||
13437 | |||||
13438 | Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, | ||||
13439 | SkipBodyInfo *SkipBody) { | ||||
13440 | if (!D) { | ||||
13441 | // Parsing the function declaration failed in some way. Push on a fake scope | ||||
13442 | // anyway so we can try to parse the function body. | ||||
13443 | PushFunctionScope(); | ||||
13444 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||
13445 | return D; | ||||
13446 | } | ||||
13447 | |||||
13448 | FunctionDecl *FD = nullptr; | ||||
13449 | |||||
13450 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) | ||||
13451 | FD = FunTmpl->getTemplatedDecl(); | ||||
13452 | else | ||||
13453 | FD = cast<FunctionDecl>(D); | ||||
13454 | |||||
13455 | // Do not push if it is a lambda because one is already pushed when building | ||||
13456 | // the lambda in ActOnStartOfLambdaDefinition(). | ||||
13457 | if (!isLambdaCallOperator(FD)) | ||||
13458 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||
13459 | |||||
13460 | // Check for defining attributes before the check for redefinition. | ||||
13461 | if (const auto *Attr = FD->getAttr<AliasAttr>()) { | ||||
13462 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; | ||||
13463 | FD->dropAttr<AliasAttr>(); | ||||
13464 | FD->setInvalidDecl(); | ||||
13465 | } | ||||
13466 | if (const auto *Attr = FD->getAttr<IFuncAttr>()) { | ||||
13467 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; | ||||
13468 | FD->dropAttr<IFuncAttr>(); | ||||
13469 | FD->setInvalidDecl(); | ||||
13470 | } | ||||
13471 | |||||
13472 | // See if this is a redefinition. If 'will have body' is already set, then | ||||
13473 | // these checks were already performed when it was set. | ||||
13474 | if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { | ||||
13475 | CheckForFunctionRedefinition(FD, nullptr, SkipBody); | ||||
13476 | |||||
13477 | // If we're skipping the body, we're done. Don't enter the scope. | ||||
13478 | if (SkipBody && SkipBody->ShouldSkip) | ||||
13479 | return D; | ||||
13480 | } | ||||
13481 | |||||
13482 | // Mark this function as "will have a body eventually". This lets users to | ||||
13483 | // call e.g. isInlineDefinitionExternallyVisible while we're still parsing | ||||
13484 | // this function. | ||||
13485 | FD->setWillHaveBody(); | ||||
13486 | |||||
13487 | // If we are instantiating a generic lambda call operator, push | ||||
13488 | // a LambdaScopeInfo onto the function stack. But use the information | ||||
13489 | // that's already been calculated (ActOnLambdaExpr) to prime the current | ||||
13490 | // LambdaScopeInfo. | ||||
13491 | // When the template operator is being specialized, the LambdaScopeInfo, | ||||
13492 | // has to be properly restored so that tryCaptureVariable doesn't try | ||||
13493 | // and capture any new variables. In addition when calculating potential | ||||
13494 | // captures during transformation of nested lambdas, it is necessary to | ||||
13495 | // have the LSI properly restored. | ||||
13496 | if (isGenericLambdaCallOperatorSpecialization(FD)) { | ||||
13497 | assert(inTemplateInstantiation() &&((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13499, __PRETTY_FUNCTION__)) | ||||
13498 | "There should be an active template instantiation on the stack "((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13499, __PRETTY_FUNCTION__)) | ||||
13499 | "when instantiating a generic lambda!")((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13499, __PRETTY_FUNCTION__)); | ||||
13500 | RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); | ||||
13501 | } else { | ||||
13502 | // Enter a new function scope | ||||
13503 | PushFunctionScope(); | ||||
13504 | } | ||||
13505 | |||||
13506 | // Builtin functions cannot be defined. | ||||
13507 | if (unsigned BuiltinID = FD->getBuiltinID()) { | ||||
13508 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && | ||||
13509 | !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { | ||||
13510 | Diag(FD->getLocation(), diag::err_builtin_definition) << FD; | ||||
13511 | FD->setInvalidDecl(); | ||||
13512 | } | ||||
13513 | } | ||||
13514 | |||||
13515 | // The return type of a function definition must be complete | ||||
13516 | // (C99 6.9.1p3, C++ [dcl.fct]p6). | ||||
13517 | QualType ResultType = FD->getReturnType(); | ||||
13518 | if (!ResultType->isDependentType() && !ResultType->isVoidType() && | ||||
13519 | !FD->isInvalidDecl() && | ||||
13520 | RequireCompleteType(FD->getLocation(), ResultType, | ||||
13521 | diag::err_func_def_incomplete_result)) | ||||
13522 | FD->setInvalidDecl(); | ||||
13523 | |||||
13524 | if (FnBodyScope) | ||||
13525 | PushDeclContext(FnBodyScope, FD); | ||||
13526 | |||||
13527 | // Check the validity of our function parameters | ||||
13528 | CheckParmsForFunctionDef(FD->parameters(), | ||||
13529 | /*CheckParameterNames=*/true); | ||||
13530 | |||||
13531 | // Add non-parameter declarations already in the function to the current | ||||
13532 | // scope. | ||||
13533 | if (FnBodyScope) { | ||||
13534 | for (Decl *NPD : FD->decls()) { | ||||
13535 | auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); | ||||
13536 | if (!NonParmDecl) | ||||
13537 | continue; | ||||
13538 | assert(!isa<ParmVarDecl>(NonParmDecl) &&((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13539, __PRETTY_FUNCTION__)) | ||||
13539 | "parameters should not be in newly created FD yet")((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13539, __PRETTY_FUNCTION__)); | ||||
13540 | |||||
13541 | // If the decl has a name, make it accessible in the current scope. | ||||
13542 | if (NonParmDecl->getDeclName()) | ||||
13543 | PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); | ||||
13544 | |||||
13545 | // Similarly, dive into enums and fish their constants out, making them | ||||
13546 | // accessible in this scope. | ||||
13547 | if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { | ||||
13548 | for (auto *EI : ED->enumerators()) | ||||
13549 | PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); | ||||
13550 | } | ||||
13551 | } | ||||
13552 | } | ||||
13553 | |||||
13554 | // Introduce our parameters into the function scope | ||||
13555 | for (auto Param : FD->parameters()) { | ||||
13556 | Param->setOwningFunction(FD); | ||||
13557 | |||||
13558 | // If this has an identifier, add it to the scope stack. | ||||
13559 | if (Param->getIdentifier() && FnBodyScope) { | ||||
13560 | CheckShadow(FnBodyScope, Param); | ||||
13561 | |||||
13562 | PushOnScopeChains(Param, FnBodyScope); | ||||
13563 | } | ||||
13564 | } | ||||
13565 | |||||
13566 | // Ensure that the function's exception specification is instantiated. | ||||
13567 | if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) | ||||
13568 | ResolveExceptionSpec(D->getLocation(), FPT); | ||||
13569 | |||||
13570 | // dllimport cannot be applied to non-inline function definitions. | ||||
13571 | if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && | ||||
13572 | !FD->isTemplateInstantiation()) { | ||||
13573 | assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void > (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13573, __PRETTY_FUNCTION__)); | ||||
13574 | Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); | ||||
13575 | FD->setInvalidDecl(); | ||||
13576 | return D; | ||||
13577 | } | ||||
13578 | // We want to attach documentation to original Decl (which might be | ||||
13579 | // a function template). | ||||
13580 | ActOnDocumentableDecl(D); | ||||
13581 | if (getCurLexicalContext()->isObjCContainer() && | ||||
13582 | getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && | ||||
13583 | getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) | ||||
13584 | Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); | ||||
13585 | |||||
13586 | return D; | ||||
13587 | } | ||||
13588 | |||||
13589 | /// Given the set of return statements within a function body, | ||||
13590 | /// compute the variables that are subject to the named return value | ||||
13591 | /// optimization. | ||||
13592 | /// | ||||
13593 | /// Each of the variables that is subject to the named return value | ||||
13594 | /// optimization will be marked as NRVO variables in the AST, and any | ||||
13595 | /// return statement that has a marked NRVO variable as its NRVO candidate can | ||||
13596 | /// use the named return value optimization. | ||||
13597 | /// | ||||
13598 | /// This function applies a very simplistic algorithm for NRVO: if every return | ||||
13599 | /// statement in the scope of a variable has the same NRVO candidate, that | ||||
13600 | /// candidate is an NRVO variable. | ||||
13601 | void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { | ||||
13602 | ReturnStmt **Returns = Scope->Returns.data(); | ||||
13603 | |||||
13604 | for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { | ||||
13605 | if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { | ||||
13606 | if (!NRVOCandidate->isNRVOVariable()) | ||||
13607 | Returns[I]->setNRVOCandidate(nullptr); | ||||
13608 | } | ||||
13609 | } | ||||
13610 | } | ||||
13611 | |||||
13612 | bool Sema::canDelayFunctionBody(const Declarator &D) { | ||||
13613 | // We can't delay parsing the body of a constexpr function template (yet). | ||||
13614 | if (D.getDeclSpec().hasConstexprSpecifier()) | ||||
13615 | return false; | ||||
13616 | |||||
13617 | // We can't delay parsing the body of a function template with a deduced | ||||
13618 | // return type (yet). | ||||
13619 | if (D.getDeclSpec().hasAutoTypeSpec()) { | ||||
13620 | // If the placeholder introduces a non-deduced trailing return type, | ||||
13621 | // we can still delay parsing it. | ||||
13622 | if (D.getNumTypeObjects()) { | ||||
13623 | const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); | ||||
13624 | if (Outer.Kind == DeclaratorChunk::Function && | ||||
13625 | Outer.Fun.hasTrailingReturnType()) { | ||||
13626 | QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); | ||||
13627 | return Ty.isNull() || !Ty->isUndeducedType(); | ||||
13628 | } | ||||
13629 | } | ||||
13630 | return false; | ||||
13631 | } | ||||
13632 | |||||
13633 | return true; | ||||
13634 | } | ||||
13635 | |||||
13636 | bool Sema::canSkipFunctionBody(Decl *D) { | ||||
13637 | // We cannot skip the body of a function (or function template) which is | ||||
13638 | // constexpr, since we may need to evaluate its body in order to parse the | ||||
13639 | // rest of the file. | ||||
13640 | // We cannot skip the body of a function with an undeduced return type, | ||||
13641 | // because any callers of that function need to know the type. | ||||
13642 | if (const FunctionDecl *FD = D->getAsFunction()) { | ||||
13643 | if (FD->isConstexpr()) | ||||
13644 | return false; | ||||
13645 | // We can't simply call Type::isUndeducedType here, because inside template | ||||
13646 | // auto can be deduced to a dependent type, which is not considered | ||||
13647 | // "undeduced". | ||||
13648 | if (FD->getReturnType()->getContainedDeducedType()) | ||||
13649 | return false; | ||||
13650 | } | ||||
13651 | return Consumer.shouldSkipFunctionBody(D); | ||||
13652 | } | ||||
13653 | |||||
13654 | Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { | ||||
13655 | if (!Decl) | ||||
13656 | return nullptr; | ||||
13657 | if (FunctionDecl *FD = Decl->getAsFunction()) | ||||
13658 | FD->setHasSkippedBody(); | ||||
13659 | else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) | ||||
13660 | MD->setHasSkippedBody(); | ||||
13661 | return Decl; | ||||
13662 | } | ||||
13663 | |||||
13664 | Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { | ||||
13665 | return ActOnFinishFunctionBody(D, BodyArg, false); | ||||
13666 | } | ||||
13667 | |||||
13668 | /// RAII object that pops an ExpressionEvaluationContext when exiting a function | ||||
13669 | /// body. | ||||
13670 | class ExitFunctionBodyRAII { | ||||
13671 | public: | ||||
13672 | ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} | ||||
13673 | ~ExitFunctionBodyRAII() { | ||||
13674 | if (!IsLambda) | ||||
13675 | S.PopExpressionEvaluationContext(); | ||||
13676 | } | ||||
13677 | |||||
13678 | private: | ||||
13679 | Sema &S; | ||||
13680 | bool IsLambda = false; | ||||
13681 | }; | ||||
13682 | |||||
13683 | static void diagnoseImplicitlyRetainedSelf(Sema &S) { | ||||
13684 | llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; | ||||
13685 | |||||
13686 | auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { | ||||
13687 | if (EscapeInfo.count(BD)) | ||||
13688 | return EscapeInfo[BD]; | ||||
13689 | |||||
13690 | bool R = false; | ||||
13691 | const BlockDecl *CurBD = BD; | ||||
13692 | |||||
13693 | do { | ||||
13694 | R = !CurBD->doesNotEscape(); | ||||
13695 | if (R) | ||||
13696 | break; | ||||
13697 | CurBD = CurBD->getParent()->getInnermostBlockDecl(); | ||||
13698 | } while (CurBD); | ||||
13699 | |||||
13700 | return EscapeInfo[BD] = R; | ||||
13701 | }; | ||||
13702 | |||||
13703 | // If the location where 'self' is implicitly retained is inside a escaping | ||||
13704 | // block, emit a diagnostic. | ||||
13705 | for (const std::pair<SourceLocation, const BlockDecl *> &P : | ||||
13706 | S.ImplicitlyRetainedSelfLocs) | ||||
13707 | if (IsOrNestedInEscapingBlock(P.second)) | ||||
13708 | S.Diag(P.first, diag::warn_implicitly_retains_self) | ||||
13709 | << FixItHint::CreateInsertion(P.first, "self->"); | ||||
13710 | } | ||||
13711 | |||||
13712 | Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, | ||||
13713 | bool IsInstantiation) { | ||||
13714 | FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; | ||||
13715 | |||||
13716 | sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | ||||
13717 | sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; | ||||
13718 | |||||
13719 | if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) | ||||
13720 | CheckCompletedCoroutineBody(FD, Body); | ||||
13721 | |||||
13722 | // Do not call PopExpressionEvaluationContext() if it is a lambda because one | ||||
13723 | // is already popped when finishing the lambda in BuildLambdaExpr(). This is | ||||
13724 | // meant to pop the context added in ActOnStartOfFunctionDef(). | ||||
13725 | ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); | ||||
13726 | |||||
13727 | if (FD) { | ||||
13728 | FD->setBody(Body); | ||||
13729 | FD->setWillHaveBody(false); | ||||
13730 | |||||
13731 | if (getLangOpts().CPlusPlus14) { | ||||
13732 | if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && | ||||
13733 | FD->getReturnType()->isUndeducedType()) { | ||||
13734 | // If the function has a deduced result type but contains no 'return' | ||||
13735 | // statements, the result type as written must be exactly 'auto', and | ||||
13736 | // the deduced result type is 'void'. | ||||
13737 | if (!FD->getReturnType()->getAs<AutoType>()) { | ||||
13738 | Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) | ||||
13739 | << FD->getReturnType(); | ||||
13740 | FD->setInvalidDecl(); | ||||
13741 | } else { | ||||
13742 | // Substitute 'void' for the 'auto' in the type. | ||||
13743 | TypeLoc ResultType = getReturnTypeLoc(FD); | ||||
13744 | Context.adjustDeducedFunctionResultType( | ||||
13745 | FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); | ||||
13746 | } | ||||
13747 | } | ||||
13748 | } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { | ||||
13749 | // In C++11, we don't use 'auto' deduction rules for lambda call | ||||
13750 | // operators because we don't support return type deduction. | ||||
13751 | auto *LSI = getCurLambda(); | ||||
13752 | if (LSI->HasImplicitReturnType) { | ||||
13753 | deduceClosureReturnType(*LSI); | ||||
13754 | |||||
13755 | // C++11 [expr.prim.lambda]p4: | ||||
13756 | // [...] if there are no return statements in the compound-statement | ||||
13757 | // [the deduced type is] the type void | ||||
13758 | QualType RetType = | ||||
13759 | LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; | ||||
13760 | |||||
13761 | // Update the return type to the deduced type. | ||||
13762 | const FunctionProtoType *Proto = | ||||
13763 | FD->getType()->getAs<FunctionProtoType>(); | ||||
13764 | FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), | ||||
13765 | Proto->getExtProtoInfo())); | ||||
13766 | } | ||||
13767 | } | ||||
13768 | |||||
13769 | // If the function implicitly returns zero (like 'main') or is naked, | ||||
13770 | // don't complain about missing return statements. | ||||
13771 | if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) | ||||
13772 | WP.disableCheckFallThrough(); | ||||
13773 | |||||
13774 | // MSVC permits the use of pure specifier (=0) on function definition, | ||||
13775 | // defined at class scope, warn about this non-standard construct. | ||||
13776 | if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) | ||||
13777 | Diag(FD->getLocation(), diag::ext_pure_function_definition); | ||||
13778 | |||||
13779 | if (!FD->isInvalidDecl()) { | ||||
13780 | // Don't diagnose unused parameters of defaulted or deleted functions. | ||||
13781 | if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) | ||||
13782 | DiagnoseUnusedParameters(FD->parameters()); | ||||
13783 | DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), | ||||
13784 | FD->getReturnType(), FD); | ||||
13785 | |||||
13786 | // If this is a structor, we need a vtable. | ||||
13787 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) | ||||
13788 | MarkVTableUsed(FD->getLocation(), Constructor->getParent()); | ||||
13789 | else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) | ||||
13790 | MarkVTableUsed(FD->getLocation(), Destructor->getParent()); | ||||
13791 | |||||
13792 | // Try to apply the named return value optimization. We have to check | ||||
13793 | // if we can do this here because lambdas keep return statements around | ||||
13794 | // to deduce an implicit return type. | ||||
13795 | if (FD->getReturnType()->isRecordType() && | ||||
13796 | (!getLangOpts().CPlusPlus || !FD->isDependentContext())) | ||||
13797 | computeNRVO(Body, getCurFunction()); | ||||
13798 | } | ||||
13799 | |||||
13800 | // GNU warning -Wmissing-prototypes: | ||||
13801 | // Warn if a global function is defined without a previous | ||||
13802 | // prototype declaration. This warning is issued even if the | ||||
13803 | // definition itself provides a prototype. The aim is to detect | ||||
13804 | // global functions that fail to be declared in header files. | ||||
13805 | const FunctionDecl *PossiblePrototype = nullptr; | ||||
13806 | if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { | ||||
13807 | Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; | ||||
13808 | |||||
13809 | if (PossiblePrototype) { | ||||
13810 | // We found a declaration that is not a prototype, | ||||
13811 | // but that could be a zero-parameter prototype | ||||
13812 | if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { | ||||
13813 | TypeLoc TL = TI->getTypeLoc(); | ||||
13814 | if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) | ||||
13815 | Diag(PossiblePrototype->getLocation(), | ||||
13816 | diag::note_declaration_not_a_prototype) | ||||
13817 | << (FD->getNumParams() != 0) | ||||
13818 | << (FD->getNumParams() == 0 | ||||
13819 | ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") | ||||
13820 | : FixItHint{}); | ||||
13821 | } | ||||
13822 | } else { | ||||
13823 | Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) | ||||
13824 | << /* function */ 1 | ||||
13825 | << (FD->getStorageClass() == SC_None | ||||
13826 | ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), | ||||
13827 | "static ") | ||||
13828 | : FixItHint{}); | ||||
13829 | } | ||||
13830 | |||||
13831 | // GNU warning -Wstrict-prototypes | ||||
13832 | // Warn if K&R function is defined without a previous declaration. | ||||
13833 | // This warning is issued only if the definition itself does not provide | ||||
13834 | // a prototype. Only K&R definitions do not provide a prototype. | ||||
13835 | // An empty list in a function declarator that is part of a definition | ||||
13836 | // of that function specifies that the function has no parameters | ||||
13837 | // (C99 6.7.5.3p14) | ||||
13838 | if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && | ||||
13839 | !LangOpts.CPlusPlus) { | ||||
13840 | TypeSourceInfo *TI = FD->getTypeSourceInfo(); | ||||
13841 | TypeLoc TL = TI->getTypeLoc(); | ||||
13842 | FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); | ||||
13843 | Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; | ||||
13844 | } | ||||
13845 | } | ||||
13846 | |||||
13847 | // Warn on CPUDispatch with an actual body. | ||||
13848 | if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) | ||||
13849 | if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) | ||||
13850 | if (!CmpndBody->body_empty()) | ||||
13851 | Diag(CmpndBody->body_front()->getBeginLoc(), | ||||
13852 | diag::warn_dispatch_body_ignored); | ||||
13853 | |||||
13854 | if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||
13855 | const CXXMethodDecl *KeyFunction; | ||||
13856 | if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && | ||||
13857 | MD->isVirtual() && | ||||
13858 | (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && | ||||
13859 | MD == KeyFunction->getCanonicalDecl()) { | ||||
13860 | // Update the key-function state if necessary for this ABI. | ||||
13861 | if (FD->isInlined() && | ||||
13862 | !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { | ||||
13863 | Context.setNonKeyFunction(MD); | ||||
13864 | |||||
13865 | // If the newly-chosen key function is already defined, then we | ||||
13866 | // need to mark the vtable as used retroactively. | ||||
13867 | KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); | ||||
13868 | const FunctionDecl *Definition; | ||||
13869 | if (KeyFunction && KeyFunction->isDefined(Definition)) | ||||
13870 | MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); | ||||
13871 | } else { | ||||
13872 | // We just defined they key function; mark the vtable as used. | ||||
13873 | MarkVTableUsed(FD->getLocation(), MD->getParent(), true); | ||||
13874 | } | ||||
13875 | } | ||||
13876 | } | ||||
13877 | |||||
13878 | assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && "Function parsing confused") ? static_cast <void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13879, __PRETTY_FUNCTION__)) | ||||
13879 | "Function parsing confused")(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && "Function parsing confused") ? static_cast <void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13879, __PRETTY_FUNCTION__)); | ||||
13880 | } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { | ||||
13881 | assert(MD == getCurMethodDecl() && "Method parsing confused")((MD == getCurMethodDecl() && "Method parsing confused" ) ? static_cast<void> (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13881, __PRETTY_FUNCTION__)); | ||||
13882 | MD->setBody(Body); | ||||
13883 | if (!MD->isInvalidDecl()) { | ||||
13884 | DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), | ||||
13885 | MD->getReturnType(), MD); | ||||
13886 | |||||
13887 | if (Body) | ||||
13888 | computeNRVO(Body, getCurFunction()); | ||||
13889 | } | ||||
13890 | if (getCurFunction()->ObjCShouldCallSuper) { | ||||
13891 | Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) | ||||
13892 | << MD->getSelector().getAsString(); | ||||
13893 | getCurFunction()->ObjCShouldCallSuper = false; | ||||
13894 | } | ||||
13895 | if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { | ||||
13896 | const ObjCMethodDecl *InitMethod = nullptr; | ||||
13897 | bool isDesignated = | ||||
13898 | MD->isDesignatedInitializerForTheInterface(&InitMethod); | ||||
13899 | assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void> (0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13899, __PRETTY_FUNCTION__)); | ||||
13900 | (void)isDesignated; | ||||
13901 | |||||
13902 | auto superIsNSObject = [&](const ObjCMethodDecl *MD) { | ||||
13903 | auto IFace = MD->getClassInterface(); | ||||
13904 | if (!IFace) | ||||
13905 | return false; | ||||
13906 | auto SuperD = IFace->getSuperClass(); | ||||
13907 | if (!SuperD) | ||||
13908 | return false; | ||||
13909 | return SuperD->getIdentifier() == | ||||
13910 | NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); | ||||
13911 | }; | ||||
13912 | // Don't issue this warning for unavailable inits or direct subclasses | ||||
13913 | // of NSObject. | ||||
13914 | if (!MD->isUnavailable() && !superIsNSObject(MD)) { | ||||
13915 | Diag(MD->getLocation(), | ||||
13916 | diag::warn_objc_designated_init_missing_super_call); | ||||
13917 | Diag(InitMethod->getLocation(), | ||||
13918 | diag::note_objc_designated_init_marked_here); | ||||
13919 | } | ||||
13920 | getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; | ||||
13921 | } | ||||
13922 | if (getCurFunction()->ObjCWarnForNoInitDelegation) { | ||||
13923 | // Don't issue this warning for unavaialable inits. | ||||
13924 | if (!MD->isUnavailable()) | ||||
13925 | Diag(MD->getLocation(), | ||||
13926 | diag::warn_objc_secondary_init_missing_init_call); | ||||
13927 | getCurFunction()->ObjCWarnForNoInitDelegation = false; | ||||
13928 | } | ||||
13929 | |||||
13930 | diagnoseImplicitlyRetainedSelf(*this); | ||||
13931 | } else { | ||||
13932 | // Parsing the function declaration failed in some way. Pop the fake scope | ||||
13933 | // we pushed on. | ||||
13934 | PopFunctionScopeInfo(ActivePolicy, dcl); | ||||
13935 | return nullptr; | ||||
13936 | } | ||||
13937 | |||||
13938 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | ||||
13939 | DiagnoseUnguardedAvailabilityViolations(dcl); | ||||
13940 | |||||
13941 | assert(!getCurFunction()->ObjCShouldCallSuper &&((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13943, __PRETTY_FUNCTION__)) | ||||
13942 | "This should only be set for ObjC methods, which should have been "((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13943, __PRETTY_FUNCTION__)) | ||||
13943 | "handled in the block above.")((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 13943, __PRETTY_FUNCTION__)); | ||||
13944 | |||||
13945 | // Verify and clean out per-function state. | ||||
13946 | if (Body && (!FD || !FD->isDefaulted())) { | ||||
13947 | // C++ constructors that have function-try-blocks can't have return | ||||
13948 | // statements in the handlers of that block. (C++ [except.handle]p14) | ||||
13949 | // Verify this. | ||||
13950 | if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) | ||||
13951 | DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); | ||||
13952 | |||||
13953 | // Verify that gotos and switch cases don't jump into scopes illegally. | ||||
13954 | if (getCurFunction()->NeedsScopeChecking() && | ||||
13955 | !PP.isCodeCompletionEnabled()) | ||||
13956 | DiagnoseInvalidJumps(Body); | ||||
13957 | |||||
13958 | if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { | ||||
13959 | if (!Destructor->getParent()->isDependentType()) | ||||
13960 | CheckDestructor(Destructor); | ||||
13961 | |||||
13962 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | ||||
13963 | Destructor->getParent()); | ||||
13964 | } | ||||
13965 | |||||
13966 | // If any errors have occurred, clear out any temporaries that may have | ||||
13967 | // been leftover. This ensures that these temporaries won't be picked up for | ||||
13968 | // deletion in some later function. | ||||
13969 | if (getDiagnostics().hasErrorOccurred() || | ||||
13970 | getDiagnostics().getSuppressAllDiagnostics()) { | ||||
13971 | DiscardCleanupsInEvaluationContext(); | ||||
13972 | } | ||||
13973 | if (!getDiagnostics().hasUncompilableErrorOccurred() && | ||||
13974 | !isa<FunctionTemplateDecl>(dcl)) { | ||||
13975 | // Since the body is valid, issue any analysis-based warnings that are | ||||
13976 | // enabled. | ||||
13977 | ActivePolicy = &WP; | ||||
13978 | } | ||||
13979 | |||||
13980 | if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && | ||||
13981 | !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) | ||||
13982 | FD->setInvalidDecl(); | ||||
13983 | |||||
13984 | if (FD && FD->hasAttr<NakedAttr>()) { | ||||
13985 | for (const Stmt *S : Body->children()) { | ||||
13986 | // Allow local register variables without initializer as they don't | ||||
13987 | // require prologue. | ||||
13988 | bool RegisterVariables = false; | ||||
13989 | if (auto *DS = dyn_cast<DeclStmt>(S)) { | ||||
13990 | for (const auto *Decl : DS->decls()) { | ||||
13991 | if (const auto *Var = dyn_cast<VarDecl>(Decl)) { | ||||
13992 | RegisterVariables = | ||||
13993 | Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); | ||||
13994 | if (!RegisterVariables) | ||||
13995 | break; | ||||
13996 | } | ||||
13997 | } | ||||
13998 | } | ||||
13999 | if (RegisterVariables) | ||||
14000 | continue; | ||||
14001 | if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { | ||||
14002 | Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); | ||||
14003 | Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); | ||||
14004 | FD->setInvalidDecl(); | ||||
14005 | break; | ||||
14006 | } | ||||
14007 | } | ||||
14008 | } | ||||
14009 | |||||
14010 | assert(ExprCleanupObjects.size() ==((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14012, __PRETTY_FUNCTION__)) | ||||
14011 | ExprEvalContexts.back().NumCleanupObjects &&((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14012, __PRETTY_FUNCTION__)) | ||||
14012 | "Leftover temporaries in function")((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14012, __PRETTY_FUNCTION__)); | ||||
14013 | assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")((!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14013, __PRETTY_FUNCTION__)); | ||||
14014 | assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14015, __PRETTY_FUNCTION__)) | ||||
14015 | "Leftover expressions for odr-use checking")((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14015, __PRETTY_FUNCTION__)); | ||||
14016 | } | ||||
14017 | |||||
14018 | if (!IsInstantiation) | ||||
14019 | PopDeclContext(); | ||||
14020 | |||||
14021 | PopFunctionScopeInfo(ActivePolicy, dcl); | ||||
14022 | // If any errors have occurred, clear out any temporaries that may have | ||||
14023 | // been leftover. This ensures that these temporaries won't be picked up for | ||||
14024 | // deletion in some later function. | ||||
14025 | if (getDiagnostics().hasErrorOccurred()) { | ||||
14026 | DiscardCleanupsInEvaluationContext(); | ||||
14027 | } | ||||
14028 | |||||
14029 | return dcl; | ||||
14030 | } | ||||
14031 | |||||
14032 | /// When we finish delayed parsing of an attribute, we must attach it to the | ||||
14033 | /// relevant Decl. | ||||
14034 | void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, | ||||
14035 | ParsedAttributes &Attrs) { | ||||
14036 | // Always attach attributes to the underlying decl. | ||||
14037 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | ||||
14038 | D = TD->getTemplatedDecl(); | ||||
14039 | ProcessDeclAttributeList(S, D, Attrs); | ||||
14040 | |||||
14041 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) | ||||
14042 | if (Method->isStatic()) | ||||
14043 | checkThisInStaticMemberFunctionAttributes(Method); | ||||
14044 | } | ||||
14045 | |||||
14046 | /// ImplicitlyDefineFunction - An undeclared identifier was used in a function | ||||
14047 | /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). | ||||
14048 | NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, | ||||
14049 | IdentifierInfo &II, Scope *S) { | ||||
14050 | // Find the scope in which the identifier is injected and the corresponding | ||||
14051 | // DeclContext. | ||||
14052 | // FIXME: C89 does not say what happens if there is no enclosing block scope. | ||||
14053 | // In that case, we inject the declaration into the translation unit scope | ||||
14054 | // instead. | ||||
14055 | Scope *BlockScope = S; | ||||
14056 | while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) | ||||
14057 | BlockScope = BlockScope->getParent(); | ||||
14058 | |||||
14059 | Scope *ContextScope = BlockScope; | ||||
14060 | while (!ContextScope->getEntity()) | ||||
14061 | ContextScope = ContextScope->getParent(); | ||||
14062 | ContextRAII SavedContext(*this, ContextScope->getEntity()); | ||||
14063 | |||||
14064 | // Before we produce a declaration for an implicitly defined | ||||
14065 | // function, see whether there was a locally-scoped declaration of | ||||
14066 | // this name as a function or variable. If so, use that | ||||
14067 | // (non-visible) declaration, and complain about it. | ||||
14068 | NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); | ||||
14069 | if (ExternCPrev) { | ||||
14070 | // We still need to inject the function into the enclosing block scope so | ||||
14071 | // that later (non-call) uses can see it. | ||||
14072 | PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); | ||||
14073 | |||||
14074 | // C89 footnote 38: | ||||
14075 | // If in fact it is not defined as having type "function returning int", | ||||
14076 | // the behavior is undefined. | ||||
14077 | if (!isa<FunctionDecl>(ExternCPrev) || | ||||
14078 | !Context.typesAreCompatible( | ||||
14079 | cast<FunctionDecl>(ExternCPrev)->getType(), | ||||
14080 | Context.getFunctionNoProtoType(Context.IntTy))) { | ||||
14081 | Diag(Loc, diag::ext_use_out_of_scope_declaration) | ||||
14082 | << ExternCPrev << !getLangOpts().C99; | ||||
14083 | Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); | ||||
14084 | return ExternCPrev; | ||||
14085 | } | ||||
14086 | } | ||||
14087 | |||||
14088 | // Extension in C99. Legal in C90, but warn about it. | ||||
14089 | unsigned diag_id; | ||||
14090 | if (II.getName().startswith("__builtin_")) | ||||
14091 | diag_id = diag::warn_builtin_unknown; | ||||
14092 | // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. | ||||
14093 | else if (getLangOpts().OpenCL) | ||||
14094 | diag_id = diag::err_opencl_implicit_function_decl; | ||||
14095 | else if (getLangOpts().C99) | ||||
14096 | diag_id = diag::ext_implicit_function_decl; | ||||
14097 | else | ||||
14098 | diag_id = diag::warn_implicit_function_decl; | ||||
14099 | Diag(Loc, diag_id) << &II; | ||||
14100 | |||||
14101 | // If we found a prior declaration of this function, don't bother building | ||||
14102 | // another one. We've already pushed that one into scope, so there's nothing | ||||
14103 | // more to do. | ||||
14104 | if (ExternCPrev) | ||||
14105 | return ExternCPrev; | ||||
14106 | |||||
14107 | // Because typo correction is expensive, only do it if the implicit | ||||
14108 | // function declaration is going to be treated as an error. | ||||
14109 | if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { | ||||
14110 | TypoCorrection Corrected; | ||||
14111 | DeclFilterCCC<FunctionDecl> CCC{}; | ||||
14112 | if (S && (Corrected = | ||||
14113 | CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, | ||||
14114 | S, nullptr, CCC, CTK_NonError))) | ||||
14115 | diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), | ||||
14116 | /*ErrorRecovery*/false); | ||||
14117 | } | ||||
14118 | |||||
14119 | // Set a Declarator for the implicit definition: int foo(); | ||||
14120 | const char *Dummy; | ||||
14121 | AttributeFactory attrFactory; | ||||
14122 | DeclSpec DS(attrFactory); | ||||
14123 | unsigned DiagID; | ||||
14124 | bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, | ||||
14125 | Context.getPrintingPolicy()); | ||||
14126 | (void)Error; // Silence warning. | ||||
14127 | assert(!Error && "Error setting up implicit decl!")((!Error && "Error setting up implicit decl!") ? static_cast <void> (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14127, __PRETTY_FUNCTION__)); | ||||
14128 | SourceLocation NoLoc; | ||||
14129 | Declarator D(DS, DeclaratorContext::BlockContext); | ||||
14130 | D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, | ||||
14131 | /*IsAmbiguous=*/false, | ||||
14132 | /*LParenLoc=*/NoLoc, | ||||
14133 | /*Params=*/nullptr, | ||||
14134 | /*NumParams=*/0, | ||||
14135 | /*EllipsisLoc=*/NoLoc, | ||||
14136 | /*RParenLoc=*/NoLoc, | ||||
14137 | /*RefQualifierIsLvalueRef=*/true, | ||||
14138 | /*RefQualifierLoc=*/NoLoc, | ||||
14139 | /*MutableLoc=*/NoLoc, EST_None, | ||||
14140 | /*ESpecRange=*/SourceRange(), | ||||
14141 | /*Exceptions=*/nullptr, | ||||
14142 | /*ExceptionRanges=*/nullptr, | ||||
14143 | /*NumExceptions=*/0, | ||||
14144 | /*NoexceptExpr=*/nullptr, | ||||
14145 | /*ExceptionSpecTokens=*/nullptr, | ||||
14146 | /*DeclsInPrototype=*/None, Loc, | ||||
14147 | Loc, D), | ||||
14148 | std::move(DS.getAttributes()), SourceLocation()); | ||||
14149 | D.SetIdentifier(&II, Loc); | ||||
14150 | |||||
14151 | // Insert this function into the enclosing block scope. | ||||
14152 | FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); | ||||
14153 | FD->setImplicit(); | ||||
14154 | |||||
14155 | AddKnownFunctionAttributes(FD); | ||||
14156 | |||||
14157 | return FD; | ||||
14158 | } | ||||
14159 | |||||
14160 | /// Adds any function attributes that we know a priori based on | ||||
14161 | /// the declaration of this function. | ||||
14162 | /// | ||||
14163 | /// These attributes can apply both to implicitly-declared builtins | ||||
14164 | /// (like __builtin___printf_chk) or to library-declared functions | ||||
14165 | /// like NSLog or printf. | ||||
14166 | /// | ||||
14167 | /// We need to check for duplicate attributes both here and where user-written | ||||
14168 | /// attributes are applied to declarations. | ||||
14169 | void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { | ||||
14170 | if (FD->isInvalidDecl()) | ||||
14171 | return; | ||||
14172 | |||||
14173 | // If this is a built-in function, map its builtin attributes to | ||||
14174 | // actual attributes. | ||||
14175 | if (unsigned BuiltinID = FD->getBuiltinID()) { | ||||
14176 | // Handle printf-formatting attributes. | ||||
14177 | unsigned FormatIdx; | ||||
14178 | bool HasVAListArg; | ||||
14179 | if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { | ||||
14180 | if (!FD->hasAttr<FormatAttr>()) { | ||||
14181 | const char *fmt = "printf"; | ||||
14182 | unsigned int NumParams = FD->getNumParams(); | ||||
14183 | if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) | ||||
14184 | FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) | ||||
14185 | fmt = "NSString"; | ||||
14186 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||
14187 | &Context.Idents.get(fmt), | ||||
14188 | FormatIdx+1, | ||||
14189 | HasVAListArg ? 0 : FormatIdx+2, | ||||
14190 | FD->getLocation())); | ||||
14191 | } | ||||
14192 | } | ||||
14193 | if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, | ||||
14194 | HasVAListArg)) { | ||||
14195 | if (!FD->hasAttr<FormatAttr>()) | ||||
14196 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||
14197 | &Context.Idents.get("scanf"), | ||||
14198 | FormatIdx+1, | ||||
14199 | HasVAListArg ? 0 : FormatIdx+2, | ||||
14200 | FD->getLocation())); | ||||
14201 | } | ||||
14202 | |||||
14203 | // Handle automatically recognized callbacks. | ||||
14204 | SmallVector<int, 4> Encoding; | ||||
14205 | if (!FD->hasAttr<CallbackAttr>() && | ||||
14206 | Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) | ||||
14207 | FD->addAttr(CallbackAttr::CreateImplicit( | ||||
14208 | Context, Encoding.data(), Encoding.size(), FD->getLocation())); | ||||
14209 | |||||
14210 | // Mark const if we don't care about errno and that is the only thing | ||||
14211 | // preventing the function from being const. This allows IRgen to use LLVM | ||||
14212 | // intrinsics for such functions. | ||||
14213 | if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && | ||||
14214 | Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) | ||||
14215 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||
14216 | |||||
14217 | // We make "fma" on some platforms const because we know it does not set | ||||
14218 | // errno in those environments even though it could set errno based on the | ||||
14219 | // C standard. | ||||
14220 | const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); | ||||
14221 | if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && | ||||
14222 | !FD->hasAttr<ConstAttr>()) { | ||||
14223 | switch (BuiltinID) { | ||||
14224 | case Builtin::BI__builtin_fma: | ||||
14225 | case Builtin::BI__builtin_fmaf: | ||||
14226 | case Builtin::BI__builtin_fmal: | ||||
14227 | case Builtin::BIfma: | ||||
14228 | case Builtin::BIfmaf: | ||||
14229 | case Builtin::BIfmal: | ||||
14230 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||
14231 | break; | ||||
14232 | default: | ||||
14233 | break; | ||||
14234 | } | ||||
14235 | } | ||||
14236 | |||||
14237 | if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && | ||||
14238 | !FD->hasAttr<ReturnsTwiceAttr>()) | ||||
14239 | FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, | ||||
14240 | FD->getLocation())); | ||||
14241 | if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) | ||||
14242 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | ||||
14243 | if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) | ||||
14244 | FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); | ||||
14245 | if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) | ||||
14246 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||
14247 | if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && | ||||
14248 | !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { | ||||
14249 | // Add the appropriate attribute, depending on the CUDA compilation mode | ||||
14250 | // and which target the builtin belongs to. For example, during host | ||||
14251 | // compilation, aux builtins are __device__, while the rest are __host__. | ||||
14252 | if (getLangOpts().CUDAIsDevice != | ||||
14253 | Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) | ||||
14254 | FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); | ||||
14255 | else | ||||
14256 | FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); | ||||
14257 | } | ||||
14258 | } | ||||
14259 | |||||
14260 | // If C++ exceptions are enabled but we are told extern "C" functions cannot | ||||
14261 | // throw, add an implicit nothrow attribute to any extern "C" function we come | ||||
14262 | // across. | ||||
14263 | if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && | ||||
14264 | FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { | ||||
14265 | const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); | ||||
14266 | if (!FPT || FPT->getExceptionSpecType() == EST_None) | ||||
14267 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | ||||
14268 | } | ||||
14269 | |||||
14270 | IdentifierInfo *Name = FD->getIdentifier(); | ||||
14271 | if (!Name) | ||||
14272 | return; | ||||
14273 | if ((!getLangOpts().CPlusPlus && | ||||
14274 | FD->getDeclContext()->isTranslationUnit()) || | ||||
14275 | (isa<LinkageSpecDecl>(FD->getDeclContext()) && | ||||
14276 | cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == | ||||
14277 | LinkageSpecDecl::lang_c)) { | ||||
14278 | // Okay: this could be a libc/libm/Objective-C function we know | ||||
14279 | // about. | ||||
14280 | } else | ||||
14281 | return; | ||||
14282 | |||||
14283 | if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { | ||||
14284 | // FIXME: asprintf and vasprintf aren't C99 functions. Should they be | ||||
14285 | // target-specific builtins, perhaps? | ||||
14286 | if (!FD->hasAttr<FormatAttr>()) | ||||
14287 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||
14288 | &Context.Idents.get("printf"), 2, | ||||
14289 | Name->isStr("vasprintf") ? 0 : 3, | ||||
14290 | FD->getLocation())); | ||||
14291 | } | ||||
14292 | |||||
14293 | if (Name->isStr("__CFStringMakeConstantString")) { | ||||
14294 | // We already have a __builtin___CFStringMakeConstantString, | ||||
14295 | // but builds that use -fno-constant-cfstrings don't go through that. | ||||
14296 | if (!FD->hasAttr<FormatArgAttr>()) | ||||
14297 | FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), | ||||
14298 | FD->getLocation())); | ||||
14299 | } | ||||
14300 | } | ||||
14301 | |||||
14302 | TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, | ||||
14303 | TypeSourceInfo *TInfo) { | ||||
14304 | assert(D.getIdentifier() && "Wrong callback for declspec without declarator")((D.getIdentifier() && "Wrong callback for declspec without declarator" ) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14304, __PRETTY_FUNCTION__)); | ||||
14305 | assert(!T.isNull() && "GetTypeForDeclarator() returned null type")((!T.isNull() && "GetTypeForDeclarator() returned null type" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14305, __PRETTY_FUNCTION__)); | ||||
14306 | |||||
14307 | if (!TInfo) { | ||||
14308 | assert(D.isInvalidType() && "no declarator info for valid type")((D.isInvalidType() && "no declarator info for valid type" ) ? static_cast<void> (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14308, __PRETTY_FUNCTION__)); | ||||
14309 | TInfo = Context.getTrivialTypeSourceInfo(T); | ||||
14310 | } | ||||
14311 | |||||
14312 | // Scope manipulation handled by caller. | ||||
14313 | TypedefDecl *NewTD = | ||||
14314 | TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), | ||||
14315 | D.getIdentifierLoc(), D.getIdentifier(), TInfo); | ||||
14316 | |||||
14317 | // Bail out immediately if we have an invalid declaration. | ||||
14318 | if (D.isInvalidType()) { | ||||
14319 | NewTD->setInvalidDecl(); | ||||
14320 | return NewTD; | ||||
14321 | } | ||||
14322 | |||||
14323 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||
14324 | if (CurContext->isFunctionOrMethod()) | ||||
14325 | Diag(NewTD->getLocation(), diag::err_module_private_local) | ||||
14326 | << 2 << NewTD->getDeclName() | ||||
14327 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||
14328 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||
14329 | else | ||||
14330 | NewTD->setModulePrivate(); | ||||
14331 | } | ||||
14332 | |||||
14333 | // C++ [dcl.typedef]p8: | ||||
14334 | // If the typedef declaration defines an unnamed class (or | ||||
14335 | // enum), the first typedef-name declared by the declaration | ||||
14336 | // to be that class type (or enum type) is used to denote the | ||||
14337 | // class type (or enum type) for linkage purposes only. | ||||
14338 | // We need to check whether the type was declared in the declaration. | ||||
14339 | switch (D.getDeclSpec().getTypeSpecType()) { | ||||
14340 | case TST_enum: | ||||
14341 | case TST_struct: | ||||
14342 | case TST_interface: | ||||
14343 | case TST_union: | ||||
14344 | case TST_class: { | ||||
14345 | TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | ||||
14346 | setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); | ||||
14347 | break; | ||||
14348 | } | ||||
14349 | |||||
14350 | default: | ||||
14351 | break; | ||||
14352 | } | ||||
14353 | |||||
14354 | return NewTD; | ||||
14355 | } | ||||
14356 | |||||
14357 | /// Check that this is a valid underlying type for an enum declaration. | ||||
14358 | bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { | ||||
14359 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); | ||||
14360 | QualType T = TI->getType(); | ||||
14361 | |||||
14362 | if (T->isDependentType()) | ||||
14363 | return false; | ||||
14364 | |||||
14365 | if (const BuiltinType *BT = T->getAs<BuiltinType>()) | ||||
14366 | if (BT->isInteger()) | ||||
14367 | return false; | ||||
14368 | |||||
14369 | Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; | ||||
14370 | return true; | ||||
14371 | } | ||||
14372 | |||||
14373 | /// Check whether this is a valid redeclaration of a previous enumeration. | ||||
14374 | /// \return true if the redeclaration was invalid. | ||||
14375 | bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, | ||||
14376 | QualType EnumUnderlyingTy, bool IsFixed, | ||||
14377 | const EnumDecl *Prev) { | ||||
14378 | if (IsScoped != Prev->isScoped()) { | ||||
14379 | Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) | ||||
14380 | << Prev->isScoped(); | ||||
14381 | Diag(Prev->getLocation(), diag::note_previous_declaration); | ||||
14382 | return true; | ||||
14383 | } | ||||
14384 | |||||
14385 | if (IsFixed && Prev->isFixed()) { | ||||
14386 | if (!EnumUnderlyingTy->isDependentType() && | ||||
14387 | !Prev->getIntegerType()->isDependentType() && | ||||
14388 | !Context.hasSameUnqualifiedType(EnumUnderlyingTy, | ||||
14389 | Prev->getIntegerType())) { | ||||
14390 | // TODO: Highlight the underlying type of the redeclaration. | ||||
14391 | Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) | ||||
14392 | << EnumUnderlyingTy << Prev->getIntegerType(); | ||||
14393 | Diag(Prev->getLocation(), diag::note_previous_declaration) | ||||
14394 | << Prev->getIntegerTypeRange(); | ||||
14395 | return true; | ||||
14396 | } | ||||
14397 | } else if (IsFixed != Prev->isFixed()) { | ||||
14398 | Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) | ||||
14399 | << Prev->isFixed(); | ||||
14400 | Diag(Prev->getLocation(), diag::note_previous_declaration); | ||||
14401 | return true; | ||||
14402 | } | ||||
14403 | |||||
14404 | return false; | ||||
14405 | } | ||||
14406 | |||||
14407 | /// Get diagnostic %select index for tag kind for | ||||
14408 | /// redeclaration diagnostic message. | ||||
14409 | /// WARNING: Indexes apply to particular diagnostics only! | ||||
14410 | /// | ||||
14411 | /// \returns diagnostic %select index. | ||||
14412 | static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { | ||||
14413 | switch (Tag) { | ||||
14414 | case TTK_Struct: return 0; | ||||
14415 | case TTK_Interface: return 1; | ||||
14416 | case TTK_Class: return 2; | ||||
14417 | default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14417); | ||||
14418 | } | ||||
14419 | } | ||||
14420 | |||||
14421 | /// Determine if tag kind is a class-key compatible with | ||||
14422 | /// class for redeclaration (class, struct, or __interface). | ||||
14423 | /// | ||||
14424 | /// \returns true iff the tag kind is compatible. | ||||
14425 | static bool isClassCompatTagKind(TagTypeKind Tag) | ||||
14426 | { | ||||
14427 | return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; | ||||
14428 | } | ||||
14429 | |||||
14430 | Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, | ||||
14431 | TagTypeKind TTK) { | ||||
14432 | if (isa<TypedefDecl>(PrevDecl)) | ||||
14433 | return NTK_Typedef; | ||||
14434 | else if (isa<TypeAliasDecl>(PrevDecl)) | ||||
14435 | return NTK_TypeAlias; | ||||
14436 | else if (isa<ClassTemplateDecl>(PrevDecl)) | ||||
14437 | return NTK_Template; | ||||
14438 | else if (isa<TypeAliasTemplateDecl>(PrevDecl)) | ||||
14439 | return NTK_TypeAliasTemplate; | ||||
14440 | else if (isa<TemplateTemplateParmDecl>(PrevDecl)) | ||||
14441 | return NTK_TemplateTemplateArgument; | ||||
14442 | switch (TTK) { | ||||
14443 | case TTK_Struct: | ||||
14444 | case TTK_Interface: | ||||
14445 | case TTK_Class: | ||||
14446 | return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; | ||||
14447 | case TTK_Union: | ||||
14448 | return NTK_NonUnion; | ||||
14449 | case TTK_Enum: | ||||
14450 | return NTK_NonEnum; | ||||
14451 | } | ||||
14452 | llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14452); | ||||
14453 | } | ||||
14454 | |||||
14455 | /// Determine whether a tag with a given kind is acceptable | ||||
14456 | /// as a redeclaration of the given tag declaration. | ||||
14457 | /// | ||||
14458 | /// \returns true if the new tag kind is acceptable, false otherwise. | ||||
14459 | bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, | ||||
14460 | TagTypeKind NewTag, bool isDefinition, | ||||
14461 | SourceLocation NewTagLoc, | ||||
14462 | const IdentifierInfo *Name) { | ||||
14463 | // C++ [dcl.type.elab]p3: | ||||
14464 | // The class-key or enum keyword present in the | ||||
14465 | // elaborated-type-specifier shall agree in kind with the | ||||
14466 | // declaration to which the name in the elaborated-type-specifier | ||||
14467 | // refers. This rule also applies to the form of | ||||
14468 | // elaborated-type-specifier that declares a class-name or | ||||
14469 | // friend class since it can be construed as referring to the | ||||
14470 | // definition of the class. Thus, in any | ||||
14471 | // elaborated-type-specifier, the enum keyword shall be used to | ||||
14472 | // refer to an enumeration (7.2), the union class-key shall be | ||||
14473 | // used to refer to a union (clause 9), and either the class or | ||||
14474 | // struct class-key shall be used to refer to a class (clause 9) | ||||
14475 | // declared using the class or struct class-key. | ||||
14476 | TagTypeKind OldTag = Previous->getTagKind(); | ||||
14477 | if (OldTag != NewTag && | ||||
14478 | !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) | ||||
14479 | return false; | ||||
14480 | |||||
14481 | // Tags are compatible, but we might still want to warn on mismatched tags. | ||||
14482 | // Non-class tags can't be mismatched at this point. | ||||
14483 | if (!isClassCompatTagKind(NewTag)) | ||||
14484 | return true; | ||||
14485 | |||||
14486 | // Declarations for which -Wmismatched-tags is disabled are entirely ignored | ||||
14487 | // by our warning analysis. We don't want to warn about mismatches with (eg) | ||||
14488 | // declarations in system headers that are designed to be specialized, but if | ||||
14489 | // a user asks us to warn, we should warn if their code contains mismatched | ||||
14490 | // declarations. | ||||
14491 | auto IsIgnoredLoc = [&](SourceLocation Loc) { | ||||
14492 | return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, | ||||
14493 | Loc); | ||||
14494 | }; | ||||
14495 | if (IsIgnoredLoc(NewTagLoc)) | ||||
14496 | return true; | ||||
14497 | |||||
14498 | auto IsIgnored = [&](const TagDecl *Tag) { | ||||
14499 | return IsIgnoredLoc(Tag->getLocation()); | ||||
14500 | }; | ||||
14501 | while (IsIgnored(Previous)) { | ||||
14502 | Previous = Previous->getPreviousDecl(); | ||||
14503 | if (!Previous) | ||||
14504 | return true; | ||||
14505 | OldTag = Previous->getTagKind(); | ||||
14506 | } | ||||
14507 | |||||
14508 | bool isTemplate = false; | ||||
14509 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) | ||||
14510 | isTemplate = Record->getDescribedClassTemplate(); | ||||
14511 | |||||
14512 | if (inTemplateInstantiation()) { | ||||
14513 | if (OldTag != NewTag) { | ||||
14514 | // In a template instantiation, do not offer fix-its for tag mismatches | ||||
14515 | // since they usually mess up the template instead of fixing the problem. | ||||
14516 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | ||||
14517 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||
14518 | << getRedeclDiagFromTagKind(OldTag); | ||||
14519 | // FIXME: Note previous location? | ||||
14520 | } | ||||
14521 | return true; | ||||
14522 | } | ||||
14523 | |||||
14524 | if (isDefinition) { | ||||
14525 | // On definitions, check all previous tags and issue a fix-it for each | ||||
14526 | // one that doesn't match the current tag. | ||||
14527 | if (Previous->getDefinition()) { | ||||
14528 | // Don't suggest fix-its for redefinitions. | ||||
14529 | return true; | ||||
14530 | } | ||||
14531 | |||||
14532 | bool previousMismatch = false; | ||||
14533 | for (const TagDecl *I : Previous->redecls()) { | ||||
14534 | if (I->getTagKind() != NewTag) { | ||||
14535 | // Ignore previous declarations for which the warning was disabled. | ||||
14536 | if (IsIgnored(I)) | ||||
14537 | continue; | ||||
14538 | |||||
14539 | if (!previousMismatch) { | ||||
14540 | previousMismatch = true; | ||||
14541 | Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) | ||||
14542 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||
14543 | << getRedeclDiagFromTagKind(I->getTagKind()); | ||||
14544 | } | ||||
14545 | Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) | ||||
14546 | << getRedeclDiagFromTagKind(NewTag) | ||||
14547 | << FixItHint::CreateReplacement(I->getInnerLocStart(), | ||||
14548 | TypeWithKeyword::getTagTypeKindName(NewTag)); | ||||
14549 | } | ||||
14550 | } | ||||
14551 | return true; | ||||
14552 | } | ||||
14553 | |||||
14554 | // Identify the prevailing tag kind: this is the kind of the definition (if | ||||
14555 | // there is a non-ignored definition), or otherwise the kind of the prior | ||||
14556 | // (non-ignored) declaration. | ||||
14557 | const TagDecl *PrevDef = Previous->getDefinition(); | ||||
14558 | if (PrevDef && IsIgnored(PrevDef)) | ||||
14559 | PrevDef = nullptr; | ||||
14560 | const TagDecl *Redecl = PrevDef ? PrevDef : Previous; | ||||
14561 | if (Redecl->getTagKind() != NewTag) { | ||||
14562 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | ||||
14563 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||
14564 | << getRedeclDiagFromTagKind(OldTag); | ||||
14565 | Diag(Redecl->getLocation(), diag::note_previous_use); | ||||
14566 | |||||
14567 | // If there is a previous definition, suggest a fix-it. | ||||
14568 | if (PrevDef) { | ||||
14569 | Diag(NewTagLoc, diag::note_struct_class_suggestion) | ||||
14570 | << getRedeclDiagFromTagKind(Redecl->getTagKind()) | ||||
14571 | << FixItHint::CreateReplacement(SourceRange(NewTagLoc), | ||||
14572 | TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); | ||||
14573 | } | ||||
14574 | } | ||||
14575 | |||||
14576 | return true; | ||||
14577 | } | ||||
14578 | |||||
14579 | /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name | ||||
14580 | /// from an outer enclosing namespace or file scope inside a friend declaration. | ||||
14581 | /// This should provide the commented out code in the following snippet: | ||||
14582 | /// namespace N { | ||||
14583 | /// struct X; | ||||
14584 | /// namespace M { | ||||
14585 | /// struct Y { friend struct /*N::*/ X; }; | ||||
14586 | /// } | ||||
14587 | /// } | ||||
14588 | static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, | ||||
14589 | SourceLocation NameLoc) { | ||||
14590 | // While the decl is in a namespace, do repeated lookup of that name and see | ||||
14591 | // if we get the same namespace back. If we do not, continue until | ||||
14592 | // translation unit scope, at which point we have a fully qualified NNS. | ||||
14593 | SmallVector<IdentifierInfo *, 4> Namespaces; | ||||
14594 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | ||||
14595 | for (; !DC->isTranslationUnit(); DC = DC->getParent()) { | ||||
14596 | // This tag should be declared in a namespace, which can only be enclosed by | ||||
14597 | // other namespaces. Bail if there's an anonymous namespace in the chain. | ||||
14598 | NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); | ||||
14599 | if (!Namespace || Namespace->isAnonymousNamespace()) | ||||
14600 | return FixItHint(); | ||||
14601 | IdentifierInfo *II = Namespace->getIdentifier(); | ||||
14602 | Namespaces.push_back(II); | ||||
14603 | NamedDecl *Lookup = SemaRef.LookupSingleName( | ||||
14604 | S, II, NameLoc, Sema::LookupNestedNameSpecifierName); | ||||
14605 | if (Lookup == Namespace) | ||||
14606 | break; | ||||
14607 | } | ||||
14608 | |||||
14609 | // Once we have all the namespaces, reverse them to go outermost first, and | ||||
14610 | // build an NNS. | ||||
14611 | SmallString<64> Insertion; | ||||
14612 | llvm::raw_svector_ostream OS(Insertion); | ||||
14613 | if (DC->isTranslationUnit()) | ||||
14614 | OS << "::"; | ||||
14615 | std::reverse(Namespaces.begin(), Namespaces.end()); | ||||
14616 | for (auto *II : Namespaces) | ||||
14617 | OS << II->getName() << "::"; | ||||
14618 | return FixItHint::CreateInsertion(NameLoc, Insertion); | ||||
14619 | } | ||||
14620 | |||||
14621 | /// Determine whether a tag originally declared in context \p OldDC can | ||||
14622 | /// be redeclared with an unqualified name in \p NewDC (assuming name lookup | ||||
14623 | /// found a declaration in \p OldDC as a previous decl, perhaps through a | ||||
14624 | /// using-declaration). | ||||
14625 | static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, | ||||
14626 | DeclContext *NewDC) { | ||||
14627 | OldDC = OldDC->getRedeclContext(); | ||||
14628 | NewDC = NewDC->getRedeclContext(); | ||||
14629 | |||||
14630 | if (OldDC->Equals(NewDC)) | ||||
14631 | return true; | ||||
14632 | |||||
14633 | // In MSVC mode, we allow a redeclaration if the contexts are related (either | ||||
14634 | // encloses the other). | ||||
14635 | if (S.getLangOpts().MSVCCompat && | ||||
14636 | (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) | ||||
14637 | return true; | ||||
14638 | |||||
14639 | return false; | ||||
14640 | } | ||||
14641 | |||||
14642 | /// This is invoked when we see 'struct foo' or 'struct {'. In the | ||||
14643 | /// former case, Name will be non-null. In the later case, Name will be null. | ||||
14644 | /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a | ||||
14645 | /// reference/declaration/definition of a tag. | ||||
14646 | /// | ||||
14647 | /// \param IsTypeSpecifier \c true if this is a type-specifier (or | ||||
14648 | /// trailing-type-specifier) other than one in an alias-declaration. | ||||
14649 | /// | ||||
14650 | /// \param SkipBody If non-null, will be set to indicate if the caller should | ||||
14651 | /// skip the definition of this tag and treat it as if it were a declaration. | ||||
14652 | Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, | ||||
14653 | SourceLocation KWLoc, CXXScopeSpec &SS, | ||||
14654 | IdentifierInfo *Name, SourceLocation NameLoc, | ||||
14655 | const ParsedAttributesView &Attrs, AccessSpecifier AS, | ||||
14656 | SourceLocation ModulePrivateLoc, | ||||
14657 | MultiTemplateParamsArg TemplateParameterLists, | ||||
14658 | bool &OwnedDecl, bool &IsDependent, | ||||
14659 | SourceLocation ScopedEnumKWLoc, | ||||
14660 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, | ||||
14661 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, | ||||
14662 | SkipBodyInfo *SkipBody) { | ||||
14663 | // If this is not a definition, it must have a name. | ||||
14664 | IdentifierInfo *OrigName = Name; | ||||
14665 | assert((Name != nullptr || TUK == TUK_Definition) &&(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!" ) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14666, __PRETTY_FUNCTION__)) | ||||
14666 | "Nameless record must be a definition!")(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!" ) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14666, __PRETTY_FUNCTION__)); | ||||
14667 | assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)((TemplateParameterLists.size() == 0 || TUK != TUK_Reference) ? static_cast<void> (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14667, __PRETTY_FUNCTION__)); | ||||
14668 | |||||
14669 | OwnedDecl = false; | ||||
14670 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); | ||||
14671 | bool ScopedEnum = ScopedEnumKWLoc.isValid(); | ||||
14672 | |||||
14673 | // FIXME: Check member specializations more carefully. | ||||
14674 | bool isMemberSpecialization = false; | ||||
14675 | bool Invalid = false; | ||||
14676 | |||||
14677 | // We only need to do this matching if we have template parameters | ||||
14678 | // or a scope specifier, which also conveniently avoids this work | ||||
14679 | // for non-C++ cases. | ||||
14680 | if (TemplateParameterLists.size() > 0 || | ||||
14681 | (SS.isNotEmpty() && TUK != TUK_Reference)) { | ||||
14682 | if (TemplateParameterList *TemplateParams = | ||||
14683 | MatchTemplateParametersToScopeSpecifier( | ||||
14684 | KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, | ||||
14685 | TUK == TUK_Friend, isMemberSpecialization, Invalid)) { | ||||
14686 | if (Kind == TTK_Enum) { | ||||
14687 | Diag(KWLoc, diag::err_enum_template); | ||||
14688 | return nullptr; | ||||
14689 | } | ||||
14690 | |||||
14691 | if (TemplateParams->size() > 0) { | ||||
14692 | // This is a declaration or definition of a class template (which may | ||||
14693 | // be a member of another template). | ||||
14694 | |||||
14695 | if (Invalid) | ||||
14696 | return nullptr; | ||||
14697 | |||||
14698 | OwnedDecl = false; | ||||
14699 | DeclResult Result = CheckClassTemplate( | ||||
14700 | S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, | ||||
14701 | AS, ModulePrivateLoc, | ||||
14702 | /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, | ||||
14703 | TemplateParameterLists.data(), SkipBody); | ||||
14704 | return Result.get(); | ||||
14705 | } else { | ||||
14706 | // The "template<>" header is extraneous. | ||||
14707 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) | ||||
14708 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; | ||||
14709 | isMemberSpecialization = true; | ||||
14710 | } | ||||
14711 | } | ||||
14712 | } | ||||
14713 | |||||
14714 | // Figure out the underlying type if this a enum declaration. We need to do | ||||
14715 | // this early, because it's needed to detect if this is an incompatible | ||||
14716 | // redeclaration. | ||||
14717 | llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; | ||||
14718 | bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; | ||||
14719 | |||||
14720 | if (Kind == TTK_Enum) { | ||||
14721 | if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { | ||||
14722 | // No underlying type explicitly specified, or we failed to parse the | ||||
14723 | // type, default to int. | ||||
14724 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||
14725 | } else if (UnderlyingType.get()) { | ||||
14726 | // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an | ||||
14727 | // integral type; any cv-qualification is ignored. | ||||
14728 | TypeSourceInfo *TI = nullptr; | ||||
14729 | GetTypeFromParser(UnderlyingType.get(), &TI); | ||||
14730 | EnumUnderlying = TI; | ||||
14731 | |||||
14732 | if (CheckEnumUnderlyingType(TI)) | ||||
14733 | // Recover by falling back to int. | ||||
14734 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||
14735 | |||||
14736 | if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, | ||||
14737 | UPPC_FixedUnderlyingType)) | ||||
14738 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||
14739 | |||||
14740 | } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { | ||||
14741 | // For MSVC ABI compatibility, unfixed enums must use an underlying type | ||||
14742 | // of 'int'. However, if this is an unfixed forward declaration, don't set | ||||
14743 | // the underlying type unless the user enables -fms-compatibility. This | ||||
14744 | // makes unfixed forward declared enums incomplete and is more conforming. | ||||
14745 | if (TUK == TUK_Definition || getLangOpts().MSVCCompat) | ||||
14746 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||
14747 | } | ||||
14748 | } | ||||
14749 | |||||
14750 | DeclContext *SearchDC = CurContext; | ||||
14751 | DeclContext *DC = CurContext; | ||||
14752 | bool isStdBadAlloc = false; | ||||
14753 | bool isStdAlignValT = false; | ||||
14754 | |||||
14755 | RedeclarationKind Redecl = forRedeclarationInCurContext(); | ||||
14756 | if (TUK == TUK_Friend || TUK == TUK_Reference) | ||||
14757 | Redecl = NotForRedeclaration; | ||||
14758 | |||||
14759 | /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C | ||||
14760 | /// implemented asks for structural equivalence checking, the returned decl | ||||
14761 | /// here is passed back to the parser, allowing the tag body to be parsed. | ||||
14762 | auto createTagFromNewDecl = [&]() -> TagDecl * { | ||||
14763 | assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")((!getLangOpts().CPlusPlus && "not meant for C++ usage" ) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14763, __PRETTY_FUNCTION__)); | ||||
14764 | // If there is an identifier, use the location of the identifier as the | ||||
14765 | // location of the decl, otherwise use the location of the struct/union | ||||
14766 | // keyword. | ||||
14767 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | ||||
14768 | TagDecl *New = nullptr; | ||||
14769 | |||||
14770 | if (Kind == TTK_Enum) { | ||||
14771 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, | ||||
14772 | ScopedEnum, ScopedEnumUsesClassTag, IsFixed); | ||||
14773 | // If this is an undefined enum, bail. | ||||
14774 | if (TUK != TUK_Definition && !Invalid) | ||||
14775 | return nullptr; | ||||
14776 | if (EnumUnderlying) { | ||||
14777 | EnumDecl *ED = cast<EnumDecl>(New); | ||||
14778 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) | ||||
14779 | ED->setIntegerTypeSourceInfo(TI); | ||||
14780 | else | ||||
14781 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); | ||||
14782 | ED->setPromotionType(ED->getIntegerType()); | ||||
14783 | } | ||||
14784 | } else { // struct/union | ||||
14785 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||
14786 | nullptr); | ||||
14787 | } | ||||
14788 | |||||
14789 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | ||||
14790 | // Add alignment attributes if necessary; these attributes are checked | ||||
14791 | // when the ASTContext lays out the structure. | ||||
14792 | // | ||||
14793 | // It is important for implementing the correct semantics that this | ||||
14794 | // happen here (in ActOnTag). The #pragma pack stack is | ||||
14795 | // maintained as a result of parser callbacks which can occur at | ||||
14796 | // many points during the parsing of a struct declaration (because | ||||
14797 | // the #pragma tokens are effectively skipped over during the | ||||
14798 | // parsing of the struct). | ||||
14799 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | ||||
14800 | AddAlignmentAttributesForRecord(RD); | ||||
14801 | AddMsStructLayoutForRecord(RD); | ||||
14802 | } | ||||
14803 | } | ||||
14804 | New->setLexicalDeclContext(CurContext); | ||||
14805 | return New; | ||||
14806 | }; | ||||
14807 | |||||
14808 | LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); | ||||
14809 | if (Name && SS.isNotEmpty()) { | ||||
14810 | // We have a nested-name tag ('struct foo::bar'). | ||||
14811 | |||||
14812 | // Check for invalid 'foo::'. | ||||
14813 | if (SS.isInvalid()) { | ||||
14814 | Name = nullptr; | ||||
14815 | goto CreateNewDecl; | ||||
14816 | } | ||||
14817 | |||||
14818 | // If this is a friend or a reference to a class in a dependent | ||||
14819 | // context, don't try to make a decl for it. | ||||
14820 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | ||||
14821 | DC = computeDeclContext(SS, false); | ||||
14822 | if (!DC) { | ||||
14823 | IsDependent = true; | ||||
14824 | return nullptr; | ||||
14825 | } | ||||
14826 | } else { | ||||
14827 | DC = computeDeclContext(SS, true); | ||||
14828 | if (!DC) { | ||||
14829 | Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) | ||||
14830 | << SS.getRange(); | ||||
14831 | return nullptr; | ||||
14832 | } | ||||
14833 | } | ||||
14834 | |||||
14835 | if (RequireCompleteDeclContext(SS, DC)) | ||||
14836 | return nullptr; | ||||
14837 | |||||
14838 | SearchDC = DC; | ||||
14839 | // Look-up name inside 'foo::'. | ||||
14840 | LookupQualifiedName(Previous, DC); | ||||
14841 | |||||
14842 | if (Previous.isAmbiguous()) | ||||
14843 | return nullptr; | ||||
14844 | |||||
14845 | if (Previous.empty()) { | ||||
14846 | // Name lookup did not find anything. However, if the | ||||
14847 | // nested-name-specifier refers to the current instantiation, | ||||
14848 | // and that current instantiation has any dependent base | ||||
14849 | // classes, we might find something at instantiation time: treat | ||||
14850 | // this as a dependent elaborated-type-specifier. | ||||
14851 | // But this only makes any sense for reference-like lookups. | ||||
14852 | if (Previous.wasNotFoundInCurrentInstantiation() && | ||||
14853 | (TUK == TUK_Reference || TUK == TUK_Friend)) { | ||||
14854 | IsDependent = true; | ||||
14855 | return nullptr; | ||||
14856 | } | ||||
14857 | |||||
14858 | // A tag 'foo::bar' must already exist. | ||||
14859 | Diag(NameLoc, diag::err_not_tag_in_scope) | ||||
14860 | << Kind << Name << DC << SS.getRange(); | ||||
14861 | Name = nullptr; | ||||
14862 | Invalid = true; | ||||
14863 | goto CreateNewDecl; | ||||
14864 | } | ||||
14865 | } else if (Name) { | ||||
14866 | // C++14 [class.mem]p14: | ||||
14867 | // If T is the name of a class, then each of the following shall have a | ||||
14868 | // name different from T: | ||||
14869 | // -- every member of class T that is itself a type | ||||
14870 | if (TUK != TUK_Reference && TUK != TUK_Friend && | ||||
14871 | DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) | ||||
14872 | return nullptr; | ||||
14873 | |||||
14874 | // If this is a named struct, check to see if there was a previous forward | ||||
14875 | // declaration or definition. | ||||
14876 | // FIXME: We're looking into outer scopes here, even when we | ||||
14877 | // shouldn't be. Doing so can result in ambiguities that we | ||||
14878 | // shouldn't be diagnosing. | ||||
14879 | LookupName(Previous, S); | ||||
14880 | |||||
14881 | // When declaring or defining a tag, ignore ambiguities introduced | ||||
14882 | // by types using'ed into this scope. | ||||
14883 | if (Previous.isAmbiguous() && | ||||
14884 | (TUK == TUK_Definition || TUK == TUK_Declaration)) { | ||||
14885 | LookupResult::Filter F = Previous.makeFilter(); | ||||
14886 | while (F.hasNext()) { | ||||
14887 | NamedDecl *ND = F.next(); | ||||
14888 | if (!ND->getDeclContext()->getRedeclContext()->Equals( | ||||
14889 | SearchDC->getRedeclContext())) | ||||
14890 | F.erase(); | ||||
14891 | } | ||||
14892 | F.done(); | ||||
14893 | } | ||||
14894 | |||||
14895 | // C++11 [namespace.memdef]p3: | ||||
14896 | // If the name in a friend declaration is neither qualified nor | ||||
14897 | // a template-id and the declaration is a function or an | ||||
14898 | // elaborated-type-specifier, the lookup to determine whether | ||||
14899 | // the entity has been previously declared shall not consider | ||||
14900 | // any scopes outside the innermost enclosing namespace. | ||||
14901 | // | ||||
14902 | // MSVC doesn't implement the above rule for types, so a friend tag | ||||
14903 | // declaration may be a redeclaration of a type declared in an enclosing | ||||
14904 | // scope. They do implement this rule for friend functions. | ||||
14905 | // | ||||
14906 | // Does it matter that this should be by scope instead of by | ||||
14907 | // semantic context? | ||||
14908 | if (!Previous.empty() && TUK == TUK_Friend) { | ||||
14909 | DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); | ||||
14910 | LookupResult::Filter F = Previous.makeFilter(); | ||||
14911 | bool FriendSawTagOutsideEnclosingNamespace = false; | ||||
14912 | while (F.hasNext()) { | ||||
14913 | NamedDecl *ND = F.next(); | ||||
14914 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | ||||
14915 | if (DC->isFileContext() && | ||||
14916 | !EnclosingNS->Encloses(ND->getDeclContext())) { | ||||
14917 | if (getLangOpts().MSVCCompat) | ||||
14918 | FriendSawTagOutsideEnclosingNamespace = true; | ||||
14919 | else | ||||
14920 | F.erase(); | ||||
14921 | } | ||||
14922 | } | ||||
14923 | F.done(); | ||||
14924 | |||||
14925 | // Diagnose this MSVC extension in the easy case where lookup would have | ||||
14926 | // unambiguously found something outside the enclosing namespace. | ||||
14927 | if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { | ||||
14928 | NamedDecl *ND = Previous.getFoundDecl(); | ||||
14929 | Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) | ||||
14930 | << createFriendTagNNSFixIt(*this, ND, S, NameLoc); | ||||
14931 | } | ||||
14932 | } | ||||
14933 | |||||
14934 | // Note: there used to be some attempt at recovery here. | ||||
14935 | if (Previous.isAmbiguous()) | ||||
14936 | return nullptr; | ||||
14937 | |||||
14938 | if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { | ||||
14939 | // FIXME: This makes sure that we ignore the contexts associated | ||||
14940 | // with C structs, unions, and enums when looking for a matching | ||||
14941 | // tag declaration or definition. See the similar lookup tweak | ||||
14942 | // in Sema::LookupName; is there a better way to deal with this? | ||||
14943 | while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) | ||||
14944 | SearchDC = SearchDC->getParent(); | ||||
14945 | } | ||||
14946 | } | ||||
14947 | |||||
14948 | if (Previous.isSingleResult() && | ||||
14949 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||
14950 | // Maybe we will complain about the shadowed template parameter. | ||||
14951 | DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); | ||||
14952 | // Just pretend that we didn't see the previous declaration. | ||||
14953 | Previous.clear(); | ||||
14954 | } | ||||
14955 | |||||
14956 | if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && | ||||
14957 | DC->Equals(getStdNamespace())) { | ||||
14958 | if (Name->isStr("bad_alloc")) { | ||||
14959 | // This is a declaration of or a reference to "std::bad_alloc". | ||||
14960 | isStdBadAlloc = true; | ||||
14961 | |||||
14962 | // If std::bad_alloc has been implicitly declared (but made invisible to | ||||
14963 | // name lookup), fill in this implicit declaration as the previous | ||||
14964 | // declaration, so that the declarations get chained appropriately. | ||||
14965 | if (Previous.empty() && StdBadAlloc) | ||||
14966 | Previous.addDecl(getStdBadAlloc()); | ||||
14967 | } else if (Name->isStr("align_val_t")) { | ||||
14968 | isStdAlignValT = true; | ||||
14969 | if (Previous.empty() && StdAlignValT) | ||||
14970 | Previous.addDecl(getStdAlignValT()); | ||||
14971 | } | ||||
14972 | } | ||||
14973 | |||||
14974 | // If we didn't find a previous declaration, and this is a reference | ||||
14975 | // (or friend reference), move to the correct scope. In C++, we | ||||
14976 | // also need to do a redeclaration lookup there, just in case | ||||
14977 | // there's a shadow friend decl. | ||||
14978 | if (Name && Previous.empty() && | ||||
14979 | (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { | ||||
14980 | if (Invalid) goto CreateNewDecl; | ||||
14981 | assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 14981, __PRETTY_FUNCTION__)); | ||||
14982 | |||||
14983 | if (TUK == TUK_Reference || IsTemplateParamOrArg) { | ||||
14984 | // C++ [basic.scope.pdecl]p5: | ||||
14985 | // -- for an elaborated-type-specifier of the form | ||||
14986 | // | ||||
14987 | // class-key identifier | ||||
14988 | // | ||||
14989 | // if the elaborated-type-specifier is used in the | ||||
14990 | // decl-specifier-seq or parameter-declaration-clause of a | ||||
14991 | // function defined in namespace scope, the identifier is | ||||
14992 | // declared as a class-name in the namespace that contains | ||||
14993 | // the declaration; otherwise, except as a friend | ||||
14994 | // declaration, the identifier is declared in the smallest | ||||
14995 | // non-class, non-function-prototype scope that contains the | ||||
14996 | // declaration. | ||||
14997 | // | ||||
14998 | // C99 6.7.2.3p8 has a similar (but not identical!) provision for | ||||
14999 | // C structs and unions. | ||||
15000 | // | ||||
15001 | // It is an error in C++ to declare (rather than define) an enum | ||||
15002 | // type, including via an elaborated type specifier. We'll | ||||
15003 | // diagnose that later; for now, declare the enum in the same | ||||
15004 | // scope as we would have picked for any other tag type. | ||||
15005 | // | ||||
15006 | // GNU C also supports this behavior as part of its incomplete | ||||
15007 | // enum types extension, while GNU C++ does not. | ||||
15008 | // | ||||
15009 | // Find the context where we'll be declaring the tag. | ||||
15010 | // FIXME: We would like to maintain the current DeclContext as the | ||||
15011 | // lexical context, | ||||
15012 | SearchDC = getTagInjectionContext(SearchDC); | ||||
15013 | |||||
15014 | // Find the scope where we'll be declaring the tag. | ||||
15015 | S = getTagInjectionScope(S, getLangOpts()); | ||||
15016 | } else { | ||||
15017 | assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail ("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 15017, __PRETTY_FUNCTION__)); | ||||
15018 | // C++ [namespace.memdef]p3: | ||||
15019 | // If a friend declaration in a non-local class first declares a | ||||
15020 | // class or function, the friend class or function is a member of | ||||
15021 | // the innermost enclosing namespace. | ||||
15022 | SearchDC = SearchDC->getEnclosingNamespaceContext(); | ||||
15023 | } | ||||
15024 | |||||
15025 | // In C++, we need to do a redeclaration lookup to properly | ||||
15026 | // diagnose some problems. | ||||
15027 | // FIXME: redeclaration lookup is also used (with and without C++) to find a | ||||
15028 | // hidden declaration so that we don't get ambiguity errors when using a | ||||
15029 | // type declared by an elaborated-type-specifier. In C that is not correct | ||||
15030 | // and we should instead merge compatible types found by lookup. | ||||
15031 | if (getLangOpts().CPlusPlus) { | ||||
15032 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | ||||
15033 | LookupQualifiedName(Previous, SearchDC); | ||||
15034 | } else { | ||||
15035 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | ||||
15036 | LookupName(Previous, S); | ||||
15037 | } | ||||
15038 | } | ||||
15039 | |||||
15040 | // If we have a known previous declaration to use, then use it. | ||||
15041 | if (Previous.empty() && SkipBody && SkipBody->Previous) | ||||
15042 | Previous.addDecl(SkipBody->Previous); | ||||
15043 | |||||
15044 | if (!Previous.empty()) { | ||||
15045 | NamedDecl *PrevDecl = Previous.getFoundDecl(); | ||||
15046 | NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); | ||||
15047 | |||||
15048 | // It's okay to have a tag decl in the same scope as a typedef | ||||
15049 | // which hides a tag decl in the same scope. Finding this | ||||
15050 | // insanity with a redeclaration lookup can only actually happen | ||||
15051 | // in C++. | ||||
15052 | // | ||||
15053 | // This is also okay for elaborated-type-specifiers, which is | ||||
15054 | // technically forbidden by the current standard but which is | ||||
15055 | // okay according to the likely resolution of an open issue; | ||||
15056 | // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 | ||||
15057 | if (getLangOpts().CPlusPlus) { | ||||
15058 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { | ||||
15059 | if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { | ||||
15060 | TagDecl *Tag = TT->getDecl(); | ||||
15061 | if (Tag->getDeclName() == Name && | ||||
15062 | Tag->getDeclContext()->getRedeclContext() | ||||
15063 | ->Equals(TD->getDeclContext()->getRedeclContext())) { | ||||
15064 | PrevDecl = Tag; | ||||
15065 | Previous.clear(); | ||||
15066 | Previous.addDecl(Tag); | ||||
15067 | Previous.resolveKind(); | ||||
15068 | } | ||||
15069 | } | ||||
15070 | } | ||||
15071 | } | ||||
15072 | |||||
15073 | // If this is a redeclaration of a using shadow declaration, it must | ||||
15074 | // declare a tag in the same context. In MSVC mode, we allow a | ||||
15075 | // redefinition if either context is within the other. | ||||
15076 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { | ||||
15077 | auto *OldTag = dyn_cast<TagDecl>(PrevDecl); | ||||
15078 | if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && | ||||
15079 | isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && | ||||
15080 | !(OldTag && isAcceptableTagRedeclContext( | ||||
15081 | *this, OldTag->getDeclContext(), SearchDC))) { | ||||
15082 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); | ||||
15083 | Diag(Shadow->getTargetDecl()->getLocation(), | ||||
15084 | diag::note_using_decl_target); | ||||
15085 | Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) | ||||
15086 | << 0; | ||||
15087 | // Recover by ignoring the old declaration. | ||||
15088 | Previous.clear(); | ||||
15089 | goto CreateNewDecl; | ||||
15090 | } | ||||
15091 | } | ||||
15092 | |||||
15093 | if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { | ||||
15094 | // If this is a use of a previous tag, or if the tag is already declared | ||||
15095 | // in the same scope (so that the definition/declaration completes or | ||||
15096 | // rementions the tag), reuse the decl. | ||||
15097 | if (TUK == TUK_Reference || TUK == TUK_Friend || | ||||
15098 | isDeclInScope(DirectPrevDecl, SearchDC, S, | ||||
15099 | SS.isNotEmpty() || isMemberSpecialization)) { | ||||
15100 | // Make sure that this wasn't declared as an enum and now used as a | ||||
15101 | // struct or something similar. | ||||
15102 | if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, | ||||
15103 | TUK == TUK_Definition, KWLoc, | ||||
15104 | Name)) { | ||||
15105 | bool SafeToContinue | ||||
15106 | = (PrevTagDecl->getTagKind() != TTK_Enum && | ||||
15107 | Kind != TTK_Enum); | ||||
15108 | if (SafeToContinue) | ||||
15109 | Diag(KWLoc, diag::err_use_with_wrong_tag) | ||||
15110 | << Name | ||||
15111 | << FixItHint::CreateReplacement(SourceRange(KWLoc), | ||||
15112 | PrevTagDecl->getKindName()); | ||||
15113 | else | ||||
15114 | Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; | ||||
15115 | Diag(PrevTagDecl->getLocation(), diag::note_previous_use); | ||||
15116 | |||||
15117 | if (SafeToContinue) | ||||
15118 | Kind = PrevTagDecl->getTagKind(); | ||||
15119 | else { | ||||
15120 | // Recover by making this an anonymous redefinition. | ||||
15121 | Name = nullptr; | ||||
15122 | Previous.clear(); | ||||
15123 | Invalid = true; | ||||
15124 | } | ||||
15125 | } | ||||
15126 | |||||
15127 | if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { | ||||
15128 | const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); | ||||
15129 | |||||
15130 | // If this is an elaborated-type-specifier for a scoped enumeration, | ||||
15131 | // the 'class' keyword is not necessary and not permitted. | ||||
15132 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||
15133 | if (ScopedEnum) | ||||
15134 | Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) | ||||
15135 | << PrevEnum->isScoped() | ||||
15136 | << FixItHint::CreateRemoval(ScopedEnumKWLoc); | ||||
15137 | return PrevTagDecl; | ||||
15138 | } | ||||
15139 | |||||
15140 | QualType EnumUnderlyingTy; | ||||
15141 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | ||||
15142 | EnumUnderlyingTy = TI->getType().getUnqualifiedType(); | ||||
15143 | else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) | ||||
15144 | EnumUnderlyingTy = QualType(T, 0); | ||||
15145 | |||||
15146 | // All conflicts with previous declarations are recovered by | ||||
15147 | // returning the previous declaration, unless this is a definition, | ||||
15148 | // in which case we want the caller to bail out. | ||||
15149 | if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, | ||||
15150 | ScopedEnum, EnumUnderlyingTy, | ||||
15151 | IsFixed, PrevEnum)) | ||||
15152 | return TUK == TUK_Declaration ? PrevTagDecl : nullptr; | ||||
15153 | } | ||||
15154 | |||||
15155 | // C++11 [class.mem]p1: | ||||
15156 | // A member shall not be declared twice in the member-specification, | ||||
15157 | // except that a nested class or member class template can be declared | ||||
15158 | // and then later defined. | ||||
15159 | if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && | ||||
15160 | S->isDeclScope(PrevDecl)) { | ||||
15161 | Diag(NameLoc, diag::ext_member_redeclared); | ||||
15162 | Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); | ||||
15163 | } | ||||
15164 | |||||
15165 | if (!Invalid) { | ||||
15166 | // If this is a use, just return the declaration we found, unless | ||||
15167 | // we have attributes. | ||||
15168 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||
15169 | if (!Attrs.empty()) { | ||||
15170 | // FIXME: Diagnose these attributes. For now, we create a new | ||||
15171 | // declaration to hold them. | ||||
15172 | } else if (TUK == TUK_Reference && | ||||
15173 | (PrevTagDecl->getFriendObjectKind() == | ||||
15174 | Decl::FOK_Undeclared || | ||||
15175 | PrevDecl->getOwningModule() != getCurrentModule()) && | ||||
15176 | SS.isEmpty()) { | ||||
15177 | // This declaration is a reference to an existing entity, but | ||||
15178 | // has different visibility from that entity: it either makes | ||||
15179 | // a friend visible or it makes a type visible in a new module. | ||||
15180 | // In either case, create a new declaration. We only do this if | ||||
15181 | // the declaration would have meant the same thing if no prior | ||||
15182 | // declaration were found, that is, if it was found in the same | ||||
15183 | // scope where we would have injected a declaration. | ||||
15184 | if (!getTagInjectionContext(CurContext)->getRedeclContext() | ||||
15185 | ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) | ||||
15186 | return PrevTagDecl; | ||||
15187 | // This is in the injected scope, create a new declaration in | ||||
15188 | // that scope. | ||||
15189 | S = getTagInjectionScope(S, getLangOpts()); | ||||
15190 | } else { | ||||
15191 | return PrevTagDecl; | ||||
15192 | } | ||||
15193 | } | ||||
15194 | |||||
15195 | // Diagnose attempts to redefine a tag. | ||||
15196 | if (TUK == TUK_Definition) { | ||||
15197 | if (NamedDecl *Def = PrevTagDecl->getDefinition()) { | ||||
15198 | // If we're defining a specialization and the previous definition | ||||
15199 | // is from an implicit instantiation, don't emit an error | ||||
15200 | // here; we'll catch this in the general case below. | ||||
15201 | bool IsExplicitSpecializationAfterInstantiation = false; | ||||
15202 | if (isMemberSpecialization) { | ||||
15203 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) | ||||
15204 | IsExplicitSpecializationAfterInstantiation = | ||||
15205 | RD->getTemplateSpecializationKind() != | ||||
15206 | TSK_ExplicitSpecialization; | ||||
15207 | else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) | ||||
15208 | IsExplicitSpecializationAfterInstantiation = | ||||
15209 | ED->getTemplateSpecializationKind() != | ||||
15210 | TSK_ExplicitSpecialization; | ||||
15211 | } | ||||
15212 | |||||
15213 | // Note that clang allows ODR-like semantics for ObjC/C, i.e., do | ||||
15214 | // not keep more that one definition around (merge them). However, | ||||
15215 | // ensure the decl passes the structural compatibility check in | ||||
15216 | // C11 6.2.7/1 (or 6.1.2.6/1 in C89). | ||||
15217 | NamedDecl *Hidden = nullptr; | ||||
15218 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { | ||||
15219 | // There is a definition of this tag, but it is not visible. We | ||||
15220 | // explicitly make use of C++'s one definition rule here, and | ||||
15221 | // assume that this definition is identical to the hidden one | ||||
15222 | // we already have. Make the existing definition visible and | ||||
15223 | // use it in place of this one. | ||||
15224 | if (!getLangOpts().CPlusPlus) { | ||||
15225 | // Postpone making the old definition visible until after we | ||||
15226 | // complete parsing the new one and do the structural | ||||
15227 | // comparison. | ||||
15228 | SkipBody->CheckSameAsPrevious = true; | ||||
15229 | SkipBody->New = createTagFromNewDecl(); | ||||
15230 | SkipBody->Previous = Def; | ||||
15231 | return Def; | ||||
15232 | } else { | ||||
15233 | SkipBody->ShouldSkip = true; | ||||
15234 | SkipBody->Previous = Def; | ||||
15235 | makeMergedDefinitionVisible(Hidden); | ||||
15236 | // Carry on and handle it like a normal definition. We'll | ||||
15237 | // skip starting the definitiion later. | ||||
15238 | } | ||||
15239 | } else if (!IsExplicitSpecializationAfterInstantiation) { | ||||
15240 | // A redeclaration in function prototype scope in C isn't | ||||
15241 | // visible elsewhere, so merely issue a warning. | ||||
15242 | if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) | ||||
15243 | Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; | ||||
15244 | else | ||||
15245 | Diag(NameLoc, diag::err_redefinition) << Name; | ||||
15246 | notePreviousDefinition(Def, | ||||
15247 | NameLoc.isValid() ? NameLoc : KWLoc); | ||||
15248 | // If this is a redefinition, recover by making this | ||||
15249 | // struct be anonymous, which will make any later | ||||
15250 | // references get the previous definition. | ||||
15251 | Name = nullptr; | ||||
15252 | Previous.clear(); | ||||
15253 | Invalid = true; | ||||
15254 | } | ||||
15255 | } else { | ||||
15256 | // If the type is currently being defined, complain | ||||
15257 | // about a nested redefinition. | ||||
15258 | auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); | ||||
15259 | if (TD->isBeingDefined()) { | ||||
15260 | Diag(NameLoc, diag::err_nested_redefinition) << Name; | ||||
15261 | Diag(PrevTagDecl->getLocation(), | ||||
15262 | diag::note_previous_definition); | ||||
15263 | Name = nullptr; | ||||
15264 | Previous.clear(); | ||||
15265 | Invalid = true; | ||||
15266 | } | ||||
15267 | } | ||||
15268 | |||||
15269 | // Okay, this is definition of a previously declared or referenced | ||||
15270 | // tag. We're going to create a new Decl for it. | ||||
15271 | } | ||||
15272 | |||||
15273 | // Okay, we're going to make a redeclaration. If this is some kind | ||||
15274 | // of reference, make sure we build the redeclaration in the same DC | ||||
15275 | // as the original, and ignore the current access specifier. | ||||
15276 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | ||||
15277 | SearchDC = PrevTagDecl->getDeclContext(); | ||||
15278 | AS = AS_none; | ||||
15279 | } | ||||
15280 | } | ||||
15281 | // If we get here we have (another) forward declaration or we | ||||
15282 | // have a definition. Just create a new decl. | ||||
15283 | |||||
15284 | } else { | ||||
15285 | // If we get here, this is a definition of a new tag type in a nested | ||||
15286 | // scope, e.g. "struct foo; void bar() { struct foo; }", just create a | ||||
15287 | // new decl/type. We set PrevDecl to NULL so that the entities | ||||
15288 | // have distinct types. | ||||
15289 | Previous.clear(); | ||||
15290 | } | ||||
15291 | // If we get here, we're going to create a new Decl. If PrevDecl | ||||
15292 | // is non-NULL, it's a definition of the tag declared by | ||||
15293 | // PrevDecl. If it's NULL, we have a new definition. | ||||
15294 | |||||
15295 | // Otherwise, PrevDecl is not a tag, but was found with tag | ||||
15296 | // lookup. This is only actually possible in C++, where a few | ||||
15297 | // things like templates still live in the tag namespace. | ||||
15298 | } else { | ||||
15299 | // Use a better diagnostic if an elaborated-type-specifier | ||||
15300 | // found the wrong kind of type on the first | ||||
15301 | // (non-redeclaration) lookup. | ||||
15302 | if ((TUK == TUK_Reference || TUK == TUK_Friend) && | ||||
15303 | !Previous.isForRedeclaration()) { | ||||
15304 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | ||||
15305 | Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK | ||||
15306 | << Kind; | ||||
15307 | Diag(PrevDecl->getLocation(), diag::note_declared_at); | ||||
15308 | Invalid = true; | ||||
15309 | |||||
15310 | // Otherwise, only diagnose if the declaration is in scope. | ||||
15311 | } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, | ||||
15312 | SS.isNotEmpty() || isMemberSpecialization)) { | ||||
15313 | // do nothing | ||||
15314 | |||||
15315 | // Diagnose implicit declarations introduced by elaborated types. | ||||
15316 | } else if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||
15317 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | ||||
15318 | Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; | ||||
15319 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | ||||
15320 | Invalid = true; | ||||
15321 | |||||
15322 | // Otherwise it's a declaration. Call out a particularly common | ||||
15323 | // case here. | ||||
15324 | } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { | ||||
15325 | unsigned Kind = 0; | ||||
15326 | if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; | ||||
15327 | Diag(NameLoc, diag::err_tag_definition_of_typedef) | ||||
15328 | << Name << Kind << TND->getUnderlyingType(); | ||||
15329 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | ||||
15330 | Invalid = true; | ||||
15331 | |||||
15332 | // Otherwise, diagnose. | ||||
15333 | } else { | ||||
15334 | // The tag name clashes with something else in the target scope, | ||||
15335 | // issue an error and recover by making this tag be anonymous. | ||||
15336 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; | ||||
15337 | notePreviousDefinition(PrevDecl, NameLoc); | ||||
15338 | Name = nullptr; | ||||
15339 | Invalid = true; | ||||
15340 | } | ||||
15341 | |||||
15342 | // The existing declaration isn't relevant to us; we're in a | ||||
15343 | // new scope, so clear out the previous declaration. | ||||
15344 | Previous.clear(); | ||||
15345 | } | ||||
15346 | } | ||||
15347 | |||||
15348 | CreateNewDecl: | ||||
15349 | |||||
15350 | TagDecl *PrevDecl = nullptr; | ||||
15351 | if (Previous.isSingleResult()) | ||||
15352 | PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); | ||||
15353 | |||||
15354 | // If there is an identifier, use the location of the identifier as the | ||||
15355 | // location of the decl, otherwise use the location of the struct/union | ||||
15356 | // keyword. | ||||
15357 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | ||||
15358 | |||||
15359 | // Otherwise, create a new declaration. If there is a previous | ||||
15360 | // declaration of the same entity, the two will be linked via | ||||
15361 | // PrevDecl. | ||||
15362 | TagDecl *New; | ||||
15363 | |||||
15364 | if (Kind == TTK_Enum) { | ||||
15365 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | ||||
15366 | // enum X { A, B, C } D; D should chain to X. | ||||
15367 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, | ||||
15368 | cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, | ||||
15369 | ScopedEnumUsesClassTag, IsFixed); | ||||
15370 | |||||
15371 | if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) | ||||
15372 | StdAlignValT = cast<EnumDecl>(New); | ||||
15373 | |||||
15374 | // If this is an undefined enum, warn. | ||||
15375 | if (TUK != TUK_Definition && !Invalid) { | ||||
15376 | TagDecl *Def; | ||||
15377 | if (IsFixed && cast<EnumDecl>(New)->isFixed()) { | ||||
15378 | // C++0x: 7.2p2: opaque-enum-declaration. | ||||
15379 | // Conflicts are diagnosed above. Do nothing. | ||||
15380 | } | ||||
15381 | else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { | ||||
15382 | Diag(Loc, diag::ext_forward_ref_enum_def) | ||||
15383 | << New; | ||||
15384 | Diag(Def->getLocation(), diag::note_previous_definition); | ||||
15385 | } else { | ||||
15386 | unsigned DiagID = diag::ext_forward_ref_enum; | ||||
15387 | if (getLangOpts().MSVCCompat) | ||||
15388 | DiagID = diag::ext_ms_forward_ref_enum; | ||||
15389 | else if (getLangOpts().CPlusPlus) | ||||
15390 | DiagID = diag::err_forward_ref_enum; | ||||
15391 | Diag(Loc, DiagID); | ||||
15392 | } | ||||
15393 | } | ||||
15394 | |||||
15395 | if (EnumUnderlying) { | ||||
15396 | EnumDecl *ED = cast<EnumDecl>(New); | ||||
15397 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | ||||
15398 | ED->setIntegerTypeSourceInfo(TI); | ||||
15399 | else | ||||
15400 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); | ||||
15401 | ED->setPromotionType(ED->getIntegerType()); | ||||
15402 | assert(ED->isComplete() && "enum with type should be complete")((ED->isComplete() && "enum with type should be complete" ) ? static_cast<void> (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 15402, __PRETTY_FUNCTION__)); | ||||
15403 | } | ||||
15404 | } else { | ||||
15405 | // struct/union/class | ||||
15406 | |||||
15407 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | ||||
15408 | // struct X { int A; } D; D should chain to X. | ||||
15409 | if (getLangOpts().CPlusPlus) { | ||||
15410 | // FIXME: Look for a way to use RecordDecl for simple structs. | ||||
15411 | New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||
15412 | cast_or_null<CXXRecordDecl>(PrevDecl)); | ||||
15413 | |||||
15414 | if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) | ||||
15415 | StdBadAlloc = cast<CXXRecordDecl>(New); | ||||
15416 | } else | ||||
15417 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||
15418 | cast_or_null<RecordDecl>(PrevDecl)); | ||||
15419 | } | ||||
15420 | |||||
15421 | // C++11 [dcl.type]p3: | ||||
15422 | // A type-specifier-seq shall not define a class or enumeration [...]. | ||||
15423 | if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && | ||||
15424 | TUK == TUK_Definition) { | ||||
15425 | Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) | ||||
15426 | << Context.getTagDeclType(New); | ||||
15427 | Invalid = true; | ||||
15428 | } | ||||
15429 | |||||
15430 | if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && | ||||
15431 | DC->getDeclKind() == Decl::Enum) { | ||||
15432 | Diag(New->getLocation(), diag::err_type_defined_in_enum) | ||||
15433 | << Context.getTagDeclType(New); | ||||
15434 | Invalid = true; | ||||
15435 | } | ||||
15436 | |||||
15437 | // Maybe add qualifier info. | ||||
15438 | if (SS.isNotEmpty()) { | ||||
15439 | if (SS.isSet()) { | ||||
15440 | // If this is either a declaration or a definition, check the | ||||
15441 | // nested-name-specifier against the current context. | ||||
15442 | if ((TUK == TUK_Definition || TUK == TUK_Declaration) && | ||||
15443 | diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, | ||||
15444 | isMemberSpecialization)) | ||||
15445 | Invalid = true; | ||||
15446 | |||||
15447 | New->setQualifierInfo(SS.getWithLocInContext(Context)); | ||||
15448 | if (TemplateParameterLists.size() > 0) { | ||||
15449 | New->setTemplateParameterListsInfo(Context, TemplateParameterLists); | ||||
15450 | } | ||||
15451 | } | ||||
15452 | else | ||||
15453 | Invalid = true; | ||||
15454 | } | ||||
15455 | |||||
15456 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | ||||
15457 | // Add alignment attributes if necessary; these attributes are checked when | ||||
15458 | // the ASTContext lays out the structure. | ||||
15459 | // | ||||
15460 | // It is important for implementing the correct semantics that this | ||||
15461 | // happen here (in ActOnTag). The #pragma pack stack is | ||||
15462 | // maintained as a result of parser callbacks which can occur at | ||||
15463 | // many points during the parsing of a struct declaration (because | ||||
15464 | // the #pragma tokens are effectively skipped over during the | ||||
15465 | // parsing of the struct). | ||||
15466 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | ||||
15467 | AddAlignmentAttributesForRecord(RD); | ||||
15468 | AddMsStructLayoutForRecord(RD); | ||||
15469 | } | ||||
15470 | } | ||||
15471 | |||||
15472 | if (ModulePrivateLoc.isValid()) { | ||||
15473 | if (isMemberSpecialization) | ||||
15474 | Diag(New->getLocation(), diag::err_module_private_specialization) | ||||
15475 | << 2 | ||||
15476 | << FixItHint::CreateRemoval(ModulePrivateLoc); | ||||
15477 | // __module_private__ does not apply to local classes. However, we only | ||||
15478 | // diagnose this as an error when the declaration specifiers are | ||||
15479 | // freestanding. Here, we just ignore the __module_private__. | ||||
15480 | else if (!SearchDC->isFunctionOrMethod()) | ||||
15481 | New->setModulePrivate(); | ||||
15482 | } | ||||
15483 | |||||
15484 | // If this is a specialization of a member class (of a class template), | ||||
15485 | // check the specialization. | ||||
15486 | if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) | ||||
15487 | Invalid = true; | ||||
15488 | |||||
15489 | // If we're declaring or defining a tag in function prototype scope in C, | ||||
15490 | // note that this type can only be used within the function and add it to | ||||
15491 | // the list of decls to inject into the function definition scope. | ||||
15492 | if ((Name || Kind == TTK_Enum) && | ||||
15493 | getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { | ||||
15494 | if (getLangOpts().CPlusPlus) { | ||||
15495 | // C++ [dcl.fct]p6: | ||||
15496 | // Types shall not be defined in return or parameter types. | ||||
15497 | if (TUK == TUK_Definition && !IsTypeSpecifier) { | ||||
15498 | Diag(Loc, diag::err_type_defined_in_param_type) | ||||
15499 | << Name; | ||||
15500 | Invalid = true; | ||||
15501 | } | ||||
15502 | } else if (!PrevDecl) { | ||||
15503 | Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); | ||||
15504 | } | ||||
15505 | } | ||||
15506 | |||||
15507 | if (Invalid) | ||||
15508 | New->setInvalidDecl(); | ||||
15509 | |||||
15510 | // Set the lexical context. If the tag has a C++ scope specifier, the | ||||
15511 | // lexical context will be different from the semantic context. | ||||
15512 | New->setLexicalDeclContext(CurContext); | ||||
15513 | |||||
15514 | // Mark this as a friend decl if applicable. | ||||
15515 | // In Microsoft mode, a friend declaration also acts as a forward | ||||
15516 | // declaration so we always pass true to setObjectOfFriendDecl to make | ||||
15517 | // the tag name visible. | ||||
15518 | if (TUK == TUK_Friend) | ||||
15519 | New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); | ||||
15520 | |||||
15521 | // Set the access specifier. | ||||
15522 | if (!Invalid && SearchDC->isRecord()) | ||||
15523 | SetMemberAccessSpecifier(New, PrevDecl, AS); | ||||
15524 | |||||
15525 | if (PrevDecl) | ||||
15526 | CheckRedeclarationModuleOwnership(New, PrevDecl); | ||||
15527 | |||||
15528 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) | ||||
15529 | New->startDefinition(); | ||||
15530 | |||||
15531 | ProcessDeclAttributeList(S, New, Attrs); | ||||
15532 | AddPragmaAttributes(S, New); | ||||
15533 | |||||
15534 | // If this has an identifier, add it to the scope stack. | ||||
15535 | if (TUK == TUK_Friend) { | ||||
15536 | // We might be replacing an existing declaration in the lookup tables; | ||||
15537 | // if so, borrow its access specifier. | ||||
15538 | if (PrevDecl) | ||||
15539 | New->setAccess(PrevDecl->getAccess()); | ||||
15540 | |||||
15541 | DeclContext *DC = New->getDeclContext()->getRedeclContext(); | ||||
15542 | DC->makeDeclVisibleInContext(New); | ||||
15543 | if (Name) // can be null along some error paths | ||||
15544 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) | ||||
15545 | PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); | ||||
15546 | } else if (Name) { | ||||
15547 | S = getNonFieldDeclScope(S); | ||||
15548 | PushOnScopeChains(New, S, true); | ||||
15549 | } else { | ||||
15550 | CurContext->addDecl(New); | ||||
15551 | } | ||||
15552 | |||||
15553 | // If this is the C FILE type, notify the AST context. | ||||
15554 | if (IdentifierInfo *II = New->getIdentifier()) | ||||
15555 | if (!New->isInvalidDecl() && | ||||
15556 | New->getDeclContext()->getRedeclContext()->isTranslationUnit() && | ||||
15557 | II->isStr("FILE")) | ||||
15558 | Context.setFILEDecl(New); | ||||
15559 | |||||
15560 | if (PrevDecl) | ||||
15561 | mergeDeclAttributes(New, PrevDecl); | ||||
15562 | |||||
15563 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) | ||||
15564 | inferGslOwnerPointerAttribute(CXXRD); | ||||
15565 | |||||
15566 | // If there's a #pragma GCC visibility in scope, set the visibility of this | ||||
15567 | // record. | ||||
15568 | AddPushedVisibilityAttribute(New); | ||||
15569 | |||||
15570 | if (isMemberSpecialization && !New->isInvalidDecl()) | ||||
15571 | CompleteMemberSpecialization(New, Previous); | ||||
15572 | |||||
15573 | OwnedDecl = true; | ||||
15574 | // In C++, don't return an invalid declaration. We can't recover well from | ||||
15575 | // the cases where we make the type anonymous. | ||||
15576 | if (Invalid && getLangOpts().CPlusPlus) { | ||||
15577 | if (New->isBeingDefined()) | ||||
15578 | if (auto RD = dyn_cast<RecordDecl>(New)) | ||||
15579 | RD->completeDefinition(); | ||||
15580 | return nullptr; | ||||
15581 | } else if (SkipBody && SkipBody->ShouldSkip) { | ||||
15582 | return SkipBody->Previous; | ||||
15583 | } else { | ||||
15584 | return New; | ||||
15585 | } | ||||
15586 | } | ||||
15587 | |||||
15588 | void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { | ||||
15589 | AdjustDeclIfTemplate(TagD); | ||||
15590 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||
15591 | |||||
15592 | // Enter the tag context. | ||||
15593 | PushDeclContext(S, Tag); | ||||
15594 | |||||
15595 | ActOnDocumentableDecl(TagD); | ||||
15596 | |||||
15597 | // If there's a #pragma GCC visibility in scope, set the visibility of this | ||||
15598 | // record. | ||||
15599 | AddPushedVisibilityAttribute(Tag); | ||||
15600 | } | ||||
15601 | |||||
15602 | bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, | ||||
15603 | SkipBodyInfo &SkipBody) { | ||||
15604 | if (!hasStructuralCompatLayout(Prev, SkipBody.New)) | ||||
15605 | return false; | ||||
15606 | |||||
15607 | // Make the previous decl visible. | ||||
15608 | makeMergedDefinitionVisible(SkipBody.Previous); | ||||
15609 | return true; | ||||
15610 | } | ||||
15611 | |||||
15612 | Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { | ||||
15613 | assert(isa<ObjCContainerDecl>(IDecl) &&((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 15614, __PRETTY_FUNCTION__)) | ||||
15614 | "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 15614, __PRETTY_FUNCTION__)); | ||||
15615 | DeclContext *OCD = cast<DeclContext>(IDecl); | ||||
15616 | assert(getContainingDC(OCD) == CurContext &&((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 15617, __PRETTY_FUNCTION__)) | ||||
15617 | "The next DeclContext should be lexically contained in the current one.")((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 15617, __PRETTY_FUNCTION__)); | ||||
15618 | CurContext = OCD; | ||||
15619 | return IDecl; | ||||
15620 | } | ||||
15621 | |||||
15622 | void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, | ||||
15623 | SourceLocation FinalLoc, | ||||
15624 | bool IsFinalSpelledSealed, | ||||
15625 | SourceLocation LBraceLoc) { | ||||
15626 | AdjustDeclIfTemplate(TagD); | ||||
15627 | CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); | ||||
15628 | |||||
15629 | FieldCollector->StartClass(); | ||||
15630 | |||||
15631 | if (!Record->getIdentifier()) | ||||
15632 | return; | ||||
15633 | |||||
15634 | if (FinalLoc.isValid()) | ||||
15635 | Record->addAttr(FinalAttr::Create( | ||||
15636 | Context, FinalLoc, AttributeCommonInfo::AS_Keyword, | ||||
15637 | static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); | ||||
15638 | |||||
15639 | // C++ [class]p2: | ||||
15640 | // [...] The class-name is also inserted into the scope of the | ||||
15641 | // class itself; this is known as the injected-class-name. For | ||||
15642 | // purposes of access checking, the injected-class-name is treated | ||||
15643 | // as if it were a public member name. | ||||
15644 | CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( | ||||
15645 | Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), | ||||
15646 | Record->getLocation(), Record->getIdentifier(), | ||||
15647 | /*PrevDecl=*/nullptr, | ||||
15648 | /*DelayTypeCreation=*/true); | ||||
15649 | Context.getTypeDeclType(InjectedClassName, Record); | ||||
15650 | InjectedClassName->setImplicit(); | ||||
15651 | InjectedClassName->setAccess(AS_public); | ||||
15652 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) | ||||
15653 | InjectedClassName->setDescribedClassTemplate(Template); | ||||
15654 | PushOnScopeChains(InjectedClassName, S); | ||||
15655 | assert(InjectedClassName->isInjectedClassName() &&((InjectedClassName->isInjectedClassName() && "Broken injected-class-name" ) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 15656, __PRETTY_FUNCTION__)) | ||||
15656 | "Broken injected-class-name")((InjectedClassName->isInjectedClassName() && "Broken injected-class-name" ) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 15656, __PRETTY_FUNCTION__)); | ||||
15657 | } | ||||
15658 | |||||
15659 | void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, | ||||
15660 | SourceRange BraceRange) { | ||||
15661 | AdjustDeclIfTemplate(TagD); | ||||
15662 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||
15663 | Tag->setBraceRange(BraceRange); | ||||
15664 | |||||
15665 | // Make sure we "complete" the definition even it is invalid. | ||||
15666 | if (Tag->isBeingDefined()) { | ||||
15667 | assert(Tag->isInvalidDecl() && "We should already have completed it")((Tag->isInvalidDecl() && "We should already have completed it" ) ? static_cast<void> (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 15667, __PRETTY_FUNCTION__)); | ||||
15668 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | ||||
15669 | RD->completeDefinition(); | ||||
15670 | } | ||||
15671 | |||||
15672 | if (isa<CXXRecordDecl>(Tag)) { | ||||
15673 | FieldCollector->FinishClass(); | ||||
15674 | } | ||||
15675 | |||||
15676 | // Exit this scope of this tag's definition. | ||||
15677 | PopDeclContext(); | ||||
15678 | |||||
15679 | if (getCurLexicalContext()->isObjCContainer() && | ||||
15680 | Tag->getDeclContext()->isFileContext()) | ||||
15681 | Tag->setTopLevelDeclInObjCContainer(); | ||||
15682 | |||||
15683 | // Notify the consumer that we've defined a tag. | ||||
15684 | if (!Tag->isInvalidDecl()) | ||||
15685 | Consumer.HandleTagDeclDefinition(Tag); | ||||
15686 | } | ||||
15687 | |||||
15688 | void Sema::ActOnObjCContainerFinishDefinition() { | ||||
15689 | // Exit this scope of this interface definition. | ||||
15690 | PopDeclContext(); | ||||
15691 | } | ||||
15692 | |||||
15693 | void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { | ||||
15694 | assert(DC == CurContext && "Mismatch of container contexts")((DC == CurContext && "Mismatch of container contexts" ) ? static_cast<void> (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 15694, __PRETTY_FUNCTION__)); | ||||
15695 | OriginalLexicalContext = DC; | ||||
15696 | ActOnObjCContainerFinishDefinition(); | ||||
15697 | } | ||||
15698 | |||||
15699 | void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { | ||||
15700 | ActOnObjCContainerStartDefinition(cast<Decl>(DC)); | ||||
15701 | OriginalLexicalContext = nullptr; | ||||
15702 | } | ||||
15703 | |||||
15704 | void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { | ||||
15705 | AdjustDeclIfTemplate(TagD); | ||||
15706 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||
15707 | Tag->setInvalidDecl(); | ||||
15708 | |||||
15709 | // Make sure we "complete" the definition even it is invalid. | ||||
15710 | if (Tag->isBeingDefined()) { | ||||
15711 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | ||||
15712 | RD->completeDefinition(); | ||||
15713 | } | ||||
15714 | |||||
15715 | // We're undoing ActOnTagStartDefinition here, not | ||||
15716 | // ActOnStartCXXMemberDeclarations, so we don't have to mess with | ||||
15717 | // the FieldCollector. | ||||
15718 | |||||
15719 | PopDeclContext(); | ||||
15720 | } | ||||
15721 | |||||
15722 | // Note that FieldName may be null for anonymous bitfields. | ||||
15723 | ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, | ||||
15724 | IdentifierInfo *FieldName, | ||||
15725 | QualType FieldTy, bool IsMsStruct, | ||||
15726 | Expr *BitWidth, bool *ZeroWidth) { | ||||
15727 | // Default to true; that shouldn't confuse checks for emptiness | ||||
15728 | if (ZeroWidth) | ||||
15729 | *ZeroWidth = true; | ||||
15730 | |||||
15731 | // C99 6.7.2.1p4 - verify the field type. | ||||
15732 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | ||||
15733 | if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { | ||||
15734 | // Handle incomplete types with specific error. | ||||
15735 | if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) | ||||
15736 | return ExprError(); | ||||
15737 | if (FieldName) | ||||
15738 | return Diag(FieldLoc, diag::err_not_integral_type_bitfield) | ||||
15739 | << FieldName << FieldTy << BitWidth->getSourceRange(); | ||||
15740 | return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) | ||||
15741 | << FieldTy << BitWidth->getSourceRange(); | ||||
15742 | } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), | ||||
15743 | UPPC_BitFieldWidth)) | ||||
15744 | return ExprError(); | ||||
15745 | |||||
15746 | // If the bit-width is type- or value-dependent, don't try to check | ||||
15747 | // it now. | ||||
15748 | if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) | ||||
15749 | return BitWidth; | ||||
15750 | |||||
15751 | llvm::APSInt Value; | ||||
15752 | ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); | ||||
15753 | if (ICE.isInvalid()) | ||||
15754 | return ICE; | ||||
15755 | BitWidth = ICE.get(); | ||||
15756 | |||||
15757 | if (Value != 0 && ZeroWidth) | ||||
15758 | *ZeroWidth = false; | ||||
15759 | |||||
15760 | // Zero-width bitfield is ok for anonymous field. | ||||
15761 | if (Value == 0 && FieldName) | ||||
15762 | return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; | ||||
15763 | |||||
15764 | if (Value.isSigned() && Value.isNegative()) { | ||||
15765 | if (FieldName) | ||||
15766 | return Diag(FieldLoc, diag::err_bitfield_has_negative_width) | ||||
15767 | << FieldName << Value.toString(10); | ||||
15768 | return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) | ||||
15769 | << Value.toString(10); | ||||
15770 | } | ||||
15771 | |||||
15772 | if (!FieldTy->isDependentType()) { | ||||
15773 | uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); | ||||
15774 | uint64_t TypeWidth = Context.getIntWidth(FieldTy); | ||||
15775 | bool BitfieldIsOverwide = Value.ugt(TypeWidth); | ||||
15776 | |||||
15777 | // Over-wide bitfields are an error in C or when using the MSVC bitfield | ||||
15778 | // ABI. | ||||
15779 | bool CStdConstraintViolation = | ||||
15780 | BitfieldIsOverwide && !getLangOpts().CPlusPlus; | ||||
15781 | bool MSBitfieldViolation = | ||||
15782 | Value.ugt(TypeStorageSize) && | ||||
15783 | (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); | ||||
15784 | if (CStdConstraintViolation || MSBitfieldViolation) { | ||||
15785 | unsigned DiagWidth = | ||||
15786 | CStdConstraintViolation ? TypeWidth : TypeStorageSize; | ||||
15787 | if (FieldName) | ||||
15788 | return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) | ||||
15789 | << FieldName << (unsigned)Value.getZExtValue() | ||||
15790 | << !CStdConstraintViolation << DiagWidth; | ||||
15791 | |||||
15792 | return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) | ||||
15793 | << (unsigned)Value.getZExtValue() << !CStdConstraintViolation | ||||
15794 | << DiagWidth; | ||||
15795 | } | ||||
15796 | |||||
15797 | // Warn on types where the user might conceivably expect to get all | ||||
15798 | // specified bits as value bits: that's all integral types other than | ||||
15799 | // 'bool'. | ||||
15800 | if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { | ||||
15801 | if (FieldName) | ||||
15802 | Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) | ||||
15803 | << FieldName << (unsigned)Value.getZExtValue() | ||||
15804 | << (unsigned)TypeWidth; | ||||
15805 | else | ||||
15806 | Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) | ||||
15807 | << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; | ||||
15808 | } | ||||
15809 | } | ||||
15810 | |||||
15811 | return BitWidth; | ||||
15812 | } | ||||
15813 | |||||
15814 | /// ActOnField - Each field of a C struct/union is passed into this in order | ||||
15815 | /// to create a FieldDecl object for it. | ||||
15816 | Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, | ||||
15817 | Declarator &D, Expr *BitfieldWidth) { | ||||
15818 | FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), | ||||
15819 | DeclStart, D, static_cast<Expr*>(BitfieldWidth), | ||||
15820 | /*InitStyle=*/ICIS_NoInit, AS_public); | ||||
15821 | return Res; | ||||
15822 | } | ||||
15823 | |||||
15824 | /// HandleField - Analyze a field of a C struct or a C++ data member. | ||||
15825 | /// | ||||
15826 | FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, | ||||
15827 | SourceLocation DeclStart, | ||||
15828 | Declarator &D, Expr *BitWidth, | ||||
15829 | InClassInitStyle InitStyle, | ||||
15830 | AccessSpecifier AS) { | ||||
15831 | if (D.isDecompositionDeclarator()) { | ||||
15832 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); | ||||
15833 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) | ||||
15834 | << Decomp.getSourceRange(); | ||||
15835 | return nullptr; | ||||
15836 | } | ||||
15837 | |||||
15838 | IdentifierInfo *II = D.getIdentifier(); | ||||
15839 | SourceLocation Loc = DeclStart; | ||||
15840 | if (II) Loc = D.getIdentifierLoc(); | ||||
15841 | |||||
15842 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||
15843 | QualType T = TInfo->getType(); | ||||
15844 | if (getLangOpts().CPlusPlus) { | ||||
15845 | CheckExtraCXXDefaultArguments(D); | ||||
15846 | |||||
15847 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||
15848 | UPPC_DataMemberType)) { | ||||
15849 | D.setInvalidType(); | ||||
15850 | T = Context.IntTy; | ||||
15851 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | ||||
15852 | } | ||||
15853 | } | ||||
15854 | |||||
15855 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||
15856 | |||||
15857 | if (D.getDeclSpec().isInlineSpecified()) | ||||
15858 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||
15859 | << getLangOpts().CPlusPlus17; | ||||
15860 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | ||||
15861 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
15862 | diag::err_invalid_thread) | ||||
15863 | << DeclSpec::getSpecifierName(TSCS); | ||||
15864 | |||||
15865 | // Check to see if this name was declared as a member previously | ||||
15866 | NamedDecl *PrevDecl = nullptr; | ||||
15867 | LookupResult Previous(*this, II, Loc, LookupMemberName, | ||||
15868 | ForVisibleRedeclaration); | ||||
15869 | LookupName(Previous, S); | ||||
15870 | switch (Previous.getResultKind()) { | ||||
15871 | case LookupResult::Found: | ||||
15872 | case LookupResult::FoundUnresolvedValue: | ||||
15873 | PrevDecl = Previous.getAsSingle<NamedDecl>(); | ||||
15874 | break; | ||||
15875 | |||||
15876 | case LookupResult::FoundOverloaded: | ||||
15877 | PrevDecl = Previous.getRepresentativeDecl(); | ||||
15878 | break; | ||||
15879 | |||||
15880 | case LookupResult::NotFound: | ||||
15881 | case LookupResult::NotFoundInCurrentInstantiation: | ||||
15882 | case LookupResult::Ambiguous: | ||||
15883 | break; | ||||
15884 | } | ||||
15885 | Previous.suppressDiagnostics(); | ||||
15886 | |||||
15887 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | ||||
15888 | // Maybe we will complain about the shadowed template parameter. | ||||
15889 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | ||||
15890 | // Just pretend that we didn't see the previous declaration. | ||||
15891 | PrevDecl = nullptr; | ||||
15892 | } | ||||
15893 | |||||
15894 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) | ||||
15895 | PrevDecl = nullptr; | ||||
15896 | |||||
15897 | bool Mutable | ||||
15898 | = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); | ||||
15899 | SourceLocation TSSL = D.getBeginLoc(); | ||||
15900 | FieldDecl *NewFD | ||||
15901 | = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, | ||||
15902 | TSSL, AS, PrevDecl, &D); | ||||
15903 | |||||
15904 | if (NewFD->isInvalidDecl()) | ||||
15905 | Record->setInvalidDecl(); | ||||
15906 | |||||
15907 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||
15908 | NewFD->setModulePrivate(); | ||||
15909 | |||||
15910 | if (NewFD->isInvalidDecl() && PrevDecl) { | ||||
15911 | // Don't introduce NewFD into scope; there's already something | ||||
15912 | // with the same name in the same scope. | ||||
15913 | } else if (II) { | ||||
15914 | PushOnScopeChains(NewFD, S); | ||||
15915 | } else | ||||
15916 | Record->addDecl(NewFD); | ||||
15917 | |||||
15918 | return NewFD; | ||||
15919 | } | ||||
15920 | |||||
15921 | /// Build a new FieldDecl and check its well-formedness. | ||||
15922 | /// | ||||
15923 | /// This routine builds a new FieldDecl given the fields name, type, | ||||
15924 | /// record, etc. \p PrevDecl should refer to any previous declaration | ||||
15925 | /// with the same name and in the same scope as the field to be | ||||
15926 | /// created. | ||||
15927 | /// | ||||
15928 | /// \returns a new FieldDecl. | ||||
15929 | /// | ||||
15930 | /// \todo The Declarator argument is a hack. It will be removed once | ||||
15931 | FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, | ||||
15932 | TypeSourceInfo *TInfo, | ||||
15933 | RecordDecl *Record, SourceLocation Loc, | ||||
15934 | bool Mutable, Expr *BitWidth, | ||||
15935 | InClassInitStyle InitStyle, | ||||
15936 | SourceLocation TSSL, | ||||
15937 | AccessSpecifier AS, NamedDecl *PrevDecl, | ||||
15938 | Declarator *D) { | ||||
15939 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||
15940 | bool InvalidDecl = false; | ||||
15941 | if (D) InvalidDecl = D->isInvalidType(); | ||||
15942 | |||||
15943 | // If we receive a broken type, recover by assuming 'int' and | ||||
15944 | // marking this declaration as invalid. | ||||
15945 | if (T.isNull()) { | ||||
15946 | InvalidDecl = true; | ||||
15947 | T = Context.IntTy; | ||||
15948 | } | ||||
15949 | |||||
15950 | QualType EltTy = Context.getBaseElementType(T); | ||||
15951 | if (!EltTy->isDependentType()) { | ||||
15952 | if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { | ||||
15953 | // Fields of incomplete type force their record to be invalid. | ||||
15954 | Record->setInvalidDecl(); | ||||
15955 | InvalidDecl = true; | ||||
15956 | } else { | ||||
15957 | NamedDecl *Def; | ||||
15958 | EltTy->isIncompleteType(&Def); | ||||
15959 | if (Def && Def->isInvalidDecl()) { | ||||
15960 | Record->setInvalidDecl(); | ||||
15961 | InvalidDecl = true; | ||||
15962 | } | ||||
15963 | } | ||||
15964 | } | ||||
15965 | |||||
15966 | // TR 18037 does not allow fields to be declared with address space | ||||
15967 | if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() || | ||||
15968 | T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { | ||||
15969 | Diag(Loc, diag::err_field_with_address_space); | ||||
15970 | Record->setInvalidDecl(); | ||||
15971 | InvalidDecl = true; | ||||
15972 | } | ||||
15973 | |||||
15974 | if (LangOpts.OpenCL) { | ||||
15975 | // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be | ||||
15976 | // used as structure or union field: image, sampler, event or block types. | ||||
15977 | if (T->isEventT() || T->isImageType() || T->isSamplerT() || | ||||
15978 | T->isBlockPointerType()) { | ||||
15979 | Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; | ||||
15980 | Record->setInvalidDecl(); | ||||
15981 | InvalidDecl = true; | ||||
15982 | } | ||||
15983 | // OpenCL v1.2 s6.9.c: bitfields are not supported. | ||||
15984 | if (BitWidth) { | ||||
15985 | Diag(Loc, diag::err_opencl_bitfields); | ||||
15986 | InvalidDecl = true; | ||||
15987 | } | ||||
15988 | } | ||||
15989 | |||||
15990 | // Anonymous bit-fields cannot be cv-qualified (CWG 2229). | ||||
15991 | if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && | ||||
15992 | T.hasQualifiers()) { | ||||
15993 | InvalidDecl = true; | ||||
15994 | Diag(Loc, diag::err_anon_bitfield_qualifiers); | ||||
15995 | } | ||||
15996 | |||||
15997 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | ||||
15998 | // than a variably modified type. | ||||
15999 | if (!InvalidDecl && T->isVariablyModifiedType()) { | ||||
16000 | bool SizeIsNegative; | ||||
16001 | llvm::APSInt Oversized; | ||||
16002 | |||||
16003 | TypeSourceInfo *FixedTInfo = | ||||
16004 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | ||||
16005 | SizeIsNegative, | ||||
16006 | Oversized); | ||||
16007 | if (FixedTInfo) { | ||||
16008 | Diag(Loc, diag::warn_illegal_constant_array_size); | ||||
16009 | TInfo = FixedTInfo; | ||||
16010 | T = FixedTInfo->getType(); | ||||
16011 | } else { | ||||
16012 | if (SizeIsNegative) | ||||
16013 | Diag(Loc, diag::err_typecheck_negative_array_size); | ||||
16014 | else if (Oversized.getBoolValue()) | ||||
16015 | Diag(Loc, diag::err_array_too_large) | ||||
16016 | << Oversized.toString(10); | ||||
16017 | else | ||||
16018 | Diag(Loc, diag::err_typecheck_field_variable_size); | ||||
16019 | InvalidDecl = true; | ||||
16020 | } | ||||
16021 | } | ||||
16022 | |||||
16023 | // Fields can not have abstract class types | ||||
16024 | if (!InvalidDecl && RequireNonAbstractType(Loc, T, | ||||
16025 | diag::err_abstract_type_in_decl, | ||||
16026 | AbstractFieldType)) | ||||
16027 | InvalidDecl = true; | ||||
16028 | |||||
16029 | bool ZeroWidth = false; | ||||
16030 | if (InvalidDecl) | ||||
16031 | BitWidth = nullptr; | ||||
16032 | // If this is declared as a bit-field, check the bit-field. | ||||
16033 | if (BitWidth) { | ||||
16034 | BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, | ||||
16035 | &ZeroWidth).get(); | ||||
16036 | if (!BitWidth) { | ||||
16037 | InvalidDecl = true; | ||||
16038 | BitWidth = nullptr; | ||||
16039 | ZeroWidth = false; | ||||
16040 | } | ||||
16041 | } | ||||
16042 | |||||
16043 | // Check that 'mutable' is consistent with the type of the declaration. | ||||
16044 | if (!InvalidDecl && Mutable) { | ||||
16045 | unsigned DiagID = 0; | ||||
16046 | if (T->isReferenceType()) | ||||
16047 | DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference | ||||
16048 | : diag::err_mutable_reference; | ||||
16049 | else if (T.isConstQualified()) | ||||
16050 | DiagID = diag::err_mutable_const; | ||||
16051 | |||||
16052 | if (DiagID) { | ||||
16053 | SourceLocation ErrLoc = Loc; | ||||
16054 | if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) | ||||
16055 | ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); | ||||
16056 | Diag(ErrLoc, DiagID); | ||||
16057 | if (DiagID != diag::ext_mutable_reference) { | ||||
16058 | Mutable = false; | ||||
16059 | InvalidDecl = true; | ||||
16060 | } | ||||
16061 | } | ||||
16062 | } | ||||
16063 | |||||
16064 | // C++11 [class.union]p8 (DR1460): | ||||
16065 | // At most one variant member of a union may have a | ||||
16066 | // brace-or-equal-initializer. | ||||
16067 | if (InitStyle != ICIS_NoInit) | ||||
16068 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); | ||||
16069 | |||||
16070 | FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, | ||||
16071 | BitWidth, Mutable, InitStyle); | ||||
16072 | if (InvalidDecl) | ||||
16073 | NewFD->setInvalidDecl(); | ||||
16074 | |||||
16075 | if (PrevDecl && !isa<TagDecl>(PrevDecl)) { | ||||
16076 | Diag(Loc, diag::err_duplicate_member) << II; | ||||
16077 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||
16078 | NewFD->setInvalidDecl(); | ||||
16079 | } | ||||
16080 | |||||
16081 | if (!InvalidDecl && getLangOpts().CPlusPlus) { | ||||
16082 | if (Record->isUnion()) { | ||||
16083 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | ||||
16084 | CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||
16085 | if (RDecl->getDefinition()) { | ||||
16086 | // C++ [class.union]p1: An object of a class with a non-trivial | ||||
16087 | // constructor, a non-trivial copy constructor, a non-trivial | ||||
16088 | // destructor, or a non-trivial copy assignment operator | ||||
16089 | // cannot be a member of a union, nor can an array of such | ||||
16090 | // objects. | ||||
16091 | if (CheckNontrivialField(NewFD)) | ||||
16092 | NewFD->setInvalidDecl(); | ||||
16093 | } | ||||
16094 | } | ||||
16095 | |||||
16096 | // C++ [class.union]p1: If a union contains a member of reference type, | ||||
16097 | // the program is ill-formed, except when compiling with MSVC extensions | ||||
16098 | // enabled. | ||||
16099 | if (EltTy->isReferenceType()) { | ||||
16100 | Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? | ||||
16101 | diag::ext_union_member_of_reference_type : | ||||
16102 | diag::err_union_member_of_reference_type) | ||||
16103 | << NewFD->getDeclName() << EltTy; | ||||
16104 | if (!getLangOpts().MicrosoftExt) | ||||
16105 | NewFD->setInvalidDecl(); | ||||
16106 | } | ||||
16107 | } | ||||
16108 | } | ||||
16109 | |||||
16110 | // FIXME: We need to pass in the attributes given an AST | ||||
16111 | // representation, not a parser representation. | ||||
16112 | if (D) { | ||||
16113 | // FIXME: The current scope is almost... but not entirely... correct here. | ||||
16114 | ProcessDeclAttributes(getCurScope(), NewFD, *D); | ||||
16115 | |||||
16116 | if (NewFD->hasAttrs()) | ||||
16117 | CheckAlignasUnderalignment(NewFD); | ||||
16118 | } | ||||
16119 | |||||
16120 | // In auto-retain/release, infer strong retension for fields of | ||||
16121 | // retainable type. | ||||
16122 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) | ||||
16123 | NewFD->setInvalidDecl(); | ||||
16124 | |||||
16125 | if (T.isObjCGCWeak()) | ||||
16126 | Diag(Loc, diag::warn_attribute_weak_on_field); | ||||
16127 | |||||
16128 | NewFD->setAccess(AS); | ||||
16129 | return NewFD; | ||||
16130 | } | ||||
16131 | |||||
16132 | bool Sema::CheckNontrivialField(FieldDecl *FD) { | ||||
16133 | assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16133, __PRETTY_FUNCTION__)); | ||||
16134 | assert(getLangOpts().CPlusPlus && "valid check only for C++")((getLangOpts().CPlusPlus && "valid check only for C++" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16134, __PRETTY_FUNCTION__)); | ||||
16135 | |||||
16136 | if (FD->isInvalidDecl() || FD->getType()->isDependentType()) | ||||
16137 | return false; | ||||
16138 | |||||
16139 | QualType EltTy = Context.getBaseElementType(FD->getType()); | ||||
16140 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | ||||
16141 | CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||
16142 | if (RDecl->getDefinition()) { | ||||
16143 | // We check for copy constructors before constructors | ||||
16144 | // because otherwise we'll never get complaints about | ||||
16145 | // copy constructors. | ||||
16146 | |||||
16147 | CXXSpecialMember member = CXXInvalid; | ||||
16148 | // We're required to check for any non-trivial constructors. Since the | ||||
16149 | // implicit default constructor is suppressed if there are any | ||||
16150 | // user-declared constructors, we just need to check that there is a | ||||
16151 | // trivial default constructor and a trivial copy constructor. (We don't | ||||
16152 | // worry about move constructors here, since this is a C++98 check.) | ||||
16153 | if (RDecl->hasNonTrivialCopyConstructor()) | ||||
16154 | member = CXXCopyConstructor; | ||||
16155 | else if (!RDecl->hasTrivialDefaultConstructor()) | ||||
16156 | member = CXXDefaultConstructor; | ||||
16157 | else if (RDecl->hasNonTrivialCopyAssignment()) | ||||
16158 | member = CXXCopyAssignment; | ||||
16159 | else if (RDecl->hasNonTrivialDestructor()) | ||||
16160 | member = CXXDestructor; | ||||
16161 | |||||
16162 | if (member != CXXInvalid) { | ||||
16163 | if (!getLangOpts().CPlusPlus11 && | ||||
16164 | getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { | ||||
16165 | // Objective-C++ ARC: it is an error to have a non-trivial field of | ||||
16166 | // a union. However, system headers in Objective-C programs | ||||
16167 | // occasionally have Objective-C lifetime objects within unions, | ||||
16168 | // and rather than cause the program to fail, we make those | ||||
16169 | // members unavailable. | ||||
16170 | SourceLocation Loc = FD->getLocation(); | ||||
16171 | if (getSourceManager().isInSystemHeader(Loc)) { | ||||
16172 | if (!FD->hasAttr<UnavailableAttr>()) | ||||
16173 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", | ||||
16174 | UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); | ||||
16175 | return false; | ||||
16176 | } | ||||
16177 | } | ||||
16178 | |||||
16179 | Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? | ||||
16180 | diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : | ||||
16181 | diag::err_illegal_union_or_anon_struct_member) | ||||
16182 | << FD->getParent()->isUnion() << FD->getDeclName() << member; | ||||
16183 | DiagnoseNontrivial(RDecl, member); | ||||
16184 | return !getLangOpts().CPlusPlus11; | ||||
16185 | } | ||||
16186 | } | ||||
16187 | } | ||||
16188 | |||||
16189 | return false; | ||||
16190 | } | ||||
16191 | |||||
16192 | /// TranslateIvarVisibility - Translate visibility from a token ID to an | ||||
16193 | /// AST enum value. | ||||
16194 | static ObjCIvarDecl::AccessControl | ||||
16195 | TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { | ||||
16196 | switch (ivarVisibility) { | ||||
16197 | default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16197); | ||||
16198 | case tok::objc_private: return ObjCIvarDecl::Private; | ||||
16199 | case tok::objc_public: return ObjCIvarDecl::Public; | ||||
16200 | case tok::objc_protected: return ObjCIvarDecl::Protected; | ||||
16201 | case tok::objc_package: return ObjCIvarDecl::Package; | ||||
16202 | } | ||||
16203 | } | ||||
16204 | |||||
16205 | /// ActOnIvar - Each ivar field of an objective-c class is passed into this | ||||
16206 | /// in order to create an IvarDecl object for it. | ||||
16207 | Decl *Sema::ActOnIvar(Scope *S, | ||||
16208 | SourceLocation DeclStart, | ||||
16209 | Declarator &D, Expr *BitfieldWidth, | ||||
16210 | tok::ObjCKeywordKind Visibility) { | ||||
16211 | |||||
16212 | IdentifierInfo *II = D.getIdentifier(); | ||||
16213 | Expr *BitWidth = (Expr*)BitfieldWidth; | ||||
16214 | SourceLocation Loc = DeclStart; | ||||
16215 | if (II) Loc = D.getIdentifierLoc(); | ||||
16216 | |||||
16217 | // FIXME: Unnamed fields can be handled in various different ways, for | ||||
16218 | // example, unnamed unions inject all members into the struct namespace! | ||||
16219 | |||||
16220 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||
16221 | QualType T = TInfo->getType(); | ||||
16222 | |||||
16223 | if (BitWidth) { | ||||
16224 | // 6.7.2.1p3, 6.7.2.1p4 | ||||
16225 | BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); | ||||
16226 | if (!BitWidth) | ||||
16227 | D.setInvalidType(); | ||||
16228 | } else { | ||||
16229 | // Not a bitfield. | ||||
16230 | |||||
16231 | // validate II. | ||||
16232 | |||||
16233 | } | ||||
16234 | if (T->isReferenceType()) { | ||||
16235 | Diag(Loc, diag::err_ivar_reference_type); | ||||
16236 | D.setInvalidType(); | ||||
16237 | } | ||||
16238 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | ||||
16239 | // than a variably modified type. | ||||
16240 | else if (T->isVariablyModifiedType()) { | ||||
16241 | Diag(Loc, diag::err_typecheck_ivar_variable_size); | ||||
16242 | D.setInvalidType(); | ||||
16243 | } | ||||
16244 | |||||
16245 | // Get the visibility (access control) for this ivar. | ||||
16246 | ObjCIvarDecl::AccessControl ac = | ||||
16247 | Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) | ||||
16248 | : ObjCIvarDecl::None; | ||||
16249 | // Must set ivar's DeclContext to its enclosing interface. | ||||
16250 | ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); | ||||
16251 | if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) | ||||
16252 | return nullptr; | ||||
16253 | ObjCContainerDecl *EnclosingContext; | ||||
16254 | if (ObjCImplementationDecl *IMPDecl = | ||||
16255 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | ||||
16256 | if (LangOpts.ObjCRuntime.isFragile()) { | ||||
16257 | // Case of ivar declared in an implementation. Context is that of its class. | ||||
16258 | EnclosingContext = IMPDecl->getClassInterface(); | ||||
16259 | assert(EnclosingContext && "Implementation has no class interface!")((EnclosingContext && "Implementation has no class interface!" ) ? static_cast<void> (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16259, __PRETTY_FUNCTION__)); | ||||
16260 | } | ||||
16261 | else | ||||
16262 | EnclosingContext = EnclosingDecl; | ||||
16263 | } else { | ||||
16264 | if (ObjCCategoryDecl *CDecl = | ||||
16265 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | ||||
16266 | if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { | ||||
16267 | Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); | ||||
16268 | return nullptr; | ||||
16269 | } | ||||
16270 | } | ||||
16271 | EnclosingContext = EnclosingDecl; | ||||
16272 | } | ||||
16273 | |||||
16274 | // Construct the decl. | ||||
16275 | ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, | ||||
16276 | DeclStart, Loc, II, T, | ||||
16277 | TInfo, ac, (Expr *)BitfieldWidth); | ||||
16278 | |||||
16279 | if (II) { | ||||
16280 | NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, | ||||
16281 | ForVisibleRedeclaration); | ||||
16282 | if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) | ||||
16283 | && !isa<TagDecl>(PrevDecl)) { | ||||
16284 | Diag(Loc, diag::err_duplicate_member) << II; | ||||
16285 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||
16286 | NewID->setInvalidDecl(); | ||||
16287 | } | ||||
16288 | } | ||||
16289 | |||||
16290 | // Process attributes attached to the ivar. | ||||
16291 | ProcessDeclAttributes(S, NewID, D); | ||||
16292 | |||||
16293 | if (D.isInvalidType()) | ||||
16294 | NewID->setInvalidDecl(); | ||||
16295 | |||||
16296 | // In ARC, infer 'retaining' for ivars of retainable type. | ||||
16297 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) | ||||
16298 | NewID->setInvalidDecl(); | ||||
16299 | |||||
16300 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||
16301 | NewID->setModulePrivate(); | ||||
16302 | |||||
16303 | if (II) { | ||||
16304 | // FIXME: When interfaces are DeclContexts, we'll need to add | ||||
16305 | // these to the interface. | ||||
16306 | S->AddDecl(NewID); | ||||
16307 | IdResolver.AddDecl(NewID); | ||||
16308 | } | ||||
16309 | |||||
16310 | if (LangOpts.ObjCRuntime.isNonFragile() && | ||||
16311 | !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) | ||||
16312 | Diag(Loc, diag::warn_ivars_in_interface); | ||||
16313 | |||||
16314 | return NewID; | ||||
16315 | } | ||||
16316 | |||||
16317 | /// ActOnLastBitfield - This routine handles synthesized bitfields rules for | ||||
16318 | /// class and class extensions. For every class \@interface and class | ||||
16319 | /// extension \@interface, if the last ivar is a bitfield of any type, | ||||
16320 | /// then add an implicit `char :0` ivar to the end of that interface. | ||||
16321 | void Sema::ActOnLastBitfield(SourceLocation DeclLoc, | ||||
16322 | SmallVectorImpl<Decl *> &AllIvarDecls) { | ||||
16323 | if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) | ||||
16324 | return; | ||||
16325 | |||||
16326 | Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; | ||||
16327 | ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); | ||||
16328 | |||||
16329 | if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) | ||||
16330 | return; | ||||
16331 | ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); | ||||
16332 | if (!ID) { | ||||
16333 | if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { | ||||
16334 | if (!CD->IsClassExtension()) | ||||
16335 | return; | ||||
16336 | } | ||||
16337 | // No need to add this to end of @implementation. | ||||
16338 | else | ||||
16339 | return; | ||||
16340 | } | ||||
16341 | // All conditions are met. Add a new bitfield to the tail end of ivars. | ||||
16342 | llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); | ||||
16343 | Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); | ||||
16344 | |||||
16345 | Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), | ||||
16346 | DeclLoc, DeclLoc, nullptr, | ||||
16347 | Context.CharTy, | ||||
16348 | Context.getTrivialTypeSourceInfo(Context.CharTy, | ||||
16349 | DeclLoc), | ||||
16350 | ObjCIvarDecl::Private, BW, | ||||
16351 | true); | ||||
16352 | AllIvarDecls.push_back(Ivar); | ||||
16353 | } | ||||
16354 | |||||
16355 | void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, | ||||
16356 | ArrayRef<Decl *> Fields, SourceLocation LBrac, | ||||
16357 | SourceLocation RBrac, | ||||
16358 | const ParsedAttributesView &Attrs) { | ||||
16359 | assert(EnclosingDecl && "missing record or interface decl")((EnclosingDecl && "missing record or interface decl" ) ? static_cast<void> (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16359, __PRETTY_FUNCTION__)); | ||||
16360 | |||||
16361 | // If this is an Objective-C @implementation or category and we have | ||||
16362 | // new fields here we should reset the layout of the interface since | ||||
16363 | // it will now change. | ||||
16364 | if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { | ||||
16365 | ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); | ||||
16366 | switch (DC->getKind()) { | ||||
16367 | default: break; | ||||
16368 | case Decl::ObjCCategory: | ||||
16369 | Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); | ||||
16370 | break; | ||||
16371 | case Decl::ObjCImplementation: | ||||
16372 | Context. | ||||
16373 | ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); | ||||
16374 | break; | ||||
16375 | } | ||||
16376 | } | ||||
16377 | |||||
16378 | RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); | ||||
16379 | CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); | ||||
16380 | |||||
16381 | // Start counting up the number of named members; make sure to include | ||||
16382 | // members of anonymous structs and unions in the total. | ||||
16383 | unsigned NumNamedMembers = 0; | ||||
16384 | if (Record) { | ||||
16385 | for (const auto *I : Record->decls()) { | ||||
16386 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | ||||
16387 | if (IFD->getDeclName()) | ||||
16388 | ++NumNamedMembers; | ||||
16389 | } | ||||
16390 | } | ||||
16391 | |||||
16392 | // Verify that all the fields are okay. | ||||
16393 | SmallVector<FieldDecl*, 32> RecFields; | ||||
16394 | |||||
16395 | for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); | ||||
16396 | i != end; ++i) { | ||||
16397 | FieldDecl *FD = cast<FieldDecl>(*i); | ||||
16398 | |||||
16399 | // Get the type for the field. | ||||
16400 | const Type *FDTy = FD->getType().getTypePtr(); | ||||
16401 | |||||
16402 | if (!FD->isAnonymousStructOrUnion()) { | ||||
16403 | // Remember all fields written by the user. | ||||
16404 | RecFields.push_back(FD); | ||||
16405 | } | ||||
16406 | |||||
16407 | // If the field is already invalid for some reason, don't emit more | ||||
16408 | // diagnostics about it. | ||||
16409 | if (FD->isInvalidDecl()) { | ||||
16410 | EnclosingDecl->setInvalidDecl(); | ||||
16411 | continue; | ||||
16412 | } | ||||
16413 | |||||
16414 | // C99 6.7.2.1p2: | ||||
16415 | // A structure or union shall not contain a member with | ||||
16416 | // incomplete or function type (hence, a structure shall not | ||||
16417 | // contain an instance of itself, but may contain a pointer to | ||||
16418 | // an instance of itself), except that the last member of a | ||||
16419 | // structure with more than one named member may have incomplete | ||||
16420 | // array type; such a structure (and any union containing, | ||||
16421 | // possibly recursively, a member that is such a structure) | ||||
16422 | // shall not be a member of a structure or an element of an | ||||
16423 | // array. | ||||
16424 | bool IsLastField = (i + 1 == Fields.end()); | ||||
16425 | if (FDTy->isFunctionType()) { | ||||
16426 | // Field declared as a function. | ||||
16427 | Diag(FD->getLocation(), diag::err_field_declared_as_function) | ||||
16428 | << FD->getDeclName(); | ||||
16429 | FD->setInvalidDecl(); | ||||
16430 | EnclosingDecl->setInvalidDecl(); | ||||
16431 | continue; | ||||
16432 | } else if (FDTy->isIncompleteArrayType() && | ||||
16433 | (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { | ||||
16434 | if (Record) { | ||||
16435 | // Flexible array member. | ||||
16436 | // Microsoft and g++ is more permissive regarding flexible array. | ||||
16437 | // It will accept flexible array in union and also | ||||
16438 | // as the sole element of a struct/class. | ||||
16439 | unsigned DiagID = 0; | ||||
16440 | if (!Record->isUnion() && !IsLastField) { | ||||
16441 | Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) | ||||
16442 | << FD->getDeclName() << FD->getType() << Record->getTagKind(); | ||||
16443 | Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); | ||||
16444 | FD->setInvalidDecl(); | ||||
16445 | EnclosingDecl->setInvalidDecl(); | ||||
16446 | continue; | ||||
16447 | } else if (Record->isUnion()) | ||||
16448 | DiagID = getLangOpts().MicrosoftExt | ||||
16449 | ? diag::ext_flexible_array_union_ms | ||||
16450 | : getLangOpts().CPlusPlus | ||||
16451 | ? diag::ext_flexible_array_union_gnu | ||||
16452 | : diag::err_flexible_array_union; | ||||
16453 | else if (NumNamedMembers < 1) | ||||
16454 | DiagID = getLangOpts().MicrosoftExt | ||||
16455 | ? diag::ext_flexible_array_empty_aggregate_ms | ||||
16456 | : getLangOpts().CPlusPlus | ||||
16457 | ? diag::ext_flexible_array_empty_aggregate_gnu | ||||
16458 | : diag::err_flexible_array_empty_aggregate; | ||||
16459 | |||||
16460 | if (DiagID) | ||||
16461 | Diag(FD->getLocation(), DiagID) << FD->getDeclName() | ||||
16462 | << Record->getTagKind(); | ||||
16463 | // While the layout of types that contain virtual bases is not specified | ||||
16464 | // by the C++ standard, both the Itanium and Microsoft C++ ABIs place | ||||
16465 | // virtual bases after the derived members. This would make a flexible | ||||
16466 | // array member declared at the end of an object not adjacent to the end | ||||
16467 | // of the type. | ||||
16468 | if (CXXRecord && CXXRecord->getNumVBases() != 0) | ||||
16469 | Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) | ||||
16470 | << FD->getDeclName() << Record->getTagKind(); | ||||
16471 | if (!getLangOpts().C99) | ||||
16472 | Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) | ||||
16473 | << FD->getDeclName() << Record->getTagKind(); | ||||
16474 | |||||
16475 | // If the element type has a non-trivial destructor, we would not | ||||
16476 | // implicitly destroy the elements, so disallow it for now. | ||||
16477 | // | ||||
16478 | // FIXME: GCC allows this. We should probably either implicitly delete | ||||
16479 | // the destructor of the containing class, or just allow this. | ||||
16480 | QualType BaseElem = Context.getBaseElementType(FD->getType()); | ||||
16481 | if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { | ||||
16482 | Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) | ||||
16483 | << FD->getDeclName() << FD->getType(); | ||||
16484 | FD->setInvalidDecl(); | ||||
16485 | EnclosingDecl->setInvalidDecl(); | ||||
16486 | continue; | ||||
16487 | } | ||||
16488 | // Okay, we have a legal flexible array member at the end of the struct. | ||||
16489 | Record->setHasFlexibleArrayMember(true); | ||||
16490 | } else { | ||||
16491 | // In ObjCContainerDecl ivars with incomplete array type are accepted, | ||||
16492 | // unless they are followed by another ivar. That check is done | ||||
16493 | // elsewhere, after synthesized ivars are known. | ||||
16494 | } | ||||
16495 | } else if (!FDTy->isDependentType() && | ||||
16496 | RequireCompleteType(FD->getLocation(), FD->getType(), | ||||
16497 | diag::err_field_incomplete)) { | ||||
16498 | // Incomplete type | ||||
16499 | FD->setInvalidDecl(); | ||||
16500 | EnclosingDecl->setInvalidDecl(); | ||||
16501 | continue; | ||||
16502 | } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { | ||||
16503 | if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { | ||||
16504 | // A type which contains a flexible array member is considered to be a | ||||
16505 | // flexible array member. | ||||
16506 | Record->setHasFlexibleArrayMember(true); | ||||
16507 | if (!Record->isUnion()) { | ||||
16508 | // If this is a struct/class and this is not the last element, reject | ||||
16509 | // it. Note that GCC supports variable sized arrays in the middle of | ||||
16510 | // structures. | ||||
16511 | if (!IsLastField) | ||||
16512 | Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) | ||||
16513 | << FD->getDeclName() << FD->getType(); | ||||
16514 | else { | ||||
16515 | // We support flexible arrays at the end of structs in | ||||
16516 | // other structs as an extension. | ||||
16517 | Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) | ||||
16518 | << FD->getDeclName(); | ||||
16519 | } | ||||
16520 | } | ||||
16521 | } | ||||
16522 | if (isa<ObjCContainerDecl>(EnclosingDecl) && | ||||
16523 | RequireNonAbstractType(FD->getLocation(), FD->getType(), | ||||
16524 | diag::err_abstract_type_in_decl, | ||||
16525 | AbstractIvarType)) { | ||||
16526 | // Ivars can not have abstract class types | ||||
16527 | FD->setInvalidDecl(); | ||||
16528 | } | ||||
16529 | if (Record && FDTTy->getDecl()->hasObjectMember()) | ||||
16530 | Record->setHasObjectMember(true); | ||||
16531 | if (Record && FDTTy->getDecl()->hasVolatileMember()) | ||||
16532 | Record->setHasVolatileMember(true); | ||||
16533 | } else if (FDTy->isObjCObjectType()) { | ||||
16534 | /// A field cannot be an Objective-c object | ||||
16535 | Diag(FD->getLocation(), diag::err_statically_allocated_object) | ||||
16536 | << FixItHint::CreateInsertion(FD->getLocation(), "*"); | ||||
16537 | QualType T = Context.getObjCObjectPointerType(FD->getType()); | ||||
16538 | FD->setType(T); | ||||
16539 | } else if (Record && Record->isUnion() && | ||||
16540 | FD->getType().hasNonTrivialObjCLifetime() && | ||||
16541 | getSourceManager().isInSystemHeader(FD->getLocation()) && | ||||
16542 | !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && | ||||
16543 | (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || | ||||
16544 | !Context.hasDirectOwnershipQualifier(FD->getType()))) { | ||||
16545 | // For backward compatibility, fields of C unions declared in system | ||||
16546 | // headers that have non-trivial ObjC ownership qualifications are marked | ||||
16547 | // as unavailable unless the qualifier is explicit and __strong. This can | ||||
16548 | // break ABI compatibility between programs compiled with ARC and MRR, but | ||||
16549 | // is a better option than rejecting programs using those unions under | ||||
16550 | // ARC. | ||||
16551 | FD->addAttr(UnavailableAttr::CreateImplicit( | ||||
16552 | Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, | ||||
16553 | FD->getLocation())); | ||||
16554 | } else if (getLangOpts().ObjC && | ||||
16555 | getLangOpts().getGC() != LangOptions::NonGC && | ||||
16556 | Record && !Record->hasObjectMember()) { | ||||
16557 | if (FD->getType()->isObjCObjectPointerType() || | ||||
16558 | FD->getType().isObjCGCStrong()) | ||||
16559 | Record->setHasObjectMember(true); | ||||
16560 | else if (Context.getAsArrayType(FD->getType())) { | ||||
16561 | QualType BaseType = Context.getBaseElementType(FD->getType()); | ||||
16562 | if (BaseType->isRecordType() && | ||||
16563 | BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) | ||||
16564 | Record->setHasObjectMember(true); | ||||
16565 | else if (BaseType->isObjCObjectPointerType() || | ||||
16566 | BaseType.isObjCGCStrong()) | ||||
16567 | Record->setHasObjectMember(true); | ||||
16568 | } | ||||
16569 | } | ||||
16570 | |||||
16571 | if (Record && !getLangOpts().CPlusPlus && | ||||
16572 | !shouldIgnoreForRecordTriviality(FD)) { | ||||
16573 | QualType FT = FD->getType(); | ||||
16574 | if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { | ||||
16575 | Record->setNonTrivialToPrimitiveDefaultInitialize(true); | ||||
16576 | if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||
16577 | Record->isUnion()) | ||||
16578 | Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); | ||||
16579 | } | ||||
16580 | QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); | ||||
16581 | if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { | ||||
16582 | Record->setNonTrivialToPrimitiveCopy(true); | ||||
16583 | if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) | ||||
16584 | Record->setHasNonTrivialToPrimitiveCopyCUnion(true); | ||||
16585 | } | ||||
16586 | if (FT.isDestructedType()) { | ||||
16587 | Record->setNonTrivialToPrimitiveDestroy(true); | ||||
16588 | Record->setParamDestroyedInCallee(true); | ||||
16589 | if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) | ||||
16590 | Record->setHasNonTrivialToPrimitiveDestructCUnion(true); | ||||
16591 | } | ||||
16592 | |||||
16593 | if (const auto *RT = FT->getAs<RecordType>()) { | ||||
16594 | if (RT->getDecl()->getArgPassingRestrictions() == | ||||
16595 | RecordDecl::APK_CanNeverPassInRegs) | ||||
16596 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | ||||
16597 | } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||
16598 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | ||||
16599 | } | ||||
16600 | |||||
16601 | if (Record && FD->getType().isVolatileQualified()) | ||||
16602 | Record->setHasVolatileMember(true); | ||||
16603 | // Keep track of the number of named members. | ||||
16604 | if (FD->getIdentifier()) | ||||
16605 | ++NumNamedMembers; | ||||
16606 | } | ||||
16607 | |||||
16608 | // Okay, we successfully defined 'Record'. | ||||
16609 | if (Record) { | ||||
16610 | bool Completed = false; | ||||
16611 | if (CXXRecord) { | ||||
16612 | if (!CXXRecord->isInvalidDecl()) { | ||||
16613 | // Set access bits correctly on the directly-declared conversions. | ||||
16614 | for (CXXRecordDecl::conversion_iterator | ||||
16615 | I = CXXRecord->conversion_begin(), | ||||
16616 | E = CXXRecord->conversion_end(); I != E; ++I) | ||||
16617 | I.setAccess((*I)->getAccess()); | ||||
16618 | } | ||||
16619 | |||||
16620 | if (!CXXRecord->isDependentType()) { | ||||
16621 | // Add any implicitly-declared members to this class. | ||||
16622 | AddImplicitlyDeclaredMembersToClass(CXXRecord); | ||||
16623 | |||||
16624 | if (!CXXRecord->isInvalidDecl()) { | ||||
16625 | // If we have virtual base classes, we may end up finding multiple | ||||
16626 | // final overriders for a given virtual function. Check for this | ||||
16627 | // problem now. | ||||
16628 | if (CXXRecord->getNumVBases()) { | ||||
16629 | CXXFinalOverriderMap FinalOverriders; | ||||
16630 | CXXRecord->getFinalOverriders(FinalOverriders); | ||||
16631 | |||||
16632 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | ||||
16633 | MEnd = FinalOverriders.end(); | ||||
16634 | M != MEnd; ++M) { | ||||
16635 | for (OverridingMethods::iterator SO = M->second.begin(), | ||||
16636 | SOEnd = M->second.end(); | ||||
16637 | SO != SOEnd; ++SO) { | ||||
16638 | assert(SO->second.size() > 0 &&((SO->second.size() > 0 && "Virtual function without overriding functions?" ) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16639, __PRETTY_FUNCTION__)) | ||||
16639 | "Virtual function without overriding functions?")((SO->second.size() > 0 && "Virtual function without overriding functions?" ) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16639, __PRETTY_FUNCTION__)); | ||||
16640 | if (SO->second.size() == 1) | ||||
16641 | continue; | ||||
16642 | |||||
16643 | // C++ [class.virtual]p2: | ||||
16644 | // In a derived class, if a virtual member function of a base | ||||
16645 | // class subobject has more than one final overrider the | ||||
16646 | // program is ill-formed. | ||||
16647 | Diag(Record->getLocation(), diag::err_multiple_final_overriders) | ||||
16648 | << (const NamedDecl *)M->first << Record; | ||||
16649 | Diag(M->first->getLocation(), | ||||
16650 | diag::note_overridden_virtual_function); | ||||
16651 | for (OverridingMethods::overriding_iterator | ||||
16652 | OM = SO->second.begin(), | ||||
16653 | OMEnd = SO->second.end(); | ||||
16654 | OM != OMEnd; ++OM) | ||||
16655 | Diag(OM->Method->getLocation(), diag::note_final_overrider) | ||||
16656 | << (const NamedDecl *)M->first << OM->Method->getParent(); | ||||
16657 | |||||
16658 | Record->setInvalidDecl(); | ||||
16659 | } | ||||
16660 | } | ||||
16661 | CXXRecord->completeDefinition(&FinalOverriders); | ||||
16662 | Completed = true; | ||||
16663 | } | ||||
16664 | } | ||||
16665 | } | ||||
16666 | } | ||||
16667 | |||||
16668 | if (!Completed) | ||||
16669 | Record->completeDefinition(); | ||||
16670 | |||||
16671 | // Handle attributes before checking the layout. | ||||
16672 | ProcessDeclAttributeList(S, Record, Attrs); | ||||
16673 | |||||
16674 | // We may have deferred checking for a deleted destructor. Check now. | ||||
16675 | if (CXXRecord) { | ||||
16676 | auto *Dtor = CXXRecord->getDestructor(); | ||||
16677 | if (Dtor && Dtor->isImplicit() && | ||||
16678 | ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { | ||||
16679 | CXXRecord->setImplicitDestructorIsDeleted(); | ||||
16680 | SetDeclDeleted(Dtor, CXXRecord->getLocation()); | ||||
16681 | } | ||||
16682 | } | ||||
16683 | |||||
16684 | if (Record->hasAttrs()) { | ||||
16685 | CheckAlignasUnderalignment(Record); | ||||
16686 | |||||
16687 | if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) | ||||
16688 | checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), | ||||
16689 | IA->getRange(), IA->getBestCase(), | ||||
16690 | IA->getSemanticSpelling()); | ||||
16691 | } | ||||
16692 | |||||
16693 | // Check if the structure/union declaration is a type that can have zero | ||||
16694 | // size in C. For C this is a language extension, for C++ it may cause | ||||
16695 | // compatibility problems. | ||||
16696 | bool CheckForZeroSize; | ||||
16697 | if (!getLangOpts().CPlusPlus) { | ||||
16698 | CheckForZeroSize = true; | ||||
16699 | } else { | ||||
16700 | // For C++ filter out types that cannot be referenced in C code. | ||||
16701 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); | ||||
16702 | CheckForZeroSize = | ||||
16703 | CXXRecord->getLexicalDeclContext()->isExternCContext() && | ||||
16704 | !CXXRecord->isDependentType() && | ||||
16705 | CXXRecord->isCLike(); | ||||
16706 | } | ||||
16707 | if (CheckForZeroSize) { | ||||
16708 | bool ZeroSize = true; | ||||
16709 | bool IsEmpty = true; | ||||
16710 | unsigned NonBitFields = 0; | ||||
16711 | for (RecordDecl::field_iterator I = Record->field_begin(), | ||||
16712 | E = Record->field_end(); | ||||
16713 | (NonBitFields == 0 || ZeroSize) && I != E; ++I) { | ||||
16714 | IsEmpty = false; | ||||
16715 | if (I->isUnnamedBitfield()) { | ||||
16716 | if (!I->isZeroLengthBitField(Context)) | ||||
16717 | ZeroSize = false; | ||||
16718 | } else { | ||||
16719 | ++NonBitFields; | ||||
16720 | QualType FieldType = I->getType(); | ||||
16721 | if (FieldType->isIncompleteType() || | ||||
16722 | !Context.getTypeSizeInChars(FieldType).isZero()) | ||||
16723 | ZeroSize = false; | ||||
16724 | } | ||||
16725 | } | ||||
16726 | |||||
16727 | // Empty structs are an extension in C (C99 6.7.2.1p7). They are | ||||
16728 | // allowed in C++, but warn if its declaration is inside | ||||
16729 | // extern "C" block. | ||||
16730 | if (ZeroSize) { | ||||
16731 | Diag(RecLoc, getLangOpts().CPlusPlus ? | ||||
16732 | diag::warn_zero_size_struct_union_in_extern_c : | ||||
16733 | diag::warn_zero_size_struct_union_compat) | ||||
16734 | << IsEmpty << Record->isUnion() << (NonBitFields > 1); | ||||
16735 | } | ||||
16736 | |||||
16737 | // Structs without named members are extension in C (C99 6.7.2.1p7), | ||||
16738 | // but are accepted by GCC. | ||||
16739 | if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { | ||||
16740 | Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : | ||||
16741 | diag::ext_no_named_members_in_struct_union) | ||||
16742 | << Record->isUnion(); | ||||
16743 | } | ||||
16744 | } | ||||
16745 | } else { | ||||
16746 | ObjCIvarDecl **ClsFields = | ||||
16747 | reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); | ||||
16748 | if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { | ||||
16749 | ID->setEndOfDefinitionLoc(RBrac); | ||||
16750 | // Add ivar's to class's DeclContext. | ||||
16751 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | ||||
16752 | ClsFields[i]->setLexicalDeclContext(ID); | ||||
16753 | ID->addDecl(ClsFields[i]); | ||||
16754 | } | ||||
16755 | // Must enforce the rule that ivars in the base classes may not be | ||||
16756 | // duplicates. | ||||
16757 | if (ID->getSuperClass()) | ||||
16758 | DiagnoseDuplicateIvars(ID, ID->getSuperClass()); | ||||
16759 | } else if (ObjCImplementationDecl *IMPDecl = | ||||
16760 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | ||||
16761 | assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl" ) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16761, __PRETTY_FUNCTION__)); | ||||
16762 | for (unsigned I = 0, N = RecFields.size(); I != N; ++I) | ||||
16763 | // Ivar declared in @implementation never belongs to the implementation. | ||||
16764 | // Only it is in implementation's lexical context. | ||||
16765 | ClsFields[I]->setLexicalDeclContext(IMPDecl); | ||||
16766 | CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); | ||||
16767 | IMPDecl->setIvarLBraceLoc(LBrac); | ||||
16768 | IMPDecl->setIvarRBraceLoc(RBrac); | ||||
16769 | } else if (ObjCCategoryDecl *CDecl = | ||||
16770 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | ||||
16771 | // case of ivars in class extension; all other cases have been | ||||
16772 | // reported as errors elsewhere. | ||||
16773 | // FIXME. Class extension does not have a LocEnd field. | ||||
16774 | // CDecl->setLocEnd(RBrac); | ||||
16775 | // Add ivar's to class extension's DeclContext. | ||||
16776 | // Diagnose redeclaration of private ivars. | ||||
16777 | ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); | ||||
16778 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | ||||
16779 | if (IDecl) { | ||||
16780 | if (const ObjCIvarDecl *ClsIvar = | ||||
16781 | IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { | ||||
16782 | Diag(ClsFields[i]->getLocation(), | ||||
16783 | diag::err_duplicate_ivar_declaration); | ||||
16784 | Diag(ClsIvar->getLocation(), diag::note_previous_definition); | ||||
16785 | continue; | ||||
16786 | } | ||||
16787 | for (const auto *Ext : IDecl->known_extensions()) { | ||||
16788 | if (const ObjCIvarDecl *ClsExtIvar | ||||
16789 | = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { | ||||
16790 | Diag(ClsFields[i]->getLocation(), | ||||
16791 | diag::err_duplicate_ivar_declaration); | ||||
16792 | Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); | ||||
16793 | continue; | ||||
16794 | } | ||||
16795 | } | ||||
16796 | } | ||||
16797 | ClsFields[i]->setLexicalDeclContext(CDecl); | ||||
16798 | CDecl->addDecl(ClsFields[i]); | ||||
16799 | } | ||||
16800 | CDecl->setIvarLBraceLoc(LBrac); | ||||
16801 | CDecl->setIvarRBraceLoc(RBrac); | ||||
16802 | } | ||||
16803 | } | ||||
16804 | } | ||||
16805 | |||||
16806 | /// Determine whether the given integral value is representable within | ||||
16807 | /// the given type T. | ||||
16808 | static bool isRepresentableIntegerValue(ASTContext &Context, | ||||
16809 | llvm::APSInt &Value, | ||||
16810 | QualType T) { | ||||
16811 | assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16812, __PRETTY_FUNCTION__)) | ||||
16812 | "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16812, __PRETTY_FUNCTION__)); | ||||
16813 | unsigned BitWidth = Context.getIntWidth(T); | ||||
16814 | |||||
16815 | if (Value.isUnsigned() || Value.isNonNegative()) { | ||||
16816 | if (T->isSignedIntegerOrEnumerationType()) | ||||
16817 | --BitWidth; | ||||
16818 | return Value.getActiveBits() <= BitWidth; | ||||
16819 | } | ||||
16820 | return Value.getMinSignedBits() <= BitWidth; | ||||
16821 | } | ||||
16822 | |||||
16823 | // Given an integral type, return the next larger integral type | ||||
16824 | // (or a NULL type of no such type exists). | ||||
16825 | static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { | ||||
16826 | // FIXME: Int128/UInt128 support, which also needs to be introduced into | ||||
16827 | // enum checking below. | ||||
16828 | assert((T->isIntegralType(Context) ||(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16829, __PRETTY_FUNCTION__)) | ||||
16829 | T->isEnumeralType()) && "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 16829, __PRETTY_FUNCTION__)); | ||||
16830 | const unsigned NumTypes = 4; | ||||
16831 | QualType SignedIntegralTypes[NumTypes] = { | ||||
16832 | Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy | ||||
16833 | }; | ||||
16834 | QualType UnsignedIntegralTypes[NumTypes] = { | ||||
16835 | Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, | ||||
16836 | Context.UnsignedLongLongTy | ||||
16837 | }; | ||||
16838 | |||||
16839 | unsigned BitWidth = Context.getTypeSize(T); | ||||
16840 | QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes | ||||
16841 | : UnsignedIntegralTypes; | ||||
16842 | for (unsigned I = 0; I != NumTypes; ++I) | ||||
16843 | if (Context.getTypeSize(Types[I]) > BitWidth) | ||||
16844 | return Types[I]; | ||||
16845 | |||||
16846 | return QualType(); | ||||
16847 | } | ||||
16848 | |||||
16849 | EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, | ||||
16850 | EnumConstantDecl *LastEnumConst, | ||||
16851 | SourceLocation IdLoc, | ||||
16852 | IdentifierInfo *Id, | ||||
16853 | Expr *Val) { | ||||
16854 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | ||||
16855 | llvm::APSInt EnumVal(IntWidth); | ||||
16856 | QualType EltTy; | ||||
16857 | |||||
16858 | if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) | ||||
16859 | Val = nullptr; | ||||
16860 | |||||
16861 | if (Val) | ||||
16862 | Val = DefaultLvalueConversion(Val).get(); | ||||
16863 | |||||
16864 | if (Val) { | ||||
16865 | if (Enum->isDependentType() || Val->isTypeDependent()) | ||||
16866 | EltTy = Context.DependentTy; | ||||
16867 | else { | ||||
16868 | if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { | ||||
16869 | // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the | ||||
16870 | // constant-expression in the enumerator-definition shall be a converted | ||||
16871 | // constant expression of the underlying type. | ||||
16872 | EltTy = Enum->getIntegerType(); | ||||
16873 | ExprResult Converted = | ||||
16874 | CheckConvertedConstantExpression(Val, EltTy, EnumVal, | ||||
16875 | CCEK_Enumerator); | ||||
16876 | if (Converted.isInvalid()) | ||||
16877 | Val = nullptr; | ||||
16878 | else | ||||
16879 | Val = Converted.get(); | ||||
16880 | } else if (!Val->isValueDependent() && | ||||
16881 | !(Val = VerifyIntegerConstantExpression(Val, | ||||
16882 | &EnumVal).get())) { | ||||
16883 | // C99 6.7.2.2p2: Make sure we have an integer constant expression. | ||||
16884 | } else { | ||||
16885 | if (Enum->isComplete()) { | ||||
16886 | EltTy = Enum->getIntegerType(); | ||||
16887 | |||||
16888 | // In Obj-C and Microsoft mode, require the enumeration value to be | ||||
16889 | // representable in the underlying type of the enumeration. In C++11, | ||||
16890 | // we perform a non-narrowing conversion as part of converted constant | ||||
16891 | // expression checking. | ||||
16892 | if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | ||||
16893 | if (Context.getTargetInfo() | ||||
16894 | .getTriple() | ||||
16895 | .isWindowsMSVCEnvironment()) { | ||||
16896 | Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; | ||||
16897 | } else { | ||||
16898 | Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; | ||||
16899 | } | ||||
16900 | } | ||||
16901 | |||||
16902 | // Cast to the underlying type. | ||||
16903 | Val = ImpCastExprToType(Val, EltTy, | ||||
16904 | EltTy->isBooleanType() ? CK_IntegralToBoolean | ||||
16905 | : CK_IntegralCast) | ||||
16906 | .get(); | ||||
16907 | } else if (getLangOpts().CPlusPlus) { | ||||
16908 | // C++11 [dcl.enum]p5: | ||||
16909 | // If the underlying type is not fixed, the type of each enumerator | ||||
16910 | // is the type of its initializing value: | ||||
16911 | // - If an initializer is specified for an enumerator, the | ||||
16912 | // initializing value has the same type as the expression. | ||||
16913 | EltTy = Val->getType(); | ||||
16914 | } else { | ||||
16915 | // C99 6.7.2.2p2: | ||||
16916 | // The expression that defines the value of an enumeration constant | ||||
16917 | // shall be an integer constant expression that has a value | ||||
16918 | // representable as an int. | ||||
16919 | |||||
16920 | // Complain if the value is not representable in an int. | ||||
16921 | if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) | ||||
16922 | Diag(IdLoc, diag::ext_enum_value_not_int) | ||||
16923 | << EnumVal.toString(10) << Val->getSourceRange() | ||||
16924 | << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); | ||||
16925 | else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { | ||||
16926 | // Force the type of the expression to 'int'. | ||||
16927 | Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); | ||||
16928 | } | ||||
16929 | EltTy = Val->getType(); | ||||
16930 | } | ||||
16931 | } | ||||
16932 | } | ||||
16933 | } | ||||
16934 | |||||
16935 | if (!Val) { | ||||
16936 | if (Enum->isDependentType()) | ||||
16937 | EltTy = Context.DependentTy; | ||||
16938 | else if (!LastEnumConst) { | ||||
16939 | // C++0x [dcl.enum]p5: | ||||
16940 | // If the underlying type is not fixed, the type of each enumerator | ||||
16941 | // is the type of its initializing value: | ||||
16942 | // - If no initializer is specified for the first enumerator, the | ||||
16943 | // initializing value has an unspecified integral type. | ||||
16944 | // | ||||
16945 | // GCC uses 'int' for its unspecified integral type, as does | ||||
16946 | // C99 6.7.2.2p3. | ||||
16947 | if (Enum->isFixed()) { | ||||
16948 | EltTy = Enum->getIntegerType(); | ||||
16949 | } | ||||
16950 | else { | ||||
16951 | EltTy = Context.IntTy; | ||||
16952 | } | ||||
16953 | } else { | ||||
16954 | // Assign the last value + 1. | ||||
16955 | EnumVal = LastEnumConst->getInitVal(); | ||||
16956 | ++EnumVal; | ||||
16957 | EltTy = LastEnumConst->getType(); | ||||
16958 | |||||
16959 | // Check for overflow on increment. | ||||
16960 | if (EnumVal < LastEnumConst->getInitVal()) { | ||||
16961 | // C++0x [dcl.enum]p5: | ||||
16962 | // If the underlying type is not fixed, the type of each enumerator | ||||
16963 | // is the type of its initializing value: | ||||
16964 | // | ||||
16965 | // - Otherwise the type of the initializing value is the same as | ||||
16966 | // the type of the initializing value of the preceding enumerator | ||||
16967 | // unless the incremented value is not representable in that type, | ||||
16968 | // in which case the type is an unspecified integral type | ||||
16969 | // sufficient to contain the incremented value. If no such type | ||||
16970 | // exists, the program is ill-formed. | ||||
16971 | QualType T = getNextLargerIntegralType(Context, EltTy); | ||||
16972 | if (T.isNull() || Enum->isFixed()) { | ||||
16973 | // There is no integral type larger enough to represent this | ||||
16974 | // value. Complain, then allow the value to wrap around. | ||||
16975 | EnumVal = LastEnumConst->getInitVal(); | ||||
16976 | EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); | ||||
16977 | ++EnumVal; | ||||
16978 | if (Enum->isFixed()) | ||||
16979 | // When the underlying type is fixed, this is ill-formed. | ||||
16980 | Diag(IdLoc, diag::err_enumerator_wrapped) | ||||
16981 | << EnumVal.toString(10) | ||||
16982 | << EltTy; | ||||
16983 | else | ||||
16984 | Diag(IdLoc, diag::ext_enumerator_increment_too_large) | ||||
16985 | << EnumVal.toString(10); | ||||
16986 | } else { | ||||
16987 | EltTy = T; | ||||
16988 | } | ||||
16989 | |||||
16990 | // Retrieve the last enumerator's value, extent that type to the | ||||
16991 | // type that is supposed to be large enough to represent the incremented | ||||
16992 | // value, then increment. | ||||
16993 | EnumVal = LastEnumConst->getInitVal(); | ||||
16994 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | ||||
16995 | EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); | ||||
16996 | ++EnumVal; | ||||
16997 | |||||
16998 | // If we're not in C++, diagnose the overflow of enumerator values, | ||||
16999 | // which in C99 means that the enumerator value is not representable in | ||||
17000 | // an int (C99 6.7.2.2p2). However, we support GCC's extension that | ||||
17001 | // permits enumerator values that are representable in some larger | ||||
17002 | // integral type. | ||||
17003 | if (!getLangOpts().CPlusPlus && !T.isNull()) | ||||
17004 | Diag(IdLoc, diag::warn_enum_value_overflow); | ||||
17005 | } else if (!getLangOpts().CPlusPlus && | ||||
17006 | !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | ||||
17007 | // Enforce C99 6.7.2.2p2 even when we compute the next value. | ||||
17008 | Diag(IdLoc, diag::ext_enum_value_not_int) | ||||
17009 | << EnumVal.toString(10) << 1; | ||||
17010 | } | ||||
17011 | } | ||||
17012 | } | ||||
17013 | |||||
17014 | if (!EltTy->isDependentType()) { | ||||
17015 | // Make the enumerator value match the signedness and size of the | ||||
17016 | // enumerator's type. | ||||
17017 | EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); | ||||
17018 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | ||||
17019 | } | ||||
17020 | |||||
17021 | return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, | ||||
17022 | Val, EnumVal); | ||||
17023 | } | ||||
17024 | |||||
17025 | Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, | ||||
17026 | SourceLocation IILoc) { | ||||
17027 | if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || | ||||
17028 | !getLangOpts().CPlusPlus) | ||||
17029 | return SkipBodyInfo(); | ||||
17030 | |||||
17031 | // We have an anonymous enum definition. Look up the first enumerator to | ||||
17032 | // determine if we should merge the definition with an existing one and | ||||
17033 | // skip the body. | ||||
17034 | NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, | ||||
17035 | forRedeclarationInCurContext()); | ||||
17036 | auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); | ||||
17037 | if (!PrevECD) | ||||
17038 | return SkipBodyInfo(); | ||||
17039 | |||||
17040 | EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); | ||||
17041 | NamedDecl *Hidden; | ||||
17042 | if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { | ||||
17043 | SkipBodyInfo Skip; | ||||
17044 | Skip.Previous = Hidden; | ||||
17045 | return Skip; | ||||
17046 | } | ||||
17047 | |||||
17048 | return SkipBodyInfo(); | ||||
17049 | } | ||||
17050 | |||||
17051 | Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, | ||||
17052 | SourceLocation IdLoc, IdentifierInfo *Id, | ||||
17053 | const ParsedAttributesView &Attrs, | ||||
17054 | SourceLocation EqualLoc, Expr *Val) { | ||||
17055 | EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); | ||||
17056 | EnumConstantDecl *LastEnumConst = | ||||
17057 | cast_or_null<EnumConstantDecl>(lastEnumConst); | ||||
17058 | |||||
17059 | // The scope passed in may not be a decl scope. Zip up the scope tree until | ||||
17060 | // we find one that is. | ||||
17061 | S = getNonFieldDeclScope(S); | ||||
17062 | |||||
17063 | // Verify that there isn't already something declared with this name in this | ||||
17064 | // scope. | ||||
17065 | LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); | ||||
17066 | LookupName(R, S); | ||||
17067 | NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); | ||||
17068 | |||||
17069 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | ||||
17070 | // Maybe we will complain about the shadowed template parameter. | ||||
17071 | DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); | ||||
17072 | // Just pretend that we didn't see the previous declaration. | ||||
17073 | PrevDecl = nullptr; | ||||
17074 | } | ||||
17075 | |||||
17076 | // C++ [class.mem]p15: | ||||
17077 | // If T is the name of a class, then each of the following shall have a name | ||||
17078 | // different from T: | ||||
17079 | // - every enumerator of every member of class T that is an unscoped | ||||
17080 | // enumerated type | ||||
17081 | if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) | ||||
17082 | DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), | ||||
17083 | DeclarationNameInfo(Id, IdLoc)); | ||||
17084 | |||||
17085 | EnumConstantDecl *New = | ||||
17086 | CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); | ||||
17087 | if (!New) | ||||
17088 | return nullptr; | ||||
17089 | |||||
17090 | if (PrevDecl) { | ||||
17091 | if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { | ||||
17092 | // Check for other kinds of shadowing not already handled. | ||||
17093 | CheckShadow(New, PrevDecl, R); | ||||
17094 | } | ||||
17095 | |||||
17096 | // When in C++, we may get a TagDecl with the same name; in this case the | ||||
17097 | // enum constant will 'hide' the tag. | ||||
17098 | assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!") ? static_cast<void> (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 17099, __PRETTY_FUNCTION__)) | ||||
17099 | "Received TagDecl when not in C++!")(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!") ? static_cast<void> (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 17099, __PRETTY_FUNCTION__)); | ||||
17100 | if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { | ||||
17101 | if (isa<EnumConstantDecl>(PrevDecl)) | ||||
17102 | Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; | ||||
17103 | else | ||||
17104 | Diag(IdLoc, diag::err_redefinition) << Id; | ||||
17105 | notePreviousDefinition(PrevDecl, IdLoc); | ||||
17106 | return nullptr; | ||||
17107 | } | ||||
17108 | } | ||||
17109 | |||||
17110 | // Process attributes. | ||||
17111 | ProcessDeclAttributeList(S, New, Attrs); | ||||
17112 | AddPragmaAttributes(S, New); | ||||
17113 | |||||
17114 | // Register this decl in the current scope stack. | ||||
17115 | New->setAccess(TheEnumDecl->getAccess()); | ||||
17116 | PushOnScopeChains(New, S); | ||||
17117 | |||||
17118 | ActOnDocumentableDecl(New); | ||||
17119 | |||||
17120 | return New; | ||||
17121 | } | ||||
17122 | |||||
17123 | // Returns true when the enum initial expression does not trigger the | ||||
17124 | // duplicate enum warning. A few common cases are exempted as follows: | ||||
17125 | // Element2 = Element1 | ||||
17126 | // Element2 = Element1 + 1 | ||||
17127 | // Element2 = Element1 - 1 | ||||
17128 | // Where Element2 and Element1 are from the same enum. | ||||
17129 | static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { | ||||
17130 | Expr *InitExpr = ECD->getInitExpr(); | ||||
17131 | if (!InitExpr) | ||||
17132 | return true; | ||||
17133 | InitExpr = InitExpr->IgnoreImpCasts(); | ||||
17134 | |||||
17135 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { | ||||
17136 | if (!BO->isAdditiveOp()) | ||||
17137 | return true; | ||||
17138 | IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); | ||||
17139 | if (!IL) | ||||
17140 | return true; | ||||
17141 | if (IL->getValue() != 1) | ||||
17142 | return true; | ||||
17143 | |||||
17144 | InitExpr = BO->getLHS(); | ||||
17145 | } | ||||
17146 | |||||
17147 | // This checks if the elements are from the same enum. | ||||
17148 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); | ||||
17149 | if (!DRE) | ||||
17150 | return true; | ||||
17151 | |||||
17152 | EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); | ||||
17153 | if (!EnumConstant) | ||||
17154 | return true; | ||||
17155 | |||||
17156 | if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != | ||||
17157 | Enum) | ||||
17158 | return true; | ||||
17159 | |||||
17160 | return false; | ||||
17161 | } | ||||
17162 | |||||
17163 | // Emits a warning when an element is implicitly set a value that | ||||
17164 | // a previous element has already been set to. | ||||
17165 | static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, | ||||
17166 | EnumDecl *Enum, QualType EnumType) { | ||||
17167 | // Avoid anonymous enums | ||||
17168 | if (!Enum->getIdentifier()) | ||||
17169 | return; | ||||
17170 | |||||
17171 | // Only check for small enums. | ||||
17172 | if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) | ||||
17173 | return; | ||||
17174 | |||||
17175 | if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) | ||||
17176 | return; | ||||
17177 | |||||
17178 | typedef SmallVector<EnumConstantDecl *, 3> ECDVector; | ||||
17179 | typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; | ||||
17180 | |||||
17181 | typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; | ||||
17182 | typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; | ||||
17183 | |||||
17184 | // Use int64_t as a key to avoid needing special handling for DenseMap keys. | ||||
17185 | auto EnumConstantToKey = [](const EnumConstantDecl *D) { | ||||
17186 | llvm::APSInt Val = D->getInitVal(); | ||||
17187 | return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); | ||||
17188 | }; | ||||
17189 | |||||
17190 | DuplicatesVector DupVector; | ||||
17191 | ValueToVectorMap EnumMap; | ||||
17192 | |||||
17193 | // Populate the EnumMap with all values represented by enum constants without | ||||
17194 | // an initializer. | ||||
17195 | for (auto *Element : Elements) { | ||||
17196 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); | ||||
17197 | |||||
17198 | // Null EnumConstantDecl means a previous diagnostic has been emitted for | ||||
17199 | // this constant. Skip this enum since it may be ill-formed. | ||||
17200 | if (!ECD) { | ||||
17201 | return; | ||||
17202 | } | ||||
17203 | |||||
17204 | // Constants with initalizers are handled in the next loop. | ||||
17205 | if (ECD->getInitExpr()) | ||||
17206 | continue; | ||||
17207 | |||||
17208 | // Duplicate values are handled in the next loop. | ||||
17209 | EnumMap.insert({EnumConstantToKey(ECD), ECD}); | ||||
17210 | } | ||||
17211 | |||||
17212 | if (EnumMap.size() == 0) | ||||
17213 | return; | ||||
17214 | |||||
17215 | // Create vectors for any values that has duplicates. | ||||
17216 | for (auto *Element : Elements) { | ||||
17217 | // The last loop returned if any constant was null. | ||||
17218 | EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); | ||||
17219 | if (!ValidDuplicateEnum(ECD, Enum)) | ||||
17220 | continue; | ||||
17221 | |||||
17222 | auto Iter = EnumMap.find(EnumConstantToKey(ECD)); | ||||
17223 | if (Iter == EnumMap.end()) | ||||
17224 | continue; | ||||
17225 | |||||
17226 | DeclOrVector& Entry = Iter->second; | ||||
17227 | if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { | ||||
17228 | // Ensure constants are different. | ||||
17229 | if (D == ECD) | ||||
17230 | continue; | ||||
17231 | |||||
17232 | // Create new vector and push values onto it. | ||||
17233 | auto Vec = std::make_unique<ECDVector>(); | ||||
17234 | Vec->push_back(D); | ||||
17235 | Vec->push_back(ECD); | ||||
17236 | |||||
17237 | // Update entry to point to the duplicates vector. | ||||
17238 | Entry = Vec.get(); | ||||
17239 | |||||
17240 | // Store the vector somewhere we can consult later for quick emission of | ||||
17241 | // diagnostics. | ||||
17242 | DupVector.emplace_back(std::move(Vec)); | ||||
17243 | continue; | ||||
17244 | } | ||||
17245 | |||||
17246 | ECDVector *Vec = Entry.get<ECDVector*>(); | ||||
17247 | // Make sure constants are not added more than once. | ||||
17248 | if (*Vec->begin() == ECD) | ||||
17249 | continue; | ||||
17250 | |||||
17251 | Vec->push_back(ECD); | ||||
17252 | } | ||||
17253 | |||||
17254 | // Emit diagnostics. | ||||
17255 | for (const auto &Vec : DupVector) { | ||||
17256 | assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")((Vec->size() > 1 && "ECDVector should have at least 2 elements." ) ? static_cast<void> (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 17256, __PRETTY_FUNCTION__)); | ||||
17257 | |||||
17258 | // Emit warning for one enum constant. | ||||
17259 | auto *FirstECD = Vec->front(); | ||||
17260 | S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) | ||||
17261 | << FirstECD << FirstECD->getInitVal().toString(10) | ||||
17262 | << FirstECD->getSourceRange(); | ||||
17263 | |||||
17264 | // Emit one note for each of the remaining enum constants with | ||||
17265 | // the same value. | ||||
17266 | for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) | ||||
17267 | S.Diag(ECD->getLocation(), diag::note_duplicate_element) | ||||
17268 | << ECD << ECD->getInitVal().toString(10) | ||||
17269 | << ECD->getSourceRange(); | ||||
17270 | } | ||||
17271 | } | ||||
17272 | |||||
17273 | bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, | ||||
17274 | bool AllowMask) const { | ||||
17275 | assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")((ED->isClosedFlag() && "looking for value in non-flag or open enum" ) ? static_cast<void> (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 17275, __PRETTY_FUNCTION__)); | ||||
17276 | assert(ED->isCompleteDefinition() && "expected enum definition")((ED->isCompleteDefinition() && "expected enum definition" ) ? static_cast<void> (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 17276, __PRETTY_FUNCTION__)); | ||||
17277 | |||||
17278 | auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); | ||||
17279 | llvm::APInt &FlagBits = R.first->second; | ||||
17280 | |||||
17281 | if (R.second) { | ||||
17282 | for (auto *E : ED->enumerators()) { | ||||
17283 | const auto &EVal = E->getInitVal(); | ||||
17284 | // Only single-bit enumerators introduce new flag values. | ||||
17285 | if (EVal.isPowerOf2()) | ||||
17286 | FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; | ||||
17287 | } | ||||
17288 | } | ||||
17289 | |||||
17290 | // A value is in a flag enum if either its bits are a subset of the enum's | ||||
17291 | // flag bits (the first condition) or we are allowing masks and the same is | ||||
17292 | // true of its complement (the second condition). When masks are allowed, we | ||||
17293 | // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. | ||||
17294 | // | ||||
17295 | // While it's true that any value could be used as a mask, the assumption is | ||||
17296 | // that a mask will have all of the insignificant bits set. Anything else is | ||||
17297 | // likely a logic error. | ||||
17298 | llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); | ||||
17299 | return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); | ||||
17300 | } | ||||
17301 | |||||
17302 | void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, | ||||
17303 | Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, | ||||
17304 | const ParsedAttributesView &Attrs) { | ||||
17305 | EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); | ||||
17306 | QualType EnumType = Context.getTypeDeclType(Enum); | ||||
17307 | |||||
17308 | ProcessDeclAttributeList(S, Enum, Attrs); | ||||
17309 | |||||
17310 | if (Enum->isDependentType()) { | ||||
17311 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | ||||
17312 | EnumConstantDecl *ECD = | ||||
17313 | cast_or_null<EnumConstantDecl>(Elements[i]); | ||||
17314 | if (!ECD) continue; | ||||
17315 | |||||
17316 | ECD->setType(EnumType); | ||||
17317 | } | ||||
17318 | |||||
17319 | Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); | ||||
17320 | return; | ||||
17321 | } | ||||
17322 | |||||
17323 | // TODO: If the result value doesn't fit in an int, it must be a long or long | ||||
17324 | // long value. ISO C does not support this, but GCC does as an extension, | ||||
17325 | // emit a warning. | ||||
17326 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | ||||
17327 | unsigned CharWidth = Context.getTargetInfo().getCharWidth(); | ||||
17328 | unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); | ||||
17329 | |||||
17330 | // Verify that all the values are okay, compute the size of the values, and | ||||
17331 | // reverse the list. | ||||
17332 | unsigned NumNegativeBits = 0; | ||||
17333 | unsigned NumPositiveBits = 0; | ||||
17334 | |||||
17335 | // Keep track of whether all elements have type int. | ||||
17336 | bool AllElementsInt = true; | ||||
17337 | |||||
17338 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | ||||
17339 | EnumConstantDecl *ECD = | ||||
17340 | cast_or_null<EnumConstantDecl>(Elements[i]); | ||||
17341 | if (!ECD) continue; // Already issued a diagnostic. | ||||
17342 | |||||
17343 | const llvm::APSInt &InitVal = ECD->getInitVal(); | ||||
17344 | |||||
17345 | // Keep track of the size of positive and negative values. | ||||
17346 | if (InitVal.isUnsigned() || InitVal.isNonNegative()) | ||||
17347 | NumPositiveBits = std::max(NumPositiveBits, | ||||
17348 | (unsigned)InitVal.getActiveBits()); | ||||
17349 | else | ||||
17350 | NumNegativeBits = std::max(NumNegativeBits, | ||||
17351 | (unsigned)InitVal.getMinSignedBits()); | ||||
17352 | |||||
17353 | // Keep track of whether every enum element has type int (very common). | ||||
17354 | if (AllElementsInt) | ||||
17355 | AllElementsInt = ECD->getType() == Context.IntTy; | ||||
17356 | } | ||||
17357 | |||||
17358 | // Figure out the type that should be used for this enum. | ||||
17359 | QualType BestType; | ||||
17360 | unsigned BestWidth; | ||||
17361 | |||||
17362 | // C++0x N3000 [conv.prom]p3: | ||||
17363 | // An rvalue of an unscoped enumeration type whose underlying | ||||
17364 | // type is not fixed can be converted to an rvalue of the first | ||||
17365 | // of the following types that can represent all the values of | ||||
17366 | // the enumeration: int, unsigned int, long int, unsigned long | ||||
17367 | // int, long long int, or unsigned long long int. | ||||
17368 | // C99 6.4.4.3p2: | ||||
17369 | // An identifier declared as an enumeration constant has type int. | ||||
17370 | // The C99 rule is modified by a gcc extension | ||||
17371 | QualType BestPromotionType; | ||||
17372 | |||||
17373 | bool Packed = Enum->hasAttr<PackedAttr>(); | ||||
17374 | // -fshort-enums is the equivalent to specifying the packed attribute on all | ||||
17375 | // enum definitions. | ||||
17376 | if (LangOpts.ShortEnums) | ||||
17377 | Packed = true; | ||||
17378 | |||||
17379 | // If the enum already has a type because it is fixed or dictated by the | ||||
17380 | // target, promote that type instead of analyzing the enumerators. | ||||
17381 | if (Enum->isComplete()) { | ||||
17382 | BestType = Enum->getIntegerType(); | ||||
17383 | if (BestType->isPromotableIntegerType()) | ||||
17384 | BestPromotionType = Context.getPromotedIntegerType(BestType); | ||||
17385 | else | ||||
17386 | BestPromotionType = BestType; | ||||
17387 | |||||
17388 | BestWidth = Context.getIntWidth(BestType); | ||||
17389 | } | ||||
17390 | else if (NumNegativeBits) { | ||||
17391 | // If there is a negative value, figure out the smallest integer type (of | ||||
17392 | // int/long/longlong) that fits. | ||||
17393 | // If it's packed, check also if it fits a char or a short. | ||||
17394 | if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { | ||||
17395 | BestType = Context.SignedCharTy; | ||||
17396 | BestWidth = CharWidth; | ||||
17397 | } else if (Packed && NumNegativeBits <= ShortWidth && | ||||
17398 | NumPositiveBits < ShortWidth) { | ||||
17399 | BestType = Context.ShortTy; | ||||
17400 | BestWidth = ShortWidth; | ||||
17401 | } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { | ||||
17402 | BestType = Context.IntTy; | ||||
17403 | BestWidth = IntWidth; | ||||
17404 | } else { | ||||
17405 | BestWidth = Context.getTargetInfo().getLongWidth(); | ||||
17406 | |||||
17407 | if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { | ||||
17408 | BestType = Context.LongTy; | ||||
17409 | } else { | ||||
17410 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | ||||
17411 | |||||
17412 | if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) | ||||
17413 | Diag(Enum->getLocation(), diag::ext_enum_too_large); | ||||
17414 | BestType = Context.LongLongTy; | ||||
17415 | } | ||||
17416 | } | ||||
17417 | BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); | ||||
17418 | } else { | ||||
17419 | // If there is no negative value, figure out the smallest type that fits | ||||
17420 | // all of the enumerator values. | ||||
17421 | // If it's packed, check also if it fits a char or a short. | ||||
17422 | if (Packed && NumPositiveBits <= CharWidth) { | ||||
17423 | BestType = Context.UnsignedCharTy; | ||||
17424 | BestPromotionType = Context.IntTy; | ||||
17425 | BestWidth = CharWidth; | ||||
17426 | } else if (Packed && NumPositiveBits <= ShortWidth) { | ||||
17427 | BestType = Context.UnsignedShortTy; | ||||
17428 | BestPromotionType = Context.IntTy; | ||||
17429 | BestWidth = ShortWidth; | ||||
17430 | } else if (NumPositiveBits <= IntWidth) { | ||||
17431 | BestType = Context.UnsignedIntTy; | ||||
17432 | BestWidth = IntWidth; | ||||
17433 | BestPromotionType | ||||
17434 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||
17435 | ? Context.UnsignedIntTy : Context.IntTy; | ||||
17436 | } else if (NumPositiveBits <= | ||||
17437 | (BestWidth = Context.getTargetInfo().getLongWidth())) { | ||||
17438 | BestType = Context.UnsignedLongTy; | ||||
17439 | BestPromotionType | ||||
17440 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||
17441 | ? Context.UnsignedLongTy : Context.LongTy; | ||||
17442 | } else { | ||||
17443 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | ||||
17444 | assert(NumPositiveBits <= BestWidth &&((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?" ) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 17445, __PRETTY_FUNCTION__)) | ||||
17445 | "How could an initializer get larger than ULL?")((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?" ) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDecl.cpp" , 17445, __PRETTY_FUNCTION__)); | ||||
17446 | BestType = Context.UnsignedLongLongTy; | ||||
17447 | BestPromotionType | ||||
17448 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||
17449 | ? Context.UnsignedLongLongTy : Context.LongLongTy; | ||||
17450 | } | ||||
17451 | } | ||||
17452 | |||||
17453 | // Loop over all of the enumerator constants, changing their types to match | ||||
17454 | // the type of the enum if needed. | ||||
17455 | for (auto *D : Elements) { | ||||
17456 | auto *ECD = cast_or_null<EnumConstantDecl>(D); | ||||
17457 | if (!ECD) continue; // Already issued a diagnostic. | ||||
17458 | |||||
17459 | // Standard C says the enumerators have int type, but we allow, as an | ||||
17460 | // extension, the enumerators to be larger than int size. If each | ||||
17461 | // enumerator value fits in an int, type it as an int, otherwise type it the | ||||
17462 | // same as the enumerator decl itself. This means that in "enum { X = 1U }" | ||||
17463 | // that X has type 'int', not 'unsigned'. | ||||
17464 | |||||
17465 | // Determine whether the value fits into an int. | ||||
17466 | llvm::APSInt InitVal = ECD->getInitVal(); | ||||
17467 | |||||
17468 | // If it fits into an integer type, force it. Otherwise force it to match | ||||
17469 | // the enum decl type. | ||||
17470 | QualType NewTy; | ||||
17471 | unsigned NewWidth; | ||||
17472 | bool NewSign; | ||||
17473 | if (!getLangOpts().CPlusPlus && | ||||
17474 | !Enum->isFixed() && | ||||
17475 | isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { | ||||
17476 | NewTy = Context.IntTy; | ||||
17477 | NewWidth = IntWidth; | ||||
17478 | NewSign = true; | ||||
17479 | } else if (ECD->getType() == BestType) { | ||||
17480 | // Already the right type! | ||||
17481 | if (getLangOpts().CPlusPlus) | ||||
17482 | // C++ [dcl.enum]p4: Following the closing brace of an | ||||
17483 | // enum-specifier, each enumerator has the type of its | ||||
17484 | // enumeration. | ||||
17485 | ECD->setType(EnumType); | ||||
17486 | continue; | ||||
17487 | } else { | ||||
17488 | NewTy = BestType; | ||||
17489 | NewWidth = BestWidth; | ||||
17490 | NewSign = BestType->isSignedIntegerOrEnumerationType(); | ||||
17491 | } | ||||
17492 | |||||
17493 | // Adjust the APSInt value. | ||||
17494 | InitVal = InitVal.extOrTrunc(NewWidth); | ||||
17495 | InitVal.setIsSigned(NewSign); | ||||
17496 | ECD->setInitVal(InitVal); | ||||
17497 | |||||
17498 | // Adjust the Expr initializer and type. | ||||
17499 | if (ECD->getInitExpr() && | ||||
17500 | !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) | ||||
17501 | ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, | ||||
17502 | CK_IntegralCast, | ||||
17503 | ECD->getInitExpr(), | ||||
17504 | /*base paths*/ nullptr, | ||||
17505 | VK_RValue)); | ||||
17506 | if (getLangOpts().CPlusPlus) | ||||
17507 | // C++ [dcl.enum]p4: Following the closing brace of an | ||||
17508 | // enum-specifier, each enumerator has the type of its | ||||
17509 | // enumeration. | ||||
17510 | ECD->setType(EnumType); | ||||
17511 | else | ||||
17512 | ECD->setType(NewTy); | ||||
17513 | } | ||||
17514 | |||||
17515 | Enum->completeDefinition(BestType, BestPromotionType, | ||||
17516 | NumPositiveBits, NumNegativeBits); | ||||
17517 | |||||
17518 | CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); | ||||
17519 | |||||
17520 | if (Enum->isClosedFlag()) { | ||||
17521 | for (Decl *D : Elements) { | ||||
17522 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); | ||||
17523 | if (!ECD) continue; // Already issued a diagnostic. | ||||
17524 | |||||
17525 | llvm::APSInt InitVal = ECD->getInitVal(); | ||||
17526 | if (InitVal != 0 && !InitVal.isPowerOf2() && | ||||
17527 | !IsValueInFlagEnum(Enum, InitVal, true)) | ||||
17528 | Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) | ||||
17529 | << ECD << Enum; | ||||
17530 | } | ||||
17531 | } | ||||
17532 | |||||
17533 | // Now that the enum type is defined, ensure it's not been underaligned. | ||||
17534 | if (Enum->hasAttrs()) | ||||
17535 | CheckAlignasUnderalignment(Enum); | ||||
17536 | } | ||||
17537 | |||||
17538 | Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, | ||||
17539 | SourceLocation StartLoc, | ||||
17540 | SourceLocation EndLoc) { | ||||
17541 | StringLiteral *AsmString = cast<StringLiteral>(expr); | ||||
17542 | |||||
17543 | FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, | ||||
17544 | AsmString, StartLoc, | ||||
17545 | EndLoc); | ||||
17546 | CurContext->addDecl(New); | ||||
17547 | return New; | ||||
17548 | } | ||||
17549 | |||||
17550 | void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, | ||||
17551 | IdentifierInfo* AliasName, | ||||
17552 | SourceLocation PragmaLoc, | ||||
17553 | SourceLocation NameLoc, | ||||
17554 | SourceLocation AliasNameLoc) { | ||||
17555 | NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, | ||||
17556 | LookupOrdinaryName); | ||||
17557 | AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), | ||||
17558 | AttributeCommonInfo::AS_Pragma); | ||||
17559 | AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( | ||||
17560 | Context, AliasName->getName(), /*LiteralLabel=*/true, Info); | ||||
17561 | |||||
17562 | // If a declaration that: | ||||
17563 | // 1) declares a function or a variable | ||||
17564 | // 2) has external linkage | ||||
17565 | // already exists, add a label attribute to it. | ||||
17566 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | ||||
17567 | if (isDeclExternC(PrevDecl)) | ||||
17568 | PrevDecl->addAttr(Attr); | ||||
17569 | else | ||||
17570 | Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) | ||||
17571 | << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; | ||||
17572 | // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. | ||||
17573 | } else | ||||
17574 | (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); | ||||
17575 | } | ||||
17576 | |||||
17577 | void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, | ||||
17578 | SourceLocation PragmaLoc, | ||||
17579 | SourceLocation NameLoc) { | ||||
17580 | Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); | ||||
17581 | |||||
17582 | if (PrevDecl) { | ||||
17583 | PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); | ||||
17584 | } else { | ||||
17585 | (void)WeakUndeclaredIdentifiers.insert( | ||||
17586 | std::pair<IdentifierInfo*,WeakInfo> | ||||
17587 | (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); | ||||
17588 | } | ||||
17589 | } | ||||
17590 | |||||
17591 | void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, | ||||
17592 | IdentifierInfo* AliasName, | ||||
17593 | SourceLocation PragmaLoc, | ||||
17594 | SourceLocation NameLoc, | ||||
17595 | SourceLocation AliasNameLoc) { | ||||
17596 | Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, | ||||
17597 | LookupOrdinaryName); | ||||
17598 | WeakInfo W = WeakInfo(Name, NameLoc); | ||||
17599 | |||||
17600 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | ||||
17601 | if (!PrevDecl->hasAttr<AliasAttr>()) | ||||
17602 | if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) | ||||
17603 | DeclApplyPragmaWeak(TUScope, ND, W); | ||||
17604 | } else { | ||||
17605 | (void)WeakUndeclaredIdentifiers.insert( | ||||
17606 | std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); | ||||
17607 | } | ||||
17608 | } | ||||
17609 | |||||
17610 | Decl *Sema::getObjCDeclContext() const { | ||||
17611 | return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); | ||||
17612 | } |
1 | //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | /// \file |
10 | /// C Language Family Type Representation |
11 | /// |
12 | /// This file defines the clang::Type interface and subclasses, used to |
13 | /// represent types for languages in the C family. |
14 | // |
15 | //===----------------------------------------------------------------------===// |
16 | |
17 | #ifndef LLVM_CLANG_AST_TYPE_H |
18 | #define LLVM_CLANG_AST_TYPE_H |
19 | |
20 | #include "clang/AST/NestedNameSpecifier.h" |
21 | #include "clang/AST/TemplateName.h" |
22 | #include "clang/Basic/AddressSpaces.h" |
23 | #include "clang/Basic/AttrKinds.h" |
24 | #include "clang/Basic/Diagnostic.h" |
25 | #include "clang/Basic/ExceptionSpecificationType.h" |
26 | #include "clang/Basic/LLVM.h" |
27 | #include "clang/Basic/Linkage.h" |
28 | #include "clang/Basic/PartialDiagnostic.h" |
29 | #include "clang/Basic/SourceLocation.h" |
30 | #include "clang/Basic/Specifiers.h" |
31 | #include "clang/Basic/Visibility.h" |
32 | #include "llvm/ADT/APInt.h" |
33 | #include "llvm/ADT/APSInt.h" |
34 | #include "llvm/ADT/ArrayRef.h" |
35 | #include "llvm/ADT/FoldingSet.h" |
36 | #include "llvm/ADT/None.h" |
37 | #include "llvm/ADT/Optional.h" |
38 | #include "llvm/ADT/PointerIntPair.h" |
39 | #include "llvm/ADT/PointerUnion.h" |
40 | #include "llvm/ADT/StringRef.h" |
41 | #include "llvm/ADT/Twine.h" |
42 | #include "llvm/ADT/iterator_range.h" |
43 | #include "llvm/Support/Casting.h" |
44 | #include "llvm/Support/Compiler.h" |
45 | #include "llvm/Support/ErrorHandling.h" |
46 | #include "llvm/Support/PointerLikeTypeTraits.h" |
47 | #include "llvm/Support/type_traits.h" |
48 | #include "llvm/Support/TrailingObjects.h" |
49 | #include <cassert> |
50 | #include <cstddef> |
51 | #include <cstdint> |
52 | #include <cstring> |
53 | #include <string> |
54 | #include <type_traits> |
55 | #include <utility> |
56 | |
57 | namespace clang { |
58 | |
59 | class ExtQuals; |
60 | class QualType; |
61 | class TagDecl; |
62 | class Type; |
63 | |
64 | enum { |
65 | TypeAlignmentInBits = 4, |
66 | TypeAlignment = 1 << TypeAlignmentInBits |
67 | }; |
68 | |
69 | } // namespace clang |
70 | |
71 | namespace llvm { |
72 | |
73 | template <typename T> |
74 | struct PointerLikeTypeTraits; |
75 | template<> |
76 | struct PointerLikeTypeTraits< ::clang::Type*> { |
77 | static inline void *getAsVoidPointer(::clang::Type *P) { return P; } |
78 | |
79 | static inline ::clang::Type *getFromVoidPointer(void *P) { |
80 | return static_cast< ::clang::Type*>(P); |
81 | } |
82 | |
83 | enum { NumLowBitsAvailable = clang::TypeAlignmentInBits }; |
84 | }; |
85 | |
86 | template<> |
87 | struct PointerLikeTypeTraits< ::clang::ExtQuals*> { |
88 | static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } |
89 | |
90 | static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { |
91 | return static_cast< ::clang::ExtQuals*>(P); |
92 | } |
93 | |
94 | enum { NumLowBitsAvailable = clang::TypeAlignmentInBits }; |
95 | }; |
96 | |
97 | } // namespace llvm |
98 | |
99 | namespace clang { |
100 | |
101 | class ASTContext; |
102 | template <typename> class CanQual; |
103 | class CXXRecordDecl; |
104 | class DeclContext; |
105 | class EnumDecl; |
106 | class Expr; |
107 | class ExtQualsTypeCommonBase; |
108 | class FunctionDecl; |
109 | class IdentifierInfo; |
110 | class NamedDecl; |
111 | class ObjCInterfaceDecl; |
112 | class ObjCProtocolDecl; |
113 | class ObjCTypeParamDecl; |
114 | struct PrintingPolicy; |
115 | class RecordDecl; |
116 | class Stmt; |
117 | class TagDecl; |
118 | class TemplateArgument; |
119 | class TemplateArgumentListInfo; |
120 | class TemplateArgumentLoc; |
121 | class TemplateTypeParmDecl; |
122 | class TypedefNameDecl; |
123 | class UnresolvedUsingTypenameDecl; |
124 | |
125 | using CanQualType = CanQual<Type>; |
126 | |
127 | // Provide forward declarations for all of the *Type classes. |
128 | #define TYPE(Class, Base) class Class##Type; |
129 | #include "clang/AST/TypeNodes.inc" |
130 | |
131 | /// The collection of all-type qualifiers we support. |
132 | /// Clang supports five independent qualifiers: |
133 | /// * C99: const, volatile, and restrict |
134 | /// * MS: __unaligned |
135 | /// * Embedded C (TR18037): address spaces |
136 | /// * Objective C: the GC attributes (none, weak, or strong) |
137 | class Qualifiers { |
138 | public: |
139 | enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. |
140 | Const = 0x1, |
141 | Restrict = 0x2, |
142 | Volatile = 0x4, |
143 | CVRMask = Const | Volatile | Restrict |
144 | }; |
145 | |
146 | enum GC { |
147 | GCNone = 0, |
148 | Weak, |
149 | Strong |
150 | }; |
151 | |
152 | enum ObjCLifetime { |
153 | /// There is no lifetime qualification on this type. |
154 | OCL_None, |
155 | |
156 | /// This object can be modified without requiring retains or |
157 | /// releases. |
158 | OCL_ExplicitNone, |
159 | |
160 | /// Assigning into this object requires the old value to be |
161 | /// released and the new value to be retained. The timing of the |
162 | /// release of the old value is inexact: it may be moved to |
163 | /// immediately after the last known point where the value is |
164 | /// live. |
165 | OCL_Strong, |
166 | |
167 | /// Reading or writing from this object requires a barrier call. |
168 | OCL_Weak, |
169 | |
170 | /// Assigning into this object requires a lifetime extension. |
171 | OCL_Autoreleasing |
172 | }; |
173 | |
174 | enum { |
175 | /// The maximum supported address space number. |
176 | /// 23 bits should be enough for anyone. |
177 | MaxAddressSpace = 0x7fffffu, |
178 | |
179 | /// The width of the "fast" qualifier mask. |
180 | FastWidth = 3, |
181 | |
182 | /// The fast qualifier mask. |
183 | FastMask = (1 << FastWidth) - 1 |
184 | }; |
185 | |
186 | /// Returns the common set of qualifiers while removing them from |
187 | /// the given sets. |
188 | static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { |
189 | // If both are only CVR-qualified, bit operations are sufficient. |
190 | if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { |
191 | Qualifiers Q; |
192 | Q.Mask = L.Mask & R.Mask; |
193 | L.Mask &= ~Q.Mask; |
194 | R.Mask &= ~Q.Mask; |
195 | return Q; |
196 | } |
197 | |
198 | Qualifiers Q; |
199 | unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); |
200 | Q.addCVRQualifiers(CommonCRV); |
201 | L.removeCVRQualifiers(CommonCRV); |
202 | R.removeCVRQualifiers(CommonCRV); |
203 | |
204 | if (L.getObjCGCAttr() == R.getObjCGCAttr()) { |
205 | Q.setObjCGCAttr(L.getObjCGCAttr()); |
206 | L.removeObjCGCAttr(); |
207 | R.removeObjCGCAttr(); |
208 | } |
209 | |
210 | if (L.getObjCLifetime() == R.getObjCLifetime()) { |
211 | Q.setObjCLifetime(L.getObjCLifetime()); |
212 | L.removeObjCLifetime(); |
213 | R.removeObjCLifetime(); |
214 | } |
215 | |
216 | if (L.getAddressSpace() == R.getAddressSpace()) { |
217 | Q.setAddressSpace(L.getAddressSpace()); |
218 | L.removeAddressSpace(); |
219 | R.removeAddressSpace(); |
220 | } |
221 | return Q; |
222 | } |
223 | |
224 | static Qualifiers fromFastMask(unsigned Mask) { |
225 | Qualifiers Qs; |
226 | Qs.addFastQualifiers(Mask); |
227 | return Qs; |
228 | } |
229 | |
230 | static Qualifiers fromCVRMask(unsigned CVR) { |
231 | Qualifiers Qs; |
232 | Qs.addCVRQualifiers(CVR); |
233 | return Qs; |
234 | } |
235 | |
236 | static Qualifiers fromCVRUMask(unsigned CVRU) { |
237 | Qualifiers Qs; |
238 | Qs.addCVRUQualifiers(CVRU); |
239 | return Qs; |
240 | } |
241 | |
242 | // Deserialize qualifiers from an opaque representation. |
243 | static Qualifiers fromOpaqueValue(unsigned opaque) { |
244 | Qualifiers Qs; |
245 | Qs.Mask = opaque; |
246 | return Qs; |
247 | } |
248 | |
249 | // Serialize these qualifiers into an opaque representation. |
250 | unsigned getAsOpaqueValue() const { |
251 | return Mask; |
252 | } |
253 | |
254 | bool hasConst() const { return Mask & Const; } |
255 | bool hasOnlyConst() const { return Mask == Const; } |
256 | void removeConst() { Mask &= ~Const; } |
257 | void addConst() { Mask |= Const; } |
258 | |
259 | bool hasVolatile() const { return Mask & Volatile; } |
260 | bool hasOnlyVolatile() const { return Mask == Volatile; } |
261 | void removeVolatile() { Mask &= ~Volatile; } |
262 | void addVolatile() { Mask |= Volatile; } |
263 | |
264 | bool hasRestrict() const { return Mask & Restrict; } |
265 | bool hasOnlyRestrict() const { return Mask == Restrict; } |
266 | void removeRestrict() { Mask &= ~Restrict; } |
267 | void addRestrict() { Mask |= Restrict; } |
268 | |
269 | bool hasCVRQualifiers() const { return getCVRQualifiers(); } |
270 | unsigned getCVRQualifiers() const { return Mask & CVRMask; } |
271 | unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } |
272 | |
273 | void setCVRQualifiers(unsigned mask) { |
274 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 274, __PRETTY_FUNCTION__)); |
275 | Mask = (Mask & ~CVRMask) | mask; |
276 | } |
277 | void removeCVRQualifiers(unsigned mask) { |
278 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 278, __PRETTY_FUNCTION__)); |
279 | Mask &= ~mask; |
280 | } |
281 | void removeCVRQualifiers() { |
282 | removeCVRQualifiers(CVRMask); |
283 | } |
284 | void addCVRQualifiers(unsigned mask) { |
285 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 285, __PRETTY_FUNCTION__)); |
286 | Mask |= mask; |
287 | } |
288 | void addCVRUQualifiers(unsigned mask) { |
289 | assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 289, __PRETTY_FUNCTION__)); |
290 | Mask |= mask; |
291 | } |
292 | |
293 | bool hasUnaligned() const { return Mask & UMask; } |
294 | void setUnaligned(bool flag) { |
295 | Mask = (Mask & ~UMask) | (flag ? UMask : 0); |
296 | } |
297 | void removeUnaligned() { Mask &= ~UMask; } |
298 | void addUnaligned() { Mask |= UMask; } |
299 | |
300 | bool hasObjCGCAttr() const { return Mask & GCAttrMask; } |
301 | GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } |
302 | void setObjCGCAttr(GC type) { |
303 | Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); |
304 | } |
305 | void removeObjCGCAttr() { setObjCGCAttr(GCNone); } |
306 | void addObjCGCAttr(GC type) { |
307 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 307, __PRETTY_FUNCTION__)); |
308 | setObjCGCAttr(type); |
309 | } |
310 | Qualifiers withoutObjCGCAttr() const { |
311 | Qualifiers qs = *this; |
312 | qs.removeObjCGCAttr(); |
313 | return qs; |
314 | } |
315 | Qualifiers withoutObjCLifetime() const { |
316 | Qualifiers qs = *this; |
317 | qs.removeObjCLifetime(); |
318 | return qs; |
319 | } |
320 | Qualifiers withoutAddressSpace() const { |
321 | Qualifiers qs = *this; |
322 | qs.removeAddressSpace(); |
323 | return qs; |
324 | } |
325 | |
326 | bool hasObjCLifetime() const { return Mask & LifetimeMask; } |
327 | ObjCLifetime getObjCLifetime() const { |
328 | return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); |
329 | } |
330 | void setObjCLifetime(ObjCLifetime type) { |
331 | Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); |
332 | } |
333 | void removeObjCLifetime() { setObjCLifetime(OCL_None); } |
334 | void addObjCLifetime(ObjCLifetime type) { |
335 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 335, __PRETTY_FUNCTION__)); |
336 | assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 336, __PRETTY_FUNCTION__)); |
337 | Mask |= (type << LifetimeShift); |
338 | } |
339 | |
340 | /// True if the lifetime is neither None or ExplicitNone. |
341 | bool hasNonTrivialObjCLifetime() const { |
342 | ObjCLifetime lifetime = getObjCLifetime(); |
343 | return (lifetime > OCL_ExplicitNone); |
344 | } |
345 | |
346 | /// True if the lifetime is either strong or weak. |
347 | bool hasStrongOrWeakObjCLifetime() const { |
348 | ObjCLifetime lifetime = getObjCLifetime(); |
349 | return (lifetime == OCL_Strong || lifetime == OCL_Weak); |
350 | } |
351 | |
352 | bool hasAddressSpace() const { return Mask & AddressSpaceMask; } |
353 | LangAS getAddressSpace() const { |
354 | return static_cast<LangAS>(Mask >> AddressSpaceShift); |
355 | } |
356 | bool hasTargetSpecificAddressSpace() const { |
357 | return isTargetAddressSpace(getAddressSpace()); |
358 | } |
359 | /// Get the address space attribute value to be printed by diagnostics. |
360 | unsigned getAddressSpaceAttributePrintValue() const { |
361 | auto Addr = getAddressSpace(); |
362 | // This function is not supposed to be used with language specific |
363 | // address spaces. If that happens, the diagnostic message should consider |
364 | // printing the QualType instead of the address space value. |
365 | assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace()) ? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 365, __PRETTY_FUNCTION__)); |
366 | if (Addr != LangAS::Default) |
367 | return toTargetAddressSpace(Addr); |
368 | // TODO: The diagnostic messages where Addr may be 0 should be fixed |
369 | // since it cannot differentiate the situation where 0 denotes the default |
370 | // address space or user specified __attribute__((address_space(0))). |
371 | return 0; |
372 | } |
373 | void setAddressSpace(LangAS space) { |
374 | assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void > (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 374, __PRETTY_FUNCTION__)); |
375 | Mask = (Mask & ~AddressSpaceMask) |
376 | | (((uint32_t) space) << AddressSpaceShift); |
377 | } |
378 | void removeAddressSpace() { setAddressSpace(LangAS::Default); } |
379 | void addAddressSpace(LangAS space) { |
380 | assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 380, __PRETTY_FUNCTION__)); |
381 | setAddressSpace(space); |
382 | } |
383 | |
384 | // Fast qualifiers are those that can be allocated directly |
385 | // on a QualType object. |
386 | bool hasFastQualifiers() const { return getFastQualifiers(); } |
387 | unsigned getFastQualifiers() const { return Mask & FastMask; } |
388 | void setFastQualifiers(unsigned mask) { |
389 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 389, __PRETTY_FUNCTION__)); |
390 | Mask = (Mask & ~FastMask) | mask; |
391 | } |
392 | void removeFastQualifiers(unsigned mask) { |
393 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 393, __PRETTY_FUNCTION__)); |
394 | Mask &= ~mask; |
395 | } |
396 | void removeFastQualifiers() { |
397 | removeFastQualifiers(FastMask); |
398 | } |
399 | void addFastQualifiers(unsigned mask) { |
400 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 400, __PRETTY_FUNCTION__)); |
401 | Mask |= mask; |
402 | } |
403 | |
404 | /// Return true if the set contains any qualifiers which require an ExtQuals |
405 | /// node to be allocated. |
406 | bool hasNonFastQualifiers() const { return Mask & ~FastMask; } |
407 | Qualifiers getNonFastQualifiers() const { |
408 | Qualifiers Quals = *this; |
409 | Quals.setFastQualifiers(0); |
410 | return Quals; |
411 | } |
412 | |
413 | /// Return true if the set contains any qualifiers. |
414 | bool hasQualifiers() const { return Mask; } |
415 | bool empty() const { return !Mask; } |
416 | |
417 | /// Add the qualifiers from the given set to this set. |
418 | void addQualifiers(Qualifiers Q) { |
419 | // If the other set doesn't have any non-boolean qualifiers, just |
420 | // bit-or it in. |
421 | if (!(Q.Mask & ~CVRMask)) |
422 | Mask |= Q.Mask; |
423 | else { |
424 | Mask |= (Q.Mask & CVRMask); |
425 | if (Q.hasAddressSpace()) |
426 | addAddressSpace(Q.getAddressSpace()); |
427 | if (Q.hasObjCGCAttr()) |
428 | addObjCGCAttr(Q.getObjCGCAttr()); |
429 | if (Q.hasObjCLifetime()) |
430 | addObjCLifetime(Q.getObjCLifetime()); |
431 | } |
432 | } |
433 | |
434 | /// Remove the qualifiers from the given set from this set. |
435 | void removeQualifiers(Qualifiers Q) { |
436 | // If the other set doesn't have any non-boolean qualifiers, just |
437 | // bit-and the inverse in. |
438 | if (!(Q.Mask & ~CVRMask)) |
439 | Mask &= ~Q.Mask; |
440 | else { |
441 | Mask &= ~(Q.Mask & CVRMask); |
442 | if (getObjCGCAttr() == Q.getObjCGCAttr()) |
443 | removeObjCGCAttr(); |
444 | if (getObjCLifetime() == Q.getObjCLifetime()) |
445 | removeObjCLifetime(); |
446 | if (getAddressSpace() == Q.getAddressSpace()) |
447 | removeAddressSpace(); |
448 | } |
449 | } |
450 | |
451 | /// Add the qualifiers from the given set to this set, given that |
452 | /// they don't conflict. |
453 | void addConsistentQualifiers(Qualifiers qs) { |
454 | assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 455, __PRETTY_FUNCTION__)) |
455 | !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 455, __PRETTY_FUNCTION__)); |
456 | assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 457, __PRETTY_FUNCTION__)) |
457 | !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 457, __PRETTY_FUNCTION__)); |
458 | assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 459, __PRETTY_FUNCTION__)) |
459 | !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 459, __PRETTY_FUNCTION__)); |
460 | Mask |= qs.Mask; |
461 | } |
462 | |
463 | /// Returns true if address space A is equal to or a superset of B. |
464 | /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of |
465 | /// overlapping address spaces. |
466 | /// CL1.1 or CL1.2: |
467 | /// every address space is a superset of itself. |
468 | /// CL2.0 adds: |
469 | /// __generic is a superset of any address space except for __constant. |
470 | static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { |
471 | // Address spaces must match exactly. |
472 | return A == B || |
473 | // Otherwise in OpenCLC v2.0 s6.5.5: every address space except |
474 | // for __constant can be used as __generic. |
475 | (A == LangAS::opencl_generic && B != LangAS::opencl_constant); |
476 | } |
477 | |
478 | /// Returns true if the address space in these qualifiers is equal to or |
479 | /// a superset of the address space in the argument qualifiers. |
480 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
481 | return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); |
482 | } |
483 | |
484 | /// Determines if these qualifiers compatibly include another set. |
485 | /// Generally this answers the question of whether an object with the other |
486 | /// qualifiers can be safely used as an object with these qualifiers. |
487 | bool compatiblyIncludes(Qualifiers other) const { |
488 | return isAddressSpaceSupersetOf(other) && |
489 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
490 | // be changed. |
491 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
492 | !other.hasObjCGCAttr()) && |
493 | // ObjC lifetime qualifiers must match exactly. |
494 | getObjCLifetime() == other.getObjCLifetime() && |
495 | // CVR qualifiers may subset. |
496 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
497 | // U qualifier may superset. |
498 | (!other.hasUnaligned() || hasUnaligned()); |
499 | } |
500 | |
501 | /// Determines if these qualifiers compatibly include another set of |
502 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
503 | /// |
504 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
505 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
506 | /// including set also contains the 'const' qualifier, or both are non-__weak |
507 | /// and one is None (which can only happen in non-ARC modes). |
508 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
509 | if (getObjCLifetime() == other.getObjCLifetime()) |
510 | return true; |
511 | |
512 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
513 | return false; |
514 | |
515 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
516 | return true; |
517 | |
518 | return hasConst(); |
519 | } |
520 | |
521 | /// Determine whether this set of qualifiers is a strict superset of |
522 | /// another set of qualifiers, not considering qualifier compatibility. |
523 | bool isStrictSupersetOf(Qualifiers Other) const; |
524 | |
525 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
526 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
527 | |
528 | explicit operator bool() const { return hasQualifiers(); } |
529 | |
530 | Qualifiers &operator+=(Qualifiers R) { |
531 | addQualifiers(R); |
532 | return *this; |
533 | } |
534 | |
535 | // Union two qualifier sets. If an enumerated qualifier appears |
536 | // in both sets, use the one from the right. |
537 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
538 | L += R; |
539 | return L; |
540 | } |
541 | |
542 | Qualifiers &operator-=(Qualifiers R) { |
543 | removeQualifiers(R); |
544 | return *this; |
545 | } |
546 | |
547 | /// Compute the difference between two qualifier sets. |
548 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
549 | L -= R; |
550 | return L; |
551 | } |
552 | |
553 | std::string getAsString() const; |
554 | std::string getAsString(const PrintingPolicy &Policy) const; |
555 | |
556 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
557 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
558 | bool appendSpaceIfNonEmpty = false) const; |
559 | |
560 | void Profile(llvm::FoldingSetNodeID &ID) const { |
561 | ID.AddInteger(Mask); |
562 | } |
563 | |
564 | private: |
565 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
566 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
567 | uint32_t Mask = 0; |
568 | |
569 | static const uint32_t UMask = 0x8; |
570 | static const uint32_t UShift = 3; |
571 | static const uint32_t GCAttrMask = 0x30; |
572 | static const uint32_t GCAttrShift = 4; |
573 | static const uint32_t LifetimeMask = 0x1C0; |
574 | static const uint32_t LifetimeShift = 6; |
575 | static const uint32_t AddressSpaceMask = |
576 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
577 | static const uint32_t AddressSpaceShift = 9; |
578 | }; |
579 | |
580 | /// A std::pair-like structure for storing a qualified type split |
581 | /// into its local qualifiers and its locally-unqualified type. |
582 | struct SplitQualType { |
583 | /// The locally-unqualified type. |
584 | const Type *Ty = nullptr; |
585 | |
586 | /// The local qualifiers. |
587 | Qualifiers Quals; |
588 | |
589 | SplitQualType() = default; |
590 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
591 | |
592 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
593 | |
594 | // Make std::tie work. |
595 | std::pair<const Type *,Qualifiers> asPair() const { |
596 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
597 | } |
598 | |
599 | friend bool operator==(SplitQualType a, SplitQualType b) { |
600 | return a.Ty == b.Ty && a.Quals == b.Quals; |
601 | } |
602 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
603 | return a.Ty != b.Ty || a.Quals != b.Quals; |
604 | } |
605 | }; |
606 | |
607 | /// The kind of type we are substituting Objective-C type arguments into. |
608 | /// |
609 | /// The kind of substitution affects the replacement of type parameters when |
610 | /// no concrete type information is provided, e.g., when dealing with an |
611 | /// unspecialized type. |
612 | enum class ObjCSubstitutionContext { |
613 | /// An ordinary type. |
614 | Ordinary, |
615 | |
616 | /// The result type of a method or function. |
617 | Result, |
618 | |
619 | /// The parameter type of a method or function. |
620 | Parameter, |
621 | |
622 | /// The type of a property. |
623 | Property, |
624 | |
625 | /// The superclass of a type. |
626 | Superclass, |
627 | }; |
628 | |
629 | /// A (possibly-)qualified type. |
630 | /// |
631 | /// For efficiency, we don't store CV-qualified types as nodes on their |
632 | /// own: instead each reference to a type stores the qualifiers. This |
633 | /// greatly reduces the number of nodes we need to allocate for types (for |
634 | /// example we only need one for 'int', 'const int', 'volatile int', |
635 | /// 'const volatile int', etc). |
636 | /// |
637 | /// As an added efficiency bonus, instead of making this a pair, we |
638 | /// just store the two bits we care about in the low bits of the |
639 | /// pointer. To handle the packing/unpacking, we make QualType be a |
640 | /// simple wrapper class that acts like a smart pointer. A third bit |
641 | /// indicates whether there are extended qualifiers present, in which |
642 | /// case the pointer points to a special structure. |
643 | class QualType { |
644 | friend class QualifierCollector; |
645 | |
646 | // Thankfully, these are efficiently composable. |
647 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
648 | Qualifiers::FastWidth> Value; |
649 | |
650 | const ExtQuals *getExtQualsUnsafe() const { |
651 | return Value.getPointer().get<const ExtQuals*>(); |
652 | } |
653 | |
654 | const Type *getTypePtrUnsafe() const { |
655 | return Value.getPointer().get<const Type*>(); |
656 | } |
657 | |
658 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
659 | assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer") ? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 659, __PRETTY_FUNCTION__)); |
660 | auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
661 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
662 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
663 | } |
664 | |
665 | public: |
666 | QualType() = default; |
667 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
668 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
669 | |
670 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
671 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
672 | |
673 | /// Retrieves a pointer to the underlying (unqualified) type. |
674 | /// |
675 | /// This function requires that the type not be NULL. If the type might be |
676 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
677 | const Type *getTypePtr() const; |
678 | |
679 | const Type *getTypePtrOrNull() const; |
680 | |
681 | /// Retrieves a pointer to the name of the base type. |
682 | const IdentifierInfo *getBaseTypeIdentifier() const; |
683 | |
684 | /// Divides a QualType into its unqualified type and a set of local |
685 | /// qualifiers. |
686 | SplitQualType split() const; |
687 | |
688 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
689 | |
690 | static QualType getFromOpaquePtr(const void *Ptr) { |
691 | QualType T; |
692 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
693 | return T; |
694 | } |
695 | |
696 | const Type &operator*() const { |
697 | return *getTypePtr(); |
698 | } |
699 | |
700 | const Type *operator->() const { |
701 | return getTypePtr(); |
702 | } |
703 | |
704 | bool isCanonical() const; |
705 | bool isCanonicalAsParam() const; |
706 | |
707 | /// Return true if this QualType doesn't point to a type yet. |
708 | bool isNull() const { |
709 | return Value.getPointer().isNull(); |
710 | } |
711 | |
712 | /// Determine whether this particular QualType instance has the |
713 | /// "const" qualifier set, without looking through typedefs that may have |
714 | /// added "const" at a different level. |
715 | bool isLocalConstQualified() const { |
716 | return (getLocalFastQualifiers() & Qualifiers::Const); |
717 | } |
718 | |
719 | /// Determine whether this type is const-qualified. |
720 | bool isConstQualified() const; |
721 | |
722 | /// Determine whether this particular QualType instance has the |
723 | /// "restrict" qualifier set, without looking through typedefs that may have |
724 | /// added "restrict" at a different level. |
725 | bool isLocalRestrictQualified() const { |
726 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
727 | } |
728 | |
729 | /// Determine whether this type is restrict-qualified. |
730 | bool isRestrictQualified() const; |
731 | |
732 | /// Determine whether this particular QualType instance has the |
733 | /// "volatile" qualifier set, without looking through typedefs that may have |
734 | /// added "volatile" at a different level. |
735 | bool isLocalVolatileQualified() const { |
736 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
737 | } |
738 | |
739 | /// Determine whether this type is volatile-qualified. |
740 | bool isVolatileQualified() const; |
741 | |
742 | /// Determine whether this particular QualType instance has any |
743 | /// qualifiers, without looking through any typedefs that might add |
744 | /// qualifiers at a different level. |
745 | bool hasLocalQualifiers() const { |
746 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
747 | } |
748 | |
749 | /// Determine whether this type has any qualifiers. |
750 | bool hasQualifiers() const; |
751 | |
752 | /// Determine whether this particular QualType instance has any |
753 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
754 | /// instance. |
755 | bool hasLocalNonFastQualifiers() const { |
756 | return Value.getPointer().is<const ExtQuals*>(); |
757 | } |
758 | |
759 | /// Retrieve the set of qualifiers local to this particular QualType |
760 | /// instance, not including any qualifiers acquired through typedefs or |
761 | /// other sugar. |
762 | Qualifiers getLocalQualifiers() const; |
763 | |
764 | /// Retrieve the set of qualifiers applied to this type. |
765 | Qualifiers getQualifiers() const; |
766 | |
767 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
768 | /// local to this particular QualType instance, not including any qualifiers |
769 | /// acquired through typedefs or other sugar. |
770 | unsigned getLocalCVRQualifiers() const { |
771 | return getLocalFastQualifiers(); |
772 | } |
773 | |
774 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
775 | /// applied to this type. |
776 | unsigned getCVRQualifiers() const; |
777 | |
778 | bool isConstant(const ASTContext& Ctx) const { |
779 | return QualType::isConstant(*this, Ctx); |
780 | } |
781 | |
782 | /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
783 | bool isPODType(const ASTContext &Context) const; |
784 | |
785 | /// Return true if this is a POD type according to the rules of the C++98 |
786 | /// standard, regardless of the current compilation's language. |
787 | bool isCXX98PODType(const ASTContext &Context) const; |
788 | |
789 | /// Return true if this is a POD type according to the more relaxed rules |
790 | /// of the C++11 standard, regardless of the current compilation's language. |
791 | /// (C++0x [basic.types]p9). Note that, unlike |
792 | /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. |
793 | bool isCXX11PODType(const ASTContext &Context) const; |
794 | |
795 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
796 | bool isTrivialType(const ASTContext &Context) const; |
797 | |
798 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
799 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
800 | |
801 | |
802 | /// Returns true if it is a class and it might be dynamic. |
803 | bool mayBeDynamicClass() const; |
804 | |
805 | /// Returns true if it is not a class or if the class might not be dynamic. |
806 | bool mayBeNotDynamicClass() const; |
807 | |
808 | // Don't promise in the API that anything besides 'const' can be |
809 | // easily added. |
810 | |
811 | /// Add the `const` type qualifier to this QualType. |
812 | void addConst() { |
813 | addFastQualifiers(Qualifiers::Const); |
814 | } |
815 | QualType withConst() const { |
816 | return withFastQualifiers(Qualifiers::Const); |
817 | } |
818 | |
819 | /// Add the `volatile` type qualifier to this QualType. |
820 | void addVolatile() { |
821 | addFastQualifiers(Qualifiers::Volatile); |
822 | } |
823 | QualType withVolatile() const { |
824 | return withFastQualifiers(Qualifiers::Volatile); |
825 | } |
826 | |
827 | /// Add the `restrict` qualifier to this QualType. |
828 | void addRestrict() { |
829 | addFastQualifiers(Qualifiers::Restrict); |
830 | } |
831 | QualType withRestrict() const { |
832 | return withFastQualifiers(Qualifiers::Restrict); |
833 | } |
834 | |
835 | QualType withCVRQualifiers(unsigned CVR) const { |
836 | return withFastQualifiers(CVR); |
837 | } |
838 | |
839 | void addFastQualifiers(unsigned TQs) { |
840 | assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 841, __PRETTY_FUNCTION__)) |
841 | && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 841, __PRETTY_FUNCTION__)); |
842 | Value.setInt(Value.getInt() | TQs); |
843 | } |
844 | |
845 | void removeLocalConst(); |
846 | void removeLocalVolatile(); |
847 | void removeLocalRestrict(); |
848 | void removeLocalCVRQualifiers(unsigned Mask); |
849 | |
850 | void removeLocalFastQualifiers() { Value.setInt(0); } |
851 | void removeLocalFastQualifiers(unsigned Mask) { |
852 | assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 852, __PRETTY_FUNCTION__)); |
853 | Value.setInt(Value.getInt() & ~Mask); |
854 | } |
855 | |
856 | // Creates a type with the given qualifiers in addition to any |
857 | // qualifiers already on this type. |
858 | QualType withFastQualifiers(unsigned TQs) const { |
859 | QualType T = *this; |
860 | T.addFastQualifiers(TQs); |
861 | return T; |
862 | } |
863 | |
864 | // Creates a type with exactly the given fast qualifiers, removing |
865 | // any existing fast qualifiers. |
866 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
867 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
868 | } |
869 | |
870 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
871 | QualType withoutLocalFastQualifiers() const { |
872 | QualType T = *this; |
873 | T.removeLocalFastQualifiers(); |
874 | return T; |
875 | } |
876 | |
877 | QualType getCanonicalType() const; |
878 | |
879 | /// Return this type with all of the instance-specific qualifiers |
880 | /// removed, but without removing any qualifiers that may have been applied |
881 | /// through typedefs. |
882 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
883 | |
884 | /// Retrieve the unqualified variant of the given type, |
885 | /// removing as little sugar as possible. |
886 | /// |
887 | /// This routine looks through various kinds of sugar to find the |
888 | /// least-desugared type that is unqualified. For example, given: |
889 | /// |
890 | /// \code |
891 | /// typedef int Integer; |
892 | /// typedef const Integer CInteger; |
893 | /// typedef CInteger DifferenceType; |
894 | /// \endcode |
895 | /// |
896 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
897 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
898 | /// |
899 | /// The resulting type might still be qualified if it's sugar for an array |
900 | /// type. To strip qualifiers even from within a sugared array type, use |
901 | /// ASTContext::getUnqualifiedArrayType. |
902 | inline QualType getUnqualifiedType() const; |
903 | |
904 | /// Retrieve the unqualified variant of the given type, removing as little |
905 | /// sugar as possible. |
906 | /// |
907 | /// Like getUnqualifiedType(), but also returns the set of |
908 | /// qualifiers that were built up. |
909 | /// |
910 | /// The resulting type might still be qualified if it's sugar for an array |
911 | /// type. To strip qualifiers even from within a sugared array type, use |
912 | /// ASTContext::getUnqualifiedArrayType. |
913 | inline SplitQualType getSplitUnqualifiedType() const; |
914 | |
915 | /// Determine whether this type is more qualified than the other |
916 | /// given type, requiring exact equality for non-CVR qualifiers. |
917 | bool isMoreQualifiedThan(QualType Other) const; |
918 | |
919 | /// Determine whether this type is at least as qualified as the other |
920 | /// given type, requiring exact equality for non-CVR qualifiers. |
921 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
922 | |
923 | QualType getNonReferenceType() const; |
924 | |
925 | /// Determine the type of a (typically non-lvalue) expression with the |
926 | /// specified result type. |
927 | /// |
928 | /// This routine should be used for expressions for which the return type is |
929 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
930 | /// an lvalue. It removes a top-level reference (since there are no |
931 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
932 | /// from non-class types (in C++) or all types (in C). |
933 | QualType getNonLValueExprType(const ASTContext &Context) const; |
934 | |
935 | /// Return the specified type with any "sugar" removed from |
936 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
937 | /// the type is already concrete, it returns it unmodified. This is similar |
938 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
939 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
940 | /// concrete. |
941 | /// |
942 | /// Qualifiers are left in place. |
943 | QualType getDesugaredType(const ASTContext &Context) const { |
944 | return getDesugaredType(*this, Context); |
945 | } |
946 | |
947 | SplitQualType getSplitDesugaredType() const { |
948 | return getSplitDesugaredType(*this); |
949 | } |
950 | |
951 | /// Return the specified type with one level of "sugar" removed from |
952 | /// the type. |
953 | /// |
954 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
955 | /// of the type is already concrete, it returns it unmodified. |
956 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
957 | return getSingleStepDesugaredTypeImpl(*this, Context); |
958 | } |
959 | |
960 | /// Returns the specified type after dropping any |
961 | /// outer-level parentheses. |
962 | QualType IgnoreParens() const { |
963 | if (isa<ParenType>(*this)) |
964 | return QualType::IgnoreParens(*this); |
965 | return *this; |
966 | } |
967 | |
968 | /// Indicate whether the specified types and qualifiers are identical. |
969 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
970 | return LHS.Value == RHS.Value; |
971 | } |
972 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
973 | return LHS.Value != RHS.Value; |
974 | } |
975 | friend bool operator<(const QualType &LHS, const QualType &RHS) { |
976 | return LHS.Value < RHS.Value; |
977 | } |
978 | |
979 | static std::string getAsString(SplitQualType split, |
980 | const PrintingPolicy &Policy) { |
981 | return getAsString(split.Ty, split.Quals, Policy); |
982 | } |
983 | static std::string getAsString(const Type *ty, Qualifiers qs, |
984 | const PrintingPolicy &Policy); |
985 | |
986 | std::string getAsString() const; |
987 | std::string getAsString(const PrintingPolicy &Policy) const; |
988 | |
989 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
990 | const Twine &PlaceHolder = Twine(), |
991 | unsigned Indentation = 0) const; |
992 | |
993 | static void print(SplitQualType split, raw_ostream &OS, |
994 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
995 | unsigned Indentation = 0) { |
996 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
997 | } |
998 | |
999 | static void print(const Type *ty, Qualifiers qs, |
1000 | raw_ostream &OS, const PrintingPolicy &policy, |
1001 | const Twine &PlaceHolder, |
1002 | unsigned Indentation = 0); |
1003 | |
1004 | void getAsStringInternal(std::string &Str, |
1005 | const PrintingPolicy &Policy) const; |
1006 | |
1007 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1008 | const PrintingPolicy &policy) { |
1009 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1010 | } |
1011 | |
1012 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1013 | std::string &out, |
1014 | const PrintingPolicy &policy); |
1015 | |
1016 | class StreamedQualTypeHelper { |
1017 | const QualType &T; |
1018 | const PrintingPolicy &Policy; |
1019 | const Twine &PlaceHolder; |
1020 | unsigned Indentation; |
1021 | |
1022 | public: |
1023 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1024 | const Twine &PlaceHolder, unsigned Indentation) |
1025 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1026 | Indentation(Indentation) {} |
1027 | |
1028 | friend raw_ostream &operator<<(raw_ostream &OS, |
1029 | const StreamedQualTypeHelper &SQT) { |
1030 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1031 | return OS; |
1032 | } |
1033 | }; |
1034 | |
1035 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1036 | const Twine &PlaceHolder = Twine(), |
1037 | unsigned Indentation = 0) const { |
1038 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1039 | } |
1040 | |
1041 | void dump(const char *s) const; |
1042 | void dump() const; |
1043 | void dump(llvm::raw_ostream &OS) const; |
1044 | |
1045 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1046 | ID.AddPointer(getAsOpaquePtr()); |
1047 | } |
1048 | |
1049 | /// Return the address space of this type. |
1050 | inline LangAS getAddressSpace() const; |
1051 | |
1052 | /// Returns gc attribute of this type. |
1053 | inline Qualifiers::GC getObjCGCAttr() const; |
1054 | |
1055 | /// true when Type is objc's weak. |
1056 | bool isObjCGCWeak() const { |
1057 | return getObjCGCAttr() == Qualifiers::Weak; |
1058 | } |
1059 | |
1060 | /// true when Type is objc's strong. |
1061 | bool isObjCGCStrong() const { |
1062 | return getObjCGCAttr() == Qualifiers::Strong; |
1063 | } |
1064 | |
1065 | /// Returns lifetime attribute of this type. |
1066 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1067 | return getQualifiers().getObjCLifetime(); |
1068 | } |
1069 | |
1070 | bool hasNonTrivialObjCLifetime() const { |
1071 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1072 | } |
1073 | |
1074 | bool hasStrongOrWeakObjCLifetime() const { |
1075 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1076 | } |
1077 | |
1078 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1079 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1080 | |
1081 | enum PrimitiveDefaultInitializeKind { |
1082 | /// The type does not fall into any of the following categories. Note that |
1083 | /// this case is zero-valued so that values of this enum can be used as a |
1084 | /// boolean condition for non-triviality. |
1085 | PDIK_Trivial, |
1086 | |
1087 | /// The type is an Objective-C retainable pointer type that is qualified |
1088 | /// with the ARC __strong qualifier. |
1089 | PDIK_ARCStrong, |
1090 | |
1091 | /// The type is an Objective-C retainable pointer type that is qualified |
1092 | /// with the ARC __weak qualifier. |
1093 | PDIK_ARCWeak, |
1094 | |
1095 | /// The type is a struct containing a field whose type is not PCK_Trivial. |
1096 | PDIK_Struct |
1097 | }; |
1098 | |
1099 | /// Functions to query basic properties of non-trivial C struct types. |
1100 | |
1101 | /// Check if this is a non-trivial type that would cause a C struct |
1102 | /// transitively containing this type to be non-trivial to default initialize |
1103 | /// and return the kind. |
1104 | PrimitiveDefaultInitializeKind |
1105 | isNonTrivialToPrimitiveDefaultInitialize() const; |
1106 | |
1107 | enum PrimitiveCopyKind { |
1108 | /// The type does not fall into any of the following categories. Note that |
1109 | /// this case is zero-valued so that values of this enum can be used as a |
1110 | /// boolean condition for non-triviality. |
1111 | PCK_Trivial, |
1112 | |
1113 | /// The type would be trivial except that it is volatile-qualified. Types |
1114 | /// that fall into one of the other non-trivial cases may additionally be |
1115 | /// volatile-qualified. |
1116 | PCK_VolatileTrivial, |
1117 | |
1118 | /// The type is an Objective-C retainable pointer type that is qualified |
1119 | /// with the ARC __strong qualifier. |
1120 | PCK_ARCStrong, |
1121 | |
1122 | /// The type is an Objective-C retainable pointer type that is qualified |
1123 | /// with the ARC __weak qualifier. |
1124 | PCK_ARCWeak, |
1125 | |
1126 | /// The type is a struct containing a field whose type is neither |
1127 | /// PCK_Trivial nor PCK_VolatileTrivial. |
1128 | /// Note that a C++ struct type does not necessarily match this; C++ copying |
1129 | /// semantics are too complex to express here, in part because they depend |
1130 | /// on the exact constructor or assignment operator that is chosen by |
1131 | /// overload resolution to do the copy. |
1132 | PCK_Struct |
1133 | }; |
1134 | |
1135 | /// Check if this is a non-trivial type that would cause a C struct |
1136 | /// transitively containing this type to be non-trivial to copy and return the |
1137 | /// kind. |
1138 | PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; |
1139 | |
1140 | /// Check if this is a non-trivial type that would cause a C struct |
1141 | /// transitively containing this type to be non-trivial to destructively |
1142 | /// move and return the kind. Destructive move in this context is a C++-style |
1143 | /// move in which the source object is placed in a valid but unspecified state |
1144 | /// after it is moved, as opposed to a truly destructive move in which the |
1145 | /// source object is placed in an uninitialized state. |
1146 | PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; |
1147 | |
1148 | enum DestructionKind { |
1149 | DK_none, |
1150 | DK_cxx_destructor, |
1151 | DK_objc_strong_lifetime, |
1152 | DK_objc_weak_lifetime, |
1153 | DK_nontrivial_c_struct |
1154 | }; |
1155 | |
1156 | /// Returns a nonzero value if objects of this type require |
1157 | /// non-trivial work to clean up after. Non-zero because it's |
1158 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1159 | /// something require destruction. |
1160 | DestructionKind isDestructedType() const { |
1161 | return isDestructedTypeImpl(*this); |
1162 | } |
1163 | |
1164 | /// Check if this is or contains a C union that is non-trivial to |
1165 | /// default-initialize, which is a union that has a member that is non-trivial |
1166 | /// to default-initialize. If this returns true, |
1167 | /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. |
1168 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; |
1169 | |
1170 | /// Check if this is or contains a C union that is non-trivial to destruct, |
1171 | /// which is a union that has a member that is non-trivial to destruct. If |
1172 | /// this returns true, isDestructedType returns DK_nontrivial_c_struct. |
1173 | bool hasNonTrivialToPrimitiveDestructCUnion() const; |
1174 | |
1175 | /// Check if this is or contains a C union that is non-trivial to copy, which |
1176 | /// is a union that has a member that is non-trivial to copy. If this returns |
1177 | /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. |
1178 | bool hasNonTrivialToPrimitiveCopyCUnion() const; |
1179 | |
1180 | /// Determine whether expressions of the given type are forbidden |
1181 | /// from being lvalues in C. |
1182 | /// |
1183 | /// The expression types that are forbidden to be lvalues are: |
1184 | /// - 'void', but not qualified void |
1185 | /// - function types |
1186 | /// |
1187 | /// The exact rule here is C99 6.3.2.1: |
1188 | /// An lvalue is an expression with an object type or an incomplete |
1189 | /// type other than void. |
1190 | bool isCForbiddenLValueType() const; |
1191 | |
1192 | /// Substitute type arguments for the Objective-C type parameters used in the |
1193 | /// subject type. |
1194 | /// |
1195 | /// \param ctx ASTContext in which the type exists. |
1196 | /// |
1197 | /// \param typeArgs The type arguments that will be substituted for the |
1198 | /// Objective-C type parameters in the subject type, which are generally |
1199 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1200 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1201 | /// for the context. |
1202 | /// |
1203 | /// \param context The context in which the subject type was written. |
1204 | /// |
1205 | /// \returns the resulting type. |
1206 | QualType substObjCTypeArgs(ASTContext &ctx, |
1207 | ArrayRef<QualType> typeArgs, |
1208 | ObjCSubstitutionContext context) const; |
1209 | |
1210 | /// Substitute type arguments from an object type for the Objective-C type |
1211 | /// parameters used in the subject type. |
1212 | /// |
1213 | /// This operation combines the computation of type arguments for |
1214 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1215 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1216 | /// callers that need to perform a single substitution in isolation. |
1217 | /// |
1218 | /// \param objectType The type of the object whose member type we're |
1219 | /// substituting into. For example, this might be the receiver of a message |
1220 | /// or the base of a property access. |
1221 | /// |
1222 | /// \param dc The declaration context from which the subject type was |
1223 | /// retrieved, which indicates (for example) which type parameters should |
1224 | /// be substituted. |
1225 | /// |
1226 | /// \param context The context in which the subject type was written. |
1227 | /// |
1228 | /// \returns the subject type after replacing all of the Objective-C type |
1229 | /// parameters with their corresponding arguments. |
1230 | QualType substObjCMemberType(QualType objectType, |
1231 | const DeclContext *dc, |
1232 | ObjCSubstitutionContext context) const; |
1233 | |
1234 | /// Strip Objective-C "__kindof" types from the given type. |
1235 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1236 | |
1237 | /// Remove all qualifiers including _Atomic. |
1238 | QualType getAtomicUnqualifiedType() const; |
1239 | |
1240 | private: |
1241 | // These methods are implemented in a separate translation unit; |
1242 | // "static"-ize them to avoid creating temporary QualTypes in the |
1243 | // caller. |
1244 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1245 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1246 | static SplitQualType getSplitDesugaredType(QualType T); |
1247 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1248 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1249 | const ASTContext &C); |
1250 | static QualType IgnoreParens(QualType T); |
1251 | static DestructionKind isDestructedTypeImpl(QualType type); |
1252 | |
1253 | /// Check if \param RD is or contains a non-trivial C union. |
1254 | static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); |
1255 | static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); |
1256 | static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); |
1257 | }; |
1258 | |
1259 | } // namespace clang |
1260 | |
1261 | namespace llvm { |
1262 | |
1263 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1264 | /// to a specific Type class. |
1265 | template<> struct simplify_type< ::clang::QualType> { |
1266 | using SimpleType = const ::clang::Type *; |
1267 | |
1268 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1269 | return Val.getTypePtr(); |
1270 | } |
1271 | }; |
1272 | |
1273 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1274 | template<> |
1275 | struct PointerLikeTypeTraits<clang::QualType> { |
1276 | static inline void *getAsVoidPointer(clang::QualType P) { |
1277 | return P.getAsOpaquePtr(); |
1278 | } |
1279 | |
1280 | static inline clang::QualType getFromVoidPointer(void *P) { |
1281 | return clang::QualType::getFromOpaquePtr(P); |
1282 | } |
1283 | |
1284 | // Various qualifiers go in low bits. |
1285 | enum { NumLowBitsAvailable = 0 }; |
1286 | }; |
1287 | |
1288 | } // namespace llvm |
1289 | |
1290 | namespace clang { |
1291 | |
1292 | /// Base class that is common to both the \c ExtQuals and \c Type |
1293 | /// classes, which allows \c QualType to access the common fields between the |
1294 | /// two. |
1295 | class ExtQualsTypeCommonBase { |
1296 | friend class ExtQuals; |
1297 | friend class QualType; |
1298 | friend class Type; |
1299 | |
1300 | /// The "base" type of an extended qualifiers type (\c ExtQuals) or |
1301 | /// a self-referential pointer (for \c Type). |
1302 | /// |
1303 | /// This pointer allows an efficient mapping from a QualType to its |
1304 | /// underlying type pointer. |
1305 | const Type *const BaseType; |
1306 | |
1307 | /// The canonical type of this type. A QualType. |
1308 | QualType CanonicalType; |
1309 | |
1310 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1311 | : BaseType(baseType), CanonicalType(canon) {} |
1312 | }; |
1313 | |
1314 | /// We can encode up to four bits in the low bits of a |
1315 | /// type pointer, but there are many more type qualifiers that we want |
1316 | /// to be able to apply to an arbitrary type. Therefore we have this |
1317 | /// struct, intended to be heap-allocated and used by QualType to |
1318 | /// store qualifiers. |
1319 | /// |
1320 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1321 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1322 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1323 | /// Objective-C GC attributes) are much more rare. |
1324 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1325 | // NOTE: changing the fast qualifiers should be straightforward as |
1326 | // long as you don't make 'const' non-fast. |
1327 | // 1. Qualifiers: |
1328 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1329 | // Fast qualifiers must occupy the low-order bits. |
1330 | // b) Update Qualifiers::FastWidth and FastMask. |
1331 | // 2. QualType: |
1332 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1333 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1334 | // this header. |
1335 | // 3. ASTContext: |
1336 | // a) Update get{Volatile,Restrict}Type. |
1337 | |
1338 | /// The immutable set of qualifiers applied by this node. Always contains |
1339 | /// extended qualifiers. |
1340 | Qualifiers Quals; |
1341 | |
1342 | ExtQuals *this_() { return this; } |
1343 | |
1344 | public: |
1345 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1346 | : ExtQualsTypeCommonBase(baseType, |
1347 | canon.isNull() ? QualType(this_(), 0) : canon), |
1348 | Quals(quals) { |
1349 | assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1350, __PRETTY_FUNCTION__)) |
1350 | && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1350, __PRETTY_FUNCTION__)); |
1351 | assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1352, __PRETTY_FUNCTION__)) |
1352 | && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1352, __PRETTY_FUNCTION__)); |
1353 | } |
1354 | |
1355 | Qualifiers getQualifiers() const { return Quals; } |
1356 | |
1357 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1358 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1359 | |
1360 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1361 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1362 | return Quals.getObjCLifetime(); |
1363 | } |
1364 | |
1365 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1366 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1367 | |
1368 | const Type *getBaseType() const { return BaseType; } |
1369 | |
1370 | public: |
1371 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1372 | Profile(ID, getBaseType(), Quals); |
1373 | } |
1374 | |
1375 | static void Profile(llvm::FoldingSetNodeID &ID, |
1376 | const Type *BaseType, |
1377 | Qualifiers Quals) { |
1378 | assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1378, __PRETTY_FUNCTION__)); |
1379 | ID.AddPointer(BaseType); |
1380 | Quals.Profile(ID); |
1381 | } |
1382 | }; |
1383 | |
1384 | /// The kind of C++11 ref-qualifier associated with a function type. |
1385 | /// This determines whether a member function's "this" object can be an |
1386 | /// lvalue, rvalue, or neither. |
1387 | enum RefQualifierKind { |
1388 | /// No ref-qualifier was provided. |
1389 | RQ_None = 0, |
1390 | |
1391 | /// An lvalue ref-qualifier was provided (\c &). |
1392 | RQ_LValue, |
1393 | |
1394 | /// An rvalue ref-qualifier was provided (\c &&). |
1395 | RQ_RValue |
1396 | }; |
1397 | |
1398 | /// Which keyword(s) were used to create an AutoType. |
1399 | enum class AutoTypeKeyword { |
1400 | /// auto |
1401 | Auto, |
1402 | |
1403 | /// decltype(auto) |
1404 | DecltypeAuto, |
1405 | |
1406 | /// __auto_type (GNU extension) |
1407 | GNUAutoType |
1408 | }; |
1409 | |
1410 | /// The base class of the type hierarchy. |
1411 | /// |
1412 | /// A central concept with types is that each type always has a canonical |
1413 | /// type. A canonical type is the type with any typedef names stripped out |
1414 | /// of it or the types it references. For example, consider: |
1415 | /// |
1416 | /// typedef int foo; |
1417 | /// typedef foo* bar; |
1418 | /// 'int *' 'foo *' 'bar' |
1419 | /// |
1420 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1421 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1422 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1423 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1424 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1425 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1426 | /// is also 'int*'. |
1427 | /// |
1428 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1429 | /// information about typedefs being used. Canonical types are useful for type |
1430 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1431 | /// about whether something has a particular form (e.g. is a function type), |
1432 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1433 | /// |
1434 | /// Types, once created, are immutable. |
1435 | /// |
1436 | class alignas(8) Type : public ExtQualsTypeCommonBase { |
1437 | public: |
1438 | enum TypeClass { |
1439 | #define TYPE(Class, Base) Class, |
1440 | #define LAST_TYPE(Class) TypeLast = Class |
1441 | #define ABSTRACT_TYPE(Class, Base) |
1442 | #include "clang/AST/TypeNodes.inc" |
1443 | }; |
1444 | |
1445 | private: |
1446 | /// Bitfields required by the Type class. |
1447 | class TypeBitfields { |
1448 | friend class Type; |
1449 | template <class T> friend class TypePropertyCache; |
1450 | |
1451 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1452 | unsigned TC : 8; |
1453 | |
1454 | /// Whether this type is a dependent type (C++ [temp.dep.type]). |
1455 | unsigned Dependent : 1; |
1456 | |
1457 | /// Whether this type somehow involves a template parameter, even |
1458 | /// if the resolution of the type does not depend on a template parameter. |
1459 | unsigned InstantiationDependent : 1; |
1460 | |
1461 | /// Whether this type is a variably-modified type (C99 6.7.5). |
1462 | unsigned VariablyModified : 1; |
1463 | |
1464 | /// Whether this type contains an unexpanded parameter pack |
1465 | /// (for C++11 variadic templates). |
1466 | unsigned ContainsUnexpandedParameterPack : 1; |
1467 | |
1468 | /// True if the cache (i.e. the bitfields here starting with |
1469 | /// 'Cache') is valid. |
1470 | mutable unsigned CacheValid : 1; |
1471 | |
1472 | /// Linkage of this type. |
1473 | mutable unsigned CachedLinkage : 3; |
1474 | |
1475 | /// Whether this type involves and local or unnamed types. |
1476 | mutable unsigned CachedLocalOrUnnamed : 1; |
1477 | |
1478 | /// Whether this type comes from an AST file. |
1479 | mutable unsigned FromAST : 1; |
1480 | |
1481 | bool isCacheValid() const { |
1482 | return CacheValid; |
1483 | } |
1484 | |
1485 | Linkage getLinkage() const { |
1486 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1486, __PRETTY_FUNCTION__)); |
1487 | return static_cast<Linkage>(CachedLinkage); |
1488 | } |
1489 | |
1490 | bool hasLocalOrUnnamedType() const { |
1491 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1491, __PRETTY_FUNCTION__)); |
1492 | return CachedLocalOrUnnamed; |
1493 | } |
1494 | }; |
1495 | enum { NumTypeBits = 18 }; |
1496 | |
1497 | protected: |
1498 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1499 | // into Type. |
1500 | |
1501 | class ArrayTypeBitfields { |
1502 | friend class ArrayType; |
1503 | |
1504 | unsigned : NumTypeBits; |
1505 | |
1506 | /// CVR qualifiers from declarations like |
1507 | /// 'int X[static restrict 4]'. For function parameters only. |
1508 | unsigned IndexTypeQuals : 3; |
1509 | |
1510 | /// Storage class qualifiers from declarations like |
1511 | /// 'int X[static restrict 4]'. For function parameters only. |
1512 | /// Actually an ArrayType::ArraySizeModifier. |
1513 | unsigned SizeModifier : 3; |
1514 | }; |
1515 | |
1516 | class BuiltinTypeBitfields { |
1517 | friend class BuiltinType; |
1518 | |
1519 | unsigned : NumTypeBits; |
1520 | |
1521 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1522 | unsigned Kind : 8; |
1523 | }; |
1524 | |
1525 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1526 | /// Only common bits are stored here. Additional uncommon bits are stored |
1527 | /// in a trailing object after FunctionProtoType. |
1528 | class FunctionTypeBitfields { |
1529 | friend class FunctionProtoType; |
1530 | friend class FunctionType; |
1531 | |
1532 | unsigned : NumTypeBits; |
1533 | |
1534 | /// Extra information which affects how the function is called, like |
1535 | /// regparm and the calling convention. |
1536 | unsigned ExtInfo : 12; |
1537 | |
1538 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1539 | /// |
1540 | /// This is a value of type \c RefQualifierKind. |
1541 | unsigned RefQualifier : 2; |
1542 | |
1543 | /// Used only by FunctionProtoType, put here to pack with the |
1544 | /// other bitfields. |
1545 | /// The qualifiers are part of FunctionProtoType because... |
1546 | /// |
1547 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1548 | /// cv-qualifier-seq, [...], are part of the function type. |
1549 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1550 | /// Whether this function has extended Qualifiers. |
1551 | unsigned HasExtQuals : 1; |
1552 | |
1553 | /// The number of parameters this function has, not counting '...'. |
1554 | /// According to [implimits] 8 bits should be enough here but this is |
1555 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1556 | /// keep NumParams as wide as reasonably possible. |
1557 | unsigned NumParams : 16; |
1558 | |
1559 | /// The type of exception specification this function has. |
1560 | unsigned ExceptionSpecType : 4; |
1561 | |
1562 | /// Whether this function has extended parameter information. |
1563 | unsigned HasExtParameterInfos : 1; |
1564 | |
1565 | /// Whether the function is variadic. |
1566 | unsigned Variadic : 1; |
1567 | |
1568 | /// Whether this function has a trailing return type. |
1569 | unsigned HasTrailingReturn : 1; |
1570 | }; |
1571 | |
1572 | class ObjCObjectTypeBitfields { |
1573 | friend class ObjCObjectType; |
1574 | |
1575 | unsigned : NumTypeBits; |
1576 | |
1577 | /// The number of type arguments stored directly on this object type. |
1578 | unsigned NumTypeArgs : 7; |
1579 | |
1580 | /// The number of protocols stored directly on this object type. |
1581 | unsigned NumProtocols : 6; |
1582 | |
1583 | /// Whether this is a "kindof" type. |
1584 | unsigned IsKindOf : 1; |
1585 | }; |
1586 | |
1587 | class ReferenceTypeBitfields { |
1588 | friend class ReferenceType; |
1589 | |
1590 | unsigned : NumTypeBits; |
1591 | |
1592 | /// True if the type was originally spelled with an lvalue sigil. |
1593 | /// This is never true of rvalue references but can also be false |
1594 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1595 | /// as follows: |
1596 | /// |
1597 | /// typedef int &ref; // lvalue, spelled lvalue |
1598 | /// typedef int &&rvref; // rvalue |
1599 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1600 | /// ref &&a; // lvalue, inner ref |
1601 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1602 | /// rvref &&a; // rvalue, inner ref |
1603 | unsigned SpelledAsLValue : 1; |
1604 | |
1605 | /// True if the inner type is a reference type. This only happens |
1606 | /// in non-canonical forms. |
1607 | unsigned InnerRef : 1; |
1608 | }; |
1609 | |
1610 | class TypeWithKeywordBitfields { |
1611 | friend class TypeWithKeyword; |
1612 | |
1613 | unsigned : NumTypeBits; |
1614 | |
1615 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1616 | unsigned Keyword : 8; |
1617 | }; |
1618 | |
1619 | enum { NumTypeWithKeywordBits = 8 }; |
1620 | |
1621 | class ElaboratedTypeBitfields { |
1622 | friend class ElaboratedType; |
1623 | |
1624 | unsigned : NumTypeBits; |
1625 | unsigned : NumTypeWithKeywordBits; |
1626 | |
1627 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1628 | unsigned HasOwnedTagDecl : 1; |
1629 | }; |
1630 | |
1631 | class VectorTypeBitfields { |
1632 | friend class VectorType; |
1633 | friend class DependentVectorType; |
1634 | |
1635 | unsigned : NumTypeBits; |
1636 | |
1637 | /// The kind of vector, either a generic vector type or some |
1638 | /// target-specific vector type such as for AltiVec or Neon. |
1639 | unsigned VecKind : 3; |
1640 | |
1641 | /// The number of elements in the vector. |
1642 | unsigned NumElements : 29 - NumTypeBits; |
1643 | |
1644 | enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 }; |
1645 | }; |
1646 | |
1647 | class AttributedTypeBitfields { |
1648 | friend class AttributedType; |
1649 | |
1650 | unsigned : NumTypeBits; |
1651 | |
1652 | /// An AttributedType::Kind |
1653 | unsigned AttrKind : 32 - NumTypeBits; |
1654 | }; |
1655 | |
1656 | class AutoTypeBitfields { |
1657 | friend class AutoType; |
1658 | |
1659 | unsigned : NumTypeBits; |
1660 | |
1661 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1662 | /// or '__auto_type'? AutoTypeKeyword value. |
1663 | unsigned Keyword : 2; |
1664 | }; |
1665 | |
1666 | class SubstTemplateTypeParmPackTypeBitfields { |
1667 | friend class SubstTemplateTypeParmPackType; |
1668 | |
1669 | unsigned : NumTypeBits; |
1670 | |
1671 | /// The number of template arguments in \c Arguments, which is |
1672 | /// expected to be able to hold at least 1024 according to [implimits]. |
1673 | /// However as this limit is somewhat easy to hit with template |
1674 | /// metaprogramming we'd prefer to keep it as large as possible. |
1675 | /// At the moment it has been left as a non-bitfield since this type |
1676 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1677 | /// introduce the performance impact of a bitfield. |
1678 | unsigned NumArgs; |
1679 | }; |
1680 | |
1681 | class TemplateSpecializationTypeBitfields { |
1682 | friend class TemplateSpecializationType; |
1683 | |
1684 | unsigned : NumTypeBits; |
1685 | |
1686 | /// Whether this template specialization type is a substituted type alias. |
1687 | unsigned TypeAlias : 1; |
1688 | |
1689 | /// The number of template arguments named in this class template |
1690 | /// specialization, which is expected to be able to hold at least 1024 |
1691 | /// according to [implimits]. However, as this limit is somewhat easy to |
1692 | /// hit with template metaprogramming we'd prefer to keep it as large |
1693 | /// as possible. At the moment it has been left as a non-bitfield since |
1694 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1695 | /// to introduce the performance impact of a bitfield. |
1696 | unsigned NumArgs; |
1697 | }; |
1698 | |
1699 | class DependentTemplateSpecializationTypeBitfields { |
1700 | friend class DependentTemplateSpecializationType; |
1701 | |
1702 | unsigned : NumTypeBits; |
1703 | unsigned : NumTypeWithKeywordBits; |
1704 | |
1705 | /// The number of template arguments named in this class template |
1706 | /// specialization, which is expected to be able to hold at least 1024 |
1707 | /// according to [implimits]. However, as this limit is somewhat easy to |
1708 | /// hit with template metaprogramming we'd prefer to keep it as large |
1709 | /// as possible. At the moment it has been left as a non-bitfield since |
1710 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1711 | /// to introduce the performance impact of a bitfield. |
1712 | unsigned NumArgs; |
1713 | }; |
1714 | |
1715 | class PackExpansionTypeBitfields { |
1716 | friend class PackExpansionType; |
1717 | |
1718 | unsigned : NumTypeBits; |
1719 | |
1720 | /// The number of expansions that this pack expansion will |
1721 | /// generate when substituted (+1), which is expected to be able to |
1722 | /// hold at least 1024 according to [implimits]. However, as this limit |
1723 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1724 | /// keep it as large as possible. At the moment it has been left as a |
1725 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1726 | /// there is no reason to introduce the performance impact of a bitfield. |
1727 | /// |
1728 | /// This field will only have a non-zero value when some of the parameter |
1729 | /// packs that occur within the pattern have been substituted but others |
1730 | /// have not. |
1731 | unsigned NumExpansions; |
1732 | }; |
1733 | |
1734 | union { |
1735 | TypeBitfields TypeBits; |
1736 | ArrayTypeBitfields ArrayTypeBits; |
1737 | AttributedTypeBitfields AttributedTypeBits; |
1738 | AutoTypeBitfields AutoTypeBits; |
1739 | BuiltinTypeBitfields BuiltinTypeBits; |
1740 | FunctionTypeBitfields FunctionTypeBits; |
1741 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1742 | ReferenceTypeBitfields ReferenceTypeBits; |
1743 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1744 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1745 | VectorTypeBitfields VectorTypeBits; |
1746 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1747 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1748 | DependentTemplateSpecializationTypeBitfields |
1749 | DependentTemplateSpecializationTypeBits; |
1750 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1751 | |
1752 | static_assert(sizeof(TypeBitfields) <= 8, |
1753 | "TypeBitfields is larger than 8 bytes!"); |
1754 | static_assert(sizeof(ArrayTypeBitfields) <= 8, |
1755 | "ArrayTypeBitfields is larger than 8 bytes!"); |
1756 | static_assert(sizeof(AttributedTypeBitfields) <= 8, |
1757 | "AttributedTypeBitfields is larger than 8 bytes!"); |
1758 | static_assert(sizeof(AutoTypeBitfields) <= 8, |
1759 | "AutoTypeBitfields is larger than 8 bytes!"); |
1760 | static_assert(sizeof(BuiltinTypeBitfields) <= 8, |
1761 | "BuiltinTypeBitfields is larger than 8 bytes!"); |
1762 | static_assert(sizeof(FunctionTypeBitfields) <= 8, |
1763 | "FunctionTypeBitfields is larger than 8 bytes!"); |
1764 | static_assert(sizeof(ObjCObjectTypeBitfields) <= 8, |
1765 | "ObjCObjectTypeBitfields is larger than 8 bytes!"); |
1766 | static_assert(sizeof(ReferenceTypeBitfields) <= 8, |
1767 | "ReferenceTypeBitfields is larger than 8 bytes!"); |
1768 | static_assert(sizeof(TypeWithKeywordBitfields) <= 8, |
1769 | "TypeWithKeywordBitfields is larger than 8 bytes!"); |
1770 | static_assert(sizeof(ElaboratedTypeBitfields) <= 8, |
1771 | "ElaboratedTypeBitfields is larger than 8 bytes!"); |
1772 | static_assert(sizeof(VectorTypeBitfields) <= 8, |
1773 | "VectorTypeBitfields is larger than 8 bytes!"); |
1774 | static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8, |
1775 | "SubstTemplateTypeParmPackTypeBitfields is larger" |
1776 | " than 8 bytes!"); |
1777 | static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8, |
1778 | "TemplateSpecializationTypeBitfields is larger" |
1779 | " than 8 bytes!"); |
1780 | static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8, |
1781 | "DependentTemplateSpecializationTypeBitfields is larger" |
1782 | " than 8 bytes!"); |
1783 | static_assert(sizeof(PackExpansionTypeBitfields) <= 8, |
1784 | "PackExpansionTypeBitfields is larger than 8 bytes"); |
1785 | }; |
1786 | |
1787 | private: |
1788 | template <class T> friend class TypePropertyCache; |
1789 | |
1790 | /// Set whether this type comes from an AST file. |
1791 | void setFromAST(bool V = true) const { |
1792 | TypeBits.FromAST = V; |
1793 | } |
1794 | |
1795 | protected: |
1796 | friend class ASTContext; |
1797 | |
1798 | Type(TypeClass tc, QualType canon, bool Dependent, |
1799 | bool InstantiationDependent, bool VariablyModified, |
1800 | bool ContainsUnexpandedParameterPack) |
1801 | : ExtQualsTypeCommonBase(this, |
1802 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1803 | TypeBits.TC = tc; |
1804 | TypeBits.Dependent = Dependent; |
1805 | TypeBits.InstantiationDependent = Dependent || InstantiationDependent; |
1806 | TypeBits.VariablyModified = VariablyModified; |
1807 | TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; |
1808 | TypeBits.CacheValid = false; |
1809 | TypeBits.CachedLocalOrUnnamed = false; |
1810 | TypeBits.CachedLinkage = NoLinkage; |
1811 | TypeBits.FromAST = false; |
1812 | } |
1813 | |
1814 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1815 | Type *this_() { return this; } |
1816 | |
1817 | void setDependent(bool D = true) { |
1818 | TypeBits.Dependent = D; |
1819 | if (D) |
1820 | TypeBits.InstantiationDependent = true; |
1821 | } |
1822 | |
1823 | void setInstantiationDependent(bool D = true) { |
1824 | TypeBits.InstantiationDependent = D; } |
1825 | |
1826 | void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; } |
1827 | |
1828 | void setContainsUnexpandedParameterPack(bool PP = true) { |
1829 | TypeBits.ContainsUnexpandedParameterPack = PP; |
1830 | } |
1831 | |
1832 | public: |
1833 | friend class ASTReader; |
1834 | friend class ASTWriter; |
1835 | |
1836 | Type(const Type &) = delete; |
1837 | Type(Type &&) = delete; |
1838 | Type &operator=(const Type &) = delete; |
1839 | Type &operator=(Type &&) = delete; |
1840 | |
1841 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1842 | |
1843 | /// Whether this type comes from an AST file. |
1844 | bool isFromAST() const { return TypeBits.FromAST; } |
1845 | |
1846 | /// Whether this type is or contains an unexpanded parameter |
1847 | /// pack, used to support C++0x variadic templates. |
1848 | /// |
1849 | /// A type that contains a parameter pack shall be expanded by the |
1850 | /// ellipsis operator at some point. For example, the typedef in the |
1851 | /// following example contains an unexpanded parameter pack 'T': |
1852 | /// |
1853 | /// \code |
1854 | /// template<typename ...T> |
1855 | /// struct X { |
1856 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1857 | /// }; |
1858 | /// \endcode |
1859 | /// |
1860 | /// Note that this routine does not specify which |
1861 | bool containsUnexpandedParameterPack() const { |
1862 | return TypeBits.ContainsUnexpandedParameterPack; |
1863 | } |
1864 | |
1865 | /// Determines if this type would be canonical if it had no further |
1866 | /// qualification. |
1867 | bool isCanonicalUnqualified() const { |
1868 | return CanonicalType == QualType(this, 0); |
1869 | } |
1870 | |
1871 | /// Pull a single level of sugar off of this locally-unqualified type. |
1872 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1873 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1874 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1875 | |
1876 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1877 | /// object types, function types, and incomplete types. |
1878 | |
1879 | /// Return true if this is an incomplete type. |
1880 | /// A type that can describe objects, but which lacks information needed to |
1881 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1882 | /// routine will need to determine if the size is actually required. |
1883 | /// |
1884 | /// Def If non-null, and the type refers to some kind of declaration |
1885 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1886 | /// class), will be set to the declaration. |
1887 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1888 | |
1889 | /// Return true if this is an incomplete or object |
1890 | /// type, in other words, not a function type. |
1891 | bool isIncompleteOrObjectType() const { |
1892 | return !isFunctionType(); |
1893 | } |
1894 | |
1895 | /// Determine whether this type is an object type. |
1896 | bool isObjectType() const { |
1897 | // C++ [basic.types]p8: |
1898 | // An object type is a (possibly cv-qualified) type that is not a |
1899 | // function type, not a reference type, and not a void type. |
1900 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1901 | } |
1902 | |
1903 | /// Return true if this is a literal type |
1904 | /// (C++11 [basic.types]p10) |
1905 | bool isLiteralType(const ASTContext &Ctx) const; |
1906 | |
1907 | /// Test if this type is a standard-layout type. |
1908 | /// (C++0x [basic.type]p9) |
1909 | bool isStandardLayoutType() const; |
1910 | |
1911 | /// Helper methods to distinguish type categories. All type predicates |
1912 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1913 | |
1914 | /// Returns true if the type is a builtin type. |
1915 | bool isBuiltinType() const; |
1916 | |
1917 | /// Test for a particular builtin type. |
1918 | bool isSpecificBuiltinType(unsigned K) const; |
1919 | |
1920 | /// Test for a type which does not represent an actual type-system type but |
1921 | /// is instead used as a placeholder for various convenient purposes within |
1922 | /// Clang. All such types are BuiltinTypes. |
1923 | bool isPlaceholderType() const; |
1924 | const BuiltinType *getAsPlaceholderType() const; |
1925 | |
1926 | /// Test for a specific placeholder type. |
1927 | bool isSpecificPlaceholderType(unsigned K) const; |
1928 | |
1929 | /// Test for a placeholder type other than Overload; see |
1930 | /// BuiltinType::isNonOverloadPlaceholderType. |
1931 | bool isNonOverloadPlaceholderType() const; |
1932 | |
1933 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1934 | /// isComplexIntegerType() can be used to test for complex integers. |
1935 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1936 | bool isEnumeralType() const; |
1937 | |
1938 | /// Determine whether this type is a scoped enumeration type. |
1939 | bool isScopedEnumeralType() const; |
1940 | bool isBooleanType() const; |
1941 | bool isCharType() const; |
1942 | bool isWideCharType() const; |
1943 | bool isChar8Type() const; |
1944 | bool isChar16Type() const; |
1945 | bool isChar32Type() const; |
1946 | bool isAnyCharacterType() const; |
1947 | bool isIntegralType(const ASTContext &Ctx) const; |
1948 | |
1949 | /// Determine whether this type is an integral or enumeration type. |
1950 | bool isIntegralOrEnumerationType() const; |
1951 | |
1952 | /// Determine whether this type is an integral or unscoped enumeration type. |
1953 | bool isIntegralOrUnscopedEnumerationType() const; |
1954 | |
1955 | /// Floating point categories. |
1956 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1957 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1958 | /// isComplexIntegerType() can be used to test for complex integers. |
1959 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1960 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1961 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1962 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1963 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1964 | bool isFloat128Type() const; |
1965 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1966 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1967 | bool isVoidType() const; // C99 6.2.5p19 |
1968 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1969 | bool isAggregateType() const; |
1970 | bool isFundamentalType() const; |
1971 | bool isCompoundType() const; |
1972 | |
1973 | // Type Predicates: Check to see if this type is structurally the specified |
1974 | // type, ignoring typedefs and qualifiers. |
1975 | bool isFunctionType() const; |
1976 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
1977 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
1978 | bool isPointerType() const; |
1979 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
1980 | bool isBlockPointerType() const; |
1981 | bool isVoidPointerType() const; |
1982 | bool isReferenceType() const; |
1983 | bool isLValueReferenceType() const; |
1984 | bool isRValueReferenceType() const; |
1985 | bool isFunctionPointerType() const; |
1986 | bool isFunctionReferenceType() const; |
1987 | bool isMemberPointerType() const; |
1988 | bool isMemberFunctionPointerType() const; |
1989 | bool isMemberDataPointerType() const; |
1990 | bool isArrayType() const; |
1991 | bool isConstantArrayType() const; |
1992 | bool isIncompleteArrayType() const; |
1993 | bool isVariableArrayType() const; |
1994 | bool isDependentSizedArrayType() const; |
1995 | bool isRecordType() const; |
1996 | bool isClassType() const; |
1997 | bool isStructureType() const; |
1998 | bool isObjCBoxableRecordType() const; |
1999 | bool isInterfaceType() const; |
2000 | bool isStructureOrClassType() const; |
2001 | bool isUnionType() const; |
2002 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2003 | bool isVectorType() const; // GCC vector type. |
2004 | bool isExtVectorType() const; // Extended vector type. |
2005 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2006 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2007 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2008 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2009 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2010 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2011 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2012 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2013 | // for the common case. |
2014 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2015 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2016 | bool isObjCQualifiedIdType() const; // id<foo> |
2017 | bool isObjCQualifiedClassType() const; // Class<foo> |
2018 | bool isObjCObjectOrInterfaceType() const; |
2019 | bool isObjCIdType() const; // id |
2020 | bool isDecltypeType() const; |
2021 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2022 | /// qualifier? |
2023 | /// |
2024 | /// This approximates the answer to the following question: if this |
2025 | /// translation unit were compiled in ARC, would this type be qualified |
2026 | /// with __unsafe_unretained? |
2027 | bool isObjCInertUnsafeUnretainedType() const { |
2028 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2029 | } |
2030 | |
2031 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2032 | /// object type, e.g., __kindof NSView * or __kindof id |
2033 | /// <NSCopying>. |
2034 | /// |
2035 | /// \param bound Will be set to the bound on non-id subtype types, |
2036 | /// which will be (possibly specialized) Objective-C class type, or |
2037 | /// null for 'id. |
2038 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2039 | const ObjCObjectType *&bound) const; |
2040 | |
2041 | bool isObjCClassType() const; // Class |
2042 | |
2043 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2044 | /// Class type, e.g., __kindof Class <NSCopying>. |
2045 | /// |
2046 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2047 | /// here because Objective-C's type system cannot express "a class |
2048 | /// object for a subclass of NSFoo". |
2049 | bool isObjCClassOrClassKindOfType() const; |
2050 | |
2051 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2052 | bool isObjCSelType() const; // Class |
2053 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2054 | bool isObjCARCBridgableType() const; |
2055 | bool isCARCBridgableType() const; |
2056 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2057 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2058 | bool isNothrowT() const; // C++ std::nothrow_t |
2059 | bool isAlignValT() const; // C++17 std::align_val_t |
2060 | bool isStdByteType() const; // C++17 std::byte |
2061 | bool isAtomicType() const; // C11 _Atomic() |
2062 | |
2063 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2064 | bool is##Id##Type() const; |
2065 | #include "clang/Basic/OpenCLImageTypes.def" |
2066 | |
2067 | bool isImageType() const; // Any OpenCL image type |
2068 | |
2069 | bool isSamplerT() const; // OpenCL sampler_t |
2070 | bool isEventT() const; // OpenCL event_t |
2071 | bool isClkEventT() const; // OpenCL clk_event_t |
2072 | bool isQueueT() const; // OpenCL queue_t |
2073 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2074 | |
2075 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2076 | bool is##Id##Type() const; |
2077 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2078 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2079 | bool isOCLIntelSubgroupAVCType() const; |
2080 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2081 | |
2082 | bool isPipeType() const; // OpenCL pipe type |
2083 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2084 | |
2085 | /// Determines if this type, which must satisfy |
2086 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2087 | /// than implicitly __strong. |
2088 | bool isObjCARCImplicitlyUnretainedType() const; |
2089 | |
2090 | /// Return the implicit lifetime for this type, which must not be dependent. |
2091 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2092 | |
2093 | enum ScalarTypeKind { |
2094 | STK_CPointer, |
2095 | STK_BlockPointer, |
2096 | STK_ObjCObjectPointer, |
2097 | STK_MemberPointer, |
2098 | STK_Bool, |
2099 | STK_Integral, |
2100 | STK_Floating, |
2101 | STK_IntegralComplex, |
2102 | STK_FloatingComplex, |
2103 | STK_FixedPoint |
2104 | }; |
2105 | |
2106 | /// Given that this is a scalar type, classify it. |
2107 | ScalarTypeKind getScalarTypeKind() const; |
2108 | |
2109 | /// Whether this type is a dependent type, meaning that its definition |
2110 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2111 | bool isDependentType() const { return TypeBits.Dependent; } |
2112 | |
2113 | /// Determine whether this type is an instantiation-dependent type, |
2114 | /// meaning that the type involves a template parameter (even if the |
2115 | /// definition does not actually depend on the type substituted for that |
2116 | /// template parameter). |
2117 | bool isInstantiationDependentType() const { |
2118 | return TypeBits.InstantiationDependent; |
2119 | } |
2120 | |
2121 | /// Determine whether this type is an undeduced type, meaning that |
2122 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2123 | /// deduced. |
2124 | bool isUndeducedType() const; |
2125 | |
2126 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2127 | bool isVariablyModifiedType() const { return TypeBits.VariablyModified; } |
2128 | |
2129 | /// Whether this type involves a variable-length array type |
2130 | /// with a definite size. |
2131 | bool hasSizedVLAType() const; |
2132 | |
2133 | /// Whether this type is or contains a local or unnamed type. |
2134 | bool hasUnnamedOrLocalType() const; |
2135 | |
2136 | bool isOverloadableType() const; |
2137 | |
2138 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2139 | bool isElaboratedTypeSpecifier() const; |
2140 | |
2141 | bool canDecayToPointerType() const; |
2142 | |
2143 | /// Whether this type is represented natively as a pointer. This includes |
2144 | /// pointers, references, block pointers, and Objective-C interface, |
2145 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2146 | bool hasPointerRepresentation() const; |
2147 | |
2148 | /// Whether this type can represent an objective pointer type for the |
2149 | /// purpose of GC'ability |
2150 | bool hasObjCPointerRepresentation() const; |
2151 | |
2152 | /// Determine whether this type has an integer representation |
2153 | /// of some sort, e.g., it is an integer type or a vector. |
2154 | bool hasIntegerRepresentation() const; |
2155 | |
2156 | /// Determine whether this type has an signed integer representation |
2157 | /// of some sort, e.g., it is an signed integer type or a vector. |
2158 | bool hasSignedIntegerRepresentation() const; |
2159 | |
2160 | /// Determine whether this type has an unsigned integer representation |
2161 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2162 | bool hasUnsignedIntegerRepresentation() const; |
2163 | |
2164 | /// Determine whether this type has a floating-point representation |
2165 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2166 | bool hasFloatingRepresentation() const; |
2167 | |
2168 | // Type Checking Functions: Check to see if this type is structurally the |
2169 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2170 | // the best type we can. |
2171 | const RecordType *getAsStructureType() const; |
2172 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2173 | const RecordType *getAsUnionType() const; |
2174 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2175 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2176 | |
2177 | // The following is a convenience method that returns an ObjCObjectPointerType |
2178 | // for object declared using an interface. |
2179 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2180 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2181 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2182 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2183 | |
2184 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2185 | /// because the type is a RecordType or because it is the injected-class-name |
2186 | /// type of a class template or class template partial specialization. |
2187 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2188 | |
2189 | /// Retrieves the RecordDecl this type refers to. |
2190 | RecordDecl *getAsRecordDecl() const; |
2191 | |
2192 | /// Retrieves the TagDecl that this type refers to, either |
2193 | /// because the type is a TagType or because it is the injected-class-name |
2194 | /// type of a class template or class template partial specialization. |
2195 | TagDecl *getAsTagDecl() const; |
2196 | |
2197 | /// If this is a pointer or reference to a RecordType, return the |
2198 | /// CXXRecordDecl that the type refers to. |
2199 | /// |
2200 | /// If this is not a pointer or reference, or the type being pointed to does |
2201 | /// not refer to a CXXRecordDecl, returns NULL. |
2202 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2203 | |
2204 | /// Get the DeducedType whose type will be deduced for a variable with |
2205 | /// an initializer of this type. This looks through declarators like pointer |
2206 | /// types, but not through decltype or typedefs. |
2207 | DeducedType *getContainedDeducedType() const; |
2208 | |
2209 | /// Get the AutoType whose type will be deduced for a variable with |
2210 | /// an initializer of this type. This looks through declarators like pointer |
2211 | /// types, but not through decltype or typedefs. |
2212 | AutoType *getContainedAutoType() const { |
2213 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2214 | } |
2215 | |
2216 | /// Determine whether this type was written with a leading 'auto' |
2217 | /// corresponding to a trailing return type (possibly for a nested |
2218 | /// function type within a pointer to function type or similar). |
2219 | bool hasAutoForTrailingReturnType() const; |
2220 | |
2221 | /// Member-template getAs<specific type>'. Look through sugar for |
2222 | /// an instance of \<specific type>. This scheme will eventually |
2223 | /// replace the specific getAsXXXX methods above. |
2224 | /// |
2225 | /// There are some specializations of this member template listed |
2226 | /// immediately following this class. |
2227 | template <typename T> const T *getAs() const; |
2228 | |
2229 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2230 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2231 | /// This is used when you need to walk over sugar nodes that represent some |
2232 | /// kind of type adjustment from a type that was written as a \<specific type> |
2233 | /// to another type that is still canonically a \<specific type>. |
2234 | template <typename T> const T *getAsAdjusted() const; |
2235 | |
2236 | /// A variant of getAs<> for array types which silently discards |
2237 | /// qualifiers from the outermost type. |
2238 | const ArrayType *getAsArrayTypeUnsafe() const; |
2239 | |
2240 | /// Member-template castAs<specific type>. Look through sugar for |
2241 | /// the underlying instance of \<specific type>. |
2242 | /// |
2243 | /// This method has the same relationship to getAs<T> as cast<T> has |
2244 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2245 | /// have the intended type, and this method will never return null. |
2246 | template <typename T> const T *castAs() const; |
2247 | |
2248 | /// A variant of castAs<> for array type which silently discards |
2249 | /// qualifiers from the outermost type. |
2250 | const ArrayType *castAsArrayTypeUnsafe() const; |
2251 | |
2252 | /// Determine whether this type had the specified attribute applied to it |
2253 | /// (looking through top-level type sugar). |
2254 | bool hasAttr(attr::Kind AK) const; |
2255 | |
2256 | /// Get the base element type of this type, potentially discarding type |
2257 | /// qualifiers. This should never be used when type qualifiers |
2258 | /// are meaningful. |
2259 | const Type *getBaseElementTypeUnsafe() const; |
2260 | |
2261 | /// If this is an array type, return the element type of the array, |
2262 | /// potentially with type qualifiers missing. |
2263 | /// This should never be used when type qualifiers are meaningful. |
2264 | const Type *getArrayElementTypeNoTypeQual() const; |
2265 | |
2266 | /// If this is a pointer type, return the pointee type. |
2267 | /// If this is an array type, return the array element type. |
2268 | /// This should never be used when type qualifiers are meaningful. |
2269 | const Type *getPointeeOrArrayElementType() const; |
2270 | |
2271 | /// If this is a pointer, ObjC object pointer, or block |
2272 | /// pointer, this returns the respective pointee. |
2273 | QualType getPointeeType() const; |
2274 | |
2275 | /// Return the specified type with any "sugar" removed from the type, |
2276 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2277 | const Type *getUnqualifiedDesugaredType() const; |
2278 | |
2279 | /// More type predicates useful for type checking/promotion |
2280 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2281 | |
2282 | /// Return true if this is an integer type that is |
2283 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2284 | /// or an enum decl which has a signed representation. |
2285 | bool isSignedIntegerType() const; |
2286 | |
2287 | /// Return true if this is an integer type that is |
2288 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2289 | /// or an enum decl which has an unsigned representation. |
2290 | bool isUnsignedIntegerType() const; |
2291 | |
2292 | /// Determines whether this is an integer type that is signed or an |
2293 | /// enumeration types whose underlying type is a signed integer type. |
2294 | bool isSignedIntegerOrEnumerationType() const; |
2295 | |
2296 | /// Determines whether this is an integer type that is unsigned or an |
2297 | /// enumeration types whose underlying type is a unsigned integer type. |
2298 | bool isUnsignedIntegerOrEnumerationType() const; |
2299 | |
2300 | /// Return true if this is a fixed point type according to |
2301 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2302 | bool isFixedPointType() const; |
2303 | |
2304 | /// Return true if this is a fixed point or integer type. |
2305 | bool isFixedPointOrIntegerType() const; |
2306 | |
2307 | /// Return true if this is a saturated fixed point type according to |
2308 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2309 | bool isSaturatedFixedPointType() const; |
2310 | |
2311 | /// Return true if this is a saturated fixed point type according to |
2312 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2313 | bool isUnsaturatedFixedPointType() const; |
2314 | |
2315 | /// Return true if this is a fixed point type that is signed according |
2316 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2317 | bool isSignedFixedPointType() const; |
2318 | |
2319 | /// Return true if this is a fixed point type that is unsigned according |
2320 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2321 | bool isUnsignedFixedPointType() const; |
2322 | |
2323 | /// Return true if this is not a variable sized type, |
2324 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2325 | /// incomplete types. |
2326 | bool isConstantSizeType() const; |
2327 | |
2328 | /// Returns true if this type can be represented by some |
2329 | /// set of type specifiers. |
2330 | bool isSpecifierType() const; |
2331 | |
2332 | /// Determine the linkage of this type. |
2333 | Linkage getLinkage() const; |
2334 | |
2335 | /// Determine the visibility of this type. |
2336 | Visibility getVisibility() const { |
2337 | return getLinkageAndVisibility().getVisibility(); |
2338 | } |
2339 | |
2340 | /// Return true if the visibility was explicitly set is the code. |
2341 | bool isVisibilityExplicit() const { |
2342 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2343 | } |
2344 | |
2345 | /// Determine the linkage and visibility of this type. |
2346 | LinkageInfo getLinkageAndVisibility() const; |
2347 | |
2348 | /// True if the computed linkage is valid. Used for consistency |
2349 | /// checking. Should always return true. |
2350 | bool isLinkageValid() const; |
2351 | |
2352 | /// Determine the nullability of the given type. |
2353 | /// |
2354 | /// Note that nullability is only captured as sugar within the type |
2355 | /// system, not as part of the canonical type, so nullability will |
2356 | /// be lost by canonicalization and desugaring. |
2357 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2358 | |
2359 | /// Determine whether the given type can have a nullability |
2360 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2361 | /// |
2362 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2363 | /// this type can have nullability because it is dependent. |
2364 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2365 | |
2366 | /// Retrieve the set of substitutions required when accessing a member |
2367 | /// of the Objective-C receiver type that is declared in the given context. |
2368 | /// |
2369 | /// \c *this is the type of the object we're operating on, e.g., the |
2370 | /// receiver for a message send or the base of a property access, and is |
2371 | /// expected to be of some object or object pointer type. |
2372 | /// |
2373 | /// \param dc The declaration context for which we are building up a |
2374 | /// substitution mapping, which should be an Objective-C class, extension, |
2375 | /// category, or method within. |
2376 | /// |
2377 | /// \returns an array of type arguments that can be substituted for |
2378 | /// the type parameters of the given declaration context in any type described |
2379 | /// within that context, or an empty optional to indicate that no |
2380 | /// substitution is required. |
2381 | Optional<ArrayRef<QualType>> |
2382 | getObjCSubstitutions(const DeclContext *dc) const; |
2383 | |
2384 | /// Determines if this is an ObjC interface type that may accept type |
2385 | /// parameters. |
2386 | bool acceptsObjCTypeParams() const; |
2387 | |
2388 | const char *getTypeClassName() const; |
2389 | |
2390 | QualType getCanonicalTypeInternal() const { |
2391 | return CanonicalType; |
2392 | } |
2393 | |
2394 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2395 | void dump() const; |
2396 | void dump(llvm::raw_ostream &OS) const; |
2397 | }; |
2398 | |
2399 | /// This will check for a TypedefType by removing any existing sugar |
2400 | /// until it reaches a TypedefType or a non-sugared type. |
2401 | template <> const TypedefType *Type::getAs() const; |
2402 | |
2403 | /// This will check for a TemplateSpecializationType by removing any |
2404 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2405 | /// non-sugared type. |
2406 | template <> const TemplateSpecializationType *Type::getAs() const; |
2407 | |
2408 | /// This will check for an AttributedType by removing any existing sugar |
2409 | /// until it reaches an AttributedType or a non-sugared type. |
2410 | template <> const AttributedType *Type::getAs() const; |
2411 | |
2412 | // We can do canonical leaf types faster, because we don't have to |
2413 | // worry about preserving child type decoration. |
2414 | #define TYPE(Class, Base) |
2415 | #define LEAF_TYPE(Class) \ |
2416 | template <> inline const Class##Type *Type::getAs() const { \ |
2417 | return dyn_cast<Class##Type>(CanonicalType); \ |
2418 | } \ |
2419 | template <> inline const Class##Type *Type::castAs() const { \ |
2420 | return cast<Class##Type>(CanonicalType); \ |
2421 | } |
2422 | #include "clang/AST/TypeNodes.inc" |
2423 | |
2424 | /// This class is used for builtin types like 'int'. Builtin |
2425 | /// types are always canonical and have a literal name field. |
2426 | class BuiltinType : public Type { |
2427 | public: |
2428 | enum Kind { |
2429 | // OpenCL image types |
2430 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2431 | #include "clang/Basic/OpenCLImageTypes.def" |
2432 | // OpenCL extension types |
2433 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2434 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2435 | // SVE Types |
2436 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2437 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2438 | // All other builtin types |
2439 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2440 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2441 | #include "clang/AST/BuiltinTypes.def" |
2442 | }; |
2443 | |
2444 | private: |
2445 | friend class ASTContext; // ASTContext creates these. |
2446 | |
2447 | BuiltinType(Kind K) |
2448 | : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent), |
2449 | /*InstantiationDependent=*/(K == Dependent), |
2450 | /*VariablyModified=*/false, |
2451 | /*Unexpanded parameter pack=*/false) { |
2452 | BuiltinTypeBits.Kind = K; |
2453 | } |
2454 | |
2455 | public: |
2456 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2457 | StringRef getName(const PrintingPolicy &Policy) const; |
2458 | |
2459 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2460 | // The StringRef is null-terminated. |
2461 | StringRef str = getName(Policy); |
2462 | assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast <void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 2462, __PRETTY_FUNCTION__)); |
2463 | return str.data(); |
2464 | } |
2465 | |
2466 | bool isSugared() const { return false; } |
2467 | QualType desugar() const { return QualType(this, 0); } |
2468 | |
2469 | bool isInteger() const { |
2470 | return getKind() >= Bool && getKind() <= Int128; |
2471 | } |
2472 | |
2473 | bool isSignedInteger() const { |
2474 | return getKind() >= Char_S && getKind() <= Int128; |
2475 | } |
2476 | |
2477 | bool isUnsignedInteger() const { |
2478 | return getKind() >= Bool && getKind() <= UInt128; |
2479 | } |
2480 | |
2481 | bool isFloatingPoint() const { |
2482 | return getKind() >= Half && getKind() <= Float128; |
2483 | } |
2484 | |
2485 | /// Determines whether the given kind corresponds to a placeholder type. |
2486 | static bool isPlaceholderTypeKind(Kind K) { |
2487 | return K >= Overload; |
2488 | } |
2489 | |
2490 | /// Determines whether this type is a placeholder type, i.e. a type |
2491 | /// which cannot appear in arbitrary positions in a fully-formed |
2492 | /// expression. |
2493 | bool isPlaceholderType() const { |
2494 | return isPlaceholderTypeKind(getKind()); |
2495 | } |
2496 | |
2497 | /// Determines whether this type is a placeholder type other than |
2498 | /// Overload. Most placeholder types require only syntactic |
2499 | /// information about their context in order to be resolved (e.g. |
2500 | /// whether it is a call expression), which means they can (and |
2501 | /// should) be resolved in an earlier "phase" of analysis. |
2502 | /// Overload expressions sometimes pick up further information |
2503 | /// from their context, like whether the context expects a |
2504 | /// specific function-pointer type, and so frequently need |
2505 | /// special treatment. |
2506 | bool isNonOverloadPlaceholderType() const { |
2507 | return getKind() > Overload; |
2508 | } |
2509 | |
2510 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2511 | }; |
2512 | |
2513 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2514 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2515 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2516 | friend class ASTContext; // ASTContext creates these. |
2517 | |
2518 | QualType ElementType; |
2519 | |
2520 | ComplexType(QualType Element, QualType CanonicalPtr) |
2521 | : Type(Complex, CanonicalPtr, Element->isDependentType(), |
2522 | Element->isInstantiationDependentType(), |
2523 | Element->isVariablyModifiedType(), |
2524 | Element->containsUnexpandedParameterPack()), |
2525 | ElementType(Element) {} |
2526 | |
2527 | public: |
2528 | QualType getElementType() const { return ElementType; } |
2529 | |
2530 | bool isSugared() const { return false; } |
2531 | QualType desugar() const { return QualType(this, 0); } |
2532 | |
2533 | void Profile(llvm::FoldingSetNodeID &ID) { |
2534 | Profile(ID, getElementType()); |
2535 | } |
2536 | |
2537 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2538 | ID.AddPointer(Element.getAsOpaquePtr()); |
2539 | } |
2540 | |
2541 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2542 | }; |
2543 | |
2544 | /// Sugar for parentheses used when specifying types. |
2545 | class ParenType : public Type, public llvm::FoldingSetNode { |
2546 | friend class ASTContext; // ASTContext creates these. |
2547 | |
2548 | QualType Inner; |
2549 | |
2550 | ParenType(QualType InnerType, QualType CanonType) |
2551 | : Type(Paren, CanonType, InnerType->isDependentType(), |
2552 | InnerType->isInstantiationDependentType(), |
2553 | InnerType->isVariablyModifiedType(), |
2554 | InnerType->containsUnexpandedParameterPack()), |
2555 | Inner(InnerType) {} |
2556 | |
2557 | public: |
2558 | QualType getInnerType() const { return Inner; } |
2559 | |
2560 | bool isSugared() const { return true; } |
2561 | QualType desugar() const { return getInnerType(); } |
2562 | |
2563 | void Profile(llvm::FoldingSetNodeID &ID) { |
2564 | Profile(ID, getInnerType()); |
2565 | } |
2566 | |
2567 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2568 | Inner.Profile(ID); |
2569 | } |
2570 | |
2571 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2572 | }; |
2573 | |
2574 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2575 | class PointerType : public Type, public llvm::FoldingSetNode { |
2576 | friend class ASTContext; // ASTContext creates these. |
2577 | |
2578 | QualType PointeeType; |
2579 | |
2580 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2581 | : Type(Pointer, CanonicalPtr, Pointee->isDependentType(), |
2582 | Pointee->isInstantiationDependentType(), |
2583 | Pointee->isVariablyModifiedType(), |
2584 | Pointee->containsUnexpandedParameterPack()), |
2585 | PointeeType(Pointee) {} |
2586 | |
2587 | public: |
2588 | QualType getPointeeType() const { return PointeeType; } |
2589 | |
2590 | /// Returns true if address spaces of pointers overlap. |
2591 | /// OpenCL v2.0 defines conversion rules for pointers to different |
2592 | /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping |
2593 | /// address spaces. |
2594 | /// CL1.1 or CL1.2: |
2595 | /// address spaces overlap iff they are they same. |
2596 | /// CL2.0 adds: |
2597 | /// __generic overlaps with any address space except for __constant. |
2598 | bool isAddressSpaceOverlapping(const PointerType &other) const { |
2599 | Qualifiers thisQuals = PointeeType.getQualifiers(); |
2600 | Qualifiers otherQuals = other.getPointeeType().getQualifiers(); |
2601 | // Address spaces overlap if at least one of them is a superset of another |
2602 | return thisQuals.isAddressSpaceSupersetOf(otherQuals) || |
2603 | otherQuals.isAddressSpaceSupersetOf(thisQuals); |
2604 | } |
2605 | |
2606 | bool isSugared() const { return false; } |
2607 | QualType desugar() const { return QualType(this, 0); } |
2608 | |
2609 | void Profile(llvm::FoldingSetNodeID &ID) { |
2610 | Profile(ID, getPointeeType()); |
2611 | } |
2612 | |
2613 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2614 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2615 | } |
2616 | |
2617 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2618 | }; |
2619 | |
2620 | /// Represents a type which was implicitly adjusted by the semantic |
2621 | /// engine for arbitrary reasons. For example, array and function types can |
2622 | /// decay, and function types can have their calling conventions adjusted. |
2623 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2624 | QualType OriginalTy; |
2625 | QualType AdjustedTy; |
2626 | |
2627 | protected: |
2628 | friend class ASTContext; // ASTContext creates these. |
2629 | |
2630 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2631 | QualType CanonicalPtr) |
2632 | : Type(TC, CanonicalPtr, OriginalTy->isDependentType(), |
2633 | OriginalTy->isInstantiationDependentType(), |
2634 | OriginalTy->isVariablyModifiedType(), |
2635 | OriginalTy->containsUnexpandedParameterPack()), |
2636 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2637 | |
2638 | public: |
2639 | QualType getOriginalType() const { return OriginalTy; } |
2640 | QualType getAdjustedType() const { return AdjustedTy; } |
2641 | |
2642 | bool isSugared() const { return true; } |
2643 | QualType desugar() const { return AdjustedTy; } |
2644 | |
2645 | void Profile(llvm::FoldingSetNodeID &ID) { |
2646 | Profile(ID, OriginalTy, AdjustedTy); |
2647 | } |
2648 | |
2649 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2650 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2651 | ID.AddPointer(New.getAsOpaquePtr()); |
2652 | } |
2653 | |
2654 | static bool classof(const Type *T) { |
2655 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2656 | } |
2657 | }; |
2658 | |
2659 | /// Represents a pointer type decayed from an array or function type. |
2660 | class DecayedType : public AdjustedType { |
2661 | friend class ASTContext; // ASTContext creates these. |
2662 | |
2663 | inline |
2664 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2665 | |
2666 | public: |
2667 | QualType getDecayedType() const { return getAdjustedType(); } |
2668 | |
2669 | inline QualType getPointeeType() const; |
2670 | |
2671 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2672 | }; |
2673 | |
2674 | /// Pointer to a block type. |
2675 | /// This type is to represent types syntactically represented as |
2676 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2677 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2678 | friend class ASTContext; // ASTContext creates these. |
2679 | |
2680 | // Block is some kind of pointer type |
2681 | QualType PointeeType; |
2682 | |
2683 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2684 | : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(), |
2685 | Pointee->isInstantiationDependentType(), |
2686 | Pointee->isVariablyModifiedType(), |
2687 | Pointee->containsUnexpandedParameterPack()), |
2688 | PointeeType(Pointee) {} |
2689 | |
2690 | public: |
2691 | // Get the pointee type. Pointee is required to always be a function type. |
2692 | QualType getPointeeType() const { return PointeeType; } |
2693 | |
2694 | bool isSugared() const { return false; } |
2695 | QualType desugar() const { return QualType(this, 0); } |
2696 | |
2697 | void Profile(llvm::FoldingSetNodeID &ID) { |
2698 | Profile(ID, getPointeeType()); |
2699 | } |
2700 | |
2701 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2702 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2703 | } |
2704 | |
2705 | static bool classof(const Type *T) { |
2706 | return T->getTypeClass() == BlockPointer; |
2707 | } |
2708 | }; |
2709 | |
2710 | /// Base for LValueReferenceType and RValueReferenceType |
2711 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2712 | QualType PointeeType; |
2713 | |
2714 | protected: |
2715 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2716 | bool SpelledAsLValue) |
2717 | : Type(tc, CanonicalRef, Referencee->isDependentType(), |
2718 | Referencee->isInstantiationDependentType(), |
2719 | Referencee->isVariablyModifiedType(), |
2720 | Referencee->containsUnexpandedParameterPack()), |
2721 | PointeeType(Referencee) { |
2722 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2723 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2724 | } |
2725 | |
2726 | public: |
2727 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2728 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2729 | |
2730 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2731 | |
2732 | QualType getPointeeType() const { |
2733 | // FIXME: this might strip inner qualifiers; okay? |
2734 | const ReferenceType *T = this; |
2735 | while (T->isInnerRef()) |
2736 | T = T->PointeeType->castAs<ReferenceType>(); |
2737 | return T->PointeeType; |
2738 | } |
2739 | |
2740 | void Profile(llvm::FoldingSetNodeID &ID) { |
2741 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2742 | } |
2743 | |
2744 | static void Profile(llvm::FoldingSetNodeID &ID, |
2745 | QualType Referencee, |
2746 | bool SpelledAsLValue) { |
2747 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2748 | ID.AddBoolean(SpelledAsLValue); |
2749 | } |
2750 | |
2751 | static bool classof(const Type *T) { |
2752 | return T->getTypeClass() == LValueReference || |
2753 | T->getTypeClass() == RValueReference; |
2754 | } |
2755 | }; |
2756 | |
2757 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2758 | class LValueReferenceType : public ReferenceType { |
2759 | friend class ASTContext; // ASTContext creates these |
2760 | |
2761 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2762 | bool SpelledAsLValue) |
2763 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2764 | SpelledAsLValue) {} |
2765 | |
2766 | public: |
2767 | bool isSugared() const { return false; } |
2768 | QualType desugar() const { return QualType(this, 0); } |
2769 | |
2770 | static bool classof(const Type *T) { |
2771 | return T->getTypeClass() == LValueReference; |
2772 | } |
2773 | }; |
2774 | |
2775 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2776 | class RValueReferenceType : public ReferenceType { |
2777 | friend class ASTContext; // ASTContext creates these |
2778 | |
2779 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2780 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2781 | |
2782 | public: |
2783 | bool isSugared() const { return false; } |
2784 | QualType desugar() const { return QualType(this, 0); } |
2785 | |
2786 | static bool classof(const Type *T) { |
2787 | return T->getTypeClass() == RValueReference; |
2788 | } |
2789 | }; |
2790 | |
2791 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2792 | /// |
2793 | /// This includes both pointers to data members and pointer to member functions. |
2794 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2795 | friend class ASTContext; // ASTContext creates these. |
2796 | |
2797 | QualType PointeeType; |
2798 | |
2799 | /// The class of which the pointee is a member. Must ultimately be a |
2800 | /// RecordType, but could be a typedef or a template parameter too. |
2801 | const Type *Class; |
2802 | |
2803 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2804 | : Type(MemberPointer, CanonicalPtr, |
2805 | Cls->isDependentType() || Pointee->isDependentType(), |
2806 | (Cls->isInstantiationDependentType() || |
2807 | Pointee->isInstantiationDependentType()), |
2808 | Pointee->isVariablyModifiedType(), |
2809 | (Cls->containsUnexpandedParameterPack() || |
2810 | Pointee->containsUnexpandedParameterPack())), |
2811 | PointeeType(Pointee), Class(Cls) {} |
2812 | |
2813 | public: |
2814 | QualType getPointeeType() const { return PointeeType; } |
2815 | |
2816 | /// Returns true if the member type (i.e. the pointee type) is a |
2817 | /// function type rather than a data-member type. |
2818 | bool isMemberFunctionPointer() const { |
2819 | return PointeeType->isFunctionProtoType(); |
2820 | } |
2821 | |
2822 | /// Returns true if the member type (i.e. the pointee type) is a |
2823 | /// data type rather than a function type. |
2824 | bool isMemberDataPointer() const { |
2825 | return !PointeeType->isFunctionProtoType(); |
2826 | } |
2827 | |
2828 | const Type *getClass() const { return Class; } |
2829 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2830 | |
2831 | bool isSugared() const { return false; } |
2832 | QualType desugar() const { return QualType(this, 0); } |
2833 | |
2834 | void Profile(llvm::FoldingSetNodeID &ID) { |
2835 | Profile(ID, getPointeeType(), getClass()); |
2836 | } |
2837 | |
2838 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2839 | const Type *Class) { |
2840 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2841 | ID.AddPointer(Class); |
2842 | } |
2843 | |
2844 | static bool classof(const Type *T) { |
2845 | return T->getTypeClass() == MemberPointer; |
2846 | } |
2847 | }; |
2848 | |
2849 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2850 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2851 | public: |
2852 | /// Capture whether this is a normal array (e.g. int X[4]) |
2853 | /// an array with a static size (e.g. int X[static 4]), or an array |
2854 | /// with a star size (e.g. int X[*]). |
2855 | /// 'static' is only allowed on function parameters. |
2856 | enum ArraySizeModifier { |
2857 | Normal, Static, Star |
2858 | }; |
2859 | |
2860 | private: |
2861 | /// The element type of the array. |
2862 | QualType ElementType; |
2863 | |
2864 | protected: |
2865 | friend class ASTContext; // ASTContext creates these. |
2866 | |
2867 | // C++ [temp.dep.type]p1: |
2868 | // A type is dependent if it is... |
2869 | // - an array type constructed from any dependent type or whose |
2870 | // size is specified by a constant expression that is |
2871 | // value-dependent, |
2872 | ArrayType(TypeClass tc, QualType et, QualType can, |
2873 | ArraySizeModifier sm, unsigned tq, |
2874 | bool ContainsUnexpandedParameterPack) |
2875 | : Type(tc, can, et->isDependentType() || tc == DependentSizedArray, |
2876 | et->isInstantiationDependentType() || tc == DependentSizedArray, |
2877 | (tc == VariableArray || et->isVariablyModifiedType()), |
2878 | ContainsUnexpandedParameterPack), |
2879 | ElementType(et) { |
2880 | ArrayTypeBits.IndexTypeQuals = tq; |
2881 | ArrayTypeBits.SizeModifier = sm; |
2882 | } |
2883 | |
2884 | public: |
2885 | QualType getElementType() const { return ElementType; } |
2886 | |
2887 | ArraySizeModifier getSizeModifier() const { |
2888 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2889 | } |
2890 | |
2891 | Qualifiers getIndexTypeQualifiers() const { |
2892 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2893 | } |
2894 | |
2895 | unsigned getIndexTypeCVRQualifiers() const { |
2896 | return ArrayTypeBits.IndexTypeQuals; |
2897 | } |
2898 | |
2899 | static bool classof(const Type *T) { |
2900 | return T->getTypeClass() == ConstantArray || |
2901 | T->getTypeClass() == VariableArray || |
2902 | T->getTypeClass() == IncompleteArray || |
2903 | T->getTypeClass() == DependentSizedArray; |
2904 | } |
2905 | }; |
2906 | |
2907 | /// Represents the canonical version of C arrays with a specified constant size. |
2908 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2909 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2910 | class ConstantArrayType : public ArrayType { |
2911 | llvm::APInt Size; // Allows us to unique the type. |
2912 | |
2913 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2914 | ArraySizeModifier sm, unsigned tq) |
2915 | : ArrayType(ConstantArray, et, can, sm, tq, |
2916 | et->containsUnexpandedParameterPack()), |
2917 | Size(size) {} |
2918 | |
2919 | protected: |
2920 | friend class ASTContext; // ASTContext creates these. |
2921 | |
2922 | ConstantArrayType(TypeClass tc, QualType et, QualType can, |
2923 | const llvm::APInt &size, ArraySizeModifier sm, unsigned tq) |
2924 | : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()), |
2925 | Size(size) {} |
2926 | |
2927 | public: |
2928 | const llvm::APInt &getSize() const { return Size; } |
2929 | bool isSugared() const { return false; } |
2930 | QualType desugar() const { return QualType(this, 0); } |
2931 | |
2932 | /// Determine the number of bits required to address a member of |
2933 | // an array with the given element type and number of elements. |
2934 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2935 | QualType ElementType, |
2936 | const llvm::APInt &NumElements); |
2937 | |
2938 | /// Determine the maximum number of active bits that an array's size |
2939 | /// can require, which limits the maximum size of the array. |
2940 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2941 | |
2942 | void Profile(llvm::FoldingSetNodeID &ID) { |
2943 | Profile(ID, getElementType(), getSize(), |
2944 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2945 | } |
2946 | |
2947 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2948 | const llvm::APInt &ArraySize, ArraySizeModifier SizeMod, |
2949 | unsigned TypeQuals) { |
2950 | ID.AddPointer(ET.getAsOpaquePtr()); |
2951 | ID.AddInteger(ArraySize.getZExtValue()); |
2952 | ID.AddInteger(SizeMod); |
2953 | ID.AddInteger(TypeQuals); |
2954 | } |
2955 | |
2956 | static bool classof(const Type *T) { |
2957 | return T->getTypeClass() == ConstantArray; |
2958 | } |
2959 | }; |
2960 | |
2961 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2962 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2963 | /// unspecified. |
2964 | class IncompleteArrayType : public ArrayType { |
2965 | friend class ASTContext; // ASTContext creates these. |
2966 | |
2967 | IncompleteArrayType(QualType et, QualType can, |
2968 | ArraySizeModifier sm, unsigned tq) |
2969 | : ArrayType(IncompleteArray, et, can, sm, tq, |
2970 | et->containsUnexpandedParameterPack()) {} |
2971 | |
2972 | public: |
2973 | friend class StmtIteratorBase; |
2974 | |
2975 | bool isSugared() const { return false; } |
2976 | QualType desugar() const { return QualType(this, 0); } |
2977 | |
2978 | static bool classof(const Type *T) { |
2979 | return T->getTypeClass() == IncompleteArray; |
2980 | } |
2981 | |
2982 | void Profile(llvm::FoldingSetNodeID &ID) { |
2983 | Profile(ID, getElementType(), getSizeModifier(), |
2984 | getIndexTypeCVRQualifiers()); |
2985 | } |
2986 | |
2987 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2988 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
2989 | ID.AddPointer(ET.getAsOpaquePtr()); |
2990 | ID.AddInteger(SizeMod); |
2991 | ID.AddInteger(TypeQuals); |
2992 | } |
2993 | }; |
2994 | |
2995 | /// Represents a C array with a specified size that is not an |
2996 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
2997 | /// Since the size expression is an arbitrary expression, we store it as such. |
2998 | /// |
2999 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
3000 | /// should not be: two lexically equivalent variable array types could mean |
3001 | /// different things, for example, these variables do not have the same type |
3002 | /// dynamically: |
3003 | /// |
3004 | /// void foo(int x) { |
3005 | /// int Y[x]; |
3006 | /// ++x; |
3007 | /// int Z[x]; |
3008 | /// } |
3009 | class VariableArrayType : public ArrayType { |
3010 | friend class ASTContext; // ASTContext creates these. |
3011 | |
3012 | /// An assignment-expression. VLA's are only permitted within |
3013 | /// a function block. |
3014 | Stmt *SizeExpr; |
3015 | |
3016 | /// The range spanned by the left and right array brackets. |
3017 | SourceRange Brackets; |
3018 | |
3019 | VariableArrayType(QualType et, QualType can, Expr *e, |
3020 | ArraySizeModifier sm, unsigned tq, |
3021 | SourceRange brackets) |
3022 | : ArrayType(VariableArray, et, can, sm, tq, |
3023 | et->containsUnexpandedParameterPack()), |
3024 | SizeExpr((Stmt*) e), Brackets(brackets) {} |
3025 | |
3026 | public: |
3027 | friend class StmtIteratorBase; |
3028 | |
3029 | Expr *getSizeExpr() const { |
3030 | // We use C-style casts instead of cast<> here because we do not wish |
3031 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3032 | return (Expr*) SizeExpr; |
3033 | } |
3034 | |
3035 | SourceRange getBracketsRange() const { return Brackets; } |
3036 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3037 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3038 | |
3039 | bool isSugared() const { return false; } |
3040 | QualType desugar() const { return QualType(this, 0); } |
3041 | |
3042 | static bool classof(const Type *T) { |
3043 | return T->getTypeClass() == VariableArray; |
3044 | } |
3045 | |
3046 | void Profile(llvm::FoldingSetNodeID &ID) { |
3047 | llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3047); |
3048 | } |
3049 | }; |
3050 | |
3051 | /// Represents an array type in C++ whose size is a value-dependent expression. |
3052 | /// |
3053 | /// For example: |
3054 | /// \code |
3055 | /// template<typename T, int Size> |
3056 | /// class array { |
3057 | /// T data[Size]; |
3058 | /// }; |
3059 | /// \endcode |
3060 | /// |
3061 | /// For these types, we won't actually know what the array bound is |
3062 | /// until template instantiation occurs, at which point this will |
3063 | /// become either a ConstantArrayType or a VariableArrayType. |
3064 | class DependentSizedArrayType : public ArrayType { |
3065 | friend class ASTContext; // ASTContext creates these. |
3066 | |
3067 | const ASTContext &Context; |
3068 | |
3069 | /// An assignment expression that will instantiate to the |
3070 | /// size of the array. |
3071 | /// |
3072 | /// The expression itself might be null, in which case the array |
3073 | /// type will have its size deduced from an initializer. |
3074 | Stmt *SizeExpr; |
3075 | |
3076 | /// The range spanned by the left and right array brackets. |
3077 | SourceRange Brackets; |
3078 | |
3079 | DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, |
3080 | Expr *e, ArraySizeModifier sm, unsigned tq, |
3081 | SourceRange brackets); |
3082 | |
3083 | public: |
3084 | friend class StmtIteratorBase; |
3085 | |
3086 | Expr *getSizeExpr() const { |
3087 | // We use C-style casts instead of cast<> here because we do not wish |
3088 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3089 | return (Expr*) SizeExpr; |
3090 | } |
3091 | |
3092 | SourceRange getBracketsRange() const { return Brackets; } |
3093 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3094 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3095 | |
3096 | bool isSugared() const { return false; } |
3097 | QualType desugar() const { return QualType(this, 0); } |
3098 | |
3099 | static bool classof(const Type *T) { |
3100 | return T->getTypeClass() == DependentSizedArray; |
3101 | } |
3102 | |
3103 | void Profile(llvm::FoldingSetNodeID &ID) { |
3104 | Profile(ID, Context, getElementType(), |
3105 | getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); |
3106 | } |
3107 | |
3108 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3109 | QualType ET, ArraySizeModifier SizeMod, |
3110 | unsigned TypeQuals, Expr *E); |
3111 | }; |
3112 | |
3113 | /// Represents an extended address space qualifier where the input address space |
3114 | /// value is dependent. Non-dependent address spaces are not represented with a |
3115 | /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. |
3116 | /// |
3117 | /// For example: |
3118 | /// \code |
3119 | /// template<typename T, int AddrSpace> |
3120 | /// class AddressSpace { |
3121 | /// typedef T __attribute__((address_space(AddrSpace))) type; |
3122 | /// } |
3123 | /// \endcode |
3124 | class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { |
3125 | friend class ASTContext; |
3126 | |
3127 | const ASTContext &Context; |
3128 | Expr *AddrSpaceExpr; |
3129 | QualType PointeeType; |
3130 | SourceLocation loc; |
3131 | |
3132 | DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, |
3133 | QualType can, Expr *AddrSpaceExpr, |
3134 | SourceLocation loc); |
3135 | |
3136 | public: |
3137 | Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } |
3138 | QualType getPointeeType() const { return PointeeType; } |
3139 | SourceLocation getAttributeLoc() const { return loc; } |
3140 | |
3141 | bool isSugared() const { return false; } |
3142 | QualType desugar() const { return QualType(this, 0); } |
3143 | |
3144 | static bool classof(const Type *T) { |
3145 | return T->getTypeClass() == DependentAddressSpace; |
3146 | } |
3147 | |
3148 | void Profile(llvm::FoldingSetNodeID &ID) { |
3149 | Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); |
3150 | } |
3151 | |
3152 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3153 | QualType PointeeType, Expr *AddrSpaceExpr); |
3154 | }; |
3155 | |
3156 | /// Represents an extended vector type where either the type or size is |
3157 | /// dependent. |
3158 | /// |
3159 | /// For example: |
3160 | /// \code |
3161 | /// template<typename T, int Size> |
3162 | /// class vector { |
3163 | /// typedef T __attribute__((ext_vector_type(Size))) type; |
3164 | /// } |
3165 | /// \endcode |
3166 | class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { |
3167 | friend class ASTContext; |
3168 | |
3169 | const ASTContext &Context; |
3170 | Expr *SizeExpr; |
3171 | |
3172 | /// The element type of the array. |
3173 | QualType ElementType; |
3174 | |
3175 | SourceLocation loc; |
3176 | |
3177 | DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, |
3178 | QualType can, Expr *SizeExpr, SourceLocation loc); |
3179 | |
3180 | public: |
3181 | Expr *getSizeExpr() const { return SizeExpr; } |
3182 | QualType getElementType() const { return ElementType; } |
3183 | SourceLocation getAttributeLoc() const { return loc; } |
3184 | |
3185 | bool isSugared() const { return false; } |
3186 | QualType desugar() const { return QualType(this, 0); } |
3187 | |
3188 | static bool classof(const Type *T) { |
3189 | return T->getTypeClass() == DependentSizedExtVector; |
3190 | } |
3191 | |
3192 | void Profile(llvm::FoldingSetNodeID &ID) { |
3193 | Profile(ID, Context, getElementType(), getSizeExpr()); |
3194 | } |
3195 | |
3196 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3197 | QualType ElementType, Expr *SizeExpr); |
3198 | }; |
3199 | |
3200 | |
3201 | /// Represents a GCC generic vector type. This type is created using |
3202 | /// __attribute__((vector_size(n)), where "n" specifies the vector size in |
3203 | /// bytes; or from an Altivec __vector or vector declaration. |
3204 | /// Since the constructor takes the number of vector elements, the |
3205 | /// client is responsible for converting the size into the number of elements. |
3206 | class VectorType : public Type, public llvm::FoldingSetNode { |
3207 | public: |
3208 | enum VectorKind { |
3209 | /// not a target-specific vector type |
3210 | GenericVector, |
3211 | |
3212 | /// is AltiVec vector |
3213 | AltiVecVector, |
3214 | |
3215 | /// is AltiVec 'vector Pixel' |
3216 | AltiVecPixel, |
3217 | |
3218 | /// is AltiVec 'vector bool ...' |
3219 | AltiVecBool, |
3220 | |
3221 | /// is ARM Neon vector |
3222 | NeonVector, |
3223 | |
3224 | /// is ARM Neon polynomial vector |
3225 | NeonPolyVector |
3226 | }; |
3227 | |
3228 | protected: |
3229 | friend class ASTContext; // ASTContext creates these. |
3230 | |
3231 | /// The element type of the vector. |
3232 | QualType ElementType; |
3233 | |
3234 | VectorType(QualType vecType, unsigned nElements, QualType canonType, |
3235 | VectorKind vecKind); |
3236 | |
3237 | VectorType(TypeClass tc, QualType vecType, unsigned nElements, |
3238 | QualType canonType, VectorKind vecKind); |
3239 | |
3240 | public: |
3241 | QualType getElementType() const { return ElementType; } |
3242 | unsigned getNumElements() const { return VectorTypeBits.NumElements; } |
3243 | |
3244 | static bool isVectorSizeTooLarge(unsigned NumElements) { |
3245 | return NumElements > VectorTypeBitfields::MaxNumElements; |
3246 | } |
3247 | |
3248 | bool isSugared() const { return false; } |
3249 | QualType desugar() const { return QualType(this, 0); } |
3250 | |
3251 | VectorKind getVectorKind() const { |
3252 | return VectorKind(VectorTypeBits.VecKind); |
3253 | } |
3254 | |
3255 | void Profile(llvm::FoldingSetNodeID &ID) { |
3256 | Profile(ID, getElementType(), getNumElements(), |
3257 | getTypeClass(), getVectorKind()); |
3258 | } |
3259 | |
3260 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3261 | unsigned NumElements, TypeClass TypeClass, |
3262 | VectorKind VecKind) { |
3263 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3264 | ID.AddInteger(NumElements); |
3265 | ID.AddInteger(TypeClass); |
3266 | ID.AddInteger(VecKind); |
3267 | } |
3268 | |
3269 | static bool classof(const Type *T) { |
3270 | return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; |
3271 | } |
3272 | }; |
3273 | |
3274 | /// Represents a vector type where either the type or size is dependent. |
3275 | //// |
3276 | /// For example: |
3277 | /// \code |
3278 | /// template<typename T, int Size> |
3279 | /// class vector { |
3280 | /// typedef T __attribute__((vector_size(Size))) type; |
3281 | /// } |
3282 | /// \endcode |
3283 | class DependentVectorType : public Type, public llvm::FoldingSetNode { |
3284 | friend class ASTContext; |
3285 | |
3286 | const ASTContext &Context; |
3287 | QualType ElementType; |
3288 | Expr *SizeExpr; |
3289 | SourceLocation Loc; |
3290 | |
3291 | DependentVectorType(const ASTContext &Context, QualType ElementType, |
3292 | QualType CanonType, Expr *SizeExpr, |
3293 | SourceLocation Loc, VectorType::VectorKind vecKind); |
3294 | |
3295 | public: |
3296 | Expr *getSizeExpr() const { return SizeExpr; } |
3297 | QualType getElementType() const { return ElementType; } |
3298 | SourceLocation getAttributeLoc() const { return Loc; } |
3299 | VectorType::VectorKind getVectorKind() const { |
3300 | return VectorType::VectorKind(VectorTypeBits.VecKind); |
3301 | } |
3302 | |
3303 | bool isSugared() const { return false; } |
3304 | QualType desugar() const { return QualType(this, 0); } |
3305 | |
3306 | static bool classof(const Type *T) { |
3307 | return T->getTypeClass() == DependentVector; |
3308 | } |
3309 | |
3310 | void Profile(llvm::FoldingSetNodeID &ID) { |
3311 | Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); |
3312 | } |
3313 | |
3314 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3315 | QualType ElementType, const Expr *SizeExpr, |
3316 | VectorType::VectorKind VecKind); |
3317 | }; |
3318 | |
3319 | /// ExtVectorType - Extended vector type. This type is created using |
3320 | /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. |
3321 | /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This |
3322 | /// class enables syntactic extensions, like Vector Components for accessing |
3323 | /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL |
3324 | /// Shading Language). |
3325 | class ExtVectorType : public VectorType { |
3326 | friend class ASTContext; // ASTContext creates these. |
3327 | |
3328 | ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) |
3329 | : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} |
3330 | |
3331 | public: |
3332 | static int getPointAccessorIdx(char c) { |
3333 | switch (c) { |
3334 | default: return -1; |
3335 | case 'x': case 'r': return 0; |
3336 | case 'y': case 'g': return 1; |
3337 | case 'z': case 'b': return 2; |
3338 | case 'w': case 'a': return 3; |
3339 | } |
3340 | } |
3341 | |
3342 | static int getNumericAccessorIdx(char c) { |
3343 | switch (c) { |
3344 | default: return -1; |
3345 | case '0': return 0; |
3346 | case '1': return 1; |
3347 | case '2': return 2; |
3348 | case '3': return 3; |
3349 | case '4': return 4; |
3350 | case '5': return 5; |
3351 | case '6': return 6; |
3352 | case '7': return 7; |
3353 | case '8': return 8; |
3354 | case '9': return 9; |
3355 | case 'A': |
3356 | case 'a': return 10; |
3357 | case 'B': |
3358 | case 'b': return 11; |
3359 | case 'C': |
3360 | case 'c': return 12; |
3361 | case 'D': |
3362 | case 'd': return 13; |
3363 | case 'E': |
3364 | case 'e': return 14; |
3365 | case 'F': |
3366 | case 'f': return 15; |
3367 | } |
3368 | } |
3369 | |
3370 | static int getAccessorIdx(char c, bool isNumericAccessor) { |
3371 | if (isNumericAccessor) |
3372 | return getNumericAccessorIdx(c); |
3373 | else |
3374 | return getPointAccessorIdx(c); |
3375 | } |
3376 | |
3377 | bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { |
3378 | if (int idx = getAccessorIdx(c, isNumericAccessor)+1) |
3379 | return unsigned(idx-1) < getNumElements(); |
3380 | return false; |
3381 | } |
3382 | |
3383 | bool isSugared() const { return false; } |
3384 | QualType desugar() const { return QualType(this, 0); } |
3385 | |
3386 | static bool classof(const Type *T) { |
3387 | return T->getTypeClass() == ExtVector; |
3388 | } |
3389 | }; |
3390 | |
3391 | /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base |
3392 | /// class of FunctionNoProtoType and FunctionProtoType. |
3393 | class FunctionType : public Type { |
3394 | // The type returned by the function. |
3395 | QualType ResultType; |
3396 | |
3397 | public: |
3398 | /// Interesting information about a specific parameter that can't simply |
3399 | /// be reflected in parameter's type. This is only used by FunctionProtoType |
3400 | /// but is in FunctionType to make this class available during the |
3401 | /// specification of the bases of FunctionProtoType. |
3402 | /// |
3403 | /// It makes sense to model language features this way when there's some |
3404 | /// sort of parameter-specific override (such as an attribute) that |
3405 | /// affects how the function is called. For example, the ARC ns_consumed |
3406 | /// attribute changes whether a parameter is passed at +0 (the default) |
3407 | /// or +1 (ns_consumed). This must be reflected in the function type, |
3408 | /// but isn't really a change to the parameter type. |
3409 | /// |
3410 | /// One serious disadvantage of modelling language features this way is |
3411 | /// that they generally do not work with language features that attempt |
3412 | /// to destructure types. For example, template argument deduction will |
3413 | /// not be able to match a parameter declared as |
3414 | /// T (*)(U) |
3415 | /// against an argument of type |
3416 | /// void (*)(__attribute__((ns_consumed)) id) |
3417 | /// because the substitution of T=void, U=id into the former will |
3418 | /// not produce the latter. |
3419 | class ExtParameterInfo { |
3420 | enum { |
3421 | ABIMask = 0x0F, |
3422 | IsConsumed = 0x10, |
3423 | HasPassObjSize = 0x20, |
3424 | IsNoEscape = 0x40, |
3425 | }; |
3426 | unsigned char Data = 0; |
3427 | |
3428 | public: |
3429 | ExtParameterInfo() = default; |
3430 | |
3431 | /// Return the ABI treatment of this parameter. |
3432 | ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } |
3433 | ExtParameterInfo withABI(ParameterABI kind) const { |
3434 | ExtParameterInfo copy = *this; |
3435 | copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); |
3436 | return copy; |
3437 | } |
3438 | |
3439 | /// Is this parameter considered "consumed" by Objective-C ARC? |
3440 | /// Consumed parameters must have retainable object type. |
3441 | bool isConsumed() const { return (Data & IsConsumed); } |
3442 | ExtParameterInfo withIsConsumed(bool consumed) const { |
3443 | ExtParameterInfo copy = *this; |
3444 | if (consumed) |
3445 | copy.Data |= IsConsumed; |
3446 | else |
3447 | copy.Data &= ~IsConsumed; |
3448 | return copy; |
3449 | } |
3450 | |
3451 | bool hasPassObjectSize() const { return Data & HasPassObjSize; } |
3452 | ExtParameterInfo withHasPassObjectSize() const { |
3453 | ExtParameterInfo Copy = *this; |
3454 | Copy.Data |= HasPassObjSize; |
3455 | return Copy; |
3456 | } |
3457 | |
3458 | bool isNoEscape() const { return Data & IsNoEscape; } |
3459 | ExtParameterInfo withIsNoEscape(bool NoEscape) const { |
3460 | ExtParameterInfo Copy = *this; |
3461 | if (NoEscape) |
3462 | Copy.Data |= IsNoEscape; |
3463 | else |
3464 | Copy.Data &= ~IsNoEscape; |
3465 | return Copy; |
3466 | } |
3467 | |
3468 | unsigned char getOpaqueValue() const { return Data; } |
3469 | static ExtParameterInfo getFromOpaqueValue(unsigned char data) { |
3470 | ExtParameterInfo result; |
3471 | result.Data = data; |
3472 | return result; |
3473 | } |
3474 | |
3475 | friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3476 | return lhs.Data == rhs.Data; |
3477 | } |
3478 | |
3479 | friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3480 | return lhs.Data != rhs.Data; |
3481 | } |
3482 | }; |
3483 | |
3484 | /// A class which abstracts out some details necessary for |
3485 | /// making a call. |
3486 | /// |
3487 | /// It is not actually used directly for storing this information in |
3488 | /// a FunctionType, although FunctionType does currently use the |
3489 | /// same bit-pattern. |
3490 | /// |
3491 | // If you add a field (say Foo), other than the obvious places (both, |
3492 | // constructors, compile failures), what you need to update is |
3493 | // * Operator== |
3494 | // * getFoo |
3495 | // * withFoo |
3496 | // * functionType. Add Foo, getFoo. |
3497 | // * ASTContext::getFooType |
3498 | // * ASTContext::mergeFunctionTypes |
3499 | // * FunctionNoProtoType::Profile |
3500 | // * FunctionProtoType::Profile |
3501 | // * TypePrinter::PrintFunctionProto |
3502 | // * AST read and write |
3503 | // * Codegen |
3504 | class ExtInfo { |
3505 | friend class FunctionType; |
3506 | |
3507 | // Feel free to rearrange or add bits, but if you go over 12, |
3508 | // you'll need to adjust both the Bits field below and |
3509 | // Type::FunctionTypeBitfields. |
3510 | |
3511 | // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck| |
3512 | // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | |
3513 | // |
3514 | // regparm is either 0 (no regparm attribute) or the regparm value+1. |
3515 | enum { CallConvMask = 0x1F }; |
3516 | enum { NoReturnMask = 0x20 }; |
3517 | enum { ProducesResultMask = 0x40 }; |
3518 | enum { NoCallerSavedRegsMask = 0x80 }; |
3519 | enum { NoCfCheckMask = 0x800 }; |
3520 | enum { |
3521 | RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask | |
3522 | NoCallerSavedRegsMask | NoCfCheckMask), |
3523 | RegParmOffset = 8 |
3524 | }; // Assumed to be the last field |
3525 | uint16_t Bits = CC_C; |
3526 | |
3527 | ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} |
3528 | |
3529 | public: |
3530 | // Constructor with no defaults. Use this when you know that you |
3531 | // have all the elements (when reading an AST file for example). |
3532 | ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, |
3533 | bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) { |
3534 | assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value" ) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3534, __PRETTY_FUNCTION__)); |
3535 | Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | |
3536 | (producesResult ? ProducesResultMask : 0) | |
3537 | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | |
3538 | (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | |
3539 | (NoCfCheck ? NoCfCheckMask : 0); |
3540 | } |
3541 | |
3542 | // Constructor with all defaults. Use when for example creating a |
3543 | // function known to use defaults. |
3544 | ExtInfo() = default; |
3545 | |
3546 | // Constructor with just the calling convention, which is an important part |
3547 | // of the canonical type. |
3548 | ExtInfo(CallingConv CC) : Bits(CC) {} |
3549 | |
3550 | bool getNoReturn() const { return Bits & NoReturnMask; } |
3551 | bool getProducesResult() const { return Bits & ProducesResultMask; } |
3552 | bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } |
3553 | bool getNoCfCheck() const { return Bits & NoCfCheckMask; } |
3554 | bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; } |
3555 | |
3556 | unsigned getRegParm() const { |
3557 | unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; |
3558 | if (RegParm > 0) |
3559 | --RegParm; |
3560 | return RegParm; |
3561 | } |
3562 | |
3563 | CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } |
3564 | |
3565 | bool operator==(ExtInfo Other) const { |
3566 | return Bits == Other.Bits; |
3567 | } |
3568 | bool operator!=(ExtInfo Other) const { |
3569 | return Bits != Other.Bits; |
3570 | } |
3571 | |
3572 | // Note that we don't have setters. That is by design, use |
3573 | // the following with methods instead of mutating these objects. |
3574 | |
3575 | ExtInfo withNoReturn(bool noReturn) const { |
3576 | if (noReturn) |
3577 | return ExtInfo(Bits | NoReturnMask); |
3578 | else |
3579 | return ExtInfo(Bits & ~NoReturnMask); |
3580 | } |
3581 | |
3582 | ExtInfo withProducesResult(bool producesResult) const { |
3583 | if (producesResult) |
3584 | return ExtInfo(Bits | ProducesResultMask); |
3585 | else |
3586 | return ExtInfo(Bits & ~ProducesResultMask); |
3587 | } |
3588 | |
3589 | ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { |
3590 | if (noCallerSavedRegs) |
3591 | return ExtInfo(Bits | NoCallerSavedRegsMask); |
3592 | else |
3593 | return ExtInfo(Bits & ~NoCallerSavedRegsMask); |
3594 | } |
3595 | |
3596 | ExtInfo withNoCfCheck(bool noCfCheck) const { |
3597 | if (noCfCheck) |
3598 | return ExtInfo(Bits | NoCfCheckMask); |
3599 | else |
3600 | return ExtInfo(Bits & ~NoCfCheckMask); |
3601 | } |
3602 | |
3603 | ExtInfo withRegParm(unsigned RegParm) const { |
3604 | assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast <void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3604, __PRETTY_FUNCTION__)); |
3605 | return ExtInfo((Bits & ~RegParmMask) | |
3606 | ((RegParm + 1) << RegParmOffset)); |
3607 | } |
3608 | |
3609 | ExtInfo withCallingConv(CallingConv cc) const { |
3610 | return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); |
3611 | } |
3612 | |
3613 | void Profile(llvm::FoldingSetNodeID &ID) const { |
3614 | ID.AddInteger(Bits); |
3615 | } |
3616 | }; |
3617 | |
3618 | /// A simple holder for a QualType representing a type in an |
3619 | /// exception specification. Unfortunately needed by FunctionProtoType |
3620 | /// because TrailingObjects cannot handle repeated types. |
3621 | struct ExceptionType { QualType Type; }; |
3622 | |
3623 | /// A simple holder for various uncommon bits which do not fit in |
3624 | /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the |
3625 | /// alignment of subsequent objects in TrailingObjects. You must update |
3626 | /// hasExtraBitfields in FunctionProtoType after adding extra data here. |
3627 | struct alignas(void *) FunctionTypeExtraBitfields { |
3628 | /// The number of types in the exception specification. |
3629 | /// A whole unsigned is not needed here and according to |
3630 | /// [implimits] 8 bits would be enough here. |
3631 | unsigned NumExceptionType; |
3632 | }; |
3633 | |
3634 | protected: |
3635 | FunctionType(TypeClass tc, QualType res, |
3636 | QualType Canonical, bool Dependent, |
3637 | bool InstantiationDependent, |
3638 | bool VariablyModified, bool ContainsUnexpandedParameterPack, |
3639 | ExtInfo Info) |
3640 | : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, |
3641 | ContainsUnexpandedParameterPack), |
3642 | ResultType(res) { |
3643 | FunctionTypeBits.ExtInfo = Info.Bits; |
3644 | } |
3645 | |
3646 | Qualifiers getFastTypeQuals() const { |
3647 | return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); |
3648 | } |
3649 | |
3650 | public: |
3651 | QualType getReturnType() const { return ResultType; } |
3652 | |
3653 | bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } |
3654 | unsigned getRegParmType() const { return getExtInfo().getRegParm(); } |
3655 | |
3656 | /// Determine whether this function type includes the GNU noreturn |
3657 | /// attribute. The C++11 [[noreturn]] attribute does not affect the function |
3658 | /// type. |
3659 | bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } |
3660 | |
3661 | CallingConv getCallConv() const { return getExtInfo().getCC(); } |
3662 | ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } |
3663 | |
3664 | static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, |
3665 | "Const, volatile and restrict are assumed to be a subset of " |
3666 | "the fast qualifiers."); |
3667 | |
3668 | bool isConst() const { return getFastTypeQuals().hasConst(); } |
3669 | bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } |
3670 | bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } |
3671 | |
3672 | /// Determine the type of an expression that calls a function of |
3673 | /// this type. |
3674 | QualType getCallResultType(const ASTContext &Context) const { |
3675 | return getReturnType().getNonLValueExprType(Context); |
3676 | } |
3677 | |
3678 | static StringRef getNameForCallConv(CallingConv CC); |
3679 | |
3680 | static bool classof(const Type *T) { |
3681 | return T->getTypeClass() == FunctionNoProto || |
3682 | T->getTypeClass() == FunctionProto; |
3683 | } |
3684 | }; |
3685 | |
3686 | /// Represents a K&R-style 'int foo()' function, which has |
3687 | /// no information available about its arguments. |
3688 | class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { |
3689 | friend class ASTContext; // ASTContext creates these. |
3690 | |
3691 | FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) |
3692 | : FunctionType(FunctionNoProto, Result, Canonical, |
3693 | /*Dependent=*/false, /*InstantiationDependent=*/false, |
3694 | Result->isVariablyModifiedType(), |
3695 | /*ContainsUnexpandedParameterPack=*/false, Info) {} |
3696 | |
3697 | public: |
3698 | // No additional state past what FunctionType provides. |
3699 | |
3700 | bool isSugared() const { return false; } |
3701 | QualType desugar() const { return QualType(this, 0); } |
3702 | |
3703 | void Profile(llvm::FoldingSetNodeID &ID) { |
3704 | Profile(ID, getReturnType(), getExtInfo()); |
3705 | } |
3706 | |
3707 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, |
3708 | ExtInfo Info) { |
3709 | Info.Profile(ID); |
3710 | ID.AddPointer(ResultType.getAsOpaquePtr()); |
3711 | } |
3712 | |
3713 | static bool classof(const Type *T) { |
3714 | return T->getTypeClass() == FunctionNoProto; |
3715 | } |
3716 | }; |
3717 | |
3718 | /// Represents a prototype with parameter type info, e.g. |
3719 | /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no |
3720 | /// parameters, not as having a single void parameter. Such a type can have |
3721 | /// an exception specification, but this specification is not part of the |
3722 | /// canonical type. FunctionProtoType has several trailing objects, some of |
3723 | /// which optional. For more information about the trailing objects see |
3724 | /// the first comment inside FunctionProtoType. |
3725 | class FunctionProtoType final |
3726 | : public FunctionType, |
3727 | public llvm::FoldingSetNode, |
3728 | private llvm::TrailingObjects< |
3729 | FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields, |
3730 | FunctionType::ExceptionType, Expr *, FunctionDecl *, |
3731 | FunctionType::ExtParameterInfo, Qualifiers> { |
3732 | friend class ASTContext; // ASTContext creates these. |
3733 | friend TrailingObjects; |
3734 | |
3735 | // FunctionProtoType is followed by several trailing objects, some of |
3736 | // which optional. They are in order: |
3737 | // |
3738 | // * An array of getNumParams() QualType holding the parameter types. |
3739 | // Always present. Note that for the vast majority of FunctionProtoType, |
3740 | // these will be the only trailing objects. |
3741 | // |
3742 | // * Optionally if some extra data is stored in FunctionTypeExtraBitfields |
3743 | // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): |
3744 | // a single FunctionTypeExtraBitfields. Present if and only if |
3745 | // hasExtraBitfields() is true. |
3746 | // |
3747 | // * Optionally exactly one of: |
3748 | // * an array of getNumExceptions() ExceptionType, |
3749 | // * a single Expr *, |
3750 | // * a pair of FunctionDecl *, |
3751 | // * a single FunctionDecl * |
3752 | // used to store information about the various types of exception |
3753 | // specification. See getExceptionSpecSize for the details. |
3754 | // |
3755 | // * Optionally an array of getNumParams() ExtParameterInfo holding |
3756 | // an ExtParameterInfo for each of the parameters. Present if and |
3757 | // only if hasExtParameterInfos() is true. |
3758 | // |
3759 | // * Optionally a Qualifiers object to represent extra qualifiers that can't |
3760 | // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only |
3761 | // if hasExtQualifiers() is true. |
3762 | // |
3763 | // The optional FunctionTypeExtraBitfields has to be before the data |
3764 | // related to the exception specification since it contains the number |
3765 | // of exception types. |
3766 | // |
3767 | // We put the ExtParameterInfos last. If all were equal, it would make |
3768 | // more sense to put these before the exception specification, because |
3769 | // it's much easier to skip past them compared to the elaborate switch |
3770 | // required to skip the exception specification. However, all is not |
3771 | // equal; ExtParameterInfos are used to model very uncommon features, |
3772 | // and it's better not to burden the more common paths. |
3773 | |
3774 | public: |
3775 | /// Holds information about the various types of exception specification. |
3776 | /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is |
3777 | /// used to group together the various bits of information about the |
3778 | /// exception specification. |
3779 | struct ExceptionSpecInfo { |
3780 | /// The kind of exception specification this is. |
3781 | ExceptionSpecificationType Type = EST_None; |
3782 | |
3783 | /// Explicitly-specified list of exception types. |
3784 | ArrayRef<QualType> Exceptions; |
3785 | |
3786 | /// Noexcept expression, if this is a computed noexcept specification. |
3787 | Expr *NoexceptExpr = nullptr; |
3788 | |
3789 | /// The function whose exception specification this is, for |
3790 | /// EST_Unevaluated and EST_Uninstantiated. |
3791 | FunctionDecl *SourceDecl = nullptr; |
3792 | |
3793 | /// The function template whose exception specification this is instantiated |
3794 | /// from, for EST_Uninstantiated. |
3795 | FunctionDecl *SourceTemplate = nullptr; |
3796 | |
3797 | ExceptionSpecInfo() = default; |
3798 | |
3799 | ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} |
3800 | }; |
3801 | |
3802 | /// Extra information about a function prototype. ExtProtoInfo is not |
3803 | /// stored as such in FunctionProtoType but is used to group together |
3804 | /// the various bits of extra information about a function prototype. |
3805 | struct ExtProtoInfo { |
3806 | FunctionType::ExtInfo ExtInfo; |
3807 | bool Variadic : 1; |
3808 | bool HasTrailingReturn : 1; |
3809 | Qualifiers TypeQuals; |
3810 | RefQualifierKind RefQualifier = RQ_None; |
3811 | ExceptionSpecInfo ExceptionSpec; |
3812 | const ExtParameterInfo *ExtParameterInfos = nullptr; |
3813 | |
3814 | ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} |
3815 | |
3816 | ExtProtoInfo(CallingConv CC) |
3817 | : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} |
3818 | |
3819 | ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { |
3820 | ExtProtoInfo Result(*this); |
3821 | Result.ExceptionSpec = ESI; |
3822 | return Result; |
3823 | } |
3824 | }; |
3825 | |
3826 | private: |
3827 | unsigned numTrailingObjects(OverloadToken<QualType>) const { |
3828 | return getNumParams(); |
3829 | } |
3830 | |
3831 | unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { |
3832 | return hasExtraBitfields(); |
3833 | } |
3834 | |
3835 | unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { |
3836 | return getExceptionSpecSize().NumExceptionType; |
3837 | } |
3838 | |
3839 | unsigned numTrailingObjects(OverloadToken<Expr *>) const { |
3840 | return getExceptionSpecSize().NumExprPtr; |
3841 | } |
3842 | |
3843 | unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { |
3844 | return getExceptionSpecSize().NumFunctionDeclPtr; |
3845 | } |
3846 | |
3847 | unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { |
3848 | return hasExtParameterInfos() ? getNumParams() : 0; |
3849 | } |
3850 | |
3851 | /// Determine whether there are any argument types that |
3852 | /// contain an unexpanded parameter pack. |
3853 | static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, |
3854 | unsigned numArgs) { |
3855 | for (unsigned Idx = 0; Idx < numArgs; ++Idx) |
3856 | if (ArgArray[Idx]->containsUnexpandedParameterPack()) |
3857 | return true; |
3858 | |
3859 | return false; |
3860 | } |
3861 | |
3862 | FunctionProtoType(QualType result, ArrayRef<QualType> params, |
3863 | QualType canonical, const ExtProtoInfo &epi); |
3864 | |
3865 | /// This struct is returned by getExceptionSpecSize and is used to |
3866 | /// translate an ExceptionSpecificationType to the number and kind |
3867 | /// of trailing objects related to the exception specification. |
3868 | struct ExceptionSpecSizeHolder { |
3869 | unsigned NumExceptionType; |
3870 | unsigned NumExprPtr; |
3871 | unsigned NumFunctionDeclPtr; |
3872 | }; |
3873 | |
3874 | /// Return the number and kind of trailing objects |
3875 | /// related to the exception specification. |
3876 | static ExceptionSpecSizeHolder |
3877 | getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { |
3878 | switch (EST) { |
3879 | case EST_None: |
3880 | case EST_DynamicNone: |
3881 | case EST_MSAny: |
3882 | case EST_BasicNoexcept: |
3883 | case EST_Unparsed: |
3884 | case EST_NoThrow: |
3885 | return {0, 0, 0}; |
3886 | |
3887 | case EST_Dynamic: |
3888 | return {NumExceptions, 0, 0}; |
3889 | |
3890 | case EST_DependentNoexcept: |
3891 | case EST_NoexceptFalse: |
3892 | case EST_NoexceptTrue: |
3893 | return {0, 1, 0}; |
3894 | |
3895 | case EST_Uninstantiated: |
3896 | return {0, 0, 2}; |
3897 | |
3898 | case EST_Unevaluated: |
3899 | return {0, 0, 1}; |
3900 | } |
3901 | llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3901); |
3902 | } |
3903 | |
3904 | /// Return the number and kind of trailing objects |
3905 | /// related to the exception specification. |
3906 | ExceptionSpecSizeHolder getExceptionSpecSize() const { |
3907 | return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); |
3908 | } |
3909 | |
3910 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
3911 | static bool hasExtraBitfields(ExceptionSpecificationType EST) { |
3912 | // If the exception spec type is EST_Dynamic then we have > 0 exception |
3913 | // types and the exact number is stored in FunctionTypeExtraBitfields. |
3914 | return EST == EST_Dynamic; |
3915 | } |
3916 | |
3917 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
3918 | bool hasExtraBitfields() const { |
3919 | return hasExtraBitfields(getExceptionSpecType()); |
3920 | } |
3921 | |
3922 | bool hasExtQualifiers() const { |
3923 | return FunctionTypeBits.HasExtQuals; |
3924 | } |
3925 | |
3926 | public: |
3927 | unsigned getNumParams() const { return FunctionTypeBits.NumParams; } |
3928 | |
3929 | QualType getParamType(unsigned i) const { |
3930 | assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index") ? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3930, __PRETTY_FUNCTION__)); |
3931 | return param_type_begin()[i]; |
3932 | } |
3933 | |
3934 | ArrayRef<QualType> getParamTypes() const { |
3935 | return llvm::makeArrayRef(param_type_begin(), param_type_end()); |
3936 | } |
3937 | |
3938 | ExtProtoInfo getExtProtoInfo() const { |
3939 | ExtProtoInfo EPI; |
3940 | EPI.ExtInfo = getExtInfo(); |
3941 | EPI.Variadic = isVariadic(); |
3942 | EPI.HasTrailingReturn = hasTrailingReturn(); |
3943 | EPI.ExceptionSpec.Type = getExceptionSpecType(); |
3944 | EPI.TypeQuals = getMethodQuals(); |
3945 | EPI.RefQualifier = getRefQualifier(); |
3946 | if (EPI.ExceptionSpec.Type == EST_Dynamic) { |
3947 | EPI.ExceptionSpec.Exceptions = exceptions(); |
3948 | } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) { |
3949 | EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr(); |
3950 | } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) { |
3951 | EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl(); |
3952 | EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate(); |
3953 | } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) { |
3954 | EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl(); |
3955 | } |
3956 | EPI.ExtParameterInfos = getExtParameterInfosOrNull(); |
3957 | return EPI; |
3958 | } |
3959 | |
3960 | /// Get the kind of exception specification on this function. |
3961 | ExceptionSpecificationType getExceptionSpecType() const { |
3962 | return static_cast<ExceptionSpecificationType>( |
3963 | FunctionTypeBits.ExceptionSpecType); |
3964 | } |
3965 | |
3966 | /// Return whether this function has any kind of exception spec. |
3967 | bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } |
3968 | |
3969 | /// Return whether this function has a dynamic (throw) exception spec. |
3970 | bool hasDynamicExceptionSpec() const { |
3971 | return isDynamicExceptionSpec(getExceptionSpecType()); |
3972 | } |
3973 | |
3974 | /// Return whether this function has a noexcept exception spec. |
3975 | bool hasNoexceptExceptionSpec() const { |
3976 | return isNoexceptExceptionSpec(getExceptionSpecType()); |
3977 | } |
3978 | |
3979 | /// Return whether this function has a dependent exception spec. |
3980 | bool hasDependentExceptionSpec() const; |
3981 | |
3982 | /// Return whether this function has an instantiation-dependent exception |
3983 | /// spec. |
3984 | bool hasInstantiationDependentExceptionSpec() const; |
3985 | |
3986 | /// Return the number of types in the exception specification. |
3987 | unsigned getNumExceptions() const { |
3988 | return getExceptionSpecType() == EST_Dynamic |
3989 | ? getTrailingObjects<FunctionTypeExtraBitfields>() |
3990 | ->NumExceptionType |
3991 | : 0; |
3992 | } |
3993 | |
3994 | /// Return the ith exception type, where 0 <= i < getNumExceptions(). |
3995 | QualType getExceptionType(unsigned i) const { |
3996 | assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3996, __PRETTY_FUNCTION__)); |
3997 | return exception_begin()[i]; |
3998 | } |
3999 | |
4000 | /// Return the expression inside noexcept(expression), or a null pointer |
4001 | /// if there is none (because the exception spec is not of this form). |
4002 | Expr *getNoexceptExpr() const { |
4003 | if (!isComputedNoexcept(getExceptionSpecType())) |
4004 | return nullptr; |
4005 | return *getTrailingObjects<Expr *>(); |
4006 | } |
4007 | |
4008 | /// If this function type has an exception specification which hasn't |
4009 | /// been determined yet (either because it has not been evaluated or because |
4010 | /// it has not been instantiated), this is the function whose exception |
4011 | /// specification is represented by this type. |
4012 | FunctionDecl *getExceptionSpecDecl() const { |
4013 | if (getExceptionSpecType() != EST_Uninstantiated && |
4014 | getExceptionSpecType() != EST_Unevaluated) |
4015 | return nullptr; |
4016 | return getTrailingObjects<FunctionDecl *>()[0]; |
4017 | } |
4018 | |
4019 | /// If this function type has an uninstantiated exception |
4020 | /// specification, this is the function whose exception specification |
4021 | /// should be instantiated to find the exception specification for |
4022 | /// this type. |
4023 | FunctionDecl *getExceptionSpecTemplate() const { |
4024 | if (getExceptionSpecType() != EST_Uninstantiated) |
4025 | return nullptr; |
4026 | return getTrailingObjects<FunctionDecl *>()[1]; |
4027 | } |
4028 | |
4029 | /// Determine whether this function type has a non-throwing exception |
4030 | /// specification. |
4031 | CanThrowResult canThrow() const; |
4032 | |
4033 | /// Determine whether this function type has a non-throwing exception |
4034 | /// specification. If this depends on template arguments, returns |
4035 | /// \c ResultIfDependent. |
4036 | bool isNothrow(bool ResultIfDependent = false) const { |
4037 | return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; |
4038 | } |
4039 | |
4040 | /// Whether this function prototype is variadic. |
4041 | bool isVariadic() const { return FunctionTypeBits.Variadic; } |
4042 | |
4043 | /// Determines whether this function prototype contains a |
4044 | /// parameter pack at the end. |
4045 | /// |
4046 | /// A function template whose last parameter is a parameter pack can be |
4047 | /// called with an arbitrary number of arguments, much like a variadic |
4048 | /// function. |
4049 | bool isTemplateVariadic() const; |
4050 | |
4051 | /// Whether this function prototype has a trailing return type. |
4052 | bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } |
4053 | |
4054 | Qualifiers getMethodQuals() const { |
4055 | if (hasExtQualifiers()) |
4056 | return *getTrailingObjects<Qualifiers>(); |
4057 | else |
4058 | return getFastTypeQuals(); |
4059 | } |
4060 | |
4061 | /// Retrieve the ref-qualifier associated with this function type. |
4062 | RefQualifierKind getRefQualifier() const { |
4063 | return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); |
4064 | } |
4065 | |
4066 | using param_type_iterator = const QualType *; |
4067 | using param_type_range = llvm::iterator_range<param_type_iterator>; |
4068 | |
4069 | param_type_range param_types() const { |
4070 | return param_type_range(param_type_begin(), param_type_end()); |
4071 | } |
4072 | |
4073 | param_type_iterator param_type_begin() const { |
4074 | return getTrailingObjects<QualType>(); |
4075 | } |
4076 | |
4077 | param_type_iterator param_type_end() const { |
4078 | return param_type_begin() + getNumParams(); |
4079 | } |
4080 | |
4081 | using exception_iterator = const QualType *; |
4082 | |
4083 | ArrayRef<QualType> exceptions() const { |
4084 | return llvm::makeArrayRef(exception_begin(), exception_end()); |
4085 | } |
4086 | |
4087 | exception_iterator exception_begin() const { |
4088 | return reinterpret_cast<exception_iterator>( |
4089 | getTrailingObjects<ExceptionType>()); |
4090 | } |
4091 | |
4092 | exception_iterator exception_end() const { |
4093 | return exception_begin() + getNumExceptions(); |
4094 | } |
4095 | |
4096 | /// Is there any interesting extra information for any of the parameters |
4097 | /// of this function type? |
4098 | bool hasExtParameterInfos() const { |
4099 | return FunctionTypeBits.HasExtParameterInfos; |
4100 | } |
4101 | |
4102 | ArrayRef<ExtParameterInfo> getExtParameterInfos() const { |
4103 | assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4103, __PRETTY_FUNCTION__)); |
4104 | return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), |
4105 | getNumParams()); |
4106 | } |
4107 | |
4108 | /// Return a pointer to the beginning of the array of extra parameter |
4109 | /// information, if present, or else null if none of the parameters |
4110 | /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. |
4111 | const ExtParameterInfo *getExtParameterInfosOrNull() const { |
4112 | if (!hasExtParameterInfos()) |
4113 | return nullptr; |
4114 | return getTrailingObjects<ExtParameterInfo>(); |
4115 | } |
4116 | |
4117 | ExtParameterInfo getExtParameterInfo(unsigned I) const { |
4118 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4118, __PRETTY_FUNCTION__)); |
4119 | if (hasExtParameterInfos()) |
4120 | return getTrailingObjects<ExtParameterInfo>()[I]; |
4121 | return ExtParameterInfo(); |
4122 | } |
4123 | |
4124 | ParameterABI getParameterABI(unsigned I) const { |
4125 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4125, __PRETTY_FUNCTION__)); |
4126 | if (hasExtParameterInfos()) |
4127 | return getTrailingObjects<ExtParameterInfo>()[I].getABI(); |
4128 | return ParameterABI::Ordinary; |
4129 | } |
4130 | |
4131 | bool isParamConsumed(unsigned I) const { |
4132 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4132, __PRETTY_FUNCTION__)); |
4133 | if (hasExtParameterInfos()) |
4134 | return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); |
4135 | return false; |
4136 | } |
4137 | |
4138 | bool isSugared() const { return false; } |
4139 | QualType desugar() const { return QualType(this, 0); } |
4140 | |
4141 | void printExceptionSpecification(raw_ostream &OS, |
4142 | const PrintingPolicy &Policy) const; |
4143 | |
4144 | static bool classof(const Type *T) { |
4145 | return T->getTypeClass() == FunctionProto; |
4146 | } |
4147 | |
4148 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); |
4149 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, |
4150 | param_type_iterator ArgTys, unsigned NumArgs, |
4151 | const ExtProtoInfo &EPI, const ASTContext &Context, |
4152 | bool Canonical); |
4153 | }; |
4154 | |
4155 | /// Represents the dependent type named by a dependently-scoped |
4156 | /// typename using declaration, e.g. |
4157 | /// using typename Base<T>::foo; |
4158 | /// |
4159 | /// Template instantiation turns these into the underlying type. |
4160 | class UnresolvedUsingType : public Type { |
4161 | friend class ASTContext; // ASTContext creates these. |
4162 | |
4163 | UnresolvedUsingTypenameDecl *Decl; |
4164 | |
4165 | UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) |
4166 | : Type(UnresolvedUsing, QualType(), true, true, false, |
4167 | /*ContainsUnexpandedParameterPack=*/false), |
4168 | Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {} |
4169 | |
4170 | public: |
4171 | UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } |
4172 | |
4173 | bool isSugared() const { return false; } |
4174 | QualType desugar() const { return QualType(this, 0); } |
4175 | |
4176 | static bool classof(const Type *T) { |
4177 | return T->getTypeClass() == UnresolvedUsing; |
4178 | } |
4179 | |
4180 | void Profile(llvm::FoldingSetNodeID &ID) { |
4181 | return Profile(ID, Decl); |
4182 | } |
4183 | |
4184 | static void Profile(llvm::FoldingSetNodeID &ID, |
4185 | UnresolvedUsingTypenameDecl *D) { |
4186 | ID.AddPointer(D); |
4187 | } |
4188 | }; |
4189 | |
4190 | class TypedefType : public Type { |
4191 | TypedefNameDecl *Decl; |
4192 | |
4193 | protected: |
4194 | friend class ASTContext; // ASTContext creates these. |
4195 | |
4196 | TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can) |
4197 | : Type(tc, can, can->isDependentType(), |
4198 | can->isInstantiationDependentType(), |
4199 | can->isVariablyModifiedType(), |
4200 | /*ContainsUnexpandedParameterPack=*/false), |
4201 | Decl(const_cast<TypedefNameDecl*>(D)) { |
4202 | assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type" ) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4202, __PRETTY_FUNCTION__)); |
4203 | } |
4204 | |
4205 | public: |
4206 | TypedefNameDecl *getDecl() const { return Decl; } |
4207 | |
4208 | bool isSugared() const { return true; } |
4209 | QualType desugar() const; |
4210 | |
4211 | static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } |
4212 | }; |
4213 | |
4214 | /// Sugar type that represents a type that was qualified by a qualifier written |
4215 | /// as a macro invocation. |
4216 | class MacroQualifiedType : public Type { |
4217 | friend class ASTContext; // ASTContext creates these. |
4218 | |
4219 | QualType UnderlyingTy; |
4220 | const IdentifierInfo *MacroII; |
4221 | |
4222 | MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy, |
4223 | const IdentifierInfo *MacroII) |
4224 | : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(), |
4225 | UnderlyingTy->isInstantiationDependentType(), |
4226 | UnderlyingTy->isVariablyModifiedType(), |
4227 | UnderlyingTy->containsUnexpandedParameterPack()), |
4228 | UnderlyingTy(UnderlyingTy), MacroII(MacroII) { |
4229 | assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4230, __PRETTY_FUNCTION__)) |
4230 | "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4230, __PRETTY_FUNCTION__)); |
4231 | } |
4232 | |
4233 | public: |
4234 | const IdentifierInfo *getMacroIdentifier() const { return MacroII; } |
4235 | QualType getUnderlyingType() const { return UnderlyingTy; } |
4236 | |
4237 | /// Return this attributed type's modified type with no qualifiers attached to |
4238 | /// it. |
4239 | QualType getModifiedType() const; |
4240 | |
4241 | bool isSugared() const { return true; } |
4242 | QualType desugar() const; |
4243 | |
4244 | static bool classof(const Type *T) { |
4245 | return T->getTypeClass() == MacroQualified; |
4246 | } |
4247 | }; |
4248 | |
4249 | /// Represents a `typeof` (or __typeof__) expression (a GCC extension). |
4250 | class TypeOfExprType : public Type { |
4251 | Expr *TOExpr; |
4252 | |
4253 | protected: |
4254 | friend class ASTContext; // ASTContext creates these. |
4255 | |
4256 | TypeOfExprType(Expr *E, QualType can = QualType()); |
4257 | |
4258 | public: |
4259 | Expr *getUnderlyingExpr() const { return TOExpr; } |
4260 | |
4261 | /// Remove a single level of sugar. |
4262 | QualType desugar() const; |
4263 | |
4264 | /// Returns whether this type directly provides sugar. |
4265 | bool isSugared() const; |
4266 | |
4267 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } |
4268 | }; |
4269 | |
4270 | /// Internal representation of canonical, dependent |
4271 | /// `typeof(expr)` types. |
4272 | /// |
4273 | /// This class is used internally by the ASTContext to manage |
4274 | /// canonical, dependent types, only. Clients will only see instances |
4275 | /// of this class via TypeOfExprType nodes. |
4276 | class DependentTypeOfExprType |
4277 | : public TypeOfExprType, public llvm::FoldingSetNode { |
4278 | const ASTContext &Context; |
4279 | |
4280 | public: |
4281 | DependentTypeOfExprType(const ASTContext &Context, Expr *E) |
4282 | : TypeOfExprType(E), Context(Context) {} |
4283 | |
4284 | void Profile(llvm::FoldingSetNodeID &ID) { |
4285 | Profile(ID, Context, getUnderlyingExpr()); |
4286 | } |
4287 | |
4288 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4289 | Expr *E); |
4290 | }; |
4291 | |
4292 | /// Represents `typeof(type)`, a GCC extension. |
4293 | class TypeOfType : public Type { |
4294 | friend class ASTContext; // ASTContext creates these. |
4295 | |
4296 | QualType TOType; |
4297 | |
4298 | TypeOfType(QualType T, QualType can) |
4299 | : Type(TypeOf, can, T->isDependentType(), |
4300 | T->isInstantiationDependentType(), |
4301 | T->isVariablyModifiedType(), |
4302 | T->containsUnexpandedParameterPack()), |
4303 | TOType(T) { |
4304 | assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type" ) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4304, __PRETTY_FUNCTION__)); |
4305 | } |
4306 | |
4307 | public: |
4308 | QualType getUnderlyingType() const { return TOType; } |
4309 | |
4310 | /// Remove a single level of sugar. |
4311 | QualType desugar() const { return getUnderlyingType(); } |
4312 | |
4313 | /// Returns whether this type directly provides sugar. |
4314 | bool isSugared() const { return true; } |
4315 | |
4316 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } |
4317 | }; |
4318 | |
4319 | /// Represents the type `decltype(expr)` (C++11). |
4320 | class DecltypeType : public Type { |
4321 | Expr *E; |
4322 | QualType UnderlyingType; |
4323 | |
4324 | protected: |
4325 | friend class ASTContext; // ASTContext creates these. |
4326 | |
4327 | DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); |
4328 | |
4329 | public: |
4330 | Expr *getUnderlyingExpr() const { return E; } |
4331 | QualType getUnderlyingType() const { return UnderlyingType; } |
4332 | |
4333 | /// Remove a single level of sugar. |
4334 | QualType desugar() const; |
4335 | |
4336 | /// Returns whether this type directly provides sugar. |
4337 | bool isSugared() const; |
4338 | |
4339 | static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } |
4340 | }; |
4341 | |
4342 | /// Internal representation of canonical, dependent |
4343 | /// decltype(expr) types. |
4344 | /// |
4345 | /// This class is used internally by the ASTContext to manage |
4346 | /// canonical, dependent types, only. Clients will only see instances |
4347 | /// of this class via DecltypeType nodes. |
4348 | class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { |
4349 | const ASTContext &Context; |
4350 | |
4351 | public: |
4352 | DependentDecltypeType(const ASTContext &Context, Expr *E); |
4353 | |
4354 | void Profile(llvm::FoldingSetNodeID &ID) { |
4355 | Profile(ID, Context, getUnderlyingExpr()); |
4356 | } |
4357 | |
4358 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4359 | Expr *E); |
4360 | }; |
4361 | |
4362 | /// A unary type transform, which is a type constructed from another. |
4363 | class UnaryTransformType : public Type { |
4364 | public: |
4365 | enum UTTKind { |
4366 | EnumUnderlyingType |
4367 | }; |
4368 | |
4369 | private: |
4370 | /// The untransformed type. |
4371 | QualType BaseType; |
4372 | |
4373 | /// The transformed type if not dependent, otherwise the same as BaseType. |
4374 | QualType UnderlyingType; |
4375 | |
4376 | UTTKind UKind; |
4377 | |
4378 | protected: |
4379 | friend class ASTContext; |
4380 | |
4381 | UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, |
4382 | QualType CanonicalTy); |
4383 | |
4384 | public: |
4385 | bool isSugared() const { return !isDependentType(); } |
4386 | QualType desugar() const { return UnderlyingType; } |
4387 | |
4388 | QualType getUnderlyingType() const { return UnderlyingType; } |
4389 | QualType getBaseType() const { return BaseType; } |
4390 | |
4391 | UTTKind getUTTKind() const { return UKind; } |
4392 | |
4393 | static bool classof(const Type *T) { |
4394 | return T->getTypeClass() == UnaryTransform; |
4395 | } |
4396 | }; |
4397 | |
4398 | /// Internal representation of canonical, dependent |
4399 | /// __underlying_type(type) types. |
4400 | /// |
4401 | /// This class is used internally by the ASTContext to manage |
4402 | /// canonical, dependent types, only. Clients will only see instances |
4403 | /// of this class via UnaryTransformType nodes. |
4404 | class DependentUnaryTransformType : public UnaryTransformType, |
4405 | public llvm::FoldingSetNode { |
4406 | public: |
4407 | DependentUnaryTransformType(const ASTContext &C, QualType BaseType, |
4408 | UTTKind UKind); |
4409 | |
4410 | void Profile(llvm::FoldingSetNodeID &ID) { |
4411 | Profile(ID, getBaseType(), getUTTKind()); |
4412 | } |
4413 | |
4414 | static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, |
4415 | UTTKind UKind) { |
4416 | ID.AddPointer(BaseType.getAsOpaquePtr()); |
4417 | ID.AddInteger((unsigned)UKind); |
4418 | } |
4419 | }; |
4420 | |
4421 | class TagType : public Type { |
4422 | friend class ASTReader; |
4423 | |
4424 | /// Stores the TagDecl associated with this type. The decl may point to any |
4425 | /// TagDecl that declares the entity. |
4426 | TagDecl *decl; |
4427 | |
4428 | protected: |
4429 | TagType(TypeClass TC, const TagDecl *D, QualType can); |
4430 | |
4431 | public: |
4432 | TagDecl *getDecl() const; |
4433 | |
4434 | /// Determines whether this type is in the process of being defined. |
4435 | bool isBeingDefined() const; |
4436 | |
4437 | static bool classof(const Type *T) { |
4438 | return T->getTypeClass() == Enum || T->getTypeClass() == Record; |
4439 | } |
4440 | }; |
4441 | |
4442 | /// A helper class that allows the use of isa/cast/dyncast |
4443 | /// to detect TagType objects of structs/unions/classes. |
4444 | class RecordType : public TagType { |
4445 | protected: |
4446 | friend class ASTContext; // ASTContext creates these. |
4447 | |
4448 | explicit RecordType(const RecordDecl *D) |
4449 | : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4450 | explicit RecordType(TypeClass TC, RecordDecl *D) |
4451 | : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4452 | |
4453 | public: |
4454 | RecordDecl *getDecl() const { |
4455 | return reinterpret_cast<RecordDecl*>(TagType::getDecl()); |
4456 | } |
4457 | |
4458 | /// Recursively check all fields in the record for const-ness. If any field |
4459 | /// is declared const, return true. Otherwise, return false. |
4460 | bool hasConstFields() const; |
4461 | |
4462 | bool isSugared() const { return false; } |
4463 | QualType desugar() const { return QualType(this, 0); } |
4464 | |
4465 | static bool classof(const Type *T) { return T->getTypeClass() == Record; } |
4466 | }; |
4467 | |
4468 | /// A helper class that allows the use of isa/cast/dyncast |
4469 | /// to detect TagType objects of enums. |
4470 | class EnumType : public TagType { |
4471 | friend class ASTContext; // ASTContext creates these. |
4472 | |
4473 | explicit EnumType(const EnumDecl *D) |
4474 | : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4475 | |
4476 | public: |
4477 | EnumDecl *getDecl() const { |
4478 | return reinterpret_cast<EnumDecl*>(TagType::getDecl()); |
4479 | } |
4480 | |
4481 | bool isSugared() const { return false; } |
4482 | QualType desugar() const { return QualType(this, 0); } |
4483 | |
4484 | static bool classof(const Type *T) { return T->getTypeClass() == Enum; } |
4485 | }; |
4486 | |
4487 | /// An attributed type is a type to which a type attribute has been applied. |
4488 | /// |
4489 | /// The "modified type" is the fully-sugared type to which the attributed |
4490 | /// type was applied; generally it is not canonically equivalent to the |
4491 | /// attributed type. The "equivalent type" is the minimally-desugared type |
4492 | /// which the type is canonically equivalent to. |
4493 | /// |
4494 | /// For example, in the following attributed type: |
4495 | /// int32_t __attribute__((vector_size(16))) |
4496 | /// - the modified type is the TypedefType for int32_t |
4497 | /// - the equivalent type is VectorType(16, int32_t) |
4498 | /// - the canonical type is VectorType(16, int) |
4499 | class AttributedType : public Type, public llvm::FoldingSetNode { |
4500 | public: |
4501 | using Kind = attr::Kind; |
4502 | |
4503 | private: |
4504 | friend class ASTContext; // ASTContext creates these |
4505 | |
4506 | QualType ModifiedType; |
4507 | QualType EquivalentType; |
4508 | |
4509 | AttributedType(QualType canon, attr::Kind attrKind, QualType modified, |
4510 | QualType equivalent) |
4511 | : Type(Attributed, canon, equivalent->isDependentType(), |
4512 | equivalent->isInstantiationDependentType(), |
4513 | equivalent->isVariablyModifiedType(), |
4514 | equivalent->containsUnexpandedParameterPack()), |
4515 | ModifiedType(modified), EquivalentType(equivalent) { |
4516 | AttributedTypeBits.AttrKind = attrKind; |
4517 | } |
4518 | |
4519 | public: |
4520 | Kind getAttrKind() const { |
4521 | return static_cast<Kind>(AttributedTypeBits.AttrKind); |
4522 | } |
4523 | |
4524 | QualType getModifiedType() const { return ModifiedType; } |
4525 | QualType getEquivalentType() const { return EquivalentType; } |
4526 | |
4527 | bool isSugared() const { return true; } |
4528 | QualType desugar() const { return getEquivalentType(); } |
4529 | |
4530 | /// Does this attribute behave like a type qualifier? |
4531 | /// |
4532 | /// A type qualifier adjusts a type to provide specialized rules for |
4533 | /// a specific object, like the standard const and volatile qualifiers. |
4534 | /// This includes attributes controlling things like nullability, |
4535 | /// address spaces, and ARC ownership. The value of the object is still |
4536 | /// largely described by the modified type. |
4537 | /// |
4538 | /// In contrast, many type attributes "rewrite" their modified type to |
4539 | /// produce a fundamentally different type, not necessarily related in any |
4540 | /// formalizable way to the original type. For example, calling convention |
4541 | /// and vector attributes are not simple type qualifiers. |
4542 | /// |
4543 | /// Type qualifiers are often, but not always, reflected in the canonical |
4544 | /// type. |
4545 | bool isQualifier() const; |
4546 | |
4547 | bool isMSTypeSpec() const; |
4548 | |
4549 | bool isCallingConv() const; |
4550 | |
4551 | llvm::Optional<NullabilityKind> getImmediateNullability() const; |
4552 | |
4553 | /// Retrieve the attribute kind corresponding to the given |
4554 | /// nullability kind. |
4555 | static Kind getNullabilityAttrKind(NullabilityKind kind) { |
4556 | switch (kind) { |
4557 | case NullabilityKind::NonNull: |
4558 | return attr::TypeNonNull; |
4559 | |
4560 | case NullabilityKind::Nullable: |
4561 | return attr::TypeNullable; |
4562 | |
4563 | case NullabilityKind::Unspecified: |
4564 | return attr::TypeNullUnspecified; |
4565 | } |
4566 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4566); |
4567 | } |
4568 | |
4569 | /// Strip off the top-level nullability annotation on the given |
4570 | /// type, if it's there. |
4571 | /// |
4572 | /// \param T The type to strip. If the type is exactly an |
4573 | /// AttributedType specifying nullability (without looking through |
4574 | /// type sugar), the nullability is returned and this type changed |
4575 | /// to the underlying modified type. |
4576 | /// |
4577 | /// \returns the top-level nullability, if present. |
4578 | static Optional<NullabilityKind> stripOuterNullability(QualType &T); |
4579 | |
4580 | void Profile(llvm::FoldingSetNodeID &ID) { |
4581 | Profile(ID, getAttrKind(), ModifiedType, EquivalentType); |
4582 | } |
4583 | |
4584 | static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, |
4585 | QualType modified, QualType equivalent) { |
4586 | ID.AddInteger(attrKind); |
4587 | ID.AddPointer(modified.getAsOpaquePtr()); |
4588 | ID.AddPointer(equivalent.getAsOpaquePtr()); |
4589 | } |
4590 | |
4591 | static bool classof(const Type *T) { |
4592 | return T->getTypeClass() == Attributed; |
4593 | } |
4594 | }; |
4595 | |
4596 | class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4597 | friend class ASTContext; // ASTContext creates these |
4598 | |
4599 | // Helper data collector for canonical types. |
4600 | struct CanonicalTTPTInfo { |
4601 | unsigned Depth : 15; |
4602 | unsigned ParameterPack : 1; |
4603 | unsigned Index : 16; |
4604 | }; |
4605 | |
4606 | union { |
4607 | // Info for the canonical type. |
4608 | CanonicalTTPTInfo CanTTPTInfo; |
4609 | |
4610 | // Info for the non-canonical type. |
4611 | TemplateTypeParmDecl *TTPDecl; |
4612 | }; |
4613 | |
4614 | /// Build a non-canonical type. |
4615 | TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) |
4616 | : Type(TemplateTypeParm, Canon, /*Dependent=*/true, |
4617 | /*InstantiationDependent=*/true, |
4618 | /*VariablyModified=*/false, |
4619 | Canon->containsUnexpandedParameterPack()), |
4620 | TTPDecl(TTPDecl) {} |
4621 | |
4622 | /// Build the canonical type. |
4623 | TemplateTypeParmType(unsigned D, unsigned I, bool PP) |
4624 | : Type(TemplateTypeParm, QualType(this, 0), |
4625 | /*Dependent=*/true, |
4626 | /*InstantiationDependent=*/true, |
4627 | /*VariablyModified=*/false, PP) { |
4628 | CanTTPTInfo.Depth = D; |
4629 | CanTTPTInfo.Index = I; |
4630 | CanTTPTInfo.ParameterPack = PP; |
4631 | } |
4632 | |
4633 | const CanonicalTTPTInfo& getCanTTPTInfo() const { |
4634 | QualType Can = getCanonicalTypeInternal(); |
4635 | return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; |
4636 | } |
4637 | |
4638 | public: |
4639 | unsigned getDepth() const { return getCanTTPTInfo().Depth; } |
4640 | unsigned getIndex() const { return getCanTTPTInfo().Index; } |
4641 | bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } |
4642 | |
4643 | TemplateTypeParmDecl *getDecl() const { |
4644 | return isCanonicalUnqualified() ? nullptr : TTPDecl; |
4645 | } |
4646 | |
4647 | IdentifierInfo *getIdentifier() const; |
4648 | |
4649 | bool isSugared() const { return false; } |
4650 | QualType desugar() const { return QualType(this, 0); } |
4651 | |
4652 | void Profile(llvm::FoldingSetNodeID &ID) { |
4653 | Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); |
4654 | } |
4655 | |
4656 | static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, |
4657 | unsigned Index, bool ParameterPack, |
4658 | TemplateTypeParmDecl *TTPDecl) { |
4659 | ID.AddInteger(Depth); |
4660 | ID.AddInteger(Index); |
4661 | ID.AddBoolean(ParameterPack); |
4662 | ID.AddPointer(TTPDecl); |
4663 | } |
4664 | |
4665 | static bool classof(const Type *T) { |
4666 | return T->getTypeClass() == TemplateTypeParm; |
4667 | } |
4668 | }; |
4669 | |
4670 | /// Represents the result of substituting a type for a template |
4671 | /// type parameter. |
4672 | /// |
4673 | /// Within an instantiated template, all template type parameters have |
4674 | /// been replaced with these. They are used solely to record that a |
4675 | /// type was originally written as a template type parameter; |
4676 | /// therefore they are never canonical. |
4677 | class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4678 | friend class ASTContext; |
4679 | |
4680 | // The original type parameter. |
4681 | const TemplateTypeParmType *Replaced; |
4682 | |
4683 | SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) |
4684 | : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(), |
4685 | Canon->isInstantiationDependentType(), |
4686 | Canon->isVariablyModifiedType(), |
4687 | Canon->containsUnexpandedParameterPack()), |
4688 | Replaced(Param) {} |
4689 | |
4690 | public: |
4691 | /// Gets the template parameter that was substituted for. |
4692 | const TemplateTypeParmType *getReplacedParameter() const { |
4693 | return Replaced; |
4694 | } |
4695 | |
4696 | /// Gets the type that was substituted for the template |
4697 | /// parameter. |
4698 | QualType getReplacementType() const { |
4699 | return getCanonicalTypeInternal(); |
4700 | } |
4701 | |
4702 | bool isSugared() const { return true; } |
4703 | QualType desugar() const { return getReplacementType(); } |
4704 | |
4705 | void Profile(llvm::FoldingSetNodeID &ID) { |
4706 | Profile(ID, getReplacedParameter(), getReplacementType()); |
4707 | } |
4708 | |
4709 | static void Profile(llvm::FoldingSetNodeID &ID, |
4710 | const TemplateTypeParmType *Replaced, |
4711 | QualType Replacement) { |
4712 | ID.AddPointer(Replaced); |
4713 | ID.AddPointer(Replacement.getAsOpaquePtr()); |
4714 | } |
4715 | |
4716 | static bool classof(const Type *T) { |
4717 | return T->getTypeClass() == SubstTemplateTypeParm; |
4718 | } |
4719 | }; |
4720 | |
4721 | /// Represents the result of substituting a set of types for a template |
4722 | /// type parameter pack. |
4723 | /// |
4724 | /// When a pack expansion in the source code contains multiple parameter packs |
4725 | /// and those parameter packs correspond to different levels of template |
4726 | /// parameter lists, this type node is used to represent a template type |
4727 | /// parameter pack from an outer level, which has already had its argument pack |
4728 | /// substituted but that still lives within a pack expansion that itself |
4729 | /// could not be instantiated. When actually performing a substitution into |
4730 | /// that pack expansion (e.g., when all template parameters have corresponding |
4731 | /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType |
4732 | /// at the current pack substitution index. |
4733 | class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { |
4734 | friend class ASTContext; |
4735 | |
4736 | /// The original type parameter. |
4737 | const TemplateTypeParmType *Replaced; |
4738 | |
4739 | /// A pointer to the set of template arguments that this |
4740 | /// parameter pack is instantiated with. |
4741 | const TemplateArgument *Arguments; |
4742 | |
4743 | SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, |
4744 | QualType Canon, |
4745 | const TemplateArgument &ArgPack); |
4746 | |
4747 | public: |
4748 | IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } |
4749 | |
4750 | /// Gets the template parameter that was substituted for. |
4751 | const TemplateTypeParmType *getReplacedParameter() const { |
4752 | return Replaced; |
4753 | } |
4754 | |
4755 | unsigned getNumArgs() const { |
4756 | return SubstTemplateTypeParmPackTypeBits.NumArgs; |
4757 | } |
4758 | |
4759 | bool isSugared() const { return false; } |
4760 | QualType desugar() const { return QualType(this, 0); } |
4761 | |
4762 | TemplateArgument getArgumentPack() const; |
4763 | |
4764 | void Profile(llvm::FoldingSetNodeID &ID); |
4765 | static void Profile(llvm::FoldingSetNodeID &ID, |
4766 | const TemplateTypeParmType *Replaced, |
4767 | const TemplateArgument &ArgPack); |
4768 | |
4769 | static bool classof(const Type *T) { |
4770 | return T->getTypeClass() == SubstTemplateTypeParmPack; |
4771 | } |
4772 | }; |
4773 | |
4774 | /// Common base class for placeholders for types that get replaced by |
4775 | /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced |
4776 | /// class template types, and (eventually) constrained type names from the C++ |
4777 | /// Concepts TS. |
4778 | /// |
4779 | /// These types are usually a placeholder for a deduced type. However, before |
4780 | /// the initializer is attached, or (usually) if the initializer is |
4781 | /// type-dependent, there is no deduced type and the type is canonical. In |
4782 | /// the latter case, it is also a dependent type. |
4783 | class DeducedType : public Type { |
4784 | protected: |
4785 | DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent, |
4786 | bool IsInstantiationDependent, bool ContainsParameterPack) |
4787 | : Type(TC, |
4788 | // FIXME: Retain the sugared deduced type? |
4789 | DeducedAsType.isNull() ? QualType(this, 0) |
4790 | : DeducedAsType.getCanonicalType(), |
4791 | IsDependent, IsInstantiationDependent, |
4792 | /*VariablyModified=*/false, ContainsParameterPack) { |
4793 | if (!DeducedAsType.isNull()) { |
4794 | if (DeducedAsType->isDependentType()) |
4795 | setDependent(); |
4796 | if (DeducedAsType->isInstantiationDependentType()) |
4797 | setInstantiationDependent(); |
4798 | if (DeducedAsType->containsUnexpandedParameterPack()) |
4799 | setContainsUnexpandedParameterPack(); |
4800 | } |
4801 | } |
4802 | |
4803 | public: |
4804 | bool isSugared() const { return !isCanonicalUnqualified(); } |
4805 | QualType desugar() const { return getCanonicalTypeInternal(); } |
4806 | |
4807 | /// Get the type deduced for this placeholder type, or null if it's |
4808 | /// either not been deduced or was deduced to a dependent type. |
4809 | QualType getDeducedType() const { |
4810 | return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType(); |
4811 | } |
4812 | bool isDeduced() const { |
4813 | return !isCanonicalUnqualified() || isDependentType(); |
4814 | } |
4815 | |
4816 | static bool classof(const Type *T) { |
4817 | return T->getTypeClass() == Auto || |
4818 | T->getTypeClass() == DeducedTemplateSpecialization; |
4819 | } |
4820 | }; |
4821 | |
4822 | /// Represents a C++11 auto or C++14 decltype(auto) type. |
4823 | class AutoType : public DeducedType, public llvm::FoldingSetNode { |
4824 | friend class ASTContext; // ASTContext creates these |
4825 | |
4826 | AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, |
4827 | bool IsDeducedAsDependent, bool IsDeducedAsPack) |
4828 | : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent, |
4829 | IsDeducedAsDependent, IsDeducedAsPack) { |
4830 | AutoTypeBits.Keyword = (unsigned)Keyword; |
4831 | } |
4832 | |
4833 | public: |
4834 | bool isDecltypeAuto() const { |
4835 | return getKeyword() == AutoTypeKeyword::DecltypeAuto; |
4836 | } |
4837 | |
4838 | AutoTypeKeyword getKeyword() const { |
4839 | return (AutoTypeKeyword)AutoTypeBits.Keyword; |
4840 | } |
4841 | |
4842 | void Profile(llvm::FoldingSetNodeID &ID) { |
4843 | Profile(ID, getDeducedType(), getKeyword(), isDependentType(), |
4844 | containsUnexpandedParameterPack()); |
4845 | } |
4846 | |
4847 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced, |
4848 | AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) { |
4849 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
4850 | ID.AddInteger((unsigned)Keyword); |
4851 | ID.AddBoolean(IsDependent); |
4852 | ID.AddBoolean(IsPack); |
4853 | } |
4854 | |
4855 | static bool classof(const Type *T) { |
4856 | return T->getTypeClass() == Auto; |
4857 | } |
4858 | }; |
4859 | |
4860 | /// Represents a C++17 deduced template specialization type. |
4861 | class DeducedTemplateSpecializationType : public DeducedType, |
4862 | public llvm::FoldingSetNode { |
4863 | friend class ASTContext; // ASTContext creates these |
4864 | |
4865 | /// The name of the template whose arguments will be deduced. |
4866 | TemplateName Template; |
4867 | |
4868 | DeducedTemplateSpecializationType(TemplateName Template, |
4869 | QualType DeducedAsType, |
4870 | bool IsDeducedAsDependent) |
4871 | : DeducedType(DeducedTemplateSpecialization, DeducedAsType, |
4872 | IsDeducedAsDependent || Template.isDependent(), |
4873 | IsDeducedAsDependent || Template.isInstantiationDependent(), |
4874 | Template.containsUnexpandedParameterPack()), |
4875 | Template(Template) {} |
4876 | |
4877 | public: |
4878 | /// Retrieve the name of the template that we are deducing. |
4879 | TemplateName getTemplateName() const { return Template;} |
4880 | |
4881 | void Profile(llvm::FoldingSetNodeID &ID) { |
4882 | Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); |
4883 | } |
4884 | |
4885 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, |
4886 | QualType Deduced, bool IsDependent) { |
4887 | Template.Profile(ID); |
4888 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
4889 | ID.AddBoolean(IsDependent); |
4890 | } |
4891 | |
4892 | static bool classof(const Type *T) { |
4893 | return T->getTypeClass() == DeducedTemplateSpecialization; |
4894 | } |
4895 | }; |
4896 | |
4897 | /// Represents a type template specialization; the template |
4898 | /// must be a class template, a type alias template, or a template |
4899 | /// template parameter. A template which cannot be resolved to one of |
4900 | /// these, e.g. because it is written with a dependent scope |
4901 | /// specifier, is instead represented as a |
4902 | /// @c DependentTemplateSpecializationType. |
4903 | /// |
4904 | /// A non-dependent template specialization type is always "sugar", |
4905 | /// typically for a \c RecordType. For example, a class template |
4906 | /// specialization type of \c vector<int> will refer to a tag type for |
4907 | /// the instantiation \c std::vector<int, std::allocator<int>> |
4908 | /// |
4909 | /// Template specializations are dependent if either the template or |
4910 | /// any of the template arguments are dependent, in which case the |
4911 | /// type may also be canonical. |
4912 | /// |
4913 | /// Instances of this type are allocated with a trailing array of |
4914 | /// TemplateArguments, followed by a QualType representing the |
4915 | /// non-canonical aliased type when the template is a type alias |
4916 | /// template. |
4917 | class alignas(8) TemplateSpecializationType |
4918 | : public Type, |
4919 | public llvm::FoldingSetNode { |
4920 | friend class ASTContext; // ASTContext creates these |
4921 | |
4922 | /// The name of the template being specialized. This is |
4923 | /// either a TemplateName::Template (in which case it is a |
4924 | /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a |
4925 | /// TypeAliasTemplateDecl*), a |
4926 | /// TemplateName::SubstTemplateTemplateParmPack, or a |
4927 | /// TemplateName::SubstTemplateTemplateParm (in which case the |
4928 | /// replacement must, recursively, be one of these). |
4929 | TemplateName Template; |
4930 | |
4931 | TemplateSpecializationType(TemplateName T, |
4932 | ArrayRef<TemplateArgument> Args, |
4933 | QualType Canon, |
4934 | QualType Aliased); |
4935 | |
4936 | public: |
4937 | /// Determine whether any of the given template arguments are dependent. |
4938 | static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, |
4939 | bool &InstantiationDependent); |
4940 | |
4941 | static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &, |
4942 | bool &InstantiationDependent); |
4943 | |
4944 | /// True if this template specialization type matches a current |
4945 | /// instantiation in the context in which it is found. |
4946 | bool isCurrentInstantiation() const { |
4947 | return isa<InjectedClassNameType>(getCanonicalTypeInternal()); |
4948 | } |
4949 | |
4950 | /// Determine if this template specialization type is for a type alias |
4951 | /// template that has been substituted. |
4952 | /// |
4953 | /// Nearly every template specialization type whose template is an alias |
4954 | /// template will be substituted. However, this is not the case when |
4955 | /// the specialization contains a pack expansion but the template alias |
4956 | /// does not have a corresponding parameter pack, e.g., |
4957 | /// |
4958 | /// \code |
4959 | /// template<typename T, typename U, typename V> struct S; |
4960 | /// template<typename T, typename U> using A = S<T, int, U>; |
4961 | /// template<typename... Ts> struct X { |
4962 | /// typedef A<Ts...> type; // not a type alias |
4963 | /// }; |
4964 | /// \endcode |
4965 | bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; } |
4966 | |
4967 | /// Get the aliased type, if this is a specialization of a type alias |
4968 | /// template. |
4969 | QualType getAliasedType() const { |
4970 | assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization" ) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4970, __PRETTY_FUNCTION__)); |
4971 | return *reinterpret_cast<const QualType*>(end()); |
4972 | } |
4973 | |
4974 | using iterator = const TemplateArgument *; |
4975 | |
4976 | iterator begin() const { return getArgs(); } |
4977 | iterator end() const; // defined inline in TemplateBase.h |
4978 | |
4979 | /// Retrieve the name of the template that we are specializing. |
4980 | TemplateName getTemplateName() const { return Template; } |
4981 | |
4982 | /// Retrieve the template arguments. |
4983 | const TemplateArgument *getArgs() const { |
4984 | return reinterpret_cast<const TemplateArgument *>(this + 1); |
4985 | } |
4986 | |
4987 | /// Retrieve the number of template arguments. |
4988 | unsigned getNumArgs() const { |
4989 | return TemplateSpecializationTypeBits.NumArgs; |
4990 | } |
4991 | |
4992 | /// Retrieve a specific template argument as a type. |
4993 | /// \pre \c isArgType(Arg) |
4994 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
4995 | |
4996 | ArrayRef<TemplateArgument> template_arguments() const { |
4997 | return {getArgs(), getNumArgs()}; |
4998 | } |
4999 | |
5000 | bool isSugared() const { |
5001 | return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); |
5002 | } |
5003 | |
5004 | QualType desugar() const { |
5005 | return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal(); |
5006 | } |
5007 | |
5008 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
5009 | Profile(ID, Template, template_arguments(), Ctx); |
5010 | if (isTypeAlias()) |
5011 | getAliasedType().Profile(ID); |
5012 | } |
5013 | |
5014 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, |
5015 | ArrayRef<TemplateArgument> Args, |
5016 | const ASTContext &Context); |
5017 | |
5018 | static bool classof(const Type *T) { |
5019 | return T->getTypeClass() == TemplateSpecialization; |
5020 | } |
5021 | }; |
5022 | |
5023 | /// Print a template argument list, including the '<' and '>' |
5024 | /// enclosing the template arguments. |
5025 | void printTemplateArgumentList(raw_ostream &OS, |
5026 | ArrayRef<TemplateArgument> Args, |
5027 | const PrintingPolicy &Policy); |
5028 | |
5029 | void printTemplateArgumentList(raw_ostream &OS, |
5030 | ArrayRef<TemplateArgumentLoc> Args, |
5031 | const PrintingPolicy &Policy); |
5032 | |
5033 | void printTemplateArgumentList(raw_ostream &OS, |
5034 | const TemplateArgumentListInfo &Args, |
5035 | const PrintingPolicy &Policy); |
5036 | |
5037 | /// The injected class name of a C++ class template or class |
5038 | /// template partial specialization. Used to record that a type was |
5039 | /// spelled with a bare identifier rather than as a template-id; the |
5040 | /// equivalent for non-templated classes is just RecordType. |
5041 | /// |
5042 | /// Injected class name types are always dependent. Template |
5043 | /// instantiation turns these into RecordTypes. |
5044 | /// |
5045 | /// Injected class name types are always canonical. This works |
5046 | /// because it is impossible to compare an injected class name type |
5047 | /// with the corresponding non-injected template type, for the same |
5048 | /// reason that it is impossible to directly compare template |
5049 | /// parameters from different dependent contexts: injected class name |
5050 | /// types can only occur within the scope of a particular templated |
5051 | /// declaration, and within that scope every template specialization |
5052 | /// will canonicalize to the injected class name (when appropriate |
5053 | /// according to the rules of the language). |
5054 | class InjectedClassNameType : public Type { |
5055 | friend class ASTContext; // ASTContext creates these. |
5056 | friend class ASTNodeImporter; |
5057 | friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not |
5058 | // currently suitable for AST reading, too much |
5059 | // interdependencies. |
5060 | |
5061 | CXXRecordDecl *Decl; |
5062 | |
5063 | /// The template specialization which this type represents. |
5064 | /// For example, in |
5065 | /// template <class T> class A { ... }; |
5066 | /// this is A<T>, whereas in |
5067 | /// template <class X, class Y> class A<B<X,Y> > { ... }; |
5068 | /// this is A<B<X,Y> >. |
5069 | /// |
5070 | /// It is always unqualified, always a template specialization type, |
5071 | /// and always dependent. |
5072 | QualType InjectedType; |
5073 | |
5074 | InjectedClassNameType(CXXRecordDecl *D, QualType TST) |
5075 | : Type(InjectedClassName, QualType(), /*Dependent=*/true, |
5076 | /*InstantiationDependent=*/true, |
5077 | /*VariablyModified=*/false, |
5078 | /*ContainsUnexpandedParameterPack=*/false), |
5079 | Decl(D), InjectedType(TST) { |
5080 | assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast< void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5080, __PRETTY_FUNCTION__)); |
5081 | assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail ("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5081, __PRETTY_FUNCTION__)); |
5082 | assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail ("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5082, __PRETTY_FUNCTION__)); |
5083 | } |
5084 | |
5085 | public: |
5086 | QualType getInjectedSpecializationType() const { return InjectedType; } |
5087 | |
5088 | const TemplateSpecializationType *getInjectedTST() const { |
5089 | return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); |
5090 | } |
5091 | |
5092 | TemplateName getTemplateName() const { |
5093 | return getInjectedTST()->getTemplateName(); |
5094 | } |
5095 | |
5096 | CXXRecordDecl *getDecl() const; |
5097 | |
5098 | bool isSugared() const { return false; } |
5099 | QualType desugar() const { return QualType(this, 0); } |
5100 | |
5101 | static bool classof(const Type *T) { |
5102 | return T->getTypeClass() == InjectedClassName; |
5103 | } |
5104 | }; |
5105 | |
5106 | /// The kind of a tag type. |
5107 | enum TagTypeKind { |
5108 | /// The "struct" keyword. |
5109 | TTK_Struct, |
5110 | |
5111 | /// The "__interface" keyword. |
5112 | TTK_Interface, |
5113 | |
5114 | /// The "union" keyword. |
5115 | TTK_Union, |
5116 | |
5117 | /// The "class" keyword. |
5118 | TTK_Class, |
5119 | |
5120 | /// The "enum" keyword. |
5121 | TTK_Enum |
5122 | }; |
5123 | |
5124 | /// The elaboration keyword that precedes a qualified type name or |
5125 | /// introduces an elaborated-type-specifier. |
5126 | enum ElaboratedTypeKeyword { |
5127 | /// The "struct" keyword introduces the elaborated-type-specifier. |
5128 | ETK_Struct, |
5129 | |
5130 | /// The "__interface" keyword introduces the elaborated-type-specifier. |
5131 | ETK_Interface, |
5132 | |
5133 | /// The "union" keyword introduces the elaborated-type-specifier. |
5134 | ETK_Union, |
5135 | |
5136 | /// The "class" keyword introduces the elaborated-type-specifier. |
5137 | ETK_Class, |
5138 | |
5139 | /// The "enum" keyword introduces the elaborated-type-specifier. |
5140 | ETK_Enum, |
5141 | |
5142 | /// The "typename" keyword precedes the qualified type name, e.g., |
5143 | /// \c typename T::type. |
5144 | ETK_Typename, |
5145 | |
5146 | /// No keyword precedes the qualified type name. |
5147 | ETK_None |
5148 | }; |
5149 | |
5150 | /// A helper class for Type nodes having an ElaboratedTypeKeyword. |
5151 | /// The keyword in stored in the free bits of the base class. |
5152 | /// Also provides a few static helpers for converting and printing |
5153 | /// elaborated type keyword and tag type kind enumerations. |
5154 | class TypeWithKeyword : public Type { |
5155 | protected: |
5156 | TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, |
5157 | QualType Canonical, bool Dependent, |
5158 | bool InstantiationDependent, bool VariablyModified, |
5159 | bool ContainsUnexpandedParameterPack) |
5160 | : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, |
5161 | ContainsUnexpandedParameterPack) { |
5162 | TypeWithKeywordBits.Keyword = Keyword; |
5163 | } |
5164 | |
5165 | public: |
5166 | ElaboratedTypeKeyword getKeyword() const { |
5167 | return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); |
5168 | } |
5169 | |
5170 | /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. |
5171 | static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); |
5172 | |
5173 | /// Converts a type specifier (DeclSpec::TST) into a tag type kind. |
5174 | /// It is an error to provide a type specifier which *isn't* a tag kind here. |
5175 | static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); |
5176 | |
5177 | /// Converts a TagTypeKind into an elaborated type keyword. |
5178 | static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); |
5179 | |
5180 | /// Converts an elaborated type keyword into a TagTypeKind. |
5181 | /// It is an error to provide an elaborated type keyword |
5182 | /// which *isn't* a tag kind here. |
5183 | static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); |
5184 | |
5185 | static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); |
5186 | |
5187 | static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); |
5188 | |
5189 | static StringRef getTagTypeKindName(TagTypeKind Kind) { |
5190 | return getKeywordName(getKeywordForTagTypeKind(Kind)); |
5191 | } |
5192 | |
5193 | class CannotCastToThisType {}; |
5194 | static CannotCastToThisType classof(const Type *); |
5195 | }; |
5196 | |
5197 | /// Represents a type that was referred to using an elaborated type |
5198 | /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, |
5199 | /// or both. |
5200 | /// |
5201 | /// This type is used to keep track of a type name as written in the |
5202 | /// source code, including tag keywords and any nested-name-specifiers. |
5203 | /// The type itself is always "sugar", used to express what was written |
5204 | /// in the source code but containing no additional semantic information. |
5205 | class ElaboratedType final |
5206 | : public TypeWithKeyword, |
5207 | public llvm::FoldingSetNode, |
5208 | private llvm::TrailingObjects<ElaboratedType, TagDecl *> { |
5209 | friend class ASTContext; // ASTContext creates these |
5210 | friend TrailingObjects; |
5211 | |
5212 | /// The nested name specifier containing the qualifier. |
5213 | NestedNameSpecifier *NNS; |
5214 | |
5215 | /// The type that this qualified name refers to. |
5216 | QualType NamedType; |
5217 | |
5218 | /// The (re)declaration of this tag type owned by this occurrence is stored |
5219 | /// as a trailing object if there is one. Use getOwnedTagDecl to obtain |
5220 | /// it, or obtain a null pointer if there is none. |
5221 | |
5222 | ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5223 | QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl) |
5224 | : TypeWithKeyword(Keyword, Elaborated, CanonType, |
5225 | NamedType->isDependentType(), |
5226 | NamedType->isInstantiationDependentType(), |
5227 | NamedType->isVariablyModifiedType(), |
5228 | NamedType->containsUnexpandedParameterPack()), |
5229 | NNS(NNS), NamedType(NamedType) { |
5230 | ElaboratedTypeBits.HasOwnedTagDecl = false; |
5231 | if (OwnedTagDecl) { |
5232 | ElaboratedTypeBits.HasOwnedTagDecl = true; |
5233 | *getTrailingObjects<TagDecl *>() = OwnedTagDecl; |
5234 | } |
5235 | assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5237, __PRETTY_FUNCTION__)) |
5236 | "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5237, __PRETTY_FUNCTION__)) |
5237 | "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5237, __PRETTY_FUNCTION__)); |
5238 | } |
5239 | |
5240 | public: |
5241 | /// Retrieve the qualification on this type. |
5242 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5243 | |
5244 | /// Retrieve the type named by the qualified-id. |
5245 | QualType getNamedType() const { return NamedType; } |
5246 | |
5247 | /// Remove a single level of sugar. |
5248 | QualType desugar() const { return getNamedType(); } |
5249 | |
5250 | /// Returns whether this type directly provides sugar. |
5251 | bool isSugared() const { return true; } |
5252 | |
5253 | /// Return the (re)declaration of this type owned by this occurrence of this |
5254 | /// type, or nullptr if there is none. |
5255 | TagDecl *getOwnedTagDecl() const { |
5256 | return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>() |
5257 | : nullptr; |
5258 | } |
5259 | |
5260 | void Profile(llvm::FoldingSetNodeID &ID) { |
5261 | Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl()); |
5262 | } |
5263 | |
5264 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5265 | NestedNameSpecifier *NNS, QualType NamedType, |
5266 | TagDecl *OwnedTagDecl) { |
5267 | ID.AddInteger(Keyword); |
5268 | ID.AddPointer(NNS); |
5269 | NamedType.Profile(ID); |
5270 | ID.AddPointer(OwnedTagDecl); |
5271 | } |
5272 | |
5273 | static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; } |
5274 | }; |
5275 | |
5276 | /// Represents a qualified type name for which the type name is |
5277 | /// dependent. |
5278 | /// |
5279 | /// DependentNameType represents a class of dependent types that involve a |
5280 | /// possibly dependent nested-name-specifier (e.g., "T::") followed by a |
5281 | /// name of a type. The DependentNameType may start with a "typename" (for a |
5282 | /// typename-specifier), "class", "struct", "union", or "enum" (for a |
5283 | /// dependent elaborated-type-specifier), or nothing (in contexts where we |
5284 | /// know that we must be referring to a type, e.g., in a base class specifier). |
5285 | /// Typically the nested-name-specifier is dependent, but in MSVC compatibility |
5286 | /// mode, this type is used with non-dependent names to delay name lookup until |
5287 | /// instantiation. |
5288 | class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { |
5289 | friend class ASTContext; // ASTContext creates these |
5290 | |
5291 | /// The nested name specifier containing the qualifier. |
5292 | NestedNameSpecifier *NNS; |
5293 | |
5294 | /// The type that this typename specifier refers to. |
5295 | const IdentifierInfo *Name; |
5296 | |
5297 | DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5298 | const IdentifierInfo *Name, QualType CanonType) |
5299 | : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true, |
5300 | /*InstantiationDependent=*/true, |
5301 | /*VariablyModified=*/false, |
5302 | NNS->containsUnexpandedParameterPack()), |
5303 | NNS(NNS), Name(Name) {} |
5304 | |
5305 | public: |
5306 | /// Retrieve the qualification on this type. |
5307 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5308 | |
5309 | /// Retrieve the type named by the typename specifier as an identifier. |
5310 | /// |
5311 | /// This routine will return a non-NULL identifier pointer when the |
5312 | /// form of the original typename was terminated by an identifier, |
5313 | /// e.g., "typename T::type". |
5314 | const IdentifierInfo *getIdentifier() const { |
5315 | return Name; |
5316 | } |
5317 | |
5318 | bool isSugared() const { return false; } |
5319 | QualType desugar() const { return QualType(this, 0); } |
5320 | |
5321 | void Profile(llvm::FoldingSetNodeID &ID) { |
5322 | Profile(ID, getKeyword(), NNS, Name); |
5323 | } |
5324 | |
5325 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5326 | NestedNameSpecifier *NNS, const IdentifierInfo *Name) { |
5327 | ID.AddInteger(Keyword); |
5328 | ID.AddPointer(NNS); |
5329 | ID.AddPointer(Name); |
5330 | } |
5331 | |
5332 | static bool classof(const Type *T) { |
5333 | return T->getTypeClass() == DependentName; |
5334 | } |
5335 | }; |
5336 | |
5337 | /// Represents a template specialization type whose template cannot be |
5338 | /// resolved, e.g. |
5339 | /// A<T>::template B<T> |
5340 | class alignas(8) DependentTemplateSpecializationType |
5341 | : public TypeWithKeyword, |
5342 | public llvm::FoldingSetNode { |
5343 | friend class ASTContext; // ASTContext creates these |
5344 | |
5345 | /// The nested name specifier containing the qualifier. |
5346 | NestedNameSpecifier *NNS; |
5347 | |
5348 | /// The identifier of the template. |
5349 | const IdentifierInfo *Name; |
5350 | |
5351 | DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
5352 | NestedNameSpecifier *NNS, |
5353 | const IdentifierInfo *Name, |
5354 | ArrayRef<TemplateArgument> Args, |
5355 | QualType Canon); |
5356 | |
5357 | const TemplateArgument *getArgBuffer() const { |
5358 | return reinterpret_cast<const TemplateArgument*>(this+1); |
5359 | } |
5360 | |
5361 | TemplateArgument *getArgBuffer() { |
5362 | return reinterpret_cast<TemplateArgument*>(this+1); |
5363 | } |
5364 | |
5365 | public: |
5366 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5367 | const IdentifierInfo *getIdentifier() const { return Name; } |
5368 | |
5369 | /// Retrieve the template arguments. |
5370 | const TemplateArgument *getArgs() const { |
5371 | return getArgBuffer(); |
5372 | } |
5373 | |
5374 | /// Retrieve the number of template arguments. |
5375 | unsigned getNumArgs() const { |
5376 | return DependentTemplateSpecializationTypeBits.NumArgs; |
5377 | } |
5378 | |
5379 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5380 | |
5381 | ArrayRef<TemplateArgument> template_arguments() const { |
5382 | return {getArgs(), getNumArgs()}; |
5383 | } |
5384 | |
5385 | using iterator = const TemplateArgument *; |
5386 | |
5387 | iterator begin() const { return getArgs(); } |
5388 | iterator end() const; // inline in TemplateBase.h |
5389 | |
5390 | bool isSugared() const { return false; } |
5391 | QualType desugar() const { return QualType(this, 0); } |
5392 | |
5393 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5394 | Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()}); |
5395 | } |
5396 | |
5397 | static void Profile(llvm::FoldingSetNodeID &ID, |
5398 | const ASTContext &Context, |
5399 | ElaboratedTypeKeyword Keyword, |
5400 | NestedNameSpecifier *Qualifier, |
5401 | const IdentifierInfo *Name, |
5402 | ArrayRef<TemplateArgument> Args); |
5403 | |
5404 | static bool classof(const Type *T) { |
5405 | return T->getTypeClass() == DependentTemplateSpecialization; |
5406 | } |
5407 | }; |
5408 | |
5409 | /// Represents a pack expansion of types. |
5410 | /// |
5411 | /// Pack expansions are part of C++11 variadic templates. A pack |
5412 | /// expansion contains a pattern, which itself contains one or more |
5413 | /// "unexpanded" parameter packs. When instantiated, a pack expansion |
5414 | /// produces a series of types, each instantiated from the pattern of |
5415 | /// the expansion, where the Ith instantiation of the pattern uses the |
5416 | /// Ith arguments bound to each of the unexpanded parameter packs. The |
5417 | /// pack expansion is considered to "expand" these unexpanded |
5418 | /// parameter packs. |
5419 | /// |
5420 | /// \code |
5421 | /// template<typename ...Types> struct tuple; |
5422 | /// |
5423 | /// template<typename ...Types> |
5424 | /// struct tuple_of_references { |
5425 | /// typedef tuple<Types&...> type; |
5426 | /// }; |
5427 | /// \endcode |
5428 | /// |
5429 | /// Here, the pack expansion \c Types&... is represented via a |
5430 | /// PackExpansionType whose pattern is Types&. |
5431 | class PackExpansionType : public Type, public llvm::FoldingSetNode { |
5432 | friend class ASTContext; // ASTContext creates these |
5433 | |
5434 | /// The pattern of the pack expansion. |
5435 | QualType Pattern; |
5436 | |
5437 | PackExpansionType(QualType Pattern, QualType Canon, |
5438 | Optional<unsigned> NumExpansions) |
5439 | : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(), |
5440 | /*InstantiationDependent=*/true, |
5441 | /*VariablyModified=*/Pattern->isVariablyModifiedType(), |
5442 | /*ContainsUnexpandedParameterPack=*/false), |
5443 | Pattern(Pattern) { |
5444 | PackExpansionTypeBits.NumExpansions = |
5445 | NumExpansions ? *NumExpansions + 1 : 0; |
5446 | } |
5447 | |
5448 | public: |
5449 | /// Retrieve the pattern of this pack expansion, which is the |
5450 | /// type that will be repeatedly instantiated when instantiating the |
5451 | /// pack expansion itself. |
5452 | QualType getPattern() const { return Pattern; } |
5453 | |
5454 | /// Retrieve the number of expansions that this pack expansion will |
5455 | /// generate, if known. |
5456 | Optional<unsigned> getNumExpansions() const { |
5457 | if (PackExpansionTypeBits.NumExpansions) |
5458 | return PackExpansionTypeBits.NumExpansions - 1; |
5459 | return None; |
5460 | } |
5461 | |
5462 | bool isSugared() const { return !Pattern->isDependentType(); } |
5463 | QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); } |
5464 | |
5465 | void Profile(llvm::FoldingSetNodeID &ID) { |
5466 | Profile(ID, getPattern(), getNumExpansions()); |
5467 | } |
5468 | |
5469 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, |
5470 | Optional<unsigned> NumExpansions) { |
5471 | ID.AddPointer(Pattern.getAsOpaquePtr()); |
5472 | ID.AddBoolean(NumExpansions.hasValue()); |
5473 | if (NumExpansions) |
5474 | ID.AddInteger(*NumExpansions); |
5475 | } |
5476 | |
5477 | static bool classof(const Type *T) { |
5478 | return T->getTypeClass() == PackExpansion; |
5479 | } |
5480 | }; |
5481 | |
5482 | /// This class wraps the list of protocol qualifiers. For types that can |
5483 | /// take ObjC protocol qualifers, they can subclass this class. |
5484 | template <class T> |
5485 | class ObjCProtocolQualifiers { |
5486 | protected: |
5487 | ObjCProtocolQualifiers() = default; |
5488 | |
5489 | ObjCProtocolDecl * const *getProtocolStorage() const { |
5490 | return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); |
5491 | } |
5492 | |
5493 | ObjCProtocolDecl **getProtocolStorage() { |
5494 | return static_cast<T*>(this)->getProtocolStorageImpl(); |
5495 | } |
5496 | |
5497 | void setNumProtocols(unsigned N) { |
5498 | static_cast<T*>(this)->setNumProtocolsImpl(N); |
5499 | } |
5500 | |
5501 | void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { |
5502 | setNumProtocols(protocols.size()); |
5503 | assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5504, __PRETTY_FUNCTION__)) |
5504 | "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5504, __PRETTY_FUNCTION__)); |
5505 | if (!protocols.empty()) |
5506 | memcpy(getProtocolStorage(), protocols.data(), |
5507 | protocols.size() * sizeof(ObjCProtocolDecl*)); |
5508 | } |
5509 | |
5510 | public: |
5511 | using qual_iterator = ObjCProtocolDecl * const *; |
5512 | using qual_range = llvm::iterator_range<qual_iterator>; |
5513 | |
5514 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5515 | qual_iterator qual_begin() const { return getProtocolStorage(); } |
5516 | qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } |
5517 | |
5518 | bool qual_empty() const { return getNumProtocols() == 0; } |
5519 | |
5520 | /// Return the number of qualifying protocols in this type, or 0 if |
5521 | /// there are none. |
5522 | unsigned getNumProtocols() const { |
5523 | return static_cast<const T*>(this)->getNumProtocolsImpl(); |
5524 | } |
5525 | |
5526 | /// Fetch a protocol by index. |
5527 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
5528 | assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access" ) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5528, __PRETTY_FUNCTION__)); |
5529 | return qual_begin()[I]; |
5530 | } |
5531 | |
5532 | /// Retrieve all of the protocol qualifiers. |
5533 | ArrayRef<ObjCProtocolDecl *> getProtocols() const { |
5534 | return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); |
5535 | } |
5536 | }; |
5537 | |
5538 | /// Represents a type parameter type in Objective C. It can take |
5539 | /// a list of protocols. |
5540 | class ObjCTypeParamType : public Type, |
5541 | public ObjCProtocolQualifiers<ObjCTypeParamType>, |
5542 | public llvm::FoldingSetNode { |
5543 | friend class ASTContext; |
5544 | friend class ObjCProtocolQualifiers<ObjCTypeParamType>; |
5545 | |
5546 | /// The number of protocols stored on this type. |
5547 | unsigned NumProtocols : 6; |
5548 | |
5549 | ObjCTypeParamDecl *OTPDecl; |
5550 | |
5551 | /// The protocols are stored after the ObjCTypeParamType node. In the |
5552 | /// canonical type, the list of protocols are sorted alphabetically |
5553 | /// and uniqued. |
5554 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5555 | |
5556 | /// Return the number of qualifying protocols in this interface type, |
5557 | /// or 0 if there are none. |
5558 | unsigned getNumProtocolsImpl() const { |
5559 | return NumProtocols; |
5560 | } |
5561 | |
5562 | void setNumProtocolsImpl(unsigned N) { |
5563 | NumProtocols = N; |
5564 | } |
5565 | |
5566 | ObjCTypeParamType(const ObjCTypeParamDecl *D, |
5567 | QualType can, |
5568 | ArrayRef<ObjCProtocolDecl *> protocols); |
5569 | |
5570 | public: |
5571 | bool isSugared() const { return true; } |
5572 | QualType desugar() const { return getCanonicalTypeInternal(); } |
5573 | |
5574 | static bool classof(const Type *T) { |
5575 | return T->getTypeClass() == ObjCTypeParam; |
5576 | } |
5577 | |
5578 | void Profile(llvm::FoldingSetNodeID &ID); |
5579 | static void Profile(llvm::FoldingSetNodeID &ID, |
5580 | const ObjCTypeParamDecl *OTPDecl, |
5581 | ArrayRef<ObjCProtocolDecl *> protocols); |
5582 | |
5583 | ObjCTypeParamDecl *getDecl() const { return OTPDecl; } |
5584 | }; |
5585 | |
5586 | /// Represents a class type in Objective C. |
5587 | /// |
5588 | /// Every Objective C type is a combination of a base type, a set of |
5589 | /// type arguments (optional, for parameterized classes) and a list of |
5590 | /// protocols. |
5591 | /// |
5592 | /// Given the following declarations: |
5593 | /// \code |
5594 | /// \@class C<T>; |
5595 | /// \@protocol P; |
5596 | /// \endcode |
5597 | /// |
5598 | /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType |
5599 | /// with base C and no protocols. |
5600 | /// |
5601 | /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. |
5602 | /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no |
5603 | /// protocol list. |
5604 | /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', |
5605 | /// and protocol list [P]. |
5606 | /// |
5607 | /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose |
5608 | /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType |
5609 | /// and no protocols. |
5610 | /// |
5611 | /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType |
5612 | /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually |
5613 | /// this should get its own sugar class to better represent the source. |
5614 | class ObjCObjectType : public Type, |
5615 | public ObjCProtocolQualifiers<ObjCObjectType> { |
5616 | friend class ObjCProtocolQualifiers<ObjCObjectType>; |
5617 | |
5618 | // ObjCObjectType.NumTypeArgs - the number of type arguments stored |
5619 | // after the ObjCObjectPointerType node. |
5620 | // ObjCObjectType.NumProtocols - the number of protocols stored |
5621 | // after the type arguments of ObjCObjectPointerType node. |
5622 | // |
5623 | // These protocols are those written directly on the type. If |
5624 | // protocol qualifiers ever become additive, the iterators will need |
5625 | // to get kindof complicated. |
5626 | // |
5627 | // In the canonical object type, these are sorted alphabetically |
5628 | // and uniqued. |
5629 | |
5630 | /// Either a BuiltinType or an InterfaceType or sugar for either. |
5631 | QualType BaseType; |
5632 | |
5633 | /// Cached superclass type. |
5634 | mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> |
5635 | CachedSuperClassType; |
5636 | |
5637 | QualType *getTypeArgStorage(); |
5638 | const QualType *getTypeArgStorage() const { |
5639 | return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); |
5640 | } |
5641 | |
5642 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5643 | /// Return the number of qualifying protocols in this interface type, |
5644 | /// or 0 if there are none. |
5645 | unsigned getNumProtocolsImpl() const { |
5646 | return ObjCObjectTypeBits.NumProtocols; |
5647 | } |
5648 | void setNumProtocolsImpl(unsigned N) { |
5649 | ObjCObjectTypeBits.NumProtocols = N; |
5650 | } |
5651 | |
5652 | protected: |
5653 | enum Nonce_ObjCInterface { Nonce_ObjCInterface }; |
5654 | |
5655 | ObjCObjectType(QualType Canonical, QualType Base, |
5656 | ArrayRef<QualType> typeArgs, |
5657 | ArrayRef<ObjCProtocolDecl *> protocols, |
5658 | bool isKindOf); |
5659 | |
5660 | ObjCObjectType(enum Nonce_ObjCInterface) |
5661 | : Type(ObjCInterface, QualType(), false, false, false, false), |
5662 | BaseType(QualType(this_(), 0)) { |
5663 | ObjCObjectTypeBits.NumProtocols = 0; |
5664 | ObjCObjectTypeBits.NumTypeArgs = 0; |
5665 | ObjCObjectTypeBits.IsKindOf = 0; |
5666 | } |
5667 | |
5668 | void computeSuperClassTypeSlow() const; |
5669 | |
5670 | public: |
5671 | /// Gets the base type of this object type. This is always (possibly |
5672 | /// sugar for) one of: |
5673 | /// - the 'id' builtin type (as opposed to the 'id' type visible to the |
5674 | /// user, which is a typedef for an ObjCObjectPointerType) |
5675 | /// - the 'Class' builtin type (same caveat) |
5676 | /// - an ObjCObjectType (currently always an ObjCInterfaceType) |
5677 | QualType getBaseType() const { return BaseType; } |
5678 | |
5679 | bool isObjCId() const { |
5680 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); |
5681 | } |
5682 | |
5683 | bool isObjCClass() const { |
5684 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); |
5685 | } |
5686 | |
5687 | bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } |
5688 | bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } |
5689 | bool isObjCUnqualifiedIdOrClass() const { |
5690 | if (!qual_empty()) return false; |
5691 | if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) |
5692 | return T->getKind() == BuiltinType::ObjCId || |
5693 | T->getKind() == BuiltinType::ObjCClass; |
5694 | return false; |
5695 | } |
5696 | bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } |
5697 | bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } |
5698 | |
5699 | /// Gets the interface declaration for this object type, if the base type |
5700 | /// really is an interface. |
5701 | ObjCInterfaceDecl *getInterface() const; |
5702 | |
5703 | /// Determine whether this object type is "specialized", meaning |
5704 | /// that it has type arguments. |
5705 | bool isSpecialized() const; |
5706 | |
5707 | /// Determine whether this object type was written with type arguments. |
5708 | bool isSpecializedAsWritten() const { |
5709 | return ObjCObjectTypeBits.NumTypeArgs > 0; |
5710 | } |
5711 | |
5712 | /// Determine whether this object type is "unspecialized", meaning |
5713 | /// that it has no type arguments. |
5714 | bool isUnspecialized() const { return !isSpecialized(); } |
5715 | |
5716 | /// Determine whether this object type is "unspecialized" as |
5717 | /// written, meaning that it has no type arguments. |
5718 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5719 | |
5720 | /// Retrieve the type arguments of this object type (semantically). |
5721 | ArrayRef<QualType> getTypeArgs() const; |
5722 | |
5723 | /// Retrieve the type arguments of this object type as they were |
5724 | /// written. |
5725 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5726 | return llvm::makeArrayRef(getTypeArgStorage(), |
5727 | ObjCObjectTypeBits.NumTypeArgs); |
5728 | } |
5729 | |
5730 | /// Whether this is a "__kindof" type as written. |
5731 | bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } |
5732 | |
5733 | /// Whether this ia a "__kindof" type (semantically). |
5734 | bool isKindOfType() const; |
5735 | |
5736 | /// Retrieve the type of the superclass of this object type. |
5737 | /// |
5738 | /// This operation substitutes any type arguments into the |
5739 | /// superclass of the current class type, potentially producing a |
5740 | /// specialization of the superclass type. Produces a null type if |
5741 | /// there is no superclass. |
5742 | QualType getSuperClassType() const { |
5743 | if (!CachedSuperClassType.getInt()) |
5744 | computeSuperClassTypeSlow(); |
5745 | |
5746 | assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?" ) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5746, __PRETTY_FUNCTION__)); |
5747 | return QualType(CachedSuperClassType.getPointer(), 0); |
5748 | } |
5749 | |
5750 | /// Strip off the Objective-C "kindof" type and (with it) any |
5751 | /// protocol qualifiers. |
5752 | QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; |
5753 | |
5754 | bool isSugared() const { return false; } |
5755 | QualType desugar() const { return QualType(this, 0); } |
5756 | |
5757 | static bool classof(const Type *T) { |
5758 | return T->getTypeClass() == ObjCObject || |
5759 | T->getTypeClass() == ObjCInterface; |
5760 | } |
5761 | }; |
5762 | |
5763 | /// A class providing a concrete implementation |
5764 | /// of ObjCObjectType, so as to not increase the footprint of |
5765 | /// ObjCInterfaceType. Code outside of ASTContext and the core type |
5766 | /// system should not reference this type. |
5767 | class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { |
5768 | friend class ASTContext; |
5769 | |
5770 | // If anyone adds fields here, ObjCObjectType::getProtocolStorage() |
5771 | // will need to be modified. |
5772 | |
5773 | ObjCObjectTypeImpl(QualType Canonical, QualType Base, |
5774 | ArrayRef<QualType> typeArgs, |
5775 | ArrayRef<ObjCProtocolDecl *> protocols, |
5776 | bool isKindOf) |
5777 | : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} |
5778 | |
5779 | public: |
5780 | void Profile(llvm::FoldingSetNodeID &ID); |
5781 | static void Profile(llvm::FoldingSetNodeID &ID, |
5782 | QualType Base, |
5783 | ArrayRef<QualType> typeArgs, |
5784 | ArrayRef<ObjCProtocolDecl *> protocols, |
5785 | bool isKindOf); |
5786 | }; |
5787 | |
5788 | inline QualType *ObjCObjectType::getTypeArgStorage() { |
5789 | return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); |
5790 | } |
5791 | |
5792 | inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { |
5793 | return reinterpret_cast<ObjCProtocolDecl**>( |
5794 | getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); |
5795 | } |
5796 | |
5797 | inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { |
5798 | return reinterpret_cast<ObjCProtocolDecl**>( |
5799 | static_cast<ObjCTypeParamType*>(this)+1); |
5800 | } |
5801 | |
5802 | /// Interfaces are the core concept in Objective-C for object oriented design. |
5803 | /// They basically correspond to C++ classes. There are two kinds of interface |
5804 | /// types: normal interfaces like `NSString`, and qualified interfaces, which |
5805 | /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. |
5806 | /// |
5807 | /// ObjCInterfaceType guarantees the following properties when considered |
5808 | /// as a subtype of its superclass, ObjCObjectType: |
5809 | /// - There are no protocol qualifiers. To reinforce this, code which |
5810 | /// tries to invoke the protocol methods via an ObjCInterfaceType will |
5811 | /// fail to compile. |
5812 | /// - It is its own base type. That is, if T is an ObjCInterfaceType*, |
5813 | /// T->getBaseType() == QualType(T, 0). |
5814 | class ObjCInterfaceType : public ObjCObjectType { |
5815 | friend class ASTContext; // ASTContext creates these. |
5816 | friend class ASTReader; |
5817 | friend class ObjCInterfaceDecl; |
5818 | |
5819 | mutable ObjCInterfaceDecl *Decl; |
5820 | |
5821 | ObjCInterfaceType(const ObjCInterfaceDecl *D) |
5822 | : ObjCObjectType(Nonce_ObjCInterface), |
5823 | Decl(const_cast<ObjCInterfaceDecl*>(D)) {} |
5824 | |
5825 | public: |
5826 | /// Get the declaration of this interface. |
5827 | ObjCInterfaceDecl *getDecl() const { return Decl; } |
5828 | |
5829 | bool isSugared() const { return false; } |
5830 | QualType desugar() const { return QualType(this, 0); } |
5831 | |
5832 | static bool classof(const Type *T) { |
5833 | return T->getTypeClass() == ObjCInterface; |
5834 | } |
5835 | |
5836 | // Nonsense to "hide" certain members of ObjCObjectType within this |
5837 | // class. People asking for protocols on an ObjCInterfaceType are |
5838 | // not going to get what they want: ObjCInterfaceTypes are |
5839 | // guaranteed to have no protocols. |
5840 | enum { |
5841 | qual_iterator, |
5842 | qual_begin, |
5843 | qual_end, |
5844 | getNumProtocols, |
5845 | getProtocol |
5846 | }; |
5847 | }; |
5848 | |
5849 | inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { |
5850 | QualType baseType = getBaseType(); |
5851 | while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) { |
5852 | if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT)) |
5853 | return T->getDecl(); |
5854 | |
5855 | baseType = ObjT->getBaseType(); |
5856 | } |
5857 | |
5858 | return nullptr; |
5859 | } |
5860 | |
5861 | /// Represents a pointer to an Objective C object. |
5862 | /// |
5863 | /// These are constructed from pointer declarators when the pointee type is |
5864 | /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' |
5865 | /// types are typedefs for these, and the protocol-qualified types 'id<P>' |
5866 | /// and 'Class<P>' are translated into these. |
5867 | /// |
5868 | /// Pointers to pointers to Objective C objects are still PointerTypes; |
5869 | /// only the first level of pointer gets it own type implementation. |
5870 | class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { |
5871 | friend class ASTContext; // ASTContext creates these. |
5872 | |
5873 | QualType PointeeType; |
5874 | |
5875 | ObjCObjectPointerType(QualType Canonical, QualType Pointee) |
5876 | : Type(ObjCObjectPointer, Canonical, |
5877 | Pointee->isDependentType(), |
5878 | Pointee->isInstantiationDependentType(), |
5879 | Pointee->isVariablyModifiedType(), |
5880 | Pointee->containsUnexpandedParameterPack()), |
5881 | PointeeType(Pointee) {} |
5882 | |
5883 | public: |
5884 | /// Gets the type pointed to by this ObjC pointer. |
5885 | /// The result will always be an ObjCObjectType or sugar thereof. |
5886 | QualType getPointeeType() const { return PointeeType; } |
5887 | |
5888 | /// Gets the type pointed to by this ObjC pointer. Always returns non-null. |
5889 | /// |
5890 | /// This method is equivalent to getPointeeType() except that |
5891 | /// it discards any typedefs (or other sugar) between this |
5892 | /// type and the "outermost" object type. So for: |
5893 | /// \code |
5894 | /// \@class A; \@protocol P; \@protocol Q; |
5895 | /// typedef A<P> AP; |
5896 | /// typedef A A1; |
5897 | /// typedef A1<P> A1P; |
5898 | /// typedef A1P<Q> A1PQ; |
5899 | /// \endcode |
5900 | /// For 'A*', getObjectType() will return 'A'. |
5901 | /// For 'A<P>*', getObjectType() will return 'A<P>'. |
5902 | /// For 'AP*', getObjectType() will return 'A<P>'. |
5903 | /// For 'A1*', getObjectType() will return 'A'. |
5904 | /// For 'A1<P>*', getObjectType() will return 'A1<P>'. |
5905 | /// For 'A1P*', getObjectType() will return 'A1<P>'. |
5906 | /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because |
5907 | /// adding protocols to a protocol-qualified base discards the |
5908 | /// old qualifiers (for now). But if it didn't, getObjectType() |
5909 | /// would return 'A1P<Q>' (and we'd have to make iterating over |
5910 | /// qualifiers more complicated). |
5911 | const ObjCObjectType *getObjectType() const { |
5912 | return PointeeType->castAs<ObjCObjectType>(); |
5913 | } |
5914 | |
5915 | /// If this pointer points to an Objective C |
5916 | /// \@interface type, gets the type for that interface. Any protocol |
5917 | /// qualifiers on the interface are ignored. |
5918 | /// |
5919 | /// \return null if the base type for this pointer is 'id' or 'Class' |
5920 | const ObjCInterfaceType *getInterfaceType() const; |
5921 | |
5922 | /// If this pointer points to an Objective \@interface |
5923 | /// type, gets the declaration for that interface. |
5924 | /// |
5925 | /// \return null if the base type for this pointer is 'id' or 'Class' |
5926 | ObjCInterfaceDecl *getInterfaceDecl() const { |
5927 | return getObjectType()->getInterface(); |
5928 | } |
5929 | |
5930 | /// True if this is equivalent to the 'id' type, i.e. if |
5931 | /// its object type is the primitive 'id' type with no protocols. |
5932 | bool isObjCIdType() const { |
5933 | return getObjectType()->isObjCUnqualifiedId(); |
5934 | } |
5935 | |
5936 | /// True if this is equivalent to the 'Class' type, |
5937 | /// i.e. if its object tive is the primitive 'Class' type with no protocols. |
5938 | bool isObjCClassType() const { |
5939 | return getObjectType()->isObjCUnqualifiedClass(); |
5940 | } |
5941 | |
5942 | /// True if this is equivalent to the 'id' or 'Class' type, |
5943 | bool isObjCIdOrClassType() const { |
5944 | return getObjectType()->isObjCUnqualifiedIdOrClass(); |
5945 | } |
5946 | |
5947 | /// True if this is equivalent to 'id<P>' for some non-empty set of |
5948 | /// protocols. |
5949 | bool isObjCQualifiedIdType() const { |
5950 | return getObjectType()->isObjCQualifiedId(); |
5951 | } |
5952 | |
5953 | /// True if this is equivalent to 'Class<P>' for some non-empty set of |
5954 | /// protocols. |
5955 | bool isObjCQualifiedClassType() const { |
5956 | return getObjectType()->isObjCQualifiedClass(); |
5957 | } |
5958 | |
5959 | /// Whether this is a "__kindof" type. |
5960 | bool isKindOfType() const { return getObjectType()->isKindOfType(); } |
5961 | |
5962 | /// Whether this type is specialized, meaning that it has type arguments. |
5963 | bool isSpecialized() const { return getObjectType()->isSpecialized(); } |
5964 | |
5965 | /// Whether this type is specialized, meaning that it has type arguments. |
5966 | bool isSpecializedAsWritten() const { |
5967 | return getObjectType()->isSpecializedAsWritten(); |
5968 | } |
5969 | |
5970 | /// Whether this type is unspecialized, meaning that is has no type arguments. |
5971 | bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } |
5972 | |
5973 | /// Determine whether this object type is "unspecialized" as |
5974 | /// written, meaning that it has no type arguments. |
5975 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5976 | |
5977 | /// Retrieve the type arguments for this type. |
5978 | ArrayRef<QualType> getTypeArgs() const { |
5979 | return getObjectType()->getTypeArgs(); |
5980 | } |
5981 | |
5982 | /// Retrieve the type arguments for this type. |
5983 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5984 | return getObjectType()->getTypeArgsAsWritten(); |
5985 | } |
5986 | |
5987 | /// An iterator over the qualifiers on the object type. Provided |
5988 | /// for convenience. This will always iterate over the full set of |
5989 | /// protocols on a type, not just those provided directly. |
5990 | using qual_iterator = ObjCObjectType::qual_iterator; |
5991 | using qual_range = llvm::iterator_range<qual_iterator>; |
5992 | |
5993 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5994 | |
5995 | qual_iterator qual_begin() const { |
5996 | return getObjectType()->qual_begin(); |
5997 | } |
5998 | |
5999 | qual_iterator qual_end() const { |
6000 | return getObjectType()->qual_end(); |
6001 | } |
6002 | |
6003 | bool qual_empty() const { return getObjectType()->qual_empty(); } |
6004 | |
6005 | /// Return the number of qualifying protocols on the object type. |
6006 | unsigned getNumProtocols() const { |
6007 | return getObjectType()->getNumProtocols(); |
6008 | } |
6009 | |
6010 | /// Retrieve a qualifying protocol by index on the object type. |
6011 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
6012 | return getObjectType()->getProtocol(I); |
6013 | } |
6014 | |
6015 | bool isSugared() const { return false; } |
6016 | QualType desugar() const { return QualType(this, 0); } |
6017 | |
6018 | /// Retrieve the type of the superclass of this object pointer type. |
6019 | /// |
6020 | /// This operation substitutes any type arguments into the |
6021 | /// superclass of the current class type, potentially producing a |
6022 | /// pointer to a specialization of the superclass type. Produces a |
6023 | /// null type if there is no superclass. |
6024 | QualType getSuperClassType() const; |
6025 | |
6026 | /// Strip off the Objective-C "kindof" type and (with it) any |
6027 | /// protocol qualifiers. |
6028 | const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( |
6029 | const ASTContext &ctx) const; |
6030 | |
6031 | void Profile(llvm::FoldingSetNodeID &ID) { |
6032 | Profile(ID, getPointeeType()); |
6033 | } |
6034 | |
6035 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6036 | ID.AddPointer(T.getAsOpaquePtr()); |
6037 | } |
6038 | |
6039 | static bool classof(const Type *T) { |
6040 | return T->getTypeClass() == ObjCObjectPointer; |
6041 | } |
6042 | }; |
6043 | |
6044 | class AtomicType : public Type, public llvm::FoldingSetNode { |
6045 | friend class ASTContext; // ASTContext creates these. |
6046 | |
6047 | QualType ValueType; |
6048 | |
6049 | AtomicType(QualType ValTy, QualType Canonical) |
6050 | : Type(Atomic, Canonical, ValTy->isDependentType(), |
6051 | ValTy->isInstantiationDependentType(), |
6052 | ValTy->isVariablyModifiedType(), |
6053 | ValTy->containsUnexpandedParameterPack()), |
6054 | ValueType(ValTy) {} |
6055 | |
6056 | public: |
6057 | /// Gets the type contained by this atomic type, i.e. |
6058 | /// the type returned by performing an atomic load of this atomic type. |
6059 | QualType getValueType() const { return ValueType; } |
6060 | |
6061 | bool isSugared() const { return false; } |
6062 | QualType desugar() const { return QualType(this, 0); } |
6063 | |
6064 | void Profile(llvm::FoldingSetNodeID &ID) { |
6065 | Profile(ID, getValueType()); |
6066 | } |
6067 | |
6068 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6069 | ID.AddPointer(T.getAsOpaquePtr()); |
6070 | } |
6071 | |
6072 | static bool classof(const Type *T) { |
6073 | return T->getTypeClass() == Atomic; |
6074 | } |
6075 | }; |
6076 | |
6077 | /// PipeType - OpenCL20. |
6078 | class PipeType : public Type, public llvm::FoldingSetNode { |
6079 | friend class ASTContext; // ASTContext creates these. |
6080 | |
6081 | QualType ElementType; |
6082 | bool isRead; |
6083 | |
6084 | PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) |
6085 | : Type(Pipe, CanonicalPtr, elemType->isDependentType(), |
6086 | elemType->isInstantiationDependentType(), |
6087 | elemType->isVariablyModifiedType(), |
6088 | elemType->containsUnexpandedParameterPack()), |
6089 | ElementType(elemType), isRead(isRead) {} |
6090 | |
6091 | public: |
6092 | QualType getElementType() const { return ElementType; } |
6093 | |
6094 | bool isSugared() const { return false; } |
6095 | |
6096 | QualType desugar() const { return QualType(this, 0); } |
6097 | |
6098 | void Profile(llvm::FoldingSetNodeID &ID) { |
6099 | Profile(ID, getElementType(), isReadOnly()); |
6100 | } |
6101 | |
6102 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { |
6103 | ID.AddPointer(T.getAsOpaquePtr()); |
6104 | ID.AddBoolean(isRead); |
6105 | } |
6106 | |
6107 | static bool classof(const Type *T) { |
6108 | return T->getTypeClass() == Pipe; |
6109 | } |
6110 | |
6111 | bool isReadOnly() const { return isRead; } |
6112 | }; |
6113 | |
6114 | /// A qualifier set is used to build a set of qualifiers. |
6115 | class QualifierCollector : public Qualifiers { |
6116 | public: |
6117 | QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} |
6118 | |
6119 | /// Collect any qualifiers on the given type and return an |
6120 | /// unqualified type. The qualifiers are assumed to be consistent |
6121 | /// with those already in the type. |
6122 | const Type *strip(QualType type) { |
6123 | addFastQualifiers(type.getLocalFastQualifiers()); |
6124 | if (!type.hasLocalNonFastQualifiers()) |
6125 | return type.getTypePtrUnsafe(); |
6126 | |
6127 | const ExtQuals *extQuals = type.getExtQualsUnsafe(); |
6128 | addConsistentQualifiers(extQuals->getQualifiers()); |
6129 | return extQuals->getBaseType(); |
6130 | } |
6131 | |
6132 | /// Apply the collected qualifiers to the given type. |
6133 | QualType apply(const ASTContext &Context, QualType QT) const; |
6134 | |
6135 | /// Apply the collected qualifiers to the given type. |
6136 | QualType apply(const ASTContext &Context, const Type* T) const; |
6137 | }; |
6138 | |
6139 | // Inline function definitions. |
6140 | |
6141 | inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { |
6142 | SplitQualType desugar = |
6143 | Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); |
6144 | desugar.Quals.addConsistentQualifiers(Quals); |
6145 | return desugar; |
6146 | } |
6147 | |
6148 | inline const Type *QualType::getTypePtr() const { |
6149 | return getCommonPtr()->BaseType; |
6150 | } |
6151 | |
6152 | inline const Type *QualType::getTypePtrOrNull() const { |
6153 | return (isNull() ? nullptr : getCommonPtr()->BaseType); |
6154 | } |
6155 | |
6156 | inline SplitQualType QualType::split() const { |
6157 | if (!hasLocalNonFastQualifiers()) |
6158 | return SplitQualType(getTypePtrUnsafe(), |
6159 | Qualifiers::fromFastMask(getLocalFastQualifiers())); |
6160 | |
6161 | const ExtQuals *eq = getExtQualsUnsafe(); |
6162 | Qualifiers qs = eq->getQualifiers(); |
6163 | qs.addFastQualifiers(getLocalFastQualifiers()); |
6164 | return SplitQualType(eq->getBaseType(), qs); |
6165 | } |
6166 | |
6167 | inline Qualifiers QualType::getLocalQualifiers() const { |
6168 | Qualifiers Quals; |
6169 | if (hasLocalNonFastQualifiers()) |
6170 | Quals = getExtQualsUnsafe()->getQualifiers(); |
6171 | Quals.addFastQualifiers(getLocalFastQualifiers()); |
6172 | return Quals; |
6173 | } |
6174 | |
6175 | inline Qualifiers QualType::getQualifiers() const { |
6176 | Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); |
6177 | quals.addFastQualifiers(getLocalFastQualifiers()); |
6178 | return quals; |
6179 | } |
6180 | |
6181 | inline unsigned QualType::getCVRQualifiers() const { |
6182 | unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); |
6183 | cvr |= getLocalCVRQualifiers(); |
6184 | return cvr; |
6185 | } |
6186 | |
6187 | inline QualType QualType::getCanonicalType() const { |
6188 | QualType canon = getCommonPtr()->CanonicalType; |
6189 | return canon.withFastQualifiers(getLocalFastQualifiers()); |
6190 | } |
6191 | |
6192 | inline bool QualType::isCanonical() const { |
6193 | return getTypePtr()->isCanonicalUnqualified(); |
6194 | } |
6195 | |
6196 | inline bool QualType::isCanonicalAsParam() const { |
6197 | if (!isCanonical()) return false; |
6198 | if (hasLocalQualifiers()) return false; |
6199 | |
6200 | const Type *T = getTypePtr(); |
6201 | if (T->isVariablyModifiedType() && T->hasSizedVLAType()) |
6202 | return false; |
6203 | |
6204 | return !isa<FunctionType>(T) && !isa<ArrayType>(T); |
6205 | } |
6206 | |
6207 | inline bool QualType::isConstQualified() const { |
6208 | return isLocalConstQualified() || |
6209 | getCommonPtr()->CanonicalType.isLocalConstQualified(); |
6210 | } |
6211 | |
6212 | inline bool QualType::isRestrictQualified() const { |
6213 | return isLocalRestrictQualified() || |
6214 | getCommonPtr()->CanonicalType.isLocalRestrictQualified(); |
6215 | } |
6216 | |
6217 | |
6218 | inline bool QualType::isVolatileQualified() const { |
6219 | return isLocalVolatileQualified() || |
6220 | getCommonPtr()->CanonicalType.isLocalVolatileQualified(); |
6221 | } |
6222 | |
6223 | inline bool QualType::hasQualifiers() const { |
6224 | return hasLocalQualifiers() || |
6225 | getCommonPtr()->CanonicalType.hasLocalQualifiers(); |
6226 | } |
6227 | |
6228 | inline QualType QualType::getUnqualifiedType() const { |
6229 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6230 | return QualType(getTypePtr(), 0); |
6231 | |
6232 | return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); |
6233 | } |
6234 | |
6235 | inline SplitQualType QualType::getSplitUnqualifiedType() const { |
6236 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6237 | return split(); |
6238 | |
6239 | return getSplitUnqualifiedTypeImpl(*this); |
6240 | } |
6241 | |
6242 | inline void QualType::removeLocalConst() { |
6243 | removeLocalFastQualifiers(Qualifiers::Const); |
6244 | } |
6245 | |
6246 | inline void QualType::removeLocalRestrict() { |
6247 | removeLocalFastQualifiers(Qualifiers::Restrict); |
6248 | } |
6249 | |
6250 | inline void QualType::removeLocalVolatile() { |
6251 | removeLocalFastQualifiers(Qualifiers::Volatile); |
6252 | } |
6253 | |
6254 | inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { |
6255 | assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6255, __PRETTY_FUNCTION__)); |
6256 | static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, |
6257 | "Fast bits differ from CVR bits!"); |
6258 | |
6259 | // Fast path: we don't need to touch the slow qualifiers. |
6260 | removeLocalFastQualifiers(Mask); |
6261 | } |
6262 | |
6263 | /// Return the address space of this type. |
6264 | inline LangAS QualType::getAddressSpace() const { |
6265 | return getQualifiers().getAddressSpace(); |
6266 | } |
6267 | |
6268 | /// Return the gc attribute of this type. |
6269 | inline Qualifiers::GC QualType::getObjCGCAttr() const { |
6270 | return getQualifiers().getObjCGCAttr(); |
6271 | } |
6272 | |
6273 | inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
6274 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6275 | return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD); |
6276 | return false; |
6277 | } |
6278 | |
6279 | inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const { |
6280 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6281 | return hasNonTrivialToPrimitiveDestructCUnion(RD); |
6282 | return false; |
6283 | } |
6284 | |
6285 | inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { |
6286 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6287 | return hasNonTrivialToPrimitiveCopyCUnion(RD); |
6288 | return false; |
6289 | } |
6290 | |
6291 | inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { |
6292 | if (const auto *PT = t.getAs<PointerType>()) { |
6293 | if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) |
6294 | return FT->getExtInfo(); |
6295 | } else if (const auto *FT = t.getAs<FunctionType>()) |
6296 | return FT->getExtInfo(); |
6297 | |
6298 | return FunctionType::ExtInfo(); |
6299 | } |
6300 | |
6301 | inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { |
6302 | return getFunctionExtInfo(*t); |
6303 | } |
6304 | |
6305 | /// Determine whether this type is more |
6306 | /// qualified than the Other type. For example, "const volatile int" |
6307 | /// is more qualified than "const int", "volatile int", and |
6308 | /// "int". However, it is not more qualified than "const volatile |
6309 | /// int". |
6310 | inline bool QualType::isMoreQualifiedThan(QualType other) const { |
6311 | Qualifiers MyQuals = getQualifiers(); |
6312 | Qualifiers OtherQuals = other.getQualifiers(); |
6313 | return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); |
6314 | } |
6315 | |
6316 | /// Determine whether this type is at last |
6317 | /// as qualified as the Other type. For example, "const volatile |
6318 | /// int" is at least as qualified as "const int", "volatile int", |
6319 | /// "int", and "const volatile int". |
6320 | inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { |
6321 | Qualifiers OtherQuals = other.getQualifiers(); |
6322 | |
6323 | // Ignore __unaligned qualifier if this type is a void. |
6324 | if (getUnqualifiedType()->isVoidType()) |
6325 | OtherQuals.removeUnaligned(); |
6326 | |
6327 | return getQualifiers().compatiblyIncludes(OtherQuals); |
6328 | } |
6329 | |
6330 | /// If Type is a reference type (e.g., const |
6331 | /// int&), returns the type that the reference refers to ("const |
6332 | /// int"). Otherwise, returns the type itself. This routine is used |
6333 | /// throughout Sema to implement C++ 5p6: |
6334 | /// |
6335 | /// If an expression initially has the type "reference to T" (8.3.2, |
6336 | /// 8.5.3), the type is adjusted to "T" prior to any further |
6337 | /// analysis, the expression designates the object or function |
6338 | /// denoted by the reference, and the expression is an lvalue. |
6339 | inline QualType QualType::getNonReferenceType() const { |
6340 | if (const auto *RefType = (*this)->getAs<ReferenceType>()) |
6341 | return RefType->getPointeeType(); |
6342 | else |
6343 | return *this; |
6344 | } |
6345 | |
6346 | inline bool QualType::isCForbiddenLValueType() const { |
6347 | return ((getTypePtr()->isVoidType() && !hasQualifiers()) || |
6348 | getTypePtr()->isFunctionType()); |
6349 | } |
6350 | |
6351 | /// Tests whether the type is categorized as a fundamental type. |
6352 | /// |
6353 | /// \returns True for types specified in C++0x [basic.fundamental]. |
6354 | inline bool Type::isFundamentalType() const { |
6355 | return isVoidType() || |
6356 | isNullPtrType() || |
6357 | // FIXME: It's really annoying that we don't have an |
6358 | // 'isArithmeticType()' which agrees with the standard definition. |
6359 | (isArithmeticType() && !isEnumeralType()); |
6360 | } |
6361 | |
6362 | /// Tests whether the type is categorized as a compound type. |
6363 | /// |
6364 | /// \returns True for types specified in C++0x [basic.compound]. |
6365 | inline bool Type::isCompoundType() const { |
6366 | // C++0x [basic.compound]p1: |
6367 | // Compound types can be constructed in the following ways: |
6368 | // -- arrays of objects of a given type [...]; |
6369 | return isArrayType() || |
6370 | // -- functions, which have parameters of given types [...]; |
6371 | isFunctionType() || |
6372 | // -- pointers to void or objects or functions [...]; |
6373 | isPointerType() || |
6374 | // -- references to objects or functions of a given type. [...] |
6375 | isReferenceType() || |
6376 | // -- classes containing a sequence of objects of various types, [...]; |
6377 | isRecordType() || |
6378 | // -- unions, which are classes capable of containing objects of different |
6379 | // types at different times; |
6380 | isUnionType() || |
6381 | // -- enumerations, which comprise a set of named constant values. [...]; |
6382 | isEnumeralType() || |
6383 | // -- pointers to non-static class members, [...]. |
6384 | isMemberPointerType(); |
6385 | } |
6386 | |
6387 | inline bool Type::isFunctionType() const { |
6388 | return isa<FunctionType>(CanonicalType); |
6389 | } |
6390 | |
6391 | inline bool Type::isPointerType() const { |
6392 | return isa<PointerType>(CanonicalType); |
6393 | } |
6394 | |
6395 | inline bool Type::isAnyPointerType() const { |
6396 | return isPointerType() || isObjCObjectPointerType(); |
6397 | } |
6398 | |
6399 | inline bool Type::isBlockPointerType() const { |
6400 | return isa<BlockPointerType>(CanonicalType); |
6401 | } |
6402 | |
6403 | inline bool Type::isReferenceType() const { |
6404 | return isa<ReferenceType>(CanonicalType); |
6405 | } |
6406 | |
6407 | inline bool Type::isLValueReferenceType() const { |
6408 | return isa<LValueReferenceType>(CanonicalType); |
6409 | } |
6410 | |
6411 | inline bool Type::isRValueReferenceType() const { |
6412 | return isa<RValueReferenceType>(CanonicalType); |
6413 | } |
6414 | |
6415 | inline bool Type::isFunctionPointerType() const { |
6416 | if (const auto *T = getAs<PointerType>()) |
6417 | return T->getPointeeType()->isFunctionType(); |
6418 | else |
6419 | return false; |
6420 | } |
6421 | |
6422 | inline bool Type::isFunctionReferenceType() const { |
6423 | if (const auto *T = getAs<ReferenceType>()) |
6424 | return T->getPointeeType()->isFunctionType(); |
6425 | else |
6426 | return false; |
6427 | } |
6428 | |
6429 | inline bool Type::isMemberPointerType() const { |
6430 | return isa<MemberPointerType>(CanonicalType); |
6431 | } |
6432 | |
6433 | inline bool Type::isMemberFunctionPointerType() const { |
6434 | if (const auto *T = getAs<MemberPointerType>()) |
6435 | return T->isMemberFunctionPointer(); |
6436 | else |
6437 | return false; |
6438 | } |
6439 | |
6440 | inline bool Type::isMemberDataPointerType() const { |
6441 | if (const auto *T = getAs<MemberPointerType>()) |
6442 | return T->isMemberDataPointer(); |
6443 | else |
6444 | return false; |
6445 | } |
6446 | |
6447 | inline bool Type::isArrayType() const { |
6448 | return isa<ArrayType>(CanonicalType); |
6449 | } |
6450 | |
6451 | inline bool Type::isConstantArrayType() const { |
6452 | return isa<ConstantArrayType>(CanonicalType); |
6453 | } |
6454 | |
6455 | inline bool Type::isIncompleteArrayType() const { |
6456 | return isa<IncompleteArrayType>(CanonicalType); |
6457 | } |
6458 | |
6459 | inline bool Type::isVariableArrayType() const { |
6460 | return isa<VariableArrayType>(CanonicalType); |
6461 | } |
6462 | |
6463 | inline bool Type::isDependentSizedArrayType() const { |
6464 | return isa<DependentSizedArrayType>(CanonicalType); |
6465 | } |
6466 | |
6467 | inline bool Type::isBuiltinType() const { |
6468 | return isa<BuiltinType>(CanonicalType); |
6469 | } |
6470 | |
6471 | inline bool Type::isRecordType() const { |
6472 | return isa<RecordType>(CanonicalType); |
6473 | } |
6474 | |
6475 | inline bool Type::isEnumeralType() const { |
6476 | return isa<EnumType>(CanonicalType); |
6477 | } |
6478 | |
6479 | inline bool Type::isAnyComplexType() const { |
6480 | return isa<ComplexType>(CanonicalType); |
6481 | } |
6482 | |
6483 | inline bool Type::isVectorType() const { |
6484 | return isa<VectorType>(CanonicalType); |
6485 | } |
6486 | |
6487 | inline bool Type::isExtVectorType() const { |
6488 | return isa<ExtVectorType>(CanonicalType); |
6489 | } |
6490 | |
6491 | inline bool Type::isDependentAddressSpaceType() const { |
6492 | return isa<DependentAddressSpaceType>(CanonicalType); |
6493 | } |
6494 | |
6495 | inline bool Type::isObjCObjectPointerType() const { |
6496 | return isa<ObjCObjectPointerType>(CanonicalType); |
6497 | } |
6498 | |
6499 | inline bool Type::isObjCObjectType() const { |
6500 | return isa<ObjCObjectType>(CanonicalType); |
6501 | } |
6502 | |
6503 | inline bool Type::isObjCObjectOrInterfaceType() const { |
6504 | return isa<ObjCInterfaceType>(CanonicalType) || |
6505 | isa<ObjCObjectType>(CanonicalType); |
6506 | } |
6507 | |
6508 | inline bool Type::isAtomicType() const { |
6509 | return isa<AtomicType>(CanonicalType); |
6510 | } |
6511 | |
6512 | inline bool Type::isObjCQualifiedIdType() const { |
6513 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6514 | return OPT->isObjCQualifiedIdType(); |
6515 | return false; |
6516 | } |
6517 | |
6518 | inline bool Type::isObjCQualifiedClassType() const { |
6519 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6520 | return OPT->isObjCQualifiedClassType(); |
6521 | return false; |
6522 | } |
6523 | |
6524 | inline bool Type::isObjCIdType() const { |
6525 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6526 | return OPT->isObjCIdType(); |
6527 | return false; |
6528 | } |
6529 | |
6530 | inline bool Type::isObjCClassType() const { |
6531 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6532 | return OPT->isObjCClassType(); |
6533 | return false; |
6534 | } |
6535 | |
6536 | inline bool Type::isObjCSelType() const { |
6537 | if (const auto *OPT = getAs<PointerType>()) |
6538 | return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); |
6539 | return false; |
6540 | } |
6541 | |
6542 | inline bool Type::isObjCBuiltinType() const { |
6543 | return isObjCIdType() || isObjCClassType() || isObjCSelType(); |
6544 | } |
6545 | |
6546 | inline bool Type::isDecltypeType() const { |
6547 | return isa<DecltypeType>(this); |
6548 | } |
6549 | |
6550 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6551 | inline bool Type::is##Id##Type() const { \ |
6552 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6553 | } |
6554 | #include "clang/Basic/OpenCLImageTypes.def" |
6555 | |
6556 | inline bool Type::isSamplerT() const { |
6557 | return isSpecificBuiltinType(BuiltinType::OCLSampler); |
6558 | } |
6559 | |
6560 | inline bool Type::isEventT() const { |
6561 | return isSpecificBuiltinType(BuiltinType::OCLEvent); |
6562 | } |
6563 | |
6564 | inline bool Type::isClkEventT() const { |
6565 | return isSpecificBuiltinType(BuiltinType::OCLClkEvent); |
6566 | } |
6567 | |
6568 | inline bool Type::isQueueT() const { |
6569 | return isSpecificBuiltinType(BuiltinType::OCLQueue); |
6570 | } |
6571 | |
6572 | inline bool Type::isReserveIDT() const { |
6573 | return isSpecificBuiltinType(BuiltinType::OCLReserveID); |
6574 | } |
6575 | |
6576 | inline bool Type::isImageType() const { |
6577 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || |
6578 | return |
6579 | #include "clang/Basic/OpenCLImageTypes.def" |
6580 | false; // end boolean or operation |
6581 | } |
6582 | |
6583 | inline bool Type::isPipeType() const { |
6584 | return isa<PipeType>(CanonicalType); |
6585 | } |
6586 | |
6587 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
6588 | inline bool Type::is##Id##Type() const { \ |
6589 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6590 | } |
6591 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6592 | |
6593 | inline bool Type::isOCLIntelSubgroupAVCType() const { |
6594 | #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \ |
6595 | isOCLIntelSubgroupAVC##Id##Type() || |
6596 | return |
6597 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6598 | false; // end of boolean or operation |
6599 | } |
6600 | |
6601 | inline bool Type::isOCLExtOpaqueType() const { |
6602 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() || |
6603 | return |
6604 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6605 | false; // end of boolean or operation |
6606 | } |
6607 | |
6608 | inline bool Type::isOpenCLSpecificType() const { |
6609 | return isSamplerT() || isEventT() || isImageType() || isClkEventT() || |
6610 | isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType(); |
6611 | } |
6612 | |
6613 | inline bool Type::isTemplateTypeParmType() const { |
6614 | return isa<TemplateTypeParmType>(CanonicalType); |
6615 | } |
6616 | |
6617 | inline bool Type::isSpecificBuiltinType(unsigned K) const { |
6618 | if (const BuiltinType *BT = getAs<BuiltinType>()) |
6619 | if (BT->getKind() == (BuiltinType::Kind) K) |
6620 | return true; |
6621 | return false; |
6622 | } |
6623 | |
6624 | inline bool Type::isPlaceholderType() const { |
6625 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6626 | return BT->isPlaceholderType(); |
6627 | return false; |
6628 | } |
6629 | |
6630 | inline const BuiltinType *Type::getAsPlaceholderType() const { |
6631 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6632 | if (BT->isPlaceholderType()) |
6633 | return BT; |
6634 | return nullptr; |
6635 | } |
6636 | |
6637 | inline bool Type::isSpecificPlaceholderType(unsigned K) const { |
6638 | assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ? static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6638, __PRETTY_FUNCTION__)); |
6639 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6640 | return (BT->getKind() == (BuiltinType::Kind) K); |
6641 | return false; |
6642 | } |
6643 | |
6644 | inline bool Type::isNonOverloadPlaceholderType() const { |
6645 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6646 | return BT->isNonOverloadPlaceholderType(); |
6647 | return false; |
6648 | } |
6649 | |
6650 | inline bool Type::isVoidType() const { |
6651 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6652 | return BT->getKind() == BuiltinType::Void; |
6653 | return false; |
6654 | } |
6655 | |
6656 | inline bool Type::isHalfType() const { |
6657 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6658 | return BT->getKind() == BuiltinType::Half; |
6659 | // FIXME: Should we allow complex __fp16? Probably not. |
6660 | return false; |
6661 | } |
6662 | |
6663 | inline bool Type::isFloat16Type() const { |
6664 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6665 | return BT->getKind() == BuiltinType::Float16; |
6666 | return false; |
6667 | } |
6668 | |
6669 | inline bool Type::isFloat128Type() const { |
6670 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6671 | return BT->getKind() == BuiltinType::Float128; |
6672 | return false; |
6673 | } |
6674 | |
6675 | inline bool Type::isNullPtrType() const { |
6676 | if (const auto *BT = getAs<BuiltinType>()) |
6677 | return BT->getKind() == BuiltinType::NullPtr; |
6678 | return false; |
6679 | } |
6680 | |
6681 | bool IsEnumDeclComplete(EnumDecl *); |
6682 | bool IsEnumDeclScoped(EnumDecl *); |
6683 | |
6684 | inline bool Type::isIntegerType() const { |
6685 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6686 | return BT->getKind() >= BuiltinType::Bool && |
6687 | BT->getKind() <= BuiltinType::Int128; |
6688 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { |
6689 | // Incomplete enum types are not treated as integer types. |
6690 | // FIXME: In C++, enum types are never integer types. |
6691 | return IsEnumDeclComplete(ET->getDecl()) && |
6692 | !IsEnumDeclScoped(ET->getDecl()); |
6693 | } |
6694 | return false; |
6695 | } |
6696 | |
6697 | inline bool Type::isFixedPointType() const { |
6698 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6699 | return BT->getKind() >= BuiltinType::ShortAccum && |
6700 | BT->getKind() <= BuiltinType::SatULongFract; |
6701 | } |
6702 | return false; |
6703 | } |
6704 | |
6705 | inline bool Type::isFixedPointOrIntegerType() const { |
6706 | return isFixedPointType() || isIntegerType(); |
6707 | } |
6708 | |
6709 | inline bool Type::isSaturatedFixedPointType() const { |
6710 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6711 | return BT->getKind() >= BuiltinType::SatShortAccum && |
6712 | BT->getKind() <= BuiltinType::SatULongFract; |
6713 | } |
6714 | return false; |
6715 | } |
6716 | |
6717 | inline bool Type::isUnsaturatedFixedPointType() const { |
6718 | return isFixedPointType() && !isSaturatedFixedPointType(); |
6719 | } |
6720 | |
6721 | inline bool Type::isSignedFixedPointType() const { |
6722 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6723 | return ((BT->getKind() >= BuiltinType::ShortAccum && |
6724 | BT->getKind() <= BuiltinType::LongAccum) || |
6725 | (BT->getKind() >= BuiltinType::ShortFract && |
6726 | BT->getKind() <= BuiltinType::LongFract) || |
6727 | (BT->getKind() >= BuiltinType::SatShortAccum && |
6728 | BT->getKind() <= BuiltinType::SatLongAccum) || |
6729 | (BT->getKind() >= BuiltinType::SatShortFract && |
6730 | BT->getKind() <= BuiltinType::SatLongFract)); |
6731 | } |
6732 | return false; |
6733 | } |
6734 | |
6735 | inline bool Type::isUnsignedFixedPointType() const { |
6736 | return isFixedPointType() && !isSignedFixedPointType(); |
6737 | } |
6738 | |
6739 | inline bool Type::isScalarType() const { |
6740 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6741 | return BT->getKind() > BuiltinType::Void && |
6742 | BT->getKind() <= BuiltinType::NullPtr; |
6743 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) |
6744 | // Enums are scalar types, but only if they are defined. Incomplete enums |
6745 | // are not treated as scalar types. |
6746 | return IsEnumDeclComplete(ET->getDecl()); |
6747 | return isa<PointerType>(CanonicalType) || |
6748 | isa<BlockPointerType>(CanonicalType) || |
6749 | isa<MemberPointerType>(CanonicalType) || |
6750 | isa<ComplexType>(CanonicalType) || |
6751 | isa<ObjCObjectPointerType>(CanonicalType); |
6752 | } |
6753 | |
6754 | inline bool Type::isIntegralOrEnumerationType() const { |
6755 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6756 | return BT->getKind() >= BuiltinType::Bool && |
6757 | BT->getKind() <= BuiltinType::Int128; |
6758 | |
6759 | // Check for a complete enum type; incomplete enum types are not properly an |
6760 | // enumeration type in the sense required here. |
6761 | if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) |
6762 | return IsEnumDeclComplete(ET->getDecl()); |
6763 | |
6764 | return false; |
6765 | } |
6766 | |
6767 | inline bool Type::isBooleanType() const { |
6768 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6769 | return BT->getKind() == BuiltinType::Bool; |
6770 | return false; |
6771 | } |
6772 | |
6773 | inline bool Type::isUndeducedType() const { |
6774 | auto *DT = getContainedDeducedType(); |
6775 | return DT && !DT->isDeduced(); |
6776 | } |
6777 | |
6778 | /// Determines whether this is a type for which one can define |
6779 | /// an overloaded operator. |
6780 | inline bool Type::isOverloadableType() const { |
6781 | return isDependentType() || isRecordType() || isEnumeralType(); |
6782 | } |
6783 | |
6784 | /// Determines whether this type can decay to a pointer type. |
6785 | inline bool Type::canDecayToPointerType() const { |
6786 | return isFunctionType() || isArrayType(); |
6787 | } |
6788 | |
6789 | inline bool Type::hasPointerRepresentation() const { |
6790 | return (isPointerType() || isReferenceType() || isBlockPointerType() || |
6791 | isObjCObjectPointerType() || isNullPtrType()); |
6792 | } |
6793 | |
6794 | inline bool Type::hasObjCPointerRepresentation() const { |
6795 | return isObjCObjectPointerType(); |
6796 | } |
6797 | |
6798 | inline const Type *Type::getBaseElementTypeUnsafe() const { |
6799 | const Type *type = this; |
6800 | while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) |
6801 | type = arrayType->getElementType().getTypePtr(); |
6802 | return type; |
6803 | } |
6804 | |
6805 | inline const Type *Type::getPointeeOrArrayElementType() const { |
6806 | const Type *type = this; |
6807 | if (type->isAnyPointerType()) |
6808 | return type->getPointeeType().getTypePtr(); |
6809 | else if (type->isArrayType()) |
6810 | return type->getBaseElementTypeUnsafe(); |
6811 | return type; |
6812 | } |
6813 | |
6814 | /// Insertion operator for diagnostics. This allows sending Qualifiers into a |
6815 | /// diagnostic with <<. |
6816 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
6817 | Qualifiers Q) { |
6818 | DB.AddTaggedVal(Q.getAsOpaqueValue(), |
6819 | DiagnosticsEngine::ArgumentKind::ak_qual); |
6820 | return DB; |
6821 | } |
6822 | |
6823 | /// Insertion operator for partial diagnostics. This allows sending Qualifiers |
6824 | /// into a diagnostic with <<. |
6825 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
6826 | Qualifiers Q) { |
6827 | PD.AddTaggedVal(Q.getAsOpaqueValue(), |
6828 | DiagnosticsEngine::ArgumentKind::ak_qual); |
6829 | return PD; |
6830 | } |
6831 | |
6832 | /// Insertion operator for diagnostics. This allows sending QualType's into a |
6833 | /// diagnostic with <<. |
6834 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
6835 | QualType T) { |
6836 | DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
6837 | DiagnosticsEngine::ak_qualtype); |
6838 | return DB; |
6839 | } |
6840 | |
6841 | /// Insertion operator for partial diagnostics. This allows sending QualType's |
6842 | /// into a diagnostic with <<. |
6843 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
6844 | QualType T) { |
6845 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
6846 | DiagnosticsEngine::ak_qualtype); |
6847 | return PD; |
6848 | } |
6849 | |
6850 | // Helper class template that is used by Type::getAs to ensure that one does |
6851 | // not try to look through a qualified type to get to an array type. |
6852 | template <typename T> |
6853 | using TypeIsArrayType = |
6854 | std::integral_constant<bool, std::is_same<T, ArrayType>::value || |
6855 | std::is_base_of<ArrayType, T>::value>; |
6856 | |
6857 | // Member-template getAs<specific type>'. |
6858 | template <typename T> const T *Type::getAs() const { |
6859 | static_assert(!TypeIsArrayType<T>::value, |
6860 | "ArrayType cannot be used with getAs!"); |
6861 | |
6862 | // If this is directly a T type, return it. |
6863 | if (const auto *Ty = dyn_cast<T>(this)) |
6864 | return Ty; |
6865 | |
6866 | // If the canonical form of this type isn't the right kind, reject it. |
6867 | if (!isa<T>(CanonicalType)) |
6868 | return nullptr; |
6869 | |
6870 | // If this is a typedef for the type, strip the typedef off without |
6871 | // losing all typedef information. |
6872 | return cast<T>(getUnqualifiedDesugaredType()); |
6873 | } |
6874 | |
6875 | template <typename T> const T *Type::getAsAdjusted() const { |
6876 | static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); |
6877 | |
6878 | // If this is directly a T type, return it. |
6879 | if (const auto *Ty = dyn_cast<T>(this)) |
6880 | return Ty; |
6881 | |
6882 | // If the canonical form of this type isn't the right kind, reject it. |
6883 | if (!isa<T>(CanonicalType)) |
6884 | return nullptr; |
6885 | |
6886 | // Strip off type adjustments that do not modify the underlying nature of the |
6887 | // type. |
6888 | const Type *Ty = this; |
6889 | while (Ty) { |
6890 | if (const auto *A = dyn_cast<AttributedType>(Ty)) |
6891 | Ty = A->getModifiedType().getTypePtr(); |
6892 | else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) |
6893 | Ty = E->desugar().getTypePtr(); |
6894 | else if (const auto *P = dyn_cast<ParenType>(Ty)) |
6895 | Ty = P->desugar().getTypePtr(); |
6896 | else if (const auto *A = dyn_cast<AdjustedType>(Ty)) |
6897 | Ty = A->desugar().getTypePtr(); |
6898 | else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) |
6899 | Ty = M->desugar().getTypePtr(); |
6900 | else |
6901 | break; |
6902 | } |
6903 | |
6904 | // Just because the canonical type is correct does not mean we can use cast<>, |
6905 | // since we may not have stripped off all the sugar down to the base type. |
6906 | return dyn_cast<T>(Ty); |
6907 | } |
6908 | |
6909 | inline const ArrayType *Type::getAsArrayTypeUnsafe() const { |
6910 | // If this is directly an array type, return it. |
6911 | if (const auto *arr = dyn_cast<ArrayType>(this)) |
6912 | return arr; |
6913 | |
6914 | // If the canonical form of this type isn't the right kind, reject it. |
6915 | if (!isa<ArrayType>(CanonicalType)) |
6916 | return nullptr; |
6917 | |
6918 | // If this is a typedef for the type, strip the typedef off without |
6919 | // losing all typedef information. |
6920 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
6921 | } |
6922 | |
6923 | template <typename T> const T *Type::castAs() const { |
6924 | static_assert(!TypeIsArrayType<T>::value, |
6925 | "ArrayType cannot be used with castAs!"); |
6926 | |
6927 | if (const auto *ty = dyn_cast<T>(this)) return ty; |
6928 | assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6928, __PRETTY_FUNCTION__)); |
6929 | return cast<T>(getUnqualifiedDesugaredType()); |
6930 | } |
6931 | |
6932 | inline const ArrayType *Type::castAsArrayTypeUnsafe() const { |
6933 | assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6933, __PRETTY_FUNCTION__)); |
6934 | if (const auto *arr = dyn_cast<ArrayType>(this)) return arr; |
6935 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
6936 | } |
6937 | |
6938 | DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, |
6939 | QualType CanonicalPtr) |
6940 | : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { |
6941 | #ifndef NDEBUG |
6942 | QualType Adjusted = getAdjustedType(); |
6943 | (void)AttributedType::stripOuterNullability(Adjusted); |
6944 | assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6944, __PRETTY_FUNCTION__)); |
6945 | #endif |
6946 | } |
6947 | |
6948 | QualType DecayedType::getPointeeType() const { |
6949 | QualType Decayed = getDecayedType(); |
6950 | (void)AttributedType::stripOuterNullability(Decayed); |
6951 | return cast<PointerType>(Decayed)->getPointeeType(); |
6952 | } |
6953 | |
6954 | // Get the decimal string representation of a fixed point type, represented |
6955 | // as a scaled integer. |
6956 | // TODO: At some point, we should change the arguments to instead just accept an |
6957 | // APFixedPoint instead of APSInt and scale. |
6958 | void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val, |
6959 | unsigned Scale); |
6960 | |
6961 | } // namespace clang |
6962 | |
6963 | #endif // LLVM_CLANG_AST_TYPE_H |