Bug Summary

File:tools/clang/lib/Sema/SemaExprCXX.cpp
Warning:line 706, column 7
Potential leak of memory pointed to by field 'DiagStorage'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExprCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325118/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-14-150435-17243-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp

/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp

1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief Implements semantic analysis for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
14
15#include "clang/Sema/SemaInternal.h"
16#include "TreeTransform.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/CharUnits.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/RecursiveASTVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/AlignedAllocation.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
37#include "clang/Sema/SemaLambda.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "llvm/ADT/APInt.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/Support/ErrorHandling.h"
42using namespace clang;
43using namespace sema;
44
45/// \brief Handle the result of the special case name lookup for inheriting
46/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47/// constructor names in member using declarations, even if 'X' is not the
48/// name of the corresponding type.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name")(static_cast <bool> (NNS->getAsIdentifier() == &
Name && "not a constructor name") ? void (0) : __assert_fail
("NNS->getAsIdentifier() == &Name && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 65, __extension__ __PRETTY_FUNCTION__))
;
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
71 case NestedNameSpecifier::Super:
72 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 74)
;
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
83ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
84 IdentifierInfo &II,
85 SourceLocation NameLoc,
86 Scope *S, CXXScopeSpec &SS,
87 ParsedType ObjectTypePtr,
88 bool EnteringContext) {
89 // Determine where to perform name lookup.
90
91 // FIXME: This area of the standard is very messy, and the current
92 // wording is rather unclear about which scopes we search for the
93 // destructor name; see core issues 399 and 555. Issue 399 in
94 // particular shows where the current description of destructor name
95 // lookup is completely out of line with existing practice, e.g.,
96 // this appears to be ill-formed:
97 //
98 // namespace N {
99 // template <typename T> struct S {
100 // ~S();
101 // };
102 // }
103 //
104 // void f(N::S<int>* s) {
105 // s->N::S<int>::~S();
106 // }
107 //
108 // See also PR6358 and PR6359.
109 // For this reason, we're currently only doing the C++03 version of this
110 // code; the C++0x version has to wait until we get a proper spec.
111 QualType SearchType;
112 DeclContext *LookupCtx = nullptr;
113 bool isDependent = false;
114 bool LookInScope = false;
115
116 if (SS.isInvalid())
117 return nullptr;
118
119 // If we have an object type, it's because we are in a
120 // pseudo-destructor-expression or a member access expression, and
121 // we know what type we're looking for.
122 if (ObjectTypePtr)
123 SearchType = GetTypeFromParser(ObjectTypePtr);
124
125 if (SS.isSet()) {
126 NestedNameSpecifier *NNS = SS.getScopeRep();
127
128 bool AlreadySearched = false;
129 bool LookAtPrefix = true;
130 // C++11 [basic.lookup.qual]p6:
131 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
132 // the type-names are looked up as types in the scope designated by the
133 // nested-name-specifier. Similarly, in a qualified-id of the form:
134 //
135 // nested-name-specifier[opt] class-name :: ~ class-name
136 //
137 // the second class-name is looked up in the same scope as the first.
138 //
139 // Here, we determine whether the code below is permitted to look at the
140 // prefix of the nested-name-specifier.
141 DeclContext *DC = computeDeclContext(SS, EnteringContext);
142 if (DC && DC->isFileContext()) {
143 AlreadySearched = true;
144 LookupCtx = DC;
145 isDependent = false;
146 } else if (DC && isa<CXXRecordDecl>(DC)) {
147 LookAtPrefix = false;
148 LookInScope = true;
149 }
150
151 // The second case from the C++03 rules quoted further above.
152 NestedNameSpecifier *Prefix = nullptr;
153 if (AlreadySearched) {
154 // Nothing left to do.
155 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
156 CXXScopeSpec PrefixSS;
157 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
158 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
159 isDependent = isDependentScopeSpecifier(PrefixSS);
160 } else if (ObjectTypePtr) {
161 LookupCtx = computeDeclContext(SearchType);
162 isDependent = SearchType->isDependentType();
163 } else {
164 LookupCtx = computeDeclContext(SS, EnteringContext);
165 isDependent = LookupCtx && LookupCtx->isDependentContext();
166 }
167 } else if (ObjectTypePtr) {
168 // C++ [basic.lookup.classref]p3:
169 // If the unqualified-id is ~type-name, the type-name is looked up
170 // in the context of the entire postfix-expression. If the type T
171 // of the object expression is of a class type C, the type-name is
172 // also looked up in the scope of class C. At least one of the
173 // lookups shall find a name that refers to (possibly
174 // cv-qualified) T.
175 LookupCtx = computeDeclContext(SearchType);
176 isDependent = SearchType->isDependentType();
177 assert((isDependent || !SearchType->isIncompleteType()) &&(static_cast <bool> ((isDependent || !SearchType->isIncompleteType
()) && "Caller should have completed object type") ? void
(0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 178, __extension__ __PRETTY_FUNCTION__))
178 "Caller should have completed object type")(static_cast <bool> ((isDependent || !SearchType->isIncompleteType
()) && "Caller should have completed object type") ? void
(0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 178, __extension__ __PRETTY_FUNCTION__))
;
179
180 LookInScope = true;
181 } else {
182 // Perform lookup into the current scope (only).
183 LookInScope = true;
184 }
185
186 TypeDecl *NonMatchingTypeDecl = nullptr;
187 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
188 for (unsigned Step = 0; Step != 2; ++Step) {
189 // Look for the name first in the computed lookup context (if we
190 // have one) and, if that fails to find a match, in the scope (if
191 // we're allowed to look there).
192 Found.clear();
193 if (Step == 0 && LookupCtx) {
194 if (RequireCompleteDeclContext(SS, LookupCtx))
195 return nullptr;
196 LookupQualifiedName(Found, LookupCtx);
197 } else if (Step == 1 && LookInScope && S) {
198 LookupName(Found, S);
199 } else {
200 continue;
201 }
202
203 // FIXME: Should we be suppressing ambiguities here?
204 if (Found.isAmbiguous())
205 return nullptr;
206
207 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
208 QualType T = Context.getTypeDeclType(Type);
209 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
210
211 if (SearchType.isNull() || SearchType->isDependentType() ||
212 Context.hasSameUnqualifiedType(T, SearchType)) {
213 // We found our type!
214
215 return CreateParsedType(T,
216 Context.getTrivialTypeSourceInfo(T, NameLoc));
217 }
218
219 if (!SearchType.isNull())
220 NonMatchingTypeDecl = Type;
221 }
222
223 // If the name that we found is a class template name, and it is
224 // the same name as the template name in the last part of the
225 // nested-name-specifier (if present) or the object type, then
226 // this is the destructor for that class.
227 // FIXME: This is a workaround until we get real drafting for core
228 // issue 399, for which there isn't even an obvious direction.
229 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
230 QualType MemberOfType;
231 if (SS.isSet()) {
232 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
233 // Figure out the type of the context, if it has one.
234 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
235 MemberOfType = Context.getTypeDeclType(Record);
236 }
237 }
238 if (MemberOfType.isNull())
239 MemberOfType = SearchType;
240
241 if (MemberOfType.isNull())
242 continue;
243
244 // We're referring into a class template specialization. If the
245 // class template we found is the same as the template being
246 // specialized, we found what we are looking for.
247 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
248 if (ClassTemplateSpecializationDecl *Spec
249 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
250 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
251 Template->getCanonicalDecl())
252 return CreateParsedType(
253 MemberOfType,
254 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
255 }
256
257 continue;
258 }
259
260 // We're referring to an unresolved class template
261 // specialization. Determine whether we class template we found
262 // is the same as the template being specialized or, if we don't
263 // know which template is being specialized, that it at least
264 // has the same name.
265 if (const TemplateSpecializationType *SpecType
266 = MemberOfType->getAs<TemplateSpecializationType>()) {
267 TemplateName SpecName = SpecType->getTemplateName();
268
269 // The class template we found is the same template being
270 // specialized.
271 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
272 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
273 return CreateParsedType(
274 MemberOfType,
275 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
276
277 continue;
278 }
279
280 // The class template we found has the same name as the
281 // (dependent) template name being specialized.
282 if (DependentTemplateName *DepTemplate
283 = SpecName.getAsDependentTemplateName()) {
284 if (DepTemplate->isIdentifier() &&
285 DepTemplate->getIdentifier() == Template->getIdentifier())
286 return CreateParsedType(
287 MemberOfType,
288 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
289
290 continue;
291 }
292 }
293 }
294 }
295
296 if (isDependent) {
297 // We didn't find our type, but that's okay: it's dependent
298 // anyway.
299
300 // FIXME: What if we have no nested-name-specifier?
301 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
302 SS.getWithLocInContext(Context),
303 II, NameLoc);
304 return ParsedType::make(T);
305 }
306
307 if (NonMatchingTypeDecl) {
308 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
309 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
310 << T << SearchType;
311 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
312 << T;
313 } else if (ObjectTypePtr)
314 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
315 << &II;
316 else {
317 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
318 diag::err_destructor_class_name);
319 if (S) {
320 const DeclContext *Ctx = S->getEntity();
321 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
322 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
323 Class->getNameAsString());
324 }
325 }
326
327 return nullptr;
328}
329
330ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
331 ParsedType ObjectType) {
332 if (DS.getTypeSpecType() == DeclSpec::TST_error)
333 return nullptr;
334
335 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
336 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
337 return nullptr;
338 }
339
340 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_decltype && "unexpected type in getDestructorType"
) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 341, __extension__ __PRETTY_FUNCTION__))
341 "unexpected type in getDestructorType")(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_decltype && "unexpected type in getDestructorType"
) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 341, __extension__ __PRETTY_FUNCTION__))
;
342 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
343
344 // If we know the type of the object, check that the correct destructor
345 // type was named now; we can give better diagnostics this way.
346 QualType SearchType = GetTypeFromParser(ObjectType);
347 if (!SearchType.isNull() && !SearchType->isDependentType() &&
348 !Context.hasSameUnqualifiedType(T, SearchType)) {
349 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
350 << T << SearchType;
351 return nullptr;
352 }
353
354 return ParsedType::make(T);
355}
356
357bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
358 const UnqualifiedId &Name) {
359 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId)(static_cast <bool> (Name.getKind() == UnqualifiedIdKind
::IK_LiteralOperatorId) ? void (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 359, __extension__ __PRETTY_FUNCTION__))
;
360
361 if (!SS.isValid())
362 return false;
363
364 switch (SS.getScopeRep()->getKind()) {
365 case NestedNameSpecifier::Identifier:
366 case NestedNameSpecifier::TypeSpec:
367 case NestedNameSpecifier::TypeSpecWithTemplate:
368 // Per C++11 [over.literal]p2, literal operators can only be declared at
369 // namespace scope. Therefore, this unqualified-id cannot name anything.
370 // Reject it early, because we have no AST representation for this in the
371 // case where the scope is dependent.
372 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
373 << SS.getScopeRep();
374 return true;
375
376 case NestedNameSpecifier::Global:
377 case NestedNameSpecifier::Super:
378 case NestedNameSpecifier::Namespace:
379 case NestedNameSpecifier::NamespaceAlias:
380 return false;
381 }
382
383 llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 383)
;
384}
385
386/// \brief Build a C++ typeid expression with a type operand.
387ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
388 SourceLocation TypeidLoc,
389 TypeSourceInfo *Operand,
390 SourceLocation RParenLoc) {
391 // C++ [expr.typeid]p4:
392 // The top-level cv-qualifiers of the lvalue expression or the type-id
393 // that is the operand of typeid are always ignored.
394 // If the type of the type-id is a class type or a reference to a class
395 // type, the class shall be completely-defined.
396 Qualifiers Quals;
397 QualType T
398 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
399 Quals);
400 if (T->getAs<RecordType>() &&
401 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
402 return ExprError();
403
404 if (T->isVariablyModifiedType())
405 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
406
407 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
408 SourceRange(TypeidLoc, RParenLoc));
409}
410
411/// \brief Build a C++ typeid expression with an expression operand.
412ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
413 SourceLocation TypeidLoc,
414 Expr *E,
415 SourceLocation RParenLoc) {
416 bool WasEvaluated = false;
417 if (E && !E->isTypeDependent()) {
418 if (E->getType()->isPlaceholderType()) {
419 ExprResult result = CheckPlaceholderExpr(E);
420 if (result.isInvalid()) return ExprError();
421 E = result.get();
422 }
423
424 QualType T = E->getType();
425 if (const RecordType *RecordT = T->getAs<RecordType>()) {
426 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
427 // C++ [expr.typeid]p3:
428 // [...] If the type of the expression is a class type, the class
429 // shall be completely-defined.
430 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
431 return ExprError();
432
433 // C++ [expr.typeid]p3:
434 // When typeid is applied to an expression other than an glvalue of a
435 // polymorphic class type [...] [the] expression is an unevaluated
436 // operand. [...]
437 if (RecordD->isPolymorphic() && E->isGLValue()) {
438 // The subexpression is potentially evaluated; switch the context
439 // and recheck the subexpression.
440 ExprResult Result = TransformToPotentiallyEvaluated(E);
441 if (Result.isInvalid()) return ExprError();
442 E = Result.get();
443
444 // We require a vtable to query the type at run time.
445 MarkVTableUsed(TypeidLoc, RecordD);
446 WasEvaluated = true;
447 }
448 }
449
450 // C++ [expr.typeid]p4:
451 // [...] If the type of the type-id is a reference to a possibly
452 // cv-qualified type, the result of the typeid expression refers to a
453 // std::type_info object representing the cv-unqualified referenced
454 // type.
455 Qualifiers Quals;
456 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
457 if (!Context.hasSameType(T, UnqualT)) {
458 T = UnqualT;
459 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
460 }
461 }
462
463 if (E->getType()->isVariablyModifiedType())
464 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
465 << E->getType());
466 else if (!inTemplateInstantiation() &&
467 E->HasSideEffects(Context, WasEvaluated)) {
468 // The expression operand for typeid is in an unevaluated expression
469 // context, so side effects could result in unintended consequences.
470 Diag(E->getExprLoc(), WasEvaluated
471 ? diag::warn_side_effects_typeid
472 : diag::warn_side_effects_unevaluated_context);
473 }
474
475 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
476 SourceRange(TypeidLoc, RParenLoc));
477}
478
479/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
480ExprResult
481Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
482 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
483 // Find the std::type_info type.
484 if (!getStdNamespace())
485 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
486
487 if (!CXXTypeInfoDecl) {
488 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
489 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
490 LookupQualifiedName(R, getStdNamespace());
491 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
492 // Microsoft's typeinfo doesn't have type_info in std but in the global
493 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
494 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
495 LookupQualifiedName(R, Context.getTranslationUnitDecl());
496 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
497 }
498 if (!CXXTypeInfoDecl)
499 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
500 }
501
502 if (!getLangOpts().RTTI) {
503 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
504 }
505
506 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
507
508 if (isType) {
509 // The operand is a type; handle it as such.
510 TypeSourceInfo *TInfo = nullptr;
511 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
512 &TInfo);
513 if (T.isNull())
514 return ExprError();
515
516 if (!TInfo)
517 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
518
519 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
520 }
521
522 // The operand is an expression.
523 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
524}
525
526/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
527/// a single GUID.
528static void
529getUuidAttrOfType(Sema &SemaRef, QualType QT,
530 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
531 // Optionally remove one level of pointer, reference or array indirection.
532 const Type *Ty = QT.getTypePtr();
533 if (QT->isPointerType() || QT->isReferenceType())
534 Ty = QT->getPointeeType().getTypePtr();
535 else if (QT->isArrayType())
536 Ty = Ty->getBaseElementTypeUnsafe();
537
538 const auto *TD = Ty->getAsTagDecl();
539 if (!TD)
540 return;
541
542 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
543 UuidAttrs.insert(Uuid);
544 return;
545 }
546
547 // __uuidof can grab UUIDs from template arguments.
548 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
549 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
550 for (const TemplateArgument &TA : TAL.asArray()) {
551 const UuidAttr *UuidForTA = nullptr;
552 if (TA.getKind() == TemplateArgument::Type)
553 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
554 else if (TA.getKind() == TemplateArgument::Declaration)
555 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
556
557 if (UuidForTA)
558 UuidAttrs.insert(UuidForTA);
559 }
560 }
561}
562
563/// \brief Build a Microsoft __uuidof expression with a type operand.
564ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
565 SourceLocation TypeidLoc,
566 TypeSourceInfo *Operand,
567 SourceLocation RParenLoc) {
568 StringRef UuidStr;
569 if (!Operand->getType()->isDependentType()) {
570 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
571 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
572 if (UuidAttrs.empty())
573 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
574 if (UuidAttrs.size() > 1)
575 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
576 UuidStr = UuidAttrs.back()->getGuid();
577 }
578
579 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
580 SourceRange(TypeidLoc, RParenLoc));
581}
582
583/// \brief Build a Microsoft __uuidof expression with an expression operand.
584ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
585 SourceLocation TypeidLoc,
586 Expr *E,
587 SourceLocation RParenLoc) {
588 StringRef UuidStr;
589 if (!E->getType()->isDependentType()) {
590 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
591 UuidStr = "00000000-0000-0000-0000-000000000000";
592 } else {
593 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
594 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
595 if (UuidAttrs.empty())
596 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
597 if (UuidAttrs.size() > 1)
598 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
599 UuidStr = UuidAttrs.back()->getGuid();
600 }
601 }
602
603 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
604 SourceRange(TypeidLoc, RParenLoc));
605}
606
607/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
608ExprResult
609Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
610 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
611 // If MSVCGuidDecl has not been cached, do the lookup.
612 if (!MSVCGuidDecl) {
613 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
614 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
615 LookupQualifiedName(R, Context.getTranslationUnitDecl());
616 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
617 if (!MSVCGuidDecl)
618 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
619 }
620
621 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
622
623 if (isType) {
624 // The operand is a type; handle it as such.
625 TypeSourceInfo *TInfo = nullptr;
626 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
627 &TInfo);
628 if (T.isNull())
629 return ExprError();
630
631 if (!TInfo)
632 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
633
634 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
635 }
636
637 // The operand is an expression.
638 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
639}
640
641/// ActOnCXXBoolLiteral - Parse {true,false} literals.
642ExprResult
643Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
644 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(static_cast <bool> ((Kind == tok::kw_true || Kind == tok
::kw_false) && "Unknown C++ Boolean value!") ? void (
0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 645, __extension__ __PRETTY_FUNCTION__))
645 "Unknown C++ Boolean value!")(static_cast <bool> ((Kind == tok::kw_true || Kind == tok
::kw_false) && "Unknown C++ Boolean value!") ? void (
0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 645, __extension__ __PRETTY_FUNCTION__))
;
646 return new (Context)
647 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
648}
649
650/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
651ExprResult
652Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
653 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
654}
655
656/// ActOnCXXThrow - Parse throw expressions.
657ExprResult
658Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
659 bool IsThrownVarInScope = false;
660 if (Ex) {
1
Assuming 'Ex' is null
2
Taking false branch
661 // C++0x [class.copymove]p31:
662 // When certain criteria are met, an implementation is allowed to omit the
663 // copy/move construction of a class object [...]
664 //
665 // - in a throw-expression, when the operand is the name of a
666 // non-volatile automatic object (other than a function or catch-
667 // clause parameter) whose scope does not extend beyond the end of the
668 // innermost enclosing try-block (if there is one), the copy/move
669 // operation from the operand to the exception object (15.1) can be
670 // omitted by constructing the automatic object directly into the
671 // exception object
672 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
673 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
674 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
675 for( ; S; S = S->getParent()) {
676 if (S->isDeclScope(Var)) {
677 IsThrownVarInScope = true;
678 break;
679 }
680
681 if (S->getFlags() &
682 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
683 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
684 Scope::TryScope))
685 break;
686 }
687 }
688 }
689 }
690
691 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
3
Calling 'Sema::BuildCXXThrow'
692}
693
694ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
695 bool IsThrownVarInScope) {
696 // Don't report an error if 'throw' is used in system headers.
697 if (!getLangOpts().CXXExceptions &&
4
Assuming the condition is false
698 !getSourceManager().isInSystemHeader(OpLoc))
699 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
700
701 // Exceptions aren't allowed in CUDA device code.
702 if (getLangOpts().CUDA)
5
Assuming the condition is true
6
Taking true branch
703 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
7
Calling 'operator<<'
24
Returned allocated memory
704 << "throw" << CurrentCUDATarget();
705
706 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
25
Potential leak of memory pointed to by field 'DiagStorage'
707 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
708
709 if (Ex && !Ex->isTypeDependent()) {
710 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
711 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
712 return ExprError();
713
714 // Initialize the exception result. This implicitly weeds out
715 // abstract types or types with inaccessible copy constructors.
716
717 // C++0x [class.copymove]p31:
718 // When certain criteria are met, an implementation is allowed to omit the
719 // copy/move construction of a class object [...]
720 //
721 // - in a throw-expression, when the operand is the name of a
722 // non-volatile automatic object (other than a function or
723 // catch-clause
724 // parameter) whose scope does not extend beyond the end of the
725 // innermost enclosing try-block (if there is one), the copy/move
726 // operation from the operand to the exception object (15.1) can be
727 // omitted by constructing the automatic object directly into the
728 // exception object
729 const VarDecl *NRVOVariable = nullptr;
730 if (IsThrownVarInScope)
731 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
732
733 InitializedEntity Entity = InitializedEntity::InitializeException(
734 OpLoc, ExceptionObjectTy,
735 /*NRVO=*/NRVOVariable != nullptr);
736 ExprResult Res = PerformMoveOrCopyInitialization(
737 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
738 if (Res.isInvalid())
739 return ExprError();
740 Ex = Res.get();
741 }
742
743 return new (Context)
744 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
745}
746
747static void
748collectPublicBases(CXXRecordDecl *RD,
749 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
750 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
751 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
752 bool ParentIsPublic) {
753 for (const CXXBaseSpecifier &BS : RD->bases()) {
754 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
755 bool NewSubobject;
756 // Virtual bases constitute the same subobject. Non-virtual bases are
757 // always distinct subobjects.
758 if (BS.isVirtual())
759 NewSubobject = VBases.insert(BaseDecl).second;
760 else
761 NewSubobject = true;
762
763 if (NewSubobject)
764 ++SubobjectsSeen[BaseDecl];
765
766 // Only add subobjects which have public access throughout the entire chain.
767 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
768 if (PublicPath)
769 PublicSubobjectsSeen.insert(BaseDecl);
770
771 // Recurse on to each base subobject.
772 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
773 PublicPath);
774 }
775}
776
777static void getUnambiguousPublicSubobjects(
778 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
779 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
780 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
781 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
782 SubobjectsSeen[RD] = 1;
783 PublicSubobjectsSeen.insert(RD);
784 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
785 /*ParentIsPublic=*/true);
786
787 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
788 // Skip ambiguous objects.
789 if (SubobjectsSeen[PublicSubobject] > 1)
790 continue;
791
792 Objects.push_back(PublicSubobject);
793 }
794}
795
796/// CheckCXXThrowOperand - Validate the operand of a throw.
797bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
798 QualType ExceptionObjectTy, Expr *E) {
799 // If the type of the exception would be an incomplete type or a pointer
800 // to an incomplete type other than (cv) void the program is ill-formed.
801 QualType Ty = ExceptionObjectTy;
802 bool isPointer = false;
803 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
804 Ty = Ptr->getPointeeType();
805 isPointer = true;
806 }
807 if (!isPointer || !Ty->isVoidType()) {
808 if (RequireCompleteType(ThrowLoc, Ty,
809 isPointer ? diag::err_throw_incomplete_ptr
810 : diag::err_throw_incomplete,
811 E->getSourceRange()))
812 return true;
813
814 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
815 diag::err_throw_abstract_type, E))
816 return true;
817 }
818
819 // If the exception has class type, we need additional handling.
820 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
821 if (!RD)
822 return false;
823
824 // If we are throwing a polymorphic class type or pointer thereof,
825 // exception handling will make use of the vtable.
826 MarkVTableUsed(ThrowLoc, RD);
827
828 // If a pointer is thrown, the referenced object will not be destroyed.
829 if (isPointer)
830 return false;
831
832 // If the class has a destructor, we must be able to call it.
833 if (!RD->hasIrrelevantDestructor()) {
834 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
835 MarkFunctionReferenced(E->getExprLoc(), Destructor);
836 CheckDestructorAccess(E->getExprLoc(), Destructor,
837 PDiag(diag::err_access_dtor_exception) << Ty);
838 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
839 return true;
840 }
841 }
842
843 // The MSVC ABI creates a list of all types which can catch the exception
844 // object. This list also references the appropriate copy constructor to call
845 // if the object is caught by value and has a non-trivial copy constructor.
846 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
847 // We are only interested in the public, unambiguous bases contained within
848 // the exception object. Bases which are ambiguous or otherwise
849 // inaccessible are not catchable types.
850 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
851 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
852
853 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
854 // Attempt to lookup the copy constructor. Various pieces of machinery
855 // will spring into action, like template instantiation, which means this
856 // cannot be a simple walk of the class's decls. Instead, we must perform
857 // lookup and overload resolution.
858 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
859 if (!CD)
860 continue;
861
862 // Mark the constructor referenced as it is used by this throw expression.
863 MarkFunctionReferenced(E->getExprLoc(), CD);
864
865 // Skip this copy constructor if it is trivial, we don't need to record it
866 // in the catchable type data.
867 if (CD->isTrivial())
868 continue;
869
870 // The copy constructor is non-trivial, create a mapping from this class
871 // type to this constructor.
872 // N.B. The selection of copy constructor is not sensitive to this
873 // particular throw-site. Lookup will be performed at the catch-site to
874 // ensure that the copy constructor is, in fact, accessible (via
875 // friendship or any other means).
876 Context.addCopyConstructorForExceptionObject(Subobject, CD);
877
878 // We don't keep the instantiated default argument expressions around so
879 // we must rebuild them here.
880 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
881 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
882 return true;
883 }
884 }
885 }
886
887 return false;
888}
889
890static QualType adjustCVQualifiersForCXXThisWithinLambda(
891 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
892 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
893
894 QualType ClassType = ThisTy->getPointeeType();
895 LambdaScopeInfo *CurLSI = nullptr;
896 DeclContext *CurDC = CurSemaContext;
897
898 // Iterate through the stack of lambdas starting from the innermost lambda to
899 // the outermost lambda, checking if '*this' is ever captured by copy - since
900 // that could change the cv-qualifiers of the '*this' object.
901 // The object referred to by '*this' starts out with the cv-qualifiers of its
902 // member function. We then start with the innermost lambda and iterate
903 // outward checking to see if any lambda performs a by-copy capture of '*this'
904 // - and if so, any nested lambda must respect the 'constness' of that
905 // capturing lamdbda's call operator.
906 //
907
908 // Since the FunctionScopeInfo stack is representative of the lexical
909 // nesting of the lambda expressions during initial parsing (and is the best
910 // place for querying information about captures about lambdas that are
911 // partially processed) and perhaps during instantiation of function templates
912 // that contain lambda expressions that need to be transformed BUT not
913 // necessarily during instantiation of a nested generic lambda's function call
914 // operator (which might even be instantiated at the end of the TU) - at which
915 // time the DeclContext tree is mature enough to query capture information
916 // reliably - we use a two pronged approach to walk through all the lexically
917 // enclosing lambda expressions:
918 //
919 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
920 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
921 // enclosed by the call-operator of the LSI below it on the stack (while
922 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
923 // the stack represents the innermost lambda.
924 //
925 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
926 // represents a lambda's call operator. If it does, we must be instantiating
927 // a generic lambda's call operator (represented by the Current LSI, and
928 // should be the only scenario where an inconsistency between the LSI and the
929 // DeclContext should occur), so climb out the DeclContexts if they
930 // represent lambdas, while querying the corresponding closure types
931 // regarding capture information.
932
933 // 1) Climb down the function scope info stack.
934 for (int I = FunctionScopes.size();
935 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
936 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
937 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
938 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
939 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
940
941 if (!CurLSI->isCXXThisCaptured())
942 continue;
943
944 auto C = CurLSI->getCXXThisCapture();
945
946 if (C.isCopyCapture()) {
947 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
948 if (CurLSI->CallOperator->isConst())
949 ClassType.addConst();
950 return ASTCtx.getPointerType(ClassType);
951 }
952 }
953
954 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
955 // happen during instantiation of its nested generic lambda call operator)
956 if (isLambdaCallOperator(CurDC)) {
957 assert(CurLSI && "While computing 'this' capture-type for a generic "(static_cast <bool> (CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? void
(0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 958, __extension__ __PRETTY_FUNCTION__))
958 "lambda, we must have a corresponding LambdaScopeInfo")(static_cast <bool> (CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? void
(0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 958, __extension__ __PRETTY_FUNCTION__))
;
959 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&(static_cast <bool> (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") ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
960 "While computing 'this' capture-type for a generic lambda, when we "(static_cast <bool> (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") ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
961 "run out of enclosing LSI's, yet the enclosing DC is a "(static_cast <bool> (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") ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
962 "lambda-call-operator we must be (i.e. Current LSI) in a generic "(static_cast <bool> (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") ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
963 "lambda call oeprator")(static_cast <bool> (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") ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
;
964 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))(static_cast <bool> (CurDC == getLambdaAwareParentOfDeclContext
(CurLSI->CallOperator)) ? void (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 964, __extension__ __PRETTY_FUNCTION__))
;
965
966 auto IsThisCaptured =
967 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
968 IsConst = false;
969 IsByCopy = false;
970 for (auto &&C : Closure->captures()) {
971 if (C.capturesThis()) {
972 if (C.getCaptureKind() == LCK_StarThis)
973 IsByCopy = true;
974 if (Closure->getLambdaCallOperator()->isConst())
975 IsConst = true;
976 return true;
977 }
978 }
979 return false;
980 };
981
982 bool IsByCopyCapture = false;
983 bool IsConstCapture = false;
984 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
985 while (Closure &&
986 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
987 if (IsByCopyCapture) {
988 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
989 if (IsConstCapture)
990 ClassType.addConst();
991 return ASTCtx.getPointerType(ClassType);
992 }
993 Closure = isLambdaCallOperator(Closure->getParent())
994 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
995 : nullptr;
996 }
997 }
998 return ASTCtx.getPointerType(ClassType);
999}
1000
1001QualType Sema::getCurrentThisType() {
1002 DeclContext *DC = getFunctionLevelDeclContext();
1003 QualType ThisTy = CXXThisTypeOverride;
1004
1005 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1006 if (method && method->isInstance())
1007 ThisTy = method->getThisType(Context);
1008 }
1009
1010 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1011 inTemplateInstantiation()) {
1012
1013 assert(isa<CXXRecordDecl>(DC) &&(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"Trying to get 'this' type from static method?") ? void (0) :
__assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1014, __extension__ __PRETTY_FUNCTION__))
1014 "Trying to get 'this' type from static method?")(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"Trying to get 'this' type from static method?") ? void (0) :
__assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1014, __extension__ __PRETTY_FUNCTION__))
;
1015
1016 // This is a lambda call operator that is being instantiated as a default
1017 // initializer. DC must point to the enclosing class type, so we can recover
1018 // the 'this' type from it.
1019
1020 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1021 // There are no cv-qualifiers for 'this' within default initializers,
1022 // per [expr.prim.general]p4.
1023 ThisTy = Context.getPointerType(ClassTy);
1024 }
1025
1026 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1027 // might need to be adjusted if the lambda or any of its enclosing lambda's
1028 // captures '*this' by copy.
1029 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1030 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1031 CurContext, Context);
1032 return ThisTy;
1033}
1034
1035Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1036 Decl *ContextDecl,
1037 unsigned CXXThisTypeQuals,
1038 bool Enabled)
1039 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1040{
1041 if (!Enabled || !ContextDecl)
1042 return;
1043
1044 CXXRecordDecl *Record = nullptr;
1045 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1046 Record = Template->getTemplatedDecl();
1047 else
1048 Record = cast<CXXRecordDecl>(ContextDecl);
1049
1050 // We care only for CVR qualifiers here, so cut everything else.
1051 CXXThisTypeQuals &= Qualifiers::FastMask;
1052 S.CXXThisTypeOverride
1053 = S.Context.getPointerType(
1054 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
1055
1056 this->Enabled = true;
1057}
1058
1059
1060Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1061 if (Enabled) {
1062 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1063 }
1064}
1065
1066static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1067 QualType ThisTy, SourceLocation Loc,
1068 const bool ByCopy) {
1069
1070 QualType AdjustedThisTy = ThisTy;
1071 // The type of the corresponding data member (not a 'this' pointer if 'by
1072 // copy').
1073 QualType CaptureThisFieldTy = ThisTy;
1074 if (ByCopy) {
1075 // If we are capturing the object referred to by '*this' by copy, ignore any
1076 // cv qualifiers inherited from the type of the member function for the type
1077 // of the closure-type's corresponding data member and any use of 'this'.
1078 CaptureThisFieldTy = ThisTy->getPointeeType();
1079 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1080 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1081 }
1082
1083 FieldDecl *Field = FieldDecl::Create(
1084 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1085 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1086 ICIS_NoInit);
1087
1088 Field->setImplicit(true);
1089 Field->setAccess(AS_private);
1090 RD->addDecl(Field);
1091 Expr *This =
1092 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1093 if (ByCopy) {
1094 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1095 UO_Deref,
1096 This).get();
1097 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1098 nullptr, CaptureThisFieldTy, Loc);
1099 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1100 InitializationSequence Init(S, Entity, InitKind, StarThis);
1101 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1102 if (ER.isInvalid()) return nullptr;
1103 return ER.get();
1104 }
1105 return This;
1106}
1107
1108bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1109 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1110 const bool ByCopy) {
1111 // We don't need to capture this in an unevaluated context.
1112 if (isUnevaluatedContext() && !Explicit)
1113 return true;
1114
1115 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(static_cast <bool> ((!ByCopy || Explicit) && "cannot implicitly capture *this by value"
) ? void (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1115, __extension__ __PRETTY_FUNCTION__))
;
1116
1117 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
1118 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
1119
1120 // Check that we can capture the *enclosing object* (referred to by '*this')
1121 // by the capturing-entity/closure (lambda/block/etc) at
1122 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1123
1124 // Note: The *enclosing object* can only be captured by-value by a
1125 // closure that is a lambda, using the explicit notation:
1126 // [*this] { ... }.
1127 // Every other capture of the *enclosing object* results in its by-reference
1128 // capture.
1129
1130 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1131 // stack), we can capture the *enclosing object* only if:
1132 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1133 // - or, 'L' has an implicit capture.
1134 // AND
1135 // -- there is no enclosing closure
1136 // -- or, there is some enclosing closure 'E' that has already captured the
1137 // *enclosing object*, and every intervening closure (if any) between 'E'
1138 // and 'L' can implicitly capture the *enclosing object*.
1139 // -- or, every enclosing closure can implicitly capture the
1140 // *enclosing object*
1141
1142
1143 unsigned NumCapturingClosures = 0;
1144 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
1145 if (CapturingScopeInfo *CSI =
1146 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1147 if (CSI->CXXThisCaptureIndex != 0) {
1148 // 'this' is already being captured; there isn't anything more to do.
1149 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1150 break;
1151 }
1152 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1153 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1154 // This context can't implicitly capture 'this'; fail out.
1155 if (BuildAndDiagnose)
1156 Diag(Loc, diag::err_this_capture)
1157 << (Explicit && idx == MaxFunctionScopesIndex);
1158 return true;
1159 }
1160 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1161 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1162 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1163 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1164 (Explicit && idx == MaxFunctionScopesIndex)) {
1165 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1166 // iteration through can be an explicit capture, all enclosing closures,
1167 // if any, must perform implicit captures.
1168
1169 // This closure can capture 'this'; continue looking upwards.
1170 NumCapturingClosures++;
1171 continue;
1172 }
1173 // This context can't implicitly capture 'this'; fail out.
1174 if (BuildAndDiagnose)
1175 Diag(Loc, diag::err_this_capture)
1176 << (Explicit && idx == MaxFunctionScopesIndex);
1177 return true;
1178 }
1179 break;
1180 }
1181 if (!BuildAndDiagnose) return false;
1182
1183 // If we got here, then the closure at MaxFunctionScopesIndex on the
1184 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1185 // (including implicit by-reference captures in any enclosing closures).
1186
1187 // In the loop below, respect the ByCopy flag only for the closure requesting
1188 // the capture (i.e. first iteration through the loop below). Ignore it for
1189 // all enclosing closure's up to NumCapturingClosures (since they must be
1190 // implicitly capturing the *enclosing object* by reference (see loop
1191 // above)).
1192 assert((!ByCopy ||(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1195, __extension__ __PRETTY_FUNCTION__))
1193 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1195, __extension__ __PRETTY_FUNCTION__))
1194 "Only a lambda can capture the enclosing object (referred to by "(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1195, __extension__ __PRETTY_FUNCTION__))
1195 "*this) by copy")(static_cast <bool> ((!ByCopy || dyn_cast<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1195, __extension__ __PRETTY_FUNCTION__))
;
1196 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1197 // contexts.
1198 QualType ThisTy = getCurrentThisType();
1199 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
1200 --idx, --NumCapturingClosures) {
1201 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1202 Expr *ThisExpr = nullptr;
1203
1204 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1205 // For lambda expressions, build a field and an initializing expression,
1206 // and capture the *enclosing object* by copy only if this is the first
1207 // iteration.
1208 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1209 ByCopy && idx == MaxFunctionScopesIndex);
1210
1211 } else if (CapturedRegionScopeInfo *RSI
1212 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1213 ThisExpr =
1214 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1215 false/*ByCopy*/);
1216
1217 bool isNested = NumCapturingClosures > 1;
1218 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1219 }
1220 return false;
1221}
1222
1223ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1224 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1225 /// is a non-lvalue expression whose value is the address of the object for
1226 /// which the function is called.
1227
1228 QualType ThisTy = getCurrentThisType();
1229 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1230
1231 CheckCXXThisCapture(Loc);
1232 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1233}
1234
1235bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1236 // If we're outside the body of a member function, then we'll have a specified
1237 // type for 'this'.
1238 if (CXXThisTypeOverride.isNull())
1239 return false;
1240
1241 // Determine whether we're looking into a class that's currently being
1242 // defined.
1243 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1244 return Class && Class->isBeingDefined();
1245}
1246
1247/// Parse construction of a specified type.
1248/// Can be interpreted either as function-style casting ("int(x)")
1249/// or class type construction ("ClassType(x,y,z)")
1250/// or creation of a value-initialized type ("int()").
1251ExprResult
1252Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1253 SourceLocation LParenOrBraceLoc,
1254 MultiExprArg exprs,
1255 SourceLocation RParenOrBraceLoc,
1256 bool ListInitialization) {
1257 if (!TypeRep)
1258 return ExprError();
1259
1260 TypeSourceInfo *TInfo;
1261 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1262 if (!TInfo)
1263 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1264
1265 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1266 RParenOrBraceLoc, ListInitialization);
1267 // Avoid creating a non-type-dependent expression that contains typos.
1268 // Non-type-dependent expressions are liable to be discarded without
1269 // checking for embedded typos.
1270 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1271 !Result.get()->isTypeDependent())
1272 Result = CorrectDelayedTyposInExpr(Result.get());
1273 return Result;
1274}
1275
1276ExprResult
1277Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1278 SourceLocation LParenOrBraceLoc,
1279 MultiExprArg Exprs,
1280 SourceLocation RParenOrBraceLoc,
1281 bool ListInitialization) {
1282 QualType Ty = TInfo->getType();
1283 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1284
1285 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1286 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1287 // directly. We work around this by dropping the locations of the braces.
1288 SourceRange Locs = ListInitialization
1289 ? SourceRange()
1290 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1291 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1292 Exprs, Locs.getEnd());
1293 }
1294
1295 assert((!ListInitialization ||(static_cast <bool> ((!ListInitialization || (Exprs.size
() == 1 && isa<InitListExpr>(Exprs[0]))) &&
"List initialization must have initializer list as expression."
) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
1296 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&(static_cast <bool> ((!ListInitialization || (Exprs.size
() == 1 && isa<InitListExpr>(Exprs[0]))) &&
"List initialization must have initializer list as expression."
) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
1297 "List initialization must have initializer list as expression.")(static_cast <bool> ((!ListInitialization || (Exprs.size
() == 1 && isa<InitListExpr>(Exprs[0]))) &&
"List initialization must have initializer list as expression."
) ? void (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1297, __extension__ __PRETTY_FUNCTION__))
;
1298 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1299
1300 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1301 InitializationKind Kind =
1302 Exprs.size()
1303 ? ListInitialization
1304 ? InitializationKind::CreateDirectList(
1305 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1306 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1307 RParenOrBraceLoc)
1308 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1309 RParenOrBraceLoc);
1310
1311 // C++1z [expr.type.conv]p1:
1312 // If the type is a placeholder for a deduced class type, [...perform class
1313 // template argument deduction...]
1314 DeducedType *Deduced = Ty->getContainedDeducedType();
1315 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1316 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1317 Kind, Exprs);
1318 if (Ty.isNull())
1319 return ExprError();
1320 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1321 }
1322
1323 // C++ [expr.type.conv]p1:
1324 // If the expression list is a parenthesized single expression, the type
1325 // conversion expression is equivalent (in definedness, and if defined in
1326 // meaning) to the corresponding cast expression.
1327 if (Exprs.size() == 1 && !ListInitialization &&
1328 !isa<InitListExpr>(Exprs[0])) {
1329 Expr *Arg = Exprs[0];
1330 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1331 RParenOrBraceLoc);
1332 }
1333
1334 // For an expression of the form T(), T shall not be an array type.
1335 QualType ElemTy = Ty;
1336 if (Ty->isArrayType()) {
1337 if (!ListInitialization)
1338 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1339 << FullRange);
1340 ElemTy = Context.getBaseElementType(Ty);
1341 }
1342
1343 // There doesn't seem to be an explicit rule against this but sanity demands
1344 // we only construct objects with object types.
1345 if (Ty->isFunctionType())
1346 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1347 << Ty << FullRange);
1348
1349 // C++17 [expr.type.conv]p2:
1350 // If the type is cv void and the initializer is (), the expression is a
1351 // prvalue of the specified type that performs no initialization.
1352 if (!Ty->isVoidType() &&
1353 RequireCompleteType(TyBeginLoc, ElemTy,
1354 diag::err_invalid_incomplete_type_use, FullRange))
1355 return ExprError();
1356
1357 // Otherwise, the expression is a prvalue of the specified type whose
1358 // result object is direct-initialized (11.6) with the initializer.
1359 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1360 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1361
1362 if (Result.isInvalid())
1363 return Result;
1364
1365 Expr *Inner = Result.get();
1366 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1367 Inner = BTE->getSubExpr();
1368 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1369 !isa<CXXScalarValueInitExpr>(Inner)) {
1370 // If we created a CXXTemporaryObjectExpr, that node also represents the
1371 // functional cast. Otherwise, create an explicit cast to represent
1372 // the syntactic form of a functional-style cast that was used here.
1373 //
1374 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1375 // would give a more consistent AST representation than using a
1376 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1377 // is sometimes handled by initialization and sometimes not.
1378 QualType ResultType = Result.get()->getType();
1379 SourceRange Locs = ListInitialization
1380 ? SourceRange()
1381 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1382 Result = CXXFunctionalCastExpr::Create(
1383 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1384 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1385 }
1386
1387 return Result;
1388}
1389
1390/// \brief Determine whether the given function is a non-placement
1391/// deallocation function.
1392static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1393 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1394 return Method->isUsualDeallocationFunction();
1395
1396 if (FD->getOverloadedOperator() != OO_Delete &&
1397 FD->getOverloadedOperator() != OO_Array_Delete)
1398 return false;
1399
1400 unsigned UsualParams = 1;
1401
1402 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1403 S.Context.hasSameUnqualifiedType(
1404 FD->getParamDecl(UsualParams)->getType(),
1405 S.Context.getSizeType()))
1406 ++UsualParams;
1407
1408 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1409 S.Context.hasSameUnqualifiedType(
1410 FD->getParamDecl(UsualParams)->getType(),
1411 S.Context.getTypeDeclType(S.getStdAlignValT())))
1412 ++UsualParams;
1413
1414 return UsualParams == FD->getNumParams();
1415}
1416
1417namespace {
1418 struct UsualDeallocFnInfo {
1419 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1420 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1421 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1422 Destroying(false), HasSizeT(false), HasAlignValT(false),
1423 CUDAPref(Sema::CFP_Native) {
1424 // A function template declaration is never a usual deallocation function.
1425 if (!FD)
1426 return;
1427 unsigned NumBaseParams = 1;
1428 if (FD->isDestroyingOperatorDelete()) {
1429 Destroying = true;
1430 ++NumBaseParams;
1431 }
1432 if (FD->getNumParams() == NumBaseParams + 2)
1433 HasAlignValT = HasSizeT = true;
1434 else if (FD->getNumParams() == NumBaseParams + 1) {
1435 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
1436 HasAlignValT = !HasSizeT;
1437 }
1438
1439 // In CUDA, determine how much we'd like / dislike to call this.
1440 if (S.getLangOpts().CUDA)
1441 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1442 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1443 }
1444
1445 operator bool() const { return FD; }
1446
1447 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1448 bool WantAlign) const {
1449 // C++ P0722:
1450 // A destroying operator delete is preferred over a non-destroying
1451 // operator delete.
1452 if (Destroying != Other.Destroying)
1453 return Destroying;
1454
1455 // C++17 [expr.delete]p10:
1456 // If the type has new-extended alignment, a function with a parameter
1457 // of type std::align_val_t is preferred; otherwise a function without
1458 // such a parameter is preferred
1459 if (HasAlignValT != Other.HasAlignValT)
1460 return HasAlignValT == WantAlign;
1461
1462 if (HasSizeT != Other.HasSizeT)
1463 return HasSizeT == WantSize;
1464
1465 // Use CUDA call preference as a tiebreaker.
1466 return CUDAPref > Other.CUDAPref;
1467 }
1468
1469 DeclAccessPair Found;
1470 FunctionDecl *FD;
1471 bool Destroying, HasSizeT, HasAlignValT;
1472 Sema::CUDAFunctionPreference CUDAPref;
1473 };
1474}
1475
1476/// Determine whether a type has new-extended alignment. This may be called when
1477/// the type is incomplete (for a delete-expression with an incomplete pointee
1478/// type), in which case it will conservatively return false if the alignment is
1479/// not known.
1480static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1481 return S.getLangOpts().AlignedAllocation &&
1482 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1483 S.getASTContext().getTargetInfo().getNewAlign();
1484}
1485
1486/// Select the correct "usual" deallocation function to use from a selection of
1487/// deallocation functions (either global or class-scope).
1488static UsualDeallocFnInfo resolveDeallocationOverload(
1489 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1490 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1491 UsualDeallocFnInfo Best;
1492
1493 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1494 UsualDeallocFnInfo Info(S, I.getPair());
1495 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1496 Info.CUDAPref == Sema::CFP_Never)
1497 continue;
1498
1499 if (!Best) {
1500 Best = Info;
1501 if (BestFns)
1502 BestFns->push_back(Info);
1503 continue;
1504 }
1505
1506 if (Best.isBetterThan(Info, WantSize, WantAlign))
1507 continue;
1508
1509 // If more than one preferred function is found, all non-preferred
1510 // functions are eliminated from further consideration.
1511 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1512 BestFns->clear();
1513
1514 Best = Info;
1515 if (BestFns)
1516 BestFns->push_back(Info);
1517 }
1518
1519 return Best;
1520}
1521
1522/// Determine whether a given type is a class for which 'delete[]' would call
1523/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1524/// we need to store the array size (even if the type is
1525/// trivially-destructible).
1526static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1527 QualType allocType) {
1528 const RecordType *record =
1529 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1530 if (!record) return false;
1531
1532 // Try to find an operator delete[] in class scope.
1533
1534 DeclarationName deleteName =
1535 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1536 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1537 S.LookupQualifiedName(ops, record->getDecl());
1538
1539 // We're just doing this for information.
1540 ops.suppressDiagnostics();
1541
1542 // Very likely: there's no operator delete[].
1543 if (ops.empty()) return false;
1544
1545 // If it's ambiguous, it should be illegal to call operator delete[]
1546 // on this thing, so it doesn't matter if we allocate extra space or not.
1547 if (ops.isAmbiguous()) return false;
1548
1549 // C++17 [expr.delete]p10:
1550 // If the deallocation functions have class scope, the one without a
1551 // parameter of type std::size_t is selected.
1552 auto Best = resolveDeallocationOverload(
1553 S, ops, /*WantSize*/false,
1554 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1555 return Best && Best.HasSizeT;
1556}
1557
1558/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1559///
1560/// E.g.:
1561/// @code new (memory) int[size][4] @endcode
1562/// or
1563/// @code ::new Foo(23, "hello") @endcode
1564///
1565/// \param StartLoc The first location of the expression.
1566/// \param UseGlobal True if 'new' was prefixed with '::'.
1567/// \param PlacementLParen Opening paren of the placement arguments.
1568/// \param PlacementArgs Placement new arguments.
1569/// \param PlacementRParen Closing paren of the placement arguments.
1570/// \param TypeIdParens If the type is in parens, the source range.
1571/// \param D The type to be allocated, as well as array dimensions.
1572/// \param Initializer The initializing expression or initializer-list, or null
1573/// if there is none.
1574ExprResult
1575Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1576 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1577 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1578 Declarator &D, Expr *Initializer) {
1579 Expr *ArraySize = nullptr;
1580 // If the specified type is an array, unwrap it and save the expression.
1581 if (D.getNumTypeObjects() > 0 &&
1582 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1583 DeclaratorChunk &Chunk = D.getTypeObject(0);
1584 if (D.getDeclSpec().hasAutoTypeSpec())
1585 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1586 << D.getSourceRange());
1587 if (Chunk.Arr.hasStatic)
1588 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1589 << D.getSourceRange());
1590 if (!Chunk.Arr.NumElts)
1591 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1592 << D.getSourceRange());
1593
1594 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1595 D.DropFirstTypeObject();
1596 }
1597
1598 // Every dimension shall be of constant size.
1599 if (ArraySize) {
1600 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1601 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1602 break;
1603
1604 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1605 if (Expr *NumElts = (Expr *)Array.NumElts) {
1606 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1607 if (getLangOpts().CPlusPlus14) {
1608 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1609 // shall be a converted constant expression (5.19) of type std::size_t
1610 // and shall evaluate to a strictly positive value.
1611 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1612 assert(IntWidth && "Builtin type of size 0?")(static_cast <bool> (IntWidth && "Builtin type of size 0?"
) ? void (0) : __assert_fail ("IntWidth && \"Builtin type of size 0?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1612, __extension__ __PRETTY_FUNCTION__))
;
1613 llvm::APSInt Value(IntWidth);
1614 Array.NumElts
1615 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1616 CCEK_NewExpr)
1617 .get();
1618 } else {
1619 Array.NumElts
1620 = VerifyIntegerConstantExpression(NumElts, nullptr,
1621 diag::err_new_array_nonconst)
1622 .get();
1623 }
1624 if (!Array.NumElts)
1625 return ExprError();
1626 }
1627 }
1628 }
1629 }
1630
1631 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1632 QualType AllocType = TInfo->getType();
1633 if (D.isInvalidType())
1634 return ExprError();
1635
1636 SourceRange DirectInitRange;
1637 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1638 DirectInitRange = List->getSourceRange();
1639
1640 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1641 PlacementLParen,
1642 PlacementArgs,
1643 PlacementRParen,
1644 TypeIdParens,
1645 AllocType,
1646 TInfo,
1647 ArraySize,
1648 DirectInitRange,
1649 Initializer);
1650}
1651
1652static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1653 Expr *Init) {
1654 if (!Init)
1655 return true;
1656 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1657 return PLE->getNumExprs() == 0;
1658 if (isa<ImplicitValueInitExpr>(Init))
1659 return true;
1660 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1661 return !CCE->isListInitialization() &&
1662 CCE->getConstructor()->isDefaultConstructor();
1663 else if (Style == CXXNewExpr::ListInit) {
1664 assert(isa<InitListExpr>(Init) &&(static_cast <bool> (isa<InitListExpr>(Init) &&
"Shouldn't create list CXXConstructExprs for arrays.") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1665, __extension__ __PRETTY_FUNCTION__))
1665 "Shouldn't create list CXXConstructExprs for arrays.")(static_cast <bool> (isa<InitListExpr>(Init) &&
"Shouldn't create list CXXConstructExprs for arrays.") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1665, __extension__ __PRETTY_FUNCTION__))
;
1666 return true;
1667 }
1668 return false;
1669}
1670
1671// Emit a diagnostic if an aligned allocation/deallocation function that is not
1672// implemented in the standard library is selected.
1673static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1674 SourceLocation Loc, bool IsDelete,
1675 Sema &S) {
1676 if (!S.getLangOpts().AlignedAllocationUnavailable)
1677 return;
1678
1679 // Return if there is a definition.
1680 if (FD.isDefined())
1681 return;
1682
1683 bool IsAligned = false;
1684 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
1685 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1686 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1687 S.getASTContext().getTargetInfo().getPlatformName());
1688
1689 S.Diag(Loc, diag::warn_aligned_allocation_unavailable)
1690 << IsDelete << FD.getType().getAsString() << OSName
1691 << alignedAllocMinVersion(T.getOS()).getAsString();
1692 S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1693 }
1694}
1695
1696ExprResult
1697Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1698 SourceLocation PlacementLParen,
1699 MultiExprArg PlacementArgs,
1700 SourceLocation PlacementRParen,
1701 SourceRange TypeIdParens,
1702 QualType AllocType,
1703 TypeSourceInfo *AllocTypeInfo,
1704 Expr *ArraySize,
1705 SourceRange DirectInitRange,
1706 Expr *Initializer) {
1707 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1708 SourceLocation StartLoc = Range.getBegin();
1709
1710 CXXNewExpr::InitializationStyle initStyle;
1711 if (DirectInitRange.isValid()) {
1712 assert(Initializer && "Have parens but no initializer.")(static_cast <bool> (Initializer && "Have parens but no initializer."
) ? void (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1712, __extension__ __PRETTY_FUNCTION__))
;
1713 initStyle = CXXNewExpr::CallInit;
1714 } else if (Initializer && isa<InitListExpr>(Initializer))
1715 initStyle = CXXNewExpr::ListInit;
1716 else {
1717 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1719, __extension__ __PRETTY_FUNCTION__))
1718 isa<CXXConstructExpr>(Initializer)) &&(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1719, __extension__ __PRETTY_FUNCTION__))
1719 "Initializer expression that cannot have been implicitly created.")(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1719, __extension__ __PRETTY_FUNCTION__))
;
1720 initStyle = CXXNewExpr::NoInit;
1721 }
1722
1723 Expr **Inits = &Initializer;
1724 unsigned NumInits = Initializer ? 1 : 0;
1725 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1726 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")(static_cast <bool> (initStyle == CXXNewExpr::CallInit &&
"paren init for non-call init") ? void (0) : __assert_fail (
"initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1726, __extension__ __PRETTY_FUNCTION__))
;
1727 Inits = List->getExprs();
1728 NumInits = List->getNumExprs();
1729 }
1730
1731 // C++11 [expr.new]p15:
1732 // A new-expression that creates an object of type T initializes that
1733 // object as follows:
1734 InitializationKind Kind
1735 // - If the new-initializer is omitted, the object is default-
1736 // initialized (8.5); if no initialization is performed,
1737 // the object has indeterminate value
1738 = initStyle == CXXNewExpr::NoInit
1739 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1740 // - Otherwise, the new-initializer is interpreted according to the
1741 // initialization rules of 8.5 for direct-initialization.
1742 : initStyle == CXXNewExpr::ListInit
1743 ? InitializationKind::CreateDirectList(TypeRange.getBegin(),
1744 Initializer->getLocStart(),
1745 Initializer->getLocEnd())
1746 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1747 DirectInitRange.getBegin(),
1748 DirectInitRange.getEnd());
1749
1750 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1751 auto *Deduced = AllocType->getContainedDeducedType();
1752 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1753 if (ArraySize)
1754 return ExprError(Diag(ArraySize->getExprLoc(),
1755 diag::err_deduced_class_template_compound_type)
1756 << /*array*/ 2 << ArraySize->getSourceRange());
1757
1758 InitializedEntity Entity
1759 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1760 AllocType = DeduceTemplateSpecializationFromInitializer(
1761 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1762 if (AllocType.isNull())
1763 return ExprError();
1764 } else if (Deduced) {
1765 bool Braced = (initStyle == CXXNewExpr::ListInit);
1766 if (NumInits == 1) {
1767 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1768 Inits = p->getInits();
1769 NumInits = p->getNumInits();
1770 Braced = true;
1771 }
1772 }
1773
1774 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1775 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1776 << AllocType << TypeRange);
1777 if (NumInits > 1) {
1778 Expr *FirstBad = Inits[1];
1779 return ExprError(Diag(FirstBad->getLocStart(),
1780 diag::err_auto_new_ctor_multiple_expressions)
1781 << AllocType << TypeRange);
1782 }
1783 if (Braced && !getLangOpts().CPlusPlus17)
1784 Diag(Initializer->getLocStart(), diag::ext_auto_new_list_init)
1785 << AllocType << TypeRange;
1786 Expr *Deduce = Inits[0];
1787 QualType DeducedType;
1788 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1789 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1790 << AllocType << Deduce->getType()
1791 << TypeRange << Deduce->getSourceRange());
1792 if (DeducedType.isNull())
1793 return ExprError();
1794 AllocType = DeducedType;
1795 }
1796
1797 // Per C++0x [expr.new]p5, the type being constructed may be a
1798 // typedef of an array type.
1799 if (!ArraySize) {
1800 if (const ConstantArrayType *Array
1801 = Context.getAsConstantArrayType(AllocType)) {
1802 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1803 Context.getSizeType(),
1804 TypeRange.getEnd());
1805 AllocType = Array->getElementType();
1806 }
1807 }
1808
1809 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1810 return ExprError();
1811
1812 if (initStyle == CXXNewExpr::ListInit &&
1813 isStdInitializerList(AllocType, nullptr)) {
1814 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1815 diag::warn_dangling_std_initializer_list)
1816 << /*at end of FE*/0 << Inits[0]->getSourceRange();
1817 }
1818
1819 // In ARC, infer 'retaining' for the allocated
1820 if (getLangOpts().ObjCAutoRefCount &&
1821 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1822 AllocType->isObjCLifetimeType()) {
1823 AllocType = Context.getLifetimeQualifiedType(AllocType,
1824 AllocType->getObjCARCImplicitLifetime());
1825 }
1826
1827 QualType ResultType = Context.getPointerType(AllocType);
1828
1829 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1830 ExprResult result = CheckPlaceholderExpr(ArraySize);
1831 if (result.isInvalid()) return ExprError();
1832 ArraySize = result.get();
1833 }
1834 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1835 // integral or enumeration type with a non-negative value."
1836 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1837 // enumeration type, or a class type for which a single non-explicit
1838 // conversion function to integral or unscoped enumeration type exists.
1839 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1840 // std::size_t.
1841 llvm::Optional<uint64_t> KnownArraySize;
1842 if (ArraySize && !ArraySize->isTypeDependent()) {
1843 ExprResult ConvertedSize;
1844 if (getLangOpts().CPlusPlus14) {
1845 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")(static_cast <bool> (Context.getTargetInfo().getIntWidth
() && "Builtin type of size 0?") ? void (0) : __assert_fail
("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1845, __extension__ __PRETTY_FUNCTION__))
;
1846
1847 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1848 AA_Converting);
1849
1850 if (!ConvertedSize.isInvalid() &&
1851 ArraySize->getType()->getAs<RecordType>())
1852 // Diagnose the compatibility of this conversion.
1853 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1854 << ArraySize->getType() << 0 << "'size_t'";
1855 } else {
1856 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1857 protected:
1858 Expr *ArraySize;
1859
1860 public:
1861 SizeConvertDiagnoser(Expr *ArraySize)
1862 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1863 ArraySize(ArraySize) {}
1864
1865 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1866 QualType T) override {
1867 return S.Diag(Loc, diag::err_array_size_not_integral)
1868 << S.getLangOpts().CPlusPlus11 << T;
1869 }
1870
1871 SemaDiagnosticBuilder diagnoseIncomplete(
1872 Sema &S, SourceLocation Loc, QualType T) override {
1873 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1874 << T << ArraySize->getSourceRange();
1875 }
1876
1877 SemaDiagnosticBuilder diagnoseExplicitConv(
1878 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1879 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1880 }
1881
1882 SemaDiagnosticBuilder noteExplicitConv(
1883 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1884 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1885 << ConvTy->isEnumeralType() << ConvTy;
1886 }
1887
1888 SemaDiagnosticBuilder diagnoseAmbiguous(
1889 Sema &S, SourceLocation Loc, QualType T) override {
1890 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1891 }
1892
1893 SemaDiagnosticBuilder noteAmbiguous(
1894 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1895 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1896 << ConvTy->isEnumeralType() << ConvTy;
1897 }
1898
1899 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1900 QualType T,
1901 QualType ConvTy) override {
1902 return S.Diag(Loc,
1903 S.getLangOpts().CPlusPlus11
1904 ? diag::warn_cxx98_compat_array_size_conversion
1905 : diag::ext_array_size_conversion)
1906 << T << ConvTy->isEnumeralType() << ConvTy;
1907 }
1908 } SizeDiagnoser(ArraySize);
1909
1910 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1911 SizeDiagnoser);
1912 }
1913 if (ConvertedSize.isInvalid())
1914 return ExprError();
1915
1916 ArraySize = ConvertedSize.get();
1917 QualType SizeType = ArraySize->getType();
1918
1919 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1920 return ExprError();
1921
1922 // C++98 [expr.new]p7:
1923 // The expression in a direct-new-declarator shall have integral type
1924 // with a non-negative value.
1925 //
1926 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1927 // per CWG1464. Otherwise, if it's not a constant, we must have an
1928 // unparenthesized array type.
1929 if (!ArraySize->isValueDependent()) {
1930 llvm::APSInt Value;
1931 // We've already performed any required implicit conversion to integer or
1932 // unscoped enumeration type.
1933 // FIXME: Per CWG1464, we are required to check the value prior to
1934 // converting to size_t. This will never find a negative array size in
1935 // C++14 onwards, because Value is always unsigned here!
1936 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1937 if (Value.isSigned() && Value.isNegative()) {
1938 return ExprError(Diag(ArraySize->getLocStart(),
1939 diag::err_typecheck_negative_array_size)
1940 << ArraySize->getSourceRange());
1941 }
1942
1943 if (!AllocType->isDependentType()) {
1944 unsigned ActiveSizeBits =
1945 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1946 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1947 return ExprError(Diag(ArraySize->getLocStart(),
1948 diag::err_array_too_large)
1949 << Value.toString(10)
1950 << ArraySize->getSourceRange());
1951 }
1952
1953 KnownArraySize = Value.getZExtValue();
1954 } else if (TypeIdParens.isValid()) {
1955 // Can't have dynamic array size when the type-id is in parentheses.
1956 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1957 << ArraySize->getSourceRange()
1958 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1959 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1960
1961 TypeIdParens = SourceRange();
1962 }
1963 }
1964
1965 // Note that we do *not* convert the argument in any way. It can
1966 // be signed, larger than size_t, whatever.
1967 }
1968
1969 FunctionDecl *OperatorNew = nullptr;
1970 FunctionDecl *OperatorDelete = nullptr;
1971 unsigned Alignment =
1972 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1973 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1974 bool PassAlignment = getLangOpts().AlignedAllocation &&
1975 Alignment > NewAlignment;
1976
1977 if (!AllocType->isDependentType() &&
1978 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1979 FindAllocationFunctions(StartLoc,
1980 SourceRange(PlacementLParen, PlacementRParen),
1981 UseGlobal, AllocType, ArraySize, PassAlignment,
1982 PlacementArgs, OperatorNew, OperatorDelete))
1983 return ExprError();
1984
1985 // If this is an array allocation, compute whether the usual array
1986 // deallocation function for the type has a size_t parameter.
1987 bool UsualArrayDeleteWantsSize = false;
1988 if (ArraySize && !AllocType->isDependentType())
1989 UsualArrayDeleteWantsSize =
1990 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1991
1992 SmallVector<Expr *, 8> AllPlaceArgs;
1993 if (OperatorNew) {
1994 const FunctionProtoType *Proto =
1995 OperatorNew->getType()->getAs<FunctionProtoType>();
1996 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1997 : VariadicDoesNotApply;
1998
1999 // We've already converted the placement args, just fill in any default
2000 // arguments. Skip the first parameter because we don't have a corresponding
2001 // argument. Skip the second parameter too if we're passing in the
2002 // alignment; we've already filled it in.
2003 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2004 PassAlignment ? 2 : 1, PlacementArgs,
2005 AllPlaceArgs, CallType))
2006 return ExprError();
2007
2008 if (!AllPlaceArgs.empty())
2009 PlacementArgs = AllPlaceArgs;
2010
2011 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2012 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2013
2014 // FIXME: Missing call to CheckFunctionCall or equivalent
2015
2016 // Warn if the type is over-aligned and is being allocated by (unaligned)
2017 // global operator new.
2018 if (PlacementArgs.empty() && !PassAlignment &&
2019 (OperatorNew->isImplicit() ||
2020 (OperatorNew->getLocStart().isValid() &&
2021 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
2022 if (Alignment > NewAlignment)
2023 Diag(StartLoc, diag::warn_overaligned_type)
2024 << AllocType
2025 << unsigned(Alignment / Context.getCharWidth())
2026 << unsigned(NewAlignment / Context.getCharWidth());
2027 }
2028 }
2029
2030 // Array 'new' can't have any initializers except empty parentheses.
2031 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2032 // dialect distinction.
2033 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2034 SourceRange InitRange(Inits[0]->getLocStart(),
2035 Inits[NumInits - 1]->getLocEnd());
2036 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2037 return ExprError();
2038 }
2039
2040 // If we can perform the initialization, and we've not already done so,
2041 // do it now.
2042 if (!AllocType->isDependentType() &&
2043 !Expr::hasAnyTypeDependentArguments(
2044 llvm::makeArrayRef(Inits, NumInits))) {
2045 // The type we initialize is the complete type, including the array bound.
2046 QualType InitType;
2047 if (KnownArraySize)
2048 InitType = Context.getConstantArrayType(
2049 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2050 *KnownArraySize),
2051 ArrayType::Normal, 0);
2052 else if (ArraySize)
2053 InitType =
2054 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2055 else
2056 InitType = AllocType;
2057
2058 InitializedEntity Entity
2059 = InitializedEntity::InitializeNew(StartLoc, InitType);
2060 InitializationSequence InitSeq(*this, Entity, Kind,
2061 MultiExprArg(Inits, NumInits));
2062 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2063 MultiExprArg(Inits, NumInits));
2064 if (FullInit.isInvalid())
2065 return ExprError();
2066
2067 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2068 // we don't want the initialized object to be destructed.
2069 // FIXME: We should not create these in the first place.
2070 if (CXXBindTemporaryExpr *Binder =
2071 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2072 FullInit = Binder->getSubExpr();
2073
2074 Initializer = FullInit.get();
2075 }
2076
2077 // Mark the new and delete operators as referenced.
2078 if (OperatorNew) {
2079 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2080 return ExprError();
2081 MarkFunctionReferenced(StartLoc, OperatorNew);
2082 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
2083 }
2084 if (OperatorDelete) {
2085 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2086 return ExprError();
2087 MarkFunctionReferenced(StartLoc, OperatorDelete);
2088 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
2089 }
2090
2091 // C++0x [expr.new]p17:
2092 // If the new expression creates an array of objects of class type,
2093 // access and ambiguity control are done for the destructor.
2094 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2095 if (ArraySize && !BaseAllocType->isDependentType()) {
2096 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2097 if (CXXDestructorDecl *dtor = LookupDestructor(
2098 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2099 MarkFunctionReferenced(StartLoc, dtor);
2100 CheckDestructorAccess(StartLoc, dtor,
2101 PDiag(diag::err_access_dtor)
2102 << BaseAllocType);
2103 if (DiagnoseUseOfDecl(dtor, StartLoc))
2104 return ExprError();
2105 }
2106 }
2107 }
2108
2109 return new (Context)
2110 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
2111 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2112 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2113 Range, DirectInitRange);
2114}
2115
2116/// \brief Checks that a type is suitable as the allocated type
2117/// in a new-expression.
2118bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2119 SourceRange R) {
2120 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2121 // abstract class type or array thereof.
2122 if (AllocType->isFunctionType())
2123 return Diag(Loc, diag::err_bad_new_type)
2124 << AllocType << 0 << R;
2125 else if (AllocType->isReferenceType())
2126 return Diag(Loc, diag::err_bad_new_type)
2127 << AllocType << 1 << R;
2128 else if (!AllocType->isDependentType() &&
2129 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2130 return true;
2131 else if (RequireNonAbstractType(Loc, AllocType,
2132 diag::err_allocation_of_abstract_type))
2133 return true;
2134 else if (AllocType->isVariablyModifiedType())
2135 return Diag(Loc, diag::err_variably_modified_new_type)
2136 << AllocType;
2137 else if (AllocType.getAddressSpace() != LangAS::Default)
2138 return Diag(Loc, diag::err_address_space_qualified_new)
2139 << AllocType.getUnqualifiedType()
2140 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2141 else if (getLangOpts().ObjCAutoRefCount) {
2142 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2143 QualType BaseAllocType = Context.getBaseElementType(AT);
2144 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2145 BaseAllocType->isObjCLifetimeType())
2146 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2147 << BaseAllocType;
2148 }
2149 }
2150
2151 return false;
2152}
2153
2154static bool
2155resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2156 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2157 FunctionDecl *&Operator,
2158 OverloadCandidateSet *AlignedCandidates = nullptr,
2159 Expr *AlignArg = nullptr) {
2160 OverloadCandidateSet Candidates(R.getNameLoc(),
2161 OverloadCandidateSet::CSK_Normal);
2162 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2163 Alloc != AllocEnd; ++Alloc) {
2164 // Even member operator new/delete are implicitly treated as
2165 // static, so don't use AddMemberCandidate.
2166 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2167
2168 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2169 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2170 /*ExplicitTemplateArgs=*/nullptr, Args,
2171 Candidates,
2172 /*SuppressUserConversions=*/false);
2173 continue;
2174 }
2175
2176 FunctionDecl *Fn = cast<FunctionDecl>(D);
2177 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2178 /*SuppressUserConversions=*/false);
2179 }
2180
2181 // Do the resolution.
2182 OverloadCandidateSet::iterator Best;
2183 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2184 case OR_Success: {
2185 // Got one!
2186 FunctionDecl *FnDecl = Best->Function;
2187 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2188 Best->FoundDecl) == Sema::AR_inaccessible)
2189 return true;
2190
2191 Operator = FnDecl;
2192 return false;
2193 }
2194
2195 case OR_No_Viable_Function:
2196 // C++17 [expr.new]p13:
2197 // If no matching function is found and the allocated object type has
2198 // new-extended alignment, the alignment argument is removed from the
2199 // argument list, and overload resolution is performed again.
2200 if (PassAlignment) {
2201 PassAlignment = false;
2202 AlignArg = Args[1];
2203 Args.erase(Args.begin() + 1);
2204 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2205 Operator, &Candidates, AlignArg);
2206 }
2207
2208 // MSVC will fall back on trying to find a matching global operator new
2209 // if operator new[] cannot be found. Also, MSVC will leak by not
2210 // generating a call to operator delete or operator delete[], but we
2211 // will not replicate that bug.
2212 // FIXME: Find out how this interacts with the std::align_val_t fallback
2213 // once MSVC implements it.
2214 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2215 S.Context.getLangOpts().MSVCCompat) {
2216 R.clear();
2217 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2218 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2219 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2220 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2221 Operator, nullptr);
2222 }
2223
2224 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2225 << R.getLookupName() << Range;
2226
2227 // If we have aligned candidates, only note the align_val_t candidates
2228 // from AlignedCandidates and the non-align_val_t candidates from
2229 // Candidates.
2230 if (AlignedCandidates) {
2231 auto IsAligned = [](OverloadCandidate &C) {
2232 return C.Function->getNumParams() > 1 &&
2233 C.Function->getParamDecl(1)->getType()->isAlignValT();
2234 };
2235 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2236
2237 // This was an overaligned allocation, so list the aligned candidates
2238 // first.
2239 Args.insert(Args.begin() + 1, AlignArg);
2240 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2241 R.getNameLoc(), IsAligned);
2242 Args.erase(Args.begin() + 1);
2243 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2244 IsUnaligned);
2245 } else {
2246 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2247 }
2248 return true;
2249
2250 case OR_Ambiguous:
2251 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2252 << R.getLookupName() << Range;
2253 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2254 return true;
2255
2256 case OR_Deleted: {
2257 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2258 << Best->Function->isDeleted()
2259 << R.getLookupName()
2260 << S.getDeletedOrUnavailableSuffix(Best->Function)
2261 << Range;
2262 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2263 return true;
2264 }
2265 }
2266 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2266)
;
2267}
2268
2269
2270/// FindAllocationFunctions - Finds the overloads of operator new and delete
2271/// that are appropriate for the allocation.
2272bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2273 bool UseGlobal, QualType AllocType,
2274 bool IsArray, bool &PassAlignment,
2275 MultiExprArg PlaceArgs,
2276 FunctionDecl *&OperatorNew,
2277 FunctionDecl *&OperatorDelete) {
2278 // --- Choosing an allocation function ---
2279 // C++ 5.3.4p8 - 14 & 18
2280 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2281 // in the scope of the allocated class.
2282 // 2) If an array size is given, look for operator new[], else look for
2283 // operator new.
2284 // 3) The first argument is always size_t. Append the arguments from the
2285 // placement form.
2286
2287 SmallVector<Expr*, 8> AllocArgs;
2288 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2289
2290 // We don't care about the actual value of these arguments.
2291 // FIXME: Should the Sema create the expression and embed it in the syntax
2292 // tree? Or should the consumer just recalculate the value?
2293 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2294 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2295 Context.getTargetInfo().getPointerWidth(0)),
2296 Context.getSizeType(),
2297 SourceLocation());
2298 AllocArgs.push_back(&Size);
2299
2300 QualType AlignValT = Context.VoidTy;
2301 if (PassAlignment) {
2302 DeclareGlobalNewDelete();
2303 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2304 }
2305 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2306 if (PassAlignment)
2307 AllocArgs.push_back(&Align);
2308
2309 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2310
2311 // C++ [expr.new]p8:
2312 // If the allocated type is a non-array type, the allocation
2313 // function's name is operator new and the deallocation function's
2314 // name is operator delete. If the allocated type is an array
2315 // type, the allocation function's name is operator new[] and the
2316 // deallocation function's name is operator delete[].
2317 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2318 IsArray ? OO_Array_New : OO_New);
2319
2320 QualType AllocElemType = Context.getBaseElementType(AllocType);
2321
2322 // Find the allocation function.
2323 {
2324 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2325
2326 // C++1z [expr.new]p9:
2327 // If the new-expression begins with a unary :: operator, the allocation
2328 // function's name is looked up in the global scope. Otherwise, if the
2329 // allocated type is a class type T or array thereof, the allocation
2330 // function's name is looked up in the scope of T.
2331 if (AllocElemType->isRecordType() && !UseGlobal)
2332 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2333
2334 // We can see ambiguity here if the allocation function is found in
2335 // multiple base classes.
2336 if (R.isAmbiguous())
2337 return true;
2338
2339 // If this lookup fails to find the name, or if the allocated type is not
2340 // a class type, the allocation function's name is looked up in the
2341 // global scope.
2342 if (R.empty())
2343 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2344
2345 assert(!R.empty() && "implicitly declared allocation functions not found")(static_cast <bool> (!R.empty() && "implicitly declared allocation functions not found"
) ? void (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2345, __extension__ __PRETTY_FUNCTION__))
;
2346 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")(static_cast <bool> (!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2346, __extension__ __PRETTY_FUNCTION__))
;
2347
2348 // We do our own custom access checks below.
2349 R.suppressDiagnostics();
2350
2351 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2352 OperatorNew))
2353 return true;
2354 }
2355
2356 // We don't need an operator delete if we're running under -fno-exceptions.
2357 if (!getLangOpts().Exceptions) {
2358 OperatorDelete = nullptr;
2359 return false;
2360 }
2361
2362 // Note, the name of OperatorNew might have been changed from array to
2363 // non-array by resolveAllocationOverload.
2364 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2365 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2366 ? OO_Array_Delete
2367 : OO_Delete);
2368
2369 // C++ [expr.new]p19:
2370 //
2371 // If the new-expression begins with a unary :: operator, the
2372 // deallocation function's name is looked up in the global
2373 // scope. Otherwise, if the allocated type is a class type T or an
2374 // array thereof, the deallocation function's name is looked up in
2375 // the scope of T. If this lookup fails to find the name, or if
2376 // the allocated type is not a class type or array thereof, the
2377 // deallocation function's name is looked up in the global scope.
2378 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2379 if (AllocElemType->isRecordType() && !UseGlobal) {
2380 CXXRecordDecl *RD
2381 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2382 LookupQualifiedName(FoundDelete, RD);
2383 }
2384 if (FoundDelete.isAmbiguous())
2385 return true; // FIXME: clean up expressions?
2386
2387 bool FoundGlobalDelete = FoundDelete.empty();
2388 if (FoundDelete.empty()) {
2389 DeclareGlobalNewDelete();
2390 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2391 }
2392
2393 FoundDelete.suppressDiagnostics();
2394
2395 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2396
2397 // Whether we're looking for a placement operator delete is dictated
2398 // by whether we selected a placement operator new, not by whether
2399 // we had explicit placement arguments. This matters for things like
2400 // struct A { void *operator new(size_t, int = 0); ... };
2401 // A *a = new A()
2402 //
2403 // We don't have any definition for what a "placement allocation function"
2404 // is, but we assume it's any allocation function whose
2405 // parameter-declaration-clause is anything other than (size_t).
2406 //
2407 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2408 // This affects whether an exception from the constructor of an overaligned
2409 // type uses the sized or non-sized form of aligned operator delete.
2410 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2411 OperatorNew->isVariadic();
2412
2413 if (isPlacementNew) {
2414 // C++ [expr.new]p20:
2415 // A declaration of a placement deallocation function matches the
2416 // declaration of a placement allocation function if it has the
2417 // same number of parameters and, after parameter transformations
2418 // (8.3.5), all parameter types except the first are
2419 // identical. [...]
2420 //
2421 // To perform this comparison, we compute the function type that
2422 // the deallocation function should have, and use that type both
2423 // for template argument deduction and for comparison purposes.
2424 QualType ExpectedFunctionType;
2425 {
2426 const FunctionProtoType *Proto
2427 = OperatorNew->getType()->getAs<FunctionProtoType>();
2428
2429 SmallVector<QualType, 4> ArgTypes;
2430 ArgTypes.push_back(Context.VoidPtrTy);
2431 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2432 ArgTypes.push_back(Proto->getParamType(I));
2433
2434 FunctionProtoType::ExtProtoInfo EPI;
2435 // FIXME: This is not part of the standard's rule.
2436 EPI.Variadic = Proto->isVariadic();
2437
2438 ExpectedFunctionType
2439 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2440 }
2441
2442 for (LookupResult::iterator D = FoundDelete.begin(),
2443 DEnd = FoundDelete.end();
2444 D != DEnd; ++D) {
2445 FunctionDecl *Fn = nullptr;
2446 if (FunctionTemplateDecl *FnTmpl =
2447 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2448 // Perform template argument deduction to try to match the
2449 // expected function type.
2450 TemplateDeductionInfo Info(StartLoc);
2451 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2452 Info))
2453 continue;
2454 } else
2455 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2456
2457 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2458 ExpectedFunctionType,
2459 /*AdjustExcpetionSpec*/true),
2460 ExpectedFunctionType))
2461 Matches.push_back(std::make_pair(D.getPair(), Fn));
2462 }
2463
2464 if (getLangOpts().CUDA)
2465 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2466 } else {
2467 // C++1y [expr.new]p22:
2468 // For a non-placement allocation function, the normal deallocation
2469 // function lookup is used
2470 //
2471 // Per [expr.delete]p10, this lookup prefers a member operator delete
2472 // without a size_t argument, but prefers a non-member operator delete
2473 // with a size_t where possible (which it always is in this case).
2474 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2475 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2476 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2477 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2478 &BestDeallocFns);
2479 if (Selected)
2480 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2481 else {
2482 // If we failed to select an operator, all remaining functions are viable
2483 // but ambiguous.
2484 for (auto Fn : BestDeallocFns)
2485 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2486 }
2487 }
2488
2489 // C++ [expr.new]p20:
2490 // [...] If the lookup finds a single matching deallocation
2491 // function, that function will be called; otherwise, no
2492 // deallocation function will be called.
2493 if (Matches.size() == 1) {
2494 OperatorDelete = Matches[0].second;
2495
2496 // C++1z [expr.new]p23:
2497 // If the lookup finds a usual deallocation function (3.7.4.2)
2498 // with a parameter of type std::size_t and that function, considered
2499 // as a placement deallocation function, would have been
2500 // selected as a match for the allocation function, the program
2501 // is ill-formed.
2502 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2503 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2504 UsualDeallocFnInfo Info(*this,
2505 DeclAccessPair::make(OperatorDelete, AS_public));
2506 // Core issue, per mail to core reflector, 2016-10-09:
2507 // If this is a member operator delete, and there is a corresponding
2508 // non-sized member operator delete, this isn't /really/ a sized
2509 // deallocation function, it just happens to have a size_t parameter.
2510 bool IsSizedDelete = Info.HasSizeT;
2511 if (IsSizedDelete && !FoundGlobalDelete) {
2512 auto NonSizedDelete =
2513 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2514 /*WantAlign*/Info.HasAlignValT);
2515 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2516 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2517 IsSizedDelete = false;
2518 }
2519
2520 if (IsSizedDelete) {
2521 SourceRange R = PlaceArgs.empty()
2522 ? SourceRange()
2523 : SourceRange(PlaceArgs.front()->getLocStart(),
2524 PlaceArgs.back()->getLocEnd());
2525 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2526 if (!OperatorDelete->isImplicit())
2527 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2528 << DeleteName;
2529 }
2530 }
2531
2532 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2533 Matches[0].first);
2534 } else if (!Matches.empty()) {
2535 // We found multiple suitable operators. Per [expr.new]p20, that means we
2536 // call no 'operator delete' function, but we should at least warn the user.
2537 // FIXME: Suppress this warning if the construction cannot throw.
2538 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2539 << DeleteName << AllocElemType;
2540
2541 for (auto &Match : Matches)
2542 Diag(Match.second->getLocation(),
2543 diag::note_member_declared_here) << DeleteName;
2544 }
2545
2546 return false;
2547}
2548
2549/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2550/// delete. These are:
2551/// @code
2552/// // C++03:
2553/// void* operator new(std::size_t) throw(std::bad_alloc);
2554/// void* operator new[](std::size_t) throw(std::bad_alloc);
2555/// void operator delete(void *) throw();
2556/// void operator delete[](void *) throw();
2557/// // C++11:
2558/// void* operator new(std::size_t);
2559/// void* operator new[](std::size_t);
2560/// void operator delete(void *) noexcept;
2561/// void operator delete[](void *) noexcept;
2562/// // C++1y:
2563/// void* operator new(std::size_t);
2564/// void* operator new[](std::size_t);
2565/// void operator delete(void *) noexcept;
2566/// void operator delete[](void *) noexcept;
2567/// void operator delete(void *, std::size_t) noexcept;
2568/// void operator delete[](void *, std::size_t) noexcept;
2569/// @endcode
2570/// Note that the placement and nothrow forms of new are *not* implicitly
2571/// declared. Their use requires including \<new\>.
2572void Sema::DeclareGlobalNewDelete() {
2573 if (GlobalNewDeleteDeclared)
2574 return;
2575
2576 // C++ [basic.std.dynamic]p2:
2577 // [...] The following allocation and deallocation functions (18.4) are
2578 // implicitly declared in global scope in each translation unit of a
2579 // program
2580 //
2581 // C++03:
2582 // void* operator new(std::size_t) throw(std::bad_alloc);
2583 // void* operator new[](std::size_t) throw(std::bad_alloc);
2584 // void operator delete(void*) throw();
2585 // void operator delete[](void*) throw();
2586 // C++11:
2587 // void* operator new(std::size_t);
2588 // void* operator new[](std::size_t);
2589 // void operator delete(void*) noexcept;
2590 // void operator delete[](void*) noexcept;
2591 // C++1y:
2592 // void* operator new(std::size_t);
2593 // void* operator new[](std::size_t);
2594 // void operator delete(void*) noexcept;
2595 // void operator delete[](void*) noexcept;
2596 // void operator delete(void*, std::size_t) noexcept;
2597 // void operator delete[](void*, std::size_t) noexcept;
2598 //
2599 // These implicit declarations introduce only the function names operator
2600 // new, operator new[], operator delete, operator delete[].
2601 //
2602 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2603 // "std" or "bad_alloc" as necessary to form the exception specification.
2604 // However, we do not make these implicit declarations visible to name
2605 // lookup.
2606 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2607 // The "std::bad_alloc" class has not yet been declared, so build it
2608 // implicitly.
2609 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2610 getOrCreateStdNamespace(),
2611 SourceLocation(), SourceLocation(),
2612 &PP.getIdentifierTable().get("bad_alloc"),
2613 nullptr);
2614 getStdBadAlloc()->setImplicit(true);
2615 }
2616 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2617 // The "std::align_val_t" enum class has not yet been declared, so build it
2618 // implicitly.
2619 auto *AlignValT = EnumDecl::Create(
2620 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2621 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2622 AlignValT->setIntegerType(Context.getSizeType());
2623 AlignValT->setPromotionType(Context.getSizeType());
2624 AlignValT->setImplicit(true);
2625 StdAlignValT = AlignValT;
2626 }
2627
2628 GlobalNewDeleteDeclared = true;
2629
2630 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2631 QualType SizeT = Context.getSizeType();
2632
2633 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2634 QualType Return, QualType Param) {
2635 llvm::SmallVector<QualType, 3> Params;
2636 Params.push_back(Param);
2637
2638 // Create up to four variants of the function (sized/aligned).
2639 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2640 (Kind == OO_Delete || Kind == OO_Array_Delete);
2641 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2642
2643 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2644 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2645 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2646 if (Sized)
2647 Params.push_back(SizeT);
2648
2649 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2650 if (Aligned)
2651 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2652
2653 DeclareGlobalAllocationFunction(
2654 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2655
2656 if (Aligned)
2657 Params.pop_back();
2658 }
2659 }
2660 };
2661
2662 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2663 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2664 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2665 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2666}
2667
2668/// DeclareGlobalAllocationFunction - Declares a single implicit global
2669/// allocation function if it doesn't already exist.
2670void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2671 QualType Return,
2672 ArrayRef<QualType> Params) {
2673 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2674
2675 // Check if this function is already declared.
2676 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2677 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2678 Alloc != AllocEnd; ++Alloc) {
2679 // Only look at non-template functions, as it is the predefined,
2680 // non-templated allocation function we are trying to declare here.
2681 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2682 if (Func->getNumParams() == Params.size()) {
2683 llvm::SmallVector<QualType, 3> FuncParams;
2684 for (auto *P : Func->parameters())
2685 FuncParams.push_back(
2686 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2687 if (llvm::makeArrayRef(FuncParams) == Params) {
2688 // Make the function visible to name lookup, even if we found it in
2689 // an unimported module. It either is an implicitly-declared global
2690 // allocation function, or is suppressing that function.
2691 Func->setVisibleDespiteOwningModule();
2692 return;
2693 }
2694 }
2695 }
2696 }
2697
2698 FunctionProtoType::ExtProtoInfo EPI;
2699
2700 QualType BadAllocType;
2701 bool HasBadAllocExceptionSpec
2702 = (Name.getCXXOverloadedOperator() == OO_New ||
2703 Name.getCXXOverloadedOperator() == OO_Array_New);
2704 if (HasBadAllocExceptionSpec) {
2705 if (!getLangOpts().CPlusPlus11) {
2706 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2707 assert(StdBadAlloc && "Must have std::bad_alloc declared")(static_cast <bool> (StdBadAlloc && "Must have std::bad_alloc declared"
) ? void (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2707, __extension__ __PRETTY_FUNCTION__))
;
2708 EPI.ExceptionSpec.Type = EST_Dynamic;
2709 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2710 }
2711 } else {
2712 EPI.ExceptionSpec =
2713 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2714 }
2715
2716 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2717 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2718 FunctionDecl *Alloc = FunctionDecl::Create(
2719 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2720 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2721 Alloc->setImplicit();
2722 // Global allocation functions should always be visible.
2723 Alloc->setVisibleDespiteOwningModule();
2724
2725 // Implicit sized deallocation functions always have default visibility.
2726 Alloc->addAttr(
2727 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
2728
2729 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2730 for (QualType T : Params) {
2731 ParamDecls.push_back(ParmVarDecl::Create(
2732 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2733 /*TInfo=*/nullptr, SC_None, nullptr));
2734 ParamDecls.back()->setImplicit();
2735 }
2736 Alloc->setParams(ParamDecls);
2737 if (ExtraAttr)
2738 Alloc->addAttr(ExtraAttr);
2739 Context.getTranslationUnitDecl()->addDecl(Alloc);
2740 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2741 };
2742
2743 if (!LangOpts.CUDA)
2744 CreateAllocationFunctionDecl(nullptr);
2745 else {
2746 // Host and device get their own declaration so each can be
2747 // defined or re-declared independently.
2748 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2749 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2750 }
2751}
2752
2753FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2754 bool CanProvideSize,
2755 bool Overaligned,
2756 DeclarationName Name) {
2757 DeclareGlobalNewDelete();
2758
2759 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2760 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2761
2762 // FIXME: It's possible for this to result in ambiguity, through a
2763 // user-declared variadic operator delete or the enable_if attribute. We
2764 // should probably not consider those cases to be usual deallocation
2765 // functions. But for now we just make an arbitrary choice in that case.
2766 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2767 Overaligned);
2768 assert(Result.FD && "operator delete missing from global scope?")(static_cast <bool> (Result.FD && "operator delete missing from global scope?"
) ? void (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2768, __extension__ __PRETTY_FUNCTION__))
;
2769 return Result.FD;
2770}
2771
2772FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2773 CXXRecordDecl *RD) {
2774 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2775
2776 FunctionDecl *OperatorDelete = nullptr;
2777 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2778 return nullptr;
2779 if (OperatorDelete)
2780 return OperatorDelete;
2781
2782 // If there's no class-specific operator delete, look up the global
2783 // non-array delete.
2784 return FindUsualDeallocationFunction(
2785 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2786 Name);
2787}
2788
2789bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2790 DeclarationName Name,
2791 FunctionDecl *&Operator, bool Diagnose) {
2792 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2793 // Try to find operator delete/operator delete[] in class scope.
2794 LookupQualifiedName(Found, RD);
2795
2796 if (Found.isAmbiguous())
2797 return true;
2798
2799 Found.suppressDiagnostics();
2800
2801 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2802
2803 // C++17 [expr.delete]p10:
2804 // If the deallocation functions have class scope, the one without a
2805 // parameter of type std::size_t is selected.
2806 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2807 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2808 /*WantAlign*/ Overaligned, &Matches);
2809
2810 // If we could find an overload, use it.
2811 if (Matches.size() == 1) {
2812 Operator = cast<CXXMethodDecl>(Matches[0].FD);
2813
2814 // FIXME: DiagnoseUseOfDecl?
2815 if (Operator->isDeleted()) {
2816 if (Diagnose) {
2817 Diag(StartLoc, diag::err_deleted_function_use);
2818 NoteDeletedFunction(Operator);
2819 }
2820 return true;
2821 }
2822
2823 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2824 Matches[0].Found, Diagnose) == AR_inaccessible)
2825 return true;
2826
2827 return false;
2828 }
2829
2830 // We found multiple suitable operators; complain about the ambiguity.
2831 // FIXME: The standard doesn't say to do this; it appears that the intent
2832 // is that this should never happen.
2833 if (!Matches.empty()) {
2834 if (Diagnose) {
2835 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2836 << Name << RD;
2837 for (auto &Match : Matches)
2838 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2839 }
2840 return true;
2841 }
2842
2843 // We did find operator delete/operator delete[] declarations, but
2844 // none of them were suitable.
2845 if (!Found.empty()) {
2846 if (Diagnose) {
2847 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2848 << Name << RD;
2849
2850 for (NamedDecl *D : Found)
2851 Diag(D->getUnderlyingDecl()->getLocation(),
2852 diag::note_member_declared_here) << Name;
2853 }
2854 return true;
2855 }
2856
2857 Operator = nullptr;
2858 return false;
2859}
2860
2861namespace {
2862/// \brief Checks whether delete-expression, and new-expression used for
2863/// initializing deletee have the same array form.
2864class MismatchingNewDeleteDetector {
2865public:
2866 enum MismatchResult {
2867 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2868 NoMismatch,
2869 /// Indicates that variable is initialized with mismatching form of \a new.
2870 VarInitMismatches,
2871 /// Indicates that member is initialized with mismatching form of \a new.
2872 MemberInitMismatches,
2873 /// Indicates that 1 or more constructors' definitions could not been
2874 /// analyzed, and they will be checked again at the end of translation unit.
2875 AnalyzeLater
2876 };
2877
2878 /// \param EndOfTU True, if this is the final analysis at the end of
2879 /// translation unit. False, if this is the initial analysis at the point
2880 /// delete-expression was encountered.
2881 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2882 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2883 HasUndefinedConstructors(false) {}
2884
2885 /// \brief Checks whether pointee of a delete-expression is initialized with
2886 /// matching form of new-expression.
2887 ///
2888 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2889 /// point where delete-expression is encountered, then a warning will be
2890 /// issued immediately. If return value is \c AnalyzeLater at the point where
2891 /// delete-expression is seen, then member will be analyzed at the end of
2892 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2893 /// couldn't be analyzed. If at least one constructor initializes the member
2894 /// with matching type of new, the return value is \c NoMismatch.
2895 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2896 /// \brief Analyzes a class member.
2897 /// \param Field Class member to analyze.
2898 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2899 /// for deleting the \p Field.
2900 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2901 FieldDecl *Field;
2902 /// List of mismatching new-expressions used for initialization of the pointee
2903 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2904 /// Indicates whether delete-expression was in array form.
2905 bool IsArrayForm;
2906
2907private:
2908 const bool EndOfTU;
2909 /// \brief Indicates that there is at least one constructor without body.
2910 bool HasUndefinedConstructors;
2911 /// \brief Returns \c CXXNewExpr from given initialization expression.
2912 /// \param E Expression used for initializing pointee in delete-expression.
2913 /// E can be a single-element \c InitListExpr consisting of new-expression.
2914 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2915 /// \brief Returns whether member is initialized with mismatching form of
2916 /// \c new either by the member initializer or in-class initialization.
2917 ///
2918 /// If bodies of all constructors are not visible at the end of translation
2919 /// unit or at least one constructor initializes member with the matching
2920 /// form of \c new, mismatch cannot be proven, and this function will return
2921 /// \c NoMismatch.
2922 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2923 /// \brief Returns whether variable is initialized with mismatching form of
2924 /// \c new.
2925 ///
2926 /// If variable is initialized with matching form of \c new or variable is not
2927 /// initialized with a \c new expression, this function will return true.
2928 /// If variable is initialized with mismatching form of \c new, returns false.
2929 /// \param D Variable to analyze.
2930 bool hasMatchingVarInit(const DeclRefExpr *D);
2931 /// \brief Checks whether the constructor initializes pointee with mismatching
2932 /// form of \c new.
2933 ///
2934 /// Returns true, if member is initialized with matching form of \c new in
2935 /// member initializer list. Returns false, if member is initialized with the
2936 /// matching form of \c new in this constructor's initializer or given
2937 /// constructor isn't defined at the point where delete-expression is seen, or
2938 /// member isn't initialized by the constructor.
2939 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2940 /// \brief Checks whether member is initialized with matching form of
2941 /// \c new in member initializer list.
2942 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2943 /// Checks whether member is initialized with mismatching form of \c new by
2944 /// in-class initializer.
2945 MismatchResult analyzeInClassInitializer();
2946};
2947}
2948
2949MismatchingNewDeleteDetector::MismatchResult
2950MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2951 NewExprs.clear();
2952 assert(DE && "Expected delete-expression")(static_cast <bool> (DE && "Expected delete-expression"
) ? void (0) : __assert_fail ("DE && \"Expected delete-expression\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2952, __extension__ __PRETTY_FUNCTION__))
;
2953 IsArrayForm = DE->isArrayForm();
2954 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2955 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2956 return analyzeMemberExpr(ME);
2957 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2958 if (!hasMatchingVarInit(D))
2959 return VarInitMismatches;
2960 }
2961 return NoMismatch;
2962}
2963
2964const CXXNewExpr *
2965MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2966 assert(E != nullptr && "Expected a valid initializer expression")(static_cast <bool> (E != nullptr && "Expected a valid initializer expression"
) ? void (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2966, __extension__ __PRETTY_FUNCTION__))
;
2967 E = E->IgnoreParenImpCasts();
2968 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2969 if (ILE->getNumInits() == 1)
2970 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2971 }
2972
2973 return dyn_cast_or_null<const CXXNewExpr>(E);
2974}
2975
2976bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2977 const CXXCtorInitializer *CI) {
2978 const CXXNewExpr *NE = nullptr;
2979 if (Field == CI->getMember() &&
2980 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2981 if (NE->isArray() == IsArrayForm)
2982 return true;
2983 else
2984 NewExprs.push_back(NE);
2985 }
2986 return false;
2987}
2988
2989bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2990 const CXXConstructorDecl *CD) {
2991 if (CD->isImplicit())
2992 return false;
2993 const FunctionDecl *Definition = CD;
2994 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2995 HasUndefinedConstructors = true;
2996 return EndOfTU;
2997 }
2998 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2999 if (hasMatchingNewInCtorInit(CI))
3000 return true;
3001 }
3002 return false;
3003}
3004
3005MismatchingNewDeleteDetector::MismatchResult
3006MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3007 assert(Field != nullptr && "This should be called only for members")(static_cast <bool> (Field != nullptr && "This should be called only for members"
) ? void (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3007, __extension__ __PRETTY_FUNCTION__))
;
3008 const Expr *InitExpr = Field->getInClassInitializer();
3009 if (!InitExpr)
3010 return EndOfTU ? NoMismatch : AnalyzeLater;
3011 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3012 if (NE->isArray() != IsArrayForm) {
3013 NewExprs.push_back(NE);
3014 return MemberInitMismatches;
3015 }
3016 }
3017 return NoMismatch;
3018}
3019
3020MismatchingNewDeleteDetector::MismatchResult
3021MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3022 bool DeleteWasArrayForm) {
3023 assert(Field != nullptr && "Analysis requires a valid class member.")(static_cast <bool> (Field != nullptr && "Analysis requires a valid class member."
) ? void (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3023, __extension__ __PRETTY_FUNCTION__))
;
3024 this->Field = Field;
3025 IsArrayForm = DeleteWasArrayForm;
3026 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3027 for (const auto *CD : RD->ctors()) {
3028 if (hasMatchingNewInCtor(CD))
3029 return NoMismatch;
3030 }
3031 if (HasUndefinedConstructors)
3032 return EndOfTU ? NoMismatch : AnalyzeLater;
3033 if (!NewExprs.empty())
3034 return MemberInitMismatches;
3035 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3036 : NoMismatch;
3037}
3038
3039MismatchingNewDeleteDetector::MismatchResult
3040MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3041 assert(ME != nullptr && "Expected a member expression")(static_cast <bool> (ME != nullptr && "Expected a member expression"
) ? void (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3041, __extension__ __PRETTY_FUNCTION__))
;
3042 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3043 return analyzeField(F, IsArrayForm);
3044 return NoMismatch;
3045}
3046
3047bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3048 const CXXNewExpr *NE = nullptr;
3049 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3050 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3051 NE->isArray() != IsArrayForm) {
3052 NewExprs.push_back(NE);
3053 }
3054 }
3055 return NewExprs.empty();
3056}
3057
3058static void
3059DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3060 const MismatchingNewDeleteDetector &Detector) {
3061 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3062 FixItHint H;
3063 if (!Detector.IsArrayForm)
3064 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3065 else {
3066 SourceLocation RSquare = Lexer::findLocationAfterToken(
3067 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3068 SemaRef.getLangOpts(), true);
3069 if (RSquare.isValid())
3070 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3071 }
3072 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3073 << Detector.IsArrayForm << H;
3074
3075 for (const auto *NE : Detector.NewExprs)
3076 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3077 << Detector.IsArrayForm;
3078}
3079
3080void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3081 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3082 return;
3083 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3084 switch (Detector.analyzeDeleteExpr(DE)) {
3085 case MismatchingNewDeleteDetector::VarInitMismatches:
3086 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3087 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3088 break;
3089 }
3090 case MismatchingNewDeleteDetector::AnalyzeLater: {
3091 DeleteExprs[Detector.Field].push_back(
3092 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3093 break;
3094 }
3095 case MismatchingNewDeleteDetector::NoMismatch:
3096 break;
3097 }
3098}
3099
3100void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3101 bool DeleteWasArrayForm) {
3102 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3103 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3104 case MismatchingNewDeleteDetector::VarInitMismatches:
3105 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3105)
;
3106 case MismatchingNewDeleteDetector::AnalyzeLater:
3107 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3108)
3108 "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3108)
;
3109 case MismatchingNewDeleteDetector::MemberInitMismatches:
3110 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3111 break;
3112 case MismatchingNewDeleteDetector::NoMismatch:
3113 break;
3114 }
3115}
3116
3117/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3118/// @code ::delete ptr; @endcode
3119/// or
3120/// @code delete [] ptr; @endcode
3121ExprResult
3122Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3123 bool ArrayForm, Expr *ExE) {
3124 // C++ [expr.delete]p1:
3125 // The operand shall have a pointer type, or a class type having a single
3126 // non-explicit conversion function to a pointer type. The result has type
3127 // void.
3128 //
3129 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3130
3131 ExprResult Ex = ExE;
3132 FunctionDecl *OperatorDelete = nullptr;
3133 bool ArrayFormAsWritten = ArrayForm;
3134 bool UsualArrayDeleteWantsSize = false;
3135
3136 if (!Ex.get()->isTypeDependent()) {
3137 // Perform lvalue-to-rvalue cast, if needed.
3138 Ex = DefaultLvalueConversion(Ex.get());
3139 if (Ex.isInvalid())
3140 return ExprError();
3141
3142 QualType Type = Ex.get()->getType();
3143
3144 class DeleteConverter : public ContextualImplicitConverter {
3145 public:
3146 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3147
3148 bool match(QualType ConvType) override {
3149 // FIXME: If we have an operator T* and an operator void*, we must pick
3150 // the operator T*.
3151 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3152 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3153 return true;
3154 return false;
3155 }
3156
3157 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3158 QualType T) override {
3159 return S.Diag(Loc, diag::err_delete_operand) << T;
3160 }
3161
3162 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3163 QualType T) override {
3164 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3165 }
3166
3167 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3168 QualType T,
3169 QualType ConvTy) override {
3170 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3171 }
3172
3173 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3174 QualType ConvTy) override {
3175 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3176 << ConvTy;
3177 }
3178
3179 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3180 QualType T) override {
3181 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3182 }
3183
3184 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3185 QualType ConvTy) override {
3186 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3187 << ConvTy;
3188 }
3189
3190 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3191 QualType T,
3192 QualType ConvTy) override {
3193 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3193)
;
3194 }
3195 } Converter;
3196
3197 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3198 if (Ex.isInvalid())
3199 return ExprError();
3200 Type = Ex.get()->getType();
3201 if (!Converter.match(Type))
3202 // FIXME: PerformContextualImplicitConversion should return ExprError
3203 // itself in this case.
3204 return ExprError();
3205
3206 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3207 QualType PointeeElem = Context.getBaseElementType(Pointee);
3208
3209 if (Pointee.getAddressSpace() != LangAS::Default)
3210 return Diag(Ex.get()->getLocStart(),
3211 diag::err_address_space_qualified_delete)
3212 << Pointee.getUnqualifiedType()
3213 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3214
3215 CXXRecordDecl *PointeeRD = nullptr;
3216 if (Pointee->isVoidType() && !isSFINAEContext()) {
3217 // The C++ standard bans deleting a pointer to a non-object type, which
3218 // effectively bans deletion of "void*". However, most compilers support
3219 // this, so we treat it as a warning unless we're in a SFINAE context.
3220 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3221 << Type << Ex.get()->getSourceRange();
3222 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3223 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3224 << Type << Ex.get()->getSourceRange());
3225 } else if (!Pointee->isDependentType()) {
3226 // FIXME: This can result in errors if the definition was imported from a
3227 // module but is hidden.
3228 if (!RequireCompleteType(StartLoc, Pointee,
3229 diag::warn_delete_incomplete, Ex.get())) {
3230 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3231 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3232 }
3233 }
3234
3235 if (Pointee->isArrayType() && !ArrayForm) {
3236 Diag(StartLoc, diag::warn_delete_array_type)
3237 << Type << Ex.get()->getSourceRange()
3238 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3239 ArrayForm = true;
3240 }
3241
3242 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3243 ArrayForm ? OO_Array_Delete : OO_Delete);
3244
3245 if (PointeeRD) {
3246 if (!UseGlobal &&
3247 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3248 OperatorDelete))
3249 return ExprError();
3250
3251 // If we're allocating an array of records, check whether the
3252 // usual operator delete[] has a size_t parameter.
3253 if (ArrayForm) {
3254 // If the user specifically asked to use the global allocator,
3255 // we'll need to do the lookup into the class.
3256 if (UseGlobal)
3257 UsualArrayDeleteWantsSize =
3258 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3259
3260 // Otherwise, the usual operator delete[] should be the
3261 // function we just found.
3262 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3263 UsualArrayDeleteWantsSize =
3264 UsualDeallocFnInfo(*this,
3265 DeclAccessPair::make(OperatorDelete, AS_public))
3266 .HasSizeT;
3267 }
3268
3269 if (!PointeeRD->hasIrrelevantDestructor())
3270 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3271 MarkFunctionReferenced(StartLoc,
3272 const_cast<CXXDestructorDecl*>(Dtor));
3273 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3274 return ExprError();
3275 }
3276
3277 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3278 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3279 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3280 SourceLocation());
3281 }
3282
3283 if (!OperatorDelete) {
3284 bool IsComplete = isCompleteType(StartLoc, Pointee);
3285 bool CanProvideSize =
3286 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3287 Pointee.isDestructedType());
3288 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3289
3290 // Look for a global declaration.
3291 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3292 Overaligned, DeleteName);
3293 }
3294
3295 MarkFunctionReferenced(StartLoc, OperatorDelete);
3296
3297 // Check access and ambiguity of destructor if we're going to call it.
3298 // Note that this is required even for a virtual delete.
3299 bool IsVirtualDelete = false;
3300 if (PointeeRD) {
3301 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3302 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3303 PDiag(diag::err_access_dtor) << PointeeElem);
3304 IsVirtualDelete = Dtor->isVirtual();
3305 }
3306 }
3307
3308 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3309 *this);
3310
3311 // Convert the operand to the type of the first parameter of operator
3312 // delete. This is only necessary if we selected a destroying operator
3313 // delete that we are going to call (non-virtually); converting to void*
3314 // is trivial and left to AST consumers to handle.
3315 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3316 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3317 Qualifiers Qs = Pointee.getQualifiers();
3318 if (Qs.hasCVRQualifiers()) {
3319 // Qualifiers are irrelevant to this conversion; we're only looking
3320 // for access and ambiguity.
3321 Qs.removeCVRQualifiers();
3322 QualType Unqual = Context.getPointerType(
3323 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3324 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3325 }
3326 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3327 if (Ex.isInvalid())
3328 return ExprError();
3329 }
3330 }
3331
3332 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3333 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3334 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3335 AnalyzeDeleteExprMismatch(Result);
3336 return Result;
3337}
3338
3339void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3340 bool IsDelete, bool CallCanBeVirtual,
3341 bool WarnOnNonAbstractTypes,
3342 SourceLocation DtorLoc) {
3343 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3344 return;
3345
3346 // C++ [expr.delete]p3:
3347 // In the first alternative (delete object), if the static type of the
3348 // object to be deleted is different from its dynamic type, the static
3349 // type shall be a base class of the dynamic type of the object to be
3350 // deleted and the static type shall have a virtual destructor or the
3351 // behavior is undefined.
3352 //
3353 const CXXRecordDecl *PointeeRD = dtor->getParent();
3354 // Note: a final class cannot be derived from, no issue there
3355 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3356 return;
3357
3358 // If the superclass is in a system header, there's nothing that can be done.
3359 // The `delete` (where we emit the warning) can be in a system header,
3360 // what matters for this warning is where the deleted type is defined.
3361 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3362 return;
3363
3364 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3365 if (PointeeRD->isAbstract()) {
3366 // If the class is abstract, we warn by default, because we're
3367 // sure the code has undefined behavior.
3368 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3369 << ClassType;
3370 } else if (WarnOnNonAbstractTypes) {
3371 // Otherwise, if this is not an array delete, it's a bit suspect,
3372 // but not necessarily wrong.
3373 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3374 << ClassType;
3375 }
3376 if (!IsDelete) {
3377 std::string TypeStr;
3378 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3379 Diag(DtorLoc, diag::note_delete_non_virtual)
3380 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3381 }
3382}
3383
3384Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3385 SourceLocation StmtLoc,
3386 ConditionKind CK) {
3387 ExprResult E =
3388 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3389 if (E.isInvalid())
3390 return ConditionError();
3391 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3392 CK == ConditionKind::ConstexprIf);
3393}
3394
3395/// \brief Check the use of the given variable as a C++ condition in an if,
3396/// while, do-while, or switch statement.
3397ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3398 SourceLocation StmtLoc,
3399 ConditionKind CK) {
3400 if (ConditionVar->isInvalidDecl())
3401 return ExprError();
3402
3403 QualType T = ConditionVar->getType();
3404
3405 // C++ [stmt.select]p2:
3406 // The declarator shall not specify a function or an array.
3407 if (T->isFunctionType())
3408 return ExprError(Diag(ConditionVar->getLocation(),
3409 diag::err_invalid_use_of_function_type)
3410 << ConditionVar->getSourceRange());
3411 else if (T->isArrayType())
3412 return ExprError(Diag(ConditionVar->getLocation(),
3413 diag::err_invalid_use_of_array_type)
3414 << ConditionVar->getSourceRange());
3415
3416 ExprResult Condition = DeclRefExpr::Create(
3417 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3418 /*enclosing*/ false, ConditionVar->getLocation(),
3419 ConditionVar->getType().getNonReferenceType(), VK_LValue);
3420
3421 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3422
3423 switch (CK) {
3424 case ConditionKind::Boolean:
3425 return CheckBooleanCondition(StmtLoc, Condition.get());
3426
3427 case ConditionKind::ConstexprIf:
3428 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3429
3430 case ConditionKind::Switch:
3431 return CheckSwitchCondition(StmtLoc, Condition.get());
3432 }
3433
3434 llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3434)
;
3435}
3436
3437/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3438ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3439 // C++ 6.4p4:
3440 // The value of a condition that is an initialized declaration in a statement
3441 // other than a switch statement is the value of the declared variable
3442 // implicitly converted to type bool. If that conversion is ill-formed, the
3443 // program is ill-formed.
3444 // The value of a condition that is an expression is the value of the
3445 // expression, implicitly converted to bool.
3446 //
3447 // FIXME: Return this value to the caller so they don't need to recompute it.
3448 llvm::APSInt Value(/*BitWidth*/1);
3449 return (IsConstexpr && !CondExpr->isValueDependent())
3450 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3451 CCEK_ConstexprIf)
3452 : PerformContextuallyConvertToBool(CondExpr);
3453}
3454
3455/// Helper function to determine whether this is the (deprecated) C++
3456/// conversion from a string literal to a pointer to non-const char or
3457/// non-const wchar_t (for narrow and wide string literals,
3458/// respectively).
3459bool
3460Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3461 // Look inside the implicit cast, if it exists.
3462 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3463 From = Cast->getSubExpr();
3464
3465 // A string literal (2.13.4) that is not a wide string literal can
3466 // be converted to an rvalue of type "pointer to char"; a wide
3467 // string literal can be converted to an rvalue of type "pointer
3468 // to wchar_t" (C++ 4.2p2).
3469 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3470 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3471 if (const BuiltinType *ToPointeeType
3472 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3473 // This conversion is considered only when there is an
3474 // explicit appropriate pointer target type (C++ 4.2p2).
3475 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3476 switch (StrLit->getKind()) {
3477 case StringLiteral::UTF8:
3478 case StringLiteral::UTF16:
3479 case StringLiteral::UTF32:
3480 // We don't allow UTF literals to be implicitly converted
3481 break;
3482 case StringLiteral::Ascii:
3483 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3484 ToPointeeType->getKind() == BuiltinType::Char_S);
3485 case StringLiteral::Wide:
3486 return Context.typesAreCompatible(Context.getWideCharType(),
3487 QualType(ToPointeeType, 0));
3488 }
3489 }
3490 }
3491
3492 return false;
3493}
3494
3495static ExprResult BuildCXXCastArgument(Sema &S,
3496 SourceLocation CastLoc,
3497 QualType Ty,
3498 CastKind Kind,
3499 CXXMethodDecl *Method,
3500 DeclAccessPair FoundDecl,
3501 bool HadMultipleCandidates,
3502 Expr *From) {
3503 switch (Kind) {
3504 default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3504)
;
3505 case CK_ConstructorConversion: {
3506 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3507 SmallVector<Expr*, 8> ConstructorArgs;
3508
3509 if (S.RequireNonAbstractType(CastLoc, Ty,
3510 diag::err_allocation_of_abstract_type))
3511 return ExprError();
3512
3513 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3514 return ExprError();
3515
3516 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3517 InitializedEntity::InitializeTemporary(Ty));
3518 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3519 return ExprError();
3520
3521 ExprResult Result = S.BuildCXXConstructExpr(
3522 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3523 ConstructorArgs, HadMultipleCandidates,
3524 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3525 CXXConstructExpr::CK_Complete, SourceRange());
3526 if (Result.isInvalid())
3527 return ExprError();
3528
3529 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3530 }
3531
3532 case CK_UserDefinedConversion: {
3533 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")(static_cast <bool> (!From->getType()->isPointerType
() && "Arg can't have pointer type!") ? void (0) : __assert_fail
("!From->getType()->isPointerType() && \"Arg can't have pointer type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3533, __extension__ __PRETTY_FUNCTION__))
;
3534
3535 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3536 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3537 return ExprError();
3538
3539 // Create an implicit call expr that calls it.
3540 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3541 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3542 HadMultipleCandidates);
3543 if (Result.isInvalid())
3544 return ExprError();
3545 // Record usage of conversion in an implicit cast.
3546 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3547 CK_UserDefinedConversion, Result.get(),
3548 nullptr, Result.get()->getValueKind());
3549
3550 return S.MaybeBindToTemporary(Result.get());
3551 }
3552 }
3553}
3554
3555/// PerformImplicitConversion - Perform an implicit conversion of the
3556/// expression From to the type ToType using the pre-computed implicit
3557/// conversion sequence ICS. Returns the converted
3558/// expression. Action is the kind of conversion we're performing,
3559/// used in the error message.
3560ExprResult
3561Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3562 const ImplicitConversionSequence &ICS,
3563 AssignmentAction Action,
3564 CheckedConversionKind CCK) {
3565 switch (ICS.getKind()) {
3566 case ImplicitConversionSequence::StandardConversion: {
3567 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3568 Action, CCK);
3569 if (Res.isInvalid())
3570 return ExprError();
3571 From = Res.get();
3572 break;
3573 }
3574
3575 case ImplicitConversionSequence::UserDefinedConversion: {
3576
3577 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3578 CastKind CastKind;
3579 QualType BeforeToType;
3580 assert(FD && "no conversion function for user-defined conversion seq")(static_cast <bool> (FD && "no conversion function for user-defined conversion seq"
) ? void (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3580, __extension__ __PRETTY_FUNCTION__))
;
3581 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3582 CastKind = CK_UserDefinedConversion;
3583
3584 // If the user-defined conversion is specified by a conversion function,
3585 // the initial standard conversion sequence converts the source type to
3586 // the implicit object parameter of the conversion function.
3587 BeforeToType = Context.getTagDeclType(Conv->getParent());
3588 } else {
3589 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3590 CastKind = CK_ConstructorConversion;
3591 // Do no conversion if dealing with ... for the first conversion.
3592 if (!ICS.UserDefined.EllipsisConversion) {
3593 // If the user-defined conversion is specified by a constructor, the
3594 // initial standard conversion sequence converts the source type to
3595 // the type required by the argument of the constructor
3596 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3597 }
3598 }
3599 // Watch out for ellipsis conversion.
3600 if (!ICS.UserDefined.EllipsisConversion) {
3601 ExprResult Res =
3602 PerformImplicitConversion(From, BeforeToType,
3603 ICS.UserDefined.Before, AA_Converting,
3604 CCK);
3605 if (Res.isInvalid())
3606 return ExprError();
3607 From = Res.get();
3608 }
3609
3610 ExprResult CastArg
3611 = BuildCXXCastArgument(*this,
3612 From->getLocStart(),
3613 ToType.getNonReferenceType(),
3614 CastKind, cast<CXXMethodDecl>(FD),
3615 ICS.UserDefined.FoundConversionFunction,
3616 ICS.UserDefined.HadMultipleCandidates,
3617 From);
3618
3619 if (CastArg.isInvalid())
3620 return ExprError();
3621
3622 From = CastArg.get();
3623
3624 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3625 AA_Converting, CCK);
3626 }
3627
3628 case ImplicitConversionSequence::AmbiguousConversion:
3629 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3630 PDiag(diag::err_typecheck_ambiguous_condition)
3631 << From->getSourceRange());
3632 return ExprError();
3633
3634 case ImplicitConversionSequence::EllipsisConversion:
3635 llvm_unreachable("Cannot perform an ellipsis conversion")::llvm::llvm_unreachable_internal("Cannot perform an ellipsis conversion"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3635)
;
3636
3637 case ImplicitConversionSequence::BadConversion:
3638 bool Diagnosed =
3639 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3640 From->getType(), From, Action);
3641 assert(Diagnosed && "failed to diagnose bad conversion")(static_cast <bool> (Diagnosed && "failed to diagnose bad conversion"
) ? void (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3641, __extension__ __PRETTY_FUNCTION__))
; (void)Diagnosed;
3642 return ExprError();
3643 }
3644
3645 // Everything went well.
3646 return From;
3647}
3648
3649/// PerformImplicitConversion - Perform an implicit conversion of the
3650/// expression From to the type ToType by following the standard
3651/// conversion sequence SCS. Returns the converted
3652/// expression. Flavor is the context in which we're performing this
3653/// conversion, for use in error messages.
3654ExprResult
3655Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3656 const StandardConversionSequence& SCS,
3657 AssignmentAction Action,
3658 CheckedConversionKind CCK) {
3659 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3660
3661 // Overall FIXME: we are recomputing too many types here and doing far too
3662 // much extra work. What this means is that we need to keep track of more
3663 // information that is computed when we try the implicit conversion initially,
3664 // so that we don't need to recompute anything here.
3665 QualType FromType = From->getType();
3666
3667 if (SCS.CopyConstructor) {
3668 // FIXME: When can ToType be a reference type?
3669 assert(!ToType->isReferenceType())(static_cast <bool> (!ToType->isReferenceType()) ? void
(0) : __assert_fail ("!ToType->isReferenceType()", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3669, __extension__ __PRETTY_FUNCTION__))
;
3670 if (SCS.Second == ICK_Derived_To_Base) {
3671 SmallVector<Expr*, 8> ConstructorArgs;
3672 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3673 From, /*FIXME:ConstructLoc*/SourceLocation(),
3674 ConstructorArgs))
3675 return ExprError();
3676 return BuildCXXConstructExpr(
3677 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3678 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3679 ConstructorArgs, /*HadMultipleCandidates*/ false,
3680 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3681 CXXConstructExpr::CK_Complete, SourceRange());
3682 }
3683 return BuildCXXConstructExpr(
3684 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3685 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3686 From, /*HadMultipleCandidates*/ false,
3687 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3688 CXXConstructExpr::CK_Complete, SourceRange());
3689 }
3690
3691 // Resolve overloaded function references.
3692 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3693 DeclAccessPair Found;
3694 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3695 true, Found);
3696 if (!Fn)
3697 return ExprError();
3698
3699 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
3700 return ExprError();
3701
3702 From = FixOverloadedFunctionReference(From, Found, Fn);
3703 FromType = From->getType();
3704 }
3705
3706 // If we're converting to an atomic type, first convert to the corresponding
3707 // non-atomic type.
3708 QualType ToAtomicType;
3709 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3710 ToAtomicType = ToType;
3711 ToType = ToAtomic->getValueType();
3712 }
3713
3714 QualType InitialFromType = FromType;
3715 // Perform the first implicit conversion.
3716 switch (SCS.First) {
3717 case ICK_Identity:
3718 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3719 FromType = FromAtomic->getValueType().getUnqualifiedType();
3720 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3721 From, /*BasePath=*/nullptr, VK_RValue);
3722 }
3723 break;
3724
3725 case ICK_Lvalue_To_Rvalue: {
3726 assert(From->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (From->getObjectKind() != OK_ObjCProperty
) ? void (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3726, __extension__ __PRETTY_FUNCTION__))
;
3727 ExprResult FromRes = DefaultLvalueConversion(From);
3728 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!")(static_cast <bool> (!FromRes.isInvalid() && "Can't perform deduced conversion?!"
) ? void (0) : __assert_fail ("!FromRes.isInvalid() && \"Can't perform deduced conversion?!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3728, __extension__ __PRETTY_FUNCTION__))
;
3729 From = FromRes.get();
3730 FromType = From->getType();
3731 break;
3732 }
3733
3734 case ICK_Array_To_Pointer:
3735 FromType = Context.getArrayDecayedType(FromType);
3736 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3737 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3738 break;
3739
3740 case ICK_Function_To_Pointer:
3741 FromType = Context.getPointerType(FromType);
3742 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3743 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3744 break;
3745
3746 default:
3747 llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3747)
;
3748 }
3749
3750 // Perform the second implicit conversion
3751 switch (SCS.Second) {
3752 case ICK_Identity:
3753 // C++ [except.spec]p5:
3754 // [For] assignment to and initialization of pointers to functions,
3755 // pointers to member functions, and references to functions: the
3756 // target entity shall allow at least the exceptions allowed by the
3757 // source value in the assignment or initialization.
3758 switch (Action) {
3759 case AA_Assigning:
3760 case AA_Initializing:
3761 // Note, function argument passing and returning are initialization.
3762 case AA_Passing:
3763 case AA_Returning:
3764 case AA_Sending:
3765 case AA_Passing_CFAudited:
3766 if (CheckExceptionSpecCompatibility(From, ToType))
3767 return ExprError();
3768 break;
3769
3770 case AA_Casting:
3771 case AA_Converting:
3772 // Casts and implicit conversions are not initialization, so are not
3773 // checked for exception specification mismatches.
3774 break;
3775 }
3776 // Nothing else to do.
3777 break;
3778
3779 case ICK_Integral_Promotion:
3780 case ICK_Integral_Conversion:
3781 if (ToType->isBooleanType()) {
3782 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3784, __extension__ __PRETTY_FUNCTION__))
3783 SCS.Second == ICK_Integral_Promotion &&(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3784, __extension__ __PRETTY_FUNCTION__))
3784 "only enums with fixed underlying type can promote to bool")(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? 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-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3784, __extension__ __PRETTY_FUNCTION__))
;
3785 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
3786 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3787 } else {
3788 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
3789 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3790 }
3791 break;
3792
3793 case ICK_Floating_Promotion:
3794 case ICK_Floating_Conversion:
3795 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
3796 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3797 break;
3798
3799 case ICK_Complex_Promotion:
3800 case ICK_Complex_Conversion: {
3801 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3802 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3803 CastKind CK;
3804 if (FromEl->isRealFloatingType()) {
3805 if (ToEl->isRealFloatingType())
3806 CK = CK_FloatingComplexCast;
3807 else
3808 CK = CK_FloatingComplexToIntegralComplex;
3809 } else if (ToEl->isRealFloatingType()) {
3810 CK = CK_IntegralComplexToFloatingComplex;
3811 } else {
3812 CK = CK_IntegralComplexCast;
3813 }
3814 From = ImpCastExprToType(From, ToType, CK,
3815 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3816 break;
3817 }
3818
3819 case ICK_Floating_Integral:
3820 if (ToType->isRealFloatingType())
3821 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
3822 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3823 else
3824 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
3825 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3826 break;
3827
3828 case ICK_Compatible_Conversion:
3829 From = ImpCastExprToType(From, ToType, CK_NoOp,
3830 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3831 break;
3832
3833 case ICK_Writeback_Conversion:
3834 case ICK_Pointer_Conversion: {
3835 if (SCS.IncompatibleObjC && Action != AA_Casting) {
3836 // Diagnose incompatible Objective-C conversions
3837 if (Action == AA_Initializing || Action == AA_Assigning)
3838 Diag(From->getLocStart(),
3839 diag::ext_typecheck_convert_incompatible_pointer)
3840 << ToType << From->getType() << Action
3841 << From->getSourceRange() << 0;
3842 else
3843 Diag(From->getLocStart(),
3844 diag::ext_typecheck_convert_incompatible_pointer)
3845 << From->getType() << ToType << Action
3846 << From->getSourceRange() << 0;
3847
3848 if (From->getType()->isObjCObjectPointerType() &&
3849 ToType->isObjCObjectPointerType())
3850 EmitRelatedResultTypeNote(From);
3851 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3852 !CheckObjCARCUnavailableWeakConversion(ToType,
3853 From->getType())) {
3854 if (Action == AA_Initializing)
3855 Diag(From->getLocStart(),
3856 diag::err_arc_weak_unavailable_assign);
3857 else
3858 Diag(From->getLocStart(),
3859 diag::err_arc_convesion_of_weak_unavailable)
3860 << (Action == AA_Casting) << From->getType() << ToType
3861 << From->getSourceRange();
3862 }
3863
3864 CastKind Kind;
3865 CXXCastPath BasePath;
3866 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
3867 return ExprError();
3868
3869 // Make sure we extend blocks if necessary.
3870 // FIXME: doing this here is really ugly.
3871 if (Kind == CK_BlockPointerToObjCPointerCast) {
3872 ExprResult E = From;
3873 (void) PrepareCastToObjCObjectPointer(E);
3874 From = E.get();
3875 }
3876 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3877 CheckObjCConversion(SourceRange(), ToType, From, CCK);
3878 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3879 .get();
3880 break;
3881 }
3882
3883 case ICK_Pointer_Member: {
3884 CastKind Kind;
3885 CXXCastPath BasePath;
3886 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
3887 return ExprError();
3888 if (CheckExceptionSpecCompatibility(From, ToType))
3889 return ExprError();
3890
3891 // We may not have been able to figure out what this member pointer resolved
3892 // to up until this exact point. Attempt to lock-in it's inheritance model.
3893 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3894 (void)isCompleteType(From->getExprLoc(), From->getType());
3895 (void)isCompleteType(From->getExprLoc(), ToType);
3896 }
3897
3898 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3899 .get();
3900 break;
3901 }
3902
3903 case ICK_Boolean_Conversion:
3904 // Perform half-to-boolean conversion via float.
3905 if (From->getType()->isHalfType()) {
3906 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
3907 FromType = Context.FloatTy;
3908 }
3909
3910 From = ImpCastExprToType(From, Context.BoolTy,
3911 ScalarTypeToBooleanCastKind(FromType),
3912 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3913 break;
3914
3915 case ICK_Derived_To_Base: {
3916 CXXCastPath BasePath;
3917 if (CheckDerivedToBaseConversion(From->getType(),
3918 ToType.getNonReferenceType(),
3919 From->getLocStart(),
3920 From->getSourceRange(),
3921 &BasePath,
3922 CStyle))
3923 return ExprError();
3924
3925 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3926 CK_DerivedToBase, From->getValueKind(),
3927 &BasePath, CCK).get();
3928 break;
3929 }
3930
3931 case ICK_Vector_Conversion:
3932 From = ImpCastExprToType(From, ToType, CK_BitCast,
3933 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3934 break;
3935
3936 case ICK_Vector_Splat: {
3937 // Vector splat from any arithmetic type to a vector.
3938 Expr *Elem = prepareVectorSplat(ToType, From).get();
3939 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3940 /*BasePath=*/nullptr, CCK).get();
3941 break;
3942 }
3943
3944 case ICK_Complex_Real:
3945 // Case 1. x -> _Complex y
3946 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3947 QualType ElType = ToComplex->getElementType();
3948 bool isFloatingComplex = ElType->isRealFloatingType();
3949
3950 // x -> y
3951 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3952 // do nothing
3953 } else if (From->getType()->isRealFloatingType()) {
3954 From = ImpCastExprToType(From, ElType,
3955 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
3956 } else {
3957 assert(From->getType()->isIntegerType())(static_cast <bool> (From->getType()->isIntegerType
()) ? void (0) : __assert_fail ("From->getType()->isIntegerType()"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3957, __extension__ __PRETTY_FUNCTION__))
;
3958 From = ImpCastExprToType(From, ElType,
3959 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
3960 }
3961 // y -> _Complex y
3962 From = ImpCastExprToType(From, ToType,
3963 isFloatingComplex ? CK_FloatingRealToComplex
3964 : CK_IntegralRealToComplex).get();
3965
3966 // Case 2. _Complex x -> y
3967 } else {
3968 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3969 assert(FromComplex)(static_cast <bool> (FromComplex) ? void (0) : __assert_fail
("FromComplex", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3969, __extension__ __PRETTY_FUNCTION__))
;
3970
3971 QualType ElType = FromComplex->getElementType();
3972 bool isFloatingComplex = ElType->isRealFloatingType();
3973
3974 // _Complex x -> x
3975 From = ImpCastExprToType(From, ElType,
3976 isFloatingComplex ? CK_FloatingComplexToReal
3977 : CK_IntegralComplexToReal,
3978 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3979
3980 // x -> y
3981 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3982 // do nothing
3983 } else if (ToType->isRealFloatingType()) {
3984 From = ImpCastExprToType(From, ToType,
3985 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
3986 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3987 } else {
3988 assert(ToType->isIntegerType())(static_cast <bool> (ToType->isIntegerType()) ? void
(0) : __assert_fail ("ToType->isIntegerType()", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3988, __extension__ __PRETTY_FUNCTION__))
;
3989 From = ImpCastExprToType(From, ToType,
3990 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3991 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3992 }
3993 }
3994 break;
3995
3996 case ICK_Block_Pointer_Conversion: {
3997 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
3998 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3999 break;
4000 }
4001
4002 case ICK_TransparentUnionConversion: {
4003 ExprResult FromRes = From;
4004 Sema::AssignConvertType ConvTy =
4005 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4006 if (FromRes.isInvalid())
4007 return ExprError();
4008 From = FromRes.get();
4009 assert ((ConvTy == Sema::Compatible) &&(static_cast <bool> ((ConvTy == Sema::Compatible) &&
"Improper transparent union conversion") ? void (0) : __assert_fail
("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4010, __extension__ __PRETTY_FUNCTION__))
4010 "Improper transparent union conversion")(static_cast <bool> ((ConvTy == Sema::Compatible) &&
"Improper transparent union conversion") ? void (0) : __assert_fail
("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4010, __extension__ __PRETTY_FUNCTION__))
;
4011 (void)ConvTy;
4012 break;
4013 }
4014
4015 case ICK_Zero_Event_Conversion:
4016 From = ImpCastExprToType(From, ToType,
4017 CK_ZeroToOCLEvent,
4018 From->getValueKind()).get();
4019 break;
4020
4021 case ICK_Zero_Queue_Conversion:
4022 From = ImpCastExprToType(From, ToType,
4023 CK_ZeroToOCLQueue,
4024 From->getValueKind()).get();
4025 break;
4026
4027 case ICK_Lvalue_To_Rvalue:
4028 case ICK_Array_To_Pointer:
4029 case ICK_Function_To_Pointer:
4030 case ICK_Function_Conversion:
4031 case ICK_Qualification:
4032 case ICK_Num_Conversion_Kinds:
4033 case ICK_C_Only_Conversion:
4034 case ICK_Incompatible_Pointer_Conversion:
4035 llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4035)
;
4036 }
4037
4038 switch (SCS.Third) {
4039 case ICK_Identity:
4040 // Nothing to do.
4041 break;
4042
4043 case ICK_Function_Conversion:
4044 // If both sides are functions (or pointers/references to them), there could
4045 // be incompatible exception declarations.
4046 if (CheckExceptionSpecCompatibility(From, ToType))
4047 return ExprError();
4048
4049 From = ImpCastExprToType(From, ToType, CK_NoOp,
4050 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4051 break;
4052
4053 case ICK_Qualification: {
4054 // The qualification keeps the category of the inner expression, unless the
4055 // target type isn't a reference.
4056 ExprValueKind VK = ToType->isReferenceType() ?
4057 From->getValueKind() : VK_RValue;
4058 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
4059 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
4060
4061 if (SCS.DeprecatedStringLiteralToCharPtr &&
4062 !getLangOpts().WritableStrings) {
4063 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4064 ? diag::ext_deprecated_string_literal_conversion
4065 : diag::warn_deprecated_string_literal_conversion)
4066 << ToType.getNonReferenceType();
4067 }
4068
4069 break;
4070 }
4071
4072 default:
4073 llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4073)
;
4074 }
4075
4076 // If this conversion sequence involved a scalar -> atomic conversion, perform
4077 // that conversion now.
4078 if (!ToAtomicType.isNull()) {
4079 assert(Context.hasSameType((static_cast <bool> (Context.hasSameType( ToAtomicType->
castAs<AtomicType>()->getValueType(), From->getType
())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4080, __extension__ __PRETTY_FUNCTION__))
4080 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))(static_cast <bool> (Context.hasSameType( ToAtomicType->
castAs<AtomicType>()->getValueType(), From->getType
())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4080, __extension__ __PRETTY_FUNCTION__))
;
4081 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4082 VK_RValue, nullptr, CCK).get();
4083 }
4084
4085 // If this conversion sequence succeeded and involved implicitly converting a
4086 // _Nullable type to a _Nonnull one, complain.
4087 if (CCK == CCK_ImplicitConversion)
4088 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4089 From->getLocStart());
4090
4091 return From;
4092}
4093
4094/// \brief Check the completeness of a type in a unary type trait.
4095///
4096/// If the particular type trait requires a complete type, tries to complete
4097/// it. If completing the type fails, a diagnostic is emitted and false
4098/// returned. If completing the type succeeds or no completion was required,
4099/// returns true.
4100static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4101 SourceLocation Loc,
4102 QualType ArgTy) {
4103 // C++0x [meta.unary.prop]p3:
4104 // For all of the class templates X declared in this Clause, instantiating
4105 // that template with a template argument that is a class template
4106 // specialization may result in the implicit instantiation of the template
4107 // argument if and only if the semantics of X require that the argument
4108 // must be a complete type.
4109 // We apply this rule to all the type trait expressions used to implement
4110 // these class templates. We also try to follow any GCC documented behavior
4111 // in these expressions to ensure portability of standard libraries.
4112 switch (UTT) {
4113 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4113)
;
4114 // is_complete_type somewhat obviously cannot require a complete type.
4115 case UTT_IsCompleteType:
4116 // Fall-through
4117
4118 // These traits are modeled on the type predicates in C++0x
4119 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4120 // requiring a complete type, as whether or not they return true cannot be
4121 // impacted by the completeness of the type.
4122 case UTT_IsVoid:
4123 case UTT_IsIntegral:
4124 case UTT_IsFloatingPoint:
4125 case UTT_IsArray:
4126 case UTT_IsPointer:
4127 case UTT_IsLvalueReference:
4128 case UTT_IsRvalueReference:
4129 case UTT_IsMemberFunctionPointer:
4130 case UTT_IsMemberObjectPointer:
4131 case UTT_IsEnum:
4132 case UTT_IsUnion:
4133 case UTT_IsClass:
4134 case UTT_IsFunction:
4135 case UTT_IsReference:
4136 case UTT_IsArithmetic:
4137 case UTT_IsFundamental:
4138 case UTT_IsObject:
4139 case UTT_IsScalar:
4140 case UTT_IsCompound:
4141 case UTT_IsMemberPointer:
4142 // Fall-through
4143
4144 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4145 // which requires some of its traits to have the complete type. However,
4146 // the completeness of the type cannot impact these traits' semantics, and
4147 // so they don't require it. This matches the comments on these traits in
4148 // Table 49.
4149 case UTT_IsConst:
4150 case UTT_IsVolatile:
4151 case UTT_IsSigned:
4152 case UTT_IsUnsigned:
4153
4154 // This type trait always returns false, checking the type is moot.
4155 case UTT_IsInterfaceClass:
4156 return true;
4157
4158 // C++14 [meta.unary.prop]:
4159 // If T is a non-union class type, T shall be a complete type.
4160 case UTT_IsEmpty:
4161 case UTT_IsPolymorphic:
4162 case UTT_IsAbstract:
4163 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4164 if (!RD->isUnion())
4165 return !S.RequireCompleteType(
4166 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4167 return true;
4168
4169 // C++14 [meta.unary.prop]:
4170 // If T is a class type, T shall be a complete type.
4171 case UTT_IsFinal:
4172 case UTT_IsSealed:
4173 if (ArgTy->getAsCXXRecordDecl())
4174 return !S.RequireCompleteType(
4175 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4176 return true;
4177
4178 // C++1z [meta.unary.prop]:
4179 // remove_all_extents_t<T> shall be a complete type or cv void.
4180 case UTT_IsAggregate:
4181 case UTT_IsTrivial:
4182 case UTT_IsTriviallyCopyable:
4183 case UTT_IsStandardLayout:
4184 case UTT_IsPOD:
4185 case UTT_IsLiteral:
4186 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4187 // or an array of unknown bound. But GCC actually imposes the same constraints
4188 // as above.
4189 case UTT_HasNothrowAssign:
4190 case UTT_HasNothrowMoveAssign:
4191 case UTT_HasNothrowConstructor:
4192 case UTT_HasNothrowCopy:
4193 case UTT_HasTrivialAssign:
4194 case UTT_HasTrivialMoveAssign:
4195 case UTT_HasTrivialDefaultConstructor:
4196 case UTT_HasTrivialMoveConstructor:
4197 case UTT_HasTrivialCopy:
4198 case UTT_HasTrivialDestructor:
4199 case UTT_HasVirtualDestructor:
4200 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4201 LLVM_FALLTHROUGH[[clang::fallthrough]];
4202
4203 // C++1z [meta.unary.prop]:
4204 // T shall be a complete type, cv void, or an array of unknown bound.
4205 case UTT_IsDestructible:
4206 case UTT_IsNothrowDestructible:
4207 case UTT_IsTriviallyDestructible:
4208 case UTT_HasUniqueObjectRepresentations:
4209 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4210 return true;
4211
4212 return !S.RequireCompleteType(
4213 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4214 }
4215}
4216
4217static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4218 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4219 bool (CXXRecordDecl::*HasTrivial)() const,
4220 bool (CXXRecordDecl::*HasNonTrivial)() const,
4221 bool (CXXMethodDecl::*IsDesiredOp)() const)
4222{
4223 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4224 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4225 return true;
4226
4227 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4228 DeclarationNameInfo NameInfo(Name, KeyLoc);
4229 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4230 if (Self.LookupQualifiedName(Res, RD)) {
4231 bool FoundOperator = false;
4232 Res.suppressDiagnostics();
4233 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4234 Op != OpEnd; ++Op) {
4235 if (isa<FunctionTemplateDecl>(*Op))
4236 continue;
4237
4238 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4239 if((Operator->*IsDesiredOp)()) {
4240 FoundOperator = true;
4241 const FunctionProtoType *CPT =
4242 Operator->getType()->getAs<FunctionProtoType>();
4243 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4244 if (!CPT || !CPT->isNothrow(C))
4245 return false;
4246 }
4247 }
4248 return FoundOperator;
4249 }
4250 return false;
4251}
4252
4253static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4254 SourceLocation KeyLoc, QualType T) {
4255 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() &&
"Cannot evaluate traits of dependent type") ? void (0) : __assert_fail
("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4255, __extension__ __PRETTY_FUNCTION__))
;
4256
4257 ASTContext &C = Self.Context;
4258 switch(UTT) {
4259 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4259)
;
4260 // Type trait expressions corresponding to the primary type category
4261 // predicates in C++0x [meta.unary.cat].
4262 case UTT_IsVoid:
4263 return T->isVoidType();
4264 case UTT_IsIntegral:
4265 return T->isIntegralType(C);
4266 case UTT_IsFloatingPoint:
4267 return T->isFloatingType();
4268 case UTT_IsArray:
4269 return T->isArrayType();
4270 case UTT_IsPointer:
4271 return T->isPointerType();
4272 case UTT_IsLvalueReference:
4273 return T->isLValueReferenceType();
4274 case UTT_IsRvalueReference:
4275 return T->isRValueReferenceType();
4276 case UTT_IsMemberFunctionPointer:
4277 return T->isMemberFunctionPointerType();
4278 case UTT_IsMemberObjectPointer:
4279 return T->isMemberDataPointerType();
4280 case UTT_IsEnum:
4281 return T->isEnumeralType();
4282 case UTT_IsUnion:
4283 return T->isUnionType();
4284 case UTT_IsClass:
4285 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4286 case UTT_IsFunction:
4287 return T->isFunctionType();
4288
4289 // Type trait expressions which correspond to the convenient composition
4290 // predicates in C++0x [meta.unary.comp].
4291 case UTT_IsReference:
4292 return T->isReferenceType();
4293 case UTT_IsArithmetic:
4294 return T->isArithmeticType() && !T->isEnumeralType();
4295 case UTT_IsFundamental:
4296 return T->isFundamentalType();
4297 case UTT_IsObject:
4298 return T->isObjectType();
4299 case UTT_IsScalar:
4300 // Note: semantic analysis depends on Objective-C lifetime types to be
4301 // considered scalar types. However, such types do not actually behave
4302 // like scalar types at run time (since they may require retain/release
4303 // operations), so we report them as non-scalar.
4304 if (T->isObjCLifetimeType()) {
4305 switch (T.getObjCLifetime()) {
4306 case Qualifiers::OCL_None:
4307 case Qualifiers::OCL_ExplicitNone:
4308 return true;
4309
4310 case Qualifiers::OCL_Strong:
4311 case Qualifiers::OCL_Weak:
4312 case Qualifiers::OCL_Autoreleasing:
4313 return false;
4314 }
4315 }
4316
4317 return T->isScalarType();
4318 case UTT_IsCompound:
4319 return T->isCompoundType();
4320 case UTT_IsMemberPointer:
4321 return T->isMemberPointerType();
4322
4323 // Type trait expressions which correspond to the type property predicates
4324 // in C++0x [meta.unary.prop].
4325 case UTT_IsConst:
4326 return T.isConstQualified();
4327 case UTT_IsVolatile:
4328 return T.isVolatileQualified();
4329 case UTT_IsTrivial:
4330 return T.isTrivialType(C);
4331 case UTT_IsTriviallyCopyable:
4332 return T.isTriviallyCopyableType(C);
4333 case UTT_IsStandardLayout:
4334 return T->isStandardLayoutType();
4335 case UTT_IsPOD:
4336 return T.isPODType(C);
4337 case UTT_IsLiteral:
4338 return T->isLiteralType(C);
4339 case UTT_IsEmpty:
4340 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4341 return !RD->isUnion() && RD->isEmpty();
4342 return false;
4343 case UTT_IsPolymorphic:
4344 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4345 return !RD->isUnion() && RD->isPolymorphic();
4346 return false;
4347 case UTT_IsAbstract:
4348 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4349 return !RD->isUnion() && RD->isAbstract();
4350 return false;
4351 case UTT_IsAggregate:
4352 // Report vector extensions and complex types as aggregates because they
4353 // support aggregate initialization. GCC mirrors this behavior for vectors
4354 // but not _Complex.
4355 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4356 T->isAnyComplexType();
4357 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4358 // even then only when it is used with the 'interface struct ...' syntax
4359 // Clang doesn't support /CLR which makes this type trait moot.
4360 case UTT_IsInterfaceClass:
4361 return false;
4362 case UTT_IsFinal:
4363 case UTT_IsSealed:
4364 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4365 return RD->hasAttr<FinalAttr>();
4366 return false;
4367 case UTT_IsSigned:
4368 return T->isSignedIntegerType();
4369 case UTT_IsUnsigned:
4370 return T->isUnsignedIntegerType();
4371
4372 // Type trait expressions which query classes regarding their construction,
4373 // destruction, and copying. Rather than being based directly on the
4374 // related type predicates in the standard, they are specified by both
4375 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4376 // specifications.
4377 //
4378 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4379 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4380 //
4381 // Note that these builtins do not behave as documented in g++: if a class
4382 // has both a trivial and a non-trivial special member of a particular kind,
4383 // they return false! For now, we emulate this behavior.
4384 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4385 // does not correctly compute triviality in the presence of multiple special
4386 // members of the same kind. Revisit this once the g++ bug is fixed.
4387 case UTT_HasTrivialDefaultConstructor:
4388 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4389 // If __is_pod (type) is true then the trait is true, else if type is
4390 // a cv class or union type (or array thereof) with a trivial default
4391 // constructor ([class.ctor]) then the trait is true, else it is false.
4392 if (T.isPODType(C))
4393 return true;
4394 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4395 return RD->hasTrivialDefaultConstructor() &&
4396 !RD->hasNonTrivialDefaultConstructor();
4397 return false;
4398 case UTT_HasTrivialMoveConstructor:
4399 // This trait is implemented by MSVC 2012 and needed to parse the
4400 // standard library headers. Specifically this is used as the logic
4401 // behind std::is_trivially_move_constructible (20.9.4.3).
4402 if (T.isPODType(C))
4403 return true;
4404 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4405 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4406 return false;
4407 case UTT_HasTrivialCopy:
4408 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4409 // If __is_pod (type) is true or type is a reference type then
4410 // the trait is true, else if type is a cv class or union type
4411 // with a trivial copy constructor ([class.copy]) then the trait
4412 // is true, else it is false.
4413 if (T.isPODType(C) || T->isReferenceType())
4414 return true;
4415 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4416 return RD->hasTrivialCopyConstructor() &&
4417 !RD->hasNonTrivialCopyConstructor();
4418 return false;
4419 case UTT_HasTrivialMoveAssign:
4420 // This trait is implemented by MSVC 2012 and needed to parse the
4421 // standard library headers. Specifically it is used as the logic
4422 // behind std::is_trivially_move_assignable (20.9.4.3)
4423 if (T.isPODType(C))
4424 return true;
4425 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4426 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4427 return false;
4428 case UTT_HasTrivialAssign:
4429 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4430 // If type is const qualified or is a reference type then the
4431 // trait is false. Otherwise if __is_pod (type) is true then the
4432 // trait is true, else if type is a cv class or union type with
4433 // a trivial copy assignment ([class.copy]) then the trait is
4434 // true, else it is false.
4435 // Note: the const and reference restrictions are interesting,
4436 // given that const and reference members don't prevent a class
4437 // from having a trivial copy assignment operator (but do cause
4438 // errors if the copy assignment operator is actually used, q.v.
4439 // [class.copy]p12).
4440
4441 if (T.isConstQualified())
4442 return false;
4443 if (T.isPODType(C))
4444 return true;
4445 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4446 return RD->hasTrivialCopyAssignment() &&
4447 !RD->hasNonTrivialCopyAssignment();
4448 return false;
4449 case UTT_IsDestructible:
4450 case UTT_IsTriviallyDestructible:
4451 case UTT_IsNothrowDestructible:
4452 // C++14 [meta.unary.prop]:
4453 // For reference types, is_destructible<T>::value is true.
4454 if (T->isReferenceType())
4455 return true;
4456
4457 // Objective-C++ ARC: autorelease types don't require destruction.
4458 if (T->isObjCLifetimeType() &&
4459 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4460 return true;
4461
4462 // C++14 [meta.unary.prop]:
4463 // For incomplete types and function types, is_destructible<T>::value is
4464 // false.
4465 if (T->isIncompleteType() || T->isFunctionType())
4466 return false;
4467
4468 // A type that requires destruction (via a non-trivial destructor or ARC
4469 // lifetime semantics) is not trivially-destructible.
4470 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4471 return false;
4472
4473 // C++14 [meta.unary.prop]:
4474 // For object types and given U equal to remove_all_extents_t<T>, if the
4475 // expression std::declval<U&>().~U() is well-formed when treated as an
4476 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4477 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4478 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4479 if (!Destructor)
4480 return false;
4481 // C++14 [dcl.fct.def.delete]p2:
4482 // A program that refers to a deleted function implicitly or
4483 // explicitly, other than to declare it, is ill-formed.
4484 if (Destructor->isDeleted())
4485 return false;
4486 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4487 return false;
4488 if (UTT == UTT_IsNothrowDestructible) {
4489 const FunctionProtoType *CPT =
4490 Destructor->getType()->getAs<FunctionProtoType>();
4491 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4492 if (!CPT || !CPT->isNothrow(C))
4493 return false;
4494 }
4495 }
4496 return true;
4497
4498 case UTT_HasTrivialDestructor:
4499 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4500 // If __is_pod (type) is true or type is a reference type
4501 // then the trait is true, else if type is a cv class or union
4502 // type (or array thereof) with a trivial destructor
4503 // ([class.dtor]) then the trait is true, else it is
4504 // false.
4505 if (T.isPODType(C) || T->isReferenceType())
4506 return true;
4507
4508 // Objective-C++ ARC: autorelease types don't require destruction.
4509 if (T->isObjCLifetimeType() &&
4510 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4511 return true;
4512
4513 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4514 return RD->hasTrivialDestructor();
4515 return false;
4516 // TODO: Propagate nothrowness for implicitly declared special members.
4517 case UTT_HasNothrowAssign:
4518 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4519 // If type is const qualified or is a reference type then the
4520 // trait is false. Otherwise if __has_trivial_assign (type)
4521 // is true then the trait is true, else if type is a cv class
4522 // or union type with copy assignment operators that are known
4523 // not to throw an exception then the trait is true, else it is
4524 // false.
4525 if (C.getBaseElementType(T).isConstQualified())
4526 return false;
4527 if (T->isReferenceType())
4528 return false;
4529 if (T.isPODType(C) || T->isObjCLifetimeType())
4530 return true;
4531
4532 if (const RecordType *RT = T->getAs<RecordType>())
4533 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4534 &CXXRecordDecl::hasTrivialCopyAssignment,
4535 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4536 &CXXMethodDecl::isCopyAssignmentOperator);
4537 return false;
4538 case UTT_HasNothrowMoveAssign:
4539 // This trait is implemented by MSVC 2012 and needed to parse the
4540 // standard library headers. Specifically this is used as the logic
4541 // behind std::is_nothrow_move_assignable (20.9.4.3).
4542 if (T.isPODType(C))
4543 return true;
4544
4545 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4546 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4547 &CXXRecordDecl::hasTrivialMoveAssignment,
4548 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4549 &CXXMethodDecl::isMoveAssignmentOperator);
4550 return false;
4551 case UTT_HasNothrowCopy:
4552 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4553 // If __has_trivial_copy (type) is true then the trait is true, else
4554 // if type is a cv class or union type with copy constructors that are
4555 // known not to throw an exception then the trait is true, else it is
4556 // false.
4557 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4558 return true;
4559 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4560 if (RD->hasTrivialCopyConstructor() &&
4561 !RD->hasNonTrivialCopyConstructor())
4562 return true;
4563
4564 bool FoundConstructor = false;
4565 unsigned FoundTQs;
4566 for (const auto *ND : Self.LookupConstructors(RD)) {
4567 // A template constructor is never a copy constructor.
4568 // FIXME: However, it may actually be selected at the actual overload
4569 // resolution point.
4570 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4571 continue;
4572 // UsingDecl itself is not a constructor
4573 if (isa<UsingDecl>(ND))
4574 continue;
4575 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4576 if (Constructor->isCopyConstructor(FoundTQs)) {
4577 FoundConstructor = true;
4578 const FunctionProtoType *CPT
4579 = Constructor->getType()->getAs<FunctionProtoType>();
4580 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4581 if (!CPT)
4582 return false;
4583 // TODO: check whether evaluating default arguments can throw.
4584 // For now, we'll be conservative and assume that they can throw.
4585 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
4586 return false;
4587 }
4588 }
4589
4590 return FoundConstructor;
4591 }
4592 return false;
4593 case UTT_HasNothrowConstructor:
4594 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4595 // If __has_trivial_constructor (type) is true then the trait is
4596 // true, else if type is a cv class or union type (or array
4597 // thereof) with a default constructor that is known not to
4598 // throw an exception then the trait is true, else it is false.
4599 if (T.isPODType(C) || T->isObjCLifetimeType())
4600 return true;
4601 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4602 if (RD->hasTrivialDefaultConstructor() &&
4603 !RD->hasNonTrivialDefaultConstructor())
4604 return true;
4605
4606 bool FoundConstructor = false;
4607 for (const auto *ND : Self.LookupConstructors(RD)) {
4608 // FIXME: In C++0x, a constructor template can be a default constructor.
4609 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4610 continue;
4611 // UsingDecl itself is not a constructor
4612 if (isa<UsingDecl>(ND))
4613 continue;
4614 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4615 if (Constructor->isDefaultConstructor()) {
4616 FoundConstructor = true;
4617 const FunctionProtoType *CPT
4618 = Constructor->getType()->getAs<FunctionProtoType>();
4619 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4620 if (!CPT)
4621 return false;
4622 // FIXME: check whether evaluating default arguments can throw.
4623 // For now, we'll be conservative and assume that they can throw.
4624 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
4625 return false;
4626 }
4627 }
4628 return FoundConstructor;
4629 }
4630 return false;
4631 case UTT_HasVirtualDestructor:
4632 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4633 // If type is a class type with a virtual destructor ([class.dtor])
4634 // then the trait is true, else it is false.
4635 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4636 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4637 return Destructor->isVirtual();
4638 return false;
4639
4640 // These type trait expressions are modeled on the specifications for the
4641 // Embarcadero C++0x type trait functions:
4642 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4643 case UTT_IsCompleteType:
4644 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4645 // Returns True if and only if T is a complete type at the point of the
4646 // function call.
4647 return !T->isIncompleteType();
4648 case UTT_HasUniqueObjectRepresentations:
4649 return C.hasUniqueObjectRepresentations(T);
4650 }
4651}
4652
4653static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4654 QualType RhsT, SourceLocation KeyLoc);
4655
4656static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4657 ArrayRef<TypeSourceInfo *> Args,
4658 SourceLocation RParenLoc) {
4659 if (Kind <= UTT_Last)
4660 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4661
4662 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4663 // traits to avoid duplication.
4664 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4665 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4666 Args[1]->getType(), RParenLoc);
4667
4668 switch (Kind) {
4669 case clang::BTT_ReferenceBindsToTemporary:
4670 case clang::TT_IsConstructible:
4671 case clang::TT_IsNothrowConstructible:
4672 case clang::TT_IsTriviallyConstructible: {
4673 // C++11 [meta.unary.prop]:
4674 // is_trivially_constructible is defined as:
4675 //
4676 // is_constructible<T, Args...>::value is true and the variable
4677 // definition for is_constructible, as defined below, is known to call
4678 // no operation that is not trivial.
4679 //
4680 // The predicate condition for a template specialization
4681 // is_constructible<T, Args...> shall be satisfied if and only if the
4682 // following variable definition would be well-formed for some invented
4683 // variable t:
4684 //
4685 // T t(create<Args>()...);
4686 assert(!Args.empty())(static_cast <bool> (!Args.empty()) ? void (0) : __assert_fail
("!Args.empty()", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4686, __extension__ __PRETTY_FUNCTION__))
;
4687
4688 // Precondition: T and all types in the parameter pack Args shall be
4689 // complete types, (possibly cv-qualified) void, or arrays of
4690 // unknown bound.
4691 for (const auto *TSI : Args) {
4692 QualType ArgTy = TSI->getType();
4693 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4694 continue;
4695
4696 if (S.RequireCompleteType(KWLoc, ArgTy,
4697 diag::err_incomplete_type_used_in_type_trait_expr))
4698 return false;
4699 }
4700
4701 // Make sure the first argument is not incomplete nor a function type.
4702 QualType T = Args[0]->getType();
4703 if (T->isIncompleteType() || T->isFunctionType())
4704 return false;
4705
4706 // Make sure the first argument is not an abstract type.
4707 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4708 if (RD && RD->isAbstract())
4709 return false;
4710
4711 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4712 SmallVector<Expr *, 2> ArgExprs;
4713 ArgExprs.reserve(Args.size() - 1);
4714 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4715 QualType ArgTy = Args[I]->getType();
4716 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4717 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4718 OpaqueArgExprs.push_back(
4719 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4720 ArgTy.getNonLValueExprType(S.Context),
4721 Expr::getValueKindForType(ArgTy)));
4722 }
4723 for (Expr &E : OpaqueArgExprs)
4724 ArgExprs.push_back(&E);
4725
4726 // Perform the initialization in an unevaluated context within a SFINAE
4727 // trap at translation unit scope.
4728 EnterExpressionEvaluationContext Unevaluated(
4729 S, Sema::ExpressionEvaluationContext::Unevaluated);
4730 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4731 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4732 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4733 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4734 RParenLoc));
4735 InitializationSequence Init(S, To, InitKind, ArgExprs);
4736 if (Init.Failed())
4737 return false;
4738
4739 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4740 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4741 return false;
4742
4743 if (Kind == clang::TT_IsConstructible)
4744 return true;
4745
4746 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4747 if (!T->isReferenceType())
4748 return false;
4749
4750 return !Init.isDirectReferenceBinding();
4751 }
4752
4753 if (Kind == clang::TT_IsNothrowConstructible)
4754 return S.canThrow(Result.get()) == CT_Cannot;
4755
4756 if (Kind == clang::TT_IsTriviallyConstructible) {
4757 // Under Objective-C ARC and Weak, if the destination has non-trivial
4758 // Objective-C lifetime, this is a non-trivial construction.
4759 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
4760 return false;
4761
4762 // The initialization succeeded; now make sure there are no non-trivial
4763 // calls.
4764 return !Result.get()->hasNonTrivialCall(S.Context);
4765 }
4766
4767 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4767)
;
4768 return false;
4769 }
4770 default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4770)
;
4771 }
4772
4773 return false;
4774}
4775
4776ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4777 ArrayRef<TypeSourceInfo *> Args,
4778 SourceLocation RParenLoc) {
4779 QualType ResultType = Context.getLogicalOperationType();
4780
4781 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4782 *this, Kind, KWLoc, Args[0]->getType()))
4783 return ExprError();
4784
4785 bool Dependent = false;
4786 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4787 if (Args[I]->getType()->isDependentType()) {
4788 Dependent = true;
4789 break;
4790 }
4791 }
4792
4793 bool Result = false;
4794 if (!Dependent)
4795 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4796
4797 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4798 RParenLoc, Result);
4799}
4800
4801ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4802 ArrayRef<ParsedType> Args,
4803 SourceLocation RParenLoc) {
4804 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
4805 ConvertedArgs.reserve(Args.size());
4806
4807 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4808 TypeSourceInfo *TInfo;
4809 QualType T = GetTypeFromParser(Args[I], &TInfo);
4810 if (!TInfo)
4811 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
4812
4813 ConvertedArgs.push_back(TInfo);
4814 }
4815
4816 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4817}
4818
4819static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4820 QualType RhsT, SourceLocation KeyLoc) {
4821 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&(static_cast <bool> (!LhsT->isDependentType() &&
!RhsT->isDependentType() && "Cannot evaluate traits of dependent types"
) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4822, __extension__ __PRETTY_FUNCTION__))
4822 "Cannot evaluate traits of dependent types")(static_cast <bool> (!LhsT->isDependentType() &&
!RhsT->isDependentType() && "Cannot evaluate traits of dependent types"
) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4822, __extension__ __PRETTY_FUNCTION__))
;
4823
4824 switch(BTT) {
4825 case BTT_IsBaseOf: {
4826 // C++0x [meta.rel]p2
4827 // Base is a base class of Derived without regard to cv-qualifiers or
4828 // Base and Derived are not unions and name the same class type without
4829 // regard to cv-qualifiers.
4830
4831 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4832 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4833 if (!rhsRecord || !lhsRecord) {
4834 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4835 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4836 if (!LHSObjTy || !RHSObjTy)
4837 return false;
4838
4839 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4840 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4841 if (!BaseInterface || !DerivedInterface)
4842 return false;
4843
4844 if (Self.RequireCompleteType(
4845 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4846 return false;
4847
4848 return BaseInterface->isSuperClassOf(DerivedInterface);
4849 }
4850
4851 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)(static_cast <bool> (Self.Context.hasSameUnqualifiedType
(LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4852, __extension__ __PRETTY_FUNCTION__))
4852 == (lhsRecord == rhsRecord))(static_cast <bool> (Self.Context.hasSameUnqualifiedType
(LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4852, __extension__ __PRETTY_FUNCTION__))
;
4853
4854 if (lhsRecord == rhsRecord)
4855 return !lhsRecord->getDecl()->isUnion();
4856
4857 // C++0x [meta.rel]p2:
4858 // If Base and Derived are class types and are different types
4859 // (ignoring possible cv-qualifiers) then Derived shall be a
4860 // complete type.
4861 if (Self.RequireCompleteType(KeyLoc, RhsT,
4862 diag::err_incomplete_type_used_in_type_trait_expr))
4863 return false;
4864
4865 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4866 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4867 }
4868 case BTT_IsSame:
4869 return Self.Context.hasSameType(LhsT, RhsT);
4870 case BTT_TypeCompatible: {
4871 // GCC ignores cv-qualifiers on arrays for this builtin.
4872 Qualifiers LhsQuals, RhsQuals;
4873 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
4874 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
4875 return Self.Context.typesAreCompatible(Lhs, Rhs);
4876 }
4877 case BTT_IsConvertible:
4878 case BTT_IsConvertibleTo: {
4879 // C++0x [meta.rel]p4:
4880 // Given the following function prototype:
4881 //
4882 // template <class T>
4883 // typename add_rvalue_reference<T>::type create();
4884 //
4885 // the predicate condition for a template specialization
4886 // is_convertible<From, To> shall be satisfied if and only if
4887 // the return expression in the following code would be
4888 // well-formed, including any implicit conversions to the return
4889 // type of the function:
4890 //
4891 // To test() {
4892 // return create<From>();
4893 // }
4894 //
4895 // Access checking is performed as if in a context unrelated to To and
4896 // From. Only the validity of the immediate context of the expression
4897 // of the return-statement (including conversions to the return type)
4898 // is considered.
4899 //
4900 // We model the initialization as a copy-initialization of a temporary
4901 // of the appropriate type, which for this expression is identical to the
4902 // return statement (since NRVO doesn't apply).
4903
4904 // Functions aren't allowed to return function or array types.
4905 if (RhsT->isFunctionType() || RhsT->isArrayType())
4906 return false;
4907
4908 // A return statement in a void function must have void type.
4909 if (RhsT->isVoidType())
4910 return LhsT->isVoidType();
4911
4912 // A function definition requires a complete, non-abstract return type.
4913 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
4914 return false;
4915
4916 // Compute the result of add_rvalue_reference.
4917 if (LhsT->isObjectType() || LhsT->isFunctionType())
4918 LhsT = Self.Context.getRValueReferenceType(LhsT);
4919
4920 // Build a fake source and destination for initialization.
4921 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
4922 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4923 Expr::getValueKindForType(LhsT));
4924 Expr *FromPtr = &From;
4925 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
4926 SourceLocation()));
4927
4928 // Perform the initialization in an unevaluated context within a SFINAE
4929 // trap at translation unit scope.
4930 EnterExpressionEvaluationContext Unevaluated(
4931 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4932 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4933 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4934 InitializationSequence Init(Self, To, Kind, FromPtr);
4935 if (Init.Failed())
4936 return false;
4937
4938 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
4939 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4940 }
4941
4942 case BTT_IsAssignable:
4943 case BTT_IsNothrowAssignable:
4944 case BTT_IsTriviallyAssignable: {
4945 // C++11 [meta.unary.prop]p3:
4946 // is_trivially_assignable is defined as:
4947 // is_assignable<T, U>::value is true and the assignment, as defined by
4948 // is_assignable, is known to call no operation that is not trivial
4949 //
4950 // is_assignable is defined as:
4951 // The expression declval<T>() = declval<U>() is well-formed when
4952 // treated as an unevaluated operand (Clause 5).
4953 //
4954 // For both, T and U shall be complete types, (possibly cv-qualified)
4955 // void, or arrays of unknown bound.
4956 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
4957 Self.RequireCompleteType(KeyLoc, LhsT,
4958 diag::err_incomplete_type_used_in_type_trait_expr))
4959 return false;
4960 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
4961 Self.RequireCompleteType(KeyLoc, RhsT,
4962 diag::err_incomplete_type_used_in_type_trait_expr))
4963 return false;
4964
4965 // cv void is never assignable.
4966 if (LhsT->isVoidType() || RhsT->isVoidType())
4967 return false;
4968
4969 // Build expressions that emulate the effect of declval<T>() and
4970 // declval<U>().
4971 if (LhsT->isObjectType() || LhsT->isFunctionType())
4972 LhsT = Self.Context.getRValueReferenceType(LhsT);
4973 if (RhsT->isObjectType() || RhsT->isFunctionType())
4974 RhsT = Self.Context.getRValueReferenceType(RhsT);
4975 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4976 Expr::getValueKindForType(LhsT));
4977 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4978 Expr::getValueKindForType(RhsT));
4979
4980 // Attempt the assignment in an unevaluated context within a SFINAE
4981 // trap at translation unit scope.
4982 EnterExpressionEvaluationContext Unevaluated(
4983 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4984 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4985 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4986 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4987 &Rhs);
4988 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4989 return false;
4990
4991 if (BTT == BTT_IsAssignable)
4992 return true;
4993
4994 if (BTT == BTT_IsNothrowAssignable)
4995 return Self.canThrow(Result.get()) == CT_Cannot;
4996
4997 if (BTT == BTT_IsTriviallyAssignable) {
4998 // Under Objective-C ARC and Weak, if the destination has non-trivial
4999 // Objective-C lifetime, this is a non-trivial assignment.
5000 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5001 return false;
5002
5003 return !Result.get()->hasNonTrivialCall(Self.Context);
5004 }
5005
5006 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5006)
;
5007 return false;
5008 }
5009 default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5009)
;
5010 }
5011 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5011)
;
5012}
5013
5014ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5015 SourceLocation KWLoc,
5016 ParsedType Ty,
5017 Expr* DimExpr,
5018 SourceLocation RParen) {
5019 TypeSourceInfo *TSInfo;
5020 QualType T = GetTypeFromParser(Ty, &TSInfo);
5021 if (!TSInfo)
5022 TSInfo = Context.getTrivialTypeSourceInfo(T);
5023
5024 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5025}
5026
5027static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5028 QualType T, Expr *DimExpr,
5029 SourceLocation KeyLoc) {
5030 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() &&
"Cannot evaluate traits of dependent type") ? void (0) : __assert_fail
("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5030, __extension__ __PRETTY_FUNCTION__))
;
5031
5032 switch(ATT) {
5033 case ATT_ArrayRank:
5034 if (T->isArrayType()) {
5035 unsigned Dim = 0;
5036 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5037 ++Dim;
5038 T = AT->getElementType();
5039 }
5040 return Dim;
5041 }
5042 return 0;
5043
5044 case ATT_ArrayExtent: {
5045 llvm::APSInt Value;
5046 uint64_t Dim;
5047 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5048 diag::err_dimension_expr_not_constant_integer,
5049 false).isInvalid())
5050 return 0;
5051 if (Value.isSigned() && Value.isNegative()) {
5052 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5053 << DimExpr->getSourceRange();
5054 return 0;
5055 }
5056 Dim = Value.getLimitedValue();
5057
5058 if (T->isArrayType()) {
5059 unsigned D = 0;
5060 bool Matched = false;
5061 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5062 if (Dim == D) {
5063 Matched = true;
5064 break;
5065 }
5066 ++D;
5067 T = AT->getElementType();
5068 }
5069
5070 if (Matched && T->isArrayType()) {
5071 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5072 return CAT->getSize().getLimitedValue();
5073 }
5074 }
5075 return 0;
5076 }
5077 }
5078 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5078)
;
5079}
5080
5081ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5082 SourceLocation KWLoc,
5083 TypeSourceInfo *TSInfo,
5084 Expr* DimExpr,
5085 SourceLocation RParen) {
5086 QualType T = TSInfo->getType();
5087
5088 // FIXME: This should likely be tracked as an APInt to remove any host
5089 // assumptions about the width of size_t on the target.
5090 uint64_t Value = 0;
5091 if (!T->isDependentType())
5092 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5093
5094 // While the specification for these traits from the Embarcadero C++
5095 // compiler's documentation says the return type is 'unsigned int', Clang
5096 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5097 // compiler, there is no difference. On several other platforms this is an
5098 // important distinction.
5099 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5100 RParen, Context.getSizeType());
5101}
5102
5103ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5104 SourceLocation KWLoc,
5105 Expr *Queried,
5106 SourceLocation RParen) {
5107 // If error parsing the expression, ignore.
5108 if (!Queried)
5109 return ExprError();
5110
5111 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5112
5113 return Result;
5114}
5115
5116static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5117 switch (ET) {
5118 case ET_IsLValueExpr: return E->isLValue();
5119 case ET_IsRValueExpr: return E->isRValue();
5120 }
5121 llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5121)
;
5122}
5123
5124ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5125 SourceLocation KWLoc,
5126 Expr *Queried,
5127 SourceLocation RParen) {
5128 if (Queried->isTypeDependent()) {
5129 // Delay type-checking for type-dependent expressions.
5130 } else if (Queried->getType()->isPlaceholderType()) {
5131 ExprResult PE = CheckPlaceholderExpr(Queried);
5132 if (PE.isInvalid()) return ExprError();
5133 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5134 }
5135
5136 bool Value = EvaluateExpressionTrait(ET, Queried);
5137
5138 return new (Context)
5139 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5140}
5141
5142QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5143 ExprValueKind &VK,
5144 SourceLocation Loc,
5145 bool isIndirect) {
5146 assert(!LHS.get()->getType()->isPlaceholderType() &&(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType
() && !RHS.get()->getType()->isPlaceholderType(
) && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5148, __extension__ __PRETTY_FUNCTION__))
5147 !RHS.get()->getType()->isPlaceholderType() &&(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType
() && !RHS.get()->getType()->isPlaceholderType(
) && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5148, __extension__ __PRETTY_FUNCTION__))
5148 "placeholders should have been weeded out by now")(static_cast <bool> (!LHS.get()->getType()->isPlaceholderType
() && !RHS.get()->getType()->isPlaceholderType(
) && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5148, __extension__ __PRETTY_FUNCTION__))
;
5149
5150 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5151 // temporary materialization conversion otherwise.
5152 if (isIndirect)
5153 LHS = DefaultLvalueConversion(LHS.get());
5154 else if (LHS.get()->isRValue())
5155 LHS = TemporaryMaterializationConversion(LHS.get());
5156 if (LHS.isInvalid())
5157 return QualType();
5158
5159 // The RHS always undergoes lvalue conversions.
5160 RHS = DefaultLvalueConversion(RHS.get());
5161 if (RHS.isInvalid()) return QualType();
5162
5163 const char *OpSpelling = isIndirect ? "->*" : ".*";
5164 // C++ 5.5p2
5165 // The binary operator .* [p3: ->*] binds its second operand, which shall
5166 // be of type "pointer to member of T" (where T is a completely-defined
5167 // class type) [...]
5168 QualType RHSType = RHS.get()->getType();
5169 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5170 if (!MemPtr) {
5171 Diag(Loc, diag::err_bad_memptr_rhs)
5172 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5173 return QualType();
5174 }
5175
5176 QualType Class(MemPtr->getClass(), 0);
5177
5178 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5179 // member pointer points must be completely-defined. However, there is no
5180 // reason for this semantic distinction, and the rule is not enforced by
5181 // other compilers. Therefore, we do not check this property, as it is
5182 // likely to be considered a defect.
5183
5184 // C++ 5.5p2
5185 // [...] to its first operand, which shall be of class T or of a class of
5186 // which T is an unambiguous and accessible base class. [p3: a pointer to
5187 // such a class]
5188 QualType LHSType = LHS.get()->getType();
5189 if (isIndirect) {
5190 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5191 LHSType = Ptr->getPointeeType();
5192 else {
5193 Diag(Loc, diag::err_bad_memptr_lhs)
5194 << OpSpelling << 1 << LHSType
5195 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5196 return QualType();
5197 }
5198 }
5199
5200 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5201 // If we want to check the hierarchy, we need a complete type.
5202 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5203 OpSpelling, (int)isIndirect)) {
5204 return QualType();
5205 }
5206
5207 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5208 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5209 << (int)isIndirect << LHS.get()->getType();
5210 return QualType();
5211 }
5212
5213 CXXCastPath BasePath;
5214 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5215 SourceRange(LHS.get()->getLocStart(),
5216 RHS.get()->getLocEnd()),
5217 &BasePath))
5218 return QualType();
5219
5220 // Cast LHS to type of use.
5221 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5222 if (isIndirect)
5223 UseType = Context.getPointerType(UseType);
5224 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5225 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5226 &BasePath);
5227 }
5228
5229 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5230 // Diagnose use of pointer-to-member type which when used as
5231 // the functional cast in a pointer-to-member expression.
5232 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5233 return QualType();
5234 }
5235
5236 // C++ 5.5p2
5237 // The result is an object or a function of the type specified by the
5238 // second operand.
5239 // The cv qualifiers are the union of those in the pointer and the left side,
5240 // in accordance with 5.5p5 and 5.2.5.
5241 QualType Result = MemPtr->getPointeeType();
5242 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5243
5244 // C++0x [expr.mptr.oper]p6:
5245 // In a .* expression whose object expression is an rvalue, the program is
5246 // ill-formed if the second operand is a pointer to member function with
5247 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5248 // expression is an lvalue, the program is ill-formed if the second operand
5249 // is a pointer to member function with ref-qualifier &&.
5250 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5251 switch (Proto->getRefQualifier()) {
5252 case RQ_None:
5253 // Do nothing
5254 break;
5255
5256 case RQ_LValue:
5257 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5258 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5259 if (Proto->isConst())
5260 Diag(Loc, getLangOpts().CPlusPlus2a
5261 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5262 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5263 else
5264 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5265 << RHSType << 1 << LHS.get()->getSourceRange();
5266 }
5267 break;
5268
5269 case RQ_RValue:
5270 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5271 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5272 << RHSType << 0 << LHS.get()->getSourceRange();
5273 break;
5274 }
5275 }
5276
5277 // C++ [expr.mptr.oper]p6:
5278 // The result of a .* expression whose second operand is a pointer
5279 // to a data member is of the same value category as its
5280 // first operand. The result of a .* expression whose second
5281 // operand is a pointer to a member function is a prvalue. The
5282 // result of an ->* expression is an lvalue if its second operand
5283 // is a pointer to data member and a prvalue otherwise.
5284 if (Result->isFunctionType()) {
5285 VK = VK_RValue;
5286 return Context.BoundMemberTy;
5287 } else if (isIndirect) {
5288 VK = VK_LValue;
5289 } else {
5290 VK = LHS.get()->getValueKind();
5291 }
5292
5293 return Result;
5294}
5295
5296/// \brief Try to convert a type to another according to C++11 5.16p3.
5297///
5298/// This is part of the parameter validation for the ? operator. If either
5299/// value operand is a class type, the two operands are attempted to be
5300/// converted to each other. This function does the conversion in one direction.
5301/// It returns true if the program is ill-formed and has already been diagnosed
5302/// as such.
5303static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5304 SourceLocation QuestionLoc,
5305 bool &HaveConversion,
5306 QualType &ToType) {
5307 HaveConversion = false;
5308 ToType = To->getType();
5309
5310 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
5311 SourceLocation());
5312 // C++11 5.16p3
5313 // The process for determining whether an operand expression E1 of type T1
5314 // can be converted to match an operand expression E2 of type T2 is defined
5315 // as follows:
5316 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5317 // implicitly converted to type "lvalue reference to T2", subject to the
5318 // constraint that in the conversion the reference must bind directly to
5319 // an lvalue.
5320 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5321 // implicitly conveted to the type "rvalue reference to R2", subject to
5322 // the constraint that the reference must bind directly.
5323 if (To->isLValue() || To->isXValue()) {
5324 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5325 : Self.Context.getRValueReferenceType(ToType);
5326
5327 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5328
5329 InitializationSequence InitSeq(Self, Entity, Kind, From);
5330 if (InitSeq.isDirectReferenceBinding()) {
5331 ToType = T;
5332 HaveConversion = true;
5333 return false;
5334 }
5335
5336 if (InitSeq.isAmbiguous())
5337 return InitSeq.Diagnose(Self, Entity, Kind, From);
5338 }
5339
5340 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5341 // -- if E1 and E2 have class type, and the underlying class types are
5342 // the same or one is a base class of the other:
5343 QualType FTy = From->getType();
5344 QualType TTy = To->getType();
5345 const RecordType *FRec = FTy->getAs<RecordType>();
5346 const RecordType *TRec = TTy->getAs<RecordType>();
5347 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5348 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5349 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5350 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5351 // E1 can be converted to match E2 if the class of T2 is the
5352 // same type as, or a base class of, the class of T1, and
5353 // [cv2 > cv1].
5354 if (FRec == TRec || FDerivedFromT) {
5355 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5356 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5357 InitializationSequence InitSeq(Self, Entity, Kind, From);
5358 if (InitSeq) {
5359 HaveConversion = true;
5360 return false;
5361 }
5362
5363 if (InitSeq.isAmbiguous())
5364 return InitSeq.Diagnose(Self, Entity, Kind, From);
5365 }
5366 }
5367
5368 return false;
5369 }
5370
5371 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5372 // implicitly converted to the type that expression E2 would have
5373 // if E2 were converted to an rvalue (or the type it has, if E2 is
5374 // an rvalue).
5375 //
5376 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5377 // to the array-to-pointer or function-to-pointer conversions.
5378 TTy = TTy.getNonLValueExprType(Self.Context);
5379
5380 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5381 InitializationSequence InitSeq(Self, Entity, Kind, From);
5382 HaveConversion = !InitSeq.Failed();
5383 ToType = TTy;
5384 if (InitSeq.isAmbiguous())
5385 return InitSeq.Diagnose(Self, Entity, Kind, From);
5386
5387 return false;
5388}
5389
5390/// \brief Try to find a common type for two according to C++0x 5.16p5.
5391///
5392/// This is part of the parameter validation for the ? operator. If either
5393/// value operand is a class type, overload resolution is used to find a
5394/// conversion to a common type.
5395static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5396 SourceLocation QuestionLoc) {
5397 Expr *Args[2] = { LHS.get(), RHS.get() };
5398 OverloadCandidateSet CandidateSet(QuestionLoc,
5399 OverloadCandidateSet::CSK_Operator);
5400 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5401 CandidateSet);
5402
5403 OverloadCandidateSet::iterator Best;
5404 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5405 case OR_Success: {
5406 // We found a match. Perform the conversions on the arguments and move on.
5407 ExprResult LHSRes = Self.PerformImplicitConversion(
5408 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5409 Sema::AA_Converting);
5410 if (LHSRes.isInvalid())
5411 break;
5412 LHS = LHSRes;
5413
5414 ExprResult RHSRes = Self.PerformImplicitConversion(
5415 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5416 Sema::AA_Converting);
5417 if (RHSRes.isInvalid())
5418 break;
5419 RHS = RHSRes;
5420 if (Best->Function)
5421 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5422 return false;
5423 }
5424
5425 case OR_No_Viable_Function:
5426
5427 // Emit a better diagnostic if one of the expressions is a null pointer
5428 // constant and the other is a pointer type. In this case, the user most
5429 // likely forgot to take the address of the other expression.
5430 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5431 return true;
5432
5433 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5434 << LHS.get()->getType() << RHS.get()->getType()
5435 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5436 return true;
5437
5438 case OR_Ambiguous:
5439 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5440 << LHS.get()->getType() << RHS.get()->getType()
5441 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5442 // FIXME: Print the possible common types by printing the return types of
5443 // the viable candidates.
5444 break;
5445
5446 case OR_Deleted:
5447 llvm_unreachable("Conditional operator has only built-in overloads")::llvm::llvm_unreachable_internal("Conditional operator has only built-in overloads"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5447)
;
5448 }
5449 return true;
5450}
5451
5452/// \brief Perform an "extended" implicit conversion as returned by
5453/// TryClassUnification.
5454static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5455 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5456 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
5457 SourceLocation());
5458 Expr *Arg = E.get();
5459 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5460 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5461 if (Result.isInvalid())
5462 return true;
5463
5464 E = Result;
5465 return false;
5466}
5467
5468/// \brief Check the operands of ?: under C++ semantics.
5469///
5470/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5471/// extension. In this case, LHS == Cond. (But they're not aliases.)
5472QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5473 ExprResult &RHS, ExprValueKind &VK,
5474 ExprObjectKind &OK,
5475 SourceLocation QuestionLoc) {
5476 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5477 // interface pointers.
5478
5479 // C++11 [expr.cond]p1
5480 // The first expression is contextually converted to bool.
5481 //
5482 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5483 // a is that of a integer vector with the same number of elements and
5484 // size as the vectors of b and c. If one of either b or c is a scalar
5485 // it is implicitly converted to match the type of the vector.
5486 // Otherwise the expression is ill-formed. If both b and c are scalars,
5487 // then b and c are checked and converted to the type of a if possible.
5488 // Unlike the OpenCL ?: operator, the expression is evaluated as
5489 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5490 if (!Cond.get()->isTypeDependent()) {
5491 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5492 if (CondRes.isInvalid())
5493 return QualType();
5494 Cond = CondRes;
5495 }
5496
5497 // Assume r-value.
5498 VK = VK_RValue;
5499 OK = OK_Ordinary;
5500
5501 // Either of the arguments dependent?
5502 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5503 return Context.DependentTy;
5504
5505 // C++11 [expr.cond]p2
5506 // If either the second or the third operand has type (cv) void, ...
5507 QualType LTy = LHS.get()->getType();
5508 QualType RTy = RHS.get()->getType();
5509 bool LVoid = LTy->isVoidType();
5510 bool RVoid = RTy->isVoidType();
5511 if (LVoid || RVoid) {
5512 // ... one of the following shall hold:
5513 // -- The second or the third operand (but not both) is a (possibly
5514 // parenthesized) throw-expression; the result is of the type
5515 // and value category of the other.
5516 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5517 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5518 if (LThrow != RThrow) {
5519 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5520 VK = NonThrow->getValueKind();
5521 // DR (no number yet): the result is a bit-field if the
5522 // non-throw-expression operand is a bit-field.
5523 OK = NonThrow->getObjectKind();
5524 return NonThrow->getType();
5525 }
5526
5527 // -- Both the second and third operands have type void; the result is of
5528 // type void and is a prvalue.
5529 if (LVoid && RVoid)
5530 return Context.VoidTy;
5531
5532 // Neither holds, error.
5533 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5534 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5535 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5536 return QualType();
5537 }
5538
5539 // Neither is void.
5540
5541 // C++11 [expr.cond]p3
5542 // Otherwise, if the second and third operand have different types, and
5543 // either has (cv) class type [...] an attempt is made to convert each of
5544 // those operands to the type of the other.
5545 if (!Context.hasSameType(LTy, RTy) &&
5546 (LTy->isRecordType() || RTy->isRecordType())) {
5547 // These return true if a single direction is already ambiguous.
5548 QualType L2RType, R2LType;
5549 bool HaveL2R, HaveR2L;
5550 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5551 return QualType();
5552 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5553 return QualType();
5554
5555 // If both can be converted, [...] the program is ill-formed.
5556 if (HaveL2R && HaveR2L) {
5557 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5558 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5559 return QualType();
5560 }
5561
5562 // If exactly one conversion is possible, that conversion is applied to
5563 // the chosen operand and the converted operands are used in place of the
5564 // original operands for the remainder of this section.
5565 if (HaveL2R) {
5566 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5567 return QualType();
5568 LTy = LHS.get()->getType();
5569 } else if (HaveR2L) {
5570 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5571 return QualType();
5572 RTy = RHS.get()->getType();
5573 }
5574 }
5575
5576 // C++11 [expr.cond]p3
5577 // if both are glvalues of the same value category and the same type except
5578 // for cv-qualification, an attempt is made to convert each of those
5579 // operands to the type of the other.
5580 // FIXME:
5581 // Resolving a defect in P0012R1: we extend this to cover all cases where
5582 // one of the operands is reference-compatible with the other, in order
5583 // to support conditionals between functions differing in noexcept.
5584 ExprValueKind LVK = LHS.get()->getValueKind();
5585 ExprValueKind RVK = RHS.get()->getValueKind();
5586 if (!Context.hasSameType(LTy, RTy) &&
5587 LVK == RVK && LVK != VK_RValue) {
5588 // DerivedToBase was already handled by the class-specific case above.
5589 // FIXME: Should we allow ObjC conversions here?
5590 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5591 if (CompareReferenceRelationship(
5592 QuestionLoc, LTy, RTy, DerivedToBase,
5593 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5594 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5595 // [...] subject to the constraint that the reference must bind
5596 // directly [...]
5597 !RHS.get()->refersToBitField() &&
5598 !RHS.get()->refersToVectorElement()) {
5599 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5600 RTy = RHS.get()->getType();
5601 } else if (CompareReferenceRelationship(
5602 QuestionLoc, RTy, LTy, DerivedToBase,
5603 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5604 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5605 !LHS.get()->refersToBitField() &&
5606 !LHS.get()->refersToVectorElement()) {
5607 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5608 LTy = LHS.get()->getType();
5609 }
5610 }
5611
5612 // C++11 [expr.cond]p4
5613 // If the second and third operands are glvalues of the same value
5614 // category and have the same type, the result is of that type and
5615 // value category and it is a bit-field if the second or the third
5616 // operand is a bit-field, or if both are bit-fields.
5617 // We only extend this to bitfields, not to the crazy other kinds of
5618 // l-values.
5619 bool Same = Context.hasSameType(LTy, RTy);
5620 if (Same && LVK == RVK && LVK != VK_RValue &&
5621 LHS.get()->isOrdinaryOrBitFieldObject() &&
5622 RHS.get()->isOrdinaryOrBitFieldObject()) {
5623 VK = LHS.get()->getValueKind();
5624 if (LHS.get()->getObjectKind() == OK_BitField ||
5625 RHS.get()->getObjectKind() == OK_BitField)
5626 OK = OK_BitField;
5627
5628 // If we have function pointer types, unify them anyway to unify their
5629 // exception specifications, if any.
5630 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5631 Qualifiers Qs = LTy.getQualifiers();
5632 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
5633 /*ConvertArgs*/false);
5634 LTy = Context.getQualifiedType(LTy, Qs);
5635
5636 assert(!LTy.isNull() && "failed to find composite pointer type for "(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? void (0) : __assert_fail
("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5637, __extension__ __PRETTY_FUNCTION__))
5637 "canonically equivalent function ptr types")(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? void (0) : __assert_fail
("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5637, __extension__ __PRETTY_FUNCTION__))
;
5638 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type")(static_cast <bool> (Context.hasSameType(LTy, RTy) &&
"bad composite pointer type") ? void (0) : __assert_fail ("Context.hasSameType(LTy, RTy) && \"bad composite pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5638, __extension__ __PRETTY_FUNCTION__))
;
5639 }
5640
5641 return LTy;
5642 }
5643
5644 // C++11 [expr.cond]p5
5645 // Otherwise, the result is a prvalue. If the second and third operands
5646 // do not have the same type, and either has (cv) class type, ...
5647 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5648 // ... overload resolution is used to determine the conversions (if any)
5649 // to be applied to the operands. If the overload resolution fails, the
5650 // program is ill-formed.
5651 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5652 return QualType();
5653 }
5654
5655 // C++11 [expr.cond]p6
5656 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5657 // conversions are performed on the second and third operands.
5658 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5659 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5660 if (LHS.isInvalid() || RHS.isInvalid())
5661 return QualType();
5662 LTy = LHS.get()->getType();
5663 RTy = RHS.get()->getType();
5664
5665 // After those conversions, one of the following shall hold:
5666 // -- The second and third operands have the same type; the result
5667 // is of that type. If the operands have class type, the result
5668 // is a prvalue temporary of the result type, which is
5669 // copy-initialized from either the second operand or the third
5670 // operand depending on the value of the first operand.
5671 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5672 if (LTy->isRecordType()) {
5673 // The operands have class type. Make a temporary copy.
5674 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5675
5676 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5677 SourceLocation(),
5678 LHS);
5679 if (LHSCopy.isInvalid())
5680 return QualType();
5681
5682 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5683 SourceLocation(),
5684 RHS);
5685 if (RHSCopy.isInvalid())
5686 return QualType();
5687
5688 LHS = LHSCopy;
5689 RHS = RHSCopy;
5690 }
5691
5692 // If we have function pointer types, unify them anyway to unify their
5693 // exception specifications, if any.
5694 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5695 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5696 assert(!LTy.isNull() && "failed to find composite pointer type for "(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? void (0) : __assert_fail
("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5697, __extension__ __PRETTY_FUNCTION__))
5697 "canonically equivalent function ptr types")(static_cast <bool> (!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? void (0) : __assert_fail
("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5697, __extension__ __PRETTY_FUNCTION__))
;
5698 }
5699
5700 return LTy;
5701 }
5702
5703 // Extension: conditional operator involving vector types.
5704 if (LTy->isVectorType() || RTy->isVectorType())
5705 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5706 /*AllowBothBool*/true,
5707 /*AllowBoolConversions*/false);
5708
5709 // -- The second and third operands have arithmetic or enumeration type;
5710 // the usual arithmetic conversions are performed to bring them to a
5711 // common type, and the result is of that type.
5712 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5713 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5714 if (LHS.isInvalid() || RHS.isInvalid())
5715 return QualType();
5716 if (ResTy.isNull()) {
5717 Diag(QuestionLoc,
5718 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5719 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5720 return QualType();
5721 }
5722
5723 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5724 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5725
5726 return ResTy;
5727 }
5728
5729 // -- The second and third operands have pointer type, or one has pointer
5730 // type and the other is a null pointer constant, or both are null
5731 // pointer constants, at least one of which is non-integral; pointer
5732 // conversions and qualification conversions are performed to bring them
5733 // to their composite pointer type. The result is of the composite
5734 // pointer type.
5735 // -- The second and third operands have pointer to member type, or one has
5736 // pointer to member type and the other is a null pointer constant;
5737 // pointer to member conversions and qualification conversions are
5738 // performed to bring them to a common type, whose cv-qualification
5739 // shall match the cv-qualification of either the second or the third
5740 // operand. The result is of the common type.
5741 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5742 if (!Composite.isNull())
5743 return Composite;
5744
5745 // Similarly, attempt to find composite type of two objective-c pointers.
5746 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5747 if (!Composite.isNull())
5748 return Composite;
5749
5750 // Check if we are using a null with a non-pointer type.
5751 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5752 return QualType();
5753
5754 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5755 << LHS.get()->getType() << RHS.get()->getType()
5756 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5757 return QualType();
5758}
5759
5760static FunctionProtoType::ExceptionSpecInfo
5761mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5762 FunctionProtoType::ExceptionSpecInfo ESI2,
5763 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5764 ExceptionSpecificationType EST1 = ESI1.Type;
5765 ExceptionSpecificationType EST2 = ESI2.Type;
5766
5767 // If either of them can throw anything, that is the result.
5768 if (EST1 == EST_None) return ESI1;
5769 if (EST2 == EST_None) return ESI2;
5770 if (EST1 == EST_MSAny) return ESI1;
5771 if (EST2 == EST_MSAny) return ESI2;
5772
5773 // If either of them is non-throwing, the result is the other.
5774 if (EST1 == EST_DynamicNone) return ESI2;
5775 if (EST2 == EST_DynamicNone) return ESI1;
5776 if (EST1 == EST_BasicNoexcept) return ESI2;
5777 if (EST2 == EST_BasicNoexcept) return ESI1;
5778
5779 // If either of them is a non-value-dependent computed noexcept, that
5780 // determines the result.
5781 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5782 !ESI2.NoexceptExpr->isValueDependent())
5783 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5784 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5785 !ESI1.NoexceptExpr->isValueDependent())
5786 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5787 // If we're left with value-dependent computed noexcept expressions, we're
5788 // stuck. Before C++17, we can just drop the exception specification entirely,
5789 // since it's not actually part of the canonical type. And this should never
5790 // happen in C++17, because it would mean we were computing the composite
5791 // pointer type of dependent types, which should never happen.
5792 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5793 assert(!S.getLangOpts().CPlusPlus17 &&(static_cast <bool> (!S.getLangOpts().CPlusPlus17 &&
"computing composite pointer type of dependent types") ? void
(0) : __assert_fail ("!S.getLangOpts().CPlusPlus17 && \"computing composite pointer type of dependent types\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5794, __extension__ __PRETTY_FUNCTION__))
5794 "computing composite pointer type of dependent types")(static_cast <bool> (!S.getLangOpts().CPlusPlus17 &&
"computing composite pointer type of dependent types") ? void
(0) : __assert_fail ("!S.getLangOpts().CPlusPlus17 && \"computing composite pointer type of dependent types\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5794, __extension__ __PRETTY_FUNCTION__))
;
5795 return FunctionProtoType::ExceptionSpecInfo();
5796 }
5797
5798 // Switch over the possibilities so that people adding new values know to
5799 // update this function.
5800 switch (EST1) {
5801 case EST_None:
5802 case EST_DynamicNone:
5803 case EST_MSAny:
5804 case EST_BasicNoexcept:
5805 case EST_ComputedNoexcept:
5806 llvm_unreachable("handled above")::llvm::llvm_unreachable_internal("handled above", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5806)
;
5807
5808 case EST_Dynamic: {
5809 // This is the fun case: both exception specifications are dynamic. Form
5810 // the union of the two lists.
5811 assert(EST2 == EST_Dynamic && "other cases should already be handled")(static_cast <bool> (EST2 == EST_Dynamic && "other cases should already be handled"
) ? void (0) : __assert_fail ("EST2 == EST_Dynamic && \"other cases should already be handled\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5811, __extension__ __PRETTY_FUNCTION__))
;
5812 llvm::SmallPtrSet<QualType, 8> Found;
5813 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5814 for (QualType E : Exceptions)
5815 if (Found.insert(S.Context.getCanonicalType(E)).second)
5816 ExceptionTypeStorage.push_back(E);
5817
5818 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5819 Result.Exceptions = ExceptionTypeStorage;
5820 return Result;
5821 }
5822
5823 case EST_Unevaluated:
5824 case EST_Uninstantiated:
5825 case EST_Unparsed:
5826 llvm_unreachable("shouldn't see unresolved exception specifications here")::llvm::llvm_unreachable_internal("shouldn't see unresolved exception specifications here"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5826)
;
5827 }
5828
5829 llvm_unreachable("invalid ExceptionSpecificationType")::llvm::llvm_unreachable_internal("invalid ExceptionSpecificationType"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5829)
;
5830}
5831
5832/// \brief Find a merged pointer type and convert the two expressions to it.
5833///
5834/// This finds the composite pointer type (or member pointer type) for @p E1
5835/// and @p E2 according to C++1z 5p14. It converts both expressions to this
5836/// type and returns it.
5837/// It does not emit diagnostics.
5838///
5839/// \param Loc The location of the operator requiring these two expressions to
5840/// be converted to the composite pointer type.
5841///
5842/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
5843QualType Sema::FindCompositePointerType(SourceLocation Loc,
5844 Expr *&E1, Expr *&E2,
5845 bool ConvertArgs) {
5846 assert(getLangOpts().CPlusPlus && "This function assumes C++")(static_cast <bool> (getLangOpts().CPlusPlus &&
"This function assumes C++") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"This function assumes C++\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5846, __extension__ __PRETTY_FUNCTION__))
;
5847
5848 // C++1z [expr]p14:
5849 // The composite pointer type of two operands p1 and p2 having types T1
5850 // and T2
5851 QualType T1 = E1->getType(), T2 = E2->getType();
5852
5853 // where at least one is a pointer or pointer to member type or
5854 // std::nullptr_t is:
5855 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5856 T1->isNullPtrType();
5857 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||