File: | tools/clang/lib/Sema/SemaExprCXX.cpp |
Warning: | line 3305, column 24 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// | |||
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 | /// Implements semantic analysis for C++ expressions. | |||
11 | /// | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "clang/Sema/SemaInternal.h" | |||
15 | #include "TreeTransform.h" | |||
16 | #include "TypeLocBuilder.h" | |||
17 | #include "clang/AST/ASTContext.h" | |||
18 | #include "clang/AST/ASTLambda.h" | |||
19 | #include "clang/AST/CXXInheritance.h" | |||
20 | #include "clang/AST/CharUnits.h" | |||
21 | #include "clang/AST/DeclObjC.h" | |||
22 | #include "clang/AST/ExprCXX.h" | |||
23 | #include "clang/AST/ExprObjC.h" | |||
24 | #include "clang/AST/RecursiveASTVisitor.h" | |||
25 | #include "clang/AST/TypeLoc.h" | |||
26 | #include "clang/Basic/AlignedAllocation.h" | |||
27 | #include "clang/Basic/PartialDiagnostic.h" | |||
28 | #include "clang/Basic/TargetInfo.h" | |||
29 | #include "clang/Lex/Preprocessor.h" | |||
30 | #include "clang/Sema/DeclSpec.h" | |||
31 | #include "clang/Sema/Initialization.h" | |||
32 | #include "clang/Sema/Lookup.h" | |||
33 | #include "clang/Sema/ParsedTemplate.h" | |||
34 | #include "clang/Sema/Scope.h" | |||
35 | #include "clang/Sema/ScopeInfo.h" | |||
36 | #include "clang/Sema/SemaLambda.h" | |||
37 | #include "clang/Sema/TemplateDeduction.h" | |||
38 | #include "llvm/ADT/APInt.h" | |||
39 | #include "llvm/ADT/STLExtras.h" | |||
40 | #include "llvm/Support/ErrorHandling.h" | |||
41 | using namespace clang; | |||
42 | using namespace sema; | |||
43 | ||||
44 | /// Handle the result of the special case name lookup for inheriting | |||
45 | /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as | |||
46 | /// constructor names in member using declarations, even if 'X' is not the | |||
47 | /// name of the corresponding type. | |||
48 | ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, | |||
49 | SourceLocation NameLoc, | |||
50 | IdentifierInfo &Name) { | |||
51 | NestedNameSpecifier *NNS = SS.getScopeRep(); | |||
52 | ||||
53 | // Convert the nested-name-specifier into a type. | |||
54 | QualType Type; | |||
55 | switch (NNS->getKind()) { | |||
56 | case NestedNameSpecifier::TypeSpec: | |||
57 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
58 | Type = QualType(NNS->getAsType(), 0); | |||
59 | break; | |||
60 | ||||
61 | case NestedNameSpecifier::Identifier: | |||
62 | // Strip off the last layer of the nested-name-specifier and build a | |||
63 | // typename type for it. | |||
64 | assert(NNS->getAsIdentifier() == &Name && "not a constructor name")((NNS->getAsIdentifier() == &Name && "not a constructor name" ) ? static_cast<void> (0) : __assert_fail ("NNS->getAsIdentifier() == &Name && \"not a constructor name\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 64, __PRETTY_FUNCTION__)); | |||
65 | Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(), | |||
66 | NNS->getAsIdentifier()); | |||
67 | break; | |||
68 | ||||
69 | case NestedNameSpecifier::Global: | |||
70 | case NestedNameSpecifier::Super: | |||
71 | case NestedNameSpecifier::Namespace: | |||
72 | case NestedNameSpecifier::NamespaceAlias: | |||
73 | llvm_unreachable("Nested name specifier is not a type for inheriting ctor")::llvm::llvm_unreachable_internal("Nested name specifier is not a type for inheriting ctor" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 73); | |||
74 | } | |||
75 | ||||
76 | // This reference to the type is located entirely at the location of the | |||
77 | // final identifier in the qualified-id. | |||
78 | return CreateParsedType(Type, | |||
79 | Context.getTrivialTypeSourceInfo(Type, NameLoc)); | |||
80 | } | |||
81 | ||||
82 | ParsedType Sema::getConstructorName(IdentifierInfo &II, | |||
83 | SourceLocation NameLoc, | |||
84 | Scope *S, CXXScopeSpec &SS, | |||
85 | bool EnteringContext) { | |||
86 | CXXRecordDecl *CurClass = getCurrentClass(S, &SS); | |||
87 | assert(CurClass && &II == CurClass->getIdentifier() &&((CurClass && &II == CurClass->getIdentifier() && "not a constructor name") ? static_cast<void> (0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 88, __PRETTY_FUNCTION__)) | |||
88 | "not a constructor name")((CurClass && &II == CurClass->getIdentifier() && "not a constructor name") ? static_cast<void> (0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 88, __PRETTY_FUNCTION__)); | |||
89 | ||||
90 | // When naming a constructor as a member of a dependent context (eg, in a | |||
91 | // friend declaration or an inherited constructor declaration), form an | |||
92 | // unresolved "typename" type. | |||
93 | if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) { | |||
94 | QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II); | |||
95 | return ParsedType::make(T); | |||
96 | } | |||
97 | ||||
98 | if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass)) | |||
99 | return ParsedType(); | |||
100 | ||||
101 | // Find the injected-class-name declaration. Note that we make no attempt to | |||
102 | // diagnose cases where the injected-class-name is shadowed: the only | |||
103 | // declaration that can validly shadow the injected-class-name is a | |||
104 | // non-static data member, and if the class contains both a non-static data | |||
105 | // member and a constructor then it is ill-formed (we check that in | |||
106 | // CheckCompletedCXXClass). | |||
107 | CXXRecordDecl *InjectedClassName = nullptr; | |||
108 | for (NamedDecl *ND : CurClass->lookup(&II)) { | |||
109 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | |||
110 | if (RD && RD->isInjectedClassName()) { | |||
111 | InjectedClassName = RD; | |||
112 | break; | |||
113 | } | |||
114 | } | |||
115 | if (!InjectedClassName) { | |||
116 | if (!CurClass->isInvalidDecl()) { | |||
117 | // FIXME: RequireCompleteDeclContext doesn't check dependent contexts | |||
118 | // properly. Work around it here for now. | |||
119 | Diag(SS.getLastQualifierNameLoc(), | |||
120 | diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange(); | |||
121 | } | |||
122 | return ParsedType(); | |||
123 | } | |||
124 | ||||
125 | QualType T = Context.getTypeDeclType(InjectedClassName); | |||
126 | DiagnoseUseOfDecl(InjectedClassName, NameLoc); | |||
127 | MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false); | |||
128 | ||||
129 | return ParsedType::make(T); | |||
130 | } | |||
131 | ||||
132 | ParsedType Sema::getDestructorName(SourceLocation TildeLoc, | |||
133 | IdentifierInfo &II, | |||
134 | SourceLocation NameLoc, | |||
135 | Scope *S, CXXScopeSpec &SS, | |||
136 | ParsedType ObjectTypePtr, | |||
137 | bool EnteringContext) { | |||
138 | // Determine where to perform name lookup. | |||
139 | ||||
140 | // FIXME: This area of the standard is very messy, and the current | |||
141 | // wording is rather unclear about which scopes we search for the | |||
142 | // destructor name; see core issues 399 and 555. Issue 399 in | |||
143 | // particular shows where the current description of destructor name | |||
144 | // lookup is completely out of line with existing practice, e.g., | |||
145 | // this appears to be ill-formed: | |||
146 | // | |||
147 | // namespace N { | |||
148 | // template <typename T> struct S { | |||
149 | // ~S(); | |||
150 | // }; | |||
151 | // } | |||
152 | // | |||
153 | // void f(N::S<int>* s) { | |||
154 | // s->N::S<int>::~S(); | |||
155 | // } | |||
156 | // | |||
157 | // See also PR6358 and PR6359. | |||
158 | // For this reason, we're currently only doing the C++03 version of this | |||
159 | // code; the C++0x version has to wait until we get a proper spec. | |||
160 | QualType SearchType; | |||
161 | DeclContext *LookupCtx = nullptr; | |||
162 | bool isDependent = false; | |||
163 | bool LookInScope = false; | |||
164 | ||||
165 | if (SS.isInvalid()) | |||
166 | return nullptr; | |||
167 | ||||
168 | // If we have an object type, it's because we are in a | |||
169 | // pseudo-destructor-expression or a member access expression, and | |||
170 | // we know what type we're looking for. | |||
171 | if (ObjectTypePtr) | |||
172 | SearchType = GetTypeFromParser(ObjectTypePtr); | |||
173 | ||||
174 | if (SS.isSet()) { | |||
175 | NestedNameSpecifier *NNS = SS.getScopeRep(); | |||
176 | ||||
177 | bool AlreadySearched = false; | |||
178 | bool LookAtPrefix = true; | |||
179 | // C++11 [basic.lookup.qual]p6: | |||
180 | // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, | |||
181 | // the type-names are looked up as types in the scope designated by the | |||
182 | // nested-name-specifier. Similarly, in a qualified-id of the form: | |||
183 | // | |||
184 | // nested-name-specifier[opt] class-name :: ~ class-name | |||
185 | // | |||
186 | // the second class-name is looked up in the same scope as the first. | |||
187 | // | |||
188 | // Here, we determine whether the code below is permitted to look at the | |||
189 | // prefix of the nested-name-specifier. | |||
190 | DeclContext *DC = computeDeclContext(SS, EnteringContext); | |||
191 | if (DC && DC->isFileContext()) { | |||
192 | AlreadySearched = true; | |||
193 | LookupCtx = DC; | |||
194 | isDependent = false; | |||
195 | } else if (DC && isa<CXXRecordDecl>(DC)) { | |||
196 | LookAtPrefix = false; | |||
197 | LookInScope = true; | |||
198 | } | |||
199 | ||||
200 | // The second case from the C++03 rules quoted further above. | |||
201 | NestedNameSpecifier *Prefix = nullptr; | |||
202 | if (AlreadySearched) { | |||
203 | // Nothing left to do. | |||
204 | } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { | |||
205 | CXXScopeSpec PrefixSS; | |||
206 | PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); | |||
207 | LookupCtx = computeDeclContext(PrefixSS, EnteringContext); | |||
208 | isDependent = isDependentScopeSpecifier(PrefixSS); | |||
209 | } else if (ObjectTypePtr) { | |||
210 | LookupCtx = computeDeclContext(SearchType); | |||
211 | isDependent = SearchType->isDependentType(); | |||
212 | } else { | |||
213 | LookupCtx = computeDeclContext(SS, EnteringContext); | |||
214 | isDependent = LookupCtx && LookupCtx->isDependentContext(); | |||
215 | } | |||
216 | } else if (ObjectTypePtr) { | |||
217 | // C++ [basic.lookup.classref]p3: | |||
218 | // If the unqualified-id is ~type-name, the type-name is looked up | |||
219 | // in the context of the entire postfix-expression. If the type T | |||
220 | // of the object expression is of a class type C, the type-name is | |||
221 | // also looked up in the scope of class C. At least one of the | |||
222 | // lookups shall find a name that refers to (possibly | |||
223 | // cv-qualified) T. | |||
224 | LookupCtx = computeDeclContext(SearchType); | |||
225 | isDependent = SearchType->isDependentType(); | |||
226 | assert((isDependent || !SearchType->isIncompleteType()) &&(((isDependent || !SearchType->isIncompleteType()) && "Caller should have completed object type") ? static_cast< void> (0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 227, __PRETTY_FUNCTION__)) | |||
227 | "Caller should have completed object type")(((isDependent || !SearchType->isIncompleteType()) && "Caller should have completed object type") ? static_cast< void> (0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 227, __PRETTY_FUNCTION__)); | |||
228 | ||||
229 | LookInScope = true; | |||
230 | } else { | |||
231 | // Perform lookup into the current scope (only). | |||
232 | LookInScope = true; | |||
233 | } | |||
234 | ||||
235 | TypeDecl *NonMatchingTypeDecl = nullptr; | |||
236 | LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); | |||
237 | for (unsigned Step = 0; Step != 2; ++Step) { | |||
238 | // Look for the name first in the computed lookup context (if we | |||
239 | // have one) and, if that fails to find a match, in the scope (if | |||
240 | // we're allowed to look there). | |||
241 | Found.clear(); | |||
242 | if (Step == 0 && LookupCtx) { | |||
243 | if (RequireCompleteDeclContext(SS, LookupCtx)) | |||
244 | return nullptr; | |||
245 | LookupQualifiedName(Found, LookupCtx); | |||
246 | } else if (Step == 1 && LookInScope && S) { | |||
247 | LookupName(Found, S); | |||
248 | } else { | |||
249 | continue; | |||
250 | } | |||
251 | ||||
252 | // FIXME: Should we be suppressing ambiguities here? | |||
253 | if (Found.isAmbiguous()) | |||
254 | return nullptr; | |||
255 | ||||
256 | if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { | |||
257 | QualType T = Context.getTypeDeclType(Type); | |||
258 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | |||
259 | ||||
260 | if (SearchType.isNull() || SearchType->isDependentType() || | |||
261 | Context.hasSameUnqualifiedType(T, SearchType)) { | |||
262 | // We found our type! | |||
263 | ||||
264 | return CreateParsedType(T, | |||
265 | Context.getTrivialTypeSourceInfo(T, NameLoc)); | |||
266 | } | |||
267 | ||||
268 | if (!SearchType.isNull()) | |||
269 | NonMatchingTypeDecl = Type; | |||
270 | } | |||
271 | ||||
272 | // If the name that we found is a class template name, and it is | |||
273 | // the same name as the template name in the last part of the | |||
274 | // nested-name-specifier (if present) or the object type, then | |||
275 | // this is the destructor for that class. | |||
276 | // FIXME: This is a workaround until we get real drafting for core | |||
277 | // issue 399, for which there isn't even an obvious direction. | |||
278 | if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { | |||
279 | QualType MemberOfType; | |||
280 | if (SS.isSet()) { | |||
281 | if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { | |||
282 | // Figure out the type of the context, if it has one. | |||
283 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) | |||
284 | MemberOfType = Context.getTypeDeclType(Record); | |||
285 | } | |||
286 | } | |||
287 | if (MemberOfType.isNull()) | |||
288 | MemberOfType = SearchType; | |||
289 | ||||
290 | if (MemberOfType.isNull()) | |||
291 | continue; | |||
292 | ||||
293 | // We're referring into a class template specialization. If the | |||
294 | // class template we found is the same as the template being | |||
295 | // specialized, we found what we are looking for. | |||
296 | if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { | |||
297 | if (ClassTemplateSpecializationDecl *Spec | |||
298 | = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { | |||
299 | if (Spec->getSpecializedTemplate()->getCanonicalDecl() == | |||
300 | Template->getCanonicalDecl()) | |||
301 | return CreateParsedType( | |||
302 | MemberOfType, | |||
303 | Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc)); | |||
304 | } | |||
305 | ||||
306 | continue; | |||
307 | } | |||
308 | ||||
309 | // We're referring to an unresolved class template | |||
310 | // specialization. Determine whether we class template we found | |||
311 | // is the same as the template being specialized or, if we don't | |||
312 | // know which template is being specialized, that it at least | |||
313 | // has the same name. | |||
314 | if (const TemplateSpecializationType *SpecType | |||
315 | = MemberOfType->getAs<TemplateSpecializationType>()) { | |||
316 | TemplateName SpecName = SpecType->getTemplateName(); | |||
317 | ||||
318 | // The class template we found is the same template being | |||
319 | // specialized. | |||
320 | if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { | |||
321 | if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) | |||
322 | return CreateParsedType( | |||
323 | MemberOfType, | |||
324 | Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc)); | |||
325 | ||||
326 | continue; | |||
327 | } | |||
328 | ||||
329 | // The class template we found has the same name as the | |||
330 | // (dependent) template name being specialized. | |||
331 | if (DependentTemplateName *DepTemplate | |||
332 | = SpecName.getAsDependentTemplateName()) { | |||
333 | if (DepTemplate->isIdentifier() && | |||
334 | DepTemplate->getIdentifier() == Template->getIdentifier()) | |||
335 | return CreateParsedType( | |||
336 | MemberOfType, | |||
337 | Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc)); | |||
338 | ||||
339 | continue; | |||
340 | } | |||
341 | } | |||
342 | } | |||
343 | } | |||
344 | ||||
345 | if (isDependent) { | |||
346 | // We didn't find our type, but that's okay: it's dependent | |||
347 | // anyway. | |||
348 | ||||
349 | // FIXME: What if we have no nested-name-specifier? | |||
350 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), | |||
351 | SS.getWithLocInContext(Context), | |||
352 | II, NameLoc); | |||
353 | return ParsedType::make(T); | |||
354 | } | |||
355 | ||||
356 | if (NonMatchingTypeDecl) { | |||
357 | QualType T = Context.getTypeDeclType(NonMatchingTypeDecl); | |||
358 | Diag(NameLoc, diag::err_destructor_expr_type_mismatch) | |||
359 | << T << SearchType; | |||
360 | Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here) | |||
361 | << T; | |||
362 | } else if (ObjectTypePtr) | |||
363 | Diag(NameLoc, diag::err_ident_in_dtor_not_a_type) | |||
364 | << &II; | |||
365 | else { | |||
366 | SemaDiagnosticBuilder DtorDiag = Diag(NameLoc, | |||
367 | diag::err_destructor_class_name); | |||
368 | if (S) { | |||
369 | const DeclContext *Ctx = S->getEntity(); | |||
370 | if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx)) | |||
371 | DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc), | |||
372 | Class->getNameAsString()); | |||
373 | } | |||
374 | } | |||
375 | ||||
376 | return nullptr; | |||
377 | } | |||
378 | ||||
379 | ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, | |||
380 | ParsedType ObjectType) { | |||
381 | if (DS.getTypeSpecType() == DeclSpec::TST_error) | |||
382 | return nullptr; | |||
383 | ||||
384 | if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { | |||
385 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); | |||
386 | return nullptr; | |||
387 | } | |||
388 | ||||
389 | assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&((DS.getTypeSpecType() == DeclSpec::TST_decltype && "unexpected type in getDestructorType" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 390, __PRETTY_FUNCTION__)) | |||
390 | "unexpected type in getDestructorType")((DS.getTypeSpecType() == DeclSpec::TST_decltype && "unexpected type in getDestructorType" ) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 390, __PRETTY_FUNCTION__)); | |||
391 | QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); | |||
392 | ||||
393 | // If we know the type of the object, check that the correct destructor | |||
394 | // type was named now; we can give better diagnostics this way. | |||
395 | QualType SearchType = GetTypeFromParser(ObjectType); | |||
396 | if (!SearchType.isNull() && !SearchType->isDependentType() && | |||
397 | !Context.hasSameUnqualifiedType(T, SearchType)) { | |||
398 | Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) | |||
399 | << T << SearchType; | |||
400 | return nullptr; | |||
401 | } | |||
402 | ||||
403 | return ParsedType::make(T); | |||
404 | } | |||
405 | ||||
406 | bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, | |||
407 | const UnqualifiedId &Name) { | |||
408 | assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId)((Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) ? static_cast<void> (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 408, __PRETTY_FUNCTION__)); | |||
409 | ||||
410 | if (!SS.isValid()) | |||
411 | return false; | |||
412 | ||||
413 | switch (SS.getScopeRep()->getKind()) { | |||
414 | case NestedNameSpecifier::Identifier: | |||
415 | case NestedNameSpecifier::TypeSpec: | |||
416 | case NestedNameSpecifier::TypeSpecWithTemplate: | |||
417 | // Per C++11 [over.literal]p2, literal operators can only be declared at | |||
418 | // namespace scope. Therefore, this unqualified-id cannot name anything. | |||
419 | // Reject it early, because we have no AST representation for this in the | |||
420 | // case where the scope is dependent. | |||
421 | Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) | |||
422 | << SS.getScopeRep(); | |||
423 | return true; | |||
424 | ||||
425 | case NestedNameSpecifier::Global: | |||
426 | case NestedNameSpecifier::Super: | |||
427 | case NestedNameSpecifier::Namespace: | |||
428 | case NestedNameSpecifier::NamespaceAlias: | |||
429 | return false; | |||
430 | } | |||
431 | ||||
432 | llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 432); | |||
433 | } | |||
434 | ||||
435 | /// Build a C++ typeid expression with a type operand. | |||
436 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, | |||
437 | SourceLocation TypeidLoc, | |||
438 | TypeSourceInfo *Operand, | |||
439 | SourceLocation RParenLoc) { | |||
440 | // C++ [expr.typeid]p4: | |||
441 | // The top-level cv-qualifiers of the lvalue expression or the type-id | |||
442 | // that is the operand of typeid are always ignored. | |||
443 | // If the type of the type-id is a class type or a reference to a class | |||
444 | // type, the class shall be completely-defined. | |||
445 | Qualifiers Quals; | |||
446 | QualType T | |||
447 | = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), | |||
448 | Quals); | |||
449 | if (T->getAs<RecordType>() && | |||
450 | RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) | |||
451 | return ExprError(); | |||
452 | ||||
453 | if (T->isVariablyModifiedType()) | |||
454 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); | |||
455 | ||||
456 | if (CheckQualifiedFunctionForTypeId(T, TypeidLoc)) | |||
457 | return ExprError(); | |||
458 | ||||
459 | return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, | |||
460 | SourceRange(TypeidLoc, RParenLoc)); | |||
461 | } | |||
462 | ||||
463 | /// Build a C++ typeid expression with an expression operand. | |||
464 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, | |||
465 | SourceLocation TypeidLoc, | |||
466 | Expr *E, | |||
467 | SourceLocation RParenLoc) { | |||
468 | bool WasEvaluated = false; | |||
469 | if (E && !E->isTypeDependent()) { | |||
470 | if (E->getType()->isPlaceholderType()) { | |||
471 | ExprResult result = CheckPlaceholderExpr(E); | |||
472 | if (result.isInvalid()) return ExprError(); | |||
473 | E = result.get(); | |||
474 | } | |||
475 | ||||
476 | QualType T = E->getType(); | |||
477 | if (const RecordType *RecordT = T->getAs<RecordType>()) { | |||
478 | CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); | |||
479 | // C++ [expr.typeid]p3: | |||
480 | // [...] If the type of the expression is a class type, the class | |||
481 | // shall be completely-defined. | |||
482 | if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) | |||
483 | return ExprError(); | |||
484 | ||||
485 | // C++ [expr.typeid]p3: | |||
486 | // When typeid is applied to an expression other than an glvalue of a | |||
487 | // polymorphic class type [...] [the] expression is an unevaluated | |||
488 | // operand. [...] | |||
489 | if (RecordD->isPolymorphic() && E->isGLValue()) { | |||
490 | // The subexpression is potentially evaluated; switch the context | |||
491 | // and recheck the subexpression. | |||
492 | ExprResult Result = TransformToPotentiallyEvaluated(E); | |||
493 | if (Result.isInvalid()) return ExprError(); | |||
494 | E = Result.get(); | |||
495 | ||||
496 | // We require a vtable to query the type at run time. | |||
497 | MarkVTableUsed(TypeidLoc, RecordD); | |||
498 | WasEvaluated = true; | |||
499 | } | |||
500 | } | |||
501 | ||||
502 | ExprResult Result = CheckUnevaluatedOperand(E); | |||
503 | if (Result.isInvalid()) | |||
504 | return ExprError(); | |||
505 | E = Result.get(); | |||
506 | ||||
507 | // C++ [expr.typeid]p4: | |||
508 | // [...] If the type of the type-id is a reference to a possibly | |||
509 | // cv-qualified type, the result of the typeid expression refers to a | |||
510 | // std::type_info object representing the cv-unqualified referenced | |||
511 | // type. | |||
512 | Qualifiers Quals; | |||
513 | QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); | |||
514 | if (!Context.hasSameType(T, UnqualT)) { | |||
515 | T = UnqualT; | |||
516 | E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get(); | |||
517 | } | |||
518 | } | |||
519 | ||||
520 | if (E->getType()->isVariablyModifiedType()) | |||
521 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) | |||
522 | << E->getType()); | |||
523 | else if (!inTemplateInstantiation() && | |||
524 | E->HasSideEffects(Context, WasEvaluated)) { | |||
525 | // The expression operand for typeid is in an unevaluated expression | |||
526 | // context, so side effects could result in unintended consequences. | |||
527 | Diag(E->getExprLoc(), WasEvaluated | |||
528 | ? diag::warn_side_effects_typeid | |||
529 | : diag::warn_side_effects_unevaluated_context); | |||
530 | } | |||
531 | ||||
532 | return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, | |||
533 | SourceRange(TypeidLoc, RParenLoc)); | |||
534 | } | |||
535 | ||||
536 | /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); | |||
537 | ExprResult | |||
538 | Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, | |||
539 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { | |||
540 | // typeid is not supported in OpenCL. | |||
541 | if (getLangOpts().OpenCLCPlusPlus) { | |||
542 | return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) | |||
543 | << "typeid"); | |||
544 | } | |||
545 | ||||
546 | // Find the std::type_info type. | |||
547 | if (!getStdNamespace()) | |||
548 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); | |||
549 | ||||
550 | if (!CXXTypeInfoDecl) { | |||
551 | IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); | |||
552 | LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); | |||
553 | LookupQualifiedName(R, getStdNamespace()); | |||
554 | CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); | |||
555 | // Microsoft's typeinfo doesn't have type_info in std but in the global | |||
556 | // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. | |||
557 | if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { | |||
558 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); | |||
559 | CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); | |||
560 | } | |||
561 | if (!CXXTypeInfoDecl) | |||
562 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); | |||
563 | } | |||
564 | ||||
565 | if (!getLangOpts().RTTI) { | |||
566 | return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); | |||
567 | } | |||
568 | ||||
569 | QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); | |||
570 | ||||
571 | if (isType) { | |||
572 | // The operand is a type; handle it as such. | |||
573 | TypeSourceInfo *TInfo = nullptr; | |||
574 | QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), | |||
575 | &TInfo); | |||
576 | if (T.isNull()) | |||
577 | return ExprError(); | |||
578 | ||||
579 | if (!TInfo) | |||
580 | TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); | |||
581 | ||||
582 | return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); | |||
583 | } | |||
584 | ||||
585 | // The operand is an expression. | |||
586 | return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); | |||
587 | } | |||
588 | ||||
589 | /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to | |||
590 | /// a single GUID. | |||
591 | static void | |||
592 | getUuidAttrOfType(Sema &SemaRef, QualType QT, | |||
593 | llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { | |||
594 | // Optionally remove one level of pointer, reference or array indirection. | |||
595 | const Type *Ty = QT.getTypePtr(); | |||
596 | if (QT->isPointerType() || QT->isReferenceType()) | |||
597 | Ty = QT->getPointeeType().getTypePtr(); | |||
598 | else if (QT->isArrayType()) | |||
599 | Ty = Ty->getBaseElementTypeUnsafe(); | |||
600 | ||||
601 | const auto *TD = Ty->getAsTagDecl(); | |||
602 | if (!TD) | |||
603 | return; | |||
604 | ||||
605 | if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { | |||
606 | UuidAttrs.insert(Uuid); | |||
607 | return; | |||
608 | } | |||
609 | ||||
610 | // __uuidof can grab UUIDs from template arguments. | |||
611 | if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) { | |||
612 | const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); | |||
613 | for (const TemplateArgument &TA : TAL.asArray()) { | |||
614 | const UuidAttr *UuidForTA = nullptr; | |||
615 | if (TA.getKind() == TemplateArgument::Type) | |||
616 | getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); | |||
617 | else if (TA.getKind() == TemplateArgument::Declaration) | |||
618 | getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); | |||
619 | ||||
620 | if (UuidForTA) | |||
621 | UuidAttrs.insert(UuidForTA); | |||
622 | } | |||
623 | } | |||
624 | } | |||
625 | ||||
626 | /// Build a Microsoft __uuidof expression with a type operand. | |||
627 | ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, | |||
628 | SourceLocation TypeidLoc, | |||
629 | TypeSourceInfo *Operand, | |||
630 | SourceLocation RParenLoc) { | |||
631 | StringRef UuidStr; | |||
632 | if (!Operand->getType()->isDependentType()) { | |||
633 | llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; | |||
634 | getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); | |||
635 | if (UuidAttrs.empty()) | |||
636 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); | |||
637 | if (UuidAttrs.size() > 1) | |||
638 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); | |||
639 | UuidStr = UuidAttrs.back()->getGuid(); | |||
640 | } | |||
641 | ||||
642 | return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr, | |||
643 | SourceRange(TypeidLoc, RParenLoc)); | |||
644 | } | |||
645 | ||||
646 | /// Build a Microsoft __uuidof expression with an expression operand. | |||
647 | ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, | |||
648 | SourceLocation TypeidLoc, | |||
649 | Expr *E, | |||
650 | SourceLocation RParenLoc) { | |||
651 | StringRef UuidStr; | |||
652 | if (!E->getType()->isDependentType()) { | |||
653 | if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { | |||
654 | UuidStr = "00000000-0000-0000-0000-000000000000"; | |||
655 | } else { | |||
656 | llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; | |||
657 | getUuidAttrOfType(*this, E->getType(), UuidAttrs); | |||
658 | if (UuidAttrs.empty()) | |||
659 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); | |||
660 | if (UuidAttrs.size() > 1) | |||
661 | return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); | |||
662 | UuidStr = UuidAttrs.back()->getGuid(); | |||
663 | } | |||
664 | } | |||
665 | ||||
666 | return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr, | |||
667 | SourceRange(TypeidLoc, RParenLoc)); | |||
668 | } | |||
669 | ||||
670 | /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); | |||
671 | ExprResult | |||
672 | Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, | |||
673 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { | |||
674 | // If MSVCGuidDecl has not been cached, do the lookup. | |||
675 | if (!MSVCGuidDecl) { | |||
676 | IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID"); | |||
677 | LookupResult R(*this, GuidII, SourceLocation(), LookupTagName); | |||
678 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); | |||
679 | MSVCGuidDecl = R.getAsSingle<RecordDecl>(); | |||
680 | if (!MSVCGuidDecl) | |||
681 | return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof)); | |||
682 | } | |||
683 | ||||
684 | QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl); | |||
685 | ||||
686 | if (isType) { | |||
687 | // The operand is a type; handle it as such. | |||
688 | TypeSourceInfo *TInfo = nullptr; | |||
689 | QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), | |||
690 | &TInfo); | |||
691 | if (T.isNull()) | |||
692 | return ExprError(); | |||
693 | ||||
694 | if (!TInfo) | |||
695 | TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); | |||
696 | ||||
697 | return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); | |||
698 | } | |||
699 | ||||
700 | // The operand is an expression. | |||
701 | return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); | |||
702 | } | |||
703 | ||||
704 | /// ActOnCXXBoolLiteral - Parse {true,false} literals. | |||
705 | ExprResult | |||
706 | Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { | |||
707 | assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!" ) ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 708, __PRETTY_FUNCTION__)) | |||
708 | "Unknown C++ Boolean value!")(((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!" ) ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 708, __PRETTY_FUNCTION__)); | |||
709 | return new (Context) | |||
710 | CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); | |||
711 | } | |||
712 | ||||
713 | /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. | |||
714 | ExprResult | |||
715 | Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { | |||
716 | return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); | |||
717 | } | |||
718 | ||||
719 | /// ActOnCXXThrow - Parse throw expressions. | |||
720 | ExprResult | |||
721 | Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { | |||
722 | bool IsThrownVarInScope = false; | |||
723 | if (Ex) { | |||
724 | // C++0x [class.copymove]p31: | |||
725 | // When certain criteria are met, an implementation is allowed to omit the | |||
726 | // copy/move construction of a class object [...] | |||
727 | // | |||
728 | // - in a throw-expression, when the operand is the name of a | |||
729 | // non-volatile automatic object (other than a function or catch- | |||
730 | // clause parameter) whose scope does not extend beyond the end of the | |||
731 | // innermost enclosing try-block (if there is one), the copy/move | |||
732 | // operation from the operand to the exception object (15.1) can be | |||
733 | // omitted by constructing the automatic object directly into the | |||
734 | // exception object | |||
735 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) | |||
736 | if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { | |||
737 | if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { | |||
738 | for( ; S; S = S->getParent()) { | |||
739 | if (S->isDeclScope(Var)) { | |||
740 | IsThrownVarInScope = true; | |||
741 | break; | |||
742 | } | |||
743 | ||||
744 | if (S->getFlags() & | |||
745 | (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | | |||
746 | Scope::FunctionPrototypeScope | Scope::ObjCMethodScope | | |||
747 | Scope::TryScope)) | |||
748 | break; | |||
749 | } | |||
750 | } | |||
751 | } | |||
752 | } | |||
753 | ||||
754 | return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); | |||
755 | } | |||
756 | ||||
757 | ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, | |||
758 | bool IsThrownVarInScope) { | |||
759 | // Don't report an error if 'throw' is used in system headers. | |||
760 | if (!getLangOpts().CXXExceptions && | |||
761 | !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) { | |||
762 | // Delay error emission for the OpenMP device code. | |||
763 | targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw"; | |||
764 | } | |||
765 | ||||
766 | // Exceptions aren't allowed in CUDA device code. | |||
767 | if (getLangOpts().CUDA) | |||
768 | CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) | |||
769 | << "throw" << CurrentCUDATarget(); | |||
770 | ||||
771 | if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) | |||
772 | Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; | |||
773 | ||||
774 | if (Ex && !Ex->isTypeDependent()) { | |||
775 | QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType()); | |||
776 | if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex)) | |||
777 | return ExprError(); | |||
778 | ||||
779 | // Initialize the exception result. This implicitly weeds out | |||
780 | // abstract types or types with inaccessible copy constructors. | |||
781 | ||||
782 | // C++0x [class.copymove]p31: | |||
783 | // When certain criteria are met, an implementation is allowed to omit the | |||
784 | // copy/move construction of a class object [...] | |||
785 | // | |||
786 | // - in a throw-expression, when the operand is the name of a | |||
787 | // non-volatile automatic object (other than a function or | |||
788 | // catch-clause | |||
789 | // parameter) whose scope does not extend beyond the end of the | |||
790 | // innermost enclosing try-block (if there is one), the copy/move | |||
791 | // operation from the operand to the exception object (15.1) can be | |||
792 | // omitted by constructing the automatic object directly into the | |||
793 | // exception object | |||
794 | const VarDecl *NRVOVariable = nullptr; | |||
795 | if (IsThrownVarInScope) | |||
796 | NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict); | |||
797 | ||||
798 | InitializedEntity Entity = InitializedEntity::InitializeException( | |||
799 | OpLoc, ExceptionObjectTy, | |||
800 | /*NRVO=*/NRVOVariable != nullptr); | |||
801 | ExprResult Res = PerformMoveOrCopyInitialization( | |||
802 | Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope); | |||
803 | if (Res.isInvalid()) | |||
804 | return ExprError(); | |||
805 | Ex = Res.get(); | |||
806 | } | |||
807 | ||||
808 | return new (Context) | |||
809 | CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); | |||
810 | } | |||
811 | ||||
812 | static void | |||
813 | collectPublicBases(CXXRecordDecl *RD, | |||
814 | llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, | |||
815 | llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, | |||
816 | llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, | |||
817 | bool ParentIsPublic) { | |||
818 | for (const CXXBaseSpecifier &BS : RD->bases()) { | |||
819 | CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); | |||
820 | bool NewSubobject; | |||
821 | // Virtual bases constitute the same subobject. Non-virtual bases are | |||
822 | // always distinct subobjects. | |||
823 | if (BS.isVirtual()) | |||
824 | NewSubobject = VBases.insert(BaseDecl).second; | |||
825 | else | |||
826 | NewSubobject = true; | |||
827 | ||||
828 | if (NewSubobject) | |||
829 | ++SubobjectsSeen[BaseDecl]; | |||
830 | ||||
831 | // Only add subobjects which have public access throughout the entire chain. | |||
832 | bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; | |||
833 | if (PublicPath) | |||
834 | PublicSubobjectsSeen.insert(BaseDecl); | |||
835 | ||||
836 | // Recurse on to each base subobject. | |||
837 | collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, | |||
838 | PublicPath); | |||
839 | } | |||
840 | } | |||
841 | ||||
842 | static void getUnambiguousPublicSubobjects( | |||
843 | CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { | |||
844 | llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; | |||
845 | llvm::SmallSet<CXXRecordDecl *, 2> VBases; | |||
846 | llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; | |||
847 | SubobjectsSeen[RD] = 1; | |||
848 | PublicSubobjectsSeen.insert(RD); | |||
849 | collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, | |||
850 | /*ParentIsPublic=*/true); | |||
851 | ||||
852 | for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { | |||
853 | // Skip ambiguous objects. | |||
854 | if (SubobjectsSeen[PublicSubobject] > 1) | |||
855 | continue; | |||
856 | ||||
857 | Objects.push_back(PublicSubobject); | |||
858 | } | |||
859 | } | |||
860 | ||||
861 | /// CheckCXXThrowOperand - Validate the operand of a throw. | |||
862 | bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, | |||
863 | QualType ExceptionObjectTy, Expr *E) { | |||
864 | // If the type of the exception would be an incomplete type or a pointer | |||
865 | // to an incomplete type other than (cv) void the program is ill-formed. | |||
866 | QualType Ty = ExceptionObjectTy; | |||
867 | bool isPointer = false; | |||
868 | if (const PointerType* Ptr = Ty->getAs<PointerType>()) { | |||
869 | Ty = Ptr->getPointeeType(); | |||
870 | isPointer = true; | |||
871 | } | |||
872 | if (!isPointer || !Ty->isVoidType()) { | |||
873 | if (RequireCompleteType(ThrowLoc, Ty, | |||
874 | isPointer ? diag::err_throw_incomplete_ptr | |||
875 | : diag::err_throw_incomplete, | |||
876 | E->getSourceRange())) | |||
877 | return true; | |||
878 | ||||
879 | if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, | |||
880 | diag::err_throw_abstract_type, E)) | |||
881 | return true; | |||
882 | } | |||
883 | ||||
884 | // If the exception has class type, we need additional handling. | |||
885 | CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); | |||
886 | if (!RD) | |||
887 | return false; | |||
888 | ||||
889 | // If we are throwing a polymorphic class type or pointer thereof, | |||
890 | // exception handling will make use of the vtable. | |||
891 | MarkVTableUsed(ThrowLoc, RD); | |||
892 | ||||
893 | // If a pointer is thrown, the referenced object will not be destroyed. | |||
894 | if (isPointer) | |||
895 | return false; | |||
896 | ||||
897 | // If the class has a destructor, we must be able to call it. | |||
898 | if (!RD->hasIrrelevantDestructor()) { | |||
899 | if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { | |||
900 | MarkFunctionReferenced(E->getExprLoc(), Destructor); | |||
901 | CheckDestructorAccess(E->getExprLoc(), Destructor, | |||
902 | PDiag(diag::err_access_dtor_exception) << Ty); | |||
903 | if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) | |||
904 | return true; | |||
905 | } | |||
906 | } | |||
907 | ||||
908 | // The MSVC ABI creates a list of all types which can catch the exception | |||
909 | // object. This list also references the appropriate copy constructor to call | |||
910 | // if the object is caught by value and has a non-trivial copy constructor. | |||
911 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
912 | // We are only interested in the public, unambiguous bases contained within | |||
913 | // the exception object. Bases which are ambiguous or otherwise | |||
914 | // inaccessible are not catchable types. | |||
915 | llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; | |||
916 | getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); | |||
917 | ||||
918 | for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { | |||
919 | // Attempt to lookup the copy constructor. Various pieces of machinery | |||
920 | // will spring into action, like template instantiation, which means this | |||
921 | // cannot be a simple walk of the class's decls. Instead, we must perform | |||
922 | // lookup and overload resolution. | |||
923 | CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); | |||
924 | if (!CD) | |||
925 | continue; | |||
926 | ||||
927 | // Mark the constructor referenced as it is used by this throw expression. | |||
928 | MarkFunctionReferenced(E->getExprLoc(), CD); | |||
929 | ||||
930 | // Skip this copy constructor if it is trivial, we don't need to record it | |||
931 | // in the catchable type data. | |||
932 | if (CD->isTrivial()) | |||
933 | continue; | |||
934 | ||||
935 | // The copy constructor is non-trivial, create a mapping from this class | |||
936 | // type to this constructor. | |||
937 | // N.B. The selection of copy constructor is not sensitive to this | |||
938 | // particular throw-site. Lookup will be performed at the catch-site to | |||
939 | // ensure that the copy constructor is, in fact, accessible (via | |||
940 | // friendship or any other means). | |||
941 | Context.addCopyConstructorForExceptionObject(Subobject, CD); | |||
942 | ||||
943 | // We don't keep the instantiated default argument expressions around so | |||
944 | // we must rebuild them here. | |||
945 | for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { | |||
946 | if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I))) | |||
947 | return true; | |||
948 | } | |||
949 | } | |||
950 | } | |||
951 | ||||
952 | // Under the Itanium C++ ABI, memory for the exception object is allocated by | |||
953 | // the runtime with no ability for the compiler to request additional | |||
954 | // alignment. Warn if the exception type requires alignment beyond the minimum | |||
955 | // guaranteed by the target C++ runtime. | |||
956 | if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { | |||
957 | CharUnits TypeAlign = Context.getTypeAlignInChars(Ty); | |||
958 | CharUnits ExnObjAlign = Context.getExnObjectAlignment(); | |||
959 | if (ExnObjAlign < TypeAlign) { | |||
960 | Diag(ThrowLoc, diag::warn_throw_underaligned_obj); | |||
961 | Diag(ThrowLoc, diag::note_throw_underaligned_obj) | |||
962 | << Ty << (unsigned)TypeAlign.getQuantity() | |||
963 | << (unsigned)ExnObjAlign.getQuantity(); | |||
964 | } | |||
965 | } | |||
966 | ||||
967 | return false; | |||
968 | } | |||
969 | ||||
970 | static QualType adjustCVQualifiersForCXXThisWithinLambda( | |||
971 | ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, | |||
972 | DeclContext *CurSemaContext, ASTContext &ASTCtx) { | |||
973 | ||||
974 | QualType ClassType = ThisTy->getPointeeType(); | |||
975 | LambdaScopeInfo *CurLSI = nullptr; | |||
976 | DeclContext *CurDC = CurSemaContext; | |||
977 | ||||
978 | // Iterate through the stack of lambdas starting from the innermost lambda to | |||
979 | // the outermost lambda, checking if '*this' is ever captured by copy - since | |||
980 | // that could change the cv-qualifiers of the '*this' object. | |||
981 | // The object referred to by '*this' starts out with the cv-qualifiers of its | |||
982 | // member function. We then start with the innermost lambda and iterate | |||
983 | // outward checking to see if any lambda performs a by-copy capture of '*this' | |||
984 | // - and if so, any nested lambda must respect the 'constness' of that | |||
985 | // capturing lamdbda's call operator. | |||
986 | // | |||
987 | ||||
988 | // Since the FunctionScopeInfo stack is representative of the lexical | |||
989 | // nesting of the lambda expressions during initial parsing (and is the best | |||
990 | // place for querying information about captures about lambdas that are | |||
991 | // partially processed) and perhaps during instantiation of function templates | |||
992 | // that contain lambda expressions that need to be transformed BUT not | |||
993 | // necessarily during instantiation of a nested generic lambda's function call | |||
994 | // operator (which might even be instantiated at the end of the TU) - at which | |||
995 | // time the DeclContext tree is mature enough to query capture information | |||
996 | // reliably - we use a two pronged approach to walk through all the lexically | |||
997 | // enclosing lambda expressions: | |||
998 | // | |||
999 | // 1) Climb down the FunctionScopeInfo stack as long as each item represents | |||
1000 | // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically | |||
1001 | // enclosed by the call-operator of the LSI below it on the stack (while | |||
1002 | // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on | |||
1003 | // the stack represents the innermost lambda. | |||
1004 | // | |||
1005 | // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext | |||
1006 | // represents a lambda's call operator. If it does, we must be instantiating | |||
1007 | // a generic lambda's call operator (represented by the Current LSI, and | |||
1008 | // should be the only scenario where an inconsistency between the LSI and the | |||
1009 | // DeclContext should occur), so climb out the DeclContexts if they | |||
1010 | // represent lambdas, while querying the corresponding closure types | |||
1011 | // regarding capture information. | |||
1012 | ||||
1013 | // 1) Climb down the function scope info stack. | |||
1014 | for (int I = FunctionScopes.size(); | |||
1015 | I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) && | |||
1016 | (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == | |||
1017 | cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator); | |||
1018 | CurDC = getLambdaAwareParentOfDeclContext(CurDC)) { | |||
1019 | CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]); | |||
1020 | ||||
1021 | if (!CurLSI->isCXXThisCaptured()) | |||
1022 | continue; | |||
1023 | ||||
1024 | auto C = CurLSI->getCXXThisCapture(); | |||
1025 | ||||
1026 | if (C.isCopyCapture()) { | |||
1027 | ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); | |||
1028 | if (CurLSI->CallOperator->isConst()) | |||
1029 | ClassType.addConst(); | |||
1030 | return ASTCtx.getPointerType(ClassType); | |||
1031 | } | |||
1032 | } | |||
1033 | ||||
1034 | // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can | |||
1035 | // happen during instantiation of its nested generic lambda call operator) | |||
1036 | if (isLambdaCallOperator(CurDC)) { | |||
1037 | assert(CurLSI && "While computing 'this' capture-type for a generic "((CurLSI && "While computing 'this' capture-type for a generic " "lambda, we must have a corresponding LambdaScopeInfo") ? static_cast <void> (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1038, __PRETTY_FUNCTION__)) | |||
1038 | "lambda, we must have a corresponding LambdaScopeInfo")((CurLSI && "While computing 'this' capture-type for a generic " "lambda, we must have a corresponding LambdaScopeInfo") ? static_cast <void> (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1038, __PRETTY_FUNCTION__)); | |||
1039 | assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator ) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? static_cast<void> (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1043, __PRETTY_FUNCTION__)) | |||
1040 | "While computing 'this' capture-type for a generic lambda, when we "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator ) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? static_cast<void> (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1043, __PRETTY_FUNCTION__)) | |||
1041 | "run out of enclosing LSI's, yet the enclosing DC is a "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator ) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? static_cast<void> (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1043, __PRETTY_FUNCTION__)) | |||
1042 | "lambda-call-operator we must be (i.e. Current LSI) in a generic "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator ) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? static_cast<void> (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1043, __PRETTY_FUNCTION__)) | |||
1043 | "lambda call oeprator")((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator ) && "While computing 'this' capture-type for a generic lambda, when we " "run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic " "lambda call oeprator") ? static_cast<void> (0) : __assert_fail ("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1043, __PRETTY_FUNCTION__)); | |||
1044 | assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))((CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator )) ? static_cast<void> (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1044, __PRETTY_FUNCTION__)); | |||
1045 | ||||
1046 | auto IsThisCaptured = | |||
1047 | [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { | |||
1048 | IsConst = false; | |||
1049 | IsByCopy = false; | |||
1050 | for (auto &&C : Closure->captures()) { | |||
1051 | if (C.capturesThis()) { | |||
1052 | if (C.getCaptureKind() == LCK_StarThis) | |||
1053 | IsByCopy = true; | |||
1054 | if (Closure->getLambdaCallOperator()->isConst()) | |||
1055 | IsConst = true; | |||
1056 | return true; | |||
1057 | } | |||
1058 | } | |||
1059 | return false; | |||
1060 | }; | |||
1061 | ||||
1062 | bool IsByCopyCapture = false; | |||
1063 | bool IsConstCapture = false; | |||
1064 | CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent()); | |||
1065 | while (Closure && | |||
1066 | IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { | |||
1067 | if (IsByCopyCapture) { | |||
1068 | ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); | |||
1069 | if (IsConstCapture) | |||
1070 | ClassType.addConst(); | |||
1071 | return ASTCtx.getPointerType(ClassType); | |||
1072 | } | |||
1073 | Closure = isLambdaCallOperator(Closure->getParent()) | |||
1074 | ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) | |||
1075 | : nullptr; | |||
1076 | } | |||
1077 | } | |||
1078 | return ASTCtx.getPointerType(ClassType); | |||
1079 | } | |||
1080 | ||||
1081 | QualType Sema::getCurrentThisType() { | |||
1082 | DeclContext *DC = getFunctionLevelDeclContext(); | |||
1083 | QualType ThisTy = CXXThisTypeOverride; | |||
1084 | ||||
1085 | if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { | |||
1086 | if (method && method->isInstance()) | |||
1087 | ThisTy = method->getThisType(); | |||
1088 | } | |||
1089 | ||||
1090 | if (ThisTy.isNull() && isLambdaCallOperator(CurContext) && | |||
1091 | inTemplateInstantiation()) { | |||
1092 | ||||
1093 | assert(isa<CXXRecordDecl>(DC) &&((isa<CXXRecordDecl>(DC) && "Trying to get 'this' type from static method?" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1094, __PRETTY_FUNCTION__)) | |||
1094 | "Trying to get 'this' type from static method?")((isa<CXXRecordDecl>(DC) && "Trying to get 'this' type from static method?" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1094, __PRETTY_FUNCTION__)); | |||
1095 | ||||
1096 | // This is a lambda call operator that is being instantiated as a default | |||
1097 | // initializer. DC must point to the enclosing class type, so we can recover | |||
1098 | // the 'this' type from it. | |||
1099 | ||||
1100 | QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC)); | |||
1101 | // There are no cv-qualifiers for 'this' within default initializers, | |||
1102 | // per [expr.prim.general]p4. | |||
1103 | ThisTy = Context.getPointerType(ClassTy); | |||
1104 | } | |||
1105 | ||||
1106 | // If we are within a lambda's call operator, the cv-qualifiers of 'this' | |||
1107 | // might need to be adjusted if the lambda or any of its enclosing lambda's | |||
1108 | // captures '*this' by copy. | |||
1109 | if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) | |||
1110 | return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, | |||
1111 | CurContext, Context); | |||
1112 | return ThisTy; | |||
1113 | } | |||
1114 | ||||
1115 | Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, | |||
1116 | Decl *ContextDecl, | |||
1117 | Qualifiers CXXThisTypeQuals, | |||
1118 | bool Enabled) | |||
1119 | : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) | |||
1120 | { | |||
1121 | if (!Enabled || !ContextDecl) | |||
1122 | return; | |||
1123 | ||||
1124 | CXXRecordDecl *Record = nullptr; | |||
1125 | if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) | |||
1126 | Record = Template->getTemplatedDecl(); | |||
1127 | else | |||
1128 | Record = cast<CXXRecordDecl>(ContextDecl); | |||
1129 | ||||
1130 | QualType T = S.Context.getRecordType(Record); | |||
1131 | T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals); | |||
1132 | ||||
1133 | S.CXXThisTypeOverride = S.Context.getPointerType(T); | |||
1134 | ||||
1135 | this->Enabled = true; | |||
1136 | } | |||
1137 | ||||
1138 | ||||
1139 | Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { | |||
1140 | if (Enabled) { | |||
1141 | S.CXXThisTypeOverride = OldCXXThisTypeOverride; | |||
1142 | } | |||
1143 | } | |||
1144 | ||||
1145 | bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, | |||
1146 | bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, | |||
1147 | const bool ByCopy) { | |||
1148 | // We don't need to capture this in an unevaluated context. | |||
1149 | if (isUnevaluatedContext() && !Explicit) | |||
1150 | return true; | |||
1151 | ||||
1152 | assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(((!ByCopy || Explicit) && "cannot implicitly capture *this by value" ) ? static_cast<void> (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1152, __PRETTY_FUNCTION__)); | |||
1153 | ||||
1154 | const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt | |||
1155 | ? *FunctionScopeIndexToStopAt | |||
1156 | : FunctionScopes.size() - 1; | |||
1157 | ||||
1158 | // Check that we can capture the *enclosing object* (referred to by '*this') | |||
1159 | // by the capturing-entity/closure (lambda/block/etc) at | |||
1160 | // MaxFunctionScopesIndex-deep on the FunctionScopes stack. | |||
1161 | ||||
1162 | // Note: The *enclosing object* can only be captured by-value by a | |||
1163 | // closure that is a lambda, using the explicit notation: | |||
1164 | // [*this] { ... }. | |||
1165 | // Every other capture of the *enclosing object* results in its by-reference | |||
1166 | // capture. | |||
1167 | ||||
1168 | // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes | |||
1169 | // stack), we can capture the *enclosing object* only if: | |||
1170 | // - 'L' has an explicit byref or byval capture of the *enclosing object* | |||
1171 | // - or, 'L' has an implicit capture. | |||
1172 | // AND | |||
1173 | // -- there is no enclosing closure | |||
1174 | // -- or, there is some enclosing closure 'E' that has already captured the | |||
1175 | // *enclosing object*, and every intervening closure (if any) between 'E' | |||
1176 | // and 'L' can implicitly capture the *enclosing object*. | |||
1177 | // -- or, every enclosing closure can implicitly capture the | |||
1178 | // *enclosing object* | |||
1179 | ||||
1180 | ||||
1181 | unsigned NumCapturingClosures = 0; | |||
1182 | for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { | |||
1183 | if (CapturingScopeInfo *CSI = | |||
1184 | dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { | |||
1185 | if (CSI->CXXThisCaptureIndex != 0) { | |||
1186 | // 'this' is already being captured; there isn't anything more to do. | |||
1187 | CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); | |||
1188 | break; | |||
1189 | } | |||
1190 | LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); | |||
1191 | if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { | |||
1192 | // This context can't implicitly capture 'this'; fail out. | |||
1193 | if (BuildAndDiagnose) | |||
1194 | Diag(Loc, diag::err_this_capture) | |||
1195 | << (Explicit && idx == MaxFunctionScopesIndex); | |||
1196 | return true; | |||
1197 | } | |||
1198 | if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || | |||
1199 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || | |||
1200 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || | |||
1201 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || | |||
1202 | (Explicit && idx == MaxFunctionScopesIndex)) { | |||
1203 | // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first | |||
1204 | // iteration through can be an explicit capture, all enclosing closures, | |||
1205 | // if any, must perform implicit captures. | |||
1206 | ||||
1207 | // This closure can capture 'this'; continue looking upwards. | |||
1208 | NumCapturingClosures++; | |||
1209 | continue; | |||
1210 | } | |||
1211 | // This context can't implicitly capture 'this'; fail out. | |||
1212 | if (BuildAndDiagnose) | |||
1213 | Diag(Loc, diag::err_this_capture) | |||
1214 | << (Explicit && idx == MaxFunctionScopesIndex); | |||
1215 | return true; | |||
1216 | } | |||
1217 | break; | |||
1218 | } | |||
1219 | if (!BuildAndDiagnose) return false; | |||
1220 | ||||
1221 | // If we got here, then the closure at MaxFunctionScopesIndex on the | |||
1222 | // FunctionScopes stack, can capture the *enclosing object*, so capture it | |||
1223 | // (including implicit by-reference captures in any enclosing closures). | |||
1224 | ||||
1225 | // In the loop below, respect the ByCopy flag only for the closure requesting | |||
1226 | // the capture (i.e. first iteration through the loop below). Ignore it for | |||
1227 | // all enclosing closure's up to NumCapturingClosures (since they must be | |||
1228 | // implicitly capturing the *enclosing object* by reference (see loop | |||
1229 | // above)). | |||
1230 | assert((!ByCopy ||(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[ MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? static_cast<void> (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1233, __PRETTY_FUNCTION__)) | |||
1231 | dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[ MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? static_cast<void> (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1233, __PRETTY_FUNCTION__)) | |||
1232 | "Only a lambda can capture the enclosing object (referred to by "(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[ MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? static_cast<void> (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1233, __PRETTY_FUNCTION__)) | |||
1233 | "*this) by copy")(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[ MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by " "*this) by copy") ? static_cast<void> (0) : __assert_fail ("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1233, __PRETTY_FUNCTION__)); | |||
1234 | QualType ThisTy = getCurrentThisType(); | |||
1235 | for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; | |||
1236 | --idx, --NumCapturingClosures) { | |||
1237 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); | |||
1238 | ||||
1239 | // The type of the corresponding data member (not a 'this' pointer if 'by | |||
1240 | // copy'). | |||
1241 | QualType CaptureType = ThisTy; | |||
1242 | if (ByCopy) { | |||
1243 | // If we are capturing the object referred to by '*this' by copy, ignore | |||
1244 | // any cv qualifiers inherited from the type of the member function for | |||
1245 | // the type of the closure-type's corresponding data member and any use | |||
1246 | // of 'this'. | |||
1247 | CaptureType = ThisTy->getPointeeType(); | |||
1248 | CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask); | |||
1249 | } | |||
1250 | ||||
1251 | bool isNested = NumCapturingClosures > 1; | |||
1252 | CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); | |||
1253 | } | |||
1254 | return false; | |||
1255 | } | |||
1256 | ||||
1257 | ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { | |||
1258 | /// C++ 9.3.2: In the body of a non-static member function, the keyword this | |||
1259 | /// is a non-lvalue expression whose value is the address of the object for | |||
1260 | /// which the function is called. | |||
1261 | ||||
1262 | QualType ThisTy = getCurrentThisType(); | |||
1263 | if (ThisTy.isNull()) | |||
1264 | return Diag(Loc, diag::err_invalid_this_use); | |||
1265 | return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); | |||
1266 | } | |||
1267 | ||||
1268 | Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, | |||
1269 | bool IsImplicit) { | |||
1270 | auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit); | |||
1271 | MarkThisReferenced(This); | |||
1272 | return This; | |||
1273 | } | |||
1274 | ||||
1275 | void Sema::MarkThisReferenced(CXXThisExpr *This) { | |||
1276 | CheckCXXThisCapture(This->getExprLoc()); | |||
1277 | } | |||
1278 | ||||
1279 | bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { | |||
1280 | // If we're outside the body of a member function, then we'll have a specified | |||
1281 | // type for 'this'. | |||
1282 | if (CXXThisTypeOverride.isNull()) | |||
1283 | return false; | |||
1284 | ||||
1285 | // Determine whether we're looking into a class that's currently being | |||
1286 | // defined. | |||
1287 | CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); | |||
1288 | return Class && Class->isBeingDefined(); | |||
1289 | } | |||
1290 | ||||
1291 | /// Parse construction of a specified type. | |||
1292 | /// Can be interpreted either as function-style casting ("int(x)") | |||
1293 | /// or class type construction ("ClassType(x,y,z)") | |||
1294 | /// or creation of a value-initialized type ("int()"). | |||
1295 | ExprResult | |||
1296 | Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, | |||
1297 | SourceLocation LParenOrBraceLoc, | |||
1298 | MultiExprArg exprs, | |||
1299 | SourceLocation RParenOrBraceLoc, | |||
1300 | bool ListInitialization) { | |||
1301 | if (!TypeRep) | |||
1302 | return ExprError(); | |||
1303 | ||||
1304 | TypeSourceInfo *TInfo; | |||
1305 | QualType Ty = GetTypeFromParser(TypeRep, &TInfo); | |||
1306 | if (!TInfo) | |||
1307 | TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); | |||
1308 | ||||
1309 | auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, | |||
1310 | RParenOrBraceLoc, ListInitialization); | |||
1311 | // Avoid creating a non-type-dependent expression that contains typos. | |||
1312 | // Non-type-dependent expressions are liable to be discarded without | |||
1313 | // checking for embedded typos. | |||
1314 | if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && | |||
1315 | !Result.get()->isTypeDependent()) | |||
1316 | Result = CorrectDelayedTyposInExpr(Result.get()); | |||
1317 | return Result; | |||
1318 | } | |||
1319 | ||||
1320 | ExprResult | |||
1321 | Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, | |||
1322 | SourceLocation LParenOrBraceLoc, | |||
1323 | MultiExprArg Exprs, | |||
1324 | SourceLocation RParenOrBraceLoc, | |||
1325 | bool ListInitialization) { | |||
1326 | QualType Ty = TInfo->getType(); | |||
1327 | SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); | |||
1328 | ||||
1329 | if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { | |||
1330 | // FIXME: CXXUnresolvedConstructExpr does not model list-initialization | |||
1331 | // directly. We work around this by dropping the locations of the braces. | |||
1332 | SourceRange Locs = ListInitialization | |||
1333 | ? SourceRange() | |||
1334 | : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); | |||
1335 | return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(), | |||
1336 | Exprs, Locs.getEnd()); | |||
1337 | } | |||
1338 | ||||
1339 | assert((!ListInitialization ||(((!ListInitialization || (Exprs.size() == 1 && isa< InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression." ) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1341, __PRETTY_FUNCTION__)) | |||
1340 | (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&(((!ListInitialization || (Exprs.size() == 1 && isa< InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression." ) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1341, __PRETTY_FUNCTION__)) | |||
1341 | "List initialization must have initializer list as expression.")(((!ListInitialization || (Exprs.size() == 1 && isa< InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression." ) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1341, __PRETTY_FUNCTION__)); | |||
1342 | SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); | |||
1343 | ||||
1344 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); | |||
1345 | InitializationKind Kind = | |||
1346 | Exprs.size() | |||
1347 | ? ListInitialization | |||
1348 | ? InitializationKind::CreateDirectList( | |||
1349 | TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) | |||
1350 | : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, | |||
1351 | RParenOrBraceLoc) | |||
1352 | : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, | |||
1353 | RParenOrBraceLoc); | |||
1354 | ||||
1355 | // C++1z [expr.type.conv]p1: | |||
1356 | // If the type is a placeholder for a deduced class type, [...perform class | |||
1357 | // template argument deduction...] | |||
1358 | DeducedType *Deduced = Ty->getContainedDeducedType(); | |||
1359 | if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { | |||
1360 | Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, | |||
1361 | Kind, Exprs); | |||
1362 | if (Ty.isNull()) | |||
1363 | return ExprError(); | |||
1364 | Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); | |||
1365 | } | |||
1366 | ||||
1367 | // C++ [expr.type.conv]p1: | |||
1368 | // If the expression list is a parenthesized single expression, the type | |||
1369 | // conversion expression is equivalent (in definedness, and if defined in | |||
1370 | // meaning) to the corresponding cast expression. | |||
1371 | if (Exprs.size() == 1 && !ListInitialization && | |||
1372 | !isa<InitListExpr>(Exprs[0])) { | |||
1373 | Expr *Arg = Exprs[0]; | |||
1374 | return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, | |||
1375 | RParenOrBraceLoc); | |||
1376 | } | |||
1377 | ||||
1378 | // For an expression of the form T(), T shall not be an array type. | |||
1379 | QualType ElemTy = Ty; | |||
1380 | if (Ty->isArrayType()) { | |||
1381 | if (!ListInitialization) | |||
1382 | return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) | |||
1383 | << FullRange); | |||
1384 | ElemTy = Context.getBaseElementType(Ty); | |||
1385 | } | |||
1386 | ||||
1387 | // There doesn't seem to be an explicit rule against this but sanity demands | |||
1388 | // we only construct objects with object types. | |||
1389 | if (Ty->isFunctionType()) | |||
1390 | return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) | |||
1391 | << Ty << FullRange); | |||
1392 | ||||
1393 | // C++17 [expr.type.conv]p2: | |||
1394 | // If the type is cv void and the initializer is (), the expression is a | |||
1395 | // prvalue of the specified type that performs no initialization. | |||
1396 | if (!Ty->isVoidType() && | |||
1397 | RequireCompleteType(TyBeginLoc, ElemTy, | |||
1398 | diag::err_invalid_incomplete_type_use, FullRange)) | |||
1399 | return ExprError(); | |||
1400 | ||||
1401 | // Otherwise, the expression is a prvalue of the specified type whose | |||
1402 | // result object is direct-initialized (11.6) with the initializer. | |||
1403 | InitializationSequence InitSeq(*this, Entity, Kind, Exprs); | |||
1404 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); | |||
1405 | ||||
1406 | if (Result.isInvalid()) | |||
1407 | return Result; | |||
1408 | ||||
1409 | Expr *Inner = Result.get(); | |||
1410 | if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) | |||
1411 | Inner = BTE->getSubExpr(); | |||
1412 | if (!isa<CXXTemporaryObjectExpr>(Inner) && | |||
1413 | !isa<CXXScalarValueInitExpr>(Inner)) { | |||
1414 | // If we created a CXXTemporaryObjectExpr, that node also represents the | |||
1415 | // functional cast. Otherwise, create an explicit cast to represent | |||
1416 | // the syntactic form of a functional-style cast that was used here. | |||
1417 | // | |||
1418 | // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr | |||
1419 | // would give a more consistent AST representation than using a | |||
1420 | // CXXTemporaryObjectExpr. It's also weird that the functional cast | |||
1421 | // is sometimes handled by initialization and sometimes not. | |||
1422 | QualType ResultType = Result.get()->getType(); | |||
1423 | SourceRange Locs = ListInitialization | |||
1424 | ? SourceRange() | |||
1425 | : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); | |||
1426 | Result = CXXFunctionalCastExpr::Create( | |||
1427 | Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, | |||
1428 | Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd()); | |||
1429 | } | |||
1430 | ||||
1431 | return Result; | |||
1432 | } | |||
1433 | ||||
1434 | bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { | |||
1435 | // [CUDA] Ignore this function, if we can't call it. | |||
1436 | const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext); | |||
1437 | if (getLangOpts().CUDA && | |||
1438 | IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide) | |||
1439 | return false; | |||
1440 | ||||
1441 | SmallVector<const FunctionDecl*, 4> PreventedBy; | |||
1442 | bool Result = Method->isUsualDeallocationFunction(PreventedBy); | |||
1443 | ||||
1444 | if (Result || !getLangOpts().CUDA || PreventedBy.empty()) | |||
1445 | return Result; | |||
1446 | ||||
1447 | // In case of CUDA, return true if none of the 1-argument deallocator | |||
1448 | // functions are actually callable. | |||
1449 | return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { | |||
1450 | assert(FD->getNumParams() == 1 &&((FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy" ) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1451, __PRETTY_FUNCTION__)) | |||
1451 | "Only single-operand functions should be in PreventedBy")((FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy" ) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1451, __PRETTY_FUNCTION__)); | |||
1452 | return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice; | |||
1453 | }); | |||
1454 | } | |||
1455 | ||||
1456 | /// Determine whether the given function is a non-placement | |||
1457 | /// deallocation function. | |||
1458 | static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { | |||
1459 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) | |||
1460 | return S.isUsualDeallocationFunction(Method); | |||
1461 | ||||
1462 | if (FD->getOverloadedOperator() != OO_Delete && | |||
1463 | FD->getOverloadedOperator() != OO_Array_Delete) | |||
1464 | return false; | |||
1465 | ||||
1466 | unsigned UsualParams = 1; | |||
1467 | ||||
1468 | if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && | |||
1469 | S.Context.hasSameUnqualifiedType( | |||
1470 | FD->getParamDecl(UsualParams)->getType(), | |||
1471 | S.Context.getSizeType())) | |||
1472 | ++UsualParams; | |||
1473 | ||||
1474 | if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && | |||
1475 | S.Context.hasSameUnqualifiedType( | |||
1476 | FD->getParamDecl(UsualParams)->getType(), | |||
1477 | S.Context.getTypeDeclType(S.getStdAlignValT()))) | |||
1478 | ++UsualParams; | |||
1479 | ||||
1480 | return UsualParams == FD->getNumParams(); | |||
1481 | } | |||
1482 | ||||
1483 | namespace { | |||
1484 | struct UsualDeallocFnInfo { | |||
1485 | UsualDeallocFnInfo() : Found(), FD(nullptr) {} | |||
1486 | UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) | |||
1487 | : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), | |||
1488 | Destroying(false), HasSizeT(false), HasAlignValT(false), | |||
1489 | CUDAPref(Sema::CFP_Native) { | |||
1490 | // A function template declaration is never a usual deallocation function. | |||
1491 | if (!FD) | |||
1492 | return; | |||
1493 | unsigned NumBaseParams = 1; | |||
1494 | if (FD->isDestroyingOperatorDelete()) { | |||
1495 | Destroying = true; | |||
1496 | ++NumBaseParams; | |||
1497 | } | |||
1498 | ||||
1499 | if (NumBaseParams < FD->getNumParams() && | |||
1500 | S.Context.hasSameUnqualifiedType( | |||
1501 | FD->getParamDecl(NumBaseParams)->getType(), | |||
1502 | S.Context.getSizeType())) { | |||
1503 | ++NumBaseParams; | |||
1504 | HasSizeT = true; | |||
1505 | } | |||
1506 | ||||
1507 | if (NumBaseParams < FD->getNumParams() && | |||
1508 | FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { | |||
1509 | ++NumBaseParams; | |||
1510 | HasAlignValT = true; | |||
1511 | } | |||
1512 | ||||
1513 | // In CUDA, determine how much we'd like / dislike to call this. | |||
1514 | if (S.getLangOpts().CUDA) | |||
1515 | if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext)) | |||
1516 | CUDAPref = S.IdentifyCUDAPreference(Caller, FD); | |||
1517 | } | |||
1518 | ||||
1519 | explicit operator bool() const { return FD; } | |||
1520 | ||||
1521 | bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, | |||
1522 | bool WantAlign) const { | |||
1523 | // C++ P0722: | |||
1524 | // A destroying operator delete is preferred over a non-destroying | |||
1525 | // operator delete. | |||
1526 | if (Destroying != Other.Destroying) | |||
1527 | return Destroying; | |||
1528 | ||||
1529 | // C++17 [expr.delete]p10: | |||
1530 | // If the type has new-extended alignment, a function with a parameter | |||
1531 | // of type std::align_val_t is preferred; otherwise a function without | |||
1532 | // such a parameter is preferred | |||
1533 | if (HasAlignValT != Other.HasAlignValT) | |||
1534 | return HasAlignValT == WantAlign; | |||
1535 | ||||
1536 | if (HasSizeT != Other.HasSizeT) | |||
1537 | return HasSizeT == WantSize; | |||
1538 | ||||
1539 | // Use CUDA call preference as a tiebreaker. | |||
1540 | return CUDAPref > Other.CUDAPref; | |||
1541 | } | |||
1542 | ||||
1543 | DeclAccessPair Found; | |||
1544 | FunctionDecl *FD; | |||
1545 | bool Destroying, HasSizeT, HasAlignValT; | |||
1546 | Sema::CUDAFunctionPreference CUDAPref; | |||
1547 | }; | |||
1548 | } | |||
1549 | ||||
1550 | /// Determine whether a type has new-extended alignment. This may be called when | |||
1551 | /// the type is incomplete (for a delete-expression with an incomplete pointee | |||
1552 | /// type), in which case it will conservatively return false if the alignment is | |||
1553 | /// not known. | |||
1554 | static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { | |||
1555 | return S.getLangOpts().AlignedAllocation && | |||
1556 | S.getASTContext().getTypeAlignIfKnown(AllocType) > | |||
1557 | S.getASTContext().getTargetInfo().getNewAlign(); | |||
1558 | } | |||
1559 | ||||
1560 | /// Select the correct "usual" deallocation function to use from a selection of | |||
1561 | /// deallocation functions (either global or class-scope). | |||
1562 | static UsualDeallocFnInfo resolveDeallocationOverload( | |||
1563 | Sema &S, LookupResult &R, bool WantSize, bool WantAlign, | |||
1564 | llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { | |||
1565 | UsualDeallocFnInfo Best; | |||
1566 | ||||
1567 | for (auto I = R.begin(), E = R.end(); I != E; ++I) { | |||
1568 | UsualDeallocFnInfo Info(S, I.getPair()); | |||
1569 | if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || | |||
1570 | Info.CUDAPref == Sema::CFP_Never) | |||
1571 | continue; | |||
1572 | ||||
1573 | if (!Best) { | |||
1574 | Best = Info; | |||
1575 | if (BestFns) | |||
1576 | BestFns->push_back(Info); | |||
1577 | continue; | |||
1578 | } | |||
1579 | ||||
1580 | if (Best.isBetterThan(Info, WantSize, WantAlign)) | |||
1581 | continue; | |||
1582 | ||||
1583 | // If more than one preferred function is found, all non-preferred | |||
1584 | // functions are eliminated from further consideration. | |||
1585 | if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) | |||
1586 | BestFns->clear(); | |||
1587 | ||||
1588 | Best = Info; | |||
1589 | if (BestFns) | |||
1590 | BestFns->push_back(Info); | |||
1591 | } | |||
1592 | ||||
1593 | return Best; | |||
1594 | } | |||
1595 | ||||
1596 | /// Determine whether a given type is a class for which 'delete[]' would call | |||
1597 | /// a member 'operator delete[]' with a 'size_t' parameter. This implies that | |||
1598 | /// we need to store the array size (even if the type is | |||
1599 | /// trivially-destructible). | |||
1600 | static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, | |||
1601 | QualType allocType) { | |||
1602 | const RecordType *record = | |||
1603 | allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); | |||
1604 | if (!record) return false; | |||
1605 | ||||
1606 | // Try to find an operator delete[] in class scope. | |||
1607 | ||||
1608 | DeclarationName deleteName = | |||
1609 | S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); | |||
1610 | LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); | |||
1611 | S.LookupQualifiedName(ops, record->getDecl()); | |||
1612 | ||||
1613 | // We're just doing this for information. | |||
1614 | ops.suppressDiagnostics(); | |||
1615 | ||||
1616 | // Very likely: there's no operator delete[]. | |||
1617 | if (ops.empty()) return false; | |||
1618 | ||||
1619 | // If it's ambiguous, it should be illegal to call operator delete[] | |||
1620 | // on this thing, so it doesn't matter if we allocate extra space or not. | |||
1621 | if (ops.isAmbiguous()) return false; | |||
1622 | ||||
1623 | // C++17 [expr.delete]p10: | |||
1624 | // If the deallocation functions have class scope, the one without a | |||
1625 | // parameter of type std::size_t is selected. | |||
1626 | auto Best = resolveDeallocationOverload( | |||
1627 | S, ops, /*WantSize*/false, | |||
1628 | /*WantAlign*/hasNewExtendedAlignment(S, allocType)); | |||
1629 | return Best && Best.HasSizeT; | |||
1630 | } | |||
1631 | ||||
1632 | /// Parsed a C++ 'new' expression (C++ 5.3.4). | |||
1633 | /// | |||
1634 | /// E.g.: | |||
1635 | /// @code new (memory) int[size][4] @endcode | |||
1636 | /// or | |||
1637 | /// @code ::new Foo(23, "hello") @endcode | |||
1638 | /// | |||
1639 | /// \param StartLoc The first location of the expression. | |||
1640 | /// \param UseGlobal True if 'new' was prefixed with '::'. | |||
1641 | /// \param PlacementLParen Opening paren of the placement arguments. | |||
1642 | /// \param PlacementArgs Placement new arguments. | |||
1643 | /// \param PlacementRParen Closing paren of the placement arguments. | |||
1644 | /// \param TypeIdParens If the type is in parens, the source range. | |||
1645 | /// \param D The type to be allocated, as well as array dimensions. | |||
1646 | /// \param Initializer The initializing expression or initializer-list, or null | |||
1647 | /// if there is none. | |||
1648 | ExprResult | |||
1649 | Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, | |||
1650 | SourceLocation PlacementLParen, MultiExprArg PlacementArgs, | |||
1651 | SourceLocation PlacementRParen, SourceRange TypeIdParens, | |||
1652 | Declarator &D, Expr *Initializer) { | |||
1653 | Optional<Expr *> ArraySize; | |||
1654 | // If the specified type is an array, unwrap it and save the expression. | |||
1655 | if (D.getNumTypeObjects() > 0 && | |||
1656 | D.getTypeObject(0).Kind == DeclaratorChunk::Array) { | |||
1657 | DeclaratorChunk &Chunk = D.getTypeObject(0); | |||
1658 | if (D.getDeclSpec().hasAutoTypeSpec()) | |||
1659 | return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) | |||
1660 | << D.getSourceRange()); | |||
1661 | if (Chunk.Arr.hasStatic) | |||
1662 | return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) | |||
1663 | << D.getSourceRange()); | |||
1664 | if (!Chunk.Arr.NumElts && !Initializer) | |||
1665 | return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) | |||
1666 | << D.getSourceRange()); | |||
1667 | ||||
1668 | ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); | |||
1669 | D.DropFirstTypeObject(); | |||
1670 | } | |||
1671 | ||||
1672 | // Every dimension shall be of constant size. | |||
1673 | if (ArraySize) { | |||
1674 | for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { | |||
1675 | if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) | |||
1676 | break; | |||
1677 | ||||
1678 | DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; | |||
1679 | if (Expr *NumElts = (Expr *)Array.NumElts) { | |||
1680 | if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { | |||
1681 | if (getLangOpts().CPlusPlus14) { | |||
1682 | // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator | |||
1683 | // shall be a converted constant expression (5.19) of type std::size_t | |||
1684 | // and shall evaluate to a strictly positive value. | |||
1685 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | |||
1686 | assert(IntWidth && "Builtin type of size 0?")((IntWidth && "Builtin type of size 0?") ? static_cast <void> (0) : __assert_fail ("IntWidth && \"Builtin type of size 0?\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1686, __PRETTY_FUNCTION__)); | |||
1687 | llvm::APSInt Value(IntWidth); | |||
1688 | Array.NumElts | |||
1689 | = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, | |||
1690 | CCEK_NewExpr) | |||
1691 | .get(); | |||
1692 | } else { | |||
1693 | Array.NumElts | |||
1694 | = VerifyIntegerConstantExpression(NumElts, nullptr, | |||
1695 | diag::err_new_array_nonconst) | |||
1696 | .get(); | |||
1697 | } | |||
1698 | if (!Array.NumElts) | |||
1699 | return ExprError(); | |||
1700 | } | |||
1701 | } | |||
1702 | } | |||
1703 | } | |||
1704 | ||||
1705 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr); | |||
1706 | QualType AllocType = TInfo->getType(); | |||
1707 | if (D.isInvalidType()) | |||
1708 | return ExprError(); | |||
1709 | ||||
1710 | SourceRange DirectInitRange; | |||
1711 | if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) | |||
1712 | DirectInitRange = List->getSourceRange(); | |||
1713 | ||||
1714 | return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, | |||
1715 | PlacementLParen, PlacementArgs, PlacementRParen, | |||
1716 | TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, | |||
1717 | Initializer); | |||
1718 | } | |||
1719 | ||||
1720 | static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, | |||
1721 | Expr *Init) { | |||
1722 | if (!Init) | |||
1723 | return true; | |||
1724 | if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) | |||
1725 | return PLE->getNumExprs() == 0; | |||
1726 | if (isa<ImplicitValueInitExpr>(Init)) | |||
1727 | return true; | |||
1728 | else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) | |||
1729 | return !CCE->isListInitialization() && | |||
1730 | CCE->getConstructor()->isDefaultConstructor(); | |||
1731 | else if (Style == CXXNewExpr::ListInit) { | |||
1732 | assert(isa<InitListExpr>(Init) &&((isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays." ) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1733, __PRETTY_FUNCTION__)) | |||
1733 | "Shouldn't create list CXXConstructExprs for arrays.")((isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays." ) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1733, __PRETTY_FUNCTION__)); | |||
1734 | return true; | |||
1735 | } | |||
1736 | return false; | |||
1737 | } | |||
1738 | ||||
1739 | bool | |||
1740 | Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { | |||
1741 | if (!getLangOpts().AlignedAllocationUnavailable) | |||
1742 | return false; | |||
1743 | if (FD.isDefined()) | |||
1744 | return false; | |||
1745 | bool IsAligned = false; | |||
1746 | if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) | |||
1747 | return true; | |||
1748 | return false; | |||
1749 | } | |||
1750 | ||||
1751 | // Emit a diagnostic if an aligned allocation/deallocation function that is not | |||
1752 | // implemented in the standard library is selected. | |||
1753 | void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, | |||
1754 | SourceLocation Loc) { | |||
1755 | if (isUnavailableAlignedAllocationFunction(FD)) { | |||
1756 | const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); | |||
1757 | StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( | |||
1758 | getASTContext().getTargetInfo().getPlatformName()); | |||
1759 | ||||
1760 | OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); | |||
1761 | bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; | |||
1762 | Diag(Loc, diag::err_aligned_allocation_unavailable) | |||
1763 | << IsDelete << FD.getType().getAsString() << OSName | |||
1764 | << alignedAllocMinVersion(T.getOS()).getAsString(); | |||
1765 | Diag(Loc, diag::note_silence_aligned_allocation_unavailable); | |||
1766 | } | |||
1767 | } | |||
1768 | ||||
1769 | ExprResult | |||
1770 | Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, | |||
1771 | SourceLocation PlacementLParen, | |||
1772 | MultiExprArg PlacementArgs, | |||
1773 | SourceLocation PlacementRParen, | |||
1774 | SourceRange TypeIdParens, | |||
1775 | QualType AllocType, | |||
1776 | TypeSourceInfo *AllocTypeInfo, | |||
1777 | Optional<Expr *> ArraySize, | |||
1778 | SourceRange DirectInitRange, | |||
1779 | Expr *Initializer) { | |||
1780 | SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); | |||
1781 | SourceLocation StartLoc = Range.getBegin(); | |||
1782 | ||||
1783 | CXXNewExpr::InitializationStyle initStyle; | |||
1784 | if (DirectInitRange.isValid()) { | |||
1785 | assert(Initializer && "Have parens but no initializer.")((Initializer && "Have parens but no initializer.") ? static_cast<void> (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1785, __PRETTY_FUNCTION__)); | |||
1786 | initStyle = CXXNewExpr::CallInit; | |||
1787 | } else if (Initializer && isa<InitListExpr>(Initializer)) | |||
1788 | initStyle = CXXNewExpr::ListInit; | |||
1789 | else { | |||
1790 | assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(((!Initializer || isa<ImplicitValueInitExpr>(Initializer ) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created." ) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1792, __PRETTY_FUNCTION__)) | |||
1791 | isa<CXXConstructExpr>(Initializer)) &&(((!Initializer || isa<ImplicitValueInitExpr>(Initializer ) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created." ) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1792, __PRETTY_FUNCTION__)) | |||
1792 | "Initializer expression that cannot have been implicitly created.")(((!Initializer || isa<ImplicitValueInitExpr>(Initializer ) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created." ) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1792, __PRETTY_FUNCTION__)); | |||
1793 | initStyle = CXXNewExpr::NoInit; | |||
1794 | } | |||
1795 | ||||
1796 | Expr **Inits = &Initializer; | |||
1797 | unsigned NumInits = Initializer ? 1 : 0; | |||
1798 | if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { | |||
1799 | assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")((initStyle == CXXNewExpr::CallInit && "paren init for non-call init" ) ? static_cast<void> (0) : __assert_fail ("initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1799, __PRETTY_FUNCTION__)); | |||
1800 | Inits = List->getExprs(); | |||
1801 | NumInits = List->getNumExprs(); | |||
1802 | } | |||
1803 | ||||
1804 | // C++11 [expr.new]p15: | |||
1805 | // A new-expression that creates an object of type T initializes that | |||
1806 | // object as follows: | |||
1807 | InitializationKind Kind | |||
1808 | // - If the new-initializer is omitted, the object is default- | |||
1809 | // initialized (8.5); if no initialization is performed, | |||
1810 | // the object has indeterminate value | |||
1811 | = initStyle == CXXNewExpr::NoInit | |||
1812 | ? InitializationKind::CreateDefault(TypeRange.getBegin()) | |||
1813 | // - Otherwise, the new-initializer is interpreted according to | |||
1814 | // the | |||
1815 | // initialization rules of 8.5 for direct-initialization. | |||
1816 | : initStyle == CXXNewExpr::ListInit | |||
1817 | ? InitializationKind::CreateDirectList( | |||
1818 | TypeRange.getBegin(), Initializer->getBeginLoc(), | |||
1819 | Initializer->getEndLoc()) | |||
1820 | : InitializationKind::CreateDirect(TypeRange.getBegin(), | |||
1821 | DirectInitRange.getBegin(), | |||
1822 | DirectInitRange.getEnd()); | |||
1823 | ||||
1824 | // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. | |||
1825 | auto *Deduced = AllocType->getContainedDeducedType(); | |||
1826 | if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { | |||
1827 | if (ArraySize) | |||
1828 | return ExprError( | |||
1829 | Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), | |||
1830 | diag::err_deduced_class_template_compound_type) | |||
1831 | << /*array*/ 2 | |||
1832 | << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); | |||
1833 | ||||
1834 | InitializedEntity Entity | |||
1835 | = InitializedEntity::InitializeNew(StartLoc, AllocType); | |||
1836 | AllocType = DeduceTemplateSpecializationFromInitializer( | |||
1837 | AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits)); | |||
1838 | if (AllocType.isNull()) | |||
1839 | return ExprError(); | |||
1840 | } else if (Deduced) { | |||
1841 | bool Braced = (initStyle == CXXNewExpr::ListInit); | |||
1842 | if (NumInits == 1) { | |||
1843 | if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) { | |||
1844 | Inits = p->getInits(); | |||
1845 | NumInits = p->getNumInits(); | |||
1846 | Braced = true; | |||
1847 | } | |||
1848 | } | |||
1849 | ||||
1850 | if (initStyle == CXXNewExpr::NoInit || NumInits == 0) | |||
1851 | return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) | |||
1852 | << AllocType << TypeRange); | |||
1853 | if (NumInits > 1) { | |||
1854 | Expr *FirstBad = Inits[1]; | |||
1855 | return ExprError(Diag(FirstBad->getBeginLoc(), | |||
1856 | diag::err_auto_new_ctor_multiple_expressions) | |||
1857 | << AllocType << TypeRange); | |||
1858 | } | |||
1859 | if (Braced && !getLangOpts().CPlusPlus17) | |||
1860 | Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) | |||
1861 | << AllocType << TypeRange; | |||
1862 | Expr *Deduce = Inits[0]; | |||
1863 | QualType DeducedType; | |||
1864 | if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) | |||
1865 | return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) | |||
1866 | << AllocType << Deduce->getType() | |||
1867 | << TypeRange << Deduce->getSourceRange()); | |||
1868 | if (DeducedType.isNull()) | |||
1869 | return ExprError(); | |||
1870 | AllocType = DeducedType; | |||
1871 | } | |||
1872 | ||||
1873 | // Per C++0x [expr.new]p5, the type being constructed may be a | |||
1874 | // typedef of an array type. | |||
1875 | if (!ArraySize) { | |||
1876 | if (const ConstantArrayType *Array | |||
1877 | = Context.getAsConstantArrayType(AllocType)) { | |||
1878 | ArraySize = IntegerLiteral::Create(Context, Array->getSize(), | |||
1879 | Context.getSizeType(), | |||
1880 | TypeRange.getEnd()); | |||
1881 | AllocType = Array->getElementType(); | |||
1882 | } | |||
1883 | } | |||
1884 | ||||
1885 | if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) | |||
1886 | return ExprError(); | |||
1887 | ||||
1888 | // In ARC, infer 'retaining' for the allocated | |||
1889 | if (getLangOpts().ObjCAutoRefCount && | |||
1890 | AllocType.getObjCLifetime() == Qualifiers::OCL_None && | |||
1891 | AllocType->isObjCLifetimeType()) { | |||
1892 | AllocType = Context.getLifetimeQualifiedType(AllocType, | |||
1893 | AllocType->getObjCARCImplicitLifetime()); | |||
1894 | } | |||
1895 | ||||
1896 | QualType ResultType = Context.getPointerType(AllocType); | |||
1897 | ||||
1898 | if (ArraySize && *ArraySize && | |||
1899 | (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { | |||
1900 | ExprResult result = CheckPlaceholderExpr(*ArraySize); | |||
1901 | if (result.isInvalid()) return ExprError(); | |||
1902 | ArraySize = result.get(); | |||
1903 | } | |||
1904 | // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have | |||
1905 | // integral or enumeration type with a non-negative value." | |||
1906 | // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped | |||
1907 | // enumeration type, or a class type for which a single non-explicit | |||
1908 | // conversion function to integral or unscoped enumeration type exists. | |||
1909 | // C++1y [expr.new]p6: The expression [...] is implicitly converted to | |||
1910 | // std::size_t. | |||
1911 | llvm::Optional<uint64_t> KnownArraySize; | |||
1912 | if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { | |||
1913 | ExprResult ConvertedSize; | |||
1914 | if (getLangOpts().CPlusPlus14) { | |||
1915 | assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")((Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?" ) ? static_cast<void> (0) : __assert_fail ("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 1915, __PRETTY_FUNCTION__)); | |||
1916 | ||||
1917 | ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(), | |||
1918 | AA_Converting); | |||
1919 | ||||
1920 | if (!ConvertedSize.isInvalid() && | |||
1921 | (*ArraySize)->getType()->getAs<RecordType>()) | |||
1922 | // Diagnose the compatibility of this conversion. | |||
1923 | Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) | |||
1924 | << (*ArraySize)->getType() << 0 << "'size_t'"; | |||
1925 | } else { | |||
1926 | class SizeConvertDiagnoser : public ICEConvertDiagnoser { | |||
1927 | protected: | |||
1928 | Expr *ArraySize; | |||
1929 | ||||
1930 | public: | |||
1931 | SizeConvertDiagnoser(Expr *ArraySize) | |||
1932 | : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), | |||
1933 | ArraySize(ArraySize) {} | |||
1934 | ||||
1935 | SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, | |||
1936 | QualType T) override { | |||
1937 | return S.Diag(Loc, diag::err_array_size_not_integral) | |||
1938 | << S.getLangOpts().CPlusPlus11 << T; | |||
1939 | } | |||
1940 | ||||
1941 | SemaDiagnosticBuilder diagnoseIncomplete( | |||
1942 | Sema &S, SourceLocation Loc, QualType T) override { | |||
1943 | return S.Diag(Loc, diag::err_array_size_incomplete_type) | |||
1944 | << T << ArraySize->getSourceRange(); | |||
1945 | } | |||
1946 | ||||
1947 | SemaDiagnosticBuilder diagnoseExplicitConv( | |||
1948 | Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { | |||
1949 | return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; | |||
1950 | } | |||
1951 | ||||
1952 | SemaDiagnosticBuilder noteExplicitConv( | |||
1953 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
1954 | return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) | |||
1955 | << ConvTy->isEnumeralType() << ConvTy; | |||
1956 | } | |||
1957 | ||||
1958 | SemaDiagnosticBuilder diagnoseAmbiguous( | |||
1959 | Sema &S, SourceLocation Loc, QualType T) override { | |||
1960 | return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; | |||
1961 | } | |||
1962 | ||||
1963 | SemaDiagnosticBuilder noteAmbiguous( | |||
1964 | Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { | |||
1965 | return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) | |||
1966 | << ConvTy->isEnumeralType() << ConvTy; | |||
1967 | } | |||
1968 | ||||
1969 | SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, | |||
1970 | QualType T, | |||
1971 | QualType ConvTy) override { | |||
1972 | return S.Diag(Loc, | |||
1973 | S.getLangOpts().CPlusPlus11 | |||
1974 | ? diag::warn_cxx98_compat_array_size_conversion | |||
1975 | : diag::ext_array_size_conversion) | |||
1976 | << T << ConvTy->isEnumeralType() << ConvTy; | |||
1977 | } | |||
1978 | } SizeDiagnoser(*ArraySize); | |||
1979 | ||||
1980 | ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, | |||
1981 | SizeDiagnoser); | |||
1982 | } | |||
1983 | if (ConvertedSize.isInvalid()) | |||
1984 | return ExprError(); | |||
1985 | ||||
1986 | ArraySize = ConvertedSize.get(); | |||
1987 | QualType SizeType = (*ArraySize)->getType(); | |||
1988 | ||||
1989 | if (!SizeType->isIntegralOrUnscopedEnumerationType()) | |||
1990 | return ExprError(); | |||
1991 | ||||
1992 | // C++98 [expr.new]p7: | |||
1993 | // The expression in a direct-new-declarator shall have integral type | |||
1994 | // with a non-negative value. | |||
1995 | // | |||
1996 | // Let's see if this is a constant < 0. If so, we reject it out of hand, | |||
1997 | // per CWG1464. Otherwise, if it's not a constant, we must have an | |||
1998 | // unparenthesized array type. | |||
1999 | if (!(*ArraySize)->isValueDependent()) { | |||
2000 | llvm::APSInt Value; | |||
2001 | // We've already performed any required implicit conversion to integer or | |||
2002 | // unscoped enumeration type. | |||
2003 | // FIXME: Per CWG1464, we are required to check the value prior to | |||
2004 | // converting to size_t. This will never find a negative array size in | |||
2005 | // C++14 onwards, because Value is always unsigned here! | |||
2006 | if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) { | |||
2007 | if (Value.isSigned() && Value.isNegative()) { | |||
2008 | return ExprError(Diag((*ArraySize)->getBeginLoc(), | |||
2009 | diag::err_typecheck_negative_array_size) | |||
2010 | << (*ArraySize)->getSourceRange()); | |||
2011 | } | |||
2012 | ||||
2013 | if (!AllocType->isDependentType()) { | |||
2014 | unsigned ActiveSizeBits = | |||
2015 | ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); | |||
2016 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) | |||
2017 | return ExprError( | |||
2018 | Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) | |||
2019 | << Value.toString(10) << (*ArraySize)->getSourceRange()); | |||
2020 | } | |||
2021 | ||||
2022 | KnownArraySize = Value.getZExtValue(); | |||
2023 | } else if (TypeIdParens.isValid()) { | |||
2024 | // Can't have dynamic array size when the type-id is in parentheses. | |||
2025 | Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) | |||
2026 | << (*ArraySize)->getSourceRange() | |||
2027 | << FixItHint::CreateRemoval(TypeIdParens.getBegin()) | |||
2028 | << FixItHint::CreateRemoval(TypeIdParens.getEnd()); | |||
2029 | ||||
2030 | TypeIdParens = SourceRange(); | |||
2031 | } | |||
2032 | } | |||
2033 | ||||
2034 | // Note that we do *not* convert the argument in any way. It can | |||
2035 | // be signed, larger than size_t, whatever. | |||
2036 | } | |||
2037 | ||||
2038 | FunctionDecl *OperatorNew = nullptr; | |||
2039 | FunctionDecl *OperatorDelete = nullptr; | |||
2040 | unsigned Alignment = | |||
2041 | AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); | |||
2042 | unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); | |||
2043 | bool PassAlignment = getLangOpts().AlignedAllocation && | |||
2044 | Alignment > NewAlignment; | |||
2045 | ||||
2046 | AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; | |||
2047 | if (!AllocType->isDependentType() && | |||
2048 | !Expr::hasAnyTypeDependentArguments(PlacementArgs) && | |||
2049 | FindAllocationFunctions( | |||
2050 | StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope, | |||
2051 | AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs, | |||
2052 | OperatorNew, OperatorDelete)) | |||
2053 | return ExprError(); | |||
2054 | ||||
2055 | // If this is an array allocation, compute whether the usual array | |||
2056 | // deallocation function for the type has a size_t parameter. | |||
2057 | bool UsualArrayDeleteWantsSize = false; | |||
2058 | if (ArraySize && !AllocType->isDependentType()) | |||
2059 | UsualArrayDeleteWantsSize = | |||
2060 | doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); | |||
2061 | ||||
2062 | SmallVector<Expr *, 8> AllPlaceArgs; | |||
2063 | if (OperatorNew) { | |||
2064 | const FunctionProtoType *Proto = | |||
2065 | OperatorNew->getType()->getAs<FunctionProtoType>(); | |||
2066 | VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction | |||
2067 | : VariadicDoesNotApply; | |||
2068 | ||||
2069 | // We've already converted the placement args, just fill in any default | |||
2070 | // arguments. Skip the first parameter because we don't have a corresponding | |||
2071 | // argument. Skip the second parameter too if we're passing in the | |||
2072 | // alignment; we've already filled it in. | |||
2073 | if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, | |||
2074 | PassAlignment ? 2 : 1, PlacementArgs, | |||
2075 | AllPlaceArgs, CallType)) | |||
2076 | return ExprError(); | |||
2077 | ||||
2078 | if (!AllPlaceArgs.empty()) | |||
2079 | PlacementArgs = AllPlaceArgs; | |||
2080 | ||||
2081 | // FIXME: This is wrong: PlacementArgs misses out the first (size) argument. | |||
2082 | DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs); | |||
2083 | ||||
2084 | // FIXME: Missing call to CheckFunctionCall or equivalent | |||
2085 | ||||
2086 | // Warn if the type is over-aligned and is being allocated by (unaligned) | |||
2087 | // global operator new. | |||
2088 | if (PlacementArgs.empty() && !PassAlignment && | |||
2089 | (OperatorNew->isImplicit() || | |||
2090 | (OperatorNew->getBeginLoc().isValid() && | |||
2091 | getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { | |||
2092 | if (Alignment > NewAlignment) | |||
2093 | Diag(StartLoc, diag::warn_overaligned_type) | |||
2094 | << AllocType | |||
2095 | << unsigned(Alignment / Context.getCharWidth()) | |||
2096 | << unsigned(NewAlignment / Context.getCharWidth()); | |||
2097 | } | |||
2098 | } | |||
2099 | ||||
2100 | // Array 'new' can't have any initializers except empty parentheses. | |||
2101 | // Initializer lists are also allowed, in C++11. Rely on the parser for the | |||
2102 | // dialect distinction. | |||
2103 | if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { | |||
2104 | SourceRange InitRange(Inits[0]->getBeginLoc(), | |||
2105 | Inits[NumInits - 1]->getEndLoc()); | |||
2106 | Diag(StartLoc, diag::err_new_array_init_args) << InitRange; | |||
2107 | return ExprError(); | |||
2108 | } | |||
2109 | ||||
2110 | // If we can perform the initialization, and we've not already done so, | |||
2111 | // do it now. | |||
2112 | if (!AllocType->isDependentType() && | |||
2113 | !Expr::hasAnyTypeDependentArguments( | |||
2114 | llvm::makeArrayRef(Inits, NumInits))) { | |||
2115 | // The type we initialize is the complete type, including the array bound. | |||
2116 | QualType InitType; | |||
2117 | if (KnownArraySize) | |||
2118 | InitType = Context.getConstantArrayType( | |||
2119 | AllocType, | |||
2120 | llvm::APInt(Context.getTypeSize(Context.getSizeType()), | |||
2121 | *KnownArraySize), | |||
2122 | *ArraySize, ArrayType::Normal, 0); | |||
2123 | else if (ArraySize) | |||
2124 | InitType = | |||
2125 | Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); | |||
2126 | else | |||
2127 | InitType = AllocType; | |||
2128 | ||||
2129 | InitializedEntity Entity | |||
2130 | = InitializedEntity::InitializeNew(StartLoc, InitType); | |||
2131 | InitializationSequence InitSeq(*this, Entity, Kind, | |||
2132 | MultiExprArg(Inits, NumInits)); | |||
2133 | ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, | |||
2134 | MultiExprArg(Inits, NumInits)); | |||
2135 | if (FullInit.isInvalid()) | |||
2136 | return ExprError(); | |||
2137 | ||||
2138 | // FullInit is our initializer; strip off CXXBindTemporaryExprs, because | |||
2139 | // we don't want the initialized object to be destructed. | |||
2140 | // FIXME: We should not create these in the first place. | |||
2141 | if (CXXBindTemporaryExpr *Binder = | |||
2142 | dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) | |||
2143 | FullInit = Binder->getSubExpr(); | |||
2144 | ||||
2145 | Initializer = FullInit.get(); | |||
2146 | ||||
2147 | // FIXME: If we have a KnownArraySize, check that the array bound of the | |||
2148 | // initializer is no greater than that constant value. | |||
2149 | ||||
2150 | if (ArraySize && !*ArraySize) { | |||
2151 | auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); | |||
2152 | if (CAT) { | |||
2153 | // FIXME: Track that the array size was inferred rather than explicitly | |||
2154 | // specified. | |||
2155 | ArraySize = IntegerLiteral::Create( | |||
2156 | Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); | |||
2157 | } else { | |||
2158 | Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) | |||
2159 | << Initializer->getSourceRange(); | |||
2160 | } | |||
2161 | } | |||
2162 | } | |||
2163 | ||||
2164 | // Mark the new and delete operators as referenced. | |||
2165 | if (OperatorNew) { | |||
2166 | if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) | |||
2167 | return ExprError(); | |||
2168 | MarkFunctionReferenced(StartLoc, OperatorNew); | |||
2169 | } | |||
2170 | if (OperatorDelete) { | |||
2171 | if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) | |||
2172 | return ExprError(); | |||
2173 | MarkFunctionReferenced(StartLoc, OperatorDelete); | |||
2174 | } | |||
2175 | ||||
2176 | return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, | |||
2177 | PassAlignment, UsualArrayDeleteWantsSize, | |||
2178 | PlacementArgs, TypeIdParens, ArraySize, initStyle, | |||
2179 | Initializer, ResultType, AllocTypeInfo, Range, | |||
2180 | DirectInitRange); | |||
2181 | } | |||
2182 | ||||
2183 | /// Checks that a type is suitable as the allocated type | |||
2184 | /// in a new-expression. | |||
2185 | bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, | |||
2186 | SourceRange R) { | |||
2187 | // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an | |||
2188 | // abstract class type or array thereof. | |||
2189 | if (AllocType->isFunctionType()) | |||
2190 | return Diag(Loc, diag::err_bad_new_type) | |||
2191 | << AllocType << 0 << R; | |||
2192 | else if (AllocType->isReferenceType()) | |||
2193 | return Diag(Loc, diag::err_bad_new_type) | |||
2194 | << AllocType << 1 << R; | |||
2195 | else if (!AllocType->isDependentType() && | |||
2196 | RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R)) | |||
2197 | return true; | |||
2198 | else if (RequireNonAbstractType(Loc, AllocType, | |||
2199 | diag::err_allocation_of_abstract_type)) | |||
2200 | return true; | |||
2201 | else if (AllocType->isVariablyModifiedType()) | |||
2202 | return Diag(Loc, diag::err_variably_modified_new_type) | |||
2203 | << AllocType; | |||
2204 | else if (AllocType.getAddressSpace() != LangAS::Default && | |||
2205 | !getLangOpts().OpenCLCPlusPlus) | |||
2206 | return Diag(Loc, diag::err_address_space_qualified_new) | |||
2207 | << AllocType.getUnqualifiedType() | |||
2208 | << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); | |||
2209 | else if (getLangOpts().ObjCAutoRefCount) { | |||
2210 | if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { | |||
2211 | QualType BaseAllocType = Context.getBaseElementType(AT); | |||
2212 | if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && | |||
2213 | BaseAllocType->isObjCLifetimeType()) | |||
2214 | return Diag(Loc, diag::err_arc_new_array_without_ownership) | |||
2215 | << BaseAllocType; | |||
2216 | } | |||
2217 | } | |||
2218 | ||||
2219 | return false; | |||
2220 | } | |||
2221 | ||||
2222 | static bool resolveAllocationOverload( | |||
2223 | Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, | |||
2224 | bool &PassAlignment, FunctionDecl *&Operator, | |||
2225 | OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { | |||
2226 | OverloadCandidateSet Candidates(R.getNameLoc(), | |||
2227 | OverloadCandidateSet::CSK_Normal); | |||
2228 | for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); | |||
2229 | Alloc != AllocEnd; ++Alloc) { | |||
2230 | // Even member operator new/delete are implicitly treated as | |||
2231 | // static, so don't use AddMemberCandidate. | |||
2232 | NamedDecl *D = (*Alloc)->getUnderlyingDecl(); | |||
2233 | ||||
2234 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { | |||
2235 | S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), | |||
2236 | /*ExplicitTemplateArgs=*/nullptr, Args, | |||
2237 | Candidates, | |||
2238 | /*SuppressUserConversions=*/false); | |||
2239 | continue; | |||
2240 | } | |||
2241 | ||||
2242 | FunctionDecl *Fn = cast<FunctionDecl>(D); | |||
2243 | S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, | |||
2244 | /*SuppressUserConversions=*/false); | |||
2245 | } | |||
2246 | ||||
2247 | // Do the resolution. | |||
2248 | OverloadCandidateSet::iterator Best; | |||
2249 | switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { | |||
2250 | case OR_Success: { | |||
2251 | // Got one! | |||
2252 | FunctionDecl *FnDecl = Best->Function; | |||
2253 | if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), | |||
2254 | Best->FoundDecl) == Sema::AR_inaccessible) | |||
2255 | return true; | |||
2256 | ||||
2257 | Operator = FnDecl; | |||
2258 | return false; | |||
2259 | } | |||
2260 | ||||
2261 | case OR_No_Viable_Function: | |||
2262 | // C++17 [expr.new]p13: | |||
2263 | // If no matching function is found and the allocated object type has | |||
2264 | // new-extended alignment, the alignment argument is removed from the | |||
2265 | // argument list, and overload resolution is performed again. | |||
2266 | if (PassAlignment) { | |||
2267 | PassAlignment = false; | |||
2268 | AlignArg = Args[1]; | |||
2269 | Args.erase(Args.begin() + 1); | |||
2270 | return resolveAllocationOverload(S, R, Range, Args, PassAlignment, | |||
2271 | Operator, &Candidates, AlignArg, | |||
2272 | Diagnose); | |||
2273 | } | |||
2274 | ||||
2275 | // MSVC will fall back on trying to find a matching global operator new | |||
2276 | // if operator new[] cannot be found. Also, MSVC will leak by not | |||
2277 | // generating a call to operator delete or operator delete[], but we | |||
2278 | // will not replicate that bug. | |||
2279 | // FIXME: Find out how this interacts with the std::align_val_t fallback | |||
2280 | // once MSVC implements it. | |||
2281 | if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && | |||
2282 | S.Context.getLangOpts().MSVCCompat) { | |||
2283 | R.clear(); | |||
2284 | R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); | |||
2285 | S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); | |||
2286 | // FIXME: This will give bad diagnostics pointing at the wrong functions. | |||
2287 | return resolveAllocationOverload(S, R, Range, Args, PassAlignment, | |||
2288 | Operator, /*Candidates=*/nullptr, | |||
2289 | /*AlignArg=*/nullptr, Diagnose); | |||
2290 | } | |||
2291 | ||||
2292 | if (Diagnose) { | |||
2293 | PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call) | |||
2294 | << R.getLookupName() << Range); | |||
2295 | ||||
2296 | // If we have aligned candidates, only note the align_val_t candidates | |||
2297 | // from AlignedCandidates and the non-align_val_t candidates from | |||
2298 | // Candidates. | |||
2299 | if (AlignedCandidates) { | |||
2300 | auto IsAligned = [](OverloadCandidate &C) { | |||
2301 | return C.Function->getNumParams() > 1 && | |||
2302 | C.Function->getParamDecl(1)->getType()->isAlignValT(); | |||
2303 | }; | |||
2304 | auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; | |||
2305 | ||||
2306 | // This was an overaligned allocation, so list the aligned candidates | |||
2307 | // first. | |||
2308 | Args.insert(Args.begin() + 1, AlignArg); | |||
2309 | AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "", | |||
2310 | R.getNameLoc(), IsAligned); | |||
2311 | Args.erase(Args.begin() + 1); | |||
2312 | Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(), | |||
2313 | IsUnaligned); | |||
2314 | } else { | |||
2315 | Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args); | |||
2316 | } | |||
2317 | } | |||
2318 | return true; | |||
2319 | ||||
2320 | case OR_Ambiguous: | |||
2321 | if (Diagnose) { | |||
2322 | Candidates.NoteCandidates( | |||
2323 | PartialDiagnosticAt(R.getNameLoc(), | |||
2324 | S.PDiag(diag::err_ovl_ambiguous_call) | |||
2325 | << R.getLookupName() << Range), | |||
2326 | S, OCD_ViableCandidates, Args); | |||
2327 | } | |||
2328 | return true; | |||
2329 | ||||
2330 | case OR_Deleted: { | |||
2331 | if (Diagnose) { | |||
2332 | Candidates.NoteCandidates( | |||
2333 | PartialDiagnosticAt(R.getNameLoc(), | |||
2334 | S.PDiag(diag::err_ovl_deleted_call) | |||
2335 | << R.getLookupName() << Range), | |||
2336 | S, OCD_AllCandidates, Args); | |||
2337 | } | |||
2338 | return true; | |||
2339 | } | |||
2340 | } | |||
2341 | llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 2341); | |||
2342 | } | |||
2343 | ||||
2344 | bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, | |||
2345 | AllocationFunctionScope NewScope, | |||
2346 | AllocationFunctionScope DeleteScope, | |||
2347 | QualType AllocType, bool IsArray, | |||
2348 | bool &PassAlignment, MultiExprArg PlaceArgs, | |||
2349 | FunctionDecl *&OperatorNew, | |||
2350 | FunctionDecl *&OperatorDelete, | |||
2351 | bool Diagnose) { | |||
2352 | // --- Choosing an allocation function --- | |||
2353 | // C++ 5.3.4p8 - 14 & 18 | |||
2354 | // 1) If looking in AFS_Global scope for allocation functions, only look in | |||
2355 | // the global scope. Else, if AFS_Class, only look in the scope of the | |||
2356 | // allocated class. If AFS_Both, look in both. | |||
2357 | // 2) If an array size is given, look for operator new[], else look for | |||
2358 | // operator new. | |||
2359 | // 3) The first argument is always size_t. Append the arguments from the | |||
2360 | // placement form. | |||
2361 | ||||
2362 | SmallVector<Expr*, 8> AllocArgs; | |||
2363 | AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); | |||
2364 | ||||
2365 | // We don't care about the actual value of these arguments. | |||
2366 | // FIXME: Should the Sema create the expression and embed it in the syntax | |||
2367 | // tree? Or should the consumer just recalculate the value? | |||
2368 | // FIXME: Using a dummy value will interact poorly with attribute enable_if. | |||
2369 | IntegerLiteral Size(Context, llvm::APInt::getNullValue( | |||
2370 | Context.getTargetInfo().getPointerWidth(0)), | |||
2371 | Context.getSizeType(), | |||
2372 | SourceLocation()); | |||
2373 | AllocArgs.push_back(&Size); | |||
2374 | ||||
2375 | QualType AlignValT = Context.VoidTy; | |||
2376 | if (PassAlignment) { | |||
2377 | DeclareGlobalNewDelete(); | |||
2378 | AlignValT = Context.getTypeDeclType(getStdAlignValT()); | |||
2379 | } | |||
2380 | CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); | |||
2381 | if (PassAlignment) | |||
2382 | AllocArgs.push_back(&Align); | |||
2383 | ||||
2384 | AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); | |||
2385 | ||||
2386 | // C++ [expr.new]p8: | |||
2387 | // If the allocated type is a non-array type, the allocation | |||
2388 | // function's name is operator new and the deallocation function's | |||
2389 | // name is operator delete. If the allocated type is an array | |||
2390 | // type, the allocation function's name is operator new[] and the | |||
2391 | // deallocation function's name is operator delete[]. | |||
2392 | DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( | |||
2393 | IsArray ? OO_Array_New : OO_New); | |||
2394 | ||||
2395 | QualType AllocElemType = Context.getBaseElementType(AllocType); | |||
2396 | ||||
2397 | // Find the allocation function. | |||
2398 | { | |||
2399 | LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); | |||
2400 | ||||
2401 | // C++1z [expr.new]p9: | |||
2402 | // If the new-expression begins with a unary :: operator, the allocation | |||
2403 | // function's name is looked up in the global scope. Otherwise, if the | |||
2404 | // allocated type is a class type T or array thereof, the allocation | |||
2405 | // function's name is looked up in the scope of T. | |||
2406 | if (AllocElemType->isRecordType() && NewScope != AFS_Global) | |||
2407 | LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); | |||
2408 | ||||
2409 | // We can see ambiguity here if the allocation function is found in | |||
2410 | // multiple base classes. | |||
2411 | if (R.isAmbiguous()) | |||
2412 | return true; | |||
2413 | ||||
2414 | // If this lookup fails to find the name, or if the allocated type is not | |||
2415 | // a class type, the allocation function's name is looked up in the | |||
2416 | // global scope. | |||
2417 | if (R.empty()) { | |||
2418 | if (NewScope == AFS_Class) | |||
2419 | return true; | |||
2420 | ||||
2421 | LookupQualifiedName(R, Context.getTranslationUnitDecl()); | |||
2422 | } | |||
2423 | ||||
2424 | if (getLangOpts().OpenCLCPlusPlus && R.empty()) { | |||
2425 | if (PlaceArgs.empty()) { | |||
2426 | Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; | |||
2427 | } else { | |||
2428 | Diag(StartLoc, diag::err_openclcxx_placement_new); | |||
2429 | } | |||
2430 | return true; | |||
2431 | } | |||
2432 | ||||
2433 | assert(!R.empty() && "implicitly declared allocation functions not found")((!R.empty() && "implicitly declared allocation functions not found" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 2433, __PRETTY_FUNCTION__)); | |||
2434 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous")((!R.isAmbiguous() && "global allocation functions are ambiguous" ) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 2434, __PRETTY_FUNCTION__)); | |||
2435 | ||||
2436 | // We do our own custom access checks below. | |||
2437 | R.suppressDiagnostics(); | |||
2438 | ||||
2439 | if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, | |||
2440 | OperatorNew, /*Candidates=*/nullptr, | |||
2441 | /*AlignArg=*/nullptr, Diagnose)) | |||
2442 | return true; | |||
2443 | } | |||
2444 | ||||
2445 | // We don't need an operator delete if we're running under -fno-exceptions. | |||
2446 | if (!getLangOpts().Exceptions) { | |||
2447 | OperatorDelete = nullptr; | |||
2448 | return false; | |||
2449 | } | |||
2450 | ||||
2451 | // Note, the name of OperatorNew might have been changed from array to | |||
2452 | // non-array by resolveAllocationOverload. | |||
2453 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( | |||
2454 | OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New | |||
2455 | ? OO_Array_Delete | |||
2456 | : OO_Delete); | |||
2457 | ||||
2458 | // C++ [expr.new]p19: | |||
2459 | // | |||
2460 | // If the new-expression begins with a unary :: operator, the | |||
2461 | // deallocation function's name is looked up in the global | |||
2462 | // scope. Otherwise, if the allocated type is a class type T or an | |||
2463 | // array thereof, the deallocation function's name is looked up in | |||
2464 | // the scope of T. If this lookup fails to find the name, or if | |||
2465 | // the allocated type is not a class type or array thereof, the | |||
2466 | // deallocation function's name is looked up in the global scope. | |||
2467 | LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); | |||
2468 | if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { | |||
2469 | auto *RD = | |||
2470 | cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl()); | |||
2471 | LookupQualifiedName(FoundDelete, RD); | |||
2472 | } | |||
2473 | if (FoundDelete.isAmbiguous()) | |||
2474 | return true; // FIXME: clean up expressions? | |||
2475 | ||||
2476 | bool FoundGlobalDelete = FoundDelete.empty(); | |||
2477 | if (FoundDelete.empty()) { | |||
2478 | if (DeleteScope == AFS_Class) | |||
2479 | return true; | |||
2480 | ||||
2481 | DeclareGlobalNewDelete(); | |||
2482 | LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); | |||
2483 | } | |||
2484 | ||||
2485 | FoundDelete.suppressDiagnostics(); | |||
2486 | ||||
2487 | SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; | |||
2488 | ||||
2489 | // Whether we're looking for a placement operator delete is dictated | |||
2490 | // by whether we selected a placement operator new, not by whether | |||
2491 | // we had explicit placement arguments. This matters for things like | |||
2492 | // struct A { void *operator new(size_t, int = 0); ... }; | |||
2493 | // A *a = new A() | |||
2494 | // | |||
2495 | // We don't have any definition for what a "placement allocation function" | |||
2496 | // is, but we assume it's any allocation function whose | |||
2497 | // parameter-declaration-clause is anything other than (size_t). | |||
2498 | // | |||
2499 | // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? | |||
2500 | // This affects whether an exception from the constructor of an overaligned | |||
2501 | // type uses the sized or non-sized form of aligned operator delete. | |||
2502 | bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || | |||
2503 | OperatorNew->isVariadic(); | |||
2504 | ||||
2505 | if (isPlacementNew) { | |||
2506 | // C++ [expr.new]p20: | |||
2507 | // A declaration of a placement deallocation function matches the | |||
2508 | // declaration of a placement allocation function if it has the | |||
2509 | // same number of parameters and, after parameter transformations | |||
2510 | // (8.3.5), all parameter types except the first are | |||
2511 | // identical. [...] | |||
2512 | // | |||
2513 | // To perform this comparison, we compute the function type that | |||
2514 | // the deallocation function should have, and use that type both | |||
2515 | // for template argument deduction and for comparison purposes. | |||
2516 | QualType ExpectedFunctionType; | |||
2517 | { | |||
2518 | const FunctionProtoType *Proto | |||
2519 | = OperatorNew->getType()->getAs<FunctionProtoType>(); | |||
2520 | ||||
2521 | SmallVector<QualType, 4> ArgTypes; | |||
2522 | ArgTypes.push_back(Context.VoidPtrTy); | |||
2523 | for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) | |||
2524 | ArgTypes.push_back(Proto->getParamType(I)); | |||
2525 | ||||
2526 | FunctionProtoType::ExtProtoInfo EPI; | |||
2527 | // FIXME: This is not part of the standard's rule. | |||
2528 | EPI.Variadic = Proto->isVariadic(); | |||
2529 | ||||
2530 | ExpectedFunctionType | |||
2531 | = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); | |||
2532 | } | |||
2533 | ||||
2534 | for (LookupResult::iterator D = FoundDelete.begin(), | |||
2535 | DEnd = FoundDelete.end(); | |||
2536 | D != DEnd; ++D) { | |||
2537 | FunctionDecl *Fn = nullptr; | |||
2538 | if (FunctionTemplateDecl *FnTmpl = | |||
2539 | dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { | |||
2540 | // Perform template argument deduction to try to match the | |||
2541 | // expected function type. | |||
2542 | TemplateDeductionInfo Info(StartLoc); | |||
2543 | if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, | |||
2544 | Info)) | |||
2545 | continue; | |||
2546 | } else | |||
2547 | Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); | |||
2548 | ||||
2549 | if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), | |||
2550 | ExpectedFunctionType, | |||
2551 | /*AdjustExcpetionSpec*/true), | |||
2552 | ExpectedFunctionType)) | |||
2553 | Matches.push_back(std::make_pair(D.getPair(), Fn)); | |||
2554 | } | |||
2555 | ||||
2556 | if (getLangOpts().CUDA) | |||
2557 | EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches); | |||
2558 | } else { | |||
2559 | // C++1y [expr.new]p22: | |||
2560 | // For a non-placement allocation function, the normal deallocation | |||
2561 | // function lookup is used | |||
2562 | // | |||
2563 | // Per [expr.delete]p10, this lookup prefers a member operator delete | |||
2564 | // without a size_t argument, but prefers a non-member operator delete | |||
2565 | // with a size_t where possible (which it always is in this case). | |||
2566 | llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; | |||
2567 | UsualDeallocFnInfo Selected = resolveDeallocationOverload( | |||
2568 | *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, | |||
2569 | /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), | |||
2570 | &BestDeallocFns); | |||
2571 | if (Selected) | |||
2572 | Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); | |||
2573 | else { | |||
2574 | // If we failed to select an operator, all remaining functions are viable | |||
2575 | // but ambiguous. | |||
2576 | for (auto Fn : BestDeallocFns) | |||
2577 | Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); | |||
2578 | } | |||
2579 | } | |||
2580 | ||||
2581 | // C++ [expr.new]p20: | |||
2582 | // [...] If the lookup finds a single matching deallocation | |||
2583 | // function, that function will be called; otherwise, no | |||
2584 | // deallocation function will be called. | |||
2585 | if (Matches.size() == 1) { | |||
2586 | OperatorDelete = Matches[0].second; | |||
2587 | ||||
2588 | // C++1z [expr.new]p23: | |||
2589 | // If the lookup finds a usual deallocation function (3.7.4.2) | |||
2590 | // with a parameter of type std::size_t and that function, considered | |||
2591 | // as a placement deallocation function, would have been | |||
2592 | // selected as a match for the allocation function, the program | |||
2593 | // is ill-formed. | |||
2594 | if (getLangOpts().CPlusPlus11 && isPlacementNew && | |||
2595 | isNonPlacementDeallocationFunction(*this, OperatorDelete)) { | |||
2596 | UsualDeallocFnInfo Info(*this, | |||
2597 | DeclAccessPair::make(OperatorDelete, AS_public)); | |||
2598 | // Core issue, per mail to core reflector, 2016-10-09: | |||
2599 | // If this is a member operator delete, and there is a corresponding | |||
2600 | // non-sized member operator delete, this isn't /really/ a sized | |||
2601 | // deallocation function, it just happens to have a size_t parameter. | |||
2602 | bool IsSizedDelete = Info.HasSizeT; | |||
2603 | if (IsSizedDelete && !FoundGlobalDelete) { | |||
2604 | auto NonSizedDelete = | |||
2605 | resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, | |||
2606 | /*WantAlign*/Info.HasAlignValT); | |||
2607 | if (NonSizedDelete && !NonSizedDelete.HasSizeT && | |||
2608 | NonSizedDelete.HasAlignValT == Info.HasAlignValT) | |||
2609 | IsSizedDelete = false; | |||
2610 | } | |||
2611 | ||||
2612 | if (IsSizedDelete) { | |||
2613 | SourceRange R = PlaceArgs.empty() | |||
2614 | ? SourceRange() | |||
2615 | : SourceRange(PlaceArgs.front()->getBeginLoc(), | |||
2616 | PlaceArgs.back()->getEndLoc()); | |||
2617 | Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; | |||
2618 | if (!OperatorDelete->isImplicit()) | |||
2619 | Diag(OperatorDelete->getLocation(), diag::note_previous_decl) | |||
2620 | << DeleteName; | |||
2621 | } | |||
2622 | } | |||
2623 | ||||
2624 | CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), | |||
2625 | Matches[0].first); | |||
2626 | } else if (!Matches.empty()) { | |||
2627 | // We found multiple suitable operators. Per [expr.new]p20, that means we | |||
2628 | // call no 'operator delete' function, but we should at least warn the user. | |||
2629 | // FIXME: Suppress this warning if the construction cannot throw. | |||
2630 | Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) | |||
2631 | << DeleteName << AllocElemType; | |||
2632 | ||||
2633 | for (auto &Match : Matches) | |||
2634 | Diag(Match.second->getLocation(), | |||
2635 | diag::note_member_declared_here) << DeleteName; | |||
2636 | } | |||
2637 | ||||
2638 | return false; | |||
2639 | } | |||
2640 | ||||
2641 | /// DeclareGlobalNewDelete - Declare the global forms of operator new and | |||
2642 | /// delete. These are: | |||
2643 | /// @code | |||
2644 | /// // C++03: | |||
2645 | /// void* operator new(std::size_t) throw(std::bad_alloc); | |||
2646 | /// void* operator new[](std::size_t) throw(std::bad_alloc); | |||
2647 | /// void operator delete(void *) throw(); | |||
2648 | /// void operator delete[](void *) throw(); | |||
2649 | /// // C++11: | |||
2650 | /// void* operator new(std::size_t); | |||
2651 | /// void* operator new[](std::size_t); | |||
2652 | /// void operator delete(void *) noexcept; | |||
2653 | /// void operator delete[](void *) noexcept; | |||
2654 | /// // C++1y: | |||
2655 | /// void* operator new(std::size_t); | |||
2656 | /// void* operator new[](std::size_t); | |||
2657 | /// void operator delete(void *) noexcept; | |||
2658 | /// void operator delete[](void *) noexcept; | |||
2659 | /// void operator delete(void *, std::size_t) noexcept; | |||
2660 | /// void operator delete[](void *, std::size_t) noexcept; | |||
2661 | /// @endcode | |||
2662 | /// Note that the placement and nothrow forms of new are *not* implicitly | |||
2663 | /// declared. Their use requires including \<new\>. | |||
2664 | void Sema::DeclareGlobalNewDelete() { | |||
2665 | if (GlobalNewDeleteDeclared) | |||
2666 | return; | |||
2667 | ||||
2668 | // The implicitly declared new and delete operators | |||
2669 | // are not supported in OpenCL. | |||
2670 | if (getLangOpts().OpenCLCPlusPlus) | |||
2671 | return; | |||
2672 | ||||
2673 | // C++ [basic.std.dynamic]p2: | |||
2674 | // [...] The following allocation and deallocation functions (18.4) are | |||
2675 | // implicitly declared in global scope in each translation unit of a | |||
2676 | // program | |||
2677 | // | |||
2678 | // C++03: | |||
2679 | // void* operator new(std::size_t) throw(std::bad_alloc); | |||
2680 | // void* operator new[](std::size_t) throw(std::bad_alloc); | |||
2681 | // void operator delete(void*) throw(); | |||
2682 | // void operator delete[](void*) throw(); | |||
2683 | // C++11: | |||
2684 | // void* operator new(std::size_t); | |||
2685 | // void* operator new[](std::size_t); | |||
2686 | // void operator delete(void*) noexcept; | |||
2687 | // void operator delete[](void*) noexcept; | |||
2688 | // C++1y: | |||
2689 | // void* operator new(std::size_t); | |||
2690 | // void* operator new[](std::size_t); | |||
2691 | // void operator delete(void*) noexcept; | |||
2692 | // void operator delete[](void*) noexcept; | |||
2693 | // void operator delete(void*, std::size_t) noexcept; | |||
2694 | // void operator delete[](void*, std::size_t) noexcept; | |||
2695 | // | |||
2696 | // These implicit declarations introduce only the function names operator | |||
2697 | // new, operator new[], operator delete, operator delete[]. | |||
2698 | // | |||
2699 | // Here, we need to refer to std::bad_alloc, so we will implicitly declare | |||
2700 | // "std" or "bad_alloc" as necessary to form the exception specification. | |||
2701 | // However, we do not make these implicit declarations visible to name | |||
2702 | // lookup. | |||
2703 | if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { | |||
2704 | // The "std::bad_alloc" class has not yet been declared, so build it | |||
2705 | // implicitly. | |||
2706 | StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, | |||
2707 | getOrCreateStdNamespace(), | |||
2708 | SourceLocation(), SourceLocation(), | |||
2709 | &PP.getIdentifierTable().get("bad_alloc"), | |||
2710 | nullptr); | |||
2711 | getStdBadAlloc()->setImplicit(true); | |||
2712 | } | |||
2713 | if (!StdAlignValT && getLangOpts().AlignedAllocation) { | |||
2714 | // The "std::align_val_t" enum class has not yet been declared, so build it | |||
2715 | // implicitly. | |||
2716 | auto *AlignValT = EnumDecl::Create( | |||
2717 | Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), | |||
2718 | &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); | |||
2719 | AlignValT->setIntegerType(Context.getSizeType()); | |||
2720 | AlignValT->setPromotionType(Context.getSizeType()); | |||
2721 | AlignValT->setImplicit(true); | |||
2722 | StdAlignValT = AlignValT; | |||
2723 | } | |||
2724 | ||||
2725 | GlobalNewDeleteDeclared = true; | |||
2726 | ||||
2727 | QualType VoidPtr = Context.getPointerType(Context.VoidTy); | |||
2728 | QualType SizeT = Context.getSizeType(); | |||
2729 | ||||
2730 | auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, | |||
2731 | QualType Return, QualType Param) { | |||
2732 | llvm::SmallVector<QualType, 3> Params; | |||
2733 | Params.push_back(Param); | |||
2734 | ||||
2735 | // Create up to four variants of the function (sized/aligned). | |||
2736 | bool HasSizedVariant = getLangOpts().SizedDeallocation && | |||
2737 | (Kind == OO_Delete || Kind == OO_Array_Delete); | |||
2738 | bool HasAlignedVariant = getLangOpts().AlignedAllocation; | |||
2739 | ||||
2740 | int NumSizeVariants = (HasSizedVariant ? 2 : 1); | |||
2741 | int NumAlignVariants = (HasAlignedVariant ? 2 : 1); | |||
2742 | for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { | |||
2743 | if (Sized) | |||
2744 | Params.push_back(SizeT); | |||
2745 | ||||
2746 | for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { | |||
2747 | if (Aligned) | |||
2748 | Params.push_back(Context.getTypeDeclType(getStdAlignValT())); | |||
2749 | ||||
2750 | DeclareGlobalAllocationFunction( | |||
2751 | Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); | |||
2752 | ||||
2753 | if (Aligned) | |||
2754 | Params.pop_back(); | |||
2755 | } | |||
2756 | } | |||
2757 | }; | |||
2758 | ||||
2759 | DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); | |||
2760 | DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); | |||
2761 | DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); | |||
2762 | DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); | |||
2763 | } | |||
2764 | ||||
2765 | /// DeclareGlobalAllocationFunction - Declares a single implicit global | |||
2766 | /// allocation function if it doesn't already exist. | |||
2767 | void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, | |||
2768 | QualType Return, | |||
2769 | ArrayRef<QualType> Params) { | |||
2770 | DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); | |||
2771 | ||||
2772 | // Check if this function is already declared. | |||
2773 | DeclContext::lookup_result R = GlobalCtx->lookup(Name); | |||
2774 | for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); | |||
2775 | Alloc != AllocEnd; ++Alloc) { | |||
2776 | // Only look at non-template functions, as it is the predefined, | |||
2777 | // non-templated allocation function we are trying to declare here. | |||
2778 | if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { | |||
2779 | if (Func->getNumParams() == Params.size()) { | |||
2780 | llvm::SmallVector<QualType, 3> FuncParams; | |||
2781 | for (auto *P : Func->parameters()) | |||
2782 | FuncParams.push_back( | |||
2783 | Context.getCanonicalType(P->getType().getUnqualifiedType())); | |||
2784 | if (llvm::makeArrayRef(FuncParams) == Params) { | |||
2785 | // Make the function visible to name lookup, even if we found it in | |||
2786 | // an unimported module. It either is an implicitly-declared global | |||
2787 | // allocation function, or is suppressing that function. | |||
2788 | Func->setVisibleDespiteOwningModule(); | |||
2789 | return; | |||
2790 | } | |||
2791 | } | |||
2792 | } | |||
2793 | } | |||
2794 | ||||
2795 | FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( | |||
2796 | /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); | |||
2797 | ||||
2798 | QualType BadAllocType; | |||
2799 | bool HasBadAllocExceptionSpec | |||
2800 | = (Name.getCXXOverloadedOperator() == OO_New || | |||
2801 | Name.getCXXOverloadedOperator() == OO_Array_New); | |||
2802 | if (HasBadAllocExceptionSpec) { | |||
2803 | if (!getLangOpts().CPlusPlus11) { | |||
2804 | BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); | |||
2805 | assert(StdBadAlloc && "Must have std::bad_alloc declared")((StdBadAlloc && "Must have std::bad_alloc declared") ? static_cast<void> (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 2805, __PRETTY_FUNCTION__)); | |||
2806 | EPI.ExceptionSpec.Type = EST_Dynamic; | |||
2807 | EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType); | |||
2808 | } | |||
2809 | } else { | |||
2810 | EPI.ExceptionSpec = | |||
2811 | getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; | |||
2812 | } | |||
2813 | ||||
2814 | auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { | |||
2815 | QualType FnType = Context.getFunctionType(Return, Params, EPI); | |||
2816 | FunctionDecl *Alloc = FunctionDecl::Create( | |||
2817 | Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, | |||
2818 | FnType, /*TInfo=*/nullptr, SC_None, false, true); | |||
2819 | Alloc->setImplicit(); | |||
2820 | // Global allocation functions should always be visible. | |||
2821 | Alloc->setVisibleDespiteOwningModule(); | |||
2822 | ||||
2823 | Alloc->addAttr(VisibilityAttr::CreateImplicit( | |||
2824 | Context, LangOpts.GlobalAllocationFunctionVisibilityHidden | |||
2825 | ? VisibilityAttr::Hidden | |||
2826 | : VisibilityAttr::Default)); | |||
2827 | ||||
2828 | llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; | |||
2829 | for (QualType T : Params) { | |||
2830 | ParamDecls.push_back(ParmVarDecl::Create( | |||
2831 | Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, | |||
2832 | /*TInfo=*/nullptr, SC_None, nullptr)); | |||
2833 | ParamDecls.back()->setImplicit(); | |||
2834 | } | |||
2835 | Alloc->setParams(ParamDecls); | |||
2836 | if (ExtraAttr) | |||
2837 | Alloc->addAttr(ExtraAttr); | |||
2838 | Context.getTranslationUnitDecl()->addDecl(Alloc); | |||
2839 | IdResolver.tryAddTopLevelDecl(Alloc, Name); | |||
2840 | }; | |||
2841 | ||||
2842 | if (!LangOpts.CUDA) | |||
2843 | CreateAllocationFunctionDecl(nullptr); | |||
2844 | else { | |||
2845 | // Host and device get their own declaration so each can be | |||
2846 | // defined or re-declared independently. | |||
2847 | CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); | |||
2848 | CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); | |||
2849 | } | |||
2850 | } | |||
2851 | ||||
2852 | FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, | |||
2853 | bool CanProvideSize, | |||
2854 | bool Overaligned, | |||
2855 | DeclarationName Name) { | |||
2856 | DeclareGlobalNewDelete(); | |||
2857 | ||||
2858 | LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); | |||
2859 | LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); | |||
2860 | ||||
2861 | // FIXME: It's possible for this to result in ambiguity, through a | |||
2862 | // user-declared variadic operator delete or the enable_if attribute. We | |||
2863 | // should probably not consider those cases to be usual deallocation | |||
2864 | // functions. But for now we just make an arbitrary choice in that case. | |||
2865 | auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, | |||
2866 | Overaligned); | |||
2867 | assert(Result.FD && "operator delete missing from global scope?")((Result.FD && "operator delete missing from global scope?" ) ? static_cast<void> (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 2867, __PRETTY_FUNCTION__)); | |||
2868 | return Result.FD; | |||
2869 | } | |||
2870 | ||||
2871 | FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, | |||
2872 | CXXRecordDecl *RD) { | |||
2873 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); | |||
2874 | ||||
2875 | FunctionDecl *OperatorDelete = nullptr; | |||
2876 | if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) | |||
2877 | return nullptr; | |||
2878 | if (OperatorDelete) | |||
2879 | return OperatorDelete; | |||
2880 | ||||
2881 | // If there's no class-specific operator delete, look up the global | |||
2882 | // non-array delete. | |||
2883 | return FindUsualDeallocationFunction( | |||
2884 | Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), | |||
2885 | Name); | |||
2886 | } | |||
2887 | ||||
2888 | bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, | |||
2889 | DeclarationName Name, | |||
2890 | FunctionDecl *&Operator, bool Diagnose) { | |||
2891 | LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); | |||
2892 | // Try to find operator delete/operator delete[] in class scope. | |||
2893 | LookupQualifiedName(Found, RD); | |||
2894 | ||||
2895 | if (Found.isAmbiguous()) | |||
2896 | return true; | |||
2897 | ||||
2898 | Found.suppressDiagnostics(); | |||
2899 | ||||
2900 | bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD)); | |||
2901 | ||||
2902 | // C++17 [expr.delete]p10: | |||
2903 | // If the deallocation functions have class scope, the one without a | |||
2904 | // parameter of type std::size_t is selected. | |||
2905 | llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; | |||
2906 | resolveDeallocationOverload(*this, Found, /*WantSize*/ false, | |||
2907 | /*WantAlign*/ Overaligned, &Matches); | |||
2908 | ||||
2909 | // If we could find an overload, use it. | |||
2910 | if (Matches.size() == 1) { | |||
2911 | Operator = cast<CXXMethodDecl>(Matches[0].FD); | |||
2912 | ||||
2913 | // FIXME: DiagnoseUseOfDecl? | |||
2914 | if (Operator->isDeleted()) { | |||
2915 | if (Diagnose) { | |||
2916 | Diag(StartLoc, diag::err_deleted_function_use); | |||
2917 | NoteDeletedFunction(Operator); | |||
2918 | } | |||
2919 | return true; | |||
2920 | } | |||
2921 | ||||
2922 | if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), | |||
2923 | Matches[0].Found, Diagnose) == AR_inaccessible) | |||
2924 | return true; | |||
2925 | ||||
2926 | return false; | |||
2927 | } | |||
2928 | ||||
2929 | // We found multiple suitable operators; complain about the ambiguity. | |||
2930 | // FIXME: The standard doesn't say to do this; it appears that the intent | |||
2931 | // is that this should never happen. | |||
2932 | if (!Matches.empty()) { | |||
2933 | if (Diagnose) { | |||
2934 | Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) | |||
2935 | << Name << RD; | |||
2936 | for (auto &Match : Matches) | |||
2937 | Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; | |||
2938 | } | |||
2939 | return true; | |||
2940 | } | |||
2941 | ||||
2942 | // We did find operator delete/operator delete[] declarations, but | |||
2943 | // none of them were suitable. | |||
2944 | if (!Found.empty()) { | |||
2945 | if (Diagnose) { | |||
2946 | Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) | |||
2947 | << Name << RD; | |||
2948 | ||||
2949 | for (NamedDecl *D : Found) | |||
2950 | Diag(D->getUnderlyingDecl()->getLocation(), | |||
2951 | diag::note_member_declared_here) << Name; | |||
2952 | } | |||
2953 | return true; | |||
2954 | } | |||
2955 | ||||
2956 | Operator = nullptr; | |||
2957 | return false; | |||
2958 | } | |||
2959 | ||||
2960 | namespace { | |||
2961 | /// Checks whether delete-expression, and new-expression used for | |||
2962 | /// initializing deletee have the same array form. | |||
2963 | class MismatchingNewDeleteDetector { | |||
2964 | public: | |||
2965 | enum MismatchResult { | |||
2966 | /// Indicates that there is no mismatch or a mismatch cannot be proven. | |||
2967 | NoMismatch, | |||
2968 | /// Indicates that variable is initialized with mismatching form of \a new. | |||
2969 | VarInitMismatches, | |||
2970 | /// Indicates that member is initialized with mismatching form of \a new. | |||
2971 | MemberInitMismatches, | |||
2972 | /// Indicates that 1 or more constructors' definitions could not been | |||
2973 | /// analyzed, and they will be checked again at the end of translation unit. | |||
2974 | AnalyzeLater | |||
2975 | }; | |||
2976 | ||||
2977 | /// \param EndOfTU True, if this is the final analysis at the end of | |||
2978 | /// translation unit. False, if this is the initial analysis at the point | |||
2979 | /// delete-expression was encountered. | |||
2980 | explicit MismatchingNewDeleteDetector(bool EndOfTU) | |||
2981 | : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), | |||
2982 | HasUndefinedConstructors(false) {} | |||
2983 | ||||
2984 | /// Checks whether pointee of a delete-expression is initialized with | |||
2985 | /// matching form of new-expression. | |||
2986 | /// | |||
2987 | /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the | |||
2988 | /// point where delete-expression is encountered, then a warning will be | |||
2989 | /// issued immediately. If return value is \c AnalyzeLater at the point where | |||
2990 | /// delete-expression is seen, then member will be analyzed at the end of | |||
2991 | /// translation unit. \c AnalyzeLater is returned iff at least one constructor | |||
2992 | /// couldn't be analyzed. If at least one constructor initializes the member | |||
2993 | /// with matching type of new, the return value is \c NoMismatch. | |||
2994 | MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); | |||
2995 | /// Analyzes a class member. | |||
2996 | /// \param Field Class member to analyze. | |||
2997 | /// \param DeleteWasArrayForm Array form-ness of the delete-expression used | |||
2998 | /// for deleting the \p Field. | |||
2999 | MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); | |||
3000 | FieldDecl *Field; | |||
3001 | /// List of mismatching new-expressions used for initialization of the pointee | |||
3002 | llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; | |||
3003 | /// Indicates whether delete-expression was in array form. | |||
3004 | bool IsArrayForm; | |||
3005 | ||||
3006 | private: | |||
3007 | const bool EndOfTU; | |||
3008 | /// Indicates that there is at least one constructor without body. | |||
3009 | bool HasUndefinedConstructors; | |||
3010 | /// Returns \c CXXNewExpr from given initialization expression. | |||
3011 | /// \param E Expression used for initializing pointee in delete-expression. | |||
3012 | /// E can be a single-element \c InitListExpr consisting of new-expression. | |||
3013 | const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); | |||
3014 | /// Returns whether member is initialized with mismatching form of | |||
3015 | /// \c new either by the member initializer or in-class initialization. | |||
3016 | /// | |||
3017 | /// If bodies of all constructors are not visible at the end of translation | |||
3018 | /// unit or at least one constructor initializes member with the matching | |||
3019 | /// form of \c new, mismatch cannot be proven, and this function will return | |||
3020 | /// \c NoMismatch. | |||
3021 | MismatchResult analyzeMemberExpr(const MemberExpr *ME); | |||
3022 | /// Returns whether variable is initialized with mismatching form of | |||
3023 | /// \c new. | |||
3024 | /// | |||
3025 | /// If variable is initialized with matching form of \c new or variable is not | |||
3026 | /// initialized with a \c new expression, this function will return true. | |||
3027 | /// If variable is initialized with mismatching form of \c new, returns false. | |||
3028 | /// \param D Variable to analyze. | |||
3029 | bool hasMatchingVarInit(const DeclRefExpr *D); | |||
3030 | /// Checks whether the constructor initializes pointee with mismatching | |||
3031 | /// form of \c new. | |||
3032 | /// | |||
3033 | /// Returns true, if member is initialized with matching form of \c new in | |||
3034 | /// member initializer list. Returns false, if member is initialized with the | |||
3035 | /// matching form of \c new in this constructor's initializer or given | |||
3036 | /// constructor isn't defined at the point where delete-expression is seen, or | |||
3037 | /// member isn't initialized by the constructor. | |||
3038 | bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); | |||
3039 | /// Checks whether member is initialized with matching form of | |||
3040 | /// \c new in member initializer list. | |||
3041 | bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); | |||
3042 | /// Checks whether member is initialized with mismatching form of \c new by | |||
3043 | /// in-class initializer. | |||
3044 | MismatchResult analyzeInClassInitializer(); | |||
3045 | }; | |||
3046 | } | |||
3047 | ||||
3048 | MismatchingNewDeleteDetector::MismatchResult | |||
3049 | MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { | |||
3050 | NewExprs.clear(); | |||
3051 | assert(DE && "Expected delete-expression")((DE && "Expected delete-expression") ? static_cast< void> (0) : __assert_fail ("DE && \"Expected delete-expression\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3051, __PRETTY_FUNCTION__)); | |||
3052 | IsArrayForm = DE->isArrayForm(); | |||
3053 | const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); | |||
3054 | if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { | |||
3055 | return analyzeMemberExpr(ME); | |||
3056 | } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { | |||
3057 | if (!hasMatchingVarInit(D)) | |||
3058 | return VarInitMismatches; | |||
3059 | } | |||
3060 | return NoMismatch; | |||
3061 | } | |||
3062 | ||||
3063 | const CXXNewExpr * | |||
3064 | MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { | |||
3065 | assert(E != nullptr && "Expected a valid initializer expression")((E != nullptr && "Expected a valid initializer expression" ) ? static_cast<void> (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3065, __PRETTY_FUNCTION__)); | |||
3066 | E = E->IgnoreParenImpCasts(); | |||
3067 | if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { | |||
3068 | if (ILE->getNumInits() == 1) | |||
3069 | E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); | |||
3070 | } | |||
3071 | ||||
3072 | return dyn_cast_or_null<const CXXNewExpr>(E); | |||
3073 | } | |||
3074 | ||||
3075 | bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( | |||
3076 | const CXXCtorInitializer *CI) { | |||
3077 | const CXXNewExpr *NE = nullptr; | |||
3078 | if (Field == CI->getMember() && | |||
3079 | (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { | |||
3080 | if (NE->isArray() == IsArrayForm) | |||
3081 | return true; | |||
3082 | else | |||
3083 | NewExprs.push_back(NE); | |||
3084 | } | |||
3085 | return false; | |||
3086 | } | |||
3087 | ||||
3088 | bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( | |||
3089 | const CXXConstructorDecl *CD) { | |||
3090 | if (CD->isImplicit()) | |||
3091 | return false; | |||
3092 | const FunctionDecl *Definition = CD; | |||
3093 | if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { | |||
3094 | HasUndefinedConstructors = true; | |||
3095 | return EndOfTU; | |||
3096 | } | |||
3097 | for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { | |||
3098 | if (hasMatchingNewInCtorInit(CI)) | |||
3099 | return true; | |||
3100 | } | |||
3101 | return false; | |||
3102 | } | |||
3103 | ||||
3104 | MismatchingNewDeleteDetector::MismatchResult | |||
3105 | MismatchingNewDeleteDetector::analyzeInClassInitializer() { | |||
3106 | assert(Field != nullptr && "This should be called only for members")((Field != nullptr && "This should be called only for members" ) ? static_cast<void> (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3106, __PRETTY_FUNCTION__)); | |||
3107 | const Expr *InitExpr = Field->getInClassInitializer(); | |||
3108 | if (!InitExpr) | |||
3109 | return EndOfTU ? NoMismatch : AnalyzeLater; | |||
3110 | if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { | |||
3111 | if (NE->isArray() != IsArrayForm) { | |||
3112 | NewExprs.push_back(NE); | |||
3113 | return MemberInitMismatches; | |||
3114 | } | |||
3115 | } | |||
3116 | return NoMismatch; | |||
3117 | } | |||
3118 | ||||
3119 | MismatchingNewDeleteDetector::MismatchResult | |||
3120 | MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, | |||
3121 | bool DeleteWasArrayForm) { | |||
3122 | assert(Field != nullptr && "Analysis requires a valid class member.")((Field != nullptr && "Analysis requires a valid class member." ) ? static_cast<void> (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3122, __PRETTY_FUNCTION__)); | |||
3123 | this->Field = Field; | |||
3124 | IsArrayForm = DeleteWasArrayForm; | |||
3125 | const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); | |||
3126 | for (const auto *CD : RD->ctors()) { | |||
3127 | if (hasMatchingNewInCtor(CD)) | |||
3128 | return NoMismatch; | |||
3129 | } | |||
3130 | if (HasUndefinedConstructors) | |||
3131 | return EndOfTU ? NoMismatch : AnalyzeLater; | |||
3132 | if (!NewExprs.empty()) | |||
3133 | return MemberInitMismatches; | |||
3134 | return Field->hasInClassInitializer() ? analyzeInClassInitializer() | |||
3135 | : NoMismatch; | |||
3136 | } | |||
3137 | ||||
3138 | MismatchingNewDeleteDetector::MismatchResult | |||
3139 | MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { | |||
3140 | assert(ME != nullptr && "Expected a member expression")((ME != nullptr && "Expected a member expression") ? static_cast <void> (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3140, __PRETTY_FUNCTION__)); | |||
3141 | if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) | |||
3142 | return analyzeField(F, IsArrayForm); | |||
3143 | return NoMismatch; | |||
3144 | } | |||
3145 | ||||
3146 | bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { | |||
3147 | const CXXNewExpr *NE = nullptr; | |||
3148 | if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { | |||
3149 | if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && | |||
3150 | NE->isArray() != IsArrayForm) { | |||
3151 | NewExprs.push_back(NE); | |||
3152 | } | |||
3153 | } | |||
3154 | return NewExprs.empty(); | |||
3155 | } | |||
3156 | ||||
3157 | static void | |||
3158 | DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, | |||
3159 | const MismatchingNewDeleteDetector &Detector) { | |||
3160 | SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); | |||
3161 | FixItHint H; | |||
3162 | if (!Detector.IsArrayForm) | |||
3163 | H = FixItHint::CreateInsertion(EndOfDelete, "[]"); | |||
3164 | else { | |||
3165 | SourceLocation RSquare = Lexer::findLocationAfterToken( | |||
3166 | DeleteLoc, tok::l_square, SemaRef.getSourceManager(), | |||
3167 | SemaRef.getLangOpts(), true); | |||
3168 | if (RSquare.isValid()) | |||
3169 | H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); | |||
3170 | } | |||
3171 | SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) | |||
3172 | << Detector.IsArrayForm << H; | |||
3173 | ||||
3174 | for (const auto *NE : Detector.NewExprs) | |||
3175 | SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) | |||
3176 | << Detector.IsArrayForm; | |||
3177 | } | |||
3178 | ||||
3179 | void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { | |||
3180 | if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) | |||
3181 | return; | |||
3182 | MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); | |||
3183 | switch (Detector.analyzeDeleteExpr(DE)) { | |||
3184 | case MismatchingNewDeleteDetector::VarInitMismatches: | |||
3185 | case MismatchingNewDeleteDetector::MemberInitMismatches: { | |||
3186 | DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); | |||
3187 | break; | |||
3188 | } | |||
3189 | case MismatchingNewDeleteDetector::AnalyzeLater: { | |||
3190 | DeleteExprs[Detector.Field].push_back( | |||
3191 | std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); | |||
3192 | break; | |||
3193 | } | |||
3194 | case MismatchingNewDeleteDetector::NoMismatch: | |||
3195 | break; | |||
3196 | } | |||
3197 | } | |||
3198 | ||||
3199 | void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, | |||
3200 | bool DeleteWasArrayForm) { | |||
3201 | MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); | |||
3202 | switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { | |||
3203 | case MismatchingNewDeleteDetector::VarInitMismatches: | |||
3204 | llvm_unreachable("This analysis should have been done for class members.")::llvm::llvm_unreachable_internal("This analysis should have been done for class members." , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3204); | |||
3205 | case MismatchingNewDeleteDetector::AnalyzeLater: | |||
3206 | llvm_unreachable("Analysis cannot be postponed any point beyond end of "::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of " "translation unit.", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3207) | |||
3207 | "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of " "translation unit.", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3207); | |||
3208 | case MismatchingNewDeleteDetector::MemberInitMismatches: | |||
3209 | DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); | |||
3210 | break; | |||
3211 | case MismatchingNewDeleteDetector::NoMismatch: | |||
3212 | break; | |||
3213 | } | |||
3214 | } | |||
3215 | ||||
3216 | /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: | |||
3217 | /// @code ::delete ptr; @endcode | |||
3218 | /// or | |||
3219 | /// @code delete [] ptr; @endcode | |||
3220 | ExprResult | |||
3221 | Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, | |||
3222 | bool ArrayForm, Expr *ExE) { | |||
3223 | // C++ [expr.delete]p1: | |||
3224 | // The operand shall have a pointer type, or a class type having a single | |||
3225 | // non-explicit conversion function to a pointer type. The result has type | |||
3226 | // void. | |||
3227 | // | |||
3228 | // DR599 amends "pointer type" to "pointer to object type" in both cases. | |||
3229 | ||||
3230 | ExprResult Ex = ExE; | |||
3231 | FunctionDecl *OperatorDelete = nullptr; | |||
3232 | bool ArrayFormAsWritten = ArrayForm; | |||
3233 | bool UsualArrayDeleteWantsSize = false; | |||
3234 | ||||
3235 | if (!Ex.get()->isTypeDependent()) { | |||
| ||||
3236 | // Perform lvalue-to-rvalue cast, if needed. | |||
3237 | Ex = DefaultLvalueConversion(Ex.get()); | |||
3238 | if (Ex.isInvalid()) | |||
3239 | return ExprError(); | |||
3240 | ||||
3241 | QualType Type = Ex.get()->getType(); | |||
3242 | ||||
3243 | class DeleteConverter : public ContextualImplicitConverter { | |||
3244 | public: | |||
3245 | DeleteConverter() : ContextualImplicitConverter(false, true) {} | |||
3246 | ||||
3247 | bool match(QualType ConvType) override { | |||
3248 | // FIXME: If we have an operator T* and an operator void*, we must pick | |||
3249 | // the operator T*. | |||
3250 | if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) | |||
3251 | if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) | |||
3252 | return true; | |||
3253 | return false; | |||
3254 | } | |||
3255 | ||||
3256 | SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, | |||
3257 | QualType T) override { | |||
3258 | return S.Diag(Loc, diag::err_delete_operand) << T; | |||
3259 | } | |||
3260 | ||||
3261 | SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, | |||
3262 | QualType T) override { | |||
3263 | return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; | |||
3264 | } | |||
3265 | ||||
3266 | SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, | |||
3267 | QualType T, | |||
3268 | QualType ConvTy) override { | |||
3269 | return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; | |||
3270 | } | |||
3271 | ||||
3272 | SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, | |||
3273 | QualType ConvTy) override { | |||
3274 | return S.Diag(Conv->getLocation(), diag::note_delete_conversion) | |||
3275 | << ConvTy; | |||
3276 | } | |||
3277 | ||||
3278 | SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, | |||
3279 | QualType T) override { | |||
3280 | return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; | |||
3281 | } | |||
3282 | ||||
3283 | SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, | |||
3284 | QualType ConvTy) override { | |||
3285 | return S.Diag(Conv->getLocation(), diag::note_delete_conversion) | |||
3286 | << ConvTy; | |||
3287 | } | |||
3288 | ||||
3289 | SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, | |||
3290 | QualType T, | |||
3291 | QualType ConvTy) override { | |||
3292 | llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3292); | |||
3293 | } | |||
3294 | } Converter; | |||
3295 | ||||
3296 | Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); | |||
3297 | if (Ex.isInvalid()) | |||
3298 | return ExprError(); | |||
3299 | Type = Ex.get()->getType(); | |||
3300 | if (!Converter.match(Type)) | |||
3301 | // FIXME: PerformContextualImplicitConversion should return ExprError | |||
3302 | // itself in this case. | |||
3303 | return ExprError(); | |||
3304 | ||||
3305 | QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); | |||
| ||||
3306 | QualType PointeeElem = Context.getBaseElementType(Pointee); | |||
3307 | ||||
3308 | if (Pointee.getAddressSpace() != LangAS::Default && | |||
3309 | !getLangOpts().OpenCLCPlusPlus) | |||
3310 | return Diag(Ex.get()->getBeginLoc(), | |||
3311 | diag::err_address_space_qualified_delete) | |||
3312 | << Pointee.getUnqualifiedType() | |||
3313 | << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); | |||
3314 | ||||
3315 | CXXRecordDecl *PointeeRD = nullptr; | |||
3316 | if (Pointee->isVoidType() && !isSFINAEContext()) { | |||
3317 | // The C++ standard bans deleting a pointer to a non-object type, which | |||
3318 | // effectively bans deletion of "void*". However, most compilers support | |||
3319 | // this, so we treat it as a warning unless we're in a SFINAE context. | |||
3320 | Diag(StartLoc, diag::ext_delete_void_ptr_operand) | |||
3321 | << Type << Ex.get()->getSourceRange(); | |||
3322 | } else if (Pointee->isFunctionType() || Pointee->isVoidType()) { | |||
3323 | return ExprError(Diag(StartLoc, diag::err_delete_operand) | |||
3324 | << Type << Ex.get()->getSourceRange()); | |||
3325 | } else if (!Pointee->isDependentType()) { | |||
3326 | // FIXME: This can result in errors if the definition was imported from a | |||
3327 | // module but is hidden. | |||
3328 | if (!RequireCompleteType(StartLoc, Pointee, | |||
3329 | diag::warn_delete_incomplete, Ex.get())) { | |||
3330 | if (const RecordType *RT = PointeeElem->getAs<RecordType>()) | |||
3331 | PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); | |||
3332 | } | |||
3333 | } | |||
3334 | ||||
3335 | if (Pointee->isArrayType() && !ArrayForm) { | |||
3336 | Diag(StartLoc, diag::warn_delete_array_type) | |||
3337 | << Type << Ex.get()->getSourceRange() | |||
3338 | << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); | |||
3339 | ArrayForm = true; | |||
3340 | } | |||
3341 | ||||
3342 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( | |||
3343 | ArrayForm ? OO_Array_Delete : OO_Delete); | |||
3344 | ||||
3345 | if (PointeeRD) { | |||
3346 | if (!UseGlobal && | |||
3347 | FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, | |||
3348 | OperatorDelete)) | |||
3349 | return ExprError(); | |||
3350 | ||||
3351 | // If we're allocating an array of records, check whether the | |||
3352 | // usual operator delete[] has a size_t parameter. | |||
3353 | if (ArrayForm) { | |||
3354 | // If the user specifically asked to use the global allocator, | |||
3355 | // we'll need to do the lookup into the class. | |||
3356 | if (UseGlobal) | |||
3357 | UsualArrayDeleteWantsSize = | |||
3358 | doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); | |||
3359 | ||||
3360 | // Otherwise, the usual operator delete[] should be the | |||
3361 | // function we just found. | |||
3362 | else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) | |||
3363 | UsualArrayDeleteWantsSize = | |||
3364 | UsualDeallocFnInfo(*this, | |||
3365 | DeclAccessPair::make(OperatorDelete, AS_public)) | |||
3366 | .HasSizeT; | |||
3367 | } | |||
3368 | ||||
3369 | if (!PointeeRD->hasIrrelevantDestructor()) | |||
3370 | if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { | |||
3371 | MarkFunctionReferenced(StartLoc, | |||
3372 | const_cast<CXXDestructorDecl*>(Dtor)); | |||
3373 | if (DiagnoseUseOfDecl(Dtor, StartLoc)) | |||
3374 | return ExprError(); | |||
3375 | } | |||
3376 | ||||
3377 | CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, | |||
3378 | /*IsDelete=*/true, /*CallCanBeVirtual=*/true, | |||
3379 | /*WarnOnNonAbstractTypes=*/!ArrayForm, | |||
3380 | SourceLocation()); | |||
3381 | } | |||
3382 | ||||
3383 | if (!OperatorDelete) { | |||
3384 | if (getLangOpts().OpenCLCPlusPlus) { | |||
3385 | Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; | |||
3386 | return ExprError(); | |||
3387 | } | |||
3388 | ||||
3389 | bool IsComplete = isCompleteType(StartLoc, Pointee); | |||
3390 | bool CanProvideSize = | |||
3391 | IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || | |||
3392 | Pointee.isDestructedType()); | |||
3393 | bool Overaligned = hasNewExtendedAlignment(*this, Pointee); | |||
3394 | ||||
3395 | // Look for a global declaration. | |||
3396 | OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, | |||
3397 | Overaligned, DeleteName); | |||
3398 | } | |||
3399 | ||||
3400 | MarkFunctionReferenced(StartLoc, OperatorDelete); | |||
3401 | ||||
3402 | // Check access and ambiguity of destructor if we're going to call it. | |||
3403 | // Note that this is required even for a virtual delete. | |||
3404 | bool IsVirtualDelete = false; | |||
3405 | if (PointeeRD) { | |||
3406 | if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { | |||
3407 | CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, | |||
3408 | PDiag(diag::err_access_dtor) << PointeeElem); | |||
3409 | IsVirtualDelete = Dtor->isVirtual(); | |||
3410 | } | |||
3411 | } | |||
3412 | ||||
3413 | DiagnoseUseOfDecl(OperatorDelete, StartLoc); | |||
3414 | ||||
3415 | // Convert the operand to the type of the first parameter of operator | |||
3416 | // delete. This is only necessary if we selected a destroying operator | |||
3417 | // delete that we are going to call (non-virtually); converting to void* | |||
3418 | // is trivial and left to AST consumers to handle. | |||
3419 | QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); | |||
3420 | if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { | |||
3421 | Qualifiers Qs = Pointee.getQualifiers(); | |||
3422 | if (Qs.hasCVRQualifiers()) { | |||
3423 | // Qualifiers are irrelevant to this conversion; we're only looking | |||
3424 | // for access and ambiguity. | |||
3425 | Qs.removeCVRQualifiers(); | |||
3426 | QualType Unqual = Context.getPointerType( | |||
3427 | Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); | |||
3428 | Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); | |||
3429 | } | |||
3430 | Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing); | |||
3431 | if (Ex.isInvalid()) | |||
3432 | return ExprError(); | |||
3433 | } | |||
3434 | } | |||
3435 | ||||
3436 | CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( | |||
3437 | Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, | |||
3438 | UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); | |||
3439 | AnalyzeDeleteExprMismatch(Result); | |||
3440 | return Result; | |||
3441 | } | |||
3442 | ||||
3443 | static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, | |||
3444 | bool IsDelete, | |||
3445 | FunctionDecl *&Operator) { | |||
3446 | ||||
3447 | DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( | |||
3448 | IsDelete ? OO_Delete : OO_New); | |||
3449 | ||||
3450 | LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); | |||
3451 | S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); | |||
3452 | assert(!R.empty() && "implicitly declared allocation functions not found")((!R.empty() && "implicitly declared allocation functions not found" ) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3452, __PRETTY_FUNCTION__)); | |||
3453 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous")((!R.isAmbiguous() && "global allocation functions are ambiguous" ) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3453, __PRETTY_FUNCTION__)); | |||
3454 | ||||
3455 | // We do our own custom access checks below. | |||
3456 | R.suppressDiagnostics(); | |||
3457 | ||||
3458 | SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end()); | |||
3459 | OverloadCandidateSet Candidates(R.getNameLoc(), | |||
3460 | OverloadCandidateSet::CSK_Normal); | |||
3461 | for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); | |||
3462 | FnOvl != FnOvlEnd; ++FnOvl) { | |||
3463 | // Even member operator new/delete are implicitly treated as | |||
3464 | // static, so don't use AddMemberCandidate. | |||
3465 | NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); | |||
3466 | ||||
3467 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { | |||
3468 | S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), | |||
3469 | /*ExplicitTemplateArgs=*/nullptr, Args, | |||
3470 | Candidates, | |||
3471 | /*SuppressUserConversions=*/false); | |||
3472 | continue; | |||
3473 | } | |||
3474 | ||||
3475 | FunctionDecl *Fn = cast<FunctionDecl>(D); | |||
3476 | S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, | |||
3477 | /*SuppressUserConversions=*/false); | |||
3478 | } | |||
3479 | ||||
3480 | SourceRange Range = TheCall->getSourceRange(); | |||
3481 | ||||
3482 | // Do the resolution. | |||
3483 | OverloadCandidateSet::iterator Best; | |||
3484 | switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { | |||
3485 | case OR_Success: { | |||
3486 | // Got one! | |||
3487 | FunctionDecl *FnDecl = Best->Function; | |||
3488 | assert(R.getNamingClass() == nullptr &&((R.getNamingClass() == nullptr && "class members should not be considered" ) ? static_cast<void> (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3489, __PRETTY_FUNCTION__)) | |||
3489 | "class members should not be considered")((R.getNamingClass() == nullptr && "class members should not be considered" ) ? static_cast<void> (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3489, __PRETTY_FUNCTION__)); | |||
3490 | ||||
3491 | if (!FnDecl->isReplaceableGlobalAllocationFunction()) { | |||
3492 | S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) | |||
3493 | << (IsDelete ? 1 : 0) << Range; | |||
3494 | S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) | |||
3495 | << R.getLookupName() << FnDecl->getSourceRange(); | |||
3496 | return true; | |||
3497 | } | |||
3498 | ||||
3499 | Operator = FnDecl; | |||
3500 | return false; | |||
3501 | } | |||
3502 | ||||
3503 | case OR_No_Viable_Function: | |||
3504 | Candidates.NoteCandidates( | |||
3505 | PartialDiagnosticAt(R.getNameLoc(), | |||
3506 | S.PDiag(diag::err_ovl_no_viable_function_in_call) | |||
3507 | << R.getLookupName() << Range), | |||
3508 | S, OCD_AllCandidates, Args); | |||
3509 | return true; | |||
3510 | ||||
3511 | case OR_Ambiguous: | |||
3512 | Candidates.NoteCandidates( | |||
3513 | PartialDiagnosticAt(R.getNameLoc(), | |||
3514 | S.PDiag(diag::err_ovl_ambiguous_call) | |||
3515 | << R.getLookupName() << Range), | |||
3516 | S, OCD_ViableCandidates, Args); | |||
3517 | return true; | |||
3518 | ||||
3519 | case OR_Deleted: { | |||
3520 | Candidates.NoteCandidates( | |||
3521 | PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call) | |||
3522 | << R.getLookupName() << Range), | |||
3523 | S, OCD_AllCandidates, Args); | |||
3524 | return true; | |||
3525 | } | |||
3526 | } | |||
3527 | llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3527); | |||
3528 | } | |||
3529 | ||||
3530 | ExprResult | |||
3531 | Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, | |||
3532 | bool IsDelete) { | |||
3533 | CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); | |||
3534 | if (!getLangOpts().CPlusPlus) { | |||
3535 | Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) | |||
3536 | << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") | |||
3537 | << "C++"; | |||
3538 | return ExprError(); | |||
3539 | } | |||
3540 | // CodeGen assumes it can find the global new and delete to call, | |||
3541 | // so ensure that they are declared. | |||
3542 | DeclareGlobalNewDelete(); | |||
3543 | ||||
3544 | FunctionDecl *OperatorNewOrDelete = nullptr; | |||
3545 | if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, | |||
3546 | OperatorNewOrDelete)) | |||
3547 | return ExprError(); | |||
3548 | assert(OperatorNewOrDelete && "should be found")((OperatorNewOrDelete && "should be found") ? static_cast <void> (0) : __assert_fail ("OperatorNewOrDelete && \"should be found\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3548, __PRETTY_FUNCTION__)); | |||
3549 | ||||
3550 | DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); | |||
3551 | MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); | |||
3552 | ||||
3553 | TheCall->setType(OperatorNewOrDelete->getReturnType()); | |||
3554 | for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { | |||
3555 | QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); | |||
3556 | InitializedEntity Entity = | |||
3557 | InitializedEntity::InitializeParameter(Context, ParamTy, false); | |||
3558 | ExprResult Arg = PerformCopyInitialization( | |||
3559 | Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); | |||
3560 | if (Arg.isInvalid()) | |||
3561 | return ExprError(); | |||
3562 | TheCall->setArg(i, Arg.get()); | |||
3563 | } | |||
3564 | auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); | |||
3565 | assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&((Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && "Callee expected to be implicit cast to a builtin function pointer" ) ? static_cast<void> (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3566, __PRETTY_FUNCTION__)) | |||
3566 | "Callee expected to be implicit cast to a builtin function pointer")((Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && "Callee expected to be implicit cast to a builtin function pointer" ) ? static_cast<void> (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3566, __PRETTY_FUNCTION__)); | |||
3567 | Callee->setType(OperatorNewOrDelete->getType()); | |||
3568 | ||||
3569 | return TheCallResult; | |||
3570 | } | |||
3571 | ||||
3572 | void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, | |||
3573 | bool IsDelete, bool CallCanBeVirtual, | |||
3574 | bool WarnOnNonAbstractTypes, | |||
3575 | SourceLocation DtorLoc) { | |||
3576 | if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) | |||
3577 | return; | |||
3578 | ||||
3579 | // C++ [expr.delete]p3: | |||
3580 | // In the first alternative (delete object), if the static type of the | |||
3581 | // object to be deleted is different from its dynamic type, the static | |||
3582 | // type shall be a base class of the dynamic type of the object to be | |||
3583 | // deleted and the static type shall have a virtual destructor or the | |||
3584 | // behavior is undefined. | |||
3585 | // | |||
3586 | const CXXRecordDecl *PointeeRD = dtor->getParent(); | |||
3587 | // Note: a final class cannot be derived from, no issue there | |||
3588 | if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) | |||
3589 | return; | |||
3590 | ||||
3591 | // If the superclass is in a system header, there's nothing that can be done. | |||
3592 | // The `delete` (where we emit the warning) can be in a system header, | |||
3593 | // what matters for this warning is where the deleted type is defined. | |||
3594 | if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) | |||
3595 | return; | |||
3596 | ||||
3597 | QualType ClassType = dtor->getThisType()->getPointeeType(); | |||
3598 | if (PointeeRD->isAbstract()) { | |||
3599 | // If the class is abstract, we warn by default, because we're | |||
3600 | // sure the code has undefined behavior. | |||
3601 | Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) | |||
3602 | << ClassType; | |||
3603 | } else if (WarnOnNonAbstractTypes) { | |||
3604 | // Otherwise, if this is not an array delete, it's a bit suspect, | |||
3605 | // but not necessarily wrong. | |||
3606 | Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) | |||
3607 | << ClassType; | |||
3608 | } | |||
3609 | if (!IsDelete) { | |||
3610 | std::string TypeStr; | |||
3611 | ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); | |||
3612 | Diag(DtorLoc, diag::note_delete_non_virtual) | |||
3613 | << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); | |||
3614 | } | |||
3615 | } | |||
3616 | ||||
3617 | Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, | |||
3618 | SourceLocation StmtLoc, | |||
3619 | ConditionKind CK) { | |||
3620 | ExprResult E = | |||
3621 | CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); | |||
3622 | if (E.isInvalid()) | |||
3623 | return ConditionError(); | |||
3624 | return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), | |||
3625 | CK == ConditionKind::ConstexprIf); | |||
3626 | } | |||
3627 | ||||
3628 | /// Check the use of the given variable as a C++ condition in an if, | |||
3629 | /// while, do-while, or switch statement. | |||
3630 | ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, | |||
3631 | SourceLocation StmtLoc, | |||
3632 | ConditionKind CK) { | |||
3633 | if (ConditionVar->isInvalidDecl()) | |||
3634 | return ExprError(); | |||
3635 | ||||
3636 | QualType T = ConditionVar->getType(); | |||
3637 | ||||
3638 | // C++ [stmt.select]p2: | |||
3639 | // The declarator shall not specify a function or an array. | |||
3640 | if (T->isFunctionType()) | |||
3641 | return ExprError(Diag(ConditionVar->getLocation(), | |||
3642 | diag::err_invalid_use_of_function_type) | |||
3643 | << ConditionVar->getSourceRange()); | |||
3644 | else if (T->isArrayType()) | |||
3645 | return ExprError(Diag(ConditionVar->getLocation(), | |||
3646 | diag::err_invalid_use_of_array_type) | |||
3647 | << ConditionVar->getSourceRange()); | |||
3648 | ||||
3649 | ExprResult Condition = BuildDeclRefExpr( | |||
3650 | ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, | |||
3651 | ConditionVar->getLocation()); | |||
3652 | ||||
3653 | switch (CK) { | |||
3654 | case ConditionKind::Boolean: | |||
3655 | return CheckBooleanCondition(StmtLoc, Condition.get()); | |||
3656 | ||||
3657 | case ConditionKind::ConstexprIf: | |||
3658 | return CheckBooleanCondition(StmtLoc, Condition.get(), true); | |||
3659 | ||||
3660 | case ConditionKind::Switch: | |||
3661 | return CheckSwitchCondition(StmtLoc, Condition.get()); | |||
3662 | } | |||
3663 | ||||
3664 | llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3664); | |||
3665 | } | |||
3666 | ||||
3667 | /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. | |||
3668 | ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { | |||
3669 | // C++ 6.4p4: | |||
3670 | // The value of a condition that is an initialized declaration in a statement | |||
3671 | // other than a switch statement is the value of the declared variable | |||
3672 | // implicitly converted to type bool. If that conversion is ill-formed, the | |||
3673 | // program is ill-formed. | |||
3674 | // The value of a condition that is an expression is the value of the | |||
3675 | // expression, implicitly converted to bool. | |||
3676 | // | |||
3677 | // FIXME: Return this value to the caller so they don't need to recompute it. | |||
3678 | llvm::APSInt Value(/*BitWidth*/1); | |||
3679 | return (IsConstexpr && !CondExpr->isValueDependent()) | |||
3680 | ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value, | |||
3681 | CCEK_ConstexprIf) | |||
3682 | : PerformContextuallyConvertToBool(CondExpr); | |||
3683 | } | |||
3684 | ||||
3685 | /// Helper function to determine whether this is the (deprecated) C++ | |||
3686 | /// conversion from a string literal to a pointer to non-const char or | |||
3687 | /// non-const wchar_t (for narrow and wide string literals, | |||
3688 | /// respectively). | |||
3689 | bool | |||
3690 | Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { | |||
3691 | // Look inside the implicit cast, if it exists. | |||
3692 | if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) | |||
3693 | From = Cast->getSubExpr(); | |||
3694 | ||||
3695 | // A string literal (2.13.4) that is not a wide string literal can | |||
3696 | // be converted to an rvalue of type "pointer to char"; a wide | |||
3697 | // string literal can be converted to an rvalue of type "pointer | |||
3698 | // to wchar_t" (C++ 4.2p2). | |||
3699 | if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) | |||
3700 | if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) | |||
3701 | if (const BuiltinType *ToPointeeType | |||
3702 | = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { | |||
3703 | // This conversion is considered only when there is an | |||
3704 | // explicit appropriate pointer target type (C++ 4.2p2). | |||
3705 | if (!ToPtrType->getPointeeType().hasQualifiers()) { | |||
3706 | switch (StrLit->getKind()) { | |||
3707 | case StringLiteral::UTF8: | |||
3708 | case StringLiteral::UTF16: | |||
3709 | case StringLiteral::UTF32: | |||
3710 | // We don't allow UTF literals to be implicitly converted | |||
3711 | break; | |||
3712 | case StringLiteral::Ascii: | |||
3713 | return (ToPointeeType->getKind() == BuiltinType::Char_U || | |||
3714 | ToPointeeType->getKind() == BuiltinType::Char_S); | |||
3715 | case StringLiteral::Wide: | |||
3716 | return Context.typesAreCompatible(Context.getWideCharType(), | |||
3717 | QualType(ToPointeeType, 0)); | |||
3718 | } | |||
3719 | } | |||
3720 | } | |||
3721 | ||||
3722 | return false; | |||
3723 | } | |||
3724 | ||||
3725 | static ExprResult BuildCXXCastArgument(Sema &S, | |||
3726 | SourceLocation CastLoc, | |||
3727 | QualType Ty, | |||
3728 | CastKind Kind, | |||
3729 | CXXMethodDecl *Method, | |||
3730 | DeclAccessPair FoundDecl, | |||
3731 | bool HadMultipleCandidates, | |||
3732 | Expr *From) { | |||
3733 | switch (Kind) { | |||
3734 | default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3734); | |||
3735 | case CK_ConstructorConversion: { | |||
3736 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); | |||
3737 | SmallVector<Expr*, 8> ConstructorArgs; | |||
3738 | ||||
3739 | if (S.RequireNonAbstractType(CastLoc, Ty, | |||
3740 | diag::err_allocation_of_abstract_type)) | |||
3741 | return ExprError(); | |||
3742 | ||||
3743 | if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs)) | |||
3744 | return ExprError(); | |||
3745 | ||||
3746 | S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, | |||
3747 | InitializedEntity::InitializeTemporary(Ty)); | |||
3748 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) | |||
3749 | return ExprError(); | |||
3750 | ||||
3751 | ExprResult Result = S.BuildCXXConstructExpr( | |||
3752 | CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), | |||
3753 | ConstructorArgs, HadMultipleCandidates, | |||
3754 | /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, | |||
3755 | CXXConstructExpr::CK_Complete, SourceRange()); | |||
3756 | if (Result.isInvalid()) | |||
3757 | return ExprError(); | |||
3758 | ||||
3759 | return S.MaybeBindToTemporary(Result.getAs<Expr>()); | |||
3760 | } | |||
3761 | ||||
3762 | case CK_UserDefinedConversion: { | |||
3763 | assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")((!From->getType()->isPointerType() && "Arg can't have pointer type!" ) ? static_cast<void> (0) : __assert_fail ("!From->getType()->isPointerType() && \"Arg can't have pointer type!\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3763, __PRETTY_FUNCTION__)); | |||
3764 | ||||
3765 | S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); | |||
3766 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) | |||
3767 | return ExprError(); | |||
3768 | ||||
3769 | // Create an implicit call expr that calls it. | |||
3770 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); | |||
3771 | ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, | |||
3772 | HadMultipleCandidates); | |||
3773 | if (Result.isInvalid()) | |||
3774 | return ExprError(); | |||
3775 | // Record usage of conversion in an implicit cast. | |||
3776 | Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), | |||
3777 | CK_UserDefinedConversion, Result.get(), | |||
3778 | nullptr, Result.get()->getValueKind()); | |||
3779 | ||||
3780 | return S.MaybeBindToTemporary(Result.get()); | |||
3781 | } | |||
3782 | } | |||
3783 | } | |||
3784 | ||||
3785 | /// PerformImplicitConversion - Perform an implicit conversion of the | |||
3786 | /// expression From to the type ToType using the pre-computed implicit | |||
3787 | /// conversion sequence ICS. Returns the converted | |||
3788 | /// expression. Action is the kind of conversion we're performing, | |||
3789 | /// used in the error message. | |||
3790 | ExprResult | |||
3791 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, | |||
3792 | const ImplicitConversionSequence &ICS, | |||
3793 | AssignmentAction Action, | |||
3794 | CheckedConversionKind CCK) { | |||
3795 | // C++ [over.match.oper]p7: [...] operands of class type are converted [...] | |||
3796 | if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType()) | |||
3797 | return From; | |||
3798 | ||||
3799 | switch (ICS.getKind()) { | |||
3800 | case ImplicitConversionSequence::StandardConversion: { | |||
3801 | ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, | |||
3802 | Action, CCK); | |||
3803 | if (Res.isInvalid()) | |||
3804 | return ExprError(); | |||
3805 | From = Res.get(); | |||
3806 | break; | |||
3807 | } | |||
3808 | ||||
3809 | case ImplicitConversionSequence::UserDefinedConversion: { | |||
3810 | ||||
3811 | FunctionDecl *FD = ICS.UserDefined.ConversionFunction; | |||
3812 | CastKind CastKind; | |||
3813 | QualType BeforeToType; | |||
3814 | assert(FD && "no conversion function for user-defined conversion seq")((FD && "no conversion function for user-defined conversion seq" ) ? static_cast<void> (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3814, __PRETTY_FUNCTION__)); | |||
3815 | if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { | |||
3816 | CastKind = CK_UserDefinedConversion; | |||
3817 | ||||
3818 | // If the user-defined conversion is specified by a conversion function, | |||
3819 | // the initial standard conversion sequence converts the source type to | |||
3820 | // the implicit object parameter of the conversion function. | |||
3821 | BeforeToType = Context.getTagDeclType(Conv->getParent()); | |||
3822 | } else { | |||
3823 | const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); | |||
3824 | CastKind = CK_ConstructorConversion; | |||
3825 | // Do no conversion if dealing with ... for the first conversion. | |||
3826 | if (!ICS.UserDefined.EllipsisConversion) { | |||
3827 | // If the user-defined conversion is specified by a constructor, the | |||
3828 | // initial standard conversion sequence converts the source type to | |||
3829 | // the type required by the argument of the constructor | |||
3830 | BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); | |||
3831 | } | |||
3832 | } | |||
3833 | // Watch out for ellipsis conversion. | |||
3834 | if (!ICS.UserDefined.EllipsisConversion) { | |||
3835 | ExprResult Res = | |||
3836 | PerformImplicitConversion(From, BeforeToType, | |||
3837 | ICS.UserDefined.Before, AA_Converting, | |||
3838 | CCK); | |||
3839 | if (Res.isInvalid()) | |||
3840 | return ExprError(); | |||
3841 | From = Res.get(); | |||
3842 | } | |||
3843 | ||||
3844 | ExprResult CastArg = BuildCXXCastArgument( | |||
3845 | *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, | |||
3846 | cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, | |||
3847 | ICS.UserDefined.HadMultipleCandidates, From); | |||
3848 | ||||
3849 | if (CastArg.isInvalid()) | |||
3850 | return ExprError(); | |||
3851 | ||||
3852 | From = CastArg.get(); | |||
3853 | ||||
3854 | // C++ [over.match.oper]p7: | |||
3855 | // [...] the second standard conversion sequence of a user-defined | |||
3856 | // conversion sequence is not applied. | |||
3857 | if (CCK == CCK_ForBuiltinOverloadedOp) | |||
3858 | return From; | |||
3859 | ||||
3860 | return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, | |||
3861 | AA_Converting, CCK); | |||
3862 | } | |||
3863 | ||||
3864 | case ImplicitConversionSequence::AmbiguousConversion: | |||
3865 | ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), | |||
3866 | PDiag(diag::err_typecheck_ambiguous_condition) | |||
3867 | << From->getSourceRange()); | |||
3868 | return ExprError(); | |||
3869 | ||||
3870 | case ImplicitConversionSequence::EllipsisConversion: | |||
3871 | llvm_unreachable("Cannot perform an ellipsis conversion")::llvm::llvm_unreachable_internal("Cannot perform an ellipsis conversion" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3871); | |||
3872 | ||||
3873 | case ImplicitConversionSequence::BadConversion: | |||
3874 | bool Diagnosed = | |||
3875 | DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType, | |||
3876 | From->getType(), From, Action); | |||
3877 | assert(Diagnosed && "failed to diagnose bad conversion")((Diagnosed && "failed to diagnose bad conversion") ? static_cast<void> (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3877, __PRETTY_FUNCTION__)); (void)Diagnosed; | |||
3878 | return ExprError(); | |||
3879 | } | |||
3880 | ||||
3881 | // Everything went well. | |||
3882 | return From; | |||
3883 | } | |||
3884 | ||||
3885 | /// PerformImplicitConversion - Perform an implicit conversion of the | |||
3886 | /// expression From to the type ToType by following the standard | |||
3887 | /// conversion sequence SCS. Returns the converted | |||
3888 | /// expression. Flavor is the context in which we're performing this | |||
3889 | /// conversion, for use in error messages. | |||
3890 | ExprResult | |||
3891 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, | |||
3892 | const StandardConversionSequence& SCS, | |||
3893 | AssignmentAction Action, | |||
3894 | CheckedConversionKind CCK) { | |||
3895 | bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); | |||
3896 | ||||
3897 | // Overall FIXME: we are recomputing too many types here and doing far too | |||
3898 | // much extra work. What this means is that we need to keep track of more | |||
3899 | // information that is computed when we try the implicit conversion initially, | |||
3900 | // so that we don't need to recompute anything here. | |||
3901 | QualType FromType = From->getType(); | |||
3902 | ||||
3903 | if (SCS.CopyConstructor) { | |||
3904 | // FIXME: When can ToType be a reference type? | |||
3905 | assert(!ToType->isReferenceType())((!ToType->isReferenceType()) ? static_cast<void> (0 ) : __assert_fail ("!ToType->isReferenceType()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3905, __PRETTY_FUNCTION__)); | |||
3906 | if (SCS.Second == ICK_Derived_To_Base) { | |||
3907 | SmallVector<Expr*, 8> ConstructorArgs; | |||
3908 | if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), | |||
3909 | From, /*FIXME:ConstructLoc*/SourceLocation(), | |||
3910 | ConstructorArgs)) | |||
3911 | return ExprError(); | |||
3912 | return BuildCXXConstructExpr( | |||
3913 | /*FIXME:ConstructLoc*/ SourceLocation(), ToType, | |||
3914 | SCS.FoundCopyConstructor, SCS.CopyConstructor, | |||
3915 | ConstructorArgs, /*HadMultipleCandidates*/ false, | |||
3916 | /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, | |||
3917 | CXXConstructExpr::CK_Complete, SourceRange()); | |||
3918 | } | |||
3919 | return BuildCXXConstructExpr( | |||
3920 | /*FIXME:ConstructLoc*/ SourceLocation(), ToType, | |||
3921 | SCS.FoundCopyConstructor, SCS.CopyConstructor, | |||
3922 | From, /*HadMultipleCandidates*/ false, | |||
3923 | /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, | |||
3924 | CXXConstructExpr::CK_Complete, SourceRange()); | |||
3925 | } | |||
3926 | ||||
3927 | // Resolve overloaded function references. | |||
3928 | if (Context.hasSameType(FromType, Context.OverloadTy)) { | |||
3929 | DeclAccessPair Found; | |||
3930 | FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, | |||
3931 | true, Found); | |||
3932 | if (!Fn) | |||
3933 | return ExprError(); | |||
3934 | ||||
3935 | if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) | |||
3936 | return ExprError(); | |||
3937 | ||||
3938 | From = FixOverloadedFunctionReference(From, Found, Fn); | |||
3939 | FromType = From->getType(); | |||
3940 | } | |||
3941 | ||||
3942 | // If we're converting to an atomic type, first convert to the corresponding | |||
3943 | // non-atomic type. | |||
3944 | QualType ToAtomicType; | |||
3945 | if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { | |||
3946 | ToAtomicType = ToType; | |||
3947 | ToType = ToAtomic->getValueType(); | |||
3948 | } | |||
3949 | ||||
3950 | QualType InitialFromType = FromType; | |||
3951 | // Perform the first implicit conversion. | |||
3952 | switch (SCS.First) { | |||
3953 | case ICK_Identity: | |||
3954 | if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { | |||
3955 | FromType = FromAtomic->getValueType().getUnqualifiedType(); | |||
3956 | From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, | |||
3957 | From, /*BasePath=*/nullptr, VK_RValue); | |||
3958 | } | |||
3959 | break; | |||
3960 | ||||
3961 | case ICK_Lvalue_To_Rvalue: { | |||
3962 | assert(From->getObjectKind() != OK_ObjCProperty)((From->getObjectKind() != OK_ObjCProperty) ? static_cast< void> (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3962, __PRETTY_FUNCTION__)); | |||
3963 | ExprResult FromRes = DefaultLvalueConversion(From); | |||
3964 | assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!")((!FromRes.isInvalid() && "Can't perform deduced conversion?!" ) ? static_cast<void> (0) : __assert_fail ("!FromRes.isInvalid() && \"Can't perform deduced conversion?!\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3964, __PRETTY_FUNCTION__)); | |||
3965 | From = FromRes.get(); | |||
3966 | FromType = From->getType(); | |||
3967 | break; | |||
3968 | } | |||
3969 | ||||
3970 | case ICK_Array_To_Pointer: | |||
3971 | FromType = Context.getArrayDecayedType(FromType); | |||
3972 | From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, | |||
3973 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
3974 | break; | |||
3975 | ||||
3976 | case ICK_Function_To_Pointer: | |||
3977 | FromType = Context.getPointerType(FromType); | |||
3978 | From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, | |||
3979 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
3980 | break; | |||
3981 | ||||
3982 | default: | |||
3983 | llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 3983); | |||
3984 | } | |||
3985 | ||||
3986 | // Perform the second implicit conversion | |||
3987 | switch (SCS.Second) { | |||
3988 | case ICK_Identity: | |||
3989 | // C++ [except.spec]p5: | |||
3990 | // [For] assignment to and initialization of pointers to functions, | |||
3991 | // pointers to member functions, and references to functions: the | |||
3992 | // target entity shall allow at least the exceptions allowed by the | |||
3993 | // source value in the assignment or initialization. | |||
3994 | switch (Action) { | |||
3995 | case AA_Assigning: | |||
3996 | case AA_Initializing: | |||
3997 | // Note, function argument passing and returning are initialization. | |||
3998 | case AA_Passing: | |||
3999 | case AA_Returning: | |||
4000 | case AA_Sending: | |||
4001 | case AA_Passing_CFAudited: | |||
4002 | if (CheckExceptionSpecCompatibility(From, ToType)) | |||
4003 | return ExprError(); | |||
4004 | break; | |||
4005 | ||||
4006 | case AA_Casting: | |||
4007 | case AA_Converting: | |||
4008 | // Casts and implicit conversions are not initialization, so are not | |||
4009 | // checked for exception specification mismatches. | |||
4010 | break; | |||
4011 | } | |||
4012 | // Nothing else to do. | |||
4013 | break; | |||
4014 | ||||
4015 | case ICK_Integral_Promotion: | |||
4016 | case ICK_Integral_Conversion: | |||
4017 | if (ToType->isBooleanType()) { | |||
4018 | assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&((FromType->castAs<EnumType>()->getDecl()->isFixed () && SCS.Second == ICK_Integral_Promotion && "only enums with fixed underlying type can promote to bool") ? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4020, __PRETTY_FUNCTION__)) | |||
4019 | SCS.Second == ICK_Integral_Promotion &&((FromType->castAs<EnumType>()->getDecl()->isFixed () && SCS.Second == ICK_Integral_Promotion && "only enums with fixed underlying type can promote to bool") ? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4020, __PRETTY_FUNCTION__)) | |||
4020 | "only enums with fixed underlying type can promote to bool")((FromType->castAs<EnumType>()->getDecl()->isFixed () && SCS.Second == ICK_Integral_Promotion && "only enums with fixed underlying type can promote to bool") ? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4020, __PRETTY_FUNCTION__)); | |||
4021 | From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, | |||
4022 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4023 | } else { | |||
4024 | From = ImpCastExprToType(From, ToType, CK_IntegralCast, | |||
4025 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4026 | } | |||
4027 | break; | |||
4028 | ||||
4029 | case ICK_Floating_Promotion: | |||
4030 | case ICK_Floating_Conversion: | |||
4031 | From = ImpCastExprToType(From, ToType, CK_FloatingCast, | |||
4032 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4033 | break; | |||
4034 | ||||
4035 | case ICK_Complex_Promotion: | |||
4036 | case ICK_Complex_Conversion: { | |||
4037 | QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType(); | |||
4038 | QualType ToEl = ToType->getAs<ComplexType>()->getElementType(); | |||
4039 | CastKind CK; | |||
4040 | if (FromEl->isRealFloatingType()) { | |||
4041 | if (ToEl->isRealFloatingType()) | |||
4042 | CK = CK_FloatingComplexCast; | |||
4043 | else | |||
4044 | CK = CK_FloatingComplexToIntegralComplex; | |||
4045 | } else if (ToEl->isRealFloatingType()) { | |||
4046 | CK = CK_IntegralComplexToFloatingComplex; | |||
4047 | } else { | |||
4048 | CK = CK_IntegralComplexCast; | |||
4049 | } | |||
4050 | From = ImpCastExprToType(From, ToType, CK, | |||
4051 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4052 | break; | |||
4053 | } | |||
4054 | ||||
4055 | case ICK_Floating_Integral: | |||
4056 | if (ToType->isRealFloatingType()) | |||
4057 | From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, | |||
4058 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4059 | else | |||
4060 | From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, | |||
4061 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4062 | break; | |||
4063 | ||||
4064 | case ICK_Compatible_Conversion: | |||
4065 | From = ImpCastExprToType(From, ToType, CK_NoOp, | |||
4066 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4067 | break; | |||
4068 | ||||
4069 | case ICK_Writeback_Conversion: | |||
4070 | case ICK_Pointer_Conversion: { | |||
4071 | if (SCS.IncompatibleObjC && Action != AA_Casting) { | |||
4072 | // Diagnose incompatible Objective-C conversions | |||
4073 | if (Action == AA_Initializing || Action == AA_Assigning) | |||
4074 | Diag(From->getBeginLoc(), | |||
4075 | diag::ext_typecheck_convert_incompatible_pointer) | |||
4076 | << ToType << From->getType() << Action << From->getSourceRange() | |||
4077 | << 0; | |||
4078 | else | |||
4079 | Diag(From->getBeginLoc(), | |||
4080 | diag::ext_typecheck_convert_incompatible_pointer) | |||
4081 | << From->getType() << ToType << Action << From->getSourceRange() | |||
4082 | << 0; | |||
4083 | ||||
4084 | if (From->getType()->isObjCObjectPointerType() && | |||
4085 | ToType->isObjCObjectPointerType()) | |||
4086 | EmitRelatedResultTypeNote(From); | |||
4087 | } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && | |||
4088 | !CheckObjCARCUnavailableWeakConversion(ToType, | |||
4089 | From->getType())) { | |||
4090 | if (Action == AA_Initializing) | |||
4091 | Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); | |||
4092 | else | |||
4093 | Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) | |||
4094 | << (Action == AA_Casting) << From->getType() << ToType | |||
4095 | << From->getSourceRange(); | |||
4096 | } | |||
4097 | ||||
4098 | CastKind Kind; | |||
4099 | CXXCastPath BasePath; | |||
4100 | if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle)) | |||
4101 | return ExprError(); | |||
4102 | ||||
4103 | // Make sure we extend blocks if necessary. | |||
4104 | // FIXME: doing this here is really ugly. | |||
4105 | if (Kind == CK_BlockPointerToObjCPointerCast) { | |||
4106 | ExprResult E = From; | |||
4107 | (void) PrepareCastToObjCObjectPointer(E); | |||
4108 | From = E.get(); | |||
4109 | } | |||
4110 | if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) | |||
4111 | CheckObjCConversion(SourceRange(), ToType, From, CCK); | |||
4112 | From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) | |||
4113 | .get(); | |||
4114 | break; | |||
4115 | } | |||
4116 | ||||
4117 | case ICK_Pointer_Member: { | |||
4118 | CastKind Kind; | |||
4119 | CXXCastPath BasePath; | |||
4120 | if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) | |||
4121 | return ExprError(); | |||
4122 | if (CheckExceptionSpecCompatibility(From, ToType)) | |||
4123 | return ExprError(); | |||
4124 | ||||
4125 | // We may not have been able to figure out what this member pointer resolved | |||
4126 | // to up until this exact point. Attempt to lock-in it's inheritance model. | |||
4127 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
4128 | (void)isCompleteType(From->getExprLoc(), From->getType()); | |||
4129 | (void)isCompleteType(From->getExprLoc(), ToType); | |||
4130 | } | |||
4131 | ||||
4132 | From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) | |||
4133 | .get(); | |||
4134 | break; | |||
4135 | } | |||
4136 | ||||
4137 | case ICK_Boolean_Conversion: | |||
4138 | // Perform half-to-boolean conversion via float. | |||
4139 | if (From->getType()->isHalfType()) { | |||
4140 | From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); | |||
4141 | FromType = Context.FloatTy; | |||
4142 | } | |||
4143 | ||||
4144 | From = ImpCastExprToType(From, Context.BoolTy, | |||
4145 | ScalarTypeToBooleanCastKind(FromType), | |||
4146 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4147 | break; | |||
4148 | ||||
4149 | case ICK_Derived_To_Base: { | |||
4150 | CXXCastPath BasePath; | |||
4151 | if (CheckDerivedToBaseConversion( | |||
4152 | From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), | |||
4153 | From->getSourceRange(), &BasePath, CStyle)) | |||
4154 | return ExprError(); | |||
4155 | ||||
4156 | From = ImpCastExprToType(From, ToType.getNonReferenceType(), | |||
4157 | CK_DerivedToBase, From->getValueKind(), | |||
4158 | &BasePath, CCK).get(); | |||
4159 | break; | |||
4160 | } | |||
4161 | ||||
4162 | case ICK_Vector_Conversion: | |||
4163 | From = ImpCastExprToType(From, ToType, CK_BitCast, | |||
4164 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4165 | break; | |||
4166 | ||||
4167 | case ICK_Vector_Splat: { | |||
4168 | // Vector splat from any arithmetic type to a vector. | |||
4169 | Expr *Elem = prepareVectorSplat(ToType, From).get(); | |||
4170 | From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue, | |||
4171 | /*BasePath=*/nullptr, CCK).get(); | |||
4172 | break; | |||
4173 | } | |||
4174 | ||||
4175 | case ICK_Complex_Real: | |||
4176 | // Case 1. x -> _Complex y | |||
4177 | if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { | |||
4178 | QualType ElType = ToComplex->getElementType(); | |||
4179 | bool isFloatingComplex = ElType->isRealFloatingType(); | |||
4180 | ||||
4181 | // x -> y | |||
4182 | if (Context.hasSameUnqualifiedType(ElType, From->getType())) { | |||
4183 | // do nothing | |||
4184 | } else if (From->getType()->isRealFloatingType()) { | |||
4185 | From = ImpCastExprToType(From, ElType, | |||
4186 | isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); | |||
4187 | } else { | |||
4188 | assert(From->getType()->isIntegerType())((From->getType()->isIntegerType()) ? static_cast<void > (0) : __assert_fail ("From->getType()->isIntegerType()" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4188, __PRETTY_FUNCTION__)); | |||
4189 | From = ImpCastExprToType(From, ElType, | |||
4190 | isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); | |||
4191 | } | |||
4192 | // y -> _Complex y | |||
4193 | From = ImpCastExprToType(From, ToType, | |||
4194 | isFloatingComplex ? CK_FloatingRealToComplex | |||
4195 | : CK_IntegralRealToComplex).get(); | |||
4196 | ||||
4197 | // Case 2. _Complex x -> y | |||
4198 | } else { | |||
4199 | const ComplexType *FromComplex = From->getType()->getAs<ComplexType>(); | |||
4200 | assert(FromComplex)((FromComplex) ? static_cast<void> (0) : __assert_fail ( "FromComplex", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4200, __PRETTY_FUNCTION__)); | |||
4201 | ||||
4202 | QualType ElType = FromComplex->getElementType(); | |||
4203 | bool isFloatingComplex = ElType->isRealFloatingType(); | |||
4204 | ||||
4205 | // _Complex x -> x | |||
4206 | From = ImpCastExprToType(From, ElType, | |||
4207 | isFloatingComplex ? CK_FloatingComplexToReal | |||
4208 | : CK_IntegralComplexToReal, | |||
4209 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4210 | ||||
4211 | // x -> y | |||
4212 | if (Context.hasSameUnqualifiedType(ElType, ToType)) { | |||
4213 | // do nothing | |||
4214 | } else if (ToType->isRealFloatingType()) { | |||
4215 | From = ImpCastExprToType(From, ToType, | |||
4216 | isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, | |||
4217 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4218 | } else { | |||
4219 | assert(ToType->isIntegerType())((ToType->isIntegerType()) ? static_cast<void> (0) : __assert_fail ("ToType->isIntegerType()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4219, __PRETTY_FUNCTION__)); | |||
4220 | From = ImpCastExprToType(From, ToType, | |||
4221 | isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, | |||
4222 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4223 | } | |||
4224 | } | |||
4225 | break; | |||
4226 | ||||
4227 | case ICK_Block_Pointer_Conversion: { | |||
4228 | LangAS AddrSpaceL = | |||
4229 | ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); | |||
4230 | LangAS AddrSpaceR = | |||
4231 | FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); | |||
4232 | assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&((Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR ) && "Invalid cast") ? static_cast<void> (0) : __assert_fail ("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4233, __PRETTY_FUNCTION__)) | |||
4233 | "Invalid cast")((Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR ) && "Invalid cast") ? static_cast<void> (0) : __assert_fail ("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4233, __PRETTY_FUNCTION__)); | |||
4234 | CastKind Kind = | |||
4235 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; | |||
4236 | From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, | |||
4237 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4238 | break; | |||
4239 | } | |||
4240 | ||||
4241 | case ICK_TransparentUnionConversion: { | |||
4242 | ExprResult FromRes = From; | |||
4243 | Sema::AssignConvertType ConvTy = | |||
4244 | CheckTransparentUnionArgumentConstraints(ToType, FromRes); | |||
4245 | if (FromRes.isInvalid()) | |||
4246 | return ExprError(); | |||
4247 | From = FromRes.get(); | |||
4248 | assert ((ConvTy == Sema::Compatible) &&(((ConvTy == Sema::Compatible) && "Improper transparent union conversion" ) ? static_cast<void> (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4249, __PRETTY_FUNCTION__)) | |||
4249 | "Improper transparent union conversion")(((ConvTy == Sema::Compatible) && "Improper transparent union conversion" ) ? static_cast<void> (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4249, __PRETTY_FUNCTION__)); | |||
4250 | (void)ConvTy; | |||
4251 | break; | |||
4252 | } | |||
4253 | ||||
4254 | case ICK_Zero_Event_Conversion: | |||
4255 | case ICK_Zero_Queue_Conversion: | |||
4256 | From = ImpCastExprToType(From, ToType, | |||
4257 | CK_ZeroToOCLOpaqueType, | |||
4258 | From->getValueKind()).get(); | |||
4259 | break; | |||
4260 | ||||
4261 | case ICK_Lvalue_To_Rvalue: | |||
4262 | case ICK_Array_To_Pointer: | |||
4263 | case ICK_Function_To_Pointer: | |||
4264 | case ICK_Function_Conversion: | |||
4265 | case ICK_Qualification: | |||
4266 | case ICK_Num_Conversion_Kinds: | |||
4267 | case ICK_C_Only_Conversion: | |||
4268 | case ICK_Incompatible_Pointer_Conversion: | |||
4269 | llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4269); | |||
4270 | } | |||
4271 | ||||
4272 | switch (SCS.Third) { | |||
4273 | case ICK_Identity: | |||
4274 | // Nothing to do. | |||
4275 | break; | |||
4276 | ||||
4277 | case ICK_Function_Conversion: | |||
4278 | // If both sides are functions (or pointers/references to them), there could | |||
4279 | // be incompatible exception declarations. | |||
4280 | if (CheckExceptionSpecCompatibility(From, ToType)) | |||
4281 | return ExprError(); | |||
4282 | ||||
4283 | From = ImpCastExprToType(From, ToType, CK_NoOp, | |||
4284 | VK_RValue, /*BasePath=*/nullptr, CCK).get(); | |||
4285 | break; | |||
4286 | ||||
4287 | case ICK_Qualification: { | |||
4288 | // The qualification keeps the category of the inner expression, unless the | |||
4289 | // target type isn't a reference. | |||
4290 | ExprValueKind VK = | |||
4291 | ToType->isReferenceType() ? From->getValueKind() : VK_RValue; | |||
4292 | ||||
4293 | CastKind CK = CK_NoOp; | |||
4294 | ||||
4295 | if (ToType->isReferenceType() && | |||
4296 | ToType->getPointeeType().getAddressSpace() != | |||
4297 | From->getType().getAddressSpace()) | |||
4298 | CK = CK_AddressSpaceConversion; | |||
4299 | ||||
4300 | if (ToType->isPointerType() && | |||
4301 | ToType->getPointeeType().getAddressSpace() != | |||
4302 | From->getType()->getPointeeType().getAddressSpace()) | |||
4303 | CK = CK_AddressSpaceConversion; | |||
4304 | ||||
4305 | From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, | |||
4306 | /*BasePath=*/nullptr, CCK) | |||
4307 | .get(); | |||
4308 | ||||
4309 | if (SCS.DeprecatedStringLiteralToCharPtr && | |||
4310 | !getLangOpts().WritableStrings) { | |||
4311 | Diag(From->getBeginLoc(), | |||
4312 | getLangOpts().CPlusPlus11 | |||
4313 | ? diag::ext_deprecated_string_literal_conversion | |||
4314 | : diag::warn_deprecated_string_literal_conversion) | |||
4315 | << ToType.getNonReferenceType(); | |||
4316 | } | |||
4317 | ||||
4318 | break; | |||
4319 | } | |||
4320 | ||||
4321 | default: | |||
4322 | llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4322); | |||
4323 | } | |||
4324 | ||||
4325 | // If this conversion sequence involved a scalar -> atomic conversion, perform | |||
4326 | // that conversion now. | |||
4327 | if (!ToAtomicType.isNull()) { | |||
4328 | assert(Context.hasSameType(((Context.hasSameType( ToAtomicType->castAs<AtomicType> ()->getValueType(), From->getType())) ? static_cast< void> (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4329, __PRETTY_FUNCTION__)) | |||
4329 | ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))((Context.hasSameType( ToAtomicType->castAs<AtomicType> ()->getValueType(), From->getType())) ? static_cast< void> (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4329, __PRETTY_FUNCTION__)); | |||
4330 | From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, | |||
4331 | VK_RValue, nullptr, CCK).get(); | |||
4332 | } | |||
4333 | ||||
4334 | // If this conversion sequence succeeded and involved implicitly converting a | |||
4335 | // _Nullable type to a _Nonnull one, complain. | |||
4336 | if (!isCast(CCK)) | |||
4337 | diagnoseNullableToNonnullConversion(ToType, InitialFromType, | |||
4338 | From->getBeginLoc()); | |||
4339 | ||||
4340 | return From; | |||
4341 | } | |||
4342 | ||||
4343 | /// Check the completeness of a type in a unary type trait. | |||
4344 | /// | |||
4345 | /// If the particular type trait requires a complete type, tries to complete | |||
4346 | /// it. If completing the type fails, a diagnostic is emitted and false | |||
4347 | /// returned. If completing the type succeeds or no completion was required, | |||
4348 | /// returns true. | |||
4349 | static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, | |||
4350 | SourceLocation Loc, | |||
4351 | QualType ArgTy) { | |||
4352 | // C++0x [meta.unary.prop]p3: | |||
4353 | // For all of the class templates X declared in this Clause, instantiating | |||
4354 | // that template with a template argument that is a class template | |||
4355 | // specialization may result in the implicit instantiation of the template | |||
4356 | // argument if and only if the semantics of X require that the argument | |||
4357 | // must be a complete type. | |||
4358 | // We apply this rule to all the type trait expressions used to implement | |||
4359 | // these class templates. We also try to follow any GCC documented behavior | |||
4360 | // in these expressions to ensure portability of standard libraries. | |||
4361 | switch (UTT) { | |||
4362 | default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4362); | |||
4363 | // is_complete_type somewhat obviously cannot require a complete type. | |||
4364 | case UTT_IsCompleteType: | |||
4365 | // Fall-through | |||
4366 | ||||
4367 | // These traits are modeled on the type predicates in C++0x | |||
4368 | // [meta.unary.cat] and [meta.unary.comp]. They are not specified as | |||
4369 | // requiring a complete type, as whether or not they return true cannot be | |||
4370 | // impacted by the completeness of the type. | |||
4371 | case UTT_IsVoid: | |||
4372 | case UTT_IsIntegral: | |||
4373 | case UTT_IsFloatingPoint: | |||
4374 | case UTT_IsArray: | |||
4375 | case UTT_IsPointer: | |||
4376 | case UTT_IsLvalueReference: | |||
4377 | case UTT_IsRvalueReference: | |||
4378 | case UTT_IsMemberFunctionPointer: | |||
4379 | case UTT_IsMemberObjectPointer: | |||
4380 | case UTT_IsEnum: | |||
4381 | case UTT_IsUnion: | |||
4382 | case UTT_IsClass: | |||
4383 | case UTT_IsFunction: | |||
4384 | case UTT_IsReference: | |||
4385 | case UTT_IsArithmetic: | |||
4386 | case UTT_IsFundamental: | |||
4387 | case UTT_IsObject: | |||
4388 | case UTT_IsScalar: | |||
4389 | case UTT_IsCompound: | |||
4390 | case UTT_IsMemberPointer: | |||
4391 | // Fall-through | |||
4392 | ||||
4393 | // These traits are modeled on type predicates in C++0x [meta.unary.prop] | |||
4394 | // which requires some of its traits to have the complete type. However, | |||
4395 | // the completeness of the type cannot impact these traits' semantics, and | |||
4396 | // so they don't require it. This matches the comments on these traits in | |||
4397 | // Table 49. | |||
4398 | case UTT_IsConst: | |||
4399 | case UTT_IsVolatile: | |||
4400 | case UTT_IsSigned: | |||
4401 | case UTT_IsUnsigned: | |||
4402 | ||||
4403 | // This type trait always returns false, checking the type is moot. | |||
4404 | case UTT_IsInterfaceClass: | |||
4405 | return true; | |||
4406 | ||||
4407 | // C++14 [meta.unary.prop]: | |||
4408 | // If T is a non-union class type, T shall be a complete type. | |||
4409 | case UTT_IsEmpty: | |||
4410 | case UTT_IsPolymorphic: | |||
4411 | case UTT_IsAbstract: | |||
4412 | if (const auto *RD = ArgTy->getAsCXXRecordDecl()) | |||
4413 | if (!RD->isUnion()) | |||
4414 | return !S.RequireCompleteType( | |||
4415 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); | |||
4416 | return true; | |||
4417 | ||||
4418 | // C++14 [meta.unary.prop]: | |||
4419 | // If T is a class type, T shall be a complete type. | |||
4420 | case UTT_IsFinal: | |||
4421 | case UTT_IsSealed: | |||
4422 | if (ArgTy->getAsCXXRecordDecl()) | |||
4423 | return !S.RequireCompleteType( | |||
4424 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); | |||
4425 | return true; | |||
4426 | ||||
4427 | // C++1z [meta.unary.prop]: | |||
4428 | // remove_all_extents_t<T> shall be a complete type or cv void. | |||
4429 | case UTT_IsAggregate: | |||
4430 | case UTT_IsTrivial: | |||
4431 | case UTT_IsTriviallyCopyable: | |||
4432 | case UTT_IsStandardLayout: | |||
4433 | case UTT_IsPOD: | |||
4434 | case UTT_IsLiteral: | |||
4435 | // Per the GCC type traits documentation, T shall be a complete type, cv void, | |||
4436 | // or an array of unknown bound. But GCC actually imposes the same constraints | |||
4437 | // as above. | |||
4438 | case UTT_HasNothrowAssign: | |||
4439 | case UTT_HasNothrowMoveAssign: | |||
4440 | case UTT_HasNothrowConstructor: | |||
4441 | case UTT_HasNothrowCopy: | |||
4442 | case UTT_HasTrivialAssign: | |||
4443 | case UTT_HasTrivialMoveAssign: | |||
4444 | case UTT_HasTrivialDefaultConstructor: | |||
4445 | case UTT_HasTrivialMoveConstructor: | |||
4446 | case UTT_HasTrivialCopy: | |||
4447 | case UTT_HasTrivialDestructor: | |||
4448 | case UTT_HasVirtualDestructor: | |||
4449 | ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); | |||
4450 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
4451 | ||||
4452 | // C++1z [meta.unary.prop]: | |||
4453 | // T shall be a complete type, cv void, or an array of unknown bound. | |||
4454 | case UTT_IsDestructible: | |||
4455 | case UTT_IsNothrowDestructible: | |||
4456 | case UTT_IsTriviallyDestructible: | |||
4457 | case UTT_HasUniqueObjectRepresentations: | |||
4458 | if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) | |||
4459 | return true; | |||
4460 | ||||
4461 | return !S.RequireCompleteType( | |||
4462 | Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); | |||
4463 | } | |||
4464 | } | |||
4465 | ||||
4466 | static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, | |||
4467 | Sema &Self, SourceLocation KeyLoc, ASTContext &C, | |||
4468 | bool (CXXRecordDecl::*HasTrivial)() const, | |||
4469 | bool (CXXRecordDecl::*HasNonTrivial)() const, | |||
4470 | bool (CXXMethodDecl::*IsDesiredOp)() const) | |||
4471 | { | |||
4472 | CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
4473 | if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) | |||
4474 | return true; | |||
4475 | ||||
4476 | DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); | |||
4477 | DeclarationNameInfo NameInfo(Name, KeyLoc); | |||
4478 | LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); | |||
4479 | if (Self.LookupQualifiedName(Res, RD)) { | |||
4480 | bool FoundOperator = false; | |||
4481 | Res.suppressDiagnostics(); | |||
4482 | for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); | |||
4483 | Op != OpEnd; ++Op) { | |||
4484 | if (isa<FunctionTemplateDecl>(*Op)) | |||
4485 | continue; | |||
4486 | ||||
4487 | CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); | |||
4488 | if((Operator->*IsDesiredOp)()) { | |||
4489 | FoundOperator = true; | |||
4490 | const FunctionProtoType *CPT = | |||
4491 | Operator->getType()->getAs<FunctionProtoType>(); | |||
4492 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
4493 | if (!CPT || !CPT->isNothrow()) | |||
4494 | return false; | |||
4495 | } | |||
4496 | } | |||
4497 | return FoundOperator; | |||
4498 | } | |||
4499 | return false; | |||
4500 | } | |||
4501 | ||||
4502 | static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, | |||
4503 | SourceLocation KeyLoc, QualType T) { | |||
4504 | assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")((!T->isDependentType() && "Cannot evaluate traits of dependent type" ) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4504, __PRETTY_FUNCTION__)); | |||
4505 | ||||
4506 | ASTContext &C = Self.Context; | |||
4507 | switch(UTT) { | |||
4508 | default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4508); | |||
4509 | // Type trait expressions corresponding to the primary type category | |||
4510 | // predicates in C++0x [meta.unary.cat]. | |||
4511 | case UTT_IsVoid: | |||
4512 | return T->isVoidType(); | |||
4513 | case UTT_IsIntegral: | |||
4514 | return T->isIntegralType(C); | |||
4515 | case UTT_IsFloatingPoint: | |||
4516 | return T->isFloatingType(); | |||
4517 | case UTT_IsArray: | |||
4518 | return T->isArrayType(); | |||
4519 | case UTT_IsPointer: | |||
4520 | return T->isPointerType(); | |||
4521 | case UTT_IsLvalueReference: | |||
4522 | return T->isLValueReferenceType(); | |||
4523 | case UTT_IsRvalueReference: | |||
4524 | return T->isRValueReferenceType(); | |||
4525 | case UTT_IsMemberFunctionPointer: | |||
4526 | return T->isMemberFunctionPointerType(); | |||
4527 | case UTT_IsMemberObjectPointer: | |||
4528 | return T->isMemberDataPointerType(); | |||
4529 | case UTT_IsEnum: | |||
4530 | return T->isEnumeralType(); | |||
4531 | case UTT_IsUnion: | |||
4532 | return T->isUnionType(); | |||
4533 | case UTT_IsClass: | |||
4534 | return T->isClassType() || T->isStructureType() || T->isInterfaceType(); | |||
4535 | case UTT_IsFunction: | |||
4536 | return T->isFunctionType(); | |||
4537 | ||||
4538 | // Type trait expressions which correspond to the convenient composition | |||
4539 | // predicates in C++0x [meta.unary.comp]. | |||
4540 | case UTT_IsReference: | |||
4541 | return T->isReferenceType(); | |||
4542 | case UTT_IsArithmetic: | |||
4543 | return T->isArithmeticType() && !T->isEnumeralType(); | |||
4544 | case UTT_IsFundamental: | |||
4545 | return T->isFundamentalType(); | |||
4546 | case UTT_IsObject: | |||
4547 | return T->isObjectType(); | |||
4548 | case UTT_IsScalar: | |||
4549 | // Note: semantic analysis depends on Objective-C lifetime types to be | |||
4550 | // considered scalar types. However, such types do not actually behave | |||
4551 | // like scalar types at run time (since they may require retain/release | |||
4552 | // operations), so we report them as non-scalar. | |||
4553 | if (T->isObjCLifetimeType()) { | |||
4554 | switch (T.getObjCLifetime()) { | |||
4555 | case Qualifiers::OCL_None: | |||
4556 | case Qualifiers::OCL_ExplicitNone: | |||
4557 | return true; | |||
4558 | ||||
4559 | case Qualifiers::OCL_Strong: | |||
4560 | case Qualifiers::OCL_Weak: | |||
4561 | case Qualifiers::OCL_Autoreleasing: | |||
4562 | return false; | |||
4563 | } | |||
4564 | } | |||
4565 | ||||
4566 | return T->isScalarType(); | |||
4567 | case UTT_IsCompound: | |||
4568 | return T->isCompoundType(); | |||
4569 | case UTT_IsMemberPointer: | |||
4570 | return T->isMemberPointerType(); | |||
4571 | ||||
4572 | // Type trait expressions which correspond to the type property predicates | |||
4573 | // in C++0x [meta.unary.prop]. | |||
4574 | case UTT_IsConst: | |||
4575 | return T.isConstQualified(); | |||
4576 | case UTT_IsVolatile: | |||
4577 | return T.isVolatileQualified(); | |||
4578 | case UTT_IsTrivial: | |||
4579 | return T.isTrivialType(C); | |||
4580 | case UTT_IsTriviallyCopyable: | |||
4581 | return T.isTriviallyCopyableType(C); | |||
4582 | case UTT_IsStandardLayout: | |||
4583 | return T->isStandardLayoutType(); | |||
4584 | case UTT_IsPOD: | |||
4585 | return T.isPODType(C); | |||
4586 | case UTT_IsLiteral: | |||
4587 | return T->isLiteralType(C); | |||
4588 | case UTT_IsEmpty: | |||
4589 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4590 | return !RD->isUnion() && RD->isEmpty(); | |||
4591 | return false; | |||
4592 | case UTT_IsPolymorphic: | |||
4593 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4594 | return !RD->isUnion() && RD->isPolymorphic(); | |||
4595 | return false; | |||
4596 | case UTT_IsAbstract: | |||
4597 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4598 | return !RD->isUnion() && RD->isAbstract(); | |||
4599 | return false; | |||
4600 | case UTT_IsAggregate: | |||
4601 | // Report vector extensions and complex types as aggregates because they | |||
4602 | // support aggregate initialization. GCC mirrors this behavior for vectors | |||
4603 | // but not _Complex. | |||
4604 | return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || | |||
4605 | T->isAnyComplexType(); | |||
4606 | // __is_interface_class only returns true when CL is invoked in /CLR mode and | |||
4607 | // even then only when it is used with the 'interface struct ...' syntax | |||
4608 | // Clang doesn't support /CLR which makes this type trait moot. | |||
4609 | case UTT_IsInterfaceClass: | |||
4610 | return false; | |||
4611 | case UTT_IsFinal: | |||
4612 | case UTT_IsSealed: | |||
4613 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4614 | return RD->hasAttr<FinalAttr>(); | |||
4615 | return false; | |||
4616 | case UTT_IsSigned: | |||
4617 | // Enum types should always return false. | |||
4618 | // Floating points should always return true. | |||
4619 | return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType()); | |||
4620 | case UTT_IsUnsigned: | |||
4621 | return T->isUnsignedIntegerType(); | |||
4622 | ||||
4623 | // Type trait expressions which query classes regarding their construction, | |||
4624 | // destruction, and copying. Rather than being based directly on the | |||
4625 | // related type predicates in the standard, they are specified by both | |||
4626 | // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those | |||
4627 | // specifications. | |||
4628 | // | |||
4629 | // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html | |||
4630 | // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index | |||
4631 | // | |||
4632 | // Note that these builtins do not behave as documented in g++: if a class | |||
4633 | // has both a trivial and a non-trivial special member of a particular kind, | |||
4634 | // they return false! For now, we emulate this behavior. | |||
4635 | // FIXME: This appears to be a g++ bug: more complex cases reveal that it | |||
4636 | // does not correctly compute triviality in the presence of multiple special | |||
4637 | // members of the same kind. Revisit this once the g++ bug is fixed. | |||
4638 | case UTT_HasTrivialDefaultConstructor: | |||
4639 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
4640 | // If __is_pod (type) is true then the trait is true, else if type is | |||
4641 | // a cv class or union type (or array thereof) with a trivial default | |||
4642 | // constructor ([class.ctor]) then the trait is true, else it is false. | |||
4643 | if (T.isPODType(C)) | |||
4644 | return true; | |||
4645 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
4646 | return RD->hasTrivialDefaultConstructor() && | |||
4647 | !RD->hasNonTrivialDefaultConstructor(); | |||
4648 | return false; | |||
4649 | case UTT_HasTrivialMoveConstructor: | |||
4650 | // This trait is implemented by MSVC 2012 and needed to parse the | |||
4651 | // standard library headers. Specifically this is used as the logic | |||
4652 | // behind std::is_trivially_move_constructible (20.9.4.3). | |||
4653 | if (T.isPODType(C)) | |||
4654 | return true; | |||
4655 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
4656 | return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); | |||
4657 | return false; | |||
4658 | case UTT_HasTrivialCopy: | |||
4659 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
4660 | // If __is_pod (type) is true or type is a reference type then | |||
4661 | // the trait is true, else if type is a cv class or union type | |||
4662 | // with a trivial copy constructor ([class.copy]) then the trait | |||
4663 | // is true, else it is false. | |||
4664 | if (T.isPODType(C) || T->isReferenceType()) | |||
4665 | return true; | |||
4666 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4667 | return RD->hasTrivialCopyConstructor() && | |||
4668 | !RD->hasNonTrivialCopyConstructor(); | |||
4669 | return false; | |||
4670 | case UTT_HasTrivialMoveAssign: | |||
4671 | // This trait is implemented by MSVC 2012 and needed to parse the | |||
4672 | // standard library headers. Specifically it is used as the logic | |||
4673 | // behind std::is_trivially_move_assignable (20.9.4.3) | |||
4674 | if (T.isPODType(C)) | |||
4675 | return true; | |||
4676 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
4677 | return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); | |||
4678 | return false; | |||
4679 | case UTT_HasTrivialAssign: | |||
4680 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
4681 | // If type is const qualified or is a reference type then the | |||
4682 | // trait is false. Otherwise if __is_pod (type) is true then the | |||
4683 | // trait is true, else if type is a cv class or union type with | |||
4684 | // a trivial copy assignment ([class.copy]) then the trait is | |||
4685 | // true, else it is false. | |||
4686 | // Note: the const and reference restrictions are interesting, | |||
4687 | // given that const and reference members don't prevent a class | |||
4688 | // from having a trivial copy assignment operator (but do cause | |||
4689 | // errors if the copy assignment operator is actually used, q.v. | |||
4690 | // [class.copy]p12). | |||
4691 | ||||
4692 | if (T.isConstQualified()) | |||
4693 | return false; | |||
4694 | if (T.isPODType(C)) | |||
4695 | return true; | |||
4696 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4697 | return RD->hasTrivialCopyAssignment() && | |||
4698 | !RD->hasNonTrivialCopyAssignment(); | |||
4699 | return false; | |||
4700 | case UTT_IsDestructible: | |||
4701 | case UTT_IsTriviallyDestructible: | |||
4702 | case UTT_IsNothrowDestructible: | |||
4703 | // C++14 [meta.unary.prop]: | |||
4704 | // For reference types, is_destructible<T>::value is true. | |||
4705 | if (T->isReferenceType()) | |||
4706 | return true; | |||
4707 | ||||
4708 | // Objective-C++ ARC: autorelease types don't require destruction. | |||
4709 | if (T->isObjCLifetimeType() && | |||
4710 | T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) | |||
4711 | return true; | |||
4712 | ||||
4713 | // C++14 [meta.unary.prop]: | |||
4714 | // For incomplete types and function types, is_destructible<T>::value is | |||
4715 | // false. | |||
4716 | if (T->isIncompleteType() || T->isFunctionType()) | |||
4717 | return false; | |||
4718 | ||||
4719 | // A type that requires destruction (via a non-trivial destructor or ARC | |||
4720 | // lifetime semantics) is not trivially-destructible. | |||
4721 | if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) | |||
4722 | return false; | |||
4723 | ||||
4724 | // C++14 [meta.unary.prop]: | |||
4725 | // For object types and given U equal to remove_all_extents_t<T>, if the | |||
4726 | // expression std::declval<U&>().~U() is well-formed when treated as an | |||
4727 | // unevaluated operand (Clause 5), then is_destructible<T>::value is true | |||
4728 | if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { | |||
4729 | CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); | |||
4730 | if (!Destructor) | |||
4731 | return false; | |||
4732 | // C++14 [dcl.fct.def.delete]p2: | |||
4733 | // A program that refers to a deleted function implicitly or | |||
4734 | // explicitly, other than to declare it, is ill-formed. | |||
4735 | if (Destructor->isDeleted()) | |||
4736 | return false; | |||
4737 | if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) | |||
4738 | return false; | |||
4739 | if (UTT == UTT_IsNothrowDestructible) { | |||
4740 | const FunctionProtoType *CPT = | |||
4741 | Destructor->getType()->getAs<FunctionProtoType>(); | |||
4742 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
4743 | if (!CPT || !CPT->isNothrow()) | |||
4744 | return false; | |||
4745 | } | |||
4746 | } | |||
4747 | return true; | |||
4748 | ||||
4749 | case UTT_HasTrivialDestructor: | |||
4750 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html | |||
4751 | // If __is_pod (type) is true or type is a reference type | |||
4752 | // then the trait is true, else if type is a cv class or union | |||
4753 | // type (or array thereof) with a trivial destructor | |||
4754 | // ([class.dtor]) then the trait is true, else it is | |||
4755 | // false. | |||
4756 | if (T.isPODType(C) || T->isReferenceType()) | |||
4757 | return true; | |||
4758 | ||||
4759 | // Objective-C++ ARC: autorelease types don't require destruction. | |||
4760 | if (T->isObjCLifetimeType() && | |||
4761 | T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) | |||
4762 | return true; | |||
4763 | ||||
4764 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) | |||
4765 | return RD->hasTrivialDestructor(); | |||
4766 | return false; | |||
4767 | // TODO: Propagate nothrowness for implicitly declared special members. | |||
4768 | case UTT_HasNothrowAssign: | |||
4769 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
4770 | // If type is const qualified or is a reference type then the | |||
4771 | // trait is false. Otherwise if __has_trivial_assign (type) | |||
4772 | // is true then the trait is true, else if type is a cv class | |||
4773 | // or union type with copy assignment operators that are known | |||
4774 | // not to throw an exception then the trait is true, else it is | |||
4775 | // false. | |||
4776 | if (C.getBaseElementType(T).isConstQualified()) | |||
4777 | return false; | |||
4778 | if (T->isReferenceType()) | |||
4779 | return false; | |||
4780 | if (T.isPODType(C) || T->isObjCLifetimeType()) | |||
4781 | return true; | |||
4782 | ||||
4783 | if (const RecordType *RT = T->getAs<RecordType>()) | |||
4784 | return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, | |||
4785 | &CXXRecordDecl::hasTrivialCopyAssignment, | |||
4786 | &CXXRecordDecl::hasNonTrivialCopyAssignment, | |||
4787 | &CXXMethodDecl::isCopyAssignmentOperator); | |||
4788 | return false; | |||
4789 | case UTT_HasNothrowMoveAssign: | |||
4790 | // This trait is implemented by MSVC 2012 and needed to parse the | |||
4791 | // standard library headers. Specifically this is used as the logic | |||
4792 | // behind std::is_nothrow_move_assignable (20.9.4.3). | |||
4793 | if (T.isPODType(C)) | |||
4794 | return true; | |||
4795 | ||||
4796 | if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) | |||
4797 | return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, | |||
4798 | &CXXRecordDecl::hasTrivialMoveAssignment, | |||
4799 | &CXXRecordDecl::hasNonTrivialMoveAssignment, | |||
4800 | &CXXMethodDecl::isMoveAssignmentOperator); | |||
4801 | return false; | |||
4802 | case UTT_HasNothrowCopy: | |||
4803 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
4804 | // If __has_trivial_copy (type) is true then the trait is true, else | |||
4805 | // if type is a cv class or union type with copy constructors that are | |||
4806 | // known not to throw an exception then the trait is true, else it is | |||
4807 | // false. | |||
4808 | if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) | |||
4809 | return true; | |||
4810 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { | |||
4811 | if (RD->hasTrivialCopyConstructor() && | |||
4812 | !RD->hasNonTrivialCopyConstructor()) | |||
4813 | return true; | |||
4814 | ||||
4815 | bool FoundConstructor = false; | |||
4816 | unsigned FoundTQs; | |||
4817 | for (const auto *ND : Self.LookupConstructors(RD)) { | |||
4818 | // A template constructor is never a copy constructor. | |||
4819 | // FIXME: However, it may actually be selected at the actual overload | |||
4820 | // resolution point. | |||
4821 | if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) | |||
4822 | continue; | |||
4823 | // UsingDecl itself is not a constructor | |||
4824 | if (isa<UsingDecl>(ND)) | |||
4825 | continue; | |||
4826 | auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); | |||
4827 | if (Constructor->isCopyConstructor(FoundTQs)) { | |||
4828 | FoundConstructor = true; | |||
4829 | const FunctionProtoType *CPT | |||
4830 | = Constructor->getType()->getAs<FunctionProtoType>(); | |||
4831 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
4832 | if (!CPT) | |||
4833 | return false; | |||
4834 | // TODO: check whether evaluating default arguments can throw. | |||
4835 | // For now, we'll be conservative and assume that they can throw. | |||
4836 | if (!CPT->isNothrow() || CPT->getNumParams() > 1) | |||
4837 | return false; | |||
4838 | } | |||
4839 | } | |||
4840 | ||||
4841 | return FoundConstructor; | |||
4842 | } | |||
4843 | return false; | |||
4844 | case UTT_HasNothrowConstructor: | |||
4845 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html | |||
4846 | // If __has_trivial_constructor (type) is true then the trait is | |||
4847 | // true, else if type is a cv class or union type (or array | |||
4848 | // thereof) with a default constructor that is known not to | |||
4849 | // throw an exception then the trait is true, else it is false. | |||
4850 | if (T.isPODType(C) || T->isObjCLifetimeType()) | |||
4851 | return true; | |||
4852 | if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { | |||
4853 | if (RD->hasTrivialDefaultConstructor() && | |||
4854 | !RD->hasNonTrivialDefaultConstructor()) | |||
4855 | return true; | |||
4856 | ||||
4857 | bool FoundConstructor = false; | |||
4858 | for (const auto *ND : Self.LookupConstructors(RD)) { | |||
4859 | // FIXME: In C++0x, a constructor template can be a default constructor. | |||
4860 | if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) | |||
4861 | continue; | |||
4862 | // UsingDecl itself is not a constructor | |||
4863 | if (isa<UsingDecl>(ND)) | |||
4864 | continue; | |||
4865 | auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); | |||
4866 | if (Constructor->isDefaultConstructor()) { | |||
4867 | FoundConstructor = true; | |||
4868 | const FunctionProtoType *CPT | |||
4869 | = Constructor->getType()->getAs<FunctionProtoType>(); | |||
4870 | CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); | |||
4871 | if (!CPT) | |||
4872 | return false; | |||
4873 | // FIXME: check whether evaluating default arguments can throw. | |||
4874 | // For now, we'll be conservative and assume that they can throw. | |||
4875 | if (!CPT->isNothrow() || CPT->getNumParams() > 0) | |||
4876 | return false; | |||
4877 | } | |||
4878 | } | |||
4879 | return FoundConstructor; | |||
4880 | } | |||
4881 | return false; | |||
4882 | case UTT_HasVirtualDestructor: | |||
4883 | // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: | |||
4884 | // If type is a class type with a virtual destructor ([class.dtor]) | |||
4885 | // then the trait is true, else it is false. | |||
4886 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
4887 | if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) | |||
4888 | return Destructor->isVirtual(); | |||
4889 | return false; | |||
4890 | ||||
4891 | // These type trait expressions are modeled on the specifications for the | |||
4892 | // Embarcadero C++0x type trait functions: | |||
4893 | // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index | |||
4894 | case UTT_IsCompleteType: | |||
4895 | // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): | |||
4896 | // Returns True if and only if T is a complete type at the point of the | |||
4897 | // function call. | |||
4898 | return !T->isIncompleteType(); | |||
4899 | case UTT_HasUniqueObjectRepresentations: | |||
4900 | return C.hasUniqueObjectRepresentations(T); | |||
4901 | } | |||
4902 | } | |||
4903 | ||||
4904 | static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, | |||
4905 | QualType RhsT, SourceLocation KeyLoc); | |||
4906 | ||||
4907 | static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, | |||
4908 | ArrayRef<TypeSourceInfo *> Args, | |||
4909 | SourceLocation RParenLoc) { | |||
4910 | if (Kind <= UTT_Last) | |||
4911 | return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); | |||
4912 | ||||
4913 | // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible | |||
4914 | // traits to avoid duplication. | |||
4915 | if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary) | |||
4916 | return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), | |||
4917 | Args[1]->getType(), RParenLoc); | |||
4918 | ||||
4919 | switch (Kind) { | |||
4920 | case clang::BTT_ReferenceBindsToTemporary: | |||
4921 | case clang::TT_IsConstructible: | |||
4922 | case clang::TT_IsNothrowConstructible: | |||
4923 | case clang::TT_IsTriviallyConstructible: { | |||
4924 | // C++11 [meta.unary.prop]: | |||
4925 | // is_trivially_constructible is defined as: | |||
4926 | // | |||
4927 | // is_constructible<T, Args...>::value is true and the variable | |||
4928 | // definition for is_constructible, as defined below, is known to call | |||
4929 | // no operation that is not trivial. | |||
4930 | // | |||
4931 | // The predicate condition for a template specialization | |||
4932 | // is_constructible<T, Args...> shall be satisfied if and only if the | |||
4933 | // following variable definition would be well-formed for some invented | |||
4934 | // variable t: | |||
4935 | // | |||
4936 | // T t(create<Args>()...); | |||
4937 | assert(!Args.empty())((!Args.empty()) ? static_cast<void> (0) : __assert_fail ("!Args.empty()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 4937, __PRETTY_FUNCTION__)); | |||
4938 | ||||
4939 | // Precondition: T and all types in the parameter pack Args shall be | |||
4940 | // complete types, (possibly cv-qualified) void, or arrays of | |||
4941 | // unknown bound. | |||
4942 | for (const auto *TSI : Args) { | |||
4943 | QualType ArgTy = TSI->getType(); | |||
4944 | if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) | |||
4945 | continue; | |||
4946 | ||||
4947 | if (S.RequireCompleteType(KWLoc, ArgTy, | |||
4948 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
4949 | return false; | |||
4950 | } | |||
4951 | ||||
4952 | // Make sure the first argument is not incomplete nor a function type. | |||
4953 | QualType T = Args[0]->getType(); | |||
4954 | if (T->isIncompleteType() || T->isFunctionType()) | |||
4955 | return false; | |||
4956 | ||||
4957 | // Make sure the first argument is not an abstract type. | |||
4958 | CXXRecordDecl *RD = T->getAsCXXRecordDecl(); | |||
4959 | if (RD && RD->isAbstract()) | |||
4960 | return false; | |||
4961 | ||||
4962 | SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs; | |||
4963 | SmallVector<Expr *, 2> ArgExprs; | |||
4964 | ArgExprs.reserve(Args.size() - 1); | |||
4965 | for (unsigned I = 1, N = Args.size(); I != N; ++I) { | |||
4966 | QualType ArgTy = Args[I]->getType(); | |||
4967 | if (ArgTy->isObjectType() || ArgTy->isFunctionType()) | |||
4968 | ArgTy = S.Context.getRValueReferenceType(ArgTy); | |||
4969 | OpaqueArgExprs.push_back( | |||
4970 | OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), | |||
4971 | ArgTy.getNonLValueExprType(S.Context), | |||
4972 | Expr::getValueKindForType(ArgTy))); | |||
4973 | } | |||
4974 | for (Expr &E : OpaqueArgExprs) | |||
4975 | ArgExprs.push_back(&E); | |||
4976 | ||||
4977 | // Perform the initialization in an unevaluated context within a SFINAE | |||
4978 | // trap at translation unit scope. | |||
4979 | EnterExpressionEvaluationContext Unevaluated( | |||
4980 | S, Sema::ExpressionEvaluationContext::Unevaluated); | |||
4981 | Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); | |||
4982 | Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); | |||
4983 | InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); | |||
4984 | InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, | |||
4985 | RParenLoc)); | |||
4986 | InitializationSequence Init(S, To, InitKind, ArgExprs); | |||
4987 | if (Init.Failed()) | |||
4988 | return false; | |||
4989 | ||||
4990 | ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); | |||
4991 | if (Result.isInvalid() || SFINAE.hasErrorOccurred()) | |||
4992 | return false; | |||
4993 | ||||
4994 | if (Kind == clang::TT_IsConstructible) | |||
4995 | return true; | |||
4996 | ||||
4997 | if (Kind == clang::BTT_ReferenceBindsToTemporary) { | |||
4998 | if (!T->isReferenceType()) | |||
4999 | return false; | |||
5000 | ||||
5001 | return !Init.isDirectReferenceBinding(); | |||
5002 | } | |||
5003 | ||||
5004 | if (Kind == clang::TT_IsNothrowConstructible) | |||
5005 | return S.canThrow(Result.get()) == CT_Cannot; | |||
5006 | ||||
5007 | if (Kind == clang::TT_IsTriviallyConstructible) { | |||
5008 | // Under Objective-C ARC and Weak, if the destination has non-trivial | |||
5009 | // Objective-C lifetime, this is a non-trivial construction. | |||
5010 | if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) | |||
5011 | return false; | |||
5012 | ||||
5013 | // The initialization succeeded; now make sure there are no non-trivial | |||
5014 | // calls. | |||
5015 | return !Result.get()->hasNonTrivialCall(S.Context); | |||
5016 | } | |||
5017 | ||||
5018 | llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5018); | |||
5019 | return false; | |||
5020 | } | |||
5021 | default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5021); | |||
5022 | } | |||
5023 | ||||
5024 | return false; | |||
5025 | } | |||
5026 | ||||
5027 | ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, | |||
5028 | ArrayRef<TypeSourceInfo *> Args, | |||
5029 | SourceLocation RParenLoc) { | |||
5030 | QualType ResultType = Context.getLogicalOperationType(); | |||
5031 | ||||
5032 | if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( | |||
5033 | *this, Kind, KWLoc, Args[0]->getType())) | |||
5034 | return ExprError(); | |||
5035 | ||||
5036 | bool Dependent = false; | |||
5037 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { | |||
5038 | if (Args[I]->getType()->isDependentType()) { | |||
5039 | Dependent = true; | |||
5040 | break; | |||
5041 | } | |||
5042 | } | |||
5043 | ||||
5044 | bool Result = false; | |||
5045 | if (!Dependent) | |||
5046 | Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); | |||
5047 | ||||
5048 | return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, | |||
5049 | RParenLoc, Result); | |||
5050 | } | |||
5051 | ||||
5052 | ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, | |||
5053 | ArrayRef<ParsedType> Args, | |||
5054 | SourceLocation RParenLoc) { | |||
5055 | SmallVector<TypeSourceInfo *, 4> ConvertedArgs; | |||
5056 | ConvertedArgs.reserve(Args.size()); | |||
5057 | ||||
5058 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { | |||
5059 | TypeSourceInfo *TInfo; | |||
5060 | QualType T = GetTypeFromParser(Args[I], &TInfo); | |||
5061 | if (!TInfo) | |||
5062 | TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); | |||
5063 | ||||
5064 | ConvertedArgs.push_back(TInfo); | |||
5065 | } | |||
5066 | ||||
5067 | return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); | |||
5068 | } | |||
5069 | ||||
5070 | static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, | |||
5071 | QualType RhsT, SourceLocation KeyLoc) { | |||
5072 | assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&((!LhsT->isDependentType() && !RhsT->isDependentType () && "Cannot evaluate traits of dependent types") ? static_cast <void> (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5073, __PRETTY_FUNCTION__)) | |||
5073 | "Cannot evaluate traits of dependent types")((!LhsT->isDependentType() && !RhsT->isDependentType () && "Cannot evaluate traits of dependent types") ? static_cast <void> (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5073, __PRETTY_FUNCTION__)); | |||
5074 | ||||
5075 | switch(BTT) { | |||
5076 | case BTT_IsBaseOf: { | |||
5077 | // C++0x [meta.rel]p2 | |||
5078 | // Base is a base class of Derived without regard to cv-qualifiers or | |||
5079 | // Base and Derived are not unions and name the same class type without | |||
5080 | // regard to cv-qualifiers. | |||
5081 | ||||
5082 | const RecordType *lhsRecord = LhsT->getAs<RecordType>(); | |||
5083 | const RecordType *rhsRecord = RhsT->getAs<RecordType>(); | |||
5084 | if (!rhsRecord || !lhsRecord) { | |||
5085 | const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); | |||
5086 | const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); | |||
5087 | if (!LHSObjTy || !RHSObjTy) | |||
5088 | return false; | |||
5089 | ||||
5090 | ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); | |||
5091 | ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); | |||
5092 | if (!BaseInterface || !DerivedInterface) | |||
5093 | return false; | |||
5094 | ||||
5095 | if (Self.RequireCompleteType( | |||
5096 | KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5097 | return false; | |||
5098 | ||||
5099 | return BaseInterface->isSuperClassOf(DerivedInterface); | |||
5100 | } | |||
5101 | ||||
5102 | assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)((Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)) ? static_cast<void> (0) : __assert_fail ("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5103, __PRETTY_FUNCTION__)) | |||
5103 | == (lhsRecord == rhsRecord))((Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)) ? static_cast<void> (0) : __assert_fail ("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5103, __PRETTY_FUNCTION__)); | |||
5104 | ||||
5105 | // Unions are never base classes, and never have base classes. | |||
5106 | // It doesn't matter if they are complete or not. See PR#41843 | |||
5107 | if (lhsRecord && lhsRecord->getDecl()->isUnion()) | |||
5108 | return false; | |||
5109 | if (rhsRecord && rhsRecord->getDecl()->isUnion()) | |||
5110 | return false; | |||
5111 | ||||
5112 | if (lhsRecord == rhsRecord) | |||
5113 | return true; | |||
5114 | ||||
5115 | // C++0x [meta.rel]p2: | |||
5116 | // If Base and Derived are class types and are different types | |||
5117 | // (ignoring possible cv-qualifiers) then Derived shall be a | |||
5118 | // complete type. | |||
5119 | if (Self.RequireCompleteType(KeyLoc, RhsT, | |||
5120 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5121 | return false; | |||
5122 | ||||
5123 | return cast<CXXRecordDecl>(rhsRecord->getDecl()) | |||
5124 | ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); | |||
5125 | } | |||
5126 | case BTT_IsSame: | |||
5127 | return Self.Context.hasSameType(LhsT, RhsT); | |||
5128 | case BTT_TypeCompatible: { | |||
5129 | // GCC ignores cv-qualifiers on arrays for this builtin. | |||
5130 | Qualifiers LhsQuals, RhsQuals; | |||
5131 | QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); | |||
5132 | QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); | |||
5133 | return Self.Context.typesAreCompatible(Lhs, Rhs); | |||
5134 | } | |||
5135 | case BTT_IsConvertible: | |||
5136 | case BTT_IsConvertibleTo: { | |||
5137 | // C++0x [meta.rel]p4: | |||
5138 | // Given the following function prototype: | |||
5139 | // | |||
5140 | // template <class T> | |||
5141 | // typename add_rvalue_reference<T>::type create(); | |||
5142 | // | |||
5143 | // the predicate condition for a template specialization | |||
5144 | // is_convertible<From, To> shall be satisfied if and only if | |||
5145 | // the return expression in the following code would be | |||
5146 | // well-formed, including any implicit conversions to the return | |||
5147 | // type of the function: | |||
5148 | // | |||
5149 | // To test() { | |||
5150 | // return create<From>(); | |||
5151 | // } | |||
5152 | // | |||
5153 | // Access checking is performed as if in a context unrelated to To and | |||
5154 | // From. Only the validity of the immediate context of the expression | |||
5155 | // of the return-statement (including conversions to the return type) | |||
5156 | // is considered. | |||
5157 | // | |||
5158 | // We model the initialization as a copy-initialization of a temporary | |||
5159 | // of the appropriate type, which for this expression is identical to the | |||
5160 | // return statement (since NRVO doesn't apply). | |||
5161 | ||||
5162 | // Functions aren't allowed to return function or array types. | |||
5163 | if (RhsT->isFunctionType() || RhsT->isArrayType()) | |||
5164 | return false; | |||
5165 | ||||
5166 | // A return statement in a void function must have void type. | |||
5167 | if (RhsT->isVoidType()) | |||
5168 | return LhsT->isVoidType(); | |||
5169 | ||||
5170 | // A function definition requires a complete, non-abstract return type. | |||
5171 | if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) | |||
5172 | return false; | |||
5173 | ||||
5174 | // Compute the result of add_rvalue_reference. | |||
5175 | if (LhsT->isObjectType() || LhsT->isFunctionType()) | |||
5176 | LhsT = Self.Context.getRValueReferenceType(LhsT); | |||
5177 | ||||
5178 | // Build a fake source and destination for initialization. | |||
5179 | InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); | |||
5180 | OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), | |||
5181 | Expr::getValueKindForType(LhsT)); | |||
5182 | Expr *FromPtr = &From; | |||
5183 | InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, | |||
5184 | SourceLocation())); | |||
5185 | ||||
5186 | // Perform the initialization in an unevaluated context within a SFINAE | |||
5187 | // trap at translation unit scope. | |||
5188 | EnterExpressionEvaluationContext Unevaluated( | |||
5189 | Self, Sema::ExpressionEvaluationContext::Unevaluated); | |||
5190 | Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); | |||
5191 | Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); | |||
5192 | InitializationSequence Init(Self, To, Kind, FromPtr); | |||
5193 | if (Init.Failed()) | |||
5194 | return false; | |||
5195 | ||||
5196 | ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); | |||
5197 | return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); | |||
5198 | } | |||
5199 | ||||
5200 | case BTT_IsAssignable: | |||
5201 | case BTT_IsNothrowAssignable: | |||
5202 | case BTT_IsTriviallyAssignable: { | |||
5203 | // C++11 [meta.unary.prop]p3: | |||
5204 | // is_trivially_assignable is defined as: | |||
5205 | // is_assignable<T, U>::value is true and the assignment, as defined by | |||
5206 | // is_assignable, is known to call no operation that is not trivial | |||
5207 | // | |||
5208 | // is_assignable is defined as: | |||
5209 | // The expression declval<T>() = declval<U>() is well-formed when | |||
5210 | // treated as an unevaluated operand (Clause 5). | |||
5211 | // | |||
5212 | // For both, T and U shall be complete types, (possibly cv-qualified) | |||
5213 | // void, or arrays of unknown bound. | |||
5214 | if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && | |||
5215 | Self.RequireCompleteType(KeyLoc, LhsT, | |||
5216 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5217 | return false; | |||
5218 | if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && | |||
5219 | Self.RequireCompleteType(KeyLoc, RhsT, | |||
5220 | diag::err_incomplete_type_used_in_type_trait_expr)) | |||
5221 | return false; | |||
5222 | ||||
5223 | // cv void is never assignable. | |||
5224 | if (LhsT->isVoidType() || RhsT->isVoidType()) | |||
5225 | return false; | |||
5226 | ||||
5227 | // Build expressions that emulate the effect of declval<T>() and | |||
5228 | // declval<U>(). | |||
5229 | if (LhsT->isObjectType() || LhsT->isFunctionType()) | |||
5230 | LhsT = Self.Context.getRValueReferenceType(LhsT); | |||
5231 | if (RhsT->isObjectType() || RhsT->isFunctionType()) | |||
5232 | RhsT = Self.Context.getRValueReferenceType(RhsT); | |||
5233 | OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), | |||
5234 | Expr::getValueKindForType(LhsT)); | |||
5235 | OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), | |||
5236 | Expr::getValueKindForType(RhsT)); | |||
5237 | ||||
5238 | // Attempt the assignment in an unevaluated context within a SFINAE | |||
5239 | // trap at translation unit scope. | |||
5240 | EnterExpressionEvaluationContext Unevaluated( | |||
5241 | Self, Sema::ExpressionEvaluationContext::Unevaluated); | |||
5242 | Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); | |||
5243 | Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); | |||
5244 | ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, | |||
5245 | &Rhs); | |||
5246 | if (Result.isInvalid()) | |||
5247 | return false; | |||
5248 | ||||
5249 | // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. | |||
5250 | Self.CheckUnusedVolatileAssignment(Result.get()); | |||
5251 | ||||
5252 | if (SFINAE.hasErrorOccurred()) | |||
5253 | return false; | |||
5254 | ||||
5255 | if (BTT == BTT_IsAssignable) | |||
5256 | return true; | |||
5257 | ||||
5258 | if (BTT == BTT_IsNothrowAssignable) | |||
5259 | return Self.canThrow(Result.get()) == CT_Cannot; | |||
5260 | ||||
5261 | if (BTT == BTT_IsTriviallyAssignable) { | |||
5262 | // Under Objective-C ARC and Weak, if the destination has non-trivial | |||
5263 | // Objective-C lifetime, this is a non-trivial assignment. | |||
5264 | if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) | |||
5265 | return false; | |||
5266 | ||||
5267 | return !Result.get()->hasNonTrivialCall(Self.Context); | |||
5268 | } | |||
5269 | ||||
5270 | llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5270); | |||
5271 | return false; | |||
5272 | } | |||
5273 | default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5273); | |||
5274 | } | |||
5275 | llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5275); | |||
5276 | } | |||
5277 | ||||
5278 | ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, | |||
5279 | SourceLocation KWLoc, | |||
5280 | ParsedType Ty, | |||
5281 | Expr* DimExpr, | |||
5282 | SourceLocation RParen) { | |||
5283 | TypeSourceInfo *TSInfo; | |||
5284 | QualType T = GetTypeFromParser(Ty, &TSInfo); | |||
5285 | if (!TSInfo) | |||
5286 | TSInfo = Context.getTrivialTypeSourceInfo(T); | |||
5287 | ||||
5288 | return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); | |||
5289 | } | |||
5290 | ||||
5291 | static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, | |||
5292 | QualType T, Expr *DimExpr, | |||
5293 | SourceLocation KeyLoc) { | |||
5294 | assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")((!T->isDependentType() && "Cannot evaluate traits of dependent type" ) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5294, __PRETTY_FUNCTION__)); | |||
5295 | ||||
5296 | switch(ATT) { | |||
5297 | case ATT_ArrayRank: | |||
5298 | if (T->isArrayType()) { | |||
5299 | unsigned Dim = 0; | |||
5300 | while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { | |||
5301 | ++Dim; | |||
5302 | T = AT->getElementType(); | |||
5303 | } | |||
5304 | return Dim; | |||
5305 | } | |||
5306 | return 0; | |||
5307 | ||||
5308 | case ATT_ArrayExtent: { | |||
5309 | llvm::APSInt Value; | |||
5310 | uint64_t Dim; | |||
5311 | if (Self.VerifyIntegerConstantExpression(DimExpr, &Value, | |||
5312 | diag::err_dimension_expr_not_constant_integer, | |||
5313 | false).isInvalid()) | |||
5314 | return 0; | |||
5315 | if (Value.isSigned() && Value.isNegative()) { | |||
5316 | Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) | |||
5317 | << DimExpr->getSourceRange(); | |||
5318 | return 0; | |||
5319 | } | |||
5320 | Dim = Value.getLimitedValue(); | |||
5321 | ||||
5322 | if (T->isArrayType()) { | |||
5323 | unsigned D = 0; | |||
5324 | bool Matched = false; | |||
5325 | while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { | |||
5326 | if (Dim == D) { | |||
5327 | Matched = true; | |||
5328 | break; | |||
5329 | } | |||
5330 | ++D; | |||
5331 | T = AT->getElementType(); | |||
5332 | } | |||
5333 | ||||
5334 | if (Matched && T->isArrayType()) { | |||
5335 | if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) | |||
5336 | return CAT->getSize().getLimitedValue(); | |||
5337 | } | |||
5338 | } | |||
5339 | return 0; | |||
5340 | } | |||
5341 | } | |||
5342 | llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5342); | |||
5343 | } | |||
5344 | ||||
5345 | ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, | |||
5346 | SourceLocation KWLoc, | |||
5347 | TypeSourceInfo *TSInfo, | |||
5348 | Expr* DimExpr, | |||
5349 | SourceLocation RParen) { | |||
5350 | QualType T = TSInfo->getType(); | |||
5351 | ||||
5352 | // FIXME: This should likely be tracked as an APInt to remove any host | |||
5353 | // assumptions about the width of size_t on the target. | |||
5354 | uint64_t Value = 0; | |||
5355 | if (!T->isDependentType()) | |||
5356 | Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); | |||
5357 | ||||
5358 | // While the specification for these traits from the Embarcadero C++ | |||
5359 | // compiler's documentation says the return type is 'unsigned int', Clang | |||
5360 | // returns 'size_t'. On Windows, the primary platform for the Embarcadero | |||
5361 | // compiler, there is no difference. On several other platforms this is an | |||
5362 | // important distinction. | |||
5363 | return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, | |||
5364 | RParen, Context.getSizeType()); | |||
5365 | } | |||
5366 | ||||
5367 | ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, | |||
5368 | SourceLocation KWLoc, | |||
5369 | Expr *Queried, | |||
5370 | SourceLocation RParen) { | |||
5371 | // If error parsing the expression, ignore. | |||
5372 | if (!Queried) | |||
5373 | return ExprError(); | |||
5374 | ||||
5375 | ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); | |||
5376 | ||||
5377 | return Result; | |||
5378 | } | |||
5379 | ||||
5380 | static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { | |||
5381 | switch (ET) { | |||
5382 | case ET_IsLValueExpr: return E->isLValue(); | |||
5383 | case ET_IsRValueExpr: return E->isRValue(); | |||
5384 | } | |||
5385 | llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5385); | |||
5386 | } | |||
5387 | ||||
5388 | ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, | |||
5389 | SourceLocation KWLoc, | |||
5390 | Expr *Queried, | |||
5391 | SourceLocation RParen) { | |||
5392 | if (Queried->isTypeDependent()) { | |||
5393 | // Delay type-checking for type-dependent expressions. | |||
5394 | } else if (Queried->getType()->isPlaceholderType()) { | |||
5395 | ExprResult PE = CheckPlaceholderExpr(Queried); | |||
5396 | if (PE.isInvalid()) return ExprError(); | |||
5397 | return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); | |||
5398 | } | |||
5399 | ||||
5400 | bool Value = EvaluateExpressionTrait(ET, Queried); | |||
5401 | ||||
5402 | return new (Context) | |||
5403 | ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); | |||
5404 | } | |||
5405 | ||||
5406 | QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, | |||
5407 | ExprValueKind &VK, | |||
5408 | SourceLocation Loc, | |||
5409 | bool isIndirect) { | |||
5410 | assert(!LHS.get()->getType()->isPlaceholderType() &&((!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now" ) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5412, __PRETTY_FUNCTION__)) | |||
5411 | !RHS.get()->getType()->isPlaceholderType() &&((!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now" ) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5412, __PRETTY_FUNCTION__)) | |||
5412 | "placeholders should have been weeded out by now")((!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now" ) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5412, __PRETTY_FUNCTION__)); | |||
5413 | ||||
5414 | // The LHS undergoes lvalue conversions if this is ->*, and undergoes the | |||
5415 | // temporary materialization conversion otherwise. | |||
5416 | if (isIndirect) | |||
5417 | LHS = DefaultLvalueConversion(LHS.get()); | |||
5418 | else if (LHS.get()->isRValue()) | |||
5419 | LHS = TemporaryMaterializationConversion(LHS.get()); | |||
5420 | if (LHS.isInvalid()) | |||
5421 | return QualType(); | |||
5422 | ||||
5423 | // The RHS always undergoes lvalue conversions. | |||
5424 | RHS = DefaultLvalueConversion(RHS.get()); | |||
5425 | if (RHS.isInvalid()) return QualType(); | |||
5426 | ||||
5427 | const char *OpSpelling = isIndirect ? "->*" : ".*"; | |||
5428 | // C++ 5.5p2 | |||
5429 | // The binary operator .* [p3: ->*] binds its second operand, which shall | |||
5430 | // be of type "pointer to member of T" (where T is a completely-defined | |||
5431 | // class type) [...] | |||
5432 | QualType RHSType = RHS.get()->getType(); | |||
5433 | const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); | |||
5434 | if (!MemPtr) { | |||
5435 | Diag(Loc, diag::err_bad_memptr_rhs) | |||
5436 | << OpSpelling << RHSType << RHS.get()->getSourceRange(); | |||
5437 | return QualType(); | |||
5438 | } | |||
5439 | ||||
5440 | QualType Class(MemPtr->getClass(), 0); | |||
5441 | ||||
5442 | // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the | |||
5443 | // member pointer points must be completely-defined. However, there is no | |||
5444 | // reason for this semantic distinction, and the rule is not enforced by | |||
5445 | // other compilers. Therefore, we do not check this property, as it is | |||
5446 | // likely to be considered a defect. | |||
5447 | ||||
5448 | // C++ 5.5p2 | |||
5449 | // [...] to its first operand, which shall be of class T or of a class of | |||
5450 | // which T is an unambiguous and accessible base class. [p3: a pointer to | |||
5451 | // such a class] | |||
5452 | QualType LHSType = LHS.get()->getType(); | |||
5453 | if (isIndirect) { | |||
5454 | if (const PointerType *Ptr = LHSType->getAs<PointerType>()) | |||
5455 | LHSType = Ptr->getPointeeType(); | |||
5456 | else { | |||
5457 | Diag(Loc, diag::err_bad_memptr_lhs) | |||
5458 | << OpSpelling << 1 << LHSType | |||
5459 | << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); | |||
5460 | return QualType(); | |||
5461 | } | |||
5462 | } | |||
5463 | ||||
5464 | if (!Context.hasSameUnqualifiedType(Class, LHSType)) { | |||
5465 | // If we want to check the hierarchy, we need a complete type. | |||
5466 | if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, | |||
5467 | OpSpelling, (int)isIndirect)) { | |||
5468 | return QualType(); | |||
5469 | } | |||
5470 | ||||
5471 | if (!IsDerivedFrom(Loc, LHSType, Class)) { | |||
5472 | Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling | |||
5473 | << (int)isIndirect << LHS.get()->getType(); | |||
5474 | return QualType(); | |||
5475 | } | |||
5476 | ||||
5477 | CXXCastPath BasePath; | |||
5478 | if (CheckDerivedToBaseConversion( | |||
5479 | LHSType, Class, Loc, | |||
5480 | SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), | |||
5481 | &BasePath)) | |||
5482 | return QualType(); | |||
5483 | ||||
5484 | // Cast LHS to type of use. | |||
5485 | QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); | |||
5486 | if (isIndirect) | |||
5487 | UseType = Context.getPointerType(UseType); | |||
5488 | ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind(); | |||
5489 | LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, | |||
5490 | &BasePath); | |||
5491 | } | |||
5492 | ||||
5493 | if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { | |||
5494 | // Diagnose use of pointer-to-member type which when used as | |||
5495 | // the functional cast in a pointer-to-member expression. | |||
5496 | Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; | |||
5497 | return QualType(); | |||
5498 | } | |||
5499 | ||||
5500 | // C++ 5.5p2 | |||
5501 | // The result is an object or a function of the type specified by the | |||
5502 | // second operand. | |||
5503 | // The cv qualifiers are the union of those in the pointer and the left side, | |||
5504 | // in accordance with 5.5p5 and 5.2.5. | |||
5505 | QualType Result = MemPtr->getPointeeType(); | |||
5506 | Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); | |||
5507 | ||||
5508 | // C++0x [expr.mptr.oper]p6: | |||
5509 | // In a .* expression whose object expression is an rvalue, the program is | |||
5510 | // ill-formed if the second operand is a pointer to member function with | |||
5511 | // ref-qualifier &. In a ->* expression or in a .* expression whose object | |||
5512 | // expression is an lvalue, the program is ill-formed if the second operand | |||
5513 | // is a pointer to member function with ref-qualifier &&. | |||
5514 | if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { | |||
5515 | switch (Proto->getRefQualifier()) { | |||
5516 | case RQ_None: | |||
5517 | // Do nothing | |||
5518 | break; | |||
5519 | ||||
5520 | case RQ_LValue: | |||
5521 | if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { | |||
5522 | // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq | |||
5523 | // is (exactly) 'const'. | |||
5524 | if (Proto->isConst() && !Proto->isVolatile()) | |||
5525 | Diag(Loc, getLangOpts().CPlusPlus2a | |||
5526 | ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue | |||
5527 | : diag::ext_pointer_to_const_ref_member_on_rvalue); | |||
5528 | else | |||
5529 | Diag(Loc, diag::err_pointer_to_member_oper_value_classify) | |||
5530 | << RHSType << 1 << LHS.get()->getSourceRange(); | |||
5531 | } | |||
5532 | break; | |||
5533 | ||||
5534 | case RQ_RValue: | |||
5535 | if (isIndirect || !LHS.get()->Classify(Context).isRValue()) | |||
5536 | Diag(Loc, diag::err_pointer_to_member_oper_value_classify) | |||
5537 | << RHSType << 0 << LHS.get()->getSourceRange(); | |||
5538 | break; | |||
5539 | } | |||
5540 | } | |||
5541 | ||||
5542 | // C++ [expr.mptr.oper]p6: | |||
5543 | // The result of a .* expression whose second operand is a pointer | |||
5544 | // to a data member is of the same value category as its | |||
5545 | // first operand. The result of a .* expression whose second | |||
5546 | // operand is a pointer to a member function is a prvalue. The | |||
5547 | // result of an ->* expression is an lvalue if its second operand | |||
5548 | // is a pointer to data member and a prvalue otherwise. | |||
5549 | if (Result->isFunctionType()) { | |||
5550 | VK = VK_RValue; | |||
5551 | return Context.BoundMemberTy; | |||
5552 | } else if (isIndirect) { | |||
5553 | VK = VK_LValue; | |||
5554 | } else { | |||
5555 | VK = LHS.get()->getValueKind(); | |||
5556 | } | |||
5557 | ||||
5558 | return Result; | |||
5559 | } | |||
5560 | ||||
5561 | /// Try to convert a type to another according to C++11 5.16p3. | |||
5562 | /// | |||
5563 | /// This is part of the parameter validation for the ? operator. If either | |||
5564 | /// value operand is a class type, the two operands are attempted to be | |||
5565 | /// converted to each other. This function does the conversion in one direction. | |||
5566 | /// It returns true if the program is ill-formed and has already been diagnosed | |||
5567 | /// as such. | |||
5568 | static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, | |||
5569 | SourceLocation QuestionLoc, | |||
5570 | bool &HaveConversion, | |||
5571 | QualType &ToType) { | |||
5572 | HaveConversion = false; | |||
5573 | ToType = To->getType(); | |||
5574 | ||||
5575 | InitializationKind Kind = | |||
5576 | InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation()); | |||
5577 | // C++11 5.16p3 | |||
5578 | // The process for determining whether an operand expression E1 of type T1 | |||
5579 | // can be converted to match an operand expression E2 of type T2 is defined | |||
5580 | // as follows: | |||
5581 | // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be | |||
5582 | // implicitly converted to type "lvalue reference to T2", subject to the | |||
5583 | // constraint that in the conversion the reference must bind directly to | |||
5584 | // an lvalue. | |||
5585 | // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be | |||
5586 | // implicitly converted to the type "rvalue reference to R2", subject to | |||
5587 | // the constraint that the reference must bind directly. | |||
5588 | if (To->isLValue() || To->isXValue()) { | |||
5589 | QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType) | |||
5590 | : Self.Context.getRValueReferenceType(ToType); | |||
5591 | ||||
5592 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); | |||
5593 | ||||
5594 | InitializationSequence InitSeq(Self, Entity, Kind, From); | |||
5595 | if (InitSeq.isDirectReferenceBinding()) { | |||
5596 | ToType = T; | |||
5597 | HaveConversion = true; | |||
5598 | return false; | |||
5599 | } | |||
5600 | ||||
5601 | if (InitSeq.isAmbiguous()) | |||
5602 | return InitSeq.Diagnose(Self, Entity, Kind, From); | |||
5603 | } | |||
5604 | ||||
5605 | // -- If E2 is an rvalue, or if the conversion above cannot be done: | |||
5606 | // -- if E1 and E2 have class type, and the underlying class types are | |||
5607 | // the same or one is a base class of the other: | |||
5608 | QualType FTy = From->getType(); | |||
5609 | QualType TTy = To->getType(); | |||
5610 | const RecordType *FRec = FTy->getAs<RecordType>(); | |||
5611 | const RecordType *TRec = TTy->getAs<RecordType>(); | |||
5612 | bool FDerivedFromT = FRec && TRec && FRec != TRec && | |||
5613 | Self.IsDerivedFrom(QuestionLoc, FTy, TTy); | |||
5614 | if (FRec && TRec && (FRec == TRec || FDerivedFromT || | |||
5615 | Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { | |||
5616 | // E1 can be converted to match E2 if the class of T2 is the | |||
5617 | // same type as, or a base class of, the class of T1, and | |||
5618 | // [cv2 > cv1]. | |||
5619 | if (FRec == TRec || FDerivedFromT) { | |||
5620 | if (TTy.isAtLeastAsQualifiedAs(FTy)) { | |||
5621 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); | |||
5622 | InitializationSequence InitSeq(Self, Entity, Kind, From); | |||
5623 | if (InitSeq) { | |||
5624 | HaveConversion = true; | |||
5625 | return false; | |||
5626 | } | |||
5627 | ||||
5628 | if (InitSeq.isAmbiguous()) | |||
5629 | return InitSeq.Diagnose(Self, Entity, Kind, From); | |||
5630 | } | |||
5631 | } | |||
5632 | ||||
5633 | return false; | |||
5634 | } | |||
5635 | ||||
5636 | // -- Otherwise: E1 can be converted to match E2 if E1 can be | |||
5637 | // implicitly converted to the type that expression E2 would have | |||
5638 | // if E2 were converted to an rvalue (or the type it has, if E2 is | |||
5639 | // an rvalue). | |||
5640 | // | |||
5641 | // This actually refers very narrowly to the lvalue-to-rvalue conversion, not | |||
5642 | // to the array-to-pointer or function-to-pointer conversions. | |||
5643 | TTy = TTy.getNonLValueExprType(Self.Context); | |||
5644 | ||||
5645 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); | |||
5646 | InitializationSequence InitSeq(Self, Entity, Kind, From); | |||
5647 | HaveConversion = !InitSeq.Failed(); | |||
5648 | ToType = TTy; | |||
5649 | if (InitSeq.isAmbiguous()) | |||
5650 | return InitSeq.Diagnose(Self, Entity, Kind, From); | |||
5651 | ||||
5652 | return false; | |||
5653 | } | |||
5654 | ||||
5655 | /// Try to find a common type for two according to C++0x 5.16p5. | |||
5656 | /// | |||
5657 | /// This is part of the parameter validation for the ? operator. If either | |||
5658 | /// value operand is a class type, overload resolution is used to find a | |||
5659 | /// conversion to a common type. | |||
5660 | static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, | |||
5661 | SourceLocation QuestionLoc) { | |||
5662 | Expr *Args[2] = { LHS.get(), RHS.get() }; | |||
5663 | OverloadCandidateSet CandidateSet(QuestionLoc, | |||
5664 | OverloadCandidateSet::CSK_Operator); | |||
5665 | Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, | |||
5666 | CandidateSet); | |||
5667 | ||||
5668 | OverloadCandidateSet::iterator Best; | |||
5669 | switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { | |||
5670 | case OR_Success: { | |||
5671 | // We found a match. Perform the conversions on the arguments and move on. | |||
5672 | ExprResult LHSRes = Self.PerformImplicitConversion( | |||
5673 | LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], | |||
5674 | Sema::AA_Converting); | |||
5675 | if (LHSRes.isInvalid()) | |||
5676 | break; | |||
5677 | LHS = LHSRes; | |||
5678 | ||||
5679 | ExprResult RHSRes = Self.PerformImplicitConversion( | |||
5680 | RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], | |||
5681 | Sema::AA_Converting); | |||
5682 | if (RHSRes.isInvalid()) | |||
5683 | break; | |||
5684 | RHS = RHSRes; | |||
5685 | if (Best->Function) | |||
5686 | Self.MarkFunctionReferenced(QuestionLoc, Best->Function); | |||
5687 | return false; | |||
5688 | } | |||
5689 | ||||
5690 | case OR_No_Viable_Function: | |||
5691 | ||||
5692 | // Emit a better diagnostic if one of the expressions is a null pointer | |||
5693 | // constant and the other is a pointer type. In this case, the user most | |||
5694 | // likely forgot to take the address of the other expression. | |||
5695 | if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | |||
5696 | return true; | |||
5697 | ||||
5698 | Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
5699 | << LHS.get()->getType() << RHS.get()->getType() | |||
5700 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
5701 | return true; | |||
5702 | ||||
5703 | case OR_Ambiguous: | |||
5704 | Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) | |||
5705 | << LHS.get()->getType() << RHS.get()->getType() | |||
5706 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
5707 | // FIXME: Print the possible common types by printing the return types of | |||
5708 | // the viable candidates. | |||
5709 | break; | |||
5710 | ||||
5711 | case OR_Deleted: | |||
5712 | llvm_unreachable("Conditional operator has only built-in overloads")::llvm::llvm_unreachable_internal("Conditional operator has only built-in overloads" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5712); | |||
5713 | } | |||
5714 | return true; | |||
5715 | } | |||
5716 | ||||
5717 | /// Perform an "extended" implicit conversion as returned by | |||
5718 | /// TryClassUnification. | |||
5719 | static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { | |||
5720 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); | |||
5721 | InitializationKind Kind = | |||
5722 | InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation()); | |||
5723 | Expr *Arg = E.get(); | |||
5724 | InitializationSequence InitSeq(Self, Entity, Kind, Arg); | |||
5725 | ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); | |||
5726 | if (Result.isInvalid()) | |||
5727 | return true; | |||
5728 | ||||
5729 | E = Result; | |||
5730 | return false; | |||
5731 | } | |||
5732 | ||||
5733 | /// Check the operands of ?: under C++ semantics. | |||
5734 | /// | |||
5735 | /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y | |||
5736 | /// extension. In this case, LHS == Cond. (But they're not aliases.) | |||
5737 | QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, | |||
5738 | ExprResult &RHS, ExprValueKind &VK, | |||
5739 | ExprObjectKind &OK, | |||
5740 | SourceLocation QuestionLoc) { | |||
5741 | // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ | |||
5742 | // interface pointers. | |||
5743 | ||||
5744 | // C++11 [expr.cond]p1 | |||
5745 | // The first expression is contextually converted to bool. | |||
5746 | // | |||
5747 | // FIXME; GCC's vector extension permits the use of a?b:c where the type of | |||
5748 | // a is that of a integer vector with the same number of elements and | |||
5749 | // size as the vectors of b and c. If one of either b or c is a scalar | |||
5750 | // it is implicitly converted to match the type of the vector. | |||
5751 | // Otherwise the expression is ill-formed. If both b and c are scalars, | |||
5752 | // then b and c are checked and converted to the type of a if possible. | |||
5753 | // Unlike the OpenCL ?: operator, the expression is evaluated as | |||
5754 | // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). | |||
5755 | if (!Cond.get()->isTypeDependent()) { | |||
5756 | ExprResult CondRes = CheckCXXBooleanCondition(Cond.get()); | |||
5757 | if (CondRes.isInvalid()) | |||
5758 | return QualType(); | |||
5759 | Cond = CondRes; | |||
5760 | } | |||
5761 | ||||
5762 | // Assume r-value. | |||
5763 | VK = VK_RValue; | |||
5764 | OK = OK_Ordinary; | |||
5765 | ||||
5766 | // Either of the arguments dependent? | |||
5767 | if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) | |||
5768 | return Context.DependentTy; | |||
5769 | ||||
5770 | // C++11 [expr.cond]p2 | |||
5771 | // If either the second or the third operand has type (cv) void, ... | |||
5772 | QualType LTy = LHS.get()->getType(); | |||
5773 | QualType RTy = RHS.get()->getType(); | |||
5774 | bool LVoid = LTy->isVoidType(); | |||
5775 | bool RVoid = RTy->isVoidType(); | |||
5776 | if (LVoid || RVoid) { | |||
5777 | // ... one of the following shall hold: | |||
5778 | // -- The second or the third operand (but not both) is a (possibly | |||
5779 | // parenthesized) throw-expression; the result is of the type | |||
5780 | // and value category of the other. | |||
5781 | bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); | |||
5782 | bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); | |||
5783 | if (LThrow != RThrow) { | |||
5784 | Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); | |||
5785 | VK = NonThrow->getValueKind(); | |||
5786 | // DR (no number yet): the result is a bit-field if the | |||
5787 | // non-throw-expression operand is a bit-field. | |||
5788 | OK = NonThrow->getObjectKind(); | |||
5789 | return NonThrow->getType(); | |||
5790 | } | |||
5791 | ||||
5792 | // -- Both the second and third operands have type void; the result is of | |||
5793 | // type void and is a prvalue. | |||
5794 | if (LVoid && RVoid) | |||
5795 | return Context.VoidTy; | |||
5796 | ||||
5797 | // Neither holds, error. | |||
5798 | Diag(QuestionLoc, diag::err_conditional_void_nonvoid) | |||
5799 | << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) | |||
5800 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
5801 | return QualType(); | |||
5802 | } | |||
5803 | ||||
5804 | // Neither is void. | |||
5805 | ||||
5806 | // C++11 [expr.cond]p3 | |||
5807 | // Otherwise, if the second and third operand have different types, and | |||
5808 | // either has (cv) class type [...] an attempt is made to convert each of | |||
5809 | // those operands to the type of the other. | |||
5810 | if (!Context.hasSameType(LTy, RTy) && | |||
5811 | (LTy->isRecordType() || RTy->isRecordType())) { | |||
5812 | // These return true if a single direction is already ambiguous. | |||
5813 | QualType L2RType, R2LType; | |||
5814 | bool HaveL2R, HaveR2L; | |||
5815 | if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) | |||
5816 | return QualType(); | |||
5817 | if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) | |||
5818 | return QualType(); | |||
5819 | ||||
5820 | // If both can be converted, [...] the program is ill-formed. | |||
5821 | if (HaveL2R && HaveR2L) { | |||
5822 | Diag(QuestionLoc, diag::err_conditional_ambiguous) | |||
5823 | << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
5824 | return QualType(); | |||
5825 | } | |||
5826 | ||||
5827 | // If exactly one conversion is possible, that conversion is applied to | |||
5828 | // the chosen operand and the converted operands are used in place of the | |||
5829 | // original operands for the remainder of this section. | |||
5830 | if (HaveL2R) { | |||
5831 | if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) | |||
5832 | return QualType(); | |||
5833 | LTy = LHS.get()->getType(); | |||
5834 | } else if (HaveR2L) { | |||
5835 | if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) | |||
5836 | return QualType(); | |||
5837 | RTy = RHS.get()->getType(); | |||
5838 | } | |||
5839 | } | |||
5840 | ||||
5841 | // C++11 [expr.cond]p3 | |||
5842 | // if both are glvalues of the same value category and the same type except | |||
5843 | // for cv-qualification, an attempt is made to convert each of those | |||
5844 | // operands to the type of the other. | |||
5845 | // FIXME: | |||
5846 | // Resolving a defect in P0012R1: we extend this to cover all cases where | |||
5847 | // one of the operands is reference-compatible with the other, in order | |||
5848 | // to support conditionals between functions differing in noexcept. | |||
5849 | ExprValueKind LVK = LHS.get()->getValueKind(); | |||
5850 | ExprValueKind RVK = RHS.get()->getValueKind(); | |||
5851 | if (!Context.hasSameType(LTy, RTy) && | |||
5852 | LVK == RVK && LVK != VK_RValue) { | |||
5853 | // DerivedToBase was already handled by the class-specific case above. | |||
5854 | // FIXME: Should we allow ObjC conversions here? | |||
5855 | bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion; | |||
5856 | if (CompareReferenceRelationship( | |||
5857 | QuestionLoc, LTy, RTy, DerivedToBase, | |||
5858 | ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible && | |||
5859 | !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion && | |||
5860 | // [...] subject to the constraint that the reference must bind | |||
5861 | // directly [...] | |||
5862 | !RHS.get()->refersToBitField() && | |||
5863 | !RHS.get()->refersToVectorElement()) { | |||
5864 | RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); | |||
5865 | RTy = RHS.get()->getType(); | |||
5866 | } else if (CompareReferenceRelationship( | |||
5867 | QuestionLoc, RTy, LTy, DerivedToBase, | |||
5868 | ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible && | |||
5869 | !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion && | |||
5870 | !LHS.get()->refersToBitField() && | |||
5871 | !LHS.get()->refersToVectorElement()) { | |||
5872 | LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); | |||
5873 | LTy = LHS.get()->getType(); | |||
5874 | } | |||
5875 | } | |||
5876 | ||||
5877 | // C++11 [expr.cond]p4 | |||
5878 | // If the second and third operands are glvalues of the same value | |||
5879 | // category and have the same type, the result is of that type and | |||
5880 | // value category and it is a bit-field if the second or the third | |||
5881 | // operand is a bit-field, or if both are bit-fields. | |||
5882 | // We only extend this to bitfields, not to the crazy other kinds of | |||
5883 | // l-values. | |||
5884 | bool Same = Context.hasSameType(LTy, RTy); | |||
5885 | if (Same && LVK == RVK && LVK != VK_RValue && | |||
5886 | LHS.get()->isOrdinaryOrBitFieldObject() && | |||
5887 | RHS.get()->isOrdinaryOrBitFieldObject()) { | |||
5888 | VK = LHS.get()->getValueKind(); | |||
5889 | if (LHS.get()->getObjectKind() == OK_BitField || | |||
5890 | RHS.get()->getObjectKind() == OK_BitField) | |||
5891 | OK = OK_BitField; | |||
5892 | ||||
5893 | // If we have function pointer types, unify them anyway to unify their | |||
5894 | // exception specifications, if any. | |||
5895 | if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { | |||
5896 | Qualifiers Qs = LTy.getQualifiers(); | |||
5897 | LTy = FindCompositePointerType(QuestionLoc, LHS, RHS, | |||
5898 | /*ConvertArgs*/false); | |||
5899 | LTy = Context.getQualifiedType(LTy, Qs); | |||
5900 | ||||
5901 | assert(!LTy.isNull() && "failed to find composite pointer type for "((!LTy.isNull() && "failed to find composite pointer type for " "canonically equivalent function ptr types") ? static_cast< void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5902, __PRETTY_FUNCTION__)) | |||
5902 | "canonically equivalent function ptr types")((!LTy.isNull() && "failed to find composite pointer type for " "canonically equivalent function ptr types") ? static_cast< void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5902, __PRETTY_FUNCTION__)); | |||
5903 | assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type")((Context.hasSameType(LTy, RTy) && "bad composite pointer type" ) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(LTy, RTy) && \"bad composite pointer type\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5903, __PRETTY_FUNCTION__)); | |||
5904 | } | |||
5905 | ||||
5906 | return LTy; | |||
5907 | } | |||
5908 | ||||
5909 | // C++11 [expr.cond]p5 | |||
5910 | // Otherwise, the result is a prvalue. If the second and third operands | |||
5911 | // do not have the same type, and either has (cv) class type, ... | |||
5912 | if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { | |||
5913 | // ... overload resolution is used to determine the conversions (if any) | |||
5914 | // to be applied to the operands. If the overload resolution fails, the | |||
5915 | // program is ill-formed. | |||
5916 | if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) | |||
5917 | return QualType(); | |||
5918 | } | |||
5919 | ||||
5920 | // C++11 [expr.cond]p6 | |||
5921 | // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard | |||
5922 | // conversions are performed on the second and third operands. | |||
5923 | LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); | |||
5924 | RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); | |||
5925 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
5926 | return QualType(); | |||
5927 | LTy = LHS.get()->getType(); | |||
5928 | RTy = RHS.get()->getType(); | |||
5929 | ||||
5930 | // After those conversions, one of the following shall hold: | |||
5931 | // -- The second and third operands have the same type; the result | |||
5932 | // is of that type. If the operands have class type, the result | |||
5933 | // is a prvalue temporary of the result type, which is | |||
5934 | // copy-initialized from either the second operand or the third | |||
5935 | // operand depending on the value of the first operand. | |||
5936 | if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { | |||
5937 | if (LTy->isRecordType()) { | |||
5938 | // The operands have class type. Make a temporary copy. | |||
5939 | InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); | |||
5940 | ||||
5941 | ExprResult LHSCopy = PerformCopyInitialization(Entity, | |||
5942 | SourceLocation(), | |||
5943 | LHS); | |||
5944 | if (LHSCopy.isInvalid()) | |||
5945 | return QualType(); | |||
5946 | ||||
5947 | ExprResult RHSCopy = PerformCopyInitialization(Entity, | |||
5948 | SourceLocation(), | |||
5949 | RHS); | |||
5950 | if (RHSCopy.isInvalid()) | |||
5951 | return QualType(); | |||
5952 | ||||
5953 | LHS = LHSCopy; | |||
5954 | RHS = RHSCopy; | |||
5955 | } | |||
5956 | ||||
5957 | // If we have function pointer types, unify them anyway to unify their | |||
5958 | // exception specifications, if any. | |||
5959 | if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { | |||
5960 | LTy = FindCompositePointerType(QuestionLoc, LHS, RHS); | |||
5961 | assert(!LTy.isNull() && "failed to find composite pointer type for "((!LTy.isNull() && "failed to find composite pointer type for " "canonically equivalent function ptr types") ? static_cast< void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5962, __PRETTY_FUNCTION__)) | |||
5962 | "canonically equivalent function ptr types")((!LTy.isNull() && "failed to find composite pointer type for " "canonically equivalent function ptr types") ? static_cast< void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 5962, __PRETTY_FUNCTION__)); | |||
5963 | } | |||
5964 | ||||
5965 | return LTy; | |||
5966 | } | |||
5967 | ||||
5968 | // Extension: conditional operator involving vector types. | |||
5969 | if (LTy->isVectorType() || RTy->isVectorType()) | |||
5970 | return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, | |||
5971 | /*AllowBothBool*/true, | |||
5972 | /*AllowBoolConversions*/false); | |||
5973 | ||||
5974 | // -- The second and third operands have arithmetic or enumeration type; | |||
5975 | // the usual arithmetic conversions are performed to bring them to a | |||
5976 | // common type, and the result is of that type. | |||
5977 | if (LTy->isArithmeticType() && RTy->isArithmeticType()) { | |||
5978 | QualType ResTy = UsualArithmeticConversions(LHS, RHS); | |||
5979 | if (LHS.isInvalid() || RHS.isInvalid()) | |||
5980 | return QualType(); | |||
5981 | if (ResTy.isNull()) { | |||
5982 | Diag(QuestionLoc, | |||
5983 | diag::err_typecheck_cond_incompatible_operands) << LTy << RTy | |||
5984 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
5985 | return QualType(); | |||
5986 | } | |||
5987 | ||||
5988 | LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); | |||
5989 | RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); | |||
5990 | ||||
5991 | return ResTy; | |||
5992 | } | |||
5993 | ||||
5994 | // -- The second and third operands have pointer type, or one has pointer | |||
5995 | // type and the other is a null pointer constant, or both are null | |||
5996 | // pointer constants, at least one of which is non-integral; pointer | |||
5997 | // conversions and qualification conversions are performed to bring them | |||
5998 | // to their composite pointer type. The result is of the composite | |||
5999 | // pointer type. | |||
6000 | // -- The second and third operands have pointer to member type, or one has | |||
6001 | // pointer to member type and the other is a null pointer constant; | |||
6002 | // pointer to member conversions and qualification conversions are | |||
6003 | // performed to bring them to a common type, whose cv-qualification | |||
6004 | // shall match the cv-qualification of either the second or the third | |||
6005 | // operand. The result is of the common type. | |||
6006 | QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); | |||
6007 | if (!Composite.isNull()) | |||
6008 | return Composite; | |||
6009 | ||||
6010 | // Similarly, attempt to find composite type of two objective-c pointers. | |||
6011 | Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); | |||
6012 | if (!Composite.isNull()) | |||
6013 | return Composite; | |||
6014 | ||||
6015 | // Check if we are using a null with a non-pointer type. | |||
6016 | if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) | |||
6017 | return QualType(); | |||
6018 | ||||
6019 | Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) | |||
6020 | << LHS.get()->getType() << RHS.get()->getType() | |||
6021 | << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); | |||
6022 | return QualType(); | |||
6023 | } | |||
6024 | ||||
6025 | static FunctionProtoType::ExceptionSpecInfo | |||
6026 | mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1, | |||
6027 | FunctionProtoType::ExceptionSpecInfo ESI2, | |||
6028 | SmallVectorImpl<QualType> &ExceptionTypeStorage) { | |||
6029 | ExceptionSpecificationType EST1 = ESI1.Type; | |||
6030 | ExceptionSpecificationType EST2 = ESI2.Type; | |||
6031 | ||||
6032 | // If either of them can throw anything, that is the result. | |||
6033 | if (EST1 == EST_None) return ESI1; | |||
6034 | if (EST2 == EST_None) return ESI2; | |||
6035 | if (EST1 == EST_MSAny) return ESI1; | |||
6036 | if (EST2 == EST_MSAny) return ESI2; | |||
6037 | if (EST1 == EST_NoexceptFalse) return ESI1; | |||
6038 | if (EST2 == EST_NoexceptFalse) return ESI2; | |||
6039 | ||||
6040 | // If either of them is non-throwing, the result is the other. | |||
6041 | if (EST1 == EST_NoThrow) return ESI2; | |||
6042 | if (EST2 == EST_NoThrow) return ESI1; | |||
6043 | if (EST1 == EST_DynamicNone) return ESI2; | |||
6044 | if (EST2 == EST_DynamicNone) return ESI1; | |||
6045 | if (EST1 == EST_BasicNoexcept) return ESI2; | |||
6046 | if (EST2 == EST_BasicNoexcept) return ESI1; | |||
6047 | if (EST1 == EST_NoexceptTrue) return ESI2; | |||
6048 | if (EST2 == EST_NoexceptTrue) return ESI1; | |||
6049 | ||||
6050 | // If we're left with value-dependent computed noexcept expressions, we're | |||
6051 | // stuck. Before C++17, we can just drop the exception specification entirely, | |||
6052 | // since it's not actually part of the canonical type. And this should never | |||
6053 | // happen in C++17, because it would mean we were computing the composite | |||
6054 | // pointer type of dependent types, which should never happen. | |||
6055 | if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) { | |||
6056 | assert(!S.getLangOpts().CPlusPlus17 &&((!S.getLangOpts().CPlusPlus17 && "computing composite pointer type of dependent types" ) ? static_cast<void> (0) : __assert_fail ("!S.getLangOpts().CPlusPlus17 && \"computing composite pointer type of dependent types\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6057, __PRETTY_FUNCTION__)) | |||
6057 | "computing composite pointer type of dependent types")((!S.getLangOpts().CPlusPlus17 && "computing composite pointer type of dependent types" ) ? static_cast<void> (0) : __assert_fail ("!S.getLangOpts().CPlusPlus17 && \"computing composite pointer type of dependent types\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6057, __PRETTY_FUNCTION__)); | |||
6058 | return FunctionProtoType::ExceptionSpecInfo(); | |||
6059 | } | |||
6060 | ||||
6061 | // Switch over the possibilities so that people adding new values know to | |||
6062 | // update this function. | |||
6063 | switch (EST1) { | |||
6064 | case EST_None: | |||
6065 | case EST_DynamicNone: | |||
6066 | case EST_MSAny: | |||
6067 | case EST_BasicNoexcept: | |||
6068 | case EST_DependentNoexcept: | |||
6069 | case EST_NoexceptFalse: | |||
6070 | case EST_NoexceptTrue: | |||
6071 | case EST_NoThrow: | |||
6072 | llvm_unreachable("handled above")::llvm::llvm_unreachable_internal("handled above", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6072); | |||
6073 | ||||
6074 | case EST_Dynamic: { | |||
6075 | // This is the fun case: both exception specifications are dynamic. Form | |||
6076 | // the union of the two lists. | |||
6077 | assert(EST2 == EST_Dynamic && "other cases should already be handled")((EST2 == EST_Dynamic && "other cases should already be handled" ) ? static_cast<void> (0) : __assert_fail ("EST2 == EST_Dynamic && \"other cases should already be handled\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6077, __PRETTY_FUNCTION__)); | |||
6078 | llvm::SmallPtrSet<QualType, 8> Found; | |||
6079 | for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions}) | |||
6080 | for (QualType E : Exceptions) | |||
6081 | if (Found.insert(S.Context.getCanonicalType(E)).second) | |||
6082 | ExceptionTypeStorage.push_back(E); | |||
6083 | ||||
6084 | FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic); | |||
6085 | Result.Exceptions = ExceptionTypeStorage; | |||
6086 | return Result; | |||
6087 | } | |||
6088 | ||||
6089 | case EST_Unevaluated: | |||
6090 | case EST_Uninstantiated: | |||
6091 | case EST_Unparsed: | |||
6092 | llvm_unreachable("shouldn't see unresolved exception specifications here")::llvm::llvm_unreachable_internal("shouldn't see unresolved exception specifications here" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6092); | |||
6093 | } | |||
6094 | ||||
6095 | llvm_unreachable("invalid ExceptionSpecificationType")::llvm::llvm_unreachable_internal("invalid ExceptionSpecificationType" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6095); | |||
6096 | } | |||
6097 | ||||
6098 | /// Find a merged pointer type and convert the two expressions to it. | |||
6099 | /// | |||
6100 | /// This finds the composite pointer type (or member pointer type) for @p E1 | |||
6101 | /// and @p E2 according to C++1z 5p14. It converts both expressions to this | |||
6102 | /// type and returns it. | |||
6103 | /// It does not emit diagnostics. | |||
6104 | /// | |||
6105 | /// \param Loc The location of the operator requiring these two expressions to | |||
6106 | /// be converted to the composite pointer type. | |||
6107 | /// | |||
6108 | /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type. | |||
6109 | QualType Sema::FindCompositePointerType(SourceLocation Loc, | |||
6110 | Expr *&E1, Expr *&E2, | |||
6111 | bool ConvertArgs) { | |||
6112 | assert(getLangOpts().CPlusPlus && "This function assumes C++")((getLangOpts().CPlusPlus && "This function assumes C++" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"This function assumes C++\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6112, __PRETTY_FUNCTION__)); | |||
6113 | ||||
6114 | // C++1z [expr]p14: | |||
6115 | // The composite pointer type of two operands p1 and p2 having types T1 | |||
6116 | // and T2 | |||
6117 | QualType T1 = E1->getType(), T2 = E2->getType(); | |||
6118 | ||||
6119 | // where at least one is a pointer or pointer to member type or | |||
6120 | // std::nullptr_t is: | |||
6121 | bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || | |||
6122 | T1->isNullPtrType(); | |||
6123 | bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || | |||
6124 | T2->isNullPtrType(); | |||
6125 | if (!T1IsPointerLike && !T2IsPointerLike) | |||
6126 | return QualType(); | |||
6127 | ||||
6128 | // - if both p1 and p2 are null pointer constants, std::nullptr_t; | |||
6129 | // This can't actually happen, following the standard, but we also use this | |||
6130 | // to implement the end of [expr.conv], which hits this case. | |||
6131 | // | |||
6132 | // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; | |||
6133 | if (T1IsPointerLike && | |||
6134 | E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { | |||
6135 | if (ConvertArgs) | |||
6136 | E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() | |||
6137 | ? CK_NullToMemberPointer | |||
6138 | : CK_NullToPointer).get(); | |||
6139 | return T1; | |||
6140 | } | |||
6141 | if (T2IsPointerLike && | |||
6142 | E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { | |||
6143 | if (ConvertArgs) | |||
6144 | E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() | |||
6145 | ? CK_NullToMemberPointer | |||
6146 | : CK_NullToPointer).get(); | |||
6147 | return T2; | |||
6148 | } | |||
6149 | ||||
6150 | // Now both have to be pointers or member pointers. | |||
6151 | if (!T1IsPointerLike || !T2IsPointerLike) | |||
6152 | return QualType(); | |||
6153 | assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&((!T1->isNullPtrType() && !T2->isNullPtrType() && "nullptr_t should be a null pointer constant") ? static_cast <void> (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6154, __PRETTY_FUNCTION__)) | |||
6154 | "nullptr_t should be a null pointer constant")((!T1->isNullPtrType() && !T2->isNullPtrType() && "nullptr_t should be a null pointer constant") ? static_cast <void> (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6154, __PRETTY_FUNCTION__)); | |||
6155 | ||||
6156 | // - if T1 or T2 is "pointer to cv1 void" and the other type is | |||
6157 | // "pointer to cv2 T", "pointer to cv12 void", where cv12 is | |||
6158 | // the union of cv1 and cv2; | |||
6159 | // - if T1 or T2 is "pointer to noexcept function" and the other type is | |||
6160 | // "pointer to function", where the function types are otherwise the same, | |||
6161 | // "pointer to function"; | |||
6162 | // FIXME: This rule is defective: it should also permit removing noexcept | |||
6163 | // from a pointer to member function. As a Clang extension, we also | |||
6164 | // permit removing 'noreturn', so we generalize this rule to; | |||
6165 | // - [Clang] If T1 and T2 are both of type "pointer to function" or | |||
6166 | // "pointer to member function" and the pointee types can be unified | |||
6167 | // by a function pointer conversion, that conversion is applied | |||
6168 | // before checking the following rules. | |||
6169 | // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 | |||
6170 | // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), | |||
6171 | // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, | |||
6172 | // respectively; | |||
6173 | // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer | |||
6174 | // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or | |||
6175 | // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and | |||
6176 | // T1 or the cv-combined type of T1 and T2, respectively; | |||
6177 | // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and | |||
6178 | // T2; | |||
6179 | // | |||
6180 | // If looked at in the right way, these bullets all do the same thing. | |||
6181 | // What we do here is, we build the two possible cv-combined types, and try | |||
6182 | // the conversions in both directions. If only one works, or if the two | |||
6183 | // composite types are the same, we have succeeded. | |||
6184 | // FIXME: extended qualifiers? | |||
6185 | // | |||
6186 | // Note that this will fail to find a composite pointer type for "pointer | |||
6187 | // to void" and "pointer to function". We can't actually perform the final | |||
6188 | // conversion in this case, even though a composite pointer type formally | |||
6189 | // exists. | |||
6190 | SmallVector<unsigned, 4> QualifierUnion; | |||
6191 | SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass; | |||
6192 | QualType Composite1 = T1; | |||
6193 | QualType Composite2 = T2; | |||
6194 | unsigned NeedConstBefore = 0; | |||
6195 | while (true) { | |||
6196 | const PointerType *Ptr1, *Ptr2; | |||
6197 | if ((Ptr1 = Composite1->getAs<PointerType>()) && | |||
6198 | (Ptr2 = Composite2->getAs<PointerType>())) { | |||
6199 | Composite1 = Ptr1->getPointeeType(); | |||
6200 | Composite2 = Ptr2->getPointeeType(); | |||
6201 | ||||
6202 | // If we're allowed to create a non-standard composite type, keep track | |||
6203 | // of where we need to fill in additional 'const' qualifiers. | |||
6204 | if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) | |||
6205 | NeedConstBefore = QualifierUnion.size(); | |||
6206 | ||||
6207 | QualifierUnion.push_back( | |||
6208 | Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); | |||
6209 | MemberOfClass.push_back(std::make_pair(nullptr, nullptr)); | |||
6210 | continue; | |||
6211 | } | |||
6212 | ||||
6213 | const MemberPointerType *MemPtr1, *MemPtr2; | |||
6214 | if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && | |||
6215 | (MemPtr2 = Composite2->getAs<MemberPointerType>())) { | |||
6216 | Composite1 = MemPtr1->getPointeeType(); | |||
6217 | Composite2 = MemPtr2->getPointeeType(); | |||
6218 | ||||
6219 | // If we're allowed to create a non-standard composite type, keep track | |||
6220 | // of where we need to fill in additional 'const' qualifiers. | |||
6221 | if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) | |||
6222 | NeedConstBefore = QualifierUnion.size(); | |||
6223 | ||||
6224 | QualifierUnion.push_back( | |||
6225 | Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); | |||
6226 | MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), | |||
6227 | MemPtr2->getClass())); | |||
6228 | continue; | |||
6229 | } | |||
6230 | ||||
6231 | // FIXME: block pointer types? | |||
6232 | ||||
6233 | // Cannot unwrap any more types. | |||
6234 | break; | |||
6235 | } | |||
6236 | ||||
6237 | // Apply the function pointer conversion to unify the types. We've already | |||
6238 | // unwrapped down to the function types, and we want to merge rather than | |||
6239 | // just convert, so do this ourselves rather than calling | |||
6240 | // IsFunctionConversion. | |||
6241 | // | |||
6242 | // FIXME: In order to match the standard wording as closely as possible, we | |||
6243 | // currently only do this under a single level of pointers. Ideally, we would | |||
6244 | // allow this in general, and set NeedConstBefore to the relevant depth on | |||
6245 | // the side(s) where we changed anything. | |||
6246 | if (QualifierUnion.size() == 1) { | |||
6247 | if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { | |||
6248 | if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { | |||
6249 | FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); | |||
6250 | FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); | |||
6251 | ||||
6252 | // The result is noreturn if both operands are. | |||
6253 | bool Noreturn = | |||
6254 | EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); | |||
6255 | EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); | |||
6256 | EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); | |||
6257 | ||||
6258 | // The result is nothrow if both operands are. | |||
6259 | SmallVector<QualType, 8> ExceptionTypeStorage; | |||
6260 | EPI1.ExceptionSpec = EPI2.ExceptionSpec = | |||
6261 | mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec, | |||
6262 | ExceptionTypeStorage); | |||
6263 | ||||
6264 | Composite1 = Context.getFunctionType(FPT1->getReturnType(), | |||
6265 | FPT1->getParamTypes(), EPI1); | |||
6266 | Composite2 = Context.getFunctionType(FPT2->getReturnType(), | |||
6267 | FPT2->getParamTypes(), EPI2); | |||
6268 | } | |||
6269 | } | |||
6270 | } | |||
6271 | ||||
6272 | if (NeedConstBefore) { | |||
6273 | // Extension: Add 'const' to qualifiers that come before the first qualifier | |||
6274 | // mismatch, so that our (non-standard!) composite type meets the | |||
6275 | // requirements of C++ [conv.qual]p4 bullet 3. | |||
6276 | for (unsigned I = 0; I != NeedConstBefore; ++I) | |||
6277 | if ((QualifierUnion[I] & Qualifiers::Const) == 0) | |||
6278 | QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; | |||
6279 | } | |||
6280 | ||||
6281 | // Rewrap the composites as pointers or member pointers with the union CVRs. | |||
6282 | auto MOC = MemberOfClass.rbegin(); | |||
6283 | for (unsigned CVR : llvm::reverse(QualifierUnion)) { | |||
6284 | Qualifiers Quals = Qualifiers::fromCVRMask(CVR); | |||
6285 | auto Classes = *MOC++; | |||
6286 | if (Classes.first && Classes.second) { | |||
6287 | // Rebuild member pointer type | |||
6288 | Composite1 = Context.getMemberPointerType( | |||
6289 | Context.getQualifiedType(Composite1, Quals), Classes.first); | |||
6290 | Composite2 = Context.getMemberPointerType( | |||
6291 | Context.getQualifiedType(Composite2, Quals), Classes.second); | |||
6292 | } else { | |||
6293 | // Rebuild pointer type | |||
6294 | Composite1 = | |||
6295 | Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); | |||
6296 | Composite2 = | |||
6297 | Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); | |||
6298 | } | |||
6299 | } | |||
6300 | ||||
6301 | struct Conversion { | |||
6302 | Sema &S; | |||
6303 | Expr *&E1, *&E2; | |||
6304 | QualType Composite; | |||
6305 | InitializedEntity Entity; | |||
6306 | InitializationKind Kind; | |||
6307 | InitializationSequence E1ToC, E2ToC; | |||
6308 | bool Viable; | |||
6309 | ||||
6310 | Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2, | |||
6311 | QualType Composite) | |||
6312 | : S(S), E1(E1), E2(E2), Composite(Composite), | |||
6313 | Entity(InitializedEntity::InitializeTemporary(Composite)), | |||
6314 | Kind(InitializationKind::CreateCopy(Loc, SourceLocation())), | |||
6315 | E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2), | |||
6316 | Viable(E1ToC && E2ToC) {} | |||
6317 | ||||
6318 | bool perform() { | |||
6319 | ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1); | |||
6320 | if (E1Result.isInvalid()) | |||
6321 | return true; | |||
6322 | E1 = E1Result.getAs<Expr>(); | |||
6323 | ||||
6324 | ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2); | |||
6325 | if (E2Result.isInvalid()) | |||
6326 | return true; | |||
6327 | E2 = E2Result.getAs<Expr>(); | |||
6328 | ||||
6329 | return false; | |||
6330 | } | |||
6331 | }; | |||
6332 | ||||
6333 | // Try to convert to each composite pointer type. | |||
6334 | Conversion C1(*this, Loc, E1, E2, Composite1); | |||
6335 | if (C1.Viable && Context.hasSameType(Composite1, Composite2)) { | |||
6336 | if (ConvertArgs && C1.perform()) | |||
6337 | return QualType(); | |||
6338 | return C1.Composite; | |||
6339 | } | |||
6340 | Conversion C2(*this, Loc, E1, E2, Composite2); | |||
6341 | ||||
6342 | if (C1.Viable == C2.Viable) { | |||
6343 | // Either Composite1 and Composite2 are viable and are different, or | |||
6344 | // neither is viable. | |||
6345 | // FIXME: How both be viable and different? | |||
6346 | return QualType(); | |||
6347 | } | |||
6348 | ||||
6349 | // Convert to the chosen type. | |||
6350 | if (ConvertArgs && (C1.Viable ? C1 : C2).perform()) | |||
6351 | return QualType(); | |||
6352 | ||||
6353 | return C1.Viable ? C1.Composite : C2.Composite; | |||
6354 | } | |||
6355 | ||||
6356 | ExprResult Sema::MaybeBindToTemporary(Expr *E) { | |||
6357 | if (!E) | |||
6358 | return ExprError(); | |||
6359 | ||||
6360 | assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?")((!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?" ) ? static_cast<void> (0) : __assert_fail ("!isa<CXXBindTemporaryExpr>(E) && \"Double-bound temporary?\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6360, __PRETTY_FUNCTION__)); | |||
6361 | ||||
6362 | // If the result is a glvalue, we shouldn't bind it. | |||
6363 | if (!E->isRValue()) | |||
6364 | return E; | |||
6365 | ||||
6366 | // In ARC, calls that return a retainable type can return retained, | |||
6367 | // in which case we have to insert a consuming cast. | |||
6368 | if (getLangOpts().ObjCAutoRefCount && | |||
6369 | E->getType()->isObjCRetainableType()) { | |||
6370 | ||||
6371 | bool ReturnsRetained; | |||
6372 | ||||
6373 | // For actual calls, we compute this by examining the type of the | |||
6374 | // called value. | |||
6375 | if (CallExpr *Call = dyn_cast<CallExpr>(E)) { | |||
6376 | Expr *Callee = Call->getCallee()->IgnoreParens(); | |||
6377 | QualType T = Callee->getType(); | |||
6378 | ||||
6379 | if (T == Context.BoundMemberTy) { | |||
6380 | // Handle pointer-to-members. | |||
6381 | if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) | |||
6382 | T = BinOp->getRHS()->getType(); | |||
6383 | else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) | |||
6384 | T = Mem->getMemberDecl()->getType(); | |||
6385 | } | |||
6386 | ||||
6387 | if (const PointerType *Ptr = T->getAs<PointerType>()) | |||
6388 | T = Ptr->getPointeeType(); | |||
6389 | else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) | |||
6390 | T = Ptr->getPointeeType(); | |||
6391 | else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) | |||
6392 | T = MemPtr->getPointeeType(); | |||
6393 | ||||
6394 | const FunctionType *FTy = T->getAs<FunctionType>(); | |||
6395 | assert(FTy && "call to value not of function type?")((FTy && "call to value not of function type?") ? static_cast <void> (0) : __assert_fail ("FTy && \"call to value not of function type?\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6395, __PRETTY_FUNCTION__)); | |||
6396 | ReturnsRetained = FTy->getExtInfo().getProducesResult(); | |||
6397 | ||||
6398 | // ActOnStmtExpr arranges things so that StmtExprs of retainable | |||
6399 | // type always produce a +1 object. | |||
6400 | } else if (isa<StmtExpr>(E)) { | |||
6401 | ReturnsRetained = true; | |||
6402 | ||||
6403 | // We hit this case with the lambda conversion-to-block optimization; | |||
6404 | // we don't want any extra casts here. | |||
6405 | } else if (isa<CastExpr>(E) && | |||
6406 | isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { | |||
6407 | return E; | |||
6408 | ||||
6409 | // For message sends and property references, we try to find an | |||
6410 | // actual method. FIXME: we should infer retention by selector in | |||
6411 | // cases where we don't have an actual method. | |||
6412 | } else { | |||
6413 | ObjCMethodDecl *D = nullptr; | |||
6414 | if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { | |||
6415 | D = Send->getMethodDecl(); | |||
6416 | } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { | |||
6417 | D = BoxedExpr->getBoxingMethod(); | |||
6418 | } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { | |||
6419 | // Don't do reclaims if we're using the zero-element array | |||
6420 | // constant. | |||
6421 | if (ArrayLit->getNumElements() == 0 && | |||
6422 | Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) | |||
6423 | return E; | |||
6424 | ||||
6425 | D = ArrayLit->getArrayWithObjectsMethod(); | |||
6426 | } else if (ObjCDictionaryLiteral *DictLit | |||
6427 | = dyn_cast<ObjCDictionaryLiteral>(E)) { | |||
6428 | // Don't do reclaims if we're using the zero-element dictionary | |||
6429 | // constant. | |||
6430 | if (DictLit->getNumElements() == 0 && | |||
6431 | Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) | |||
6432 | return E; | |||
6433 | ||||
6434 | D = DictLit->getDictWithObjectsMethod(); | |||
6435 | } | |||
6436 | ||||
6437 | ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); | |||
6438 | ||||
6439 | // Don't do reclaims on performSelector calls; despite their | |||
6440 | // return type, the invoked method doesn't necessarily actually | |||
6441 | // return an object. | |||
6442 | if (!ReturnsRetained && | |||
6443 | D && D->getMethodFamily() == OMF_performSelector) | |||
6444 | return E; | |||
6445 | } | |||
6446 | ||||
6447 | // Don't reclaim an object of Class type. | |||
6448 | if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) | |||
6449 | return E; | |||
6450 | ||||
6451 | Cleanup.setExprNeedsCleanups(true); | |||
6452 | ||||
6453 | CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject | |||
6454 | : CK_ARCReclaimReturnedObject); | |||
6455 | return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, | |||
6456 | VK_RValue); | |||
6457 | } | |||
6458 | ||||
6459 | if (!getLangOpts().CPlusPlus) | |||
6460 | return E; | |||
6461 | ||||
6462 | // Search for the base element type (cf. ASTContext::getBaseElementType) with | |||
6463 | // a fast path for the common case that the type is directly a RecordType. | |||
6464 | const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); | |||
6465 | const RecordType *RT = nullptr; | |||
6466 | while (!RT) { | |||
6467 | switch (T->getTypeClass()) { | |||
6468 | case Type::Record: | |||
6469 | RT = cast<RecordType>(T); | |||
6470 | break; | |||
6471 | case Type::ConstantArray: | |||
6472 | case Type::IncompleteArray: | |||
6473 | case Type::VariableArray: | |||
6474 | case Type::DependentSizedArray: | |||
6475 | T = cast<ArrayType>(T)->getElementType().getTypePtr(); | |||
6476 | break; | |||
6477 | default: | |||
6478 | return E; | |||
6479 | } | |||
6480 | } | |||
6481 | ||||
6482 | // That should be enough to guarantee that this type is complete, if we're | |||
6483 | // not processing a decltype expression. | |||
6484 | CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); | |||
6485 | if (RD->isInvalidDecl() || RD->isDependentContext()) | |||
6486 | return E; | |||
6487 | ||||
6488 | bool IsDecltype = ExprEvalContexts.back().ExprContext == | |||
6489 | ExpressionEvaluationContextRecord::EK_Decltype; | |||
6490 | CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); | |||
6491 | ||||
6492 | if (Destructor) { | |||
6493 | MarkFunctionReferenced(E->getExprLoc(), Destructor); | |||
6494 | CheckDestructorAccess(E->getExprLoc(), Destructor, | |||
6495 | PDiag(diag::err_access_dtor_temp) | |||
6496 | << E->getType()); | |||
6497 | if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) | |||
6498 | return ExprError(); | |||
6499 | ||||
6500 | // If destructor is trivial, we can avoid the extra copy. | |||
6501 | if (Destructor->isTrivial()) | |||
6502 | return E; | |||
6503 | ||||
6504 | // We need a cleanup, but we don't need to remember the temporary. | |||
6505 | Cleanup.setExprNeedsCleanups(true); | |||
6506 | } | |||
6507 | ||||
6508 | CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); | |||
6509 | CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); | |||
6510 | ||||
6511 | if (IsDecltype) | |||
6512 | ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); | |||
6513 | ||||
6514 | return Bind; | |||
6515 | } | |||
6516 | ||||
6517 | ExprResult | |||
6518 | Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { | |||
6519 | if (SubExpr.isInvalid()) | |||
6520 | return ExprError(); | |||
6521 | ||||
6522 | return MaybeCreateExprWithCleanups(SubExpr.get()); | |||
6523 | } | |||
6524 | ||||
6525 | Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { | |||
6526 | assert(SubExpr && "subexpression can't be null!")((SubExpr && "subexpression can't be null!") ? static_cast <void> (0) : __assert_fail ("SubExpr && \"subexpression can't be null!\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6526, __PRETTY_FUNCTION__)); | |||
6527 | ||||
6528 | CleanupVarDeclMarking(); | |||
6529 | ||||
6530 | unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; | |||
6531 | assert(ExprCleanupObjects.size() >= FirstCleanup)((ExprCleanupObjects.size() >= FirstCleanup) ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() >= FirstCleanup" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6531, __PRETTY_FUNCTION__)); | |||
6532 | assert(Cleanup.exprNeedsCleanups() ||((Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup) ? static_cast<void> (0) : __assert_fail ( "Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6533, __PRETTY_FUNCTION__)) | |||
6533 | ExprCleanupObjects.size() == FirstCleanup)((Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup) ? static_cast<void> (0) : __assert_fail ( "Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6533, __PRETTY_FUNCTION__)); | |||
6534 | if (!Cleanup.exprNeedsCleanups()) | |||
6535 | return SubExpr; | |||
6536 | ||||
6537 | auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, | |||
6538 | ExprCleanupObjects.size() - FirstCleanup); | |||
6539 | ||||
6540 | auto *E = ExprWithCleanups::Create( | |||
6541 | Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); | |||
6542 | DiscardCleanupsInEvaluationContext(); | |||
6543 | ||||
6544 | return E; | |||
6545 | } | |||
6546 | ||||
6547 | Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { | |||
6548 | assert(SubStmt && "sub-statement can't be null!")((SubStmt && "sub-statement can't be null!") ? static_cast <void> (0) : __assert_fail ("SubStmt && \"sub-statement can't be null!\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6548, __PRETTY_FUNCTION__)); | |||
6549 | ||||
6550 | CleanupVarDeclMarking(); | |||
6551 | ||||
6552 | if (!Cleanup.exprNeedsCleanups()) | |||
6553 | return SubStmt; | |||
6554 | ||||
6555 | // FIXME: In order to attach the temporaries, wrap the statement into | |||
6556 | // a StmtExpr; currently this is only used for asm statements. | |||
6557 | // This is hacky, either create a new CXXStmtWithTemporaries statement or | |||
6558 | // a new AsmStmtWithTemporaries. | |||
6559 | CompoundStmt *CompStmt = CompoundStmt::Create( | |||
6560 | Context, SubStmt, SourceLocation(), SourceLocation()); | |||
6561 | Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), | |||
6562 | SourceLocation()); | |||
6563 | return MaybeCreateExprWithCleanups(E); | |||
6564 | } | |||
6565 | ||||
6566 | /// Process the expression contained within a decltype. For such expressions, | |||
6567 | /// certain semantic checks on temporaries are delayed until this point, and | |||
6568 | /// are omitted for the 'topmost' call in the decltype expression. If the | |||
6569 | /// topmost call bound a temporary, strip that temporary off the expression. | |||
6570 | ExprResult Sema::ActOnDecltypeExpression(Expr *E) { | |||
6571 | assert(ExprEvalContexts.back().ExprContext ==((ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord ::EK_Decltype && "not in a decltype expression") ? static_cast <void> (0) : __assert_fail ("ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6573, __PRETTY_FUNCTION__)) | |||
6572 | ExpressionEvaluationContextRecord::EK_Decltype &&((ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord ::EK_Decltype && "not in a decltype expression") ? static_cast <void> (0) : __assert_fail ("ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6573, __PRETTY_FUNCTION__)) | |||
6573 | "not in a decltype expression")((ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord ::EK_Decltype && "not in a decltype expression") ? static_cast <void> (0) : __assert_fail ("ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 6573, __PRETTY_FUNCTION__)); | |||
6574 | ||||
6575 | ExprResult Result = CheckPlaceholderExpr(E); | |||
6576 | if (Result.isInvalid()) | |||
6577 | return ExprError(); | |||
6578 | E = Result.get(); | |||
6579 | ||||
6580 | // C++11 [expr.call]p11: | |||
6581 | // If a function call is a prvalue of object type, | |||
6582 | // -- if the function call is either | |||
6583 | // -- the operand of a decltype-specifier, or | |||
6584 | // -- the right operand of a comma operator that is the operand of a | |||
6585 | // decltype-specifier, | |||
6586 | // a temporary object is not introduced for the prvalue. | |||
6587 | ||||
6588 | // Recursively rebuild ParenExprs and comma expressions to strip out the | |||
6589 | // outermost CXXBindTemporaryExpr, if any. | |||
6590 | if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { | |||
6591 | ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); | |||
6592 | if (SubExpr.isInvalid()) | |||
6593 | return ExprError(); | |||
6594 | if (SubExpr.get() == PE->getSubExpr()) | |||
6595 | return E; | |||
6596 | return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); | |||
6597 | } | |||
6598 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
6599 | if (BO->getOpcode() == BO_Comma) { | |||
6600 | ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); | |||
6601 | if (RHS.isInvalid()) | |||
6602 | return ExprError(); | |||
6603 | if (RHS.get() == BO->getRHS()) | |||
6604 | return E; | |||
6605 | return new (Context) BinaryOperator( | |||
6606 | BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(), | |||
6607 | BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures()); | |||
6608 | } | |||
6609 | } | |||
6610 | ||||
6611 | CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); | |||
6612 | CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) | |||
6613 | : nullptr; | |||
6614 | if (TopCall) | |||
6615 | E = TopCall; | |||
6616 | else | |||
6617 | TopBind = nullptr; | |||
6618 | ||||
6619 | // Disable the special decltype handling now. | |||
6620 | ExprEvalContexts.back().ExprContext = | |||
6621 | ExpressionEvaluationContextRecord::EK_Other; | |||
6622 | ||||
6623 | Result = CheckUnevaluatedOperand(E); | |||
6624 | if (Result.isInvalid()) | |||
6625 | return ExprError(); | |||
6626 | E = Result.get(); | |||
6627 | ||||
6628 | // In MS mode, don't perform any extra checking of call return types within a | |||
6629 | // decltype expression. | |||
6630 | if (getLangOpts().MSVCCompat) | |||
6631 | return E; | |||
6632 | ||||
6633 | // Perform the semantic checks we delayed until this point. | |||
6634 | for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); | |||
6635 | I != N; ++I) { | |||
6636 | CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; | |||
6637 | if (Call == TopCall) | |||
6638 | continue; | |||
6639 | ||||
6640 | if (CheckCallReturnType(Call->getCallReturnType(Context), | |||
6641 | Call->getBeginLoc(), Call, Call->getDirectCallee())) | |||
6642 | return ExprError(); | |||
6643 | } | |||
6644 | ||||
6645 | // Now all relevant types are complete, check the destructors are accessible | |||
6646 | // and non-deleted, and annotate them on the temporaries. | |||
6647 | for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); | |||
6648 | I != N; ++I) { | |||
6649 | CXXBindTemporaryExpr *Bind = | |||
6650 | ExprEvalContexts.back().DelayedDecltypeBinds[I]; | |||
6651 | if (Bind == TopBind) | |||
6652 | continue; | |||
6653 | ||||
6654 | CXXTemporary *Temp = Bind->getTemporary(); | |||
6655 | ||||
6656 | CXXRecordDecl *RD = | |||
6657 | Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | |||
6658 | CXXDestructorDecl *Destructor = LookupDestructor(RD); | |||
6659 | Temp->setDestructor(Destructor); | |||
6660 | ||||
6661 | MarkFunctionReferenced(Bind->getExprLoc(), Destructor); | |||
6662 | CheckDestructorAccess(Bind->getExprLoc(), Destructor, | |||
6663 | PDiag(diag::err_access_dtor_temp) | |||
6664 | << Bind->getType()); | |||
6665 | if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) | |||
6666 | return ExprError(); | |||
6667 | ||||
6668 | // We need a cleanup, but we don't need to remember the temporary. | |||
6669 | Cleanup.setExprNeedsCleanups(true); | |||
6670 | } | |||
6671 | ||||
6672 | // Possibly strip off the top CXXBindTemporaryExpr. | |||
6673 | return E; | |||
6674 | } | |||
6675 | ||||
6676 | /// Note a set of 'operator->' functions that were used for a member access. | |||
6677 | static void noteOperatorArrows(Sema &S, | |||
6678 | ArrayRef<FunctionDecl *> OperatorArrows) { | |||
6679 | unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; | |||
6680 | // FIXME: Make this configurable? | |||
6681 | unsigned Limit = 9; | |||
6682 | if (OperatorArrows.size() > Limit) { | |||
6683 | // Produce Limit-1 normal notes and one 'skipping' note. | |||
6684 | SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; | |||
6685 | SkipCount = OperatorArrows.size() - (Limit - 1); | |||
6686 | } | |||
6687 | ||||
6688 | for (unsigned I = 0; I < OperatorArrows.size(); /**/) { | |||
6689 | if (I == SkipStart) { | |||
6690 | S.Diag(OperatorArrows[I]->getLocation(), | |||
6691 | diag::note_operator_arrows_suppressed) | |||
6692 | << SkipCount; | |||
6693 | I += SkipCount; | |||
6694 | } else { | |||
6695 | S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) | |||
6696 | << OperatorArrows[I]->getCallResultType(); | |||
6697 | ++I; | |||
6698 | } | |||
6699 | } | |||
6700 | } | |||
6701 | ||||
6702 | ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, | |||
6703 | SourceLocation OpLoc, | |||
6704 | tok::TokenKind OpKind, | |||
6705 | ParsedType &ObjectType, | |||
6706 | bool &MayBePseudoDestructor) { | |||
6707 | // Since this might be a postfix expression, get rid of ParenListExprs. | |||
6708 | ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); | |||
6709 | if (Result.isInvalid()) return ExprError(); | |||
6710 | Base = Result.get(); | |||
6711 | ||||
6712 | Result = CheckPlaceholderExpr(Base); | |||
6713 | if (Result.isInvalid()) return ExprError(); | |||
6714 | Base = Result.get(); | |||
6715 | ||||
6716 | QualType BaseType = Base->getType(); | |||
6717 | MayBePseudoDestructor = false; | |||
6718 | if (BaseType->isDependentType()) { | |||
6719 | // If we have a pointer to a dependent type and are using the -> operator, | |||
6720 | // the object type is the type that the pointer points to. We might still | |||
6721 | // have enough information about that type to do something useful. | |||
6722 | if (OpKind == tok::arrow) | |||
6723 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) | |||
6724 | BaseType = Ptr->getPointeeType(); | |||
6725 | ||||
6726 | ObjectType = ParsedType::make(BaseType); | |||
6727 | MayBePseudoDestructor = true; | |||
6728 | return Base; | |||
6729 | } | |||
6730 | ||||
6731 | // C++ [over.match.oper]p8: | |||
6732 | // [...] When operator->returns, the operator-> is applied to the value | |||
6733 | // returned, with the original second operand. | |||
6734 | if (OpKind == tok::arrow) { | |||
6735 | QualType StartingType = BaseType; | |||
6736 | bool NoArrowOperatorFound = false; | |||
6737 | bool FirstIteration = true; | |||
6738 | FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); | |||
6739 | // The set of types we've considered so far. | |||
6740 | llvm::SmallPtrSet<CanQualType,8> CTypes; | |||
6741 | SmallVector<FunctionDecl*, 8> OperatorArrows; | |||
6742 | CTypes.insert(Context.getCanonicalType(BaseType)); | |||
6743 | ||||
6744 | while (BaseType->isRecordType()) { | |||
6745 | if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { | |||
6746 | Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) | |||
6747 | << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); | |||
6748 | noteOperatorArrows(*this, OperatorArrows); | |||
6749 | Diag(OpLoc, diag::note_operator_arrow_depth) | |||
6750 | << getLangOpts().ArrowDepth; | |||
6751 | return ExprError(); | |||
6752 | } | |||
6753 | ||||
6754 | Result = BuildOverloadedArrowExpr( | |||
6755 | S, Base, OpLoc, | |||
6756 | // When in a template specialization and on the first loop iteration, | |||
6757 | // potentially give the default diagnostic (with the fixit in a | |||
6758 | // separate note) instead of having the error reported back to here | |||
6759 | // and giving a diagnostic with a fixit attached to the error itself. | |||
6760 | (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) | |||
6761 | ? nullptr | |||
6762 | : &NoArrowOperatorFound); | |||
6763 | if (Result.isInvalid()) { | |||
6764 | if (NoArrowOperatorFound) { | |||
6765 | if (FirstIteration) { | |||
6766 | Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) | |||
6767 | << BaseType << 1 << Base->getSourceRange() | |||
6768 | << FixItHint::CreateReplacement(OpLoc, "."); | |||
6769 | OpKind = tok::period; | |||
6770 | break; | |||
6771 | } | |||
6772 | Diag(OpLoc, diag::err_typecheck_member_reference_arrow) | |||
6773 | << BaseType << Base->getSourceRange(); | |||
6774 | CallExpr *CE = dyn_cast<CallExpr>(Base); | |||
6775 | if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { | |||
6776 | Diag(CD->getBeginLoc(), | |||
6777 | diag::note_member_reference_arrow_from_operator_arrow); | |||
6778 | } | |||
6779 | } | |||
6780 | return ExprError(); | |||
6781 | } | |||
6782 | Base = Result.get(); | |||
6783 | if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) | |||
6784 | OperatorArrows.push_back(OpCall->getDirectCallee()); | |||
6785 | BaseType = Base->getType(); | |||
6786 | CanQualType CBaseType = Context.getCanonicalType(BaseType); | |||
6787 | if (!CTypes.insert(CBaseType).second) { | |||
6788 | Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; | |||
6789 | noteOperatorArrows(*this, OperatorArrows); | |||
6790 | return ExprError(); | |||
6791 | } | |||
6792 | FirstIteration = false; | |||
6793 | } | |||
6794 | ||||
6795 | if (OpKind == tok::arrow) { | |||
6796 | if (BaseType->isPointerType()) | |||
6797 | BaseType = BaseType->getPointeeType(); | |||
6798 | else if (auto *AT = Context.getAsArrayType(BaseType)) | |||
6799 | BaseType = AT->getElementType(); | |||
6800 | } | |||
6801 | } | |||
6802 | ||||
6803 | // Objective-C properties allow "." access on Objective-C pointer types, | |||
6804 | // so adjust the base type to the object type itself. | |||
6805 | if (BaseType->isObjCObjectPointerType()) | |||
6806 | BaseType = BaseType->getPointeeType(); | |||
6807 | ||||
6808 | // C++ [basic.lookup.classref]p2: | |||
6809 | // [...] If the type of the object expression is of pointer to scalar | |||
6810 | // type, the unqualified-id is looked up in the context of the complete | |||
6811 | // postfix-expression. | |||
6812 | // | |||
6813 | // This also indicates that we could be parsing a pseudo-destructor-name. | |||
6814 | // Note that Objective-C class and object types can be pseudo-destructor | |||
6815 | // expressions or normal member (ivar or property) access expressions, and | |||
6816 | // it's legal for the type to be incomplete if this is a pseudo-destructor | |||
6817 | // call. We'll do more incomplete-type checks later in the lookup process, | |||
6818 | // so just skip this check for ObjC types. | |||
6819 | if (!BaseType->isRecordType()) { | |||
6820 | ObjectType = ParsedType::make(BaseType); | |||
6821 | MayBePseudoDestructor = true; | |||
6822 | return Base; | |||
6823 | } | |||
6824 | ||||
6825 | // The object type must be complete (or dependent), or | |||
6826 | // C++11 [expr.prim.general]p3: | |||
6827 | // Unlike the object expression in other contexts, *this is not required to | |||
6828 | // be of complete type for purposes of class member access (5.2.5) outside | |||
6829 | // the member function body. | |||
6830 | if (!BaseType->isDependentType() && | |||
6831 | !isThisOutsideMemberFunctionBody(BaseType) && | |||
6832 | RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access)) | |||
6833 | return ExprError(); | |||
6834 | ||||
6835 | // C++ [basic.lookup.classref]p2: | |||
6836 | // If the id-expression in a class member access (5.2.5) is an | |||
6837 | // unqualified-id, and the type of the object expression is of a class | |||
6838 | // type C (or of pointer to a class type C), the unqualified-id is looked | |||
6839 | // up in the scope of class C. [...] | |||
6840 | ObjectType = ParsedType::make(BaseType); | |||
6841 | return Base; | |||
6842 | } | |||
6843 | ||||
6844 | static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base, | |||
6845 | tok::TokenKind& OpKind, SourceLocation OpLoc) { | |||
6846 | if (Base->hasPlaceholderType()) { | |||
6847 | ExprResult result = S.CheckPlaceholderExpr(Base); | |||
6848 | if (result.isInvalid()) return true; | |||
6849 | Base = result.get(); | |||
6850 | } | |||
6851 | ObjectType = Base->getType(); | |||
6852 | ||||
6853 | // C++ [expr.pseudo]p2: | |||
6854 | // The left-hand side of the dot operator shall be of scalar type. The | |||
6855 | // left-hand side of the arrow operator shall be of pointer to scalar type. | |||
6856 | // This scalar type is the object type. | |||
6857 | // Note that this is rather different from the normal handling for the | |||
6858 | // arrow operator. | |||
6859 | if (OpKind == tok::arrow) { | |||
6860 | if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { | |||
6861 | ObjectType = Ptr->getPointeeType(); | |||
6862 | } else if (!Base->isTypeDependent()) { | |||
6863 | // The user wrote "p->" when they probably meant "p."; fix it. | |||
6864 | S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) | |||
6865 | << ObjectType << true | |||
6866 | << FixItHint::CreateReplacement(OpLoc, "."); | |||
6867 | if (S.isSFINAEContext()) | |||
6868 | return true; | |||
6869 | ||||
6870 | OpKind = tok::period; | |||
6871 | } | |||
6872 | } | |||
6873 | ||||
6874 | return false; | |||
6875 | } | |||
6876 | ||||
6877 | /// Check if it's ok to try and recover dot pseudo destructor calls on | |||
6878 | /// pointer objects. | |||
6879 | static bool | |||
6880 | canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, | |||
6881 | QualType DestructedType) { | |||
6882 | // If this is a record type, check if its destructor is callable. | |||
6883 | if (auto *RD = DestructedType->getAsCXXRecordDecl()) { | |||
6884 | if (RD->hasDefinition()) | |||
6885 | if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) | |||
6886 | return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); | |||
6887 | return false; | |||
6888 | } | |||
6889 | ||||
6890 | // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. | |||
6891 | return DestructedType->isDependentType() || DestructedType->isScalarType() || | |||
6892 | DestructedType->isVectorType(); | |||
6893 | } | |||
6894 | ||||
6895 | ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, | |||
6896 | SourceLocation OpLoc, | |||
6897 | tok::TokenKind OpKind, | |||
6898 | const CXXScopeSpec &SS, | |||
6899 | TypeSourceInfo *ScopeTypeInfo, | |||
6900 | SourceLocation CCLoc, | |||
6901 | SourceLocation TildeLoc, | |||
6902 | PseudoDestructorTypeStorage Destructed) { | |||
6903 | TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); | |||
6904 | ||||
6905 | QualType ObjectType; | |||
6906 | if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) | |||
6907 | return ExprError(); | |||
6908 | ||||
6909 | if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && | |||
6910 | !ObjectType->isVectorType()) { | |||
6911 | if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) | |||
6912 | Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); | |||
6913 | else { | |||
6914 | Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) | |||
6915 | << ObjectType << Base->getSourceRange(); | |||
6916 | return ExprError(); | |||
6917 | } | |||
6918 | } | |||
6919 | ||||
6920 | // C++ [expr.pseudo]p2: | |||
6921 | // [...] The cv-unqualified versions of the object type and of the type | |||
6922 | // designated by the pseudo-destructor-name shall be the same type. | |||
6923 | if (DestructedTypeInfo) { | |||
6924 | QualType DestructedType = DestructedTypeInfo->getType(); | |||
6925 | SourceLocation DestructedTypeStart | |||
6926 | = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); | |||
6927 | if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { | |||
6928 | if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { | |||
6929 | // Detect dot pseudo destructor calls on pointer objects, e.g.: | |||
6930 | // Foo *foo; | |||
6931 | // foo.~Foo(); | |||
6932 | if (OpKind == tok::period && ObjectType->isPointerType() && | |||
6933 | Context.hasSameUnqualifiedType(DestructedType, | |||
6934 | ObjectType->getPointeeType())) { | |||
6935 | auto Diagnostic = | |||
6936 | Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) | |||
6937 | << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); | |||
6938 | ||||
6939 | // Issue a fixit only when the destructor is valid. | |||
6940 | if (canRecoverDotPseudoDestructorCallsOnPointerObjects( | |||
6941 | *this, DestructedType)) | |||
6942 | Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); | |||
6943 | ||||
6944 | // Recover by setting the object type to the destructed type and the | |||
6945 | // operator to '->'. | |||
6946 | ObjectType = DestructedType; | |||
6947 | OpKind = tok::arrow; | |||
6948 | } else { | |||
6949 | Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) | |||
6950 | << ObjectType << DestructedType << Base->getSourceRange() | |||
6951 | << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); | |||
6952 | ||||
6953 | // Recover by setting the destructed type to the object type. | |||
6954 | DestructedType = ObjectType; | |||
6955 | DestructedTypeInfo = | |||
6956 | Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); | |||
6957 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); | |||
6958 | } | |||
6959 | } else if (DestructedType.getObjCLifetime() != | |||
6960 | ObjectType.getObjCLifetime()) { | |||
6961 | ||||
6962 | if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { | |||
6963 | // Okay: just pretend that the user provided the correctly-qualified | |||
6964 | // type. | |||
6965 | } else { | |||
6966 | Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) | |||
6967 | << ObjectType << DestructedType << Base->getSourceRange() | |||
6968 | << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); | |||
6969 | } | |||
6970 | ||||
6971 | // Recover by setting the destructed type to the object type. | |||
6972 | DestructedType = ObjectType; | |||
6973 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, | |||
6974 | DestructedTypeStart); | |||
6975 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); | |||
6976 | } | |||
6977 | } | |||
6978 | } | |||
6979 | ||||
6980 | // C++ [expr.pseudo]p2: | |||
6981 | // [...] Furthermore, the two type-names in a pseudo-destructor-name of the | |||
6982 | // form | |||
6983 | // | |||
6984 | // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name | |||
6985 | // | |||
6986 | // shall designate the same scalar type. | |||
6987 | if (ScopeTypeInfo) { | |||
6988 | QualType ScopeType = ScopeTypeInfo->getType(); | |||
6989 | if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && | |||
6990 | !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { | |||
6991 | ||||
6992 | Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), | |||
6993 | diag::err_pseudo_dtor_type_mismatch) | |||
6994 | << ObjectType << ScopeType << Base->getSourceRange() | |||
6995 | << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); | |||
6996 | ||||
6997 | ScopeType = QualType(); | |||
6998 | ScopeTypeInfo = nullptr; | |||
6999 | } | |||
7000 | } | |||
7001 | ||||
7002 | Expr *Result | |||
7003 | = new (Context) CXXPseudoDestructorExpr(Context, Base, | |||
7004 | OpKind == tok::arrow, OpLoc, | |||
7005 | SS.getWithLocInContext(Context), | |||
7006 | ScopeTypeInfo, | |||
7007 | CCLoc, | |||
7008 | TildeLoc, | |||
7009 | Destructed); | |||
7010 | ||||
7011 | return Result; | |||
7012 | } | |||
7013 | ||||
7014 | ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, | |||
7015 | SourceLocation OpLoc, | |||
7016 | tok::TokenKind OpKind, | |||
7017 | CXXScopeSpec &SS, | |||
7018 | UnqualifiedId &FirstTypeName, | |||
7019 | SourceLocation CCLoc, | |||
7020 | SourceLocation TildeLoc, | |||
7021 | UnqualifiedId &SecondTypeName) { | |||
7022 | assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier ) && "Invalid first type name in pseudo-destructor") ? static_cast<void> (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7024, __PRETTY_FUNCTION__)) | |||
7023 | FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier ) && "Invalid first type name in pseudo-destructor") ? static_cast<void> (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7024, __PRETTY_FUNCTION__)) | |||
7024 | "Invalid first type name in pseudo-destructor")(((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier ) && "Invalid first type name in pseudo-destructor") ? static_cast<void> (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7024, __PRETTY_FUNCTION__)); | |||
7025 | assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier ) && "Invalid second type name in pseudo-destructor") ? static_cast<void> (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7027, __PRETTY_FUNCTION__)) | |||
7026 | SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier ) && "Invalid second type name in pseudo-destructor") ? static_cast<void> (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7027, __PRETTY_FUNCTION__)) | |||
7027 | "Invalid second type name in pseudo-destructor")(((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier ) && "Invalid second type name in pseudo-destructor") ? static_cast<void> (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7027, __PRETTY_FUNCTION__)); | |||
7028 | ||||
7029 | QualType ObjectType; | |||
7030 | if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) | |||
7031 | return ExprError(); | |||
7032 | ||||
7033 | // Compute the object type that we should use for name lookup purposes. Only | |||
7034 | // record types and dependent types matter. | |||
7035 | ParsedType ObjectTypePtrForLookup; | |||
7036 | if (!SS.isSet()) { | |||
7037 | if (ObjectType->isRecordType()) | |||
7038 | ObjectTypePtrForLookup = ParsedType::make(ObjectType); | |||
7039 | else if (ObjectType->isDependentType()) | |||
7040 | ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); | |||
7041 | } | |||
7042 | ||||
7043 | // Convert the name of the type being destructed (following the ~) into a | |||
7044 | // type (with source-location information). | |||
7045 | QualType DestructedType; | |||
7046 | TypeSourceInfo *DestructedTypeInfo = nullptr; | |||
7047 | PseudoDestructorTypeStorage Destructed; | |||
7048 | if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { | |||
7049 | ParsedType T = getTypeName(*SecondTypeName.Identifier, | |||
7050 | SecondTypeName.StartLocation, | |||
7051 | S, &SS, true, false, ObjectTypePtrForLookup, | |||
7052 | /*IsCtorOrDtorName*/true); | |||
7053 | if (!T && | |||
7054 | ((SS.isSet() && !computeDeclContext(SS, false)) || | |||
7055 | (!SS.isSet() && ObjectType->isDependentType()))) { | |||
7056 | // The name of the type being destroyed is a dependent name, and we | |||
7057 | // couldn't find anything useful in scope. Just store the identifier and | |||
7058 | // it's location, and we'll perform (qualified) name lookup again at | |||
7059 | // template instantiation time. | |||
7060 | Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, | |||
7061 | SecondTypeName.StartLocation); | |||
7062 | } else if (!T) { | |||
7063 | Diag(SecondTypeName.StartLocation, | |||
7064 | diag::err_pseudo_dtor_destructor_non_type) | |||
7065 | << SecondTypeName.Identifier << ObjectType; | |||
7066 | if (isSFINAEContext()) | |||
7067 | return ExprError(); | |||
7068 | ||||
7069 | // Recover by assuming we had the right type all along. | |||
7070 | DestructedType = ObjectType; | |||
7071 | } else | |||
7072 | DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); | |||
7073 | } else { | |||
7074 | // Resolve the template-id to a type. | |||
7075 | TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; | |||
7076 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
7077 | TemplateId->NumArgs); | |||
7078 | TypeResult T = ActOnTemplateIdType(S, | |||
7079 | TemplateId->SS, | |||
7080 | TemplateId->TemplateKWLoc, | |||
7081 | TemplateId->Template, | |||
7082 | TemplateId->Name, | |||
7083 | TemplateId->TemplateNameLoc, | |||
7084 | TemplateId->LAngleLoc, | |||
7085 | TemplateArgsPtr, | |||
7086 | TemplateId->RAngleLoc, | |||
7087 | /*IsCtorOrDtorName*/true); | |||
7088 | if (T.isInvalid() || !T.get()) { | |||
7089 | // Recover by assuming we had the right type all along. | |||
7090 | DestructedType = ObjectType; | |||
7091 | } else | |||
7092 | DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); | |||
7093 | } | |||
7094 | ||||
7095 | // If we've performed some kind of recovery, (re-)build the type source | |||
7096 | // information. | |||
7097 | if (!DestructedType.isNull()) { | |||
7098 | if (!DestructedTypeInfo) | |||
7099 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, | |||
7100 | SecondTypeName.StartLocation); | |||
7101 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); | |||
7102 | } | |||
7103 | ||||
7104 | // Convert the name of the scope type (the type prior to '::') into a type. | |||
7105 | TypeSourceInfo *ScopeTypeInfo = nullptr; | |||
7106 | QualType ScopeType; | |||
7107 | if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || | |||
7108 | FirstTypeName.Identifier) { | |||
7109 | if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { | |||
7110 | ParsedType T = getTypeName(*FirstTypeName.Identifier, | |||
7111 | FirstTypeName.StartLocation, | |||
7112 | S, &SS, true, false, ObjectTypePtrForLookup, | |||
7113 | /*IsCtorOrDtorName*/true); | |||
7114 | if (!T) { | |||
7115 | Diag(FirstTypeName.StartLocation, | |||
7116 | diag::err_pseudo_dtor_destructor_non_type) | |||
7117 | << FirstTypeName.Identifier << ObjectType; | |||
7118 | ||||
7119 | if (isSFINAEContext()) | |||
7120 | return ExprError(); | |||
7121 | ||||
7122 | // Just drop this type. It's unnecessary anyway. | |||
7123 | ScopeType = QualType(); | |||
7124 | } else | |||
7125 | ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); | |||
7126 | } else { | |||
7127 | // Resolve the template-id to a type. | |||
7128 | TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; | |||
7129 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
7130 | TemplateId->NumArgs); | |||
7131 | TypeResult T = ActOnTemplateIdType(S, | |||
7132 | TemplateId->SS, | |||
7133 | TemplateId->TemplateKWLoc, | |||
7134 | TemplateId->Template, | |||
7135 | TemplateId->Name, | |||
7136 | TemplateId->TemplateNameLoc, | |||
7137 | TemplateId->LAngleLoc, | |||
7138 | TemplateArgsPtr, | |||
7139 | TemplateId->RAngleLoc, | |||
7140 | /*IsCtorOrDtorName*/true); | |||
7141 | if (T.isInvalid() || !T.get()) { | |||
7142 | // Recover by dropping this type. | |||
7143 | ScopeType = QualType(); | |||
7144 | } else | |||
7145 | ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); | |||
7146 | } | |||
7147 | } | |||
7148 | ||||
7149 | if (!ScopeType.isNull() && !ScopeTypeInfo) | |||
7150 | ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, | |||
7151 | FirstTypeName.StartLocation); | |||
7152 | ||||
7153 | ||||
7154 | return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, | |||
7155 | ScopeTypeInfo, CCLoc, TildeLoc, | |||
7156 | Destructed); | |||
7157 | } | |||
7158 | ||||
7159 | ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, | |||
7160 | SourceLocation OpLoc, | |||
7161 | tok::TokenKind OpKind, | |||
7162 | SourceLocation TildeLoc, | |||
7163 | const DeclSpec& DS) { | |||
7164 | QualType ObjectType; | |||
7165 | if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) | |||
7166 | return ExprError(); | |||
7167 | ||||
7168 | QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(), | |||
7169 | false); | |||
7170 | ||||
7171 | TypeLocBuilder TLB; | |||
7172 | DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); | |||
7173 | DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc()); | |||
7174 | TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); | |||
7175 | PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); | |||
7176 | ||||
7177 | return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), | |||
7178 | nullptr, SourceLocation(), TildeLoc, | |||
7179 | Destructed); | |||
7180 | } | |||
7181 | ||||
7182 | ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, | |||
7183 | CXXConversionDecl *Method, | |||
7184 | bool HadMultipleCandidates) { | |||
7185 | // Convert the expression to match the conversion function's implicit object | |||
7186 | // parameter. | |||
7187 | ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr, | |||
7188 | FoundDecl, Method); | |||
7189 | if (Exp.isInvalid()) | |||
7190 | return true; | |||
7191 | ||||
7192 | if (Method->getParent()->isLambda() && | |||
7193 | Method->getConversionType()->isBlockPointerType()) { | |||
7194 | // This is a lambda conversion to block pointer; check if the argument | |||
7195 | // was a LambdaExpr. | |||
7196 | Expr *SubE = E; | |||
7197 | CastExpr *CE = dyn_cast<CastExpr>(SubE); | |||
7198 | if (CE && CE->getCastKind() == CK_NoOp) | |||
7199 | SubE = CE->getSubExpr(); | |||
7200 | SubE = SubE->IgnoreParens(); | |||
7201 | if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) | |||
7202 | SubE = BE->getSubExpr(); | |||
7203 | if (isa<LambdaExpr>(SubE)) { | |||
7204 | // For the conversion to block pointer on a lambda expression, we | |||
7205 | // construct a special BlockLiteral instead; this doesn't really make | |||
7206 | // a difference in ARC, but outside of ARC the resulting block literal | |||
7207 | // follows the normal lifetime rules for block literals instead of being | |||
7208 | // autoreleased. | |||
7209 | DiagnosticErrorTrap Trap(Diags); | |||
7210 | PushExpressionEvaluationContext( | |||
7211 | ExpressionEvaluationContext::PotentiallyEvaluated); | |||
7212 | ExprResult BlockExp = BuildBlockForLambdaConversion( | |||
7213 | Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); | |||
7214 | PopExpressionEvaluationContext(); | |||
7215 | ||||
7216 | if (BlockExp.isInvalid()) | |||
7217 | Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); | |||
7218 | return BlockExp; | |||
7219 | } | |||
7220 | } | |||
7221 | ||||
7222 | MemberExpr *ME = | |||
7223 | BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), | |||
7224 | NestedNameSpecifierLoc(), SourceLocation(), Method, | |||
7225 | DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), | |||
7226 | HadMultipleCandidates, DeclarationNameInfo(), | |||
7227 | Context.BoundMemberTy, VK_RValue, OK_Ordinary); | |||
7228 | ||||
7229 | QualType ResultType = Method->getReturnType(); | |||
7230 | ExprValueKind VK = Expr::getValueKindForType(ResultType); | |||
7231 | ResultType = ResultType.getNonLValueExprType(Context); | |||
7232 | ||||
7233 | CXXMemberCallExpr *CE = CXXMemberCallExpr::Create( | |||
7234 | Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc()); | |||
7235 | ||||
7236 | if (CheckFunctionCall(Method, CE, | |||
7237 | Method->getType()->castAs<FunctionProtoType>())) | |||
7238 | return ExprError(); | |||
7239 | ||||
7240 | return CE; | |||
7241 | } | |||
7242 | ||||
7243 | ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, | |||
7244 | SourceLocation RParen) { | |||
7245 | // If the operand is an unresolved lookup expression, the expression is ill- | |||
7246 | // formed per [over.over]p1, because overloaded function names cannot be used | |||
7247 | // without arguments except in explicit contexts. | |||
7248 | ExprResult R = CheckPlaceholderExpr(Operand); | |||
7249 | if (R.isInvalid()) | |||
7250 | return R; | |||
7251 | ||||
7252 | R = CheckUnevaluatedOperand(R.get()); | |||
7253 | if (R.isInvalid()) | |||
7254 | return ExprError(); | |||
7255 | ||||
7256 | Operand = R.get(); | |||
7257 | ||||
7258 | if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) { | |||
7259 | // The expression operand for noexcept is in an unevaluated expression | |||
7260 | // context, so side effects could result in unintended consequences. | |||
7261 | Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); | |||
7262 | } | |||
7263 | ||||
7264 | CanThrowResult CanThrow = canThrow(Operand); | |||
7265 | return new (Context) | |||
7266 | CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); | |||
7267 | } | |||
7268 | ||||
7269 | ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, | |||
7270 | Expr *Operand, SourceLocation RParen) { | |||
7271 | return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); | |||
7272 | } | |||
7273 | ||||
7274 | static bool IsSpecialDiscardedValue(Expr *E) { | |||
7275 | // In C++11, discarded-value expressions of a certain form are special, | |||
7276 | // according to [expr]p10: | |||
7277 | // The lvalue-to-rvalue conversion (4.1) is applied only if the | |||
7278 | // expression is an lvalue of volatile-qualified type and it has | |||
7279 | // one of the following forms: | |||
7280 | E = E->IgnoreParens(); | |||
7281 | ||||
7282 | // - id-expression (5.1.1), | |||
7283 | if (isa<DeclRefExpr>(E)) | |||
7284 | return true; | |||
7285 | ||||
7286 | // - subscripting (5.2.1), | |||
7287 | if (isa<ArraySubscriptExpr>(E)) | |||
7288 | return true; | |||
7289 | ||||
7290 | // - class member access (5.2.5), | |||
7291 | if (isa<MemberExpr>(E)) | |||
7292 | return true; | |||
7293 | ||||
7294 | // - indirection (5.3.1), | |||
7295 | if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) | |||
7296 | if (UO->getOpcode() == UO_Deref) | |||
7297 | return true; | |||
7298 | ||||
7299 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
7300 | // - pointer-to-member operation (5.5), | |||
7301 | if (BO->isPtrMemOp()) | |||
7302 | return true; | |||
7303 | ||||
7304 | // - comma expression (5.18) where the right operand is one of the above. | |||
7305 | if (BO->getOpcode() == BO_Comma) | |||
7306 | return IsSpecialDiscardedValue(BO->getRHS()); | |||
7307 | } | |||
7308 | ||||
7309 | // - conditional expression (5.16) where both the second and the third | |||
7310 | // operands are one of the above, or | |||
7311 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) | |||
7312 | return IsSpecialDiscardedValue(CO->getTrueExpr()) && | |||
7313 | IsSpecialDiscardedValue(CO->getFalseExpr()); | |||
7314 | // The related edge case of "*x ?: *x". | |||
7315 | if (BinaryConditionalOperator *BCO = | |||
7316 | dyn_cast<BinaryConditionalOperator>(E)) { | |||
7317 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr())) | |||
7318 | return IsSpecialDiscardedValue(OVE->getSourceExpr()) && | |||
7319 | IsSpecialDiscardedValue(BCO->getFalseExpr()); | |||
7320 | } | |||
7321 | ||||
7322 | // Objective-C++ extensions to the rule. | |||
7323 | if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E)) | |||
7324 | return true; | |||
7325 | ||||
7326 | return false; | |||
7327 | } | |||
7328 | ||||
7329 | /// Perform the conversions required for an expression used in a | |||
7330 | /// context that ignores the result. | |||
7331 | ExprResult Sema::IgnoredValueConversions(Expr *E) { | |||
7332 | if (E->hasPlaceholderType()) { | |||
7333 | ExprResult result = CheckPlaceholderExpr(E); | |||
7334 | if (result.isInvalid()) return E; | |||
7335 | E = result.get(); | |||
7336 | } | |||
7337 | ||||
7338 | // C99 6.3.2.1: | |||
7339 | // [Except in specific positions,] an lvalue that does not have | |||
7340 | // array type is converted to the value stored in the | |||
7341 | // designated object (and is no longer an lvalue). | |||
7342 | if (E->isRValue()) { | |||
7343 | // In C, function designators (i.e. expressions of function type) | |||
7344 | // are r-values, but we still want to do function-to-pointer decay | |||
7345 | // on them. This is both technically correct and convenient for | |||
7346 | // some clients. | |||
7347 | if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) | |||
7348 | return DefaultFunctionArrayConversion(E); | |||
7349 | ||||
7350 | return E; | |||
7351 | } | |||
7352 | ||||
7353 | if (getLangOpts().CPlusPlus) { | |||
7354 | // The C++11 standard defines the notion of a discarded-value expression; | |||
7355 | // normally, we don't need to do anything to handle it, but if it is a | |||
7356 | // volatile lvalue with a special form, we perform an lvalue-to-rvalue | |||
7357 | // conversion. | |||
7358 | if (getLangOpts().CPlusPlus11 && E->isGLValue() && | |||
7359 | E->getType().isVolatileQualified()) { | |||
7360 | if (IsSpecialDiscardedValue(E)) { | |||
7361 | ExprResult Res = DefaultLvalueConversion(E); | |||
7362 | if (Res.isInvalid()) | |||
7363 | return E; | |||
7364 | E = Res.get(); | |||
7365 | } else { | |||
7366 | // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if | |||
7367 | // it occurs as a discarded-value expression. | |||
7368 | CheckUnusedVolatileAssignment(E); | |||
7369 | } | |||
7370 | } | |||
7371 | ||||
7372 | // C++1z: | |||
7373 | // If the expression is a prvalue after this optional conversion, the | |||
7374 | // temporary materialization conversion is applied. | |||
7375 | // | |||
7376 | // We skip this step: IR generation is able to synthesize the storage for | |||
7377 | // itself in the aggregate case, and adding the extra node to the AST is | |||
7378 | // just clutter. | |||
7379 | // FIXME: We don't emit lifetime markers for the temporaries due to this. | |||
7380 | // FIXME: Do any other AST consumers care about this? | |||
7381 | return E; | |||
7382 | } | |||
7383 | ||||
7384 | // GCC seems to also exclude expressions of incomplete enum type. | |||
7385 | if (const EnumType *T = E->getType()->getAs<EnumType>()) { | |||
7386 | if (!T->getDecl()->isComplete()) { | |||
7387 | // FIXME: stupid workaround for a codegen bug! | |||
7388 | E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); | |||
7389 | return E; | |||
7390 | } | |||
7391 | } | |||
7392 | ||||
7393 | ExprResult Res = DefaultFunctionArrayLvalueConversion(E); | |||
7394 | if (Res.isInvalid()) | |||
7395 | return E; | |||
7396 | E = Res.get(); | |||
7397 | ||||
7398 | if (!E->getType()->isVoidType()) | |||
7399 | RequireCompleteType(E->getExprLoc(), E->getType(), | |||
7400 | diag::err_incomplete_type); | |||
7401 | return E; | |||
7402 | } | |||
7403 | ||||
7404 | ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { | |||
7405 | // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if | |||
7406 | // it occurs as an unevaluated operand. | |||
7407 | CheckUnusedVolatileAssignment(E); | |||
7408 | ||||
7409 | return E; | |||
7410 | } | |||
7411 | ||||
7412 | // If we can unambiguously determine whether Var can never be used | |||
7413 | // in a constant expression, return true. | |||
7414 | // - if the variable and its initializer are non-dependent, then | |||
7415 | // we can unambiguously check if the variable is a constant expression. | |||
7416 | // - if the initializer is not value dependent - we can determine whether | |||
7417 | // it can be used to initialize a constant expression. If Init can not | |||
7418 | // be used to initialize a constant expression we conclude that Var can | |||
7419 | // never be a constant expression. | |||
7420 | // - FXIME: if the initializer is dependent, we can still do some analysis and | |||
7421 | // identify certain cases unambiguously as non-const by using a Visitor: | |||
7422 | // - such as those that involve odr-use of a ParmVarDecl, involve a new | |||
7423 | // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... | |||
7424 | static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, | |||
7425 | ASTContext &Context) { | |||
7426 | if (isa<ParmVarDecl>(Var)) return true; | |||
7427 | const VarDecl *DefVD = nullptr; | |||
7428 | ||||
7429 | // If there is no initializer - this can not be a constant expression. | |||
7430 | if (!Var->getAnyInitializer(DefVD)) return true; | |||
7431 | assert(DefVD)((DefVD) ? static_cast<void> (0) : __assert_fail ("DefVD" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7431, __PRETTY_FUNCTION__)); | |||
7432 | if (DefVD->isWeak()) return false; | |||
7433 | EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); | |||
7434 | ||||
7435 | Expr *Init = cast<Expr>(Eval->Value); | |||
7436 | ||||
7437 | if (Var->getType()->isDependentType() || Init->isValueDependent()) { | |||
7438 | // FIXME: Teach the constant evaluator to deal with the non-dependent parts | |||
7439 | // of value-dependent expressions, and use it here to determine whether the | |||
7440 | // initializer is a potential constant expression. | |||
7441 | return false; | |||
7442 | } | |||
7443 | ||||
7444 | return !Var->isUsableInConstantExpressions(Context); | |||
7445 | } | |||
7446 | ||||
7447 | /// Check if the current lambda has any potential captures | |||
7448 | /// that must be captured by any of its enclosing lambdas that are ready to | |||
7449 | /// capture. If there is a lambda that can capture a nested | |||
7450 | /// potential-capture, go ahead and do so. Also, check to see if any | |||
7451 | /// variables are uncaptureable or do not involve an odr-use so do not | |||
7452 | /// need to be captured. | |||
7453 | ||||
7454 | static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( | |||
7455 | Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { | |||
7456 | ||||
7457 | assert(!S.isUnevaluatedContext())((!S.isUnevaluatedContext()) ? static_cast<void> (0) : __assert_fail ("!S.isUnevaluatedContext()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7457, __PRETTY_FUNCTION__)); | |||
7458 | assert(S.CurContext->isDependentContext())((S.CurContext->isDependentContext()) ? static_cast<void > (0) : __assert_fail ("S.CurContext->isDependentContext()" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7458, __PRETTY_FUNCTION__)); | |||
7459 | #ifndef NDEBUG | |||
7460 | DeclContext *DC = S.CurContext; | |||
7461 | while (DC && isa<CapturedDecl>(DC)) | |||
7462 | DC = DC->getParent(); | |||
7463 | assert(((CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext" ) ? static_cast<void> (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7465, __PRETTY_FUNCTION__)) | |||
7464 | CurrentLSI->CallOperator == DC &&((CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext" ) ? static_cast<void> (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7465, __PRETTY_FUNCTION__)) | |||
7465 | "The current call operator must be synchronized with Sema's CurContext")((CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext" ) ? static_cast<void> (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7465, __PRETTY_FUNCTION__)); | |||
7466 | #endif // NDEBUG | |||
7467 | ||||
7468 | const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); | |||
7469 | ||||
7470 | // All the potentially captureable variables in the current nested | |||
7471 | // lambda (within a generic outer lambda), must be captured by an | |||
7472 | // outer lambda that is enclosed within a non-dependent context. | |||
7473 | CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) { | |||
7474 | // If the variable is clearly identified as non-odr-used and the full | |||
7475 | // expression is not instantiation dependent, only then do we not | |||
7476 | // need to check enclosing lambda's for speculative captures. | |||
7477 | // For e.g.: | |||
7478 | // Even though 'x' is not odr-used, it should be captured. | |||
7479 | // int test() { | |||
7480 | // const int x = 10; | |||
7481 | // auto L = [=](auto a) { | |||
7482 | // (void) +x + a; | |||
7483 | // }; | |||
7484 | // } | |||
7485 | if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && | |||
7486 | !IsFullExprInstantiationDependent) | |||
7487 | return; | |||
7488 | ||||
7489 | // If we have a capture-capable lambda for the variable, go ahead and | |||
7490 | // capture the variable in that lambda (and all its enclosing lambdas). | |||
7491 | if (const Optional<unsigned> Index = | |||
7492 | getStackIndexOfNearestEnclosingCaptureCapableLambda( | |||
7493 | S.FunctionScopes, Var, S)) | |||
7494 | S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), | |||
7495 | Index.getValue()); | |||
7496 | const bool IsVarNeverAConstantExpression = | |||
7497 | VariableCanNeverBeAConstantExpression(Var, S.Context); | |||
7498 | if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { | |||
7499 | // This full expression is not instantiation dependent or the variable | |||
7500 | // can not be used in a constant expression - which means | |||
7501 | // this variable must be odr-used here, so diagnose a | |||
7502 | // capture violation early, if the variable is un-captureable. | |||
7503 | // This is purely for diagnosing errors early. Otherwise, this | |||
7504 | // error would get diagnosed when the lambda becomes capture ready. | |||
7505 | QualType CaptureType, DeclRefType; | |||
7506 | SourceLocation ExprLoc = VarExpr->getExprLoc(); | |||
7507 | if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, | |||
7508 | /*EllipsisLoc*/ SourceLocation(), | |||
7509 | /*BuildAndDiagnose*/false, CaptureType, | |||
7510 | DeclRefType, nullptr)) { | |||
7511 | // We will never be able to capture this variable, and we need | |||
7512 | // to be able to in any and all instantiations, so diagnose it. | |||
7513 | S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, | |||
7514 | /*EllipsisLoc*/ SourceLocation(), | |||
7515 | /*BuildAndDiagnose*/true, CaptureType, | |||
7516 | DeclRefType, nullptr); | |||
7517 | } | |||
7518 | } | |||
7519 | }); | |||
7520 | ||||
7521 | // Check if 'this' needs to be captured. | |||
7522 | if (CurrentLSI->hasPotentialThisCapture()) { | |||
7523 | // If we have a capture-capable lambda for 'this', go ahead and capture | |||
7524 | // 'this' in that lambda (and all its enclosing lambdas). | |||
7525 | if (const Optional<unsigned> Index = | |||
7526 | getStackIndexOfNearestEnclosingCaptureCapableLambda( | |||
7527 | S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { | |||
7528 | const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue(); | |||
7529 | S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, | |||
7530 | /*Explicit*/ false, /*BuildAndDiagnose*/ true, | |||
7531 | &FunctionScopeIndexOfCapturableLambda); | |||
7532 | } | |||
7533 | } | |||
7534 | ||||
7535 | // Reset all the potential captures at the end of each full-expression. | |||
7536 | CurrentLSI->clearPotentialCaptures(); | |||
7537 | } | |||
7538 | ||||
7539 | static ExprResult attemptRecovery(Sema &SemaRef, | |||
7540 | const TypoCorrectionConsumer &Consumer, | |||
7541 | const TypoCorrection &TC) { | |||
7542 | LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), | |||
7543 | Consumer.getLookupResult().getLookupKind()); | |||
7544 | const CXXScopeSpec *SS = Consumer.getSS(); | |||
7545 | CXXScopeSpec NewSS; | |||
7546 | ||||
7547 | // Use an approprate CXXScopeSpec for building the expr. | |||
7548 | if (auto *NNS = TC.getCorrectionSpecifier()) | |||
7549 | NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange()); | |||
7550 | else if (SS && !TC.WillReplaceSpecifier()) | |||
7551 | NewSS = *SS; | |||
7552 | ||||
7553 | if (auto *ND = TC.getFoundDecl()) { | |||
7554 | R.setLookupName(ND->getDeclName()); | |||
7555 | R.addDecl(ND); | |||
7556 | if (ND->isCXXClassMember()) { | |||
7557 | // Figure out the correct naming class to add to the LookupResult. | |||
7558 | CXXRecordDecl *Record = nullptr; | |||
7559 | if (auto *NNS = TC.getCorrectionSpecifier()) | |||
7560 | Record = NNS->getAsType()->getAsCXXRecordDecl(); | |||
7561 | if (!Record) | |||
7562 | Record = | |||
7563 | dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); | |||
7564 | if (Record) | |||
7565 | R.setNamingClass(Record); | |||
7566 | ||||
7567 | // Detect and handle the case where the decl might be an implicit | |||
7568 | // member. | |||
7569 | bool MightBeImplicitMember; | |||
7570 | if (!Consumer.isAddressOfOperand()) | |||
7571 | MightBeImplicitMember = true; | |||
7572 | else if (!NewSS.isEmpty()) | |||
7573 | MightBeImplicitMember = false; | |||
7574 | else if (R.isOverloadedResult()) | |||
7575 | MightBeImplicitMember = false; | |||
7576 | else if (R.isUnresolvableResult()) | |||
7577 | MightBeImplicitMember = true; | |||
7578 | else | |||
7579 | MightBeImplicitMember = isa<FieldDecl>(ND) || | |||
7580 | isa<IndirectFieldDecl>(ND) || | |||
7581 | isa<MSPropertyDecl>(ND); | |||
7582 | ||||
7583 | if (MightBeImplicitMember) | |||
7584 | return SemaRef.BuildPossibleImplicitMemberExpr( | |||
7585 | NewSS, /*TemplateKWLoc*/ SourceLocation(), R, | |||
7586 | /*TemplateArgs*/ nullptr, /*S*/ nullptr); | |||
7587 | } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { | |||
7588 | return SemaRef.LookupInObjCMethod(R, Consumer.getScope(), | |||
7589 | Ivar->getIdentifier()); | |||
7590 | } | |||
7591 | } | |||
7592 | ||||
7593 | return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false, | |||
7594 | /*AcceptInvalidDecl*/ true); | |||
7595 | } | |||
7596 | ||||
7597 | namespace { | |||
7598 | class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { | |||
7599 | llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; | |||
7600 | ||||
7601 | public: | |||
7602 | explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) | |||
7603 | : TypoExprs(TypoExprs) {} | |||
7604 | bool VisitTypoExpr(TypoExpr *TE) { | |||
7605 | TypoExprs.insert(TE); | |||
7606 | return true; | |||
7607 | } | |||
7608 | }; | |||
7609 | ||||
7610 | class TransformTypos : public TreeTransform<TransformTypos> { | |||
7611 | typedef TreeTransform<TransformTypos> BaseTransform; | |||
7612 | ||||
7613 | VarDecl *InitDecl; // A decl to avoid as a correction because it is in the | |||
7614 | // process of being initialized. | |||
7615 | llvm::function_ref<ExprResult(Expr *)> ExprFilter; | |||
7616 | llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; | |||
7617 | llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; | |||
7618 | llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; | |||
7619 | ||||
7620 | /// Emit diagnostics for all of the TypoExprs encountered. | |||
7621 | /// | |||
7622 | /// If the TypoExprs were successfully corrected, then the diagnostics should | |||
7623 | /// suggest the corrections. Otherwise the diagnostics will not suggest | |||
7624 | /// anything (having been passed an empty TypoCorrection). | |||
7625 | /// | |||
7626 | /// If we've failed to correct due to ambiguous corrections, we need to | |||
7627 | /// be sure to pass empty corrections and replacements. Otherwise it's | |||
7628 | /// possible that the Consumer has a TypoCorrection that failed to ambiguity | |||
7629 | /// and we don't want to report those diagnostics. | |||
7630 | void EmitAllDiagnostics(bool IsAmbiguous) { | |||
7631 | for (TypoExpr *TE : TypoExprs) { | |||
7632 | auto &State = SemaRef.getTypoExprState(TE); | |||
7633 | if (State.DiagHandler) { | |||
7634 | TypoCorrection TC = IsAmbiguous | |||
7635 | ? TypoCorrection() : State.Consumer->getCurrentCorrection(); | |||
7636 | ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE]; | |||
7637 | ||||
7638 | // Extract the NamedDecl from the transformed TypoExpr and add it to the | |||
7639 | // TypoCorrection, replacing the existing decls. This ensures the right | |||
7640 | // NamedDecl is used in diagnostics e.g. in the case where overload | |||
7641 | // resolution was used to select one from several possible decls that | |||
7642 | // had been stored in the TypoCorrection. | |||
7643 | if (auto *ND = getDeclFromExpr( | |||
7644 | Replacement.isInvalid() ? nullptr : Replacement.get())) | |||
7645 | TC.setCorrectionDecl(ND); | |||
7646 | ||||
7647 | State.DiagHandler(TC); | |||
7648 | } | |||
7649 | SemaRef.clearDelayedTypo(TE); | |||
7650 | } | |||
7651 | } | |||
7652 | ||||
7653 | /// If corrections for the first TypoExpr have been exhausted for a | |||
7654 | /// given combination of the other TypoExprs, retry those corrections against | |||
7655 | /// the next combination of substitutions for the other TypoExprs by advancing | |||
7656 | /// to the next potential correction of the second TypoExpr. For the second | |||
7657 | /// and subsequent TypoExprs, if its stream of corrections has been exhausted, | |||
7658 | /// the stream is reset and the next TypoExpr's stream is advanced by one (a | |||
7659 | /// TypoExpr's correction stream is advanced by removing the TypoExpr from the | |||
7660 | /// TransformCache). Returns true if there is still any untried combinations | |||
7661 | /// of corrections. | |||
7662 | bool CheckAndAdvanceTypoExprCorrectionStreams() { | |||
7663 | for (auto TE : TypoExprs) { | |||
7664 | auto &State = SemaRef.getTypoExprState(TE); | |||
7665 | TransformCache.erase(TE); | |||
7666 | if (!State.Consumer->finished()) | |||
7667 | return true; | |||
7668 | State.Consumer->resetCorrectionStream(); | |||
7669 | } | |||
7670 | return false; | |||
7671 | } | |||
7672 | ||||
7673 | NamedDecl *getDeclFromExpr(Expr *E) { | |||
7674 | if (auto *OE = dyn_cast_or_null<OverloadExpr>(E)) | |||
7675 | E = OverloadResolution[OE]; | |||
7676 | ||||
7677 | if (!E) | |||
7678 | return nullptr; | |||
7679 | if (auto *DRE = dyn_cast<DeclRefExpr>(E)) | |||
7680 | return DRE->getFoundDecl(); | |||
7681 | if (auto *ME = dyn_cast<MemberExpr>(E)) | |||
7682 | return ME->getFoundDecl(); | |||
7683 | // FIXME: Add any other expr types that could be be seen by the delayed typo | |||
7684 | // correction TreeTransform for which the corresponding TypoCorrection could | |||
7685 | // contain multiple decls. | |||
7686 | return nullptr; | |||
7687 | } | |||
7688 | ||||
7689 | ExprResult TryTransform(Expr *E) { | |||
7690 | Sema::SFINAETrap Trap(SemaRef); | |||
7691 | ExprResult Res = TransformExpr(E); | |||
7692 | if (Trap.hasErrorOccurred() || Res.isInvalid()) | |||
7693 | return ExprError(); | |||
7694 | ||||
7695 | return ExprFilter(Res.get()); | |||
7696 | } | |||
7697 | ||||
7698 | // Since correcting typos may intoduce new TypoExprs, this function | |||
7699 | // checks for new TypoExprs and recurses if it finds any. Note that it will | |||
7700 | // only succeed if it is able to correct all typos in the given expression. | |||
7701 | ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { | |||
7702 | if (Res.isInvalid()) { | |||
7703 | return Res; | |||
7704 | } | |||
7705 | // Check to see if any new TypoExprs were created. If so, we need to recurse | |||
7706 | // to check their validity. | |||
7707 | Expr *FixedExpr = Res.get(); | |||
7708 | ||||
7709 | auto SavedTypoExprs = std::move(TypoExprs); | |||
7710 | auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs); | |||
7711 | TypoExprs.clear(); | |||
7712 | AmbiguousTypoExprs.clear(); | |||
7713 | ||||
7714 | FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr); | |||
7715 | if (!TypoExprs.empty()) { | |||
7716 | // Recurse to handle newly created TypoExprs. If we're not able to | |||
7717 | // handle them, discard these TypoExprs. | |||
7718 | ExprResult RecurResult = | |||
7719 | RecursiveTransformLoop(FixedExpr, IsAmbiguous); | |||
7720 | if (RecurResult.isInvalid()) { | |||
7721 | Res = ExprError(); | |||
7722 | // Recursive corrections didn't work, wipe them away and don't add | |||
7723 | // them to the TypoExprs set. Remove them from Sema's TypoExpr list | |||
7724 | // since we don't want to clear them twice. Note: it's possible the | |||
7725 | // TypoExprs were created recursively and thus won't be in our | |||
7726 | // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`. | |||
7727 | auto &SemaTypoExprs = SemaRef.TypoExprs; | |||
7728 | for (auto TE : TypoExprs) { | |||
7729 | TransformCache.erase(TE); | |||
7730 | SemaRef.clearDelayedTypo(TE); | |||
7731 | ||||
7732 | auto SI = find(SemaTypoExprs, TE); | |||
7733 | if (SI != SemaTypoExprs.end()) { | |||
7734 | SemaTypoExprs.erase(SI); | |||
7735 | } | |||
7736 | } | |||
7737 | } else { | |||
7738 | // TypoExpr is valid: add newly created TypoExprs since we were | |||
7739 | // able to correct them. | |||
7740 | Res = RecurResult; | |||
7741 | SavedTypoExprs.set_union(TypoExprs); | |||
7742 | } | |||
7743 | } | |||
7744 | ||||
7745 | TypoExprs = std::move(SavedTypoExprs); | |||
7746 | AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs); | |||
7747 | ||||
7748 | return Res; | |||
7749 | } | |||
7750 | ||||
7751 | // Try to transform the given expression, looping through the correction | |||
7752 | // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`. | |||
7753 | // | |||
7754 | // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to | |||
7755 | // true and this method immediately will return an `ExprError`. | |||
7756 | ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) { | |||
7757 | ExprResult Res; | |||
7758 | auto SavedTypoExprs = std::move(SemaRef.TypoExprs); | |||
7759 | SemaRef.TypoExprs.clear(); | |||
7760 | ||||
7761 | while (true) { | |||
7762 | Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); | |||
7763 | ||||
7764 | // Recursion encountered an ambiguous correction. This means that our | |||
7765 | // correction itself is ambiguous, so stop now. | |||
7766 | if (IsAmbiguous) | |||
7767 | break; | |||
7768 | ||||
7769 | // If the transform is still valid after checking for any new typos, | |||
7770 | // it's good to go. | |||
7771 | if (!Res.isInvalid()) | |||
7772 | break; | |||
7773 | ||||
7774 | // The transform was invalid, see if we have any TypoExprs with untried | |||
7775 | // correction candidates. | |||
7776 | if (!CheckAndAdvanceTypoExprCorrectionStreams()) | |||
7777 | break; | |||
7778 | } | |||
7779 | ||||
7780 | // If we found a valid result, double check to make sure it's not ambiguous. | |||
7781 | if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { | |||
7782 | auto SavedTransformCache = std::move(TransformCache); | |||
7783 | TransformCache.clear(); | |||
7784 | // Ensure none of the TypoExprs have multiple typo correction candidates | |||
7785 | // with the same edit length that pass all the checks and filters. | |||
7786 | while (!AmbiguousTypoExprs.empty()) { | |||
7787 | auto TE = AmbiguousTypoExprs.back(); | |||
7788 | ||||
7789 | // TryTransform itself can create new Typos, adding them to the TypoExpr map | |||
7790 | // and invalidating our TypoExprState, so always fetch it instead of storing. | |||
7791 | SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); | |||
7792 | ||||
7793 | TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); | |||
7794 | TypoCorrection Next; | |||
7795 | do { | |||
7796 | // Fetch the next correction by erasing the typo from the cache and calling | |||
7797 | // `TryTransform` which will iterate through corrections in | |||
7798 | // `TransformTypoExpr`. | |||
7799 | TransformCache.erase(TE); | |||
7800 | ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); | |||
7801 | ||||
7802 | if (!AmbigRes.isInvalid() || IsAmbiguous) { | |||
7803 | SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream(); | |||
7804 | SavedTransformCache.erase(TE); | |||
7805 | Res = ExprError(); | |||
7806 | IsAmbiguous = true; | |||
7807 | break; | |||
7808 | } | |||
7809 | } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) && | |||
7810 | Next.getEditDistance(false) == TC.getEditDistance(false)); | |||
7811 | ||||
7812 | if (IsAmbiguous) | |||
7813 | break; | |||
7814 | ||||
7815 | AmbiguousTypoExprs.remove(TE); | |||
7816 | SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition(); | |||
7817 | } | |||
7818 | TransformCache = std::move(SavedTransformCache); | |||
7819 | } | |||
7820 | ||||
7821 | // Wipe away any newly created TypoExprs that we don't know about. Since we | |||
7822 | // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only | |||
7823 | // possible if a `TypoExpr` is created during a transformation but then | |||
7824 | // fails before we can discover it. | |||
7825 | auto &SemaTypoExprs = SemaRef.TypoExprs; | |||
7826 | for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) { | |||
7827 | auto TE = *Iterator; | |||
7828 | auto FI = find(TypoExprs, TE); | |||
7829 | if (FI != TypoExprs.end()) { | |||
7830 | Iterator++; | |||
7831 | continue; | |||
7832 | } | |||
7833 | SemaRef.clearDelayedTypo(TE); | |||
7834 | Iterator = SemaTypoExprs.erase(Iterator); | |||
7835 | } | |||
7836 | SemaRef.TypoExprs = std::move(SavedTypoExprs); | |||
7837 | ||||
7838 | return Res; | |||
7839 | } | |||
7840 | ||||
7841 | public: | |||
7842 | TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) | |||
7843 | : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} | |||
7844 | ||||
7845 | ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, | |||
7846 | MultiExprArg Args, | |||
7847 | SourceLocation RParenLoc, | |||
7848 | Expr *ExecConfig = nullptr) { | |||
7849 | auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, | |||
7850 | RParenLoc, ExecConfig); | |||
7851 | if (auto *OE = dyn_cast<OverloadExpr>(Callee)) { | |||
7852 | if (Result.isUsable()) { | |||
7853 | Expr *ResultCall = Result.get(); | |||
7854 | if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) | |||
7855 | ResultCall = BE->getSubExpr(); | |||
7856 | if (auto *CE = dyn_cast<CallExpr>(ResultCall)) | |||
7857 | OverloadResolution[OE] = CE->getCallee(); | |||
7858 | } | |||
7859 | } | |||
7860 | return Result; | |||
7861 | } | |||
7862 | ||||
7863 | ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } | |||
7864 | ||||
7865 | ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } | |||
7866 | ||||
7867 | ExprResult Transform(Expr *E) { | |||
7868 | bool IsAmbiguous = false; | |||
7869 | ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous); | |||
7870 | ||||
7871 | if (!Res.isUsable()) | |||
7872 | FindTypoExprs(TypoExprs).TraverseStmt(E); | |||
7873 | ||||
7874 | EmitAllDiagnostics(IsAmbiguous); | |||
7875 | ||||
7876 | return Res; | |||
7877 | } | |||
7878 | ||||
7879 | ExprResult TransformTypoExpr(TypoExpr *E) { | |||
7880 | // If the TypoExpr hasn't been seen before, record it. Otherwise, return the | |||
7881 | // cached transformation result if there is one and the TypoExpr isn't the | |||
7882 | // first one that was encountered. | |||
7883 | auto &CacheEntry = TransformCache[E]; | |||
7884 | if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) { | |||
7885 | return CacheEntry; | |||
7886 | } | |||
7887 | ||||
7888 | auto &State = SemaRef.getTypoExprState(E); | |||
7889 | assert(State.Consumer && "Cannot transform a cleared TypoExpr")((State.Consumer && "Cannot transform a cleared TypoExpr" ) ? static_cast<void> (0) : __assert_fail ("State.Consumer && \"Cannot transform a cleared TypoExpr\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7889, __PRETTY_FUNCTION__)); | |||
7890 | ||||
7891 | // For the first TypoExpr and an uncached TypoExpr, find the next likely | |||
7892 | // typo correction and return it. | |||
7893 | while (TypoCorrection TC = State.Consumer->getNextCorrection()) { | |||
7894 | if (InitDecl && TC.getFoundDecl() == InitDecl) | |||
7895 | continue; | |||
7896 | // FIXME: If we would typo-correct to an invalid declaration, it's | |||
7897 | // probably best to just suppress all errors from this typo correction. | |||
7898 | ExprResult NE = State.RecoveryHandler ? | |||
7899 | State.RecoveryHandler(SemaRef, E, TC) : | |||
7900 | attemptRecovery(SemaRef, *State.Consumer, TC); | |||
7901 | if (!NE.isInvalid()) { | |||
7902 | // Check whether there may be a second viable correction with the same | |||
7903 | // edit distance; if so, remember this TypoExpr may have an ambiguous | |||
7904 | // correction so it can be more thoroughly vetted later. | |||
7905 | TypoCorrection Next; | |||
7906 | if ((Next = State.Consumer->peekNextCorrection()) && | |||
7907 | Next.getEditDistance(false) == TC.getEditDistance(false)) { | |||
7908 | AmbiguousTypoExprs.insert(E); | |||
7909 | } else { | |||
7910 | AmbiguousTypoExprs.remove(E); | |||
7911 | } | |||
7912 | assert(!NE.isUnset() &&((!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult" ) ? static_cast<void> (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7913, __PRETTY_FUNCTION__)) | |||
7913 | "Typo was transformed into a valid-but-null ExprResult")((!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult" ) ? static_cast<void> (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7913, __PRETTY_FUNCTION__)); | |||
7914 | return CacheEntry = NE; | |||
7915 | } | |||
7916 | } | |||
7917 | return CacheEntry = ExprError(); | |||
7918 | } | |||
7919 | }; | |||
7920 | } | |||
7921 | ||||
7922 | ExprResult | |||
7923 | Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, | |||
7924 | llvm::function_ref<ExprResult(Expr *)> Filter) { | |||
7925 | // If the current evaluation context indicates there are uncorrected typos | |||
7926 | // and the current expression isn't guaranteed to not have typos, try to | |||
7927 | // resolve any TypoExpr nodes that might be in the expression. | |||
7928 | if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && | |||
7929 | (E->isTypeDependent() || E->isValueDependent() || | |||
7930 | E->isInstantiationDependent())) { | |||
7931 | auto TyposResolved = DelayedTypos.size(); | |||
7932 | auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); | |||
7933 | TyposResolved -= DelayedTypos.size(); | |||
7934 | if (Result.isInvalid() || Result.get() != E) { | |||
7935 | ExprEvalContexts.back().NumTypos -= TyposResolved; | |||
7936 | return Result; | |||
7937 | } | |||
7938 | assert(TyposResolved == 0 && "Corrected typo but got same Expr back?")((TyposResolved == 0 && "Corrected typo but got same Expr back?" ) ? static_cast<void> (0) : __assert_fail ("TyposResolved == 0 && \"Corrected typo but got same Expr back?\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 7938, __PRETTY_FUNCTION__)); | |||
7939 | } | |||
7940 | return E; | |||
7941 | } | |||
7942 | ||||
7943 | ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, | |||
7944 | bool DiscardedValue, | |||
7945 | bool IsConstexpr) { | |||
7946 | ExprResult FullExpr = FE; | |||
7947 | ||||
7948 | if (!FullExpr.get()) | |||
7949 | return ExprError(); | |||
7950 | ||||
7951 | if (DiagnoseUnexpandedParameterPack(FullExpr.get())) | |||
7952 | return ExprError(); | |||
7953 | ||||
7954 | if (DiscardedValue) { | |||
7955 | // Top-level expressions default to 'id' when we're in a debugger. | |||
7956 | if (getLangOpts().DebuggerCastResultToId && | |||
7957 | FullExpr.get()->getType() == Context.UnknownAnyTy) { | |||
7958 | FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); | |||
7959 | if (FullExpr.isInvalid()) | |||
7960 | return ExprError(); | |||
7961 | } | |||
7962 | ||||
7963 | FullExpr = CheckPlaceholderExpr(FullExpr.get()); | |||
7964 | if (FullExpr.isInvalid()) | |||
7965 | return ExprError(); | |||
7966 | ||||
7967 | FullExpr = IgnoredValueConversions(FullExpr.get()); | |||
7968 | if (FullExpr.isInvalid()) | |||
7969 | return ExprError(); | |||
7970 | ||||
7971 | DiagnoseUnusedExprResult(FullExpr.get()); | |||
7972 | } | |||
7973 | ||||
7974 | FullExpr = CorrectDelayedTyposInExpr(FullExpr.get()); | |||
7975 | if (FullExpr.isInvalid()) | |||
7976 | return ExprError(); | |||
7977 | ||||
7978 | CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); | |||
7979 | ||||
7980 | // At the end of this full expression (which could be a deeply nested | |||
7981 | // lambda), if there is a potential capture within the nested lambda, | |||
7982 | // have the outer capture-able lambda try and capture it. | |||
7983 | // Consider the following code: | |||
7984 | // void f(int, int); | |||
7985 | // void f(const int&, double); | |||
7986 | // void foo() { | |||
7987 | // const int x = 10, y = 20; | |||
7988 | // auto L = [=](auto a) { | |||
7989 | // auto M = [=](auto b) { | |||
7990 | // f(x, b); <-- requires x to be captured by L and M | |||
7991 | // f(y, a); <-- requires y to be captured by L, but not all Ms | |||
7992 | // }; | |||
7993 | // }; | |||
7994 | // } | |||
7995 | ||||
7996 | // FIXME: Also consider what happens for something like this that involves | |||
7997 | // the gnu-extension statement-expressions or even lambda-init-captures: | |||
7998 | // void f() { | |||
7999 | // const int n = 0; | |||
8000 | // auto L = [&](auto a) { | |||
8001 | // +n + ({ 0; a; }); | |||
8002 | // }; | |||
8003 | // } | |||
8004 | // | |||
8005 | // Here, we see +n, and then the full-expression 0; ends, so we don't | |||
8006 | // capture n (and instead remove it from our list of potential captures), | |||
8007 | // and then the full-expression +n + ({ 0; }); ends, but it's too late | |||
8008 | // for us to see that we need to capture n after all. | |||
8009 | ||||
8010 | LambdaScopeInfo *const CurrentLSI = | |||
8011 | getCurLambda(/*IgnoreCapturedRegions=*/true); | |||
8012 | // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer | |||
8013 | // even if CurContext is not a lambda call operator. Refer to that Bug Report | |||
8014 | // for an example of the code that might cause this asynchrony. | |||
8015 | // By ensuring we are in the context of a lambda's call operator | |||
8016 | // we can fix the bug (we only need to check whether we need to capture | |||
8017 | // if we are within a lambda's body); but per the comments in that | |||
8018 | // PR, a proper fix would entail : | |||
8019 | // "Alternative suggestion: | |||
8020 | // - Add to Sema an integer holding the smallest (outermost) scope | |||
8021 | // index that we are *lexically* within, and save/restore/set to | |||
8022 | // FunctionScopes.size() in InstantiatingTemplate's | |||
8023 | // constructor/destructor. | |||
8024 | // - Teach the handful of places that iterate over FunctionScopes to | |||
8025 | // stop at the outermost enclosing lexical scope." | |||
8026 | DeclContext *DC = CurContext; | |||
8027 | while (DC && isa<CapturedDecl>(DC)) | |||
8028 | DC = DC->getParent(); | |||
8029 | const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); | |||
8030 | if (IsInLambdaDeclContext && CurrentLSI && | |||
8031 | CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) | |||
8032 | CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, | |||
8033 | *this); | |||
8034 | return MaybeCreateExprWithCleanups(FullExpr); | |||
8035 | } | |||
8036 | ||||
8037 | StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { | |||
8038 | if (!FullStmt) return StmtError(); | |||
8039 | ||||
8040 | return MaybeCreateStmtWithCleanups(FullStmt); | |||
8041 | } | |||
8042 | ||||
8043 | Sema::IfExistsResult | |||
8044 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, | |||
8045 | CXXScopeSpec &SS, | |||
8046 | const DeclarationNameInfo &TargetNameInfo) { | |||
8047 | DeclarationName TargetName = TargetNameInfo.getName(); | |||
8048 | if (!TargetName) | |||
8049 | return IER_DoesNotExist; | |||
8050 | ||||
8051 | // If the name itself is dependent, then the result is dependent. | |||
8052 | if (TargetName.isDependentName()) | |||
8053 | return IER_Dependent; | |||
8054 | ||||
8055 | // Do the redeclaration lookup in the current scope. | |||
8056 | LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, | |||
8057 | Sema::NotForRedeclaration); | |||
8058 | LookupParsedName(R, S, &SS); | |||
8059 | R.suppressDiagnostics(); | |||
8060 | ||||
8061 | switch (R.getResultKind()) { | |||
8062 | case LookupResult::Found: | |||
8063 | case LookupResult::FoundOverloaded: | |||
8064 | case LookupResult::FoundUnresolvedValue: | |||
8065 | case LookupResult::Ambiguous: | |||
8066 | return IER_Exists; | |||
8067 | ||||
8068 | case LookupResult::NotFound: | |||
8069 | return IER_DoesNotExist; | |||
8070 | ||||
8071 | case LookupResult::NotFoundInCurrentInstantiation: | |||
8072 | return IER_Dependent; | |||
8073 | } | |||
8074 | ||||
8075 | llvm_unreachable("Invalid LookupResult Kind!")::llvm::llvm_unreachable_internal("Invalid LookupResult Kind!" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExprCXX.cpp" , 8075); | |||
8076 | } | |||
8077 | ||||
8078 | Sema::IfExistsResult | |||
8079 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, | |||
8080 | bool IsIfExists, CXXScopeSpec &SS, | |||
8081 | UnqualifiedId &Name) { | |||
8082 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); | |||
8083 | ||||
8084 | // Check for an unexpanded parameter pack. | |||
8085 | auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; | |||
8086 | if (DiagnoseUnexpandedParameterPack(SS, UPPC) || | |||
8087 | DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC)) | |||
8088 | return IER_Error; | |||
8089 | ||||
8090 | return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); | |||
8091 | } |
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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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 ConstantArrayTypeBitfields { |
1517 | friend class ConstantArrayType; |
1518 | |
1519 | unsigned : NumTypeBits + 3 + 3; |
1520 | |
1521 | /// Whether we have a stored size expression. |
1522 | unsigned HasStoredSizeExpr : 1; |
1523 | }; |
1524 | |
1525 | class BuiltinTypeBitfields { |
1526 | friend class BuiltinType; |
1527 | |
1528 | unsigned : NumTypeBits; |
1529 | |
1530 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1531 | unsigned Kind : 8; |
1532 | }; |
1533 | |
1534 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1535 | /// Only common bits are stored here. Additional uncommon bits are stored |
1536 | /// in a trailing object after FunctionProtoType. |
1537 | class FunctionTypeBitfields { |
1538 | friend class FunctionProtoType; |
1539 | friend class FunctionType; |
1540 | |
1541 | unsigned : NumTypeBits; |
1542 | |
1543 | /// Extra information which affects how the function is called, like |
1544 | /// regparm and the calling convention. |
1545 | unsigned ExtInfo : 12; |
1546 | |
1547 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1548 | /// |
1549 | /// This is a value of type \c RefQualifierKind. |
1550 | unsigned RefQualifier : 2; |
1551 | |
1552 | /// Used only by FunctionProtoType, put here to pack with the |
1553 | /// other bitfields. |
1554 | /// The qualifiers are part of FunctionProtoType because... |
1555 | /// |
1556 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1557 | /// cv-qualifier-seq, [...], are part of the function type. |
1558 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1559 | /// Whether this function has extended Qualifiers. |
1560 | unsigned HasExtQuals : 1; |
1561 | |
1562 | /// The number of parameters this function has, not counting '...'. |
1563 | /// According to [implimits] 8 bits should be enough here but this is |
1564 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1565 | /// keep NumParams as wide as reasonably possible. |
1566 | unsigned NumParams : 16; |
1567 | |
1568 | /// The type of exception specification this function has. |
1569 | unsigned ExceptionSpecType : 4; |
1570 | |
1571 | /// Whether this function has extended parameter information. |
1572 | unsigned HasExtParameterInfos : 1; |
1573 | |
1574 | /// Whether the function is variadic. |
1575 | unsigned Variadic : 1; |
1576 | |
1577 | /// Whether this function has a trailing return type. |
1578 | unsigned HasTrailingReturn : 1; |
1579 | }; |
1580 | |
1581 | class ObjCObjectTypeBitfields { |
1582 | friend class ObjCObjectType; |
1583 | |
1584 | unsigned : NumTypeBits; |
1585 | |
1586 | /// The number of type arguments stored directly on this object type. |
1587 | unsigned NumTypeArgs : 7; |
1588 | |
1589 | /// The number of protocols stored directly on this object type. |
1590 | unsigned NumProtocols : 6; |
1591 | |
1592 | /// Whether this is a "kindof" type. |
1593 | unsigned IsKindOf : 1; |
1594 | }; |
1595 | |
1596 | class ReferenceTypeBitfields { |
1597 | friend class ReferenceType; |
1598 | |
1599 | unsigned : NumTypeBits; |
1600 | |
1601 | /// True if the type was originally spelled with an lvalue sigil. |
1602 | /// This is never true of rvalue references but can also be false |
1603 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1604 | /// as follows: |
1605 | /// |
1606 | /// typedef int &ref; // lvalue, spelled lvalue |
1607 | /// typedef int &&rvref; // rvalue |
1608 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1609 | /// ref &&a; // lvalue, inner ref |
1610 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1611 | /// rvref &&a; // rvalue, inner ref |
1612 | unsigned SpelledAsLValue : 1; |
1613 | |
1614 | /// True if the inner type is a reference type. This only happens |
1615 | /// in non-canonical forms. |
1616 | unsigned InnerRef : 1; |
1617 | }; |
1618 | |
1619 | class TypeWithKeywordBitfields { |
1620 | friend class TypeWithKeyword; |
1621 | |
1622 | unsigned : NumTypeBits; |
1623 | |
1624 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1625 | unsigned Keyword : 8; |
1626 | }; |
1627 | |
1628 | enum { NumTypeWithKeywordBits = 8 }; |
1629 | |
1630 | class ElaboratedTypeBitfields { |
1631 | friend class ElaboratedType; |
1632 | |
1633 | unsigned : NumTypeBits; |
1634 | unsigned : NumTypeWithKeywordBits; |
1635 | |
1636 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1637 | unsigned HasOwnedTagDecl : 1; |
1638 | }; |
1639 | |
1640 | class VectorTypeBitfields { |
1641 | friend class VectorType; |
1642 | friend class DependentVectorType; |
1643 | |
1644 | unsigned : NumTypeBits; |
1645 | |
1646 | /// The kind of vector, either a generic vector type or some |
1647 | /// target-specific vector type such as for AltiVec or Neon. |
1648 | unsigned VecKind : 3; |
1649 | |
1650 | /// The number of elements in the vector. |
1651 | unsigned NumElements : 29 - NumTypeBits; |
1652 | |
1653 | enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 }; |
1654 | }; |
1655 | |
1656 | class AttributedTypeBitfields { |
1657 | friend class AttributedType; |
1658 | |
1659 | unsigned : NumTypeBits; |
1660 | |
1661 | /// An AttributedType::Kind |
1662 | unsigned AttrKind : 32 - NumTypeBits; |
1663 | }; |
1664 | |
1665 | class AutoTypeBitfields { |
1666 | friend class AutoType; |
1667 | |
1668 | unsigned : NumTypeBits; |
1669 | |
1670 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1671 | /// or '__auto_type'? AutoTypeKeyword value. |
1672 | unsigned Keyword : 2; |
1673 | }; |
1674 | |
1675 | class SubstTemplateTypeParmPackTypeBitfields { |
1676 | friend class SubstTemplateTypeParmPackType; |
1677 | |
1678 | unsigned : NumTypeBits; |
1679 | |
1680 | /// The number of template arguments in \c Arguments, which is |
1681 | /// expected to be able to hold at least 1024 according to [implimits]. |
1682 | /// However as this limit is somewhat easy to hit with template |
1683 | /// metaprogramming we'd prefer to keep it as large as possible. |
1684 | /// At the moment it has been left as a non-bitfield since this type |
1685 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1686 | /// introduce the performance impact of a bitfield. |
1687 | unsigned NumArgs; |
1688 | }; |
1689 | |
1690 | class TemplateSpecializationTypeBitfields { |
1691 | friend class TemplateSpecializationType; |
1692 | |
1693 | unsigned : NumTypeBits; |
1694 | |
1695 | /// Whether this template specialization type is a substituted type alias. |
1696 | unsigned TypeAlias : 1; |
1697 | |
1698 | /// The number of template arguments named in this class template |
1699 | /// specialization, which is expected to be able to hold at least 1024 |
1700 | /// according to [implimits]. However, as this limit is somewhat easy to |
1701 | /// hit with template metaprogramming we'd prefer to keep it as large |
1702 | /// as possible. At the moment it has been left as a non-bitfield since |
1703 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1704 | /// to introduce the performance impact of a bitfield. |
1705 | unsigned NumArgs; |
1706 | }; |
1707 | |
1708 | class DependentTemplateSpecializationTypeBitfields { |
1709 | friend class DependentTemplateSpecializationType; |
1710 | |
1711 | unsigned : NumTypeBits; |
1712 | unsigned : NumTypeWithKeywordBits; |
1713 | |
1714 | /// The number of template arguments named in this class template |
1715 | /// specialization, which is expected to be able to hold at least 1024 |
1716 | /// according to [implimits]. However, as this limit is somewhat easy to |
1717 | /// hit with template metaprogramming we'd prefer to keep it as large |
1718 | /// as possible. At the moment it has been left as a non-bitfield since |
1719 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1720 | /// to introduce the performance impact of a bitfield. |
1721 | unsigned NumArgs; |
1722 | }; |
1723 | |
1724 | class PackExpansionTypeBitfields { |
1725 | friend class PackExpansionType; |
1726 | |
1727 | unsigned : NumTypeBits; |
1728 | |
1729 | /// The number of expansions that this pack expansion will |
1730 | /// generate when substituted (+1), which is expected to be able to |
1731 | /// hold at least 1024 according to [implimits]. However, as this limit |
1732 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1733 | /// keep it as large as possible. At the moment it has been left as a |
1734 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1735 | /// there is no reason to introduce the performance impact of a bitfield. |
1736 | /// |
1737 | /// This field will only have a non-zero value when some of the parameter |
1738 | /// packs that occur within the pattern have been substituted but others |
1739 | /// have not. |
1740 | unsigned NumExpansions; |
1741 | }; |
1742 | |
1743 | union { |
1744 | TypeBitfields TypeBits; |
1745 | ArrayTypeBitfields ArrayTypeBits; |
1746 | ConstantArrayTypeBitfields ConstantArrayTypeBits; |
1747 | AttributedTypeBitfields AttributedTypeBits; |
1748 | AutoTypeBitfields AutoTypeBits; |
1749 | BuiltinTypeBitfields BuiltinTypeBits; |
1750 | FunctionTypeBitfields FunctionTypeBits; |
1751 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1752 | ReferenceTypeBitfields ReferenceTypeBits; |
1753 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1754 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1755 | VectorTypeBitfields VectorTypeBits; |
1756 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1757 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1758 | DependentTemplateSpecializationTypeBitfields |
1759 | DependentTemplateSpecializationTypeBits; |
1760 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1761 | |
1762 | static_assert(sizeof(TypeBitfields) <= 8, |
1763 | "TypeBitfields is larger than 8 bytes!"); |
1764 | static_assert(sizeof(ArrayTypeBitfields) <= 8, |
1765 | "ArrayTypeBitfields is larger than 8 bytes!"); |
1766 | static_assert(sizeof(AttributedTypeBitfields) <= 8, |
1767 | "AttributedTypeBitfields is larger than 8 bytes!"); |
1768 | static_assert(sizeof(AutoTypeBitfields) <= 8, |
1769 | "AutoTypeBitfields is larger than 8 bytes!"); |
1770 | static_assert(sizeof(BuiltinTypeBitfields) <= 8, |
1771 | "BuiltinTypeBitfields is larger than 8 bytes!"); |
1772 | static_assert(sizeof(FunctionTypeBitfields) <= 8, |
1773 | "FunctionTypeBitfields is larger than 8 bytes!"); |
1774 | static_assert(sizeof(ObjCObjectTypeBitfields) <= 8, |
1775 | "ObjCObjectTypeBitfields is larger than 8 bytes!"); |
1776 | static_assert(sizeof(ReferenceTypeBitfields) <= 8, |
1777 | "ReferenceTypeBitfields is larger than 8 bytes!"); |
1778 | static_assert(sizeof(TypeWithKeywordBitfields) <= 8, |
1779 | "TypeWithKeywordBitfields is larger than 8 bytes!"); |
1780 | static_assert(sizeof(ElaboratedTypeBitfields) <= 8, |
1781 | "ElaboratedTypeBitfields is larger than 8 bytes!"); |
1782 | static_assert(sizeof(VectorTypeBitfields) <= 8, |
1783 | "VectorTypeBitfields is larger than 8 bytes!"); |
1784 | static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8, |
1785 | "SubstTemplateTypeParmPackTypeBitfields is larger" |
1786 | " than 8 bytes!"); |
1787 | static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8, |
1788 | "TemplateSpecializationTypeBitfields is larger" |
1789 | " than 8 bytes!"); |
1790 | static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8, |
1791 | "DependentTemplateSpecializationTypeBitfields is larger" |
1792 | " than 8 bytes!"); |
1793 | static_assert(sizeof(PackExpansionTypeBitfields) <= 8, |
1794 | "PackExpansionTypeBitfields is larger than 8 bytes"); |
1795 | }; |
1796 | |
1797 | private: |
1798 | template <class T> friend class TypePropertyCache; |
1799 | |
1800 | /// Set whether this type comes from an AST file. |
1801 | void setFromAST(bool V = true) const { |
1802 | TypeBits.FromAST = V; |
1803 | } |
1804 | |
1805 | protected: |
1806 | friend class ASTContext; |
1807 | |
1808 | Type(TypeClass tc, QualType canon, bool Dependent, |
1809 | bool InstantiationDependent, bool VariablyModified, |
1810 | bool ContainsUnexpandedParameterPack) |
1811 | : ExtQualsTypeCommonBase(this, |
1812 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1813 | TypeBits.TC = tc; |
1814 | TypeBits.Dependent = Dependent; |
1815 | TypeBits.InstantiationDependent = Dependent || InstantiationDependent; |
1816 | TypeBits.VariablyModified = VariablyModified; |
1817 | TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; |
1818 | TypeBits.CacheValid = false; |
1819 | TypeBits.CachedLocalOrUnnamed = false; |
1820 | TypeBits.CachedLinkage = NoLinkage; |
1821 | TypeBits.FromAST = false; |
1822 | } |
1823 | |
1824 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1825 | Type *this_() { return this; } |
1826 | |
1827 | void setDependent(bool D = true) { |
1828 | TypeBits.Dependent = D; |
1829 | if (D) |
1830 | TypeBits.InstantiationDependent = true; |
1831 | } |
1832 | |
1833 | void setInstantiationDependent(bool D = true) { |
1834 | TypeBits.InstantiationDependent = D; } |
1835 | |
1836 | void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; } |
1837 | |
1838 | void setContainsUnexpandedParameterPack(bool PP = true) { |
1839 | TypeBits.ContainsUnexpandedParameterPack = PP; |
1840 | } |
1841 | |
1842 | public: |
1843 | friend class ASTReader; |
1844 | friend class ASTWriter; |
1845 | |
1846 | Type(const Type &) = delete; |
1847 | Type(Type &&) = delete; |
1848 | Type &operator=(const Type &) = delete; |
1849 | Type &operator=(Type &&) = delete; |
1850 | |
1851 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1852 | |
1853 | /// Whether this type comes from an AST file. |
1854 | bool isFromAST() const { return TypeBits.FromAST; } |
1855 | |
1856 | /// Whether this type is or contains an unexpanded parameter |
1857 | /// pack, used to support C++0x variadic templates. |
1858 | /// |
1859 | /// A type that contains a parameter pack shall be expanded by the |
1860 | /// ellipsis operator at some point. For example, the typedef in the |
1861 | /// following example contains an unexpanded parameter pack 'T': |
1862 | /// |
1863 | /// \code |
1864 | /// template<typename ...T> |
1865 | /// struct X { |
1866 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1867 | /// }; |
1868 | /// \endcode |
1869 | /// |
1870 | /// Note that this routine does not specify which |
1871 | bool containsUnexpandedParameterPack() const { |
1872 | return TypeBits.ContainsUnexpandedParameterPack; |
1873 | } |
1874 | |
1875 | /// Determines if this type would be canonical if it had no further |
1876 | /// qualification. |
1877 | bool isCanonicalUnqualified() const { |
1878 | return CanonicalType == QualType(this, 0); |
1879 | } |
1880 | |
1881 | /// Pull a single level of sugar off of this locally-unqualified type. |
1882 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1883 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1884 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1885 | |
1886 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1887 | /// object types, function types, and incomplete types. |
1888 | |
1889 | /// Return true if this is an incomplete type. |
1890 | /// A type that can describe objects, but which lacks information needed to |
1891 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1892 | /// routine will need to determine if the size is actually required. |
1893 | /// |
1894 | /// Def If non-null, and the type refers to some kind of declaration |
1895 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1896 | /// class), will be set to the declaration. |
1897 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1898 | |
1899 | /// Return true if this is an incomplete or object |
1900 | /// type, in other words, not a function type. |
1901 | bool isIncompleteOrObjectType() const { |
1902 | return !isFunctionType(); |
1903 | } |
1904 | |
1905 | /// Determine whether this type is an object type. |
1906 | bool isObjectType() const { |
1907 | // C++ [basic.types]p8: |
1908 | // An object type is a (possibly cv-qualified) type that is not a |
1909 | // function type, not a reference type, and not a void type. |
1910 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1911 | } |
1912 | |
1913 | /// Return true if this is a literal type |
1914 | /// (C++11 [basic.types]p10) |
1915 | bool isLiteralType(const ASTContext &Ctx) const; |
1916 | |
1917 | /// Test if this type is a standard-layout type. |
1918 | /// (C++0x [basic.type]p9) |
1919 | bool isStandardLayoutType() const; |
1920 | |
1921 | /// Helper methods to distinguish type categories. All type predicates |
1922 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1923 | |
1924 | /// Returns true if the type is a builtin type. |
1925 | bool isBuiltinType() const; |
1926 | |
1927 | /// Test for a particular builtin type. |
1928 | bool isSpecificBuiltinType(unsigned K) const; |
1929 | |
1930 | /// Test for a type which does not represent an actual type-system type but |
1931 | /// is instead used as a placeholder for various convenient purposes within |
1932 | /// Clang. All such types are BuiltinTypes. |
1933 | bool isPlaceholderType() const; |
1934 | const BuiltinType *getAsPlaceholderType() const; |
1935 | |
1936 | /// Test for a specific placeholder type. |
1937 | bool isSpecificPlaceholderType(unsigned K) const; |
1938 | |
1939 | /// Test for a placeholder type other than Overload; see |
1940 | /// BuiltinType::isNonOverloadPlaceholderType. |
1941 | bool isNonOverloadPlaceholderType() const; |
1942 | |
1943 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1944 | /// isComplexIntegerType() can be used to test for complex integers. |
1945 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1946 | bool isEnumeralType() const; |
1947 | |
1948 | /// Determine whether this type is a scoped enumeration type. |
1949 | bool isScopedEnumeralType() const; |
1950 | bool isBooleanType() const; |
1951 | bool isCharType() const; |
1952 | bool isWideCharType() const; |
1953 | bool isChar8Type() const; |
1954 | bool isChar16Type() const; |
1955 | bool isChar32Type() const; |
1956 | bool isAnyCharacterType() const; |
1957 | bool isIntegralType(const ASTContext &Ctx) const; |
1958 | |
1959 | /// Determine whether this type is an integral or enumeration type. |
1960 | bool isIntegralOrEnumerationType() const; |
1961 | |
1962 | /// Determine whether this type is an integral or unscoped enumeration type. |
1963 | bool isIntegralOrUnscopedEnumerationType() const; |
1964 | |
1965 | /// Floating point categories. |
1966 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1967 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1968 | /// isComplexIntegerType() can be used to test for complex integers. |
1969 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1970 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1971 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1972 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1973 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1974 | bool isFloat128Type() const; |
1975 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1976 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1977 | bool isVoidType() const; // C99 6.2.5p19 |
1978 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1979 | bool isAggregateType() const; |
1980 | bool isFundamentalType() const; |
1981 | bool isCompoundType() const; |
1982 | |
1983 | // Type Predicates: Check to see if this type is structurally the specified |
1984 | // type, ignoring typedefs and qualifiers. |
1985 | bool isFunctionType() const; |
1986 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
1987 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
1988 | bool isPointerType() const; |
1989 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
1990 | bool isBlockPointerType() const; |
1991 | bool isVoidPointerType() const; |
1992 | bool isReferenceType() const; |
1993 | bool isLValueReferenceType() const; |
1994 | bool isRValueReferenceType() const; |
1995 | bool isFunctionPointerType() const; |
1996 | bool isFunctionReferenceType() const; |
1997 | bool isMemberPointerType() const; |
1998 | bool isMemberFunctionPointerType() const; |
1999 | bool isMemberDataPointerType() const; |
2000 | bool isArrayType() const; |
2001 | bool isConstantArrayType() const; |
2002 | bool isIncompleteArrayType() const; |
2003 | bool isVariableArrayType() const; |
2004 | bool isDependentSizedArrayType() const; |
2005 | bool isRecordType() const; |
2006 | bool isClassType() const; |
2007 | bool isStructureType() const; |
2008 | bool isObjCBoxableRecordType() const; |
2009 | bool isInterfaceType() const; |
2010 | bool isStructureOrClassType() const; |
2011 | bool isUnionType() const; |
2012 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2013 | bool isVectorType() const; // GCC vector type. |
2014 | bool isExtVectorType() const; // Extended vector type. |
2015 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2016 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2017 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2018 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2019 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2020 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2021 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2022 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2023 | // for the common case. |
2024 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2025 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2026 | bool isObjCQualifiedIdType() const; // id<foo> |
2027 | bool isObjCQualifiedClassType() const; // Class<foo> |
2028 | bool isObjCObjectOrInterfaceType() const; |
2029 | bool isObjCIdType() const; // id |
2030 | bool isDecltypeType() const; |
2031 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2032 | /// qualifier? |
2033 | /// |
2034 | /// This approximates the answer to the following question: if this |
2035 | /// translation unit were compiled in ARC, would this type be qualified |
2036 | /// with __unsafe_unretained? |
2037 | bool isObjCInertUnsafeUnretainedType() const { |
2038 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2039 | } |
2040 | |
2041 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2042 | /// object type, e.g., __kindof NSView * or __kindof id |
2043 | /// <NSCopying>. |
2044 | /// |
2045 | /// \param bound Will be set to the bound on non-id subtype types, |
2046 | /// which will be (possibly specialized) Objective-C class type, or |
2047 | /// null for 'id. |
2048 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2049 | const ObjCObjectType *&bound) const; |
2050 | |
2051 | bool isObjCClassType() const; // Class |
2052 | |
2053 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2054 | /// Class type, e.g., __kindof Class <NSCopying>. |
2055 | /// |
2056 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2057 | /// here because Objective-C's type system cannot express "a class |
2058 | /// object for a subclass of NSFoo". |
2059 | bool isObjCClassOrClassKindOfType() const; |
2060 | |
2061 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2062 | bool isObjCSelType() const; // Class |
2063 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2064 | bool isObjCARCBridgableType() const; |
2065 | bool isCARCBridgableType() const; |
2066 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2067 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2068 | bool isNothrowT() const; // C++ std::nothrow_t |
2069 | bool isAlignValT() const; // C++17 std::align_val_t |
2070 | bool isStdByteType() const; // C++17 std::byte |
2071 | bool isAtomicType() const; // C11 _Atomic() |
2072 | |
2073 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2074 | bool is##Id##Type() const; |
2075 | #include "clang/Basic/OpenCLImageTypes.def" |
2076 | |
2077 | bool isImageType() const; // Any OpenCL image type |
2078 | |
2079 | bool isSamplerT() const; // OpenCL sampler_t |
2080 | bool isEventT() const; // OpenCL event_t |
2081 | bool isClkEventT() const; // OpenCL clk_event_t |
2082 | bool isQueueT() const; // OpenCL queue_t |
2083 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2084 | |
2085 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2086 | bool is##Id##Type() const; |
2087 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2088 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2089 | bool isOCLIntelSubgroupAVCType() const; |
2090 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2091 | |
2092 | bool isPipeType() const; // OpenCL pipe type |
2093 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2094 | |
2095 | /// Determines if this type, which must satisfy |
2096 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2097 | /// than implicitly __strong. |
2098 | bool isObjCARCImplicitlyUnretainedType() const; |
2099 | |
2100 | /// Return the implicit lifetime for this type, which must not be dependent. |
2101 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2102 | |
2103 | enum ScalarTypeKind { |
2104 | STK_CPointer, |
2105 | STK_BlockPointer, |
2106 | STK_ObjCObjectPointer, |
2107 | STK_MemberPointer, |
2108 | STK_Bool, |
2109 | STK_Integral, |
2110 | STK_Floating, |
2111 | STK_IntegralComplex, |
2112 | STK_FloatingComplex, |
2113 | STK_FixedPoint |
2114 | }; |
2115 | |
2116 | /// Given that this is a scalar type, classify it. |
2117 | ScalarTypeKind getScalarTypeKind() const; |
2118 | |
2119 | /// Whether this type is a dependent type, meaning that its definition |
2120 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2121 | bool isDependentType() const { return TypeBits.Dependent; } |
2122 | |
2123 | /// Determine whether this type is an instantiation-dependent type, |
2124 | /// meaning that the type involves a template parameter (even if the |
2125 | /// definition does not actually depend on the type substituted for that |
2126 | /// template parameter). |
2127 | bool isInstantiationDependentType() const { |
2128 | return TypeBits.InstantiationDependent; |
2129 | } |
2130 | |
2131 | /// Determine whether this type is an undeduced type, meaning that |
2132 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2133 | /// deduced. |
2134 | bool isUndeducedType() const; |
2135 | |
2136 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2137 | bool isVariablyModifiedType() const { return TypeBits.VariablyModified; } |
2138 | |
2139 | /// Whether this type involves a variable-length array type |
2140 | /// with a definite size. |
2141 | bool hasSizedVLAType() const; |
2142 | |
2143 | /// Whether this type is or contains a local or unnamed type. |
2144 | bool hasUnnamedOrLocalType() const; |
2145 | |
2146 | bool isOverloadableType() const; |
2147 | |
2148 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2149 | bool isElaboratedTypeSpecifier() const; |
2150 | |
2151 | bool canDecayToPointerType() const; |
2152 | |
2153 | /// Whether this type is represented natively as a pointer. This includes |
2154 | /// pointers, references, block pointers, and Objective-C interface, |
2155 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2156 | bool hasPointerRepresentation() const; |
2157 | |
2158 | /// Whether this type can represent an objective pointer type for the |
2159 | /// purpose of GC'ability |
2160 | bool hasObjCPointerRepresentation() const; |
2161 | |
2162 | /// Determine whether this type has an integer representation |
2163 | /// of some sort, e.g., it is an integer type or a vector. |
2164 | bool hasIntegerRepresentation() const; |
2165 | |
2166 | /// Determine whether this type has an signed integer representation |
2167 | /// of some sort, e.g., it is an signed integer type or a vector. |
2168 | bool hasSignedIntegerRepresentation() const; |
2169 | |
2170 | /// Determine whether this type has an unsigned integer representation |
2171 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2172 | bool hasUnsignedIntegerRepresentation() const; |
2173 | |
2174 | /// Determine whether this type has a floating-point representation |
2175 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2176 | bool hasFloatingRepresentation() const; |
2177 | |
2178 | // Type Checking Functions: Check to see if this type is structurally the |
2179 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2180 | // the best type we can. |
2181 | const RecordType *getAsStructureType() const; |
2182 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2183 | const RecordType *getAsUnionType() const; |
2184 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2185 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2186 | |
2187 | // The following is a convenience method that returns an ObjCObjectPointerType |
2188 | // for object declared using an interface. |
2189 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2190 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2191 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2192 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2193 | |
2194 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2195 | /// because the type is a RecordType or because it is the injected-class-name |
2196 | /// type of a class template or class template partial specialization. |
2197 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2198 | |
2199 | /// Retrieves the RecordDecl this type refers to. |
2200 | RecordDecl *getAsRecordDecl() const; |
2201 | |
2202 | /// Retrieves the TagDecl that this type refers to, either |
2203 | /// because the type is a TagType or because it is the injected-class-name |
2204 | /// type of a class template or class template partial specialization. |
2205 | TagDecl *getAsTagDecl() const; |
2206 | |
2207 | /// If this is a pointer or reference to a RecordType, return the |
2208 | /// CXXRecordDecl that the type refers to. |
2209 | /// |
2210 | /// If this is not a pointer or reference, or the type being pointed to does |
2211 | /// not refer to a CXXRecordDecl, returns NULL. |
2212 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2213 | |
2214 | /// Get the DeducedType whose type will be deduced for a variable with |
2215 | /// an initializer of this type. This looks through declarators like pointer |
2216 | /// types, but not through decltype or typedefs. |
2217 | DeducedType *getContainedDeducedType() const; |
2218 | |
2219 | /// Get the AutoType whose type will be deduced for a variable with |
2220 | /// an initializer of this type. This looks through declarators like pointer |
2221 | /// types, but not through decltype or typedefs. |
2222 | AutoType *getContainedAutoType() const { |
2223 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2224 | } |
2225 | |
2226 | /// Determine whether this type was written with a leading 'auto' |
2227 | /// corresponding to a trailing return type (possibly for a nested |
2228 | /// function type within a pointer to function type or similar). |
2229 | bool hasAutoForTrailingReturnType() const; |
2230 | |
2231 | /// Member-template getAs<specific type>'. Look through sugar for |
2232 | /// an instance of \<specific type>. This scheme will eventually |
2233 | /// replace the specific getAsXXXX methods above. |
2234 | /// |
2235 | /// There are some specializations of this member template listed |
2236 | /// immediately following this class. |
2237 | template <typename T> const T *getAs() const; |
2238 | |
2239 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2240 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2241 | /// This is used when you need to walk over sugar nodes that represent some |
2242 | /// kind of type adjustment from a type that was written as a \<specific type> |
2243 | /// to another type that is still canonically a \<specific type>. |
2244 | template <typename T> const T *getAsAdjusted() const; |
2245 | |
2246 | /// A variant of getAs<> for array types which silently discards |
2247 | /// qualifiers from the outermost type. |
2248 | const ArrayType *getAsArrayTypeUnsafe() const; |
2249 | |
2250 | /// Member-template castAs<specific type>. Look through sugar for |
2251 | /// the underlying instance of \<specific type>. |
2252 | /// |
2253 | /// This method has the same relationship to getAs<T> as cast<T> has |
2254 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2255 | /// have the intended type, and this method will never return null. |
2256 | template <typename T> const T *castAs() const; |
2257 | |
2258 | /// A variant of castAs<> for array type which silently discards |
2259 | /// qualifiers from the outermost type. |
2260 | const ArrayType *castAsArrayTypeUnsafe() const; |
2261 | |
2262 | /// Determine whether this type had the specified attribute applied to it |
2263 | /// (looking through top-level type sugar). |
2264 | bool hasAttr(attr::Kind AK) const; |
2265 | |
2266 | /// Get the base element type of this type, potentially discarding type |
2267 | /// qualifiers. This should never be used when type qualifiers |
2268 | /// are meaningful. |
2269 | const Type *getBaseElementTypeUnsafe() const; |
2270 | |
2271 | /// If this is an array type, return the element type of the array, |
2272 | /// potentially with type qualifiers missing. |
2273 | /// This should never be used when type qualifiers are meaningful. |
2274 | const Type *getArrayElementTypeNoTypeQual() const; |
2275 | |
2276 | /// If this is a pointer type, return the pointee type. |
2277 | /// If this is an array type, return the array element type. |
2278 | /// This should never be used when type qualifiers are meaningful. |
2279 | const Type *getPointeeOrArrayElementType() const; |
2280 | |
2281 | /// If this is a pointer, ObjC object pointer, or block |
2282 | /// pointer, this returns the respective pointee. |
2283 | QualType getPointeeType() const; |
2284 | |
2285 | /// Return the specified type with any "sugar" removed from the type, |
2286 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2287 | const Type *getUnqualifiedDesugaredType() const; |
2288 | |
2289 | /// More type predicates useful for type checking/promotion |
2290 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2291 | |
2292 | /// Return true if this is an integer type that is |
2293 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2294 | /// or an enum decl which has a signed representation. |
2295 | bool isSignedIntegerType() const; |
2296 | |
2297 | /// Return true if this is an integer type that is |
2298 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2299 | /// or an enum decl which has an unsigned representation. |
2300 | bool isUnsignedIntegerType() const; |
2301 | |
2302 | /// Determines whether this is an integer type that is signed or an |
2303 | /// enumeration types whose underlying type is a signed integer type. |
2304 | bool isSignedIntegerOrEnumerationType() const; |
2305 | |
2306 | /// Determines whether this is an integer type that is unsigned or an |
2307 | /// enumeration types whose underlying type is a unsigned integer type. |
2308 | bool isUnsignedIntegerOrEnumerationType() const; |
2309 | |
2310 | /// Return true if this is a fixed point type according to |
2311 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2312 | bool isFixedPointType() const; |
2313 | |
2314 | /// Return true if this is a fixed point or integer type. |
2315 | bool isFixedPointOrIntegerType() const; |
2316 | |
2317 | /// Return true if this is a saturated fixed point type according to |
2318 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2319 | bool isSaturatedFixedPointType() const; |
2320 | |
2321 | /// Return true if this is a saturated fixed point type according to |
2322 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2323 | bool isUnsaturatedFixedPointType() const; |
2324 | |
2325 | /// Return true if this is a fixed point type that is signed according |
2326 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2327 | bool isSignedFixedPointType() const; |
2328 | |
2329 | /// Return true if this is a fixed point type that is unsigned according |
2330 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2331 | bool isUnsignedFixedPointType() const; |
2332 | |
2333 | /// Return true if this is not a variable sized type, |
2334 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2335 | /// incomplete types. |
2336 | bool isConstantSizeType() const; |
2337 | |
2338 | /// Returns true if this type can be represented by some |
2339 | /// set of type specifiers. |
2340 | bool isSpecifierType() const; |
2341 | |
2342 | /// Determine the linkage of this type. |
2343 | Linkage getLinkage() const; |
2344 | |
2345 | /// Determine the visibility of this type. |
2346 | Visibility getVisibility() const { |
2347 | return getLinkageAndVisibility().getVisibility(); |
2348 | } |
2349 | |
2350 | /// Return true if the visibility was explicitly set is the code. |
2351 | bool isVisibilityExplicit() const { |
2352 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2353 | } |
2354 | |
2355 | /// Determine the linkage and visibility of this type. |
2356 | LinkageInfo getLinkageAndVisibility() const; |
2357 | |
2358 | /// True if the computed linkage is valid. Used for consistency |
2359 | /// checking. Should always return true. |
2360 | bool isLinkageValid() const; |
2361 | |
2362 | /// Determine the nullability of the given type. |
2363 | /// |
2364 | /// Note that nullability is only captured as sugar within the type |
2365 | /// system, not as part of the canonical type, so nullability will |
2366 | /// be lost by canonicalization and desugaring. |
2367 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2368 | |
2369 | /// Determine whether the given type can have a nullability |
2370 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2371 | /// |
2372 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2373 | /// this type can have nullability because it is dependent. |
2374 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2375 | |
2376 | /// Retrieve the set of substitutions required when accessing a member |
2377 | /// of the Objective-C receiver type that is declared in the given context. |
2378 | /// |
2379 | /// \c *this is the type of the object we're operating on, e.g., the |
2380 | /// receiver for a message send or the base of a property access, and is |
2381 | /// expected to be of some object or object pointer type. |
2382 | /// |
2383 | /// \param dc The declaration context for which we are building up a |
2384 | /// substitution mapping, which should be an Objective-C class, extension, |
2385 | /// category, or method within. |
2386 | /// |
2387 | /// \returns an array of type arguments that can be substituted for |
2388 | /// the type parameters of the given declaration context in any type described |
2389 | /// within that context, or an empty optional to indicate that no |
2390 | /// substitution is required. |
2391 | Optional<ArrayRef<QualType>> |
2392 | getObjCSubstitutions(const DeclContext *dc) const; |
2393 | |
2394 | /// Determines if this is an ObjC interface type that may accept type |
2395 | /// parameters. |
2396 | bool acceptsObjCTypeParams() const; |
2397 | |
2398 | const char *getTypeClassName() const; |
2399 | |
2400 | QualType getCanonicalTypeInternal() const { |
2401 | return CanonicalType; |
2402 | } |
2403 | |
2404 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2405 | void dump() const; |
2406 | void dump(llvm::raw_ostream &OS) const; |
2407 | }; |
2408 | |
2409 | /// This will check for a TypedefType by removing any existing sugar |
2410 | /// until it reaches a TypedefType or a non-sugared type. |
2411 | template <> const TypedefType *Type::getAs() const; |
2412 | |
2413 | /// This will check for a TemplateSpecializationType by removing any |
2414 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2415 | /// non-sugared type. |
2416 | template <> const TemplateSpecializationType *Type::getAs() const; |
2417 | |
2418 | /// This will check for an AttributedType by removing any existing sugar |
2419 | /// until it reaches an AttributedType or a non-sugared type. |
2420 | template <> const AttributedType *Type::getAs() const; |
2421 | |
2422 | // We can do canonical leaf types faster, because we don't have to |
2423 | // worry about preserving child type decoration. |
2424 | #define TYPE(Class, Base) |
2425 | #define LEAF_TYPE(Class) \ |
2426 | template <> inline const Class##Type *Type::getAs() const { \ |
2427 | return dyn_cast<Class##Type>(CanonicalType); \ |
2428 | } \ |
2429 | template <> inline const Class##Type *Type::castAs() const { \ |
2430 | return cast<Class##Type>(CanonicalType); \ |
2431 | } |
2432 | #include "clang/AST/TypeNodes.inc" |
2433 | |
2434 | /// This class is used for builtin types like 'int'. Builtin |
2435 | /// types are always canonical and have a literal name field. |
2436 | class BuiltinType : public Type { |
2437 | public: |
2438 | enum Kind { |
2439 | // OpenCL image types |
2440 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2441 | #include "clang/Basic/OpenCLImageTypes.def" |
2442 | // OpenCL extension types |
2443 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2444 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2445 | // SVE Types |
2446 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2447 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2448 | // All other builtin types |
2449 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2450 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2451 | #include "clang/AST/BuiltinTypes.def" |
2452 | }; |
2453 | |
2454 | private: |
2455 | friend class ASTContext; // ASTContext creates these. |
2456 | |
2457 | BuiltinType(Kind K) |
2458 | : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent), |
2459 | /*InstantiationDependent=*/(K == Dependent), |
2460 | /*VariablyModified=*/false, |
2461 | /*Unexpanded parameter pack=*/false) { |
2462 | BuiltinTypeBits.Kind = K; |
2463 | } |
2464 | |
2465 | public: |
2466 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2467 | StringRef getName(const PrintingPolicy &Policy) const; |
2468 | |
2469 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2470 | // The StringRef is null-terminated. |
2471 | StringRef str = getName(Policy); |
2472 | 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~svn374877/tools/clang/include/clang/AST/Type.h" , 2472, __PRETTY_FUNCTION__)); |
2473 | return str.data(); |
2474 | } |
2475 | |
2476 | bool isSugared() const { return false; } |
2477 | QualType desugar() const { return QualType(this, 0); } |
2478 | |
2479 | bool isInteger() const { |
2480 | return getKind() >= Bool && getKind() <= Int128; |
2481 | } |
2482 | |
2483 | bool isSignedInteger() const { |
2484 | return getKind() >= Char_S && getKind() <= Int128; |
2485 | } |
2486 | |
2487 | bool isUnsignedInteger() const { |
2488 | return getKind() >= Bool && getKind() <= UInt128; |
2489 | } |
2490 | |
2491 | bool isFloatingPoint() const { |
2492 | return getKind() >= Half && getKind() <= Float128; |
2493 | } |
2494 | |
2495 | /// Determines whether the given kind corresponds to a placeholder type. |
2496 | static bool isPlaceholderTypeKind(Kind K) { |
2497 | return K >= Overload; |
2498 | } |
2499 | |
2500 | /// Determines whether this type is a placeholder type, i.e. a type |
2501 | /// which cannot appear in arbitrary positions in a fully-formed |
2502 | /// expression. |
2503 | bool isPlaceholderType() const { |
2504 | return isPlaceholderTypeKind(getKind()); |
2505 | } |
2506 | |
2507 | /// Determines whether this type is a placeholder type other than |
2508 | /// Overload. Most placeholder types require only syntactic |
2509 | /// information about their context in order to be resolved (e.g. |
2510 | /// whether it is a call expression), which means they can (and |
2511 | /// should) be resolved in an earlier "phase" of analysis. |
2512 | /// Overload expressions sometimes pick up further information |
2513 | /// from their context, like whether the context expects a |
2514 | /// specific function-pointer type, and so frequently need |
2515 | /// special treatment. |
2516 | bool isNonOverloadPlaceholderType() const { |
2517 | return getKind() > Overload; |
2518 | } |
2519 | |
2520 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2521 | }; |
2522 | |
2523 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2524 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2525 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2526 | friend class ASTContext; // ASTContext creates these. |
2527 | |
2528 | QualType ElementType; |
2529 | |
2530 | ComplexType(QualType Element, QualType CanonicalPtr) |
2531 | : Type(Complex, CanonicalPtr, Element->isDependentType(), |
2532 | Element->isInstantiationDependentType(), |
2533 | Element->isVariablyModifiedType(), |
2534 | Element->containsUnexpandedParameterPack()), |
2535 | ElementType(Element) {} |
2536 | |
2537 | public: |
2538 | QualType getElementType() const { return ElementType; } |
2539 | |
2540 | bool isSugared() const { return false; } |
2541 | QualType desugar() const { return QualType(this, 0); } |
2542 | |
2543 | void Profile(llvm::FoldingSetNodeID &ID) { |
2544 | Profile(ID, getElementType()); |
2545 | } |
2546 | |
2547 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2548 | ID.AddPointer(Element.getAsOpaquePtr()); |
2549 | } |
2550 | |
2551 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2552 | }; |
2553 | |
2554 | /// Sugar for parentheses used when specifying types. |
2555 | class ParenType : public Type, public llvm::FoldingSetNode { |
2556 | friend class ASTContext; // ASTContext creates these. |
2557 | |
2558 | QualType Inner; |
2559 | |
2560 | ParenType(QualType InnerType, QualType CanonType) |
2561 | : Type(Paren, CanonType, InnerType->isDependentType(), |
2562 | InnerType->isInstantiationDependentType(), |
2563 | InnerType->isVariablyModifiedType(), |
2564 | InnerType->containsUnexpandedParameterPack()), |
2565 | Inner(InnerType) {} |
2566 | |
2567 | public: |
2568 | QualType getInnerType() const { return Inner; } |
2569 | |
2570 | bool isSugared() const { return true; } |
2571 | QualType desugar() const { return getInnerType(); } |
2572 | |
2573 | void Profile(llvm::FoldingSetNodeID &ID) { |
2574 | Profile(ID, getInnerType()); |
2575 | } |
2576 | |
2577 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2578 | Inner.Profile(ID); |
2579 | } |
2580 | |
2581 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2582 | }; |
2583 | |
2584 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2585 | class PointerType : public Type, public llvm::FoldingSetNode { |
2586 | friend class ASTContext; // ASTContext creates these. |
2587 | |
2588 | QualType PointeeType; |
2589 | |
2590 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2591 | : Type(Pointer, CanonicalPtr, Pointee->isDependentType(), |
2592 | Pointee->isInstantiationDependentType(), |
2593 | Pointee->isVariablyModifiedType(), |
2594 | Pointee->containsUnexpandedParameterPack()), |
2595 | PointeeType(Pointee) {} |
2596 | |
2597 | public: |
2598 | QualType getPointeeType() const { return PointeeType; } |
2599 | |
2600 | /// Returns true if address spaces of pointers overlap. |
2601 | /// OpenCL v2.0 defines conversion rules for pointers to different |
2602 | /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping |
2603 | /// address spaces. |
2604 | /// CL1.1 or CL1.2: |
2605 | /// address spaces overlap iff they are they same. |
2606 | /// CL2.0 adds: |
2607 | /// __generic overlaps with any address space except for __constant. |
2608 | bool isAddressSpaceOverlapping(const PointerType &other) const { |
2609 | Qualifiers thisQuals = PointeeType.getQualifiers(); |
2610 | Qualifiers otherQuals = other.getPointeeType().getQualifiers(); |
2611 | // Address spaces overlap if at least one of them is a superset of another |
2612 | return thisQuals.isAddressSpaceSupersetOf(otherQuals) || |
2613 | otherQuals.isAddressSpaceSupersetOf(thisQuals); |
2614 | } |
2615 | |
2616 | bool isSugared() const { return false; } |
2617 | QualType desugar() const { return QualType(this, 0); } |
2618 | |
2619 | void Profile(llvm::FoldingSetNodeID &ID) { |
2620 | Profile(ID, getPointeeType()); |
2621 | } |
2622 | |
2623 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2624 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2625 | } |
2626 | |
2627 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2628 | }; |
2629 | |
2630 | /// Represents a type which was implicitly adjusted by the semantic |
2631 | /// engine for arbitrary reasons. For example, array and function types can |
2632 | /// decay, and function types can have their calling conventions adjusted. |
2633 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2634 | QualType OriginalTy; |
2635 | QualType AdjustedTy; |
2636 | |
2637 | protected: |
2638 | friend class ASTContext; // ASTContext creates these. |
2639 | |
2640 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2641 | QualType CanonicalPtr) |
2642 | : Type(TC, CanonicalPtr, OriginalTy->isDependentType(), |
2643 | OriginalTy->isInstantiationDependentType(), |
2644 | OriginalTy->isVariablyModifiedType(), |
2645 | OriginalTy->containsUnexpandedParameterPack()), |
2646 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2647 | |
2648 | public: |
2649 | QualType getOriginalType() const { return OriginalTy; } |
2650 | QualType getAdjustedType() const { return AdjustedTy; } |
2651 | |
2652 | bool isSugared() const { return true; } |
2653 | QualType desugar() const { return AdjustedTy; } |
2654 | |
2655 | void Profile(llvm::FoldingSetNodeID &ID) { |
2656 | Profile(ID, OriginalTy, AdjustedTy); |
2657 | } |
2658 | |
2659 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2660 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2661 | ID.AddPointer(New.getAsOpaquePtr()); |
2662 | } |
2663 | |
2664 | static bool classof(const Type *T) { |
2665 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2666 | } |
2667 | }; |
2668 | |
2669 | /// Represents a pointer type decayed from an array or function type. |
2670 | class DecayedType : public AdjustedType { |
2671 | friend class ASTContext; // ASTContext creates these. |
2672 | |
2673 | inline |
2674 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2675 | |
2676 | public: |
2677 | QualType getDecayedType() const { return getAdjustedType(); } |
2678 | |
2679 | inline QualType getPointeeType() const; |
2680 | |
2681 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2682 | }; |
2683 | |
2684 | /// Pointer to a block type. |
2685 | /// This type is to represent types syntactically represented as |
2686 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2687 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2688 | friend class ASTContext; // ASTContext creates these. |
2689 | |
2690 | // Block is some kind of pointer type |
2691 | QualType PointeeType; |
2692 | |
2693 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2694 | : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(), |
2695 | Pointee->isInstantiationDependentType(), |
2696 | Pointee->isVariablyModifiedType(), |
2697 | Pointee->containsUnexpandedParameterPack()), |
2698 | PointeeType(Pointee) {} |
2699 | |
2700 | public: |
2701 | // Get the pointee type. Pointee is required to always be a function type. |
2702 | QualType getPointeeType() const { return PointeeType; } |
2703 | |
2704 | bool isSugared() const { return false; } |
2705 | QualType desugar() const { return QualType(this, 0); } |
2706 | |
2707 | void Profile(llvm::FoldingSetNodeID &ID) { |
2708 | Profile(ID, getPointeeType()); |
2709 | } |
2710 | |
2711 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2712 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2713 | } |
2714 | |
2715 | static bool classof(const Type *T) { |
2716 | return T->getTypeClass() == BlockPointer; |
2717 | } |
2718 | }; |
2719 | |
2720 | /// Base for LValueReferenceType and RValueReferenceType |
2721 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2722 | QualType PointeeType; |
2723 | |
2724 | protected: |
2725 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2726 | bool SpelledAsLValue) |
2727 | : Type(tc, CanonicalRef, Referencee->isDependentType(), |
2728 | Referencee->isInstantiationDependentType(), |
2729 | Referencee->isVariablyModifiedType(), |
2730 | Referencee->containsUnexpandedParameterPack()), |
2731 | PointeeType(Referencee) { |
2732 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2733 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2734 | } |
2735 | |
2736 | public: |
2737 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2738 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2739 | |
2740 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2741 | |
2742 | QualType getPointeeType() const { |
2743 | // FIXME: this might strip inner qualifiers; okay? |
2744 | const ReferenceType *T = this; |
2745 | while (T->isInnerRef()) |
2746 | T = T->PointeeType->castAs<ReferenceType>(); |
2747 | return T->PointeeType; |
2748 | } |
2749 | |
2750 | void Profile(llvm::FoldingSetNodeID &ID) { |
2751 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2752 | } |
2753 | |
2754 | static void Profile(llvm::FoldingSetNodeID &ID, |
2755 | QualType Referencee, |
2756 | bool SpelledAsLValue) { |
2757 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2758 | ID.AddBoolean(SpelledAsLValue); |
2759 | } |
2760 | |
2761 | static bool classof(const Type *T) { |
2762 | return T->getTypeClass() == LValueReference || |
2763 | T->getTypeClass() == RValueReference; |
2764 | } |
2765 | }; |
2766 | |
2767 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2768 | class LValueReferenceType : public ReferenceType { |
2769 | friend class ASTContext; // ASTContext creates these |
2770 | |
2771 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2772 | bool SpelledAsLValue) |
2773 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2774 | SpelledAsLValue) {} |
2775 | |
2776 | public: |
2777 | bool isSugared() const { return false; } |
2778 | QualType desugar() const { return QualType(this, 0); } |
2779 | |
2780 | static bool classof(const Type *T) { |
2781 | return T->getTypeClass() == LValueReference; |
2782 | } |
2783 | }; |
2784 | |
2785 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2786 | class RValueReferenceType : public ReferenceType { |
2787 | friend class ASTContext; // ASTContext creates these |
2788 | |
2789 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2790 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2791 | |
2792 | public: |
2793 | bool isSugared() const { return false; } |
2794 | QualType desugar() const { return QualType(this, 0); } |
2795 | |
2796 | static bool classof(const Type *T) { |
2797 | return T->getTypeClass() == RValueReference; |
2798 | } |
2799 | }; |
2800 | |
2801 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2802 | /// |
2803 | /// This includes both pointers to data members and pointer to member functions. |
2804 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2805 | friend class ASTContext; // ASTContext creates these. |
2806 | |
2807 | QualType PointeeType; |
2808 | |
2809 | /// The class of which the pointee is a member. Must ultimately be a |
2810 | /// RecordType, but could be a typedef or a template parameter too. |
2811 | const Type *Class; |
2812 | |
2813 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2814 | : Type(MemberPointer, CanonicalPtr, |
2815 | Cls->isDependentType() || Pointee->isDependentType(), |
2816 | (Cls->isInstantiationDependentType() || |
2817 | Pointee->isInstantiationDependentType()), |
2818 | Pointee->isVariablyModifiedType(), |
2819 | (Cls->containsUnexpandedParameterPack() || |
2820 | Pointee->containsUnexpandedParameterPack())), |
2821 | PointeeType(Pointee), Class(Cls) {} |
2822 | |
2823 | public: |
2824 | QualType getPointeeType() const { return PointeeType; } |
2825 | |
2826 | /// Returns true if the member type (i.e. the pointee type) is a |
2827 | /// function type rather than a data-member type. |
2828 | bool isMemberFunctionPointer() const { |
2829 | return PointeeType->isFunctionProtoType(); |
2830 | } |
2831 | |
2832 | /// Returns true if the member type (i.e. the pointee type) is a |
2833 | /// data type rather than a function type. |
2834 | bool isMemberDataPointer() const { |
2835 | return !PointeeType->isFunctionProtoType(); |
2836 | } |
2837 | |
2838 | const Type *getClass() const { return Class; } |
2839 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2840 | |
2841 | bool isSugared() const { return false; } |
2842 | QualType desugar() const { return QualType(this, 0); } |
2843 | |
2844 | void Profile(llvm::FoldingSetNodeID &ID) { |
2845 | Profile(ID, getPointeeType(), getClass()); |
2846 | } |
2847 | |
2848 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2849 | const Type *Class) { |
2850 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2851 | ID.AddPointer(Class); |
2852 | } |
2853 | |
2854 | static bool classof(const Type *T) { |
2855 | return T->getTypeClass() == MemberPointer; |
2856 | } |
2857 | }; |
2858 | |
2859 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2860 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2861 | public: |
2862 | /// Capture whether this is a normal array (e.g. int X[4]) |
2863 | /// an array with a static size (e.g. int X[static 4]), or an array |
2864 | /// with a star size (e.g. int X[*]). |
2865 | /// 'static' is only allowed on function parameters. |
2866 | enum ArraySizeModifier { |
2867 | Normal, Static, Star |
2868 | }; |
2869 | |
2870 | private: |
2871 | /// The element type of the array. |
2872 | QualType ElementType; |
2873 | |
2874 | protected: |
2875 | friend class ASTContext; // ASTContext creates these. |
2876 | |
2877 | ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, |
2878 | unsigned tq, const Expr *sz = nullptr); |
2879 | |
2880 | public: |
2881 | QualType getElementType() const { return ElementType; } |
2882 | |
2883 | ArraySizeModifier getSizeModifier() const { |
2884 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2885 | } |
2886 | |
2887 | Qualifiers getIndexTypeQualifiers() const { |
2888 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2889 | } |
2890 | |
2891 | unsigned getIndexTypeCVRQualifiers() const { |
2892 | return ArrayTypeBits.IndexTypeQuals; |
2893 | } |
2894 | |
2895 | static bool classof(const Type *T) { |
2896 | return T->getTypeClass() == ConstantArray || |
2897 | T->getTypeClass() == VariableArray || |
2898 | T->getTypeClass() == IncompleteArray || |
2899 | T->getTypeClass() == DependentSizedArray; |
2900 | } |
2901 | }; |
2902 | |
2903 | /// Represents the canonical version of C arrays with a specified constant size. |
2904 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2905 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2906 | class ConstantArrayType final |
2907 | : public ArrayType, |
2908 | private llvm::TrailingObjects<ConstantArrayType, const Expr *> { |
2909 | friend class ASTContext; // ASTContext creates these. |
2910 | friend TrailingObjects; |
2911 | |
2912 | llvm::APInt Size; // Allows us to unique the type. |
2913 | |
2914 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2915 | const Expr *sz, ArraySizeModifier sm, unsigned tq) |
2916 | : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) { |
2917 | ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr; |
2918 | if (ConstantArrayTypeBits.HasStoredSizeExpr) { |
2919 | assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size" ) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\"" , "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Type.h" , 2919, __PRETTY_FUNCTION__)); |
2920 | *getTrailingObjects<const Expr*>() = sz; |
2921 | } |
2922 | } |
2923 | |
2924 | unsigned numTrailingObjects(OverloadToken<const Expr*>) const { |
2925 | return ConstantArrayTypeBits.HasStoredSizeExpr; |
2926 | } |
2927 | |
2928 | public: |
2929 | const llvm::APInt &getSize() const { return Size; } |
2930 | const Expr *getSizeExpr() const { |
2931 | return ConstantArrayTypeBits.HasStoredSizeExpr |
2932 | ? *getTrailingObjects<const Expr *>() |
2933 | : nullptr; |
2934 | } |
2935 | bool isSugared() const { return false; } |
2936 | QualType desugar() const { return QualType(this, 0); } |
2937 | |
2938 | /// Determine the number of bits required to address a member of |
2939 | // an array with the given element type and number of elements. |
2940 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2941 | QualType ElementType, |
2942 | const llvm::APInt &NumElements); |
2943 | |
2944 | /// Determine the maximum number of active bits that an array's size |
2945 | /// can require, which limits the maximum size of the array. |
2946 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2947 | |
2948 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
2949 | Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(), |
2950 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2951 | } |
2952 | |
2953 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx, |
2954 | QualType ET, const llvm::APInt &ArraySize, |
2955 | const Expr *SizeExpr, ArraySizeModifier SizeMod, |
2956 | unsigned TypeQuals); |
2957 | |
2958 | static bool classof(const Type *T) { |
2959 | return T->getTypeClass() == ConstantArray; |
2960 | } |
2961 | }; |
2962 | |
2963 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2964 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2965 | /// unspecified. |
2966 | class IncompleteArrayType : public ArrayType { |
2967 | friend class ASTContext; // ASTContext creates these. |
2968 | |
2969 | IncompleteArrayType(QualType et, QualType can, |
2970 | ArraySizeModifier sm, unsigned tq) |
2971 | : ArrayType(IncompleteArray, et, can, sm, tq) {} |
2972 | |
2973 | public: |
2974 | friend class StmtIteratorBase; |
2975 | |
2976 | bool isSugared() const { return false; } |
2977 | QualType desugar() const { return QualType(this, 0); } |
2978 | |
2979 | static bool classof(const Type *T) { |
2980 | return T->getTypeClass() == IncompleteArray; |
2981 | } |
2982 | |
2983 | void Profile(llvm::FoldingSetNodeID &ID) { |
2984 | Profile(ID, getElementType(), getSizeModifier(), |
2985 | getIndexTypeCVRQualifiers()); |
2986 | } |
2987 | |
2988 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2989 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
2990 | ID.AddPointer(ET.getAsOpaquePtr()); |
2991 | ID.AddInteger(SizeMod); |
2992 | ID.AddInteger(TypeQuals); |
2993 | } |
2994 | }; |
2995 | |
2996 | /// Represents a C array with a specified size that is not an |
2997 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
2998 | /// Since the size expression is an arbitrary expression, we store it as such. |
2999 | /// |
3000 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
3001 | /// should not be: two lexically equivalent variable array types could mean |
3002 | /// different things, for example, these variables do not have the same type |
3003 | /// dynamically: |
3004 | /// |
3005 | /// void foo(int x) { |
3006 | /// int Y[x]; |
3007 | /// ++x; |
3008 | /// int Z[x]; |
3009 | /// } |
3010 | class VariableArrayType : public ArrayType { |
3011 | friend class ASTContext; // ASTContext creates these. |
3012 | |
3013 | /// An assignment-expression. VLA's are only permitted within |
3014 | /// a function block. |
3015 | Stmt *SizeExpr; |
3016 | |
3017 | /// The range spanned by the left and right array brackets. |
3018 | SourceRange Brackets; |
3019 | |
3020 | VariableArrayType(QualType et, QualType can, Expr *e, |
3021 | ArraySizeModifier sm, unsigned tq, |
3022 | SourceRange brackets) |
3023 | : ArrayType(VariableArray, et, can, sm, tq, e), |
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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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; |
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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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 |