Bug Summary

File:tools/clang/lib/Sema/SemaExprCXX.cpp
Warning:line 459, column 7
Called C++ object pointer is null

Annotated Source Code

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/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
36#include "clang/Sema/SemaLambda.h"
37#include "clang/Sema/TemplateDeduction.h"
38#include "llvm/ADT/APInt.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41using namespace clang;
42using namespace sema;
43
44/// \brief Handle the result of the special case name lookup for inheriting
45/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name")((NNS->getAsIdentifier() == &Name && "not a constructor name"
) ? static_cast<void> (0) : __assert_fail ("NNS->getAsIdentifier() == &Name && \"not a constructor name\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 64, __PRETTY_FUNCTION__))
;
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
70 case NestedNameSpecifier::Super:
71 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor")::llvm::llvm_unreachable_internal("Nested name specifier is not a type for inheriting ctor"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 73)
;
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
82ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
83 IdentifierInfo &II,
84 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
88 // Determine where to perform name lookup.
89
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
96 //
97 // namespace N {
98 // template <typename T> struct S {
99 // ~S();
100 // };
101 // }
102 //
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
105 // }
106 //
107 // See also PR6358 and PR6359.
108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
110 QualType SearchType;
111 DeclContext *LookupCtx = nullptr;
112 bool isDependent = false;
113 bool LookInScope = false;
114
115 if (SS.isInvalid())
116 return nullptr;
117
118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
121 if (ObjectTypePtr)
122 SearchType = GetTypeFromParser(ObjectTypePtr);
123
124 if (SS.isSet()) {
125 NestedNameSpecifier *NNS = SS.getScopeRep();
126
127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
129 // C++11 [basic.lookup.qual]p6:
130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
131 // the type-names are looked up as types in the scope designated by the
132 // nested-name-specifier. Similarly, in a qualified-id of the form:
133 //
134 // nested-name-specifier[opt] class-name :: ~ class-name
135 //
136 // the second class-name is looked up in the same scope as the first.
137 //
138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
143 LookupCtx = DC;
144 isDependent = false;
145 } else if (DC && isa<CXXRecordDecl>(DC)) {
146 LookAtPrefix = false;
147 LookInScope = true;
148 }
149
150 // The second case from the C++03 rules quoted further above.
151 NestedNameSpecifier *Prefix = nullptr;
152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
159 } else if (ObjectTypePtr) {
160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
162 } else {
163 LookupCtx = computeDeclContext(SS, EnteringContext);
164 isDependent = LookupCtx && LookupCtx->isDependentContext();
165 }
166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
173 // cv-qualified) T.
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
176 assert((isDependent || !SearchType->isIncompleteType()) &&(((isDependent || !SearchType->isIncompleteType()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 177, __PRETTY_FUNCTION__))
177 "Caller should have completed object type")(((isDependent || !SearchType->isIncompleteType()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 177, __PRETTY_FUNCTION__))
;
178
179 LookInScope = true;
180 } else {
181 // Perform lookup into the current scope (only).
182 LookInScope = true;
183 }
184
185 TypeDecl *NonMatchingTypeDecl = nullptr;
186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
189 // have one) and, if that fails to find a match, in the scope (if
190 // we're allowed to look there).
191 Found.clear();
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
194 else if (Step == 1 && LookInScope && S)
195 LookupName(Found, S);
196 else
197 continue;
198
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
201 return nullptr;
202
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
206
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
210
211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
213 }
214
215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
217 }
218
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
224 // issue 399, for which there isn't even an obvious direction.
225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
227 if (SS.isSet()) {
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
232 }
233 }
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
236
237 if (MemberOfType.isNull())
238 continue;
239
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
248 return CreateParsedType(
249 MemberOfType,
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
251 }
252
253 continue;
254 }
255
256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
264
265 // The class template we found is the same template being
266 // specialized.
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
269 return CreateParsedType(
270 MemberOfType,
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
272
273 continue;
274 }
275
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
278 if (DependentTemplateName *DepTemplate
279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
282 return CreateParsedType(
283 MemberOfType,
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
285
286 continue;
287 }
288 }
289 }
290 }
291
292 if (isDependent) {
293 // We didn't find our type, but that's okay: it's dependent
294 // anyway.
295
296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
299 II, NameLoc);
300 return ParsedType::make(T);
301 }
302
303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
306 << T << SearchType;
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
308 << T;
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
311 << &II;
312 else {
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
315 if (S) {
316 const DeclContext *Ctx = S->getEntity();
317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
320 }
321 }
322
323 return nullptr;
324}
325
326ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
327 ParsedType ObjectType) {
328 if (DS.getTypeSpecType() == DeclSpec::TST_error)
329 return nullptr;
330
331 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
332 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
333 return nullptr;
334 }
335
336 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&((DS.getTypeSpecType() == DeclSpec::TST_decltype && "unexpected type in getDestructorType"
) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 337, __PRETTY_FUNCTION__))
337 "unexpected type in getDestructorType")((DS.getTypeSpecType() == DeclSpec::TST_decltype && "unexpected type in getDestructorType"
) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 337, __PRETTY_FUNCTION__))
;
338 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
339
340 // If we know the type of the object, check that the correct destructor
341 // type was named now; we can give better diagnostics this way.
342 QualType SearchType = GetTypeFromParser(ObjectType);
343 if (!SearchType.isNull() && !SearchType->isDependentType() &&
344 !Context.hasSameUnqualifiedType(T, SearchType)) {
345 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
346 << T << SearchType;
347 return nullptr;
348 }
349
350 return ParsedType::make(T);
351}
352
353bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
354 const UnqualifiedId &Name) {
355 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId)((Name.getKind() == UnqualifiedId::IK_LiteralOperatorId) ? static_cast
<void> (0) : __assert_fail ("Name.getKind() == UnqualifiedId::IK_LiteralOperatorId"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 355, __PRETTY_FUNCTION__))
;
356
357 if (!SS.isValid())
358 return false;
359
360 switch (SS.getScopeRep()->getKind()) {
361 case NestedNameSpecifier::Identifier:
362 case NestedNameSpecifier::TypeSpec:
363 case NestedNameSpecifier::TypeSpecWithTemplate:
364 // Per C++11 [over.literal]p2, literal operators can only be declared at
365 // namespace scope. Therefore, this unqualified-id cannot name anything.
366 // Reject it early, because we have no AST representation for this in the
367 // case where the scope is dependent.
368 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
369 << SS.getScopeRep();
370 return true;
371
372 case NestedNameSpecifier::Global:
373 case NestedNameSpecifier::Super:
374 case NestedNameSpecifier::Namespace:
375 case NestedNameSpecifier::NamespaceAlias:
376 return false;
377 }
378
379 llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 379)
;
380}
381
382/// \brief Build a C++ typeid expression with a type operand.
383ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
384 SourceLocation TypeidLoc,
385 TypeSourceInfo *Operand,
386 SourceLocation RParenLoc) {
387 // C++ [expr.typeid]p4:
388 // The top-level cv-qualifiers of the lvalue expression or the type-id
389 // that is the operand of typeid are always ignored.
390 // If the type of the type-id is a class type or a reference to a class
391 // type, the class shall be completely-defined.
392 Qualifiers Quals;
393 QualType T
394 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
395 Quals);
396 if (T->getAs<RecordType>() &&
397 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
398 return ExprError();
399
400 if (T->isVariablyModifiedType())
401 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
402
403 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
404 SourceRange(TypeidLoc, RParenLoc));
405}
406
407/// \brief Build a C++ typeid expression with an expression operand.
408ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
409 SourceLocation TypeidLoc,
410 Expr *E,
411 SourceLocation RParenLoc) {
412 bool WasEvaluated = false;
413 if (E && !E->isTypeDependent()) {
11
Assuming 'E' is null
414 if (E->getType()->isPlaceholderType()) {
415 ExprResult result = CheckPlaceholderExpr(E);
416 if (result.isInvalid()) return ExprError();
417 E = result.get();
418 }
419
420 QualType T = E->getType();
421 if (const RecordType *RecordT = T->getAs<RecordType>()) {
422 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
423 // C++ [expr.typeid]p3:
424 // [...] If the type of the expression is a class type, the class
425 // shall be completely-defined.
426 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
427 return ExprError();
428
429 // C++ [expr.typeid]p3:
430 // When typeid is applied to an expression other than an glvalue of a
431 // polymorphic class type [...] [the] expression is an unevaluated
432 // operand. [...]
433 if (RecordD->isPolymorphic() && E->isGLValue()) {
434 // The subexpression is potentially evaluated; switch the context
435 // and recheck the subexpression.
436 ExprResult Result = TransformToPotentiallyEvaluated(E);
437 if (Result.isInvalid()) return ExprError();
438 E = Result.get();
439
440 // We require a vtable to query the type at run time.
441 MarkVTableUsed(TypeidLoc, RecordD);
442 WasEvaluated = true;
443 }
444 }
445
446 // C++ [expr.typeid]p4:
447 // [...] If the type of the type-id is a reference to a possibly
448 // cv-qualified type, the result of the typeid expression refers to a
449 // std::type_info object representing the cv-unqualified referenced
450 // type.
451 Qualifiers Quals;
452 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
453 if (!Context.hasSameType(T, UnqualT)) {
454 T = UnqualT;
455 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
456 }
457 }
458
459 if (E->getType()->isVariablyModifiedType())
12
Called C++ object pointer is null
460 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
461 << E->getType());
462 else if (!inTemplateInstantiation() &&
463 E->HasSideEffects(Context, WasEvaluated)) {
464 // The expression operand for typeid is in an unevaluated expression
465 // context, so side effects could result in unintended consequences.
466 Diag(E->getExprLoc(), WasEvaluated
467 ? diag::warn_side_effects_typeid
468 : diag::warn_side_effects_unevaluated_context);
469 }
470
471 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
472 SourceRange(TypeidLoc, RParenLoc));
473}
474
475/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
476ExprResult
477Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
478 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
479 // Find the std::type_info type.
480 if (!getStdNamespace())
1
Assuming the condition is false
2
Taking false branch
481 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
482
483 if (!CXXTypeInfoDecl) {
3
Assuming the condition is false
4
Taking false branch
484 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
485 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
486 LookupQualifiedName(R, getStdNamespace());
487 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
488 // Microsoft's typeinfo doesn't have type_info in std but in the global
489 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
490 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
491 LookupQualifiedName(R, Context.getTranslationUnitDecl());
492 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
493 }
494 if (!CXXTypeInfoDecl)
495 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
496 }
497
498 if (!getLangOpts().RTTI) {
5
Assuming the condition is false
6
Taking false branch
499 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
500 }
501
502 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
503
504 if (isType) {
7
Assuming 'isType' is 0
8
Taking false branch
505 // The operand is a type; handle it as such.
506 TypeSourceInfo *TInfo = nullptr;
507 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
508 &TInfo);
509 if (T.isNull())
510 return ExprError();
511
512 if (!TInfo)
513 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
514
515 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
516 }
517
518 // The operand is an expression.
519 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
9
Passing value via 3rd parameter 'E'
10
Calling 'Sema::BuildCXXTypeId'
520}
521
522/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
523/// a single GUID.
524static void
525getUuidAttrOfType(Sema &SemaRef, QualType QT,
526 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
527 // Optionally remove one level of pointer, reference or array indirection.
528 const Type *Ty = QT.getTypePtr();
529 if (QT->isPointerType() || QT->isReferenceType())
530 Ty = QT->getPointeeType().getTypePtr();
531 else if (QT->isArrayType())
532 Ty = Ty->getBaseElementTypeUnsafe();
533
534 const auto *TD = Ty->getAsTagDecl();
535 if (!TD)
536 return;
537
538 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
539 UuidAttrs.insert(Uuid);
540 return;
541 }
542
543 // __uuidof can grab UUIDs from template arguments.
544 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
545 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
546 for (const TemplateArgument &TA : TAL.asArray()) {
547 const UuidAttr *UuidForTA = nullptr;
548 if (TA.getKind() == TemplateArgument::Type)
549 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
550 else if (TA.getKind() == TemplateArgument::Declaration)
551 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
552
553 if (UuidForTA)
554 UuidAttrs.insert(UuidForTA);
555 }
556 }
557}
558
559/// \brief Build a Microsoft __uuidof expression with a type operand.
560ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
561 SourceLocation TypeidLoc,
562 TypeSourceInfo *Operand,
563 SourceLocation RParenLoc) {
564 StringRef UuidStr;
565 if (!Operand->getType()->isDependentType()) {
566 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
567 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
568 if (UuidAttrs.empty())
569 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
570 if (UuidAttrs.size() > 1)
571 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
572 UuidStr = UuidAttrs.back()->getGuid();
573 }
574
575 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
576 SourceRange(TypeidLoc, RParenLoc));
577}
578
579/// \brief Build a Microsoft __uuidof expression with an expression operand.
580ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
581 SourceLocation TypeidLoc,
582 Expr *E,
583 SourceLocation RParenLoc) {
584 StringRef UuidStr;
585 if (!E->getType()->isDependentType()) {
586 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
587 UuidStr = "00000000-0000-0000-0000-000000000000";
588 } else {
589 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
590 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
591 if (UuidAttrs.empty())
592 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
593 if (UuidAttrs.size() > 1)
594 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
595 UuidStr = UuidAttrs.back()->getGuid();
596 }
597 }
598
599 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
600 SourceRange(TypeidLoc, RParenLoc));
601}
602
603/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
604ExprResult
605Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
606 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
607 // If MSVCGuidDecl has not been cached, do the lookup.
608 if (!MSVCGuidDecl) {
609 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
610 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
611 LookupQualifiedName(R, Context.getTranslationUnitDecl());
612 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
613 if (!MSVCGuidDecl)
614 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
615 }
616
617 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
618
619 if (isType) {
620 // The operand is a type; handle it as such.
621 TypeSourceInfo *TInfo = nullptr;
622 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
623 &TInfo);
624 if (T.isNull())
625 return ExprError();
626
627 if (!TInfo)
628 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
629
630 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
631 }
632
633 // The operand is an expression.
634 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
635}
636
637/// ActOnCXXBoolLiteral - Parse {true,false} literals.
638ExprResult
639Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
640 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"
) ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 641, __PRETTY_FUNCTION__))
641 "Unknown C++ Boolean value!")(((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"
) ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 641, __PRETTY_FUNCTION__))
;
642 return new (Context)
643 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
644}
645
646/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
647ExprResult
648Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
649 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
650}
651
652/// ActOnCXXThrow - Parse throw expressions.
653ExprResult
654Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
655 bool IsThrownVarInScope = false;
656 if (Ex) {
657 // C++0x [class.copymove]p31:
658 // When certain criteria are met, an implementation is allowed to omit the
659 // copy/move construction of a class object [...]
660 //
661 // - in a throw-expression, when the operand is the name of a
662 // non-volatile automatic object (other than a function or catch-
663 // clause parameter) whose scope does not extend beyond the end of the
664 // innermost enclosing try-block (if there is one), the copy/move
665 // operation from the operand to the exception object (15.1) can be
666 // omitted by constructing the automatic object directly into the
667 // exception object
668 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
669 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
670 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
671 for( ; S; S = S->getParent()) {
672 if (S->isDeclScope(Var)) {
673 IsThrownVarInScope = true;
674 break;
675 }
676
677 if (S->getFlags() &
678 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
679 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
680 Scope::TryScope))
681 break;
682 }
683 }
684 }
685 }
686
687 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
688}
689
690ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
691 bool IsThrownVarInScope) {
692 // Don't report an error if 'throw' is used in system headers.
693 if (!getLangOpts().CXXExceptions &&
694 !getSourceManager().isInSystemHeader(OpLoc))
695 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
696
697 // Exceptions aren't allowed in CUDA device code.
698 if (getLangOpts().CUDA)
699 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
700 << "throw" << CurrentCUDATarget();
701
702 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
703 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
704
705 if (Ex && !Ex->isTypeDependent()) {
706 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
707 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
708 return ExprError();
709
710 // Initialize the exception result. This implicitly weeds out
711 // abstract types or types with inaccessible copy constructors.
712
713 // C++0x [class.copymove]p31:
714 // When certain criteria are met, an implementation is allowed to omit the
715 // copy/move construction of a class object [...]
716 //
717 // - in a throw-expression, when the operand is the name of a
718 // non-volatile automatic object (other than a function or
719 // catch-clause
720 // parameter) whose scope does not extend beyond the end of the
721 // innermost enclosing try-block (if there is one), the copy/move
722 // operation from the operand to the exception object (15.1) can be
723 // omitted by constructing the automatic object directly into the
724 // exception object
725 const VarDecl *NRVOVariable = nullptr;
726 if (IsThrownVarInScope)
727 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
728
729 InitializedEntity Entity = InitializedEntity::InitializeException(
730 OpLoc, ExceptionObjectTy,
731 /*NRVO=*/NRVOVariable != nullptr);
732 ExprResult Res = PerformMoveOrCopyInitialization(
733 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
734 if (Res.isInvalid())
735 return ExprError();
736 Ex = Res.get();
737 }
738
739 return new (Context)
740 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
741}
742
743static void
744collectPublicBases(CXXRecordDecl *RD,
745 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
746 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
747 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
748 bool ParentIsPublic) {
749 for (const CXXBaseSpecifier &BS : RD->bases()) {
750 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
751 bool NewSubobject;
752 // Virtual bases constitute the same subobject. Non-virtual bases are
753 // always distinct subobjects.
754 if (BS.isVirtual())
755 NewSubobject = VBases.insert(BaseDecl).second;
756 else
757 NewSubobject = true;
758
759 if (NewSubobject)
760 ++SubobjectsSeen[BaseDecl];
761
762 // Only add subobjects which have public access throughout the entire chain.
763 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
764 if (PublicPath)
765 PublicSubobjectsSeen.insert(BaseDecl);
766
767 // Recurse on to each base subobject.
768 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
769 PublicPath);
770 }
771}
772
773static void getUnambiguousPublicSubobjects(
774 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
775 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
776 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
777 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
778 SubobjectsSeen[RD] = 1;
779 PublicSubobjectsSeen.insert(RD);
780 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
781 /*ParentIsPublic=*/true);
782
783 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
784 // Skip ambiguous objects.
785 if (SubobjectsSeen[PublicSubobject] > 1)
786 continue;
787
788 Objects.push_back(PublicSubobject);
789 }
790}
791
792/// CheckCXXThrowOperand - Validate the operand of a throw.
793bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
794 QualType ExceptionObjectTy, Expr *E) {
795 // If the type of the exception would be an incomplete type or a pointer
796 // to an incomplete type other than (cv) void the program is ill-formed.
797 QualType Ty = ExceptionObjectTy;
798 bool isPointer = false;
799 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
800 Ty = Ptr->getPointeeType();
801 isPointer = true;
802 }
803 if (!isPointer || !Ty->isVoidType()) {
804 if (RequireCompleteType(ThrowLoc, Ty,
805 isPointer ? diag::err_throw_incomplete_ptr
806 : diag::err_throw_incomplete,
807 E->getSourceRange()))
808 return true;
809
810 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
811 diag::err_throw_abstract_type, E))
812 return true;
813 }
814
815 // If the exception has class type, we need additional handling.
816 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
817 if (!RD)
818 return false;
819
820 // If we are throwing a polymorphic class type or pointer thereof,
821 // exception handling will make use of the vtable.
822 MarkVTableUsed(ThrowLoc, RD);
823
824 // If a pointer is thrown, the referenced object will not be destroyed.
825 if (isPointer)
826 return false;
827
828 // If the class has a destructor, we must be able to call it.
829 if (!RD->hasIrrelevantDestructor()) {
830 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
831 MarkFunctionReferenced(E->getExprLoc(), Destructor);
832 CheckDestructorAccess(E->getExprLoc(), Destructor,
833 PDiag(diag::err_access_dtor_exception) << Ty);
834 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
835 return true;
836 }
837 }
838
839 // The MSVC ABI creates a list of all types which can catch the exception
840 // object. This list also references the appropriate copy constructor to call
841 // if the object is caught by value and has a non-trivial copy constructor.
842 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
843 // We are only interested in the public, unambiguous bases contained within
844 // the exception object. Bases which are ambiguous or otherwise
845 // inaccessible are not catchable types.
846 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
847 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
848
849 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
850 // Attempt to lookup the copy constructor. Various pieces of machinery
851 // will spring into action, like template instantiation, which means this
852 // cannot be a simple walk of the class's decls. Instead, we must perform
853 // lookup and overload resolution.
854 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
855 if (!CD)
856 continue;
857
858 // Mark the constructor referenced as it is used by this throw expression.
859 MarkFunctionReferenced(E->getExprLoc(), CD);
860
861 // Skip this copy constructor if it is trivial, we don't need to record it
862 // in the catchable type data.
863 if (CD->isTrivial())
864 continue;
865
866 // The copy constructor is non-trivial, create a mapping from this class
867 // type to this constructor.
868 // N.B. The selection of copy constructor is not sensitive to this
869 // particular throw-site. Lookup will be performed at the catch-site to
870 // ensure that the copy constructor is, in fact, accessible (via
871 // friendship or any other means).
872 Context.addCopyConstructorForExceptionObject(Subobject, CD);
873
874 // We don't keep the instantiated default argument expressions around so
875 // we must rebuild them here.
876 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
877 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
878 return true;
879 }
880 }
881 }
882
883 return false;
884}
885
886static QualType adjustCVQualifiersForCXXThisWithinLambda(
887 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
888 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
889
890 QualType ClassType = ThisTy->getPointeeType();
891 LambdaScopeInfo *CurLSI = nullptr;
892 DeclContext *CurDC = CurSemaContext;
893
894 // Iterate through the stack of lambdas starting from the innermost lambda to
895 // the outermost lambda, checking if '*this' is ever captured by copy - since
896 // that could change the cv-qualifiers of the '*this' object.
897 // The object referred to by '*this' starts out with the cv-qualifiers of its
898 // member function. We then start with the innermost lambda and iterate
899 // outward checking to see if any lambda performs a by-copy capture of '*this'
900 // - and if so, any nested lambda must respect the 'constness' of that
901 // capturing lamdbda's call operator.
902 //
903
904 // Since the FunctionScopeInfo stack is representative of the lexical
905 // nesting of the lambda expressions during initial parsing (and is the best
906 // place for querying information about captures about lambdas that are
907 // partially processed) and perhaps during instantiation of function templates
908 // that contain lambda expressions that need to be transformed BUT not
909 // necessarily during instantiation of a nested generic lambda's function call
910 // operator (which might even be instantiated at the end of the TU) - at which
911 // time the DeclContext tree is mature enough to query capture information
912 // reliably - we use a two pronged approach to walk through all the lexically
913 // enclosing lambda expressions:
914 //
915 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
916 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
917 // enclosed by the call-operator of the LSI below it on the stack (while
918 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
919 // the stack represents the innermost lambda.
920 //
921 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
922 // represents a lambda's call operator. If it does, we must be instantiating
923 // a generic lambda's call operator (represented by the Current LSI, and
924 // should be the only scenario where an inconsistency between the LSI and the
925 // DeclContext should occur), so climb out the DeclContexts if they
926 // represent lambdas, while querying the corresponding closure types
927 // regarding capture information.
928
929 // 1) Climb down the function scope info stack.
930 for (int I = FunctionScopes.size();
931 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
932 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
933 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
934 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
935 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
936
937 if (!CurLSI->isCXXThisCaptured())
938 continue;
939
940 auto C = CurLSI->getCXXThisCapture();
941
942 if (C.isCopyCapture()) {
943 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
944 if (CurLSI->CallOperator->isConst())
945 ClassType.addConst();
946 return ASTCtx.getPointerType(ClassType);
947 }
948 }
949
950 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
951 // happen during instantiation of its nested generic lambda call operator)
952 if (isLambdaCallOperator(CurDC)) {
953 assert(CurLSI && "While computing 'this' capture-type for a generic "((CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? static_cast
<void> (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 954, __PRETTY_FUNCTION__))
954 "lambda, we must have a corresponding LambdaScopeInfo")((CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? static_cast
<void> (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 954, __PRETTY_FUNCTION__))
;
955 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 959, __PRETTY_FUNCTION__))
956 "While computing 'this' capture-type for a generic lambda, when we "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 959, __PRETTY_FUNCTION__))
957 "run out of enclosing LSI's, yet the enclosing DC is a "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 959, __PRETTY_FUNCTION__))
958 "lambda-call-operator we must be (i.e. Current LSI) in a generic "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 959, __PRETTY_FUNCTION__))
959 "lambda call oeprator")((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 959, __PRETTY_FUNCTION__))
;
960 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))((CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator
)) ? static_cast<void> (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 960, __PRETTY_FUNCTION__))
;
961
962 auto IsThisCaptured =
963 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
964 IsConst = false;
965 IsByCopy = false;
966 for (auto &&C : Closure->captures()) {
967 if (C.capturesThis()) {
968 if (C.getCaptureKind() == LCK_StarThis)
969 IsByCopy = true;
970 if (Closure->getLambdaCallOperator()->isConst())
971 IsConst = true;
972 return true;
973 }
974 }
975 return false;
976 };
977
978 bool IsByCopyCapture = false;
979 bool IsConstCapture = false;
980 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
981 while (Closure &&
982 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
983 if (IsByCopyCapture) {
984 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
985 if (IsConstCapture)
986 ClassType.addConst();
987 return ASTCtx.getPointerType(ClassType);
988 }
989 Closure = isLambdaCallOperator(Closure->getParent())
990 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
991 : nullptr;
992 }
993 }
994 return ASTCtx.getPointerType(ClassType);
995}
996
997QualType Sema::getCurrentThisType() {
998 DeclContext *DC = getFunctionLevelDeclContext();
999 QualType ThisTy = CXXThisTypeOverride;
1000
1001 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1002 if (method && method->isInstance())
1003 ThisTy = method->getThisType(Context);
1004 }
1005
1006 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1007 inTemplateInstantiation()) {
1008
1009 assert(isa<CXXRecordDecl>(DC) &&((isa<CXXRecordDecl>(DC) && "Trying to get 'this' type from static method?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1010, __PRETTY_FUNCTION__))
1010 "Trying to get 'this' type from static method?")((isa<CXXRecordDecl>(DC) && "Trying to get 'this' type from static method?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1010, __PRETTY_FUNCTION__))
;
1011
1012 // This is a lambda call operator that is being instantiated as a default
1013 // initializer. DC must point to the enclosing class type, so we can recover
1014 // the 'this' type from it.
1015
1016 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1017 // There are no cv-qualifiers for 'this' within default initializers,
1018 // per [expr.prim.general]p4.
1019 ThisTy = Context.getPointerType(ClassTy);
1020 }
1021
1022 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1023 // might need to be adjusted if the lambda or any of its enclosing lambda's
1024 // captures '*this' by copy.
1025 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1026 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1027 CurContext, Context);
1028 return ThisTy;
1029}
1030
1031Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1032 Decl *ContextDecl,
1033 unsigned CXXThisTypeQuals,
1034 bool Enabled)
1035 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1036{
1037 if (!Enabled || !ContextDecl)
1038 return;
1039
1040 CXXRecordDecl *Record = nullptr;
1041 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1042 Record = Template->getTemplatedDecl();
1043 else
1044 Record = cast<CXXRecordDecl>(ContextDecl);
1045
1046 // We care only for CVR qualifiers here, so cut everything else.
1047 CXXThisTypeQuals &= Qualifiers::FastMask;
1048 S.CXXThisTypeOverride
1049 = S.Context.getPointerType(
1050 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
1051
1052 this->Enabled = true;
1053}
1054
1055
1056Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1057 if (Enabled) {
1058 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1059 }
1060}
1061
1062static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1063 QualType ThisTy, SourceLocation Loc,
1064 const bool ByCopy) {
1065
1066 QualType AdjustedThisTy = ThisTy;
1067 // The type of the corresponding data member (not a 'this' pointer if 'by
1068 // copy').
1069 QualType CaptureThisFieldTy = ThisTy;
1070 if (ByCopy) {
1071 // If we are capturing the object referred to by '*this' by copy, ignore any
1072 // cv qualifiers inherited from the type of the member function for the type
1073 // of the closure-type's corresponding data member and any use of 'this'.
1074 CaptureThisFieldTy = ThisTy->getPointeeType();
1075 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1076 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1077 }
1078
1079 FieldDecl *Field = FieldDecl::Create(
1080 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1081 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1082 ICIS_NoInit);
1083
1084 Field->setImplicit(true);
1085 Field->setAccess(AS_private);
1086 RD->addDecl(Field);
1087 Expr *This =
1088 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1089 if (ByCopy) {
1090 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1091 UO_Deref,
1092 This).get();
1093 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1094 nullptr, CaptureThisFieldTy, Loc);
1095 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1096 InitializationSequence Init(S, Entity, InitKind, StarThis);
1097 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1098 if (ER.isInvalid()) return nullptr;
1099 return ER.get();
1100 }
1101 return This;
1102}
1103
1104bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1105 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1106 const bool ByCopy) {
1107 // We don't need to capture this in an unevaluated context.
1108 if (isUnevaluatedContext() && !Explicit)
1109 return true;
1110
1111 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(((!ByCopy || Explicit) && "cannot implicitly capture *this by value"
) ? static_cast<void> (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1111, __PRETTY_FUNCTION__))
;
1112
1113 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
1114 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
1115
1116 // Check that we can capture the *enclosing object* (referred to by '*this')
1117 // by the capturing-entity/closure (lambda/block/etc) at
1118 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1119
1120 // Note: The *enclosing object* can only be captured by-value by a
1121 // closure that is a lambda, using the explicit notation:
1122 // [*this] { ... }.
1123 // Every other capture of the *enclosing object* results in its by-reference
1124 // capture.
1125
1126 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1127 // stack), we can capture the *enclosing object* only if:
1128 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1129 // - or, 'L' has an implicit capture.
1130 // AND
1131 // -- there is no enclosing closure
1132 // -- or, there is some enclosing closure 'E' that has already captured the
1133 // *enclosing object*, and every intervening closure (if any) between 'E'
1134 // and 'L' can implicitly capture the *enclosing object*.
1135 // -- or, every enclosing closure can implicitly capture the
1136 // *enclosing object*
1137
1138
1139 unsigned NumCapturingClosures = 0;
1140 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
1141 if (CapturingScopeInfo *CSI =
1142 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1143 if (CSI->CXXThisCaptureIndex != 0) {
1144 // 'this' is already being captured; there isn't anything more to do.
1145 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1146 break;
1147 }
1148 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1149 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1150 // This context can't implicitly capture 'this'; fail out.
1151 if (BuildAndDiagnose)
1152 Diag(Loc, diag::err_this_capture)
1153 << (Explicit && idx == MaxFunctionScopesIndex);
1154 return true;
1155 }
1156 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1157 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1158 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1159 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1160 (Explicit && idx == MaxFunctionScopesIndex)) {
1161 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1162 // iteration through can be an explicit capture, all enclosing closures,
1163 // if any, must perform implicit captures.
1164
1165 // This closure can capture 'this'; continue looking upwards.
1166 NumCapturingClosures++;
1167 continue;
1168 }
1169 // This context can't implicitly capture 'this'; fail out.
1170 if (BuildAndDiagnose)
1171 Diag(Loc, diag::err_this_capture)
1172 << (Explicit && idx == MaxFunctionScopesIndex);
1173 return true;
1174 }
1175 break;
1176 }
1177 if (!BuildAndDiagnose) return false;
1178
1179 // If we got here, then the closure at MaxFunctionScopesIndex on the
1180 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1181 // (including implicit by-reference captures in any enclosing closures).
1182
1183 // In the loop below, respect the ByCopy flag only for the closure requesting
1184 // the capture (i.e. first iteration through the loop below). Ignore it for
1185 // all enclosing closure's up to NumCapturingClosures (since they must be
1186 // implicitly capturing the *enclosing object* by reference (see loop
1187 // above)).
1188 assert((!ByCopy ||(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1191, __PRETTY_FUNCTION__))
1189 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1191, __PRETTY_FUNCTION__))
1190 "Only a lambda can capture the enclosing object (referred to by "(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1191, __PRETTY_FUNCTION__))
1191 "*this) by copy")(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1191, __PRETTY_FUNCTION__))
;
1192 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1193 // contexts.
1194 QualType ThisTy = getCurrentThisType();
1195 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
1196 --idx, --NumCapturingClosures) {
1197 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1198 Expr *ThisExpr = nullptr;
1199
1200 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1201 // For lambda expressions, build a field and an initializing expression,
1202 // and capture the *enclosing object* by copy only if this is the first
1203 // iteration.
1204 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1205 ByCopy && idx == MaxFunctionScopesIndex);
1206
1207 } else if (CapturedRegionScopeInfo *RSI
1208 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1209 ThisExpr =
1210 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1211 false/*ByCopy*/);
1212
1213 bool isNested = NumCapturingClosures > 1;
1214 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1215 }
1216 return false;
1217}
1218
1219ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1220 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1221 /// is a non-lvalue expression whose value is the address of the object for
1222 /// which the function is called.
1223
1224 QualType ThisTy = getCurrentThisType();
1225 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1226
1227 CheckCXXThisCapture(Loc);
1228 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1229}
1230
1231bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1232 // If we're outside the body of a member function, then we'll have a specified
1233 // type for 'this'.
1234 if (CXXThisTypeOverride.isNull())
1235 return false;
1236
1237 // Determine whether we're looking into a class that's currently being
1238 // defined.
1239 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1240 return Class && Class->isBeingDefined();
1241}
1242
1243ExprResult
1244Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1245 SourceLocation LParenLoc,
1246 MultiExprArg exprs,
1247 SourceLocation RParenLoc) {
1248 if (!TypeRep)
1249 return ExprError();
1250
1251 TypeSourceInfo *TInfo;
1252 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1253 if (!TInfo)
1254 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1255
1256 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1257 // Avoid creating a non-type-dependent expression that contains typos.
1258 // Non-type-dependent expressions are liable to be discarded without
1259 // checking for embedded typos.
1260 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1261 !Result.get()->isTypeDependent())
1262 Result = CorrectDelayedTyposInExpr(Result.get());
1263 return Result;
1264}
1265
1266/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1267/// Can be interpreted either as function-style casting ("int(x)")
1268/// or class type construction ("ClassType(x,y,z)")
1269/// or creation of a value-initialized type ("int()").
1270ExprResult
1271Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1272 SourceLocation LParenLoc,
1273 MultiExprArg Exprs,
1274 SourceLocation RParenLoc) {
1275 QualType Ty = TInfo->getType();
1276 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1277
1278 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1279 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1280 RParenLoc);
1281 }
1282
1283 bool ListInitialization = LParenLoc.isInvalid();
1284 assert((!ListInitialization ||(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1286, __PRETTY_FUNCTION__))
1285 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1286, __PRETTY_FUNCTION__))
1286 "List initialization must have initializer list as expression.")(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1286, __PRETTY_FUNCTION__))
;
1287 SourceRange FullRange = SourceRange(TyBeginLoc,
1288 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1289
1290 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1291 InitializationKind Kind =
1292 Exprs.size()
1293 ? ListInitialization
1294 ? InitializationKind::CreateDirectList(TyBeginLoc)
1295 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc,
1296 RParenLoc)
1297 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1298
1299 // C++1z [expr.type.conv]p1:
1300 // If the type is a placeholder for a deduced class type, [...perform class
1301 // template argument deduction...]
1302 DeducedType *Deduced = Ty->getContainedDeducedType();
1303 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1304 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1305 Kind, Exprs);
1306 if (Ty.isNull())
1307 return ExprError();
1308 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1309 }
1310
1311 // C++ [expr.type.conv]p1:
1312 // If the expression list is a parenthesized single expression, the type
1313 // conversion expression is equivalent (in definedness, and if defined in
1314 // meaning) to the corresponding cast expression.
1315 if (Exprs.size() == 1 && !ListInitialization &&
1316 !isa<InitListExpr>(Exprs[0])) {
1317 Expr *Arg = Exprs[0];
1318 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenLoc, Arg, RParenLoc);
1319 }
1320
1321 // For an expression of the form T(), T shall not be an array type.
1322 QualType ElemTy = Ty;
1323 if (Ty->isArrayType()) {
1324 if (!ListInitialization)
1325 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1326 << FullRange);
1327 ElemTy = Context.getBaseElementType(Ty);
1328 }
1329
1330 // There doesn't seem to be an explicit rule against this but sanity demands
1331 // we only construct objects with object types.
1332 if (Ty->isFunctionType())
1333 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1334 << Ty << FullRange);
1335
1336 // C++17 [expr.type.conv]p2:
1337 // If the type is cv void and the initializer is (), the expression is a
1338 // prvalue of the specified type that performs no initialization.
1339 if (!Ty->isVoidType() &&
1340 RequireCompleteType(TyBeginLoc, ElemTy,
1341 diag::err_invalid_incomplete_type_use, FullRange))
1342 return ExprError();
1343
1344 // Otherwise, the expression is a prvalue of the specified type whose
1345 // result object is direct-initialized (11.6) with the initializer.
1346 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1347 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1348
1349 if (Result.isInvalid())
1350 return Result;
1351
1352 Expr *Inner = Result.get();
1353 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1354 Inner = BTE->getSubExpr();
1355 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1356 !isa<CXXScalarValueInitExpr>(Inner)) {
1357 // If we created a CXXTemporaryObjectExpr, that node also represents the
1358 // functional cast. Otherwise, create an explicit cast to represent
1359 // the syntactic form of a functional-style cast that was used here.
1360 //
1361 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1362 // would give a more consistent AST representation than using a
1363 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1364 // is sometimes handled by initialization and sometimes not.
1365 QualType ResultType = Result.get()->getType();
1366 Result = CXXFunctionalCastExpr::Create(
1367 Context, ResultType, Expr::getValueKindForType(Ty), TInfo,
1368 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
1369 }
1370
1371 return Result;
1372}
1373
1374/// \brief Determine whether the given function is a non-placement
1375/// deallocation function.
1376static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1377 if (FD->isInvalidDecl())
1378 return false;
1379
1380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1381 return Method->isUsualDeallocationFunction();
1382
1383 if (FD->getOverloadedOperator() != OO_Delete &&
1384 FD->getOverloadedOperator() != OO_Array_Delete)
1385 return false;
1386
1387 unsigned UsualParams = 1;
1388
1389 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1390 S.Context.hasSameUnqualifiedType(
1391 FD->getParamDecl(UsualParams)->getType(),
1392 S.Context.getSizeType()))
1393 ++UsualParams;
1394
1395 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1396 S.Context.hasSameUnqualifiedType(
1397 FD->getParamDecl(UsualParams)->getType(),
1398 S.Context.getTypeDeclType(S.getStdAlignValT())))
1399 ++UsualParams;
1400
1401 return UsualParams == FD->getNumParams();
1402}
1403
1404namespace {
1405 struct UsualDeallocFnInfo {
1406 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1407 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1408 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1409 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
1410 // A function template declaration is never a usual deallocation function.
1411 if (!FD)
1412 return;
1413 if (FD->getNumParams() == 3)
1414 HasAlignValT = HasSizeT = true;
1415 else if (FD->getNumParams() == 2) {
1416 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1417 HasAlignValT = !HasSizeT;
1418 }
1419
1420 // In CUDA, determine how much we'd like / dislike to call this.
1421 if (S.getLangOpts().CUDA)
1422 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1423 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1424 }
1425
1426 operator bool() const { return FD; }
1427
1428 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1429 bool WantAlign) const {
1430 // C++17 [expr.delete]p10:
1431 // If the type has new-extended alignment, a function with a parameter
1432 // of type std::align_val_t is preferred; otherwise a function without
1433 // such a parameter is preferred
1434 if (HasAlignValT != Other.HasAlignValT)
1435 return HasAlignValT == WantAlign;
1436
1437 if (HasSizeT != Other.HasSizeT)
1438 return HasSizeT == WantSize;
1439
1440 // Use CUDA call preference as a tiebreaker.
1441 return CUDAPref > Other.CUDAPref;
1442 }
1443
1444 DeclAccessPair Found;
1445 FunctionDecl *FD;
1446 bool HasSizeT, HasAlignValT;
1447 Sema::CUDAFunctionPreference CUDAPref;
1448 };
1449}
1450
1451/// Determine whether a type has new-extended alignment. This may be called when
1452/// the type is incomplete (for a delete-expression with an incomplete pointee
1453/// type), in which case it will conservatively return false if the alignment is
1454/// not known.
1455static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1456 return S.getLangOpts().AlignedAllocation &&
1457 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1458 S.getASTContext().getTargetInfo().getNewAlign();
1459}
1460
1461/// Select the correct "usual" deallocation function to use from a selection of
1462/// deallocation functions (either global or class-scope).
1463static UsualDeallocFnInfo resolveDeallocationOverload(
1464 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1465 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1466 UsualDeallocFnInfo Best;
1467
1468 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1469 UsualDeallocFnInfo Info(S, I.getPair());
1470 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1471 Info.CUDAPref == Sema::CFP_Never)
1472 continue;
1473
1474 if (!Best) {
1475 Best = Info;
1476 if (BestFns)
1477 BestFns->push_back(Info);
1478 continue;
1479 }
1480
1481 if (Best.isBetterThan(Info, WantSize, WantAlign))
1482 continue;
1483
1484 // If more than one preferred function is found, all non-preferred
1485 // functions are eliminated from further consideration.
1486 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1487 BestFns->clear();
1488
1489 Best = Info;
1490 if (BestFns)
1491 BestFns->push_back(Info);
1492 }
1493
1494 return Best;
1495}
1496
1497/// Determine whether a given type is a class for which 'delete[]' would call
1498/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1499/// we need to store the array size (even if the type is
1500/// trivially-destructible).
1501static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1502 QualType allocType) {
1503 const RecordType *record =
1504 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1505 if (!record) return false;
1506
1507 // Try to find an operator delete[] in class scope.
1508
1509 DeclarationName deleteName =
1510 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1511 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1512 S.LookupQualifiedName(ops, record->getDecl());
1513
1514 // We're just doing this for information.
1515 ops.suppressDiagnostics();
1516
1517 // Very likely: there's no operator delete[].
1518 if (ops.empty()) return false;
1519
1520 // If it's ambiguous, it should be illegal to call operator delete[]
1521 // on this thing, so it doesn't matter if we allocate extra space or not.
1522 if (ops.isAmbiguous()) return false;
1523
1524 // C++17 [expr.delete]p10:
1525 // If the deallocation functions have class scope, the one without a
1526 // parameter of type std::size_t is selected.
1527 auto Best = resolveDeallocationOverload(
1528 S, ops, /*WantSize*/false,
1529 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1530 return Best && Best.HasSizeT;
1531}
1532
1533/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1534///
1535/// E.g.:
1536/// @code new (memory) int[size][4] @endcode
1537/// or
1538/// @code ::new Foo(23, "hello") @endcode
1539///
1540/// \param StartLoc The first location of the expression.
1541/// \param UseGlobal True if 'new' was prefixed with '::'.
1542/// \param PlacementLParen Opening paren of the placement arguments.
1543/// \param PlacementArgs Placement new arguments.
1544/// \param PlacementRParen Closing paren of the placement arguments.
1545/// \param TypeIdParens If the type is in parens, the source range.
1546/// \param D The type to be allocated, as well as array dimensions.
1547/// \param Initializer The initializing expression or initializer-list, or null
1548/// if there is none.
1549ExprResult
1550Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1551 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1552 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1553 Declarator &D, Expr *Initializer) {
1554 Expr *ArraySize = nullptr;
1555 // If the specified type is an array, unwrap it and save the expression.
1556 if (D.getNumTypeObjects() > 0 &&
1557 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1558 DeclaratorChunk &Chunk = D.getTypeObject(0);
1559 if (D.getDeclSpec().hasAutoTypeSpec())
1560 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1561 << D.getSourceRange());
1562 if (Chunk.Arr.hasStatic)
1563 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1564 << D.getSourceRange());
1565 if (!Chunk.Arr.NumElts)
1566 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1567 << D.getSourceRange());
1568
1569 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1570 D.DropFirstTypeObject();
1571 }
1572
1573 // Every dimension shall be of constant size.
1574 if (ArraySize) {
1575 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1576 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1577 break;
1578
1579 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1580 if (Expr *NumElts = (Expr *)Array.NumElts) {
1581 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1582 if (getLangOpts().CPlusPlus14) {
1583 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1584 // shall be a converted constant expression (5.19) of type std::size_t
1585 // and shall evaluate to a strictly positive value.
1586 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1587 assert(IntWidth && "Builtin type of size 0?")((IntWidth && "Builtin type of size 0?") ? static_cast
<void> (0) : __assert_fail ("IntWidth && \"Builtin type of size 0?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1587, __PRETTY_FUNCTION__))
;
1588 llvm::APSInt Value(IntWidth);
1589 Array.NumElts
1590 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1591 CCEK_NewExpr)
1592 .get();
1593 } else {
1594 Array.NumElts
1595 = VerifyIntegerConstantExpression(NumElts, nullptr,
1596 diag::err_new_array_nonconst)
1597 .get();
1598 }
1599 if (!Array.NumElts)
1600 return ExprError();
1601 }
1602 }
1603 }
1604 }
1605
1606 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1607 QualType AllocType = TInfo->getType();
1608 if (D.isInvalidType())
1609 return ExprError();
1610
1611 SourceRange DirectInitRange;
1612 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1613 DirectInitRange = List->getSourceRange();
1614
1615 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1616 PlacementLParen,
1617 PlacementArgs,
1618 PlacementRParen,
1619 TypeIdParens,
1620 AllocType,
1621 TInfo,
1622 ArraySize,
1623 DirectInitRange,
1624 Initializer);
1625}
1626
1627static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1628 Expr *Init) {
1629 if (!Init)
1630 return true;
1631 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1632 return PLE->getNumExprs() == 0;
1633 if (isa<ImplicitValueInitExpr>(Init))
1634 return true;
1635 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1636 return !CCE->isListInitialization() &&
1637 CCE->getConstructor()->isDefaultConstructor();
1638 else if (Style == CXXNewExpr::ListInit) {
1639 assert(isa<InitListExpr>(Init) &&((isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays."
) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1640, __PRETTY_FUNCTION__))
1640 "Shouldn't create list CXXConstructExprs for arrays.")((isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays."
) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1640, __PRETTY_FUNCTION__))
;
1641 return true;
1642 }
1643 return false;
1644}
1645
1646ExprResult
1647Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1648 SourceLocation PlacementLParen,
1649 MultiExprArg PlacementArgs,
1650 SourceLocation PlacementRParen,
1651 SourceRange TypeIdParens,
1652 QualType AllocType,
1653 TypeSourceInfo *AllocTypeInfo,
1654 Expr *ArraySize,
1655 SourceRange DirectInitRange,
1656 Expr *Initializer) {
1657 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1658 SourceLocation StartLoc = Range.getBegin();
1659
1660 CXXNewExpr::InitializationStyle initStyle;
1661 if (DirectInitRange.isValid()) {
1662 assert(Initializer && "Have parens but no initializer.")((Initializer && "Have parens but no initializer.") ?
static_cast<void> (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1662, __PRETTY_FUNCTION__))
;
1663 initStyle = CXXNewExpr::CallInit;
1664 } else if (Initializer && isa<InitListExpr>(Initializer))
1665 initStyle = CXXNewExpr::ListInit;
1666 else {
1667 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1669, __PRETTY_FUNCTION__))
1668 isa<CXXConstructExpr>(Initializer)) &&(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1669, __PRETTY_FUNCTION__))
1669 "Initializer expression that cannot have been implicitly created.")(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1669, __PRETTY_FUNCTION__))
;
1670 initStyle = CXXNewExpr::NoInit;
1671 }
1672
1673 Expr **Inits = &Initializer;
1674 unsigned NumInits = Initializer ? 1 : 0;
1675 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1676 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")((initStyle == CXXNewExpr::CallInit && "paren init for non-call init"
) ? static_cast<void> (0) : __assert_fail ("initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1676, __PRETTY_FUNCTION__))
;
1677 Inits = List->getExprs();
1678 NumInits = List->getNumExprs();
1679 }
1680
1681 // C++11 [expr.new]p15:
1682 // A new-expression that creates an object of type T initializes that
1683 // object as follows:
1684 InitializationKind Kind
1685 // - If the new-initializer is omitted, the object is default-
1686 // initialized (8.5); if no initialization is performed,
1687 // the object has indeterminate value
1688 = initStyle == CXXNewExpr::NoInit
1689 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1690 // - Otherwise, the new-initializer is interpreted according to the
1691 // initialization rules of 8.5 for direct-initialization.
1692 : initStyle == CXXNewExpr::ListInit
1693 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1694 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1695 DirectInitRange.getBegin(),
1696 DirectInitRange.getEnd());
1697
1698 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1699 auto *Deduced = AllocType->getContainedDeducedType();
1700 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1701 if (ArraySize)
1702 return ExprError(Diag(ArraySize->getExprLoc(),
1703 diag::err_deduced_class_template_compound_type)
1704 << /*array*/ 2 << ArraySize->getSourceRange());
1705
1706 InitializedEntity Entity
1707 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1708 AllocType = DeduceTemplateSpecializationFromInitializer(
1709 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1710 if (AllocType.isNull())
1711 return ExprError();
1712 } else if (Deduced) {
1713 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1714 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1715 << AllocType << TypeRange);
1716 if (initStyle == CXXNewExpr::ListInit ||
1717 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
1718 return ExprError(Diag(Inits[0]->getLocStart(),
1719 diag::err_auto_new_list_init)
1720 << AllocType << TypeRange);
1721 if (NumInits > 1) {
1722 Expr *FirstBad = Inits[1];
1723 return ExprError(Diag(FirstBad->getLocStart(),
1724 diag::err_auto_new_ctor_multiple_expressions)
1725 << AllocType << TypeRange);
1726 }
1727 Expr *Deduce = Inits[0];
1728 QualType DeducedType;
1729 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1730 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1731 << AllocType << Deduce->getType()
1732 << TypeRange << Deduce->getSourceRange());
1733 if (DeducedType.isNull())
1734 return ExprError();
1735 AllocType = DeducedType;
1736 }
1737
1738 // Per C++0x [expr.new]p5, the type being constructed may be a
1739 // typedef of an array type.
1740 if (!ArraySize) {
1741 if (const ConstantArrayType *Array
1742 = Context.getAsConstantArrayType(AllocType)) {
1743 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1744 Context.getSizeType(),
1745 TypeRange.getEnd());
1746 AllocType = Array->getElementType();
1747 }
1748 }
1749
1750 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1751 return ExprError();
1752
1753 if (initStyle == CXXNewExpr::ListInit &&
1754 isStdInitializerList(AllocType, nullptr)) {
1755 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1756 diag::warn_dangling_std_initializer_list)
1757 << /*at end of FE*/0 << Inits[0]->getSourceRange();
1758 }
1759
1760 // In ARC, infer 'retaining' for the allocated
1761 if (getLangOpts().ObjCAutoRefCount &&
1762 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1763 AllocType->isObjCLifetimeType()) {
1764 AllocType = Context.getLifetimeQualifiedType(AllocType,
1765 AllocType->getObjCARCImplicitLifetime());
1766 }
1767
1768 QualType ResultType = Context.getPointerType(AllocType);
1769
1770 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1771 ExprResult result = CheckPlaceholderExpr(ArraySize);
1772 if (result.isInvalid()) return ExprError();
1773 ArraySize = result.get();
1774 }
1775 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1776 // integral or enumeration type with a non-negative value."
1777 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1778 // enumeration type, or a class type for which a single non-explicit
1779 // conversion function to integral or unscoped enumeration type exists.
1780 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1781 // std::size_t.
1782 llvm::Optional<uint64_t> KnownArraySize;
1783 if (ArraySize && !ArraySize->isTypeDependent()) {
1784 ExprResult ConvertedSize;
1785 if (getLangOpts().CPlusPlus14) {
1786 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")((Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"
) ? static_cast<void> (0) : __assert_fail ("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1786, __PRETTY_FUNCTION__))
;
1787
1788 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1789 AA_Converting);
1790
1791 if (!ConvertedSize.isInvalid() &&
1792 ArraySize->getType()->getAs<RecordType>())
1793 // Diagnose the compatibility of this conversion.
1794 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1795 << ArraySize->getType() << 0 << "'size_t'";
1796 } else {
1797 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1798 protected:
1799 Expr *ArraySize;
1800
1801 public:
1802 SizeConvertDiagnoser(Expr *ArraySize)
1803 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1804 ArraySize(ArraySize) {}
1805
1806 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1807 QualType T) override {
1808 return S.Diag(Loc, diag::err_array_size_not_integral)
1809 << S.getLangOpts().CPlusPlus11 << T;
1810 }
1811
1812 SemaDiagnosticBuilder diagnoseIncomplete(
1813 Sema &S, SourceLocation Loc, QualType T) override {
1814 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1815 << T << ArraySize->getSourceRange();
1816 }
1817
1818 SemaDiagnosticBuilder diagnoseExplicitConv(
1819 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1820 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1821 }
1822
1823 SemaDiagnosticBuilder noteExplicitConv(
1824 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1825 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1826 << ConvTy->isEnumeralType() << ConvTy;
1827 }
1828
1829 SemaDiagnosticBuilder diagnoseAmbiguous(
1830 Sema &S, SourceLocation Loc, QualType T) override {
1831 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1832 }
1833
1834 SemaDiagnosticBuilder noteAmbiguous(
1835 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1836 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1837 << ConvTy->isEnumeralType() << ConvTy;
1838 }
1839
1840 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1841 QualType T,
1842 QualType ConvTy) override {
1843 return S.Diag(Loc,
1844 S.getLangOpts().CPlusPlus11
1845 ? diag::warn_cxx98_compat_array_size_conversion
1846 : diag::ext_array_size_conversion)
1847 << T << ConvTy->isEnumeralType() << ConvTy;
1848 }
1849 } SizeDiagnoser(ArraySize);
1850
1851 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1852 SizeDiagnoser);
1853 }
1854 if (ConvertedSize.isInvalid())
1855 return ExprError();
1856
1857 ArraySize = ConvertedSize.get();
1858 QualType SizeType = ArraySize->getType();
1859
1860 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1861 return ExprError();
1862
1863 // C++98 [expr.new]p7:
1864 // The expression in a direct-new-declarator shall have integral type
1865 // with a non-negative value.
1866 //
1867 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1868 // per CWG1464. Otherwise, if it's not a constant, we must have an
1869 // unparenthesized array type.
1870 if (!ArraySize->isValueDependent()) {
1871 llvm::APSInt Value;
1872 // We've already performed any required implicit conversion to integer or
1873 // unscoped enumeration type.
1874 // FIXME: Per CWG1464, we are required to check the value prior to
1875 // converting to size_t. This will never find a negative array size in
1876 // C++14 onwards, because Value is always unsigned here!
1877 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1878 if (Value.isSigned() && Value.isNegative()) {
1879 return ExprError(Diag(ArraySize->getLocStart(),
1880 diag::err_typecheck_negative_array_size)
1881 << ArraySize->getSourceRange());
1882 }
1883
1884 if (!AllocType->isDependentType()) {
1885 unsigned ActiveSizeBits =
1886 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1887 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1888 return ExprError(Diag(ArraySize->getLocStart(),
1889 diag::err_array_too_large)
1890 << Value.toString(10)
1891 << ArraySize->getSourceRange());
1892 }
1893
1894 KnownArraySize = Value.getZExtValue();
1895 } else if (TypeIdParens.isValid()) {
1896 // Can't have dynamic array size when the type-id is in parentheses.
1897 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1898 << ArraySize->getSourceRange()
1899 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1900 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1901
1902 TypeIdParens = SourceRange();
1903 }
1904 }
1905
1906 // Note that we do *not* convert the argument in any way. It can
1907 // be signed, larger than size_t, whatever.
1908 }
1909
1910 FunctionDecl *OperatorNew = nullptr;
1911 FunctionDecl *OperatorDelete = nullptr;
1912 unsigned Alignment =
1913 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1914 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1915 bool PassAlignment = getLangOpts().AlignedAllocation &&
1916 Alignment > NewAlignment;
1917
1918 if (!AllocType->isDependentType() &&
1919 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1920 FindAllocationFunctions(StartLoc,
1921 SourceRange(PlacementLParen, PlacementRParen),
1922 UseGlobal, AllocType, ArraySize, PassAlignment,
1923 PlacementArgs, OperatorNew, OperatorDelete))
1924 return ExprError();
1925
1926 // If this is an array allocation, compute whether the usual array
1927 // deallocation function for the type has a size_t parameter.
1928 bool UsualArrayDeleteWantsSize = false;
1929 if (ArraySize && !AllocType->isDependentType())
1930 UsualArrayDeleteWantsSize =
1931 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1932
1933 SmallVector<Expr *, 8> AllPlaceArgs;
1934 if (OperatorNew) {
1935 const FunctionProtoType *Proto =
1936 OperatorNew->getType()->getAs<FunctionProtoType>();
1937 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1938 : VariadicDoesNotApply;
1939
1940 // We've already converted the placement args, just fill in any default
1941 // arguments. Skip the first parameter because we don't have a corresponding
1942 // argument. Skip the second parameter too if we're passing in the
1943 // alignment; we've already filled it in.
1944 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1945 PassAlignment ? 2 : 1, PlacementArgs,
1946 AllPlaceArgs, CallType))
1947 return ExprError();
1948
1949 if (!AllPlaceArgs.empty())
1950 PlacementArgs = AllPlaceArgs;
1951
1952 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
1953 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
1954
1955 // FIXME: Missing call to CheckFunctionCall or equivalent
1956
1957 // Warn if the type is over-aligned and is being allocated by (unaligned)
1958 // global operator new.
1959 if (PlacementArgs.empty() && !PassAlignment &&
1960 (OperatorNew->isImplicit() ||
1961 (OperatorNew->getLocStart().isValid() &&
1962 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1963 if (Alignment > NewAlignment)
1964 Diag(StartLoc, diag::warn_overaligned_type)
1965 << AllocType
1966 << unsigned(Alignment / Context.getCharWidth())
1967 << unsigned(NewAlignment / Context.getCharWidth());
1968 }
1969 }
1970
1971 // Array 'new' can't have any initializers except empty parentheses.
1972 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1973 // dialect distinction.
1974 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1975 SourceRange InitRange(Inits[0]->getLocStart(),
1976 Inits[NumInits - 1]->getLocEnd());
1977 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1978 return ExprError();
1979 }
1980
1981 // If we can perform the initialization, and we've not already done so,
1982 // do it now.
1983 if (!AllocType->isDependentType() &&
1984 !Expr::hasAnyTypeDependentArguments(
1985 llvm::makeArrayRef(Inits, NumInits))) {
1986 // The type we initialize is the complete type, including the array bound.
1987 QualType InitType;
1988 if (KnownArraySize)
1989 InitType = Context.getConstantArrayType(
1990 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1991 *KnownArraySize),
1992 ArrayType::Normal, 0);
1993 else if (ArraySize)
1994 InitType =
1995 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1996 else
1997 InitType = AllocType;
1998
1999 InitializedEntity Entity
2000 = InitializedEntity::InitializeNew(StartLoc, InitType);
2001 InitializationSequence InitSeq(*this, Entity, Kind,
2002 MultiExprArg(Inits, NumInits));
2003 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2004 MultiExprArg(Inits, NumInits));
2005 if (FullInit.isInvalid())
2006 return ExprError();
2007
2008 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2009 // we don't want the initialized object to be destructed.
2010 // FIXME: We should not create these in the first place.
2011 if (CXXBindTemporaryExpr *Binder =
2012 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2013 FullInit = Binder->getSubExpr();
2014
2015 Initializer = FullInit.get();
2016 }
2017
2018 // Mark the new and delete operators as referenced.
2019 if (OperatorNew) {
2020 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2021 return ExprError();
2022 MarkFunctionReferenced(StartLoc, OperatorNew);
2023 }
2024 if (OperatorDelete) {
2025 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2026 return ExprError();
2027 MarkFunctionReferenced(StartLoc, OperatorDelete);
2028 }
2029
2030 // C++0x [expr.new]p17:
2031 // If the new expression creates an array of objects of class type,
2032 // access and ambiguity control are done for the destructor.
2033 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2034 if (ArraySize && !BaseAllocType->isDependentType()) {
2035 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2036 if (CXXDestructorDecl *dtor = LookupDestructor(
2037 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2038 MarkFunctionReferenced(StartLoc, dtor);
2039 CheckDestructorAccess(StartLoc, dtor,
2040 PDiag(diag::err_access_dtor)
2041 << BaseAllocType);
2042 if (DiagnoseUseOfDecl(dtor, StartLoc))
2043 return ExprError();
2044 }
2045 }
2046 }
2047
2048 return new (Context)
2049 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
2050 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2051 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2052 Range, DirectInitRange);
2053}
2054
2055/// \brief Checks that a type is suitable as the allocated type
2056/// in a new-expression.
2057bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2058 SourceRange R) {
2059 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2060 // abstract class type or array thereof.
2061 if (AllocType->isFunctionType())
2062 return Diag(Loc, diag::err_bad_new_type)
2063 << AllocType << 0 << R;
2064 else if (AllocType->isReferenceType())
2065 return Diag(Loc, diag::err_bad_new_type)
2066 << AllocType << 1 << R;
2067 else if (!AllocType->isDependentType() &&
2068 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2069 return true;
2070 else if (RequireNonAbstractType(Loc, AllocType,
2071 diag::err_allocation_of_abstract_type))
2072 return true;
2073 else if (AllocType->isVariablyModifiedType())
2074 return Diag(Loc, diag::err_variably_modified_new_type)
2075 << AllocType;
2076 else if (AllocType.getAddressSpace())
2077 return Diag(Loc, diag::err_address_space_qualified_new)
2078 << AllocType.getUnqualifiedType()
2079 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2080 else if (getLangOpts().ObjCAutoRefCount) {
2081 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2082 QualType BaseAllocType = Context.getBaseElementType(AT);
2083 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2084 BaseAllocType->isObjCLifetimeType())
2085 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2086 << BaseAllocType;
2087 }
2088 }
2089
2090 return false;
2091}
2092
2093static bool
2094resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2095 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2096 FunctionDecl *&Operator,
2097 OverloadCandidateSet *AlignedCandidates = nullptr,
2098 Expr *AlignArg = nullptr) {
2099 OverloadCandidateSet Candidates(R.getNameLoc(),
2100 OverloadCandidateSet::CSK_Normal);
2101 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2102 Alloc != AllocEnd; ++Alloc) {
2103 // Even member operator new/delete are implicitly treated as
2104 // static, so don't use AddMemberCandidate.
2105 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2106
2107 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2108 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2109 /*ExplicitTemplateArgs=*/nullptr, Args,
2110 Candidates,
2111 /*SuppressUserConversions=*/false);
2112 continue;
2113 }
2114
2115 FunctionDecl *Fn = cast<FunctionDecl>(D);
2116 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2117 /*SuppressUserConversions=*/false);
2118 }
2119
2120 // Do the resolution.
2121 OverloadCandidateSet::iterator Best;
2122 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2123 case OR_Success: {
2124 // Got one!
2125 FunctionDecl *FnDecl = Best->Function;
2126 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2127 Best->FoundDecl) == Sema::AR_inaccessible)
2128 return true;
2129
2130 Operator = FnDecl;
2131 return false;
2132 }
2133
2134 case OR_No_Viable_Function:
2135 // C++17 [expr.new]p13:
2136 // If no matching function is found and the allocated object type has
2137 // new-extended alignment, the alignment argument is removed from the
2138 // argument list, and overload resolution is performed again.
2139 if (PassAlignment) {
2140 PassAlignment = false;
2141 AlignArg = Args[1];
2142 Args.erase(Args.begin() + 1);
2143 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2144 Operator, &Candidates, AlignArg);
2145 }
2146
2147 // MSVC will fall back on trying to find a matching global operator new
2148 // if operator new[] cannot be found. Also, MSVC will leak by not
2149 // generating a call to operator delete or operator delete[], but we
2150 // will not replicate that bug.
2151 // FIXME: Find out how this interacts with the std::align_val_t fallback
2152 // once MSVC implements it.
2153 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2154 S.Context.getLangOpts().MSVCCompat) {
2155 R.clear();
2156 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2157 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2158 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2159 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2160 Operator, nullptr);
2161 }
2162
2163 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2164 << R.getLookupName() << Range;
2165
2166 // If we have aligned candidates, only note the align_val_t candidates
2167 // from AlignedCandidates and the non-align_val_t candidates from
2168 // Candidates.
2169 if (AlignedCandidates) {
2170 auto IsAligned = [](OverloadCandidate &C) {
2171 return C.Function->getNumParams() > 1 &&
2172 C.Function->getParamDecl(1)->getType()->isAlignValT();
2173 };
2174 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2175
2176 // This was an overaligned allocation, so list the aligned candidates
2177 // first.
2178 Args.insert(Args.begin() + 1, AlignArg);
2179 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2180 R.getNameLoc(), IsAligned);
2181 Args.erase(Args.begin() + 1);
2182 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2183 IsUnaligned);
2184 } else {
2185 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2186 }
2187 return true;
2188
2189 case OR_Ambiguous:
2190 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2191 << R.getLookupName() << Range;
2192 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2193 return true;
2194
2195 case OR_Deleted: {
2196 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2197 << Best->Function->isDeleted()
2198 << R.getLookupName()
2199 << S.getDeletedOrUnavailableSuffix(Best->Function)
2200 << Range;
2201 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2202 return true;
2203 }
2204 }
2205 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2205)
;
2206}
2207
2208
2209/// FindAllocationFunctions - Finds the overloads of operator new and delete
2210/// that are appropriate for the allocation.
2211bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2212 bool UseGlobal, QualType AllocType,
2213 bool IsArray, bool &PassAlignment,
2214 MultiExprArg PlaceArgs,
2215 FunctionDecl *&OperatorNew,
2216 FunctionDecl *&OperatorDelete) {
2217 // --- Choosing an allocation function ---
2218 // C++ 5.3.4p8 - 14 & 18
2219 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2220 // in the scope of the allocated class.
2221 // 2) If an array size is given, look for operator new[], else look for
2222 // operator new.
2223 // 3) The first argument is always size_t. Append the arguments from the
2224 // placement form.
2225
2226 SmallVector<Expr*, 8> AllocArgs;
2227 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2228
2229 // We don't care about the actual value of these arguments.
2230 // FIXME: Should the Sema create the expression and embed it in the syntax
2231 // tree? Or should the consumer just recalculate the value?
2232 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2233 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2234 Context.getTargetInfo().getPointerWidth(0)),
2235 Context.getSizeType(),
2236 SourceLocation());
2237 AllocArgs.push_back(&Size);
2238
2239 QualType AlignValT = Context.VoidTy;
2240 if (PassAlignment) {
2241 DeclareGlobalNewDelete();
2242 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2243 }
2244 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2245 if (PassAlignment)
2246 AllocArgs.push_back(&Align);
2247
2248 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2249
2250 // C++ [expr.new]p8:
2251 // If the allocated type is a non-array type, the allocation
2252 // function's name is operator new and the deallocation function's
2253 // name is operator delete. If the allocated type is an array
2254 // type, the allocation function's name is operator new[] and the
2255 // deallocation function's name is operator delete[].
2256 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2257 IsArray ? OO_Array_New : OO_New);
2258
2259 QualType AllocElemType = Context.getBaseElementType(AllocType);
2260
2261 // Find the allocation function.
2262 {
2263 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2264
2265 // C++1z [expr.new]p9:
2266 // If the new-expression begins with a unary :: operator, the allocation
2267 // function's name is looked up in the global scope. Otherwise, if the
2268 // allocated type is a class type T or array thereof, the allocation
2269 // function's name is looked up in the scope of T.
2270 if (AllocElemType->isRecordType() && !UseGlobal)
2271 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2272
2273 // We can see ambiguity here if the allocation function is found in
2274 // multiple base classes.
2275 if (R.isAmbiguous())
2276 return true;
2277
2278 // If this lookup fails to find the name, or if the allocated type is not
2279 // a class type, the allocation function's name is looked up in the
2280 // global scope.
2281 if (R.empty())
2282 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2283
2284 assert(!R.empty() && "implicitly declared allocation functions not found")((!R.empty() && "implicitly declared allocation functions not found"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2284, __PRETTY_FUNCTION__))
;
2285 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")((!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2285, __PRETTY_FUNCTION__))
;
2286
2287 // We do our own custom access checks below.
2288 R.suppressDiagnostics();
2289
2290 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2291 OperatorNew))
2292 return true;
2293 }
2294
2295 // We don't need an operator delete if we're running under -fno-exceptions.
2296 if (!getLangOpts().Exceptions) {
2297 OperatorDelete = nullptr;
2298 return false;
2299 }
2300
2301 // Note, the name of OperatorNew might have been changed from array to
2302 // non-array by resolveAllocationOverload.
2303 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2304 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2305 ? OO_Array_Delete
2306 : OO_Delete);
2307
2308 // C++ [expr.new]p19:
2309 //
2310 // If the new-expression begins with a unary :: operator, the
2311 // deallocation function's name is looked up in the global
2312 // scope. Otherwise, if the allocated type is a class type T or an
2313 // array thereof, the deallocation function's name is looked up in
2314 // the scope of T. If this lookup fails to find the name, or if
2315 // the allocated type is not a class type or array thereof, the
2316 // deallocation function's name is looked up in the global scope.
2317 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2318 if (AllocElemType->isRecordType() && !UseGlobal) {
2319 CXXRecordDecl *RD
2320 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2321 LookupQualifiedName(FoundDelete, RD);
2322 }
2323 if (FoundDelete.isAmbiguous())
2324 return true; // FIXME: clean up expressions?
2325
2326 bool FoundGlobalDelete = FoundDelete.empty();
2327 if (FoundDelete.empty()) {
2328 DeclareGlobalNewDelete();
2329 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2330 }
2331
2332 FoundDelete.suppressDiagnostics();
2333
2334 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2335
2336 // Whether we're looking for a placement operator delete is dictated
2337 // by whether we selected a placement operator new, not by whether
2338 // we had explicit placement arguments. This matters for things like
2339 // struct A { void *operator new(size_t, int = 0); ... };
2340 // A *a = new A()
2341 //
2342 // We don't have any definition for what a "placement allocation function"
2343 // is, but we assume it's any allocation function whose
2344 // parameter-declaration-clause is anything other than (size_t).
2345 //
2346 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2347 // This affects whether an exception from the constructor of an overaligned
2348 // type uses the sized or non-sized form of aligned operator delete.
2349 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2350 OperatorNew->isVariadic();
2351
2352 if (isPlacementNew) {
2353 // C++ [expr.new]p20:
2354 // A declaration of a placement deallocation function matches the
2355 // declaration of a placement allocation function if it has the
2356 // same number of parameters and, after parameter transformations
2357 // (8.3.5), all parameter types except the first are
2358 // identical. [...]
2359 //
2360 // To perform this comparison, we compute the function type that
2361 // the deallocation function should have, and use that type both
2362 // for template argument deduction and for comparison purposes.
2363 QualType ExpectedFunctionType;
2364 {
2365 const FunctionProtoType *Proto
2366 = OperatorNew->getType()->getAs<FunctionProtoType>();
2367
2368 SmallVector<QualType, 4> ArgTypes;
2369 ArgTypes.push_back(Context.VoidPtrTy);
2370 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2371 ArgTypes.push_back(Proto->getParamType(I));
2372
2373 FunctionProtoType::ExtProtoInfo EPI;
2374 // FIXME: This is not part of the standard's rule.
2375 EPI.Variadic = Proto->isVariadic();
2376
2377 ExpectedFunctionType
2378 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2379 }
2380
2381 for (LookupResult::iterator D = FoundDelete.begin(),
2382 DEnd = FoundDelete.end();
2383 D != DEnd; ++D) {
2384 FunctionDecl *Fn = nullptr;
2385 if (FunctionTemplateDecl *FnTmpl =
2386 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2387 // Perform template argument deduction to try to match the
2388 // expected function type.
2389 TemplateDeductionInfo Info(StartLoc);
2390 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2391 Info))
2392 continue;
2393 } else
2394 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2395
2396 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2397 ExpectedFunctionType,
2398 /*AdjustExcpetionSpec*/true),
2399 ExpectedFunctionType))
2400 Matches.push_back(std::make_pair(D.getPair(), Fn));
2401 }
2402
2403 if (getLangOpts().CUDA)
2404 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2405 } else {
2406 // C++1y [expr.new]p22:
2407 // For a non-placement allocation function, the normal deallocation
2408 // function lookup is used
2409 //
2410 // Per [expr.delete]p10, this lookup prefers a member operator delete
2411 // without a size_t argument, but prefers a non-member operator delete
2412 // with a size_t where possible (which it always is in this case).
2413 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2414 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2415 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2416 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2417 &BestDeallocFns);
2418 if (Selected)
2419 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2420 else {
2421 // If we failed to select an operator, all remaining functions are viable
2422 // but ambiguous.
2423 for (auto Fn : BestDeallocFns)
2424 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2425 }
2426 }
2427
2428 // C++ [expr.new]p20:
2429 // [...] If the lookup finds a single matching deallocation
2430 // function, that function will be called; otherwise, no
2431 // deallocation function will be called.
2432 if (Matches.size() == 1) {
2433 OperatorDelete = Matches[0].second;
2434
2435 // C++1z [expr.new]p23:
2436 // If the lookup finds a usual deallocation function (3.7.4.2)
2437 // with a parameter of type std::size_t and that function, considered
2438 // as a placement deallocation function, would have been
2439 // selected as a match for the allocation function, the program
2440 // is ill-formed.
2441 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2442 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2443 UsualDeallocFnInfo Info(*this,
2444 DeclAccessPair::make(OperatorDelete, AS_public));
2445 // Core issue, per mail to core reflector, 2016-10-09:
2446 // If this is a member operator delete, and there is a corresponding
2447 // non-sized member operator delete, this isn't /really/ a sized
2448 // deallocation function, it just happens to have a size_t parameter.
2449 bool IsSizedDelete = Info.HasSizeT;
2450 if (IsSizedDelete && !FoundGlobalDelete) {
2451 auto NonSizedDelete =
2452 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2453 /*WantAlign*/Info.HasAlignValT);
2454 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2455 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2456 IsSizedDelete = false;
2457 }
2458
2459 if (IsSizedDelete) {
2460 SourceRange R = PlaceArgs.empty()
2461 ? SourceRange()
2462 : SourceRange(PlaceArgs.front()->getLocStart(),
2463 PlaceArgs.back()->getLocEnd());
2464 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2465 if (!OperatorDelete->isImplicit())
2466 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2467 << DeleteName;
2468 }
2469 }
2470
2471 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2472 Matches[0].first);
2473 } else if (!Matches.empty()) {
2474 // We found multiple suitable operators. Per [expr.new]p20, that means we
2475 // call no 'operator delete' function, but we should at least warn the user.
2476 // FIXME: Suppress this warning if the construction cannot throw.
2477 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2478 << DeleteName << AllocElemType;
2479
2480 for (auto &Match : Matches)
2481 Diag(Match.second->getLocation(),
2482 diag::note_member_declared_here) << DeleteName;
2483 }
2484
2485 return false;
2486}
2487
2488/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2489/// delete. These are:
2490/// @code
2491/// // C++03:
2492/// void* operator new(std::size_t) throw(std::bad_alloc);
2493/// void* operator new[](std::size_t) throw(std::bad_alloc);
2494/// void operator delete(void *) throw();
2495/// void operator delete[](void *) throw();
2496/// // C++11:
2497/// void* operator new(std::size_t);
2498/// void* operator new[](std::size_t);
2499/// void operator delete(void *) noexcept;
2500/// void operator delete[](void *) noexcept;
2501/// // C++1y:
2502/// void* operator new(std::size_t);
2503/// void* operator new[](std::size_t);
2504/// void operator delete(void *) noexcept;
2505/// void operator delete[](void *) noexcept;
2506/// void operator delete(void *, std::size_t) noexcept;
2507/// void operator delete[](void *, std::size_t) noexcept;
2508/// @endcode
2509/// Note that the placement and nothrow forms of new are *not* implicitly
2510/// declared. Their use requires including \<new\>.
2511void Sema::DeclareGlobalNewDelete() {
2512 if (GlobalNewDeleteDeclared)
2513 return;
2514
2515 // C++ [basic.std.dynamic]p2:
2516 // [...] The following allocation and deallocation functions (18.4) are
2517 // implicitly declared in global scope in each translation unit of a
2518 // program
2519 //
2520 // C++03:
2521 // void* operator new(std::size_t) throw(std::bad_alloc);
2522 // void* operator new[](std::size_t) throw(std::bad_alloc);
2523 // void operator delete(void*) throw();
2524 // void operator delete[](void*) throw();
2525 // C++11:
2526 // void* operator new(std::size_t);
2527 // void* operator new[](std::size_t);
2528 // void operator delete(void*) noexcept;
2529 // void operator delete[](void*) noexcept;
2530 // C++1y:
2531 // void* operator new(std::size_t);
2532 // void* operator new[](std::size_t);
2533 // void operator delete(void*) noexcept;
2534 // void operator delete[](void*) noexcept;
2535 // void operator delete(void*, std::size_t) noexcept;
2536 // void operator delete[](void*, std::size_t) noexcept;
2537 //
2538 // These implicit declarations introduce only the function names operator
2539 // new, operator new[], operator delete, operator delete[].
2540 //
2541 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2542 // "std" or "bad_alloc" as necessary to form the exception specification.
2543 // However, we do not make these implicit declarations visible to name
2544 // lookup.
2545 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2546 // The "std::bad_alloc" class has not yet been declared, so build it
2547 // implicitly.
2548 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2549 getOrCreateStdNamespace(),
2550 SourceLocation(), SourceLocation(),
2551 &PP.getIdentifierTable().get("bad_alloc"),
2552 nullptr);
2553 getStdBadAlloc()->setImplicit(true);
2554 }
2555 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2556 // The "std::align_val_t" enum class has not yet been declared, so build it
2557 // implicitly.
2558 auto *AlignValT = EnumDecl::Create(
2559 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2560 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2561 AlignValT->setIntegerType(Context.getSizeType());
2562 AlignValT->setPromotionType(Context.getSizeType());
2563 AlignValT->setImplicit(true);
2564 StdAlignValT = AlignValT;
2565 }
2566
2567 GlobalNewDeleteDeclared = true;
2568
2569 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2570 QualType SizeT = Context.getSizeType();
2571
2572 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2573 QualType Return, QualType Param) {
2574 llvm::SmallVector<QualType, 3> Params;
2575 Params.push_back(Param);
2576
2577 // Create up to four variants of the function (sized/aligned).
2578 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2579 (Kind == OO_Delete || Kind == OO_Array_Delete);
2580 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2581
2582 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2583 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2584 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2585 if (Sized)
2586 Params.push_back(SizeT);
2587
2588 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2589 if (Aligned)
2590 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2591
2592 DeclareGlobalAllocationFunction(
2593 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2594
2595 if (Aligned)
2596 Params.pop_back();
2597 }
2598 }
2599 };
2600
2601 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2602 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2603 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2604 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2605}
2606
2607/// DeclareGlobalAllocationFunction - Declares a single implicit global
2608/// allocation function if it doesn't already exist.
2609void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2610 QualType Return,
2611 ArrayRef<QualType> Params) {
2612 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2613
2614 // Check if this function is already declared.
2615 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2616 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2617 Alloc != AllocEnd; ++Alloc) {
2618 // Only look at non-template functions, as it is the predefined,
2619 // non-templated allocation function we are trying to declare here.
2620 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2621 if (Func->getNumParams() == Params.size()) {
2622 llvm::SmallVector<QualType, 3> FuncParams;
2623 for (auto *P : Func->parameters())
2624 FuncParams.push_back(
2625 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2626 if (llvm::makeArrayRef(FuncParams) == Params) {
2627 // Make the function visible to name lookup, even if we found it in
2628 // an unimported module. It either is an implicitly-declared global
2629 // allocation function, or is suppressing that function.
2630 Func->setHidden(false);
2631 return;
2632 }
2633 }
2634 }
2635 }
2636
2637 FunctionProtoType::ExtProtoInfo EPI;
2638
2639 QualType BadAllocType;
2640 bool HasBadAllocExceptionSpec
2641 = (Name.getCXXOverloadedOperator() == OO_New ||
2642 Name.getCXXOverloadedOperator() == OO_Array_New);
2643 if (HasBadAllocExceptionSpec) {
2644 if (!getLangOpts().CPlusPlus11) {
2645 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2646 assert(StdBadAlloc && "Must have std::bad_alloc declared")((StdBadAlloc && "Must have std::bad_alloc declared")
? static_cast<void> (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2646, __PRETTY_FUNCTION__))
;
2647 EPI.ExceptionSpec.Type = EST_Dynamic;
2648 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2649 }
2650 } else {
2651 EPI.ExceptionSpec =
2652 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2653 }
2654
2655 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2656 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2657 FunctionDecl *Alloc = FunctionDecl::Create(
2658 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2659 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2660 Alloc->setImplicit();
2661
2662 // Implicit sized deallocation functions always have default visibility.
2663 Alloc->addAttr(
2664 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
2665
2666 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2667 for (QualType T : Params) {
2668 ParamDecls.push_back(ParmVarDecl::Create(
2669 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2670 /*TInfo=*/nullptr, SC_None, nullptr));
2671 ParamDecls.back()->setImplicit();
2672 }
2673 Alloc->setParams(ParamDecls);
2674 if (ExtraAttr)
2675 Alloc->addAttr(ExtraAttr);
2676 Context.getTranslationUnitDecl()->addDecl(Alloc);
2677 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2678 };
2679
2680 if (!LangOpts.CUDA)
2681 CreateAllocationFunctionDecl(nullptr);
2682 else {
2683 // Host and device get their own declaration so each can be
2684 // defined or re-declared independently.
2685 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2686 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2687 }
2688}
2689
2690FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2691 bool CanProvideSize,
2692 bool Overaligned,
2693 DeclarationName Name) {
2694 DeclareGlobalNewDelete();
2695
2696 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2697 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2698
2699 // FIXME: It's possible for this to result in ambiguity, through a
2700 // user-declared variadic operator delete or the enable_if attribute. We
2701 // should probably not consider those cases to be usual deallocation
2702 // functions. But for now we just make an arbitrary choice in that case.
2703 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2704 Overaligned);
2705 assert(Result.FD && "operator delete missing from global scope?")((Result.FD && "operator delete missing from global scope?"
) ? static_cast<void> (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2705, __PRETTY_FUNCTION__))
;
2706 return Result.FD;
2707}
2708
2709FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2710 CXXRecordDecl *RD) {
2711 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2712
2713 FunctionDecl *OperatorDelete = nullptr;
2714 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2715 return nullptr;
2716 if (OperatorDelete)
2717 return OperatorDelete;
2718
2719 // If there's no class-specific operator delete, look up the global
2720 // non-array delete.
2721 return FindUsualDeallocationFunction(
2722 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2723 Name);
2724}
2725
2726bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2727 DeclarationName Name,
2728 FunctionDecl *&Operator, bool Diagnose) {
2729 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2730 // Try to find operator delete/operator delete[] in class scope.
2731 LookupQualifiedName(Found, RD);
2732
2733 if (Found.isAmbiguous())
2734 return true;
2735
2736 Found.suppressDiagnostics();
2737
2738 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2739
2740 // C++17 [expr.delete]p10:
2741 // If the deallocation functions have class scope, the one without a
2742 // parameter of type std::size_t is selected.
2743 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2744 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2745 /*WantAlign*/ Overaligned, &Matches);
2746
2747 // If we could find an overload, use it.
2748 if (Matches.size() == 1) {
2749 Operator = cast<CXXMethodDecl>(Matches[0].FD);
2750
2751 // FIXME: DiagnoseUseOfDecl?
2752 if (Operator->isDeleted()) {
2753 if (Diagnose) {
2754 Diag(StartLoc, diag::err_deleted_function_use);
2755 NoteDeletedFunction(Operator);
2756 }
2757 return true;
2758 }
2759
2760 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2761 Matches[0].Found, Diagnose) == AR_inaccessible)
2762 return true;
2763
2764 return false;
2765 }
2766
2767 // We found multiple suitable operators; complain about the ambiguity.
2768 // FIXME: The standard doesn't say to do this; it appears that the intent
2769 // is that this should never happen.
2770 if (!Matches.empty()) {
2771 if (Diagnose) {
2772 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2773 << Name << RD;
2774 for (auto &Match : Matches)
2775 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2776 }
2777 return true;
2778 }
2779
2780 // We did find operator delete/operator delete[] declarations, but
2781 // none of them were suitable.
2782 if (!Found.empty()) {
2783 if (Diagnose) {
2784 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2785 << Name << RD;
2786
2787 for (NamedDecl *D : Found)
2788 Diag(D->getUnderlyingDecl()->getLocation(),
2789 diag::note_member_declared_here) << Name;
2790 }
2791 return true;
2792 }
2793
2794 Operator = nullptr;
2795 return false;
2796}
2797
2798namespace {
2799/// \brief Checks whether delete-expression, and new-expression used for
2800/// initializing deletee have the same array form.
2801class MismatchingNewDeleteDetector {
2802public:
2803 enum MismatchResult {
2804 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2805 NoMismatch,
2806 /// Indicates that variable is initialized with mismatching form of \a new.
2807 VarInitMismatches,
2808 /// Indicates that member is initialized with mismatching form of \a new.
2809 MemberInitMismatches,
2810 /// Indicates that 1 or more constructors' definitions could not been
2811 /// analyzed, and they will be checked again at the end of translation unit.
2812 AnalyzeLater
2813 };
2814
2815 /// \param EndOfTU True, if this is the final analysis at the end of
2816 /// translation unit. False, if this is the initial analysis at the point
2817 /// delete-expression was encountered.
2818 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2819 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2820 HasUndefinedConstructors(false) {}
2821
2822 /// \brief Checks whether pointee of a delete-expression is initialized with
2823 /// matching form of new-expression.
2824 ///
2825 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2826 /// point where delete-expression is encountered, then a warning will be
2827 /// issued immediately. If return value is \c AnalyzeLater at the point where
2828 /// delete-expression is seen, then member will be analyzed at the end of
2829 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2830 /// couldn't be analyzed. If at least one constructor initializes the member
2831 /// with matching type of new, the return value is \c NoMismatch.
2832 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2833 /// \brief Analyzes a class member.
2834 /// \param Field Class member to analyze.
2835 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2836 /// for deleting the \p Field.
2837 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2838 FieldDecl *Field;
2839 /// List of mismatching new-expressions used for initialization of the pointee
2840 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2841 /// Indicates whether delete-expression was in array form.
2842 bool IsArrayForm;
2843
2844private:
2845 const bool EndOfTU;
2846 /// \brief Indicates that there is at least one constructor without body.
2847 bool HasUndefinedConstructors;
2848 /// \brief Returns \c CXXNewExpr from given initialization expression.
2849 /// \param E Expression used for initializing pointee in delete-expression.
2850 /// E can be a single-element \c InitListExpr consisting of new-expression.
2851 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2852 /// \brief Returns whether member is initialized with mismatching form of
2853 /// \c new either by the member initializer or in-class initialization.
2854 ///
2855 /// If bodies of all constructors are not visible at the end of translation
2856 /// unit or at least one constructor initializes member with the matching
2857 /// form of \c new, mismatch cannot be proven, and this function will return
2858 /// \c NoMismatch.
2859 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2860 /// \brief Returns whether variable is initialized with mismatching form of
2861 /// \c new.
2862 ///
2863 /// If variable is initialized with matching form of \c new or variable is not
2864 /// initialized with a \c new expression, this function will return true.
2865 /// If variable is initialized with mismatching form of \c new, returns false.
2866 /// \param D Variable to analyze.
2867 bool hasMatchingVarInit(const DeclRefExpr *D);
2868 /// \brief Checks whether the constructor initializes pointee with mismatching
2869 /// form of \c new.
2870 ///
2871 /// Returns true, if member is initialized with matching form of \c new in
2872 /// member initializer list. Returns false, if member is initialized with the
2873 /// matching form of \c new in this constructor's initializer or given
2874 /// constructor isn't defined at the point where delete-expression is seen, or
2875 /// member isn't initialized by the constructor.
2876 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2877 /// \brief Checks whether member is initialized with matching form of
2878 /// \c new in member initializer list.
2879 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2880 /// Checks whether member is initialized with mismatching form of \c new by
2881 /// in-class initializer.
2882 MismatchResult analyzeInClassInitializer();
2883};
2884}
2885
2886MismatchingNewDeleteDetector::MismatchResult
2887MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2888 NewExprs.clear();
2889 assert(DE && "Expected delete-expression")((DE && "Expected delete-expression") ? static_cast<
void> (0) : __assert_fail ("DE && \"Expected delete-expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2889, __PRETTY_FUNCTION__))
;
2890 IsArrayForm = DE->isArrayForm();
2891 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2892 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2893 return analyzeMemberExpr(ME);
2894 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2895 if (!hasMatchingVarInit(D))
2896 return VarInitMismatches;
2897 }
2898 return NoMismatch;
2899}
2900
2901const CXXNewExpr *
2902MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2903 assert(E != nullptr && "Expected a valid initializer expression")((E != nullptr && "Expected a valid initializer expression"
) ? static_cast<void> (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2903, __PRETTY_FUNCTION__))
;
2904 E = E->IgnoreParenImpCasts();
2905 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2906 if (ILE->getNumInits() == 1)
2907 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2908 }
2909
2910 return dyn_cast_or_null<const CXXNewExpr>(E);
2911}
2912
2913bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2914 const CXXCtorInitializer *CI) {
2915 const CXXNewExpr *NE = nullptr;
2916 if (Field == CI->getMember() &&
2917 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2918 if (NE->isArray() == IsArrayForm)
2919 return true;
2920 else
2921 NewExprs.push_back(NE);
2922 }
2923 return false;
2924}
2925
2926bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2927 const CXXConstructorDecl *CD) {
2928 if (CD->isImplicit())
2929 return false;
2930 const FunctionDecl *Definition = CD;
2931 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2932 HasUndefinedConstructors = true;
2933 return EndOfTU;
2934 }
2935 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2936 if (hasMatchingNewInCtorInit(CI))
2937 return true;
2938 }
2939 return false;
2940}
2941
2942MismatchingNewDeleteDetector::MismatchResult
2943MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2944 assert(Field != nullptr && "This should be called only for members")((Field != nullptr && "This should be called only for members"
) ? static_cast<void> (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2944, __PRETTY_FUNCTION__))
;
2945 const Expr *InitExpr = Field->getInClassInitializer();
2946 if (!InitExpr)
2947 return EndOfTU ? NoMismatch : AnalyzeLater;
2948 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
2949 if (NE->isArray() != IsArrayForm) {
2950 NewExprs.push_back(NE);
2951 return MemberInitMismatches;
2952 }
2953 }
2954 return NoMismatch;
2955}
2956
2957MismatchingNewDeleteDetector::MismatchResult
2958MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2959 bool DeleteWasArrayForm) {
2960 assert(Field != nullptr && "Analysis requires a valid class member.")((Field != nullptr && "Analysis requires a valid class member."
) ? static_cast<void> (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2960, __PRETTY_FUNCTION__))
;
2961 this->Field = Field;
2962 IsArrayForm = DeleteWasArrayForm;
2963 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2964 for (const auto *CD : RD->ctors()) {
2965 if (hasMatchingNewInCtor(CD))
2966 return NoMismatch;
2967 }
2968 if (HasUndefinedConstructors)
2969 return EndOfTU ? NoMismatch : AnalyzeLater;
2970 if (!NewExprs.empty())
2971 return MemberInitMismatches;
2972 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2973 : NoMismatch;
2974}
2975
2976MismatchingNewDeleteDetector::MismatchResult
2977MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2978 assert(ME != nullptr && "Expected a member expression")((ME != nullptr && "Expected a member expression") ? static_cast
<void> (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2978, __PRETTY_FUNCTION__))
;
2979 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2980 return analyzeField(F, IsArrayForm);
2981 return NoMismatch;
2982}
2983
2984bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2985 const CXXNewExpr *NE = nullptr;
2986 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2987 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2988 NE->isArray() != IsArrayForm) {
2989 NewExprs.push_back(NE);
2990 }
2991 }
2992 return NewExprs.empty();
2993}
2994
2995static void
2996DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2997 const MismatchingNewDeleteDetector &Detector) {
2998 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2999 FixItHint H;
3000 if (!Detector.IsArrayForm)
3001 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3002 else {
3003 SourceLocation RSquare = Lexer::findLocationAfterToken(
3004 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3005 SemaRef.getLangOpts(), true);
3006 if (RSquare.isValid())
3007 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3008 }
3009 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3010 << Detector.IsArrayForm << H;
3011
3012 for (const auto *NE : Detector.NewExprs)
3013 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3014 << Detector.IsArrayForm;
3015}
3016
3017void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3018 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3019 return;
3020 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3021 switch (Detector.analyzeDeleteExpr(DE)) {
3022 case MismatchingNewDeleteDetector::VarInitMismatches:
3023 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3024 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3025 break;
3026 }
3027 case MismatchingNewDeleteDetector::AnalyzeLater: {
3028 DeleteExprs[Detector.Field].push_back(
3029 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3030 break;
3031 }
3032 case MismatchingNewDeleteDetector::NoMismatch:
3033 break;
3034 }
3035}
3036
3037void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3038 bool DeleteWasArrayForm) {
3039 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3040 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3041 case MismatchingNewDeleteDetector::VarInitMismatches:
3042 llvm_unreachable("This analysis should have been done for class members.")::llvm::llvm_unreachable_internal("This analysis should have been done for class members."
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3042)
;
3043 case MismatchingNewDeleteDetector::AnalyzeLater:
3044 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.", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3045)
3045 "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3045)
;
3046 case MismatchingNewDeleteDetector::MemberInitMismatches:
3047 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3048 break;
3049 case MismatchingNewDeleteDetector::NoMismatch:
3050 break;
3051 }
3052}
3053
3054/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3055/// @code ::delete ptr; @endcode
3056/// or
3057/// @code delete [] ptr; @endcode
3058ExprResult
3059Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3060 bool ArrayForm, Expr *ExE) {
3061 // C++ [expr.delete]p1:
3062 // The operand shall have a pointer type, or a class type having a single
3063 // non-explicit conversion function to a pointer type. The result has type
3064 // void.
3065 //
3066 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3067
3068 ExprResult Ex = ExE;
3069 FunctionDecl *OperatorDelete = nullptr;
3070 bool ArrayFormAsWritten = ArrayForm;
3071 bool UsualArrayDeleteWantsSize = false;
3072
3073 if (!Ex.get()->isTypeDependent()) {
3074 // Perform lvalue-to-rvalue cast, if needed.
3075 Ex = DefaultLvalueConversion(Ex.get());
3076 if (Ex.isInvalid())
3077 return ExprError();
3078
3079 QualType Type = Ex.get()->getType();
3080
3081 class DeleteConverter : public ContextualImplicitConverter {
3082 public:
3083 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3084
3085 bool match(QualType ConvType) override {
3086 // FIXME: If we have an operator T* and an operator void*, we must pick
3087 // the operator T*.
3088 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3089 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3090 return true;
3091 return false;
3092 }
3093
3094 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3095 QualType T) override {
3096 return S.Diag(Loc, diag::err_delete_operand) << T;
3097 }
3098
3099 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3100 QualType T) override {
3101 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3102 }
3103
3104 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3105 QualType T,
3106 QualType ConvTy) override {
3107 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3108 }
3109
3110 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3111 QualType ConvTy) override {
3112 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3113 << ConvTy;
3114 }
3115
3116 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3117 QualType T) override {
3118 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3119 }
3120
3121 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3122 QualType ConvTy) override {
3123 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3124 << ConvTy;
3125 }
3126
3127 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3128 QualType T,
3129 QualType ConvTy) override {
3130 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3130)
;
3131 }
3132 } Converter;
3133
3134 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3135 if (Ex.isInvalid())
3136 return ExprError();
3137 Type = Ex.get()->getType();
3138 if (!Converter.match(Type))
3139 // FIXME: PerformContextualImplicitConversion should return ExprError
3140 // itself in this case.
3141 return ExprError();
3142
3143 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3144 QualType PointeeElem = Context.getBaseElementType(Pointee);
3145
3146 if (Pointee.getAddressSpace())
3147 return Diag(Ex.get()->getLocStart(),
3148 diag::err_address_space_qualified_delete)
3149 << Pointee.getUnqualifiedType()
3150 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3151
3152 CXXRecordDecl *PointeeRD = nullptr;
3153 if (Pointee->isVoidType() && !isSFINAEContext()) {
3154 // The C++ standard bans deleting a pointer to a non-object type, which
3155 // effectively bans deletion of "void*". However, most compilers support
3156 // this, so we treat it as a warning unless we're in a SFINAE context.
3157 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3158 << Type << Ex.get()->getSourceRange();
3159 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3160 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3161 << Type << Ex.get()->getSourceRange());
3162 } else if (!Pointee->isDependentType()) {
3163 // FIXME: This can result in errors if the definition was imported from a
3164 // module but is hidden.
3165 if (!RequireCompleteType(StartLoc, Pointee,
3166 diag::warn_delete_incomplete, Ex.get())) {
3167 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3168 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3169 }
3170 }
3171
3172 if (Pointee->isArrayType() && !ArrayForm) {
3173 Diag(StartLoc, diag::warn_delete_array_type)
3174 << Type << Ex.get()->getSourceRange()
3175 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3176 ArrayForm = true;
3177 }
3178
3179 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3180 ArrayForm ? OO_Array_Delete : OO_Delete);
3181
3182 if (PointeeRD) {
3183 if (!UseGlobal &&
3184 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3185 OperatorDelete))
3186 return ExprError();
3187
3188 // If we're allocating an array of records, check whether the
3189 // usual operator delete[] has a size_t parameter.
3190 if (ArrayForm) {
3191 // If the user specifically asked to use the global allocator,
3192 // we'll need to do the lookup into the class.
3193 if (UseGlobal)
3194 UsualArrayDeleteWantsSize =
3195 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3196
3197 // Otherwise, the usual operator delete[] should be the
3198 // function we just found.
3199 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3200 UsualArrayDeleteWantsSize =
3201 UsualDeallocFnInfo(*this,
3202 DeclAccessPair::make(OperatorDelete, AS_public))
3203 .HasSizeT;
3204 }
3205
3206 if (!PointeeRD->hasIrrelevantDestructor())
3207 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3208 MarkFunctionReferenced(StartLoc,
3209 const_cast<CXXDestructorDecl*>(Dtor));
3210 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3211 return ExprError();
3212 }
3213
3214 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3215 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3216 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3217 SourceLocation());
3218 }
3219
3220 if (!OperatorDelete) {
3221 bool IsComplete = isCompleteType(StartLoc, Pointee);
3222 bool CanProvideSize =
3223 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3224 Pointee.isDestructedType());
3225 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3226
3227 // Look for a global declaration.
3228 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3229 Overaligned, DeleteName);
3230 }
3231
3232 MarkFunctionReferenced(StartLoc, OperatorDelete);
3233
3234 // Check access and ambiguity of operator delete and destructor.
3235 if (PointeeRD) {
3236 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3237 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3238 PDiag(diag::err_access_dtor) << PointeeElem);
3239 }
3240 }
3241 }
3242
3243 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3244 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3245 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3246 AnalyzeDeleteExprMismatch(Result);
3247 return Result;
3248}
3249
3250void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3251 bool IsDelete, bool CallCanBeVirtual,
3252 bool WarnOnNonAbstractTypes,
3253 SourceLocation DtorLoc) {
3254 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3255 return;
3256
3257 // C++ [expr.delete]p3:
3258 // In the first alternative (delete object), if the static type of the
3259 // object to be deleted is different from its dynamic type, the static
3260 // type shall be a base class of the dynamic type of the object to be
3261 // deleted and the static type shall have a virtual destructor or the
3262 // behavior is undefined.
3263 //
3264 const CXXRecordDecl *PointeeRD = dtor->getParent();
3265 // Note: a final class cannot be derived from, no issue there
3266 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3267 return;
3268
3269 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3270 if (PointeeRD->isAbstract()) {
3271 // If the class is abstract, we warn by default, because we're
3272 // sure the code has undefined behavior.
3273 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3274 << ClassType;
3275 } else if (WarnOnNonAbstractTypes) {
3276 // Otherwise, if this is not an array delete, it's a bit suspect,
3277 // but not necessarily wrong.
3278 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3279 << ClassType;
3280 }
3281 if (!IsDelete) {
3282 std::string TypeStr;
3283 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3284 Diag(DtorLoc, diag::note_delete_non_virtual)
3285 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3286 }
3287}
3288
3289Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3290 SourceLocation StmtLoc,
3291 ConditionKind CK) {
3292 ExprResult E =
3293 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3294 if (E.isInvalid())
3295 return ConditionError();
3296 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3297 CK == ConditionKind::ConstexprIf);
3298}
3299
3300/// \brief Check the use of the given variable as a C++ condition in an if,
3301/// while, do-while, or switch statement.
3302ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3303 SourceLocation StmtLoc,
3304 ConditionKind CK) {
3305 if (ConditionVar->isInvalidDecl())
3306 return ExprError();
3307
3308 QualType T = ConditionVar->getType();
3309
3310 // C++ [stmt.select]p2:
3311 // The declarator shall not specify a function or an array.
3312 if (T->isFunctionType())
3313 return ExprError(Diag(ConditionVar->getLocation(),
3314 diag::err_invalid_use_of_function_type)
3315 << ConditionVar->getSourceRange());
3316 else if (T->isArrayType())
3317 return ExprError(Diag(ConditionVar->getLocation(),
3318 diag::err_invalid_use_of_array_type)
3319 << ConditionVar->getSourceRange());
3320
3321 ExprResult Condition = DeclRefExpr::Create(
3322 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3323 /*enclosing*/ false, ConditionVar->getLocation(),
3324 ConditionVar->getType().getNonReferenceType(), VK_LValue);
3325
3326 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3327
3328 switch (CK) {
3329 case ConditionKind::Boolean:
3330 return CheckBooleanCondition(StmtLoc, Condition.get());
3331
3332 case ConditionKind::ConstexprIf:
3333 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3334
3335 case ConditionKind::Switch:
3336 return CheckSwitchCondition(StmtLoc, Condition.get());
3337 }
3338
3339 llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3339)
;
3340}
3341
3342/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3343ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3344 // C++ 6.4p4:
3345 // The value of a condition that is an initialized declaration in a statement
3346 // other than a switch statement is the value of the declared variable
3347 // implicitly converted to type bool. If that conversion is ill-formed, the
3348 // program is ill-formed.
3349 // The value of a condition that is an expression is the value of the
3350 // expression, implicitly converted to bool.
3351 //
3352 // FIXME: Return this value to the caller so they don't need to recompute it.
3353 llvm::APSInt Value(/*BitWidth*/1);
3354 return (IsConstexpr && !CondExpr->isValueDependent())
3355 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3356 CCEK_ConstexprIf)
3357 : PerformContextuallyConvertToBool(CondExpr);
3358}
3359
3360/// Helper function to determine whether this is the (deprecated) C++
3361/// conversion from a string literal to a pointer to non-const char or
3362/// non-const wchar_t (for narrow and wide string literals,
3363/// respectively).
3364bool
3365Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3366 // Look inside the implicit cast, if it exists.
3367 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3368 From = Cast->getSubExpr();
3369
3370 // A string literal (2.13.4) that is not a wide string literal can
3371 // be converted to an rvalue of type "pointer to char"; a wide
3372 // string literal can be converted to an rvalue of type "pointer
3373 // to wchar_t" (C++ 4.2p2).
3374 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3375 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3376 if (const BuiltinType *ToPointeeType
3377 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3378 // This conversion is considered only when there is an
3379 // explicit appropriate pointer target type (C++ 4.2p2).
3380 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3381 switch (StrLit->getKind()) {
3382 case StringLiteral::UTF8:
3383 case StringLiteral::UTF16:
3384 case StringLiteral::UTF32:
3385 // We don't allow UTF literals to be implicitly converted
3386 break;
3387 case StringLiteral::Ascii:
3388 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3389 ToPointeeType->getKind() == BuiltinType::Char_S);
3390 case StringLiteral::Wide:
3391 return Context.typesAreCompatible(Context.getWideCharType(),
3392 QualType(ToPointeeType, 0));
3393 }
3394 }
3395 }
3396
3397 return false;
3398}
3399
3400static ExprResult BuildCXXCastArgument(Sema &S,
3401 SourceLocation CastLoc,
3402 QualType Ty,
3403 CastKind Kind,
3404 CXXMethodDecl *Method,
3405 DeclAccessPair FoundDecl,
3406 bool HadMultipleCandidates,
3407 Expr *From) {
3408 switch (Kind) {
3409 default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3409)
;
3410 case CK_ConstructorConversion: {
3411 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3412 SmallVector<Expr*, 8> ConstructorArgs;
3413
3414 if (S.RequireNonAbstractType(CastLoc, Ty,
3415 diag::err_allocation_of_abstract_type))
3416 return ExprError();
3417
3418 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3419 return ExprError();
3420
3421 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3422 InitializedEntity::InitializeTemporary(Ty));
3423 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3424 return ExprError();
3425
3426 ExprResult Result = S.BuildCXXConstructExpr(
3427 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3428 ConstructorArgs, HadMultipleCandidates,
3429 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3430 CXXConstructExpr::CK_Complete, SourceRange());
3431 if (Result.isInvalid())
3432 return ExprError();
3433
3434 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3435 }
3436
3437 case CK_UserDefinedConversion: {
3438 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")((!From->getType()->isPointerType() && "Arg can't have pointer type!"
) ? static_cast<void> (0) : __assert_fail ("!From->getType()->isPointerType() && \"Arg can't have pointer type!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3438, __PRETTY_FUNCTION__))
;
3439
3440 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3441 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3442 return ExprError();
3443
3444 // Create an implicit call expr that calls it.
3445 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3446 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3447 HadMultipleCandidates);
3448 if (Result.isInvalid())
3449 return ExprError();
3450 // Record usage of conversion in an implicit cast.
3451 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3452 CK_UserDefinedConversion, Result.get(),
3453 nullptr, Result.get()->getValueKind());
3454
3455 return S.MaybeBindToTemporary(Result.get());
3456 }
3457 }
3458}
3459
3460/// PerformImplicitConversion - Perform an implicit conversion of the
3461/// expression From to the type ToType using the pre-computed implicit
3462/// conversion sequence ICS. Returns the converted
3463/// expression. Action is the kind of conversion we're performing,
3464/// used in the error message.
3465ExprResult
3466Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3467 const ImplicitConversionSequence &ICS,
3468 AssignmentAction Action,
3469 CheckedConversionKind CCK) {
3470 switch (ICS.getKind()) {
3471 case ImplicitConversionSequence::StandardConversion: {
3472 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3473 Action, CCK);
3474 if (Res.isInvalid())
3475 return ExprError();
3476 From = Res.get();
3477 break;
3478 }
3479
3480 case ImplicitConversionSequence::UserDefinedConversion: {
3481
3482 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3483 CastKind CastKind;
3484 QualType BeforeToType;
3485 assert(FD && "no conversion function for user-defined conversion seq")((FD && "no conversion function for user-defined conversion seq"
) ? static_cast<void> (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3485, __PRETTY_FUNCTION__))
;
3486 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3487 CastKind = CK_UserDefinedConversion;
3488
3489 // If the user-defined conversion is specified by a conversion function,
3490 // the initial standard conversion sequence converts the source type to
3491 // the implicit object parameter of the conversion function.
3492 BeforeToType = Context.getTagDeclType(Conv->getParent());
3493 } else {
3494 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3495 CastKind = CK_ConstructorConversion;
3496 // Do no conversion if dealing with ... for the first conversion.
3497 if (!ICS.UserDefined.EllipsisConversion) {
3498 // If the user-defined conversion is specified by a constructor, the
3499 // initial standard conversion sequence converts the source type to
3500 // the type required by the argument of the constructor
3501 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3502 }
3503 }
3504 // Watch out for ellipsis conversion.
3505 if (!ICS.UserDefined.EllipsisConversion) {
3506 ExprResult Res =
3507 PerformImplicitConversion(From, BeforeToType,
3508 ICS.UserDefined.Before, AA_Converting,
3509 CCK);
3510 if (Res.isInvalid())
3511 return ExprError();
3512 From = Res.get();
3513 }
3514
3515 ExprResult CastArg
3516 = BuildCXXCastArgument(*this,
3517 From->getLocStart(),
3518 ToType.getNonReferenceType(),
3519 CastKind, cast<CXXMethodDecl>(FD),
3520 ICS.UserDefined.FoundConversionFunction,
3521 ICS.UserDefined.HadMultipleCandidates,
3522 From);
3523
3524 if (CastArg.isInvalid())
3525 return ExprError();
3526
3527 From = CastArg.get();
3528
3529 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3530 AA_Converting, CCK);
3531 }
3532
3533 case ImplicitConversionSequence::AmbiguousConversion:
3534 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3535 PDiag(diag::err_typecheck_ambiguous_condition)
3536 << From->getSourceRange());
3537 return ExprError();
3538
3539 case ImplicitConversionSequence::EllipsisConversion:
3540 llvm_unreachable("Cannot perform an ellipsis conversion")::llvm::llvm_unreachable_internal("Cannot perform an ellipsis conversion"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3540)
;
3541
3542 case ImplicitConversionSequence::BadConversion:
3543 bool Diagnosed =
3544 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3545 From->getType(), From, Action);
3546 assert(Diagnosed && "failed to diagnose bad conversion")((Diagnosed && "failed to diagnose bad conversion") ?
static_cast<void> (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3546, __PRETTY_FUNCTION__))
; (void)Diagnosed;
3547 return ExprError();
3548 }
3549
3550 // Everything went well.
3551 return From;
3552}
3553
3554/// PerformImplicitConversion - Perform an implicit conversion of the
3555/// expression From to the type ToType by following the standard
3556/// conversion sequence SCS. Returns the converted
3557/// expression. Flavor is the context in which we're performing this
3558/// conversion, for use in error messages.
3559ExprResult
3560Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3561 const StandardConversionSequence& SCS,
3562 AssignmentAction Action,
3563 CheckedConversionKind CCK) {
3564 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3565
3566 // Overall FIXME: we are recomputing too many types here and doing far too
3567 // much extra work. What this means is that we need to keep track of more
3568 // information that is computed when we try the implicit conversion initially,
3569 // so that we don't need to recompute anything here.
3570 QualType FromType = From->getType();
3571
3572 if (SCS.CopyConstructor) {
3573 // FIXME: When can ToType be a reference type?
3574 assert(!ToType->isReferenceType())((!ToType->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ToType->isReferenceType()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3574, __PRETTY_FUNCTION__))
;
3575 if (SCS.Second == ICK_Derived_To_Base) {
3576 SmallVector<Expr*, 8> ConstructorArgs;
3577 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3578 From, /*FIXME:ConstructLoc*/SourceLocation(),
3579 ConstructorArgs))
3580 return ExprError();
3581 return BuildCXXConstructExpr(
3582 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3583 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3584 ConstructorArgs, /*HadMultipleCandidates*/ false,
3585 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3586 CXXConstructExpr::CK_Complete, SourceRange());
3587 }
3588 return BuildCXXConstructExpr(
3589 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3590 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3591 From, /*HadMultipleCandidates*/ false,
3592 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3593 CXXConstructExpr::CK_Complete, SourceRange());
3594 }
3595
3596 // Resolve overloaded function references.
3597 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3598 DeclAccessPair Found;
3599 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3600 true, Found);
3601 if (!Fn)
3602 return ExprError();
3603
3604 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
3605 return ExprError();
3606
3607 From = FixOverloadedFunctionReference(From, Found, Fn);
3608 FromType = From->getType();
3609 }
3610
3611 // If we're converting to an atomic type, first convert to the corresponding
3612 // non-atomic type.
3613 QualType ToAtomicType;
3614 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3615 ToAtomicType = ToType;
3616 ToType = ToAtomic->getValueType();
3617 }
3618
3619 QualType InitialFromType = FromType;
3620 // Perform the first implicit conversion.
3621 switch (SCS.First) {
3622 case ICK_Identity:
3623 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3624 FromType = FromAtomic->getValueType().getUnqualifiedType();
3625 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3626 From, /*BasePath=*/nullptr, VK_RValue);
3627 }
3628 break;
3629
3630 case ICK_Lvalue_To_Rvalue: {
3631 assert(From->getObjectKind() != OK_ObjCProperty)((From->getObjectKind() != OK_ObjCProperty) ? static_cast<
void> (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3631, __PRETTY_FUNCTION__))
;
3632 ExprResult FromRes = DefaultLvalueConversion(From);
3633 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!")((!FromRes.isInvalid() && "Can't perform deduced conversion?!"
) ? static_cast<void> (0) : __assert_fail ("!FromRes.isInvalid() && \"Can't perform deduced conversion?!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3633, __PRETTY_FUNCTION__))
;
3634 From = FromRes.get();
3635 FromType = From->getType();
3636 break;
3637 }
3638
3639 case ICK_Array_To_Pointer:
3640 FromType = Context.getArrayDecayedType(FromType);
3641 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3642 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3643 break;
3644
3645 case ICK_Function_To_Pointer:
3646 FromType = Context.getPointerType(FromType);
3647 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3648 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3649 break;
3650
3651 default:
3652 llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3652)
;
3653 }
3654
3655 // Perform the second implicit conversion
3656 switch (SCS.Second) {
3657 case ICK_Identity:
3658 // C++ [except.spec]p5:
3659 // [For] assignment to and initialization of pointers to functions,
3660 // pointers to member functions, and references to functions: the
3661 // target entity shall allow at least the exceptions allowed by the
3662 // source value in the assignment or initialization.
3663 switch (Action) {
3664 case AA_Assigning:
3665 case AA_Initializing:
3666 // Note, function argument passing and returning are initialization.
3667 case AA_Passing:
3668 case AA_Returning:
3669 case AA_Sending:
3670 case AA_Passing_CFAudited:
3671 if (CheckExceptionSpecCompatibility(From, ToType))
3672 return ExprError();
3673 break;
3674
3675 case AA_Casting:
3676 case AA_Converting:
3677 // Casts and implicit conversions are not initialization, so are not
3678 // checked for exception specification mismatches.
3679 break;
3680 }
3681 // Nothing else to do.
3682 break;
3683
3684 case ICK_Integral_Promotion:
3685 case ICK_Integral_Conversion:
3686 if (ToType->isBooleanType()) {
3687 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3689, __PRETTY_FUNCTION__))
3688 SCS.Second == ICK_Integral_Promotion &&((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3689, __PRETTY_FUNCTION__))
3689 "only enums with fixed underlying type can promote to bool")((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3689, __PRETTY_FUNCTION__))
;
3690 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
3691 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3692 } else {
3693 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
3694 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3695 }
3696 break;
3697
3698 case ICK_Floating_Promotion:
3699 case ICK_Floating_Conversion:
3700 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
3701 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3702 break;
3703
3704 case ICK_Complex_Promotion:
3705 case ICK_Complex_Conversion: {
3706 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3707 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3708 CastKind CK;
3709 if (FromEl->isRealFloatingType()) {
3710 if (ToEl->isRealFloatingType())
3711 CK = CK_FloatingComplexCast;
3712 else
3713 CK = CK_FloatingComplexToIntegralComplex;
3714 } else if (ToEl->isRealFloatingType()) {
3715 CK = CK_IntegralComplexToFloatingComplex;
3716 } else {
3717 CK = CK_IntegralComplexCast;
3718 }
3719 From = ImpCastExprToType(From, ToType, CK,
3720 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3721 break;
3722 }
3723
3724 case ICK_Floating_Integral:
3725 if (ToType->isRealFloatingType())
3726 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
3727 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3728 else
3729 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
3730 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3731 break;
3732
3733 case ICK_Compatible_Conversion:
3734 From = ImpCastExprToType(From, ToType, CK_NoOp,
3735 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3736 break;
3737
3738 case ICK_Writeback_Conversion:
3739 case ICK_Pointer_Conversion: {
3740 if (SCS.IncompatibleObjC && Action != AA_Casting) {
3741 // Diagnose incompatible Objective-C conversions
3742 if (Action == AA_Initializing || Action == AA_Assigning)
3743 Diag(From->getLocStart(),
3744 diag::ext_typecheck_convert_incompatible_pointer)
3745 << ToType << From->getType() << Action
3746 << From->getSourceRange() << 0;
3747 else
3748 Diag(From->getLocStart(),
3749 diag::ext_typecheck_convert_incompatible_pointer)
3750 << From->getType() << ToType << Action
3751 << From->getSourceRange() << 0;
3752
3753 if (From->getType()->isObjCObjectPointerType() &&
3754 ToType->isObjCObjectPointerType())
3755 EmitRelatedResultTypeNote(From);
3756 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3757 !CheckObjCARCUnavailableWeakConversion(ToType,
3758 From->getType())) {
3759 if (Action == AA_Initializing)
3760 Diag(From->getLocStart(),
3761 diag::err_arc_weak_unavailable_assign);
3762 else
3763 Diag(From->getLocStart(),
3764 diag::err_arc_convesion_of_weak_unavailable)
3765 << (Action == AA_Casting) << From->getType() << ToType
3766 << From->getSourceRange();
3767 }
3768
3769 CastKind Kind = CK_Invalid;
3770 CXXCastPath BasePath;
3771 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
3772 return ExprError();
3773
3774 // Make sure we extend blocks if necessary.
3775 // FIXME: doing this here is really ugly.
3776 if (Kind == CK_BlockPointerToObjCPointerCast) {
3777 ExprResult E = From;
3778 (void) PrepareCastToObjCObjectPointer(E);
3779 From = E.get();
3780 }
3781 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3782 CheckObjCConversion(SourceRange(), ToType, From, CCK);
3783 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3784 .get();
3785 break;
3786 }
3787
3788 case ICK_Pointer_Member: {
3789 CastKind Kind = CK_Invalid;
3790 CXXCastPath BasePath;
3791 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
3792 return ExprError();
3793 if (CheckExceptionSpecCompatibility(From, ToType))
3794 return ExprError();
3795
3796 // We may not have been able to figure out what this member pointer resolved
3797 // to up until this exact point. Attempt to lock-in it's inheritance model.
3798 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3799 (void)isCompleteType(From->getExprLoc(), From->getType());
3800 (void)isCompleteType(From->getExprLoc(), ToType);
3801 }
3802
3803 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3804 .get();
3805 break;
3806 }
3807
3808 case ICK_Boolean_Conversion:
3809 // Perform half-to-boolean conversion via float.
3810 if (From->getType()->isHalfType()) {
3811 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
3812 FromType = Context.FloatTy;
3813 }
3814
3815 From = ImpCastExprToType(From, Context.BoolTy,
3816 ScalarTypeToBooleanCastKind(FromType),
3817 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3818 break;
3819
3820 case ICK_Derived_To_Base: {
3821 CXXCastPath BasePath;
3822 if (CheckDerivedToBaseConversion(From->getType(),
3823 ToType.getNonReferenceType(),
3824 From->getLocStart(),
3825 From->getSourceRange(),
3826 &BasePath,
3827 CStyle))
3828 return ExprError();
3829
3830 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3831 CK_DerivedToBase, From->getValueKind(),
3832 &BasePath, CCK).get();
3833 break;
3834 }
3835
3836 case ICK_Vector_Conversion:
3837 From = ImpCastExprToType(From, ToType, CK_BitCast,
3838 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3839 break;
3840
3841 case ICK_Vector_Splat: {
3842 // Vector splat from any arithmetic type to a vector.
3843 Expr *Elem = prepareVectorSplat(ToType, From).get();
3844 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3845 /*BasePath=*/nullptr, CCK).get();
3846 break;
3847 }
3848
3849 case ICK_Complex_Real:
3850 // Case 1. x -> _Complex y
3851 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3852 QualType ElType = ToComplex->getElementType();
3853 bool isFloatingComplex = ElType->isRealFloatingType();
3854
3855 // x -> y
3856 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3857 // do nothing
3858 } else if (From->getType()->isRealFloatingType()) {
3859 From = ImpCastExprToType(From, ElType,
3860 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
3861 } else {
3862 assert(From->getType()->isIntegerType())((From->getType()->isIntegerType()) ? static_cast<void
> (0) : __assert_fail ("From->getType()->isIntegerType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3862, __PRETTY_FUNCTION__))
;
3863 From = ImpCastExprToType(From, ElType,
3864 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
3865 }
3866 // y -> _Complex y
3867 From = ImpCastExprToType(From, ToType,
3868 isFloatingComplex ? CK_FloatingRealToComplex
3869 : CK_IntegralRealToComplex).get();
3870
3871 // Case 2. _Complex x -> y
3872 } else {
3873 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3874 assert(FromComplex)((FromComplex) ? static_cast<void> (0) : __assert_fail (
"FromComplex", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3874, __PRETTY_FUNCTION__))
;
3875
3876 QualType ElType = FromComplex->getElementType();
3877 bool isFloatingComplex = ElType->isRealFloatingType();
3878
3879 // _Complex x -> x
3880 From = ImpCastExprToType(From, ElType,
3881 isFloatingComplex ? CK_FloatingComplexToReal
3882 : CK_IntegralComplexToReal,
3883 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3884
3885 // x -> y
3886 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3887 // do nothing
3888 } else if (ToType->isRealFloatingType()) {
3889 From = ImpCastExprToType(From, ToType,
3890 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
3891 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3892 } else {
3893 assert(ToType->isIntegerType())((ToType->isIntegerType()) ? static_cast<void> (0) :
__assert_fail ("ToType->isIntegerType()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3893, __PRETTY_FUNCTION__))
;
3894 From = ImpCastExprToType(From, ToType,
3895 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3896 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3897 }
3898 }
3899 break;
3900
3901 case ICK_Block_Pointer_Conversion: {
3902 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
3903 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3904 break;
3905 }
3906
3907 case ICK_TransparentUnionConversion: {
3908 ExprResult FromRes = From;
3909 Sema::AssignConvertType ConvTy =
3910 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3911 if (FromRes.isInvalid())
3912 return ExprError();
3913 From = FromRes.get();
3914 assert ((ConvTy == Sema::Compatible) &&(((ConvTy == Sema::Compatible) && "Improper transparent union conversion"
) ? static_cast<void> (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3915, __PRETTY_FUNCTION__))
3915 "Improper transparent union conversion")(((ConvTy == Sema::Compatible) && "Improper transparent union conversion"
) ? static_cast<void> (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3915, __PRETTY_FUNCTION__))
;
3916 (void)ConvTy;
3917 break;
3918 }
3919
3920 case ICK_Zero_Event_Conversion:
3921 From = ImpCastExprToType(From, ToType,
3922 CK_ZeroToOCLEvent,
3923 From->getValueKind()).get();
3924 break;
3925
3926 case ICK_Zero_Queue_Conversion:
3927 From = ImpCastExprToType(From, ToType,
3928 CK_ZeroToOCLQueue,
3929 From->getValueKind()).get();
3930 break;
3931
3932 case ICK_Lvalue_To_Rvalue:
3933 case ICK_Array_To_Pointer:
3934 case ICK_Function_To_Pointer:
3935 case ICK_Function_Conversion:
3936 case ICK_Qualification:
3937 case ICK_Num_Conversion_Kinds:
3938 case ICK_C_Only_Conversion:
3939 case ICK_Incompatible_Pointer_Conversion:
3940 llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3940)
;
3941 }
3942
3943 switch (SCS.Third) {
3944 case ICK_Identity:
3945 // Nothing to do.
3946 break;
3947
3948 case ICK_Function_Conversion:
3949 // If both sides are functions (or pointers/references to them), there could
3950 // be incompatible exception declarations.
3951 if (CheckExceptionSpecCompatibility(From, ToType))
3952 return ExprError();
3953
3954 From = ImpCastExprToType(From, ToType, CK_NoOp,
3955 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3956 break;
3957
3958 case ICK_Qualification: {
3959 // The qualification keeps the category of the inner expression, unless the
3960 // target type isn't a reference.
3961 ExprValueKind VK = ToType->isReferenceType() ?
3962 From->getValueKind() : VK_RValue;
3963 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3964 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
3965
3966 if (SCS.DeprecatedStringLiteralToCharPtr &&
3967 !getLangOpts().WritableStrings) {
3968 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3969 ? diag::ext_deprecated_string_literal_conversion
3970 : diag::warn_deprecated_string_literal_conversion)
3971 << ToType.getNonReferenceType();
3972 }
3973
3974 break;
3975 }
3976
3977 default:
3978 llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3978)
;
3979 }
3980
3981 // If this conversion sequence involved a scalar -> atomic conversion, perform
3982 // that conversion now.
3983 if (!ToAtomicType.isNull()) {
3984 assert(Context.hasSameType(((Context.hasSameType( ToAtomicType->castAs<AtomicType>
()->getValueType(), From->getType())) ? static_cast<
void> (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3985, __PRETTY_FUNCTION__))
3985 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))((Context.hasSameType( ToAtomicType->castAs<AtomicType>
()->getValueType(), From->getType())) ? static_cast<
void> (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3985, __PRETTY_FUNCTION__))
;
3986 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3987 VK_RValue, nullptr, CCK).get();
3988 }
3989
3990 // If this conversion sequence succeeded and involved implicitly converting a
3991 // _Nullable type to a _Nonnull one, complain.
3992 if (CCK == CCK_ImplicitConversion)
3993 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3994 From->getLocStart());
3995
3996 return From;
3997}
3998
3999/// \brief Check the completeness of a type in a unary type trait.
4000///
4001/// If the particular type trait requires a complete type, tries to complete
4002/// it. If completing the type fails, a diagnostic is emitted and false
4003/// returned. If completing the type succeeds or no completion was required,
4004/// returns true.
4005static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4006 SourceLocation Loc,
4007 QualType ArgTy) {
4008 // C++0x [meta.unary.prop]p3:
4009 // For all of the class templates X declared in this Clause, instantiating
4010 // that template with a template argument that is a class template
4011 // specialization may result in the implicit instantiation of the template
4012 // argument if and only if the semantics of X require that the argument
4013 // must be a complete type.
4014 // We apply this rule to all the type trait expressions used to implement
4015 // these class templates. We also try to follow any GCC documented behavior
4016 // in these expressions to ensure portability of standard libraries.
4017 switch (UTT) {
4018 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4018)
;
4019 // is_complete_type somewhat obviously cannot require a complete type.
4020 case UTT_IsCompleteType:
4021 // Fall-through
4022
4023 // These traits are modeled on the type predicates in C++0x
4024 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4025 // requiring a complete type, as whether or not they return true cannot be
4026 // impacted by the completeness of the type.
4027 case UTT_IsVoid:
4028 case UTT_IsIntegral:
4029 case UTT_IsFloatingPoint:
4030 case UTT_IsArray:
4031 case UTT_IsPointer:
4032 case UTT_IsLvalueReference:
4033 case UTT_IsRvalueReference:
4034 case UTT_IsMemberFunctionPointer:
4035 case UTT_IsMemberObjectPointer:
4036 case UTT_IsEnum:
4037 case UTT_IsUnion:
4038 case UTT_IsClass:
4039 case UTT_IsFunction:
4040 case UTT_IsReference:
4041 case UTT_IsArithmetic:
4042 case UTT_IsFundamental:
4043 case UTT_IsObject:
4044 case UTT_IsScalar:
4045 case UTT_IsCompound:
4046 case UTT_IsMemberPointer:
4047 // Fall-through
4048
4049 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4050 // which requires some of its traits to have the complete type. However,
4051 // the completeness of the type cannot impact these traits' semantics, and
4052 // so they don't require it. This matches the comments on these traits in
4053 // Table 49.
4054 case UTT_IsConst:
4055 case UTT_IsVolatile:
4056 case UTT_IsSigned:
4057 case UTT_IsUnsigned:
4058
4059 // This type trait always returns false, checking the type is moot.
4060 case UTT_IsInterfaceClass:
4061 return true;
4062
4063 // C++14 [meta.unary.prop]:
4064 // If T is a non-union class type, T shall be a complete type.
4065 case UTT_IsEmpty:
4066 case UTT_IsPolymorphic:
4067 case UTT_IsAbstract:
4068 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4069 if (!RD->isUnion())
4070 return !S.RequireCompleteType(
4071 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4072 return true;
4073
4074 // C++14 [meta.unary.prop]:
4075 // If T is a class type, T shall be a complete type.
4076 case UTT_IsFinal:
4077 case UTT_IsSealed:
4078 if (ArgTy->getAsCXXRecordDecl())
4079 return !S.RequireCompleteType(
4080 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4081 return true;
4082
4083 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
4084 // applied to a complete type.
4085 case UTT_IsAggregate:
4086 case UTT_IsTrivial:
4087 case UTT_IsTriviallyCopyable:
4088 case UTT_IsStandardLayout:
4089 case UTT_IsPOD:
4090 case UTT_IsLiteral:
4091
4092 case UTT_IsDestructible:
4093 case UTT_IsNothrowDestructible:
4094 // Fall-through
4095
4096 // These trait expressions are designed to help implement predicates in
4097 // [meta.unary.prop] despite not being named the same. They are specified
4098 // by both GCC and the Embarcadero C++ compiler, and require the complete
4099 // type due to the overarching C++0x type predicates being implemented
4100 // requiring the complete type.
4101 case UTT_HasNothrowAssign:
4102 case UTT_HasNothrowMoveAssign:
4103 case UTT_HasNothrowConstructor:
4104 case UTT_HasNothrowCopy:
4105 case UTT_HasTrivialAssign:
4106 case UTT_HasTrivialMoveAssign:
4107 case UTT_HasTrivialDefaultConstructor:
4108 case UTT_HasTrivialMoveConstructor:
4109 case UTT_HasTrivialCopy:
4110 case UTT_HasTrivialDestructor:
4111 case UTT_HasVirtualDestructor:
4112 // Arrays of unknown bound are expressly allowed.
4113 QualType ElTy = ArgTy;
4114 if (ArgTy->isIncompleteArrayType())
4115 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
4116
4117 // The void type is expressly allowed.
4118 if (ElTy->isVoidType())
4119 return true;
4120
4121 return !S.RequireCompleteType(
4122 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
4123 }
4124}
4125
4126static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4127 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4128 bool (CXXRecordDecl::*HasTrivial)() const,
4129 bool (CXXRecordDecl::*HasNonTrivial)() const,
4130 bool (CXXMethodDecl::*IsDesiredOp)() const)
4131{
4132 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4133 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4134 return true;
4135
4136 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4137 DeclarationNameInfo NameInfo(Name, KeyLoc);
4138 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4139 if (Self.LookupQualifiedName(Res, RD)) {
4140 bool FoundOperator = false;
4141 Res.suppressDiagnostics();
4142 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4143 Op != OpEnd; ++Op) {
4144 if (isa<FunctionTemplateDecl>(*Op))
4145 continue;
4146
4147 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4148 if((Operator->*IsDesiredOp)()) {
4149 FoundOperator = true;
4150 const FunctionProtoType *CPT =
4151 Operator->getType()->getAs<FunctionProtoType>();
4152 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4153 if (!CPT || !CPT->isNothrow(C))
4154 return false;
4155 }
4156 }
4157 return FoundOperator;
4158 }
4159 return false;
4160}
4161
4162static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4163 SourceLocation KeyLoc, QualType T) {
4164 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")((!T->isDependentType() && "Cannot evaluate traits of dependent type"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4164, __PRETTY_FUNCTION__))
;
4165
4166 ASTContext &C = Self.Context;
4167 switch(UTT) {
4168 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4168)
;
4169 // Type trait expressions corresponding to the primary type category
4170 // predicates in C++0x [meta.unary.cat].
4171 case UTT_IsVoid:
4172 return T->isVoidType();
4173 case UTT_IsIntegral:
4174 return T->isIntegralType(C);
4175 case UTT_IsFloatingPoint:
4176 return T->isFloatingType();
4177 case UTT_IsArray:
4178 return T->isArrayType();
4179 case UTT_IsPointer:
4180 return T->isPointerType();
4181 case UTT_IsLvalueReference:
4182 return T->isLValueReferenceType();
4183 case UTT_IsRvalueReference:
4184 return T->isRValueReferenceType();
4185 case UTT_IsMemberFunctionPointer:
4186 return T->isMemberFunctionPointerType();
4187 case UTT_IsMemberObjectPointer:
4188 return T->isMemberDataPointerType();
4189 case UTT_IsEnum:
4190 return T->isEnumeralType();
4191 case UTT_IsUnion:
4192 return T->isUnionType();
4193 case UTT_IsClass:
4194 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4195 case UTT_IsFunction:
4196 return T->isFunctionType();
4197
4198 // Type trait expressions which correspond to the convenient composition
4199 // predicates in C++0x [meta.unary.comp].
4200 case UTT_IsReference:
4201 return T->isReferenceType();
4202 case UTT_IsArithmetic:
4203 return T->isArithmeticType() && !T->isEnumeralType();
4204 case UTT_IsFundamental:
4205 return T->isFundamentalType();
4206 case UTT_IsObject:
4207 return T->isObjectType();
4208 case UTT_IsScalar:
4209 // Note: semantic analysis depends on Objective-C lifetime types to be
4210 // considered scalar types. However, such types do not actually behave
4211 // like scalar types at run time (since they may require retain/release
4212 // operations), so we report them as non-scalar.
4213 if (T->isObjCLifetimeType()) {
4214 switch (T.getObjCLifetime()) {
4215 case Qualifiers::OCL_None:
4216 case Qualifiers::OCL_ExplicitNone:
4217 return true;
4218
4219 case Qualifiers::OCL_Strong:
4220 case Qualifiers::OCL_Weak:
4221 case Qualifiers::OCL_Autoreleasing:
4222 return false;
4223 }
4224 }
4225
4226 return T->isScalarType();
4227 case UTT_IsCompound:
4228 return T->isCompoundType();
4229 case UTT_IsMemberPointer:
4230 return T->isMemberPointerType();
4231
4232 // Type trait expressions which correspond to the type property predicates
4233 // in C++0x [meta.unary.prop].
4234 case UTT_IsConst:
4235 return T.isConstQualified();
4236 case UTT_IsVolatile:
4237 return T.isVolatileQualified();
4238 case UTT_IsTrivial:
4239 return T.isTrivialType(C);
4240 case UTT_IsTriviallyCopyable:
4241 return T.isTriviallyCopyableType(C);
4242 case UTT_IsStandardLayout:
4243 return T->isStandardLayoutType();
4244 case UTT_IsPOD:
4245 return T.isPODType(C);
4246 case UTT_IsLiteral:
4247 return T->isLiteralType(C);
4248 case UTT_IsEmpty:
4249 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4250 return !RD->isUnion() && RD->isEmpty();
4251 return false;
4252 case UTT_IsPolymorphic:
4253 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4254 return !RD->isUnion() && RD->isPolymorphic();
4255 return false;
4256 case UTT_IsAbstract:
4257 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4258 return !RD->isUnion() && RD->isAbstract();
4259 return false;
4260 case UTT_IsAggregate:
4261 // Report vector extensions and complex types as aggregates because they
4262 // support aggregate initialization. GCC mirrors this behavior for vectors
4263 // but not _Complex.
4264 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4265 T->isAnyComplexType();
4266 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4267 // even then only when it is used with the 'interface struct ...' syntax
4268 // Clang doesn't support /CLR which makes this type trait moot.
4269 case UTT_IsInterfaceClass:
4270 return false;
4271 case UTT_IsFinal:
4272 case UTT_IsSealed:
4273 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4274 return RD->hasAttr<FinalAttr>();
4275 return false;
4276 case UTT_IsSigned:
4277 return T->isSignedIntegerType();
4278 case UTT_IsUnsigned:
4279 return T->isUnsignedIntegerType();
4280
4281 // Type trait expressions which query classes regarding their construction,
4282 // destruction, and copying. Rather than being based directly on the
4283 // related type predicates in the standard, they are specified by both
4284 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4285 // specifications.
4286 //
4287 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4288 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4289 //
4290 // Note that these builtins do not behave as documented in g++: if a class
4291 // has both a trivial and a non-trivial special member of a particular kind,
4292 // they return false! For now, we emulate this behavior.
4293 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4294 // does not correctly compute triviality in the presence of multiple special
4295 // members of the same kind. Revisit this once the g++ bug is fixed.
4296 case UTT_HasTrivialDefaultConstructor:
4297 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4298 // If __is_pod (type) is true then the trait is true, else if type is
4299 // a cv class or union type (or array thereof) with a trivial default
4300 // constructor ([class.ctor]) then the trait is true, else it is false.
4301 if (T.isPODType(C))
4302 return true;
4303 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4304 return RD->hasTrivialDefaultConstructor() &&
4305 !RD->hasNonTrivialDefaultConstructor();
4306 return false;
4307 case UTT_HasTrivialMoveConstructor:
4308 // This trait is implemented by MSVC 2012 and needed to parse the
4309 // standard library headers. Specifically this is used as the logic
4310 // behind std::is_trivially_move_constructible (20.9.4.3).
4311 if (T.isPODType(C))
4312 return true;
4313 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4314 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4315 return false;
4316 case UTT_HasTrivialCopy:
4317 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4318 // If __is_pod (type) is true or type is a reference type then
4319 // the trait is true, else if type is a cv class or union type
4320 // with a trivial copy constructor ([class.copy]) then the trait
4321 // is true, else it is false.
4322 if (T.isPODType(C) || T->isReferenceType())
4323 return true;
4324 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4325 return RD->hasTrivialCopyConstructor() &&
4326 !RD->hasNonTrivialCopyConstructor();
4327 return false;
4328 case UTT_HasTrivialMoveAssign:
4329 // This trait is implemented by MSVC 2012 and needed to parse the
4330 // standard library headers. Specifically it is used as the logic
4331 // behind std::is_trivially_move_assignable (20.9.4.3)
4332 if (T.isPODType(C))
4333 return true;
4334 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4335 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4336 return false;
4337 case UTT_HasTrivialAssign:
4338 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4339 // If type is const qualified or is a reference type then the
4340 // trait is false. Otherwise if __is_pod (type) is true then the
4341 // trait is true, else if type is a cv class or union type with
4342 // a trivial copy assignment ([class.copy]) then the trait is
4343 // true, else it is false.
4344 // Note: the const and reference restrictions are interesting,
4345 // given that const and reference members don't prevent a class
4346 // from having a trivial copy assignment operator (but do cause
4347 // errors if the copy assignment operator is actually used, q.v.
4348 // [class.copy]p12).
4349
4350 if (T.isConstQualified())
4351 return false;
4352 if (T.isPODType(C))
4353 return true;
4354 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4355 return RD->hasTrivialCopyAssignment() &&
4356 !RD->hasNonTrivialCopyAssignment();
4357 return false;
4358 case UTT_IsDestructible:
4359 case UTT_IsNothrowDestructible:
4360 // C++14 [meta.unary.prop]:
4361 // For reference types, is_destructible<T>::value is true.
4362 if (T->isReferenceType())
4363 return true;
4364
4365 // Objective-C++ ARC: autorelease types don't require destruction.
4366 if (T->isObjCLifetimeType() &&
4367 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4368 return true;
4369
4370 // C++14 [meta.unary.prop]:
4371 // For incomplete types and function types, is_destructible<T>::value is
4372 // false.
4373 if (T->isIncompleteType() || T->isFunctionType())
4374 return false;
4375
4376 // C++14 [meta.unary.prop]:
4377 // For object types and given U equal to remove_all_extents_t<T>, if the
4378 // expression std::declval<U&>().~U() is well-formed when treated as an
4379 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4380 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4381 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4382 if (!Destructor)
4383 return false;
4384 // C++14 [dcl.fct.def.delete]p2:
4385 // A program that refers to a deleted function implicitly or
4386 // explicitly, other than to declare it, is ill-formed.
4387 if (Destructor->isDeleted())
4388 return false;
4389 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4390 return false;
4391 if (UTT == UTT_IsNothrowDestructible) {
4392 const FunctionProtoType *CPT =
4393 Destructor->getType()->getAs<FunctionProtoType>();
4394 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4395 if (!CPT || !CPT->isNothrow(C))
4396 return false;
4397 }
4398 }
4399 return true;
4400
4401 case UTT_HasTrivialDestructor:
4402 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4403 // If __is_pod (type) is true or type is a reference type
4404 // then the trait is true, else if type is a cv class or union
4405 // type (or array thereof) with a trivial destructor
4406 // ([class.dtor]) then the trait is true, else it is
4407 // false.
4408 if (T.isPODType(C) || T->isReferenceType())
4409 return true;
4410
4411 // Objective-C++ ARC: autorelease types don't require destruction.
4412 if (T->isObjCLifetimeType() &&
4413 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4414 return true;
4415
4416 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4417 return RD->hasTrivialDestructor();
4418 return false;
4419 // TODO: Propagate nothrowness for implicitly declared special members.
4420 case UTT_HasNothrowAssign:
4421 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4422 // If type is const qualified or is a reference type then the
4423 // trait is false. Otherwise if __has_trivial_assign (type)
4424 // is true then the trait is true, else if type is a cv class
4425 // or union type with copy assignment operators that are known
4426 // not to throw an exception then the trait is true, else it is
4427 // false.
4428 if (C.getBaseElementType(T).isConstQualified())
4429 return false;
4430 if (T->isReferenceType())
4431 return false;
4432 if (T.isPODType(C) || T->isObjCLifetimeType())
4433 return true;
4434
4435 if (const RecordType *RT = T->getAs<RecordType>())
4436 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4437 &CXXRecordDecl::hasTrivialCopyAssignment,
4438 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4439 &CXXMethodDecl::isCopyAssignmentOperator);
4440 return false;
4441 case UTT_HasNothrowMoveAssign:
4442 // This trait is implemented by MSVC 2012 and needed to parse the
4443 // standard library headers. Specifically this is used as the logic
4444 // behind std::is_nothrow_move_assignable (20.9.4.3).
4445 if (T.isPODType(C))
4446 return true;
4447
4448 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4449 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4450 &CXXRecordDecl::hasTrivialMoveAssignment,
4451 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4452 &CXXMethodDecl::isMoveAssignmentOperator);
4453 return false;
4454 case UTT_HasNothrowCopy:
4455 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4456 // If __has_trivial_copy (type) is true then the trait is true, else
4457 // if type is a cv class or union type with copy constructors that are
4458 // known not to throw an exception then the trait is true, else it is
4459 // false.
4460 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4461 return true;
4462 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4463 if (RD->hasTrivialCopyConstructor() &&
4464 !RD->hasNonTrivialCopyConstructor())
4465 return true;
4466
4467 bool FoundConstructor = false;
4468 unsigned FoundTQs;
4469 for (const auto *ND : Self.LookupConstructors(RD)) {
4470 // A template constructor is never a copy constructor.
4471 // FIXME: However, it may actually be selected at the actual overload
4472 // resolution point.
4473 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4474 continue;
4475 // UsingDecl itself is not a constructor
4476 if (isa<UsingDecl>(ND))
4477 continue;
4478 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4479 if (Constructor->isCopyConstructor(FoundTQs)) {
4480 FoundConstructor = true;
4481 const FunctionProtoType *CPT
4482 = Constructor->getType()->getAs<FunctionProtoType>();
4483 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4484 if (!CPT)
4485 return false;
4486 // TODO: check whether evaluating default arguments can throw.
4487 // For now, we'll be conservative and assume that they can throw.
4488 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
4489 return false;
4490 }
4491 }
4492
4493 return FoundConstructor;
4494 }
4495 return false;
4496 case UTT_HasNothrowConstructor:
4497 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4498 // If __has_trivial_constructor (type) is true then the trait is
4499 // true, else if type is a cv class or union type (or array
4500 // thereof) with a default constructor that is known not to
4501 // throw an exception then the trait is true, else it is false.
4502 if (T.isPODType(C) || T->isObjCLifetimeType())
4503 return true;
4504 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4505 if (RD->hasTrivialDefaultConstructor() &&
4506 !RD->hasNonTrivialDefaultConstructor())
4507 return true;
4508
4509 bool FoundConstructor = false;
4510 for (const auto *ND : Self.LookupConstructors(RD)) {
4511 // FIXME: In C++0x, a constructor template can be a default constructor.
4512 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4513 continue;
4514 // UsingDecl itself is not a constructor
4515 if (isa<UsingDecl>(ND))
4516 continue;
4517 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4518 if (Constructor->isDefaultConstructor()) {
4519 FoundConstructor = true;
4520 const FunctionProtoType *CPT
4521 = Constructor->getType()->getAs<FunctionProtoType>();
4522 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4523 if (!CPT)
4524 return false;
4525 // FIXME: check whether evaluating default arguments can throw.
4526 // For now, we'll be conservative and assume that they can throw.
4527 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
4528 return false;
4529 }
4530 }
4531 return FoundConstructor;
4532 }
4533 return false;
4534 case UTT_HasVirtualDestructor:
4535 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4536 // If type is a class type with a virtual destructor ([class.dtor])
4537 // then the trait is true, else it is false.
4538 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4539 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4540 return Destructor->isVirtual();
4541 return false;
4542
4543 // These type trait expressions are modeled on the specifications for the
4544 // Embarcadero C++0x type trait functions:
4545 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4546 case UTT_IsCompleteType:
4547 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4548 // Returns True if and only if T is a complete type at the point of the
4549 // function call.
4550 return !T->isIncompleteType();
4551 }
4552}
4553
4554static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4555 QualType RhsT, SourceLocation KeyLoc);
4556
4557static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4558 ArrayRef<TypeSourceInfo *> Args,
4559 SourceLocation RParenLoc) {
4560 if (Kind <= UTT_Last)
4561 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4562
4563 if (Kind <= BTT_Last)
4564 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4565 Args[1]->getType(), RParenLoc);
4566
4567 switch (Kind) {
4568 case clang::TT_IsConstructible:
4569 case clang::TT_IsNothrowConstructible:
4570 case clang::TT_IsTriviallyConstructible: {
4571 // C++11 [meta.unary.prop]:
4572 // is_trivially_constructible is defined as:
4573 //
4574 // is_constructible<T, Args...>::value is true and the variable
4575 // definition for is_constructible, as defined below, is known to call
4576 // no operation that is not trivial.
4577 //
4578 // The predicate condition for a template specialization
4579 // is_constructible<T, Args...> shall be satisfied if and only if the
4580 // following variable definition would be well-formed for some invented
4581 // variable t:
4582 //
4583 // T t(create<Args>()...);
4584 assert(!Args.empty())((!Args.empty()) ? static_cast<void> (0) : __assert_fail
("!Args.empty()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4584, __PRETTY_FUNCTION__))
;
4585
4586 // Precondition: T and all types in the parameter pack Args shall be
4587 // complete types, (possibly cv-qualified) void, or arrays of
4588 // unknown bound.
4589 for (const auto *TSI : Args) {
4590 QualType ArgTy = TSI->getType();
4591 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4592 continue;
4593
4594 if (S.RequireCompleteType(KWLoc, ArgTy,
4595 diag::err_incomplete_type_used_in_type_trait_expr))
4596 return false;
4597 }
4598
4599 // Make sure the first argument is not incomplete nor a function type.
4600 QualType T = Args[0]->getType();
4601 if (T->isIncompleteType() || T->isFunctionType())
4602 return false;
4603
4604 // Make sure the first argument is not an abstract type.
4605 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4606 if (RD && RD->isAbstract())
4607 return false;
4608
4609 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4610 SmallVector<Expr *, 2> ArgExprs;
4611 ArgExprs.reserve(Args.size() - 1);
4612 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4613 QualType ArgTy = Args[I]->getType();
4614 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4615 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4616 OpaqueArgExprs.push_back(
4617 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4618 ArgTy.getNonLValueExprType(S.Context),
4619 Expr::getValueKindForType(ArgTy)));
4620 }
4621 for (Expr &E : OpaqueArgExprs)
4622 ArgExprs.push_back(&E);
4623
4624 // Perform the initialization in an unevaluated context within a SFINAE
4625 // trap at translation unit scope.
4626 EnterExpressionEvaluationContext Unevaluated(
4627 S, Sema::ExpressionEvaluationContext::Unevaluated);
4628 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4629 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4630 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4631 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4632 RParenLoc));
4633 InitializationSequence Init(S, To, InitKind, ArgExprs);
4634 if (Init.Failed())
4635 return false;
4636
4637 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4638 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4639 return false;
4640
4641 if (Kind == clang::TT_IsConstructible)
4642 return true;
4643
4644 if (Kind == clang::TT_IsNothrowConstructible)
4645 return S.canThrow(Result.get()) == CT_Cannot;
4646
4647 if (Kind == clang::TT_IsTriviallyConstructible) {
4648 // Under Objective-C ARC and Weak, if the destination has non-trivial
4649 // Objective-C lifetime, this is a non-trivial construction.
4650 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
4651 return false;
4652
4653 // The initialization succeeded; now make sure there are no non-trivial
4654 // calls.
4655 return !Result.get()->hasNonTrivialCall(S.Context);
4656 }
4657
4658 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4658)
;
4659 return false;
4660 }
4661 default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4661)
;
4662 }
4663
4664 return false;
4665}
4666
4667ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4668 ArrayRef<TypeSourceInfo *> Args,
4669 SourceLocation RParenLoc) {
4670 QualType ResultType = Context.getLogicalOperationType();
4671
4672 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4673 *this, Kind, KWLoc, Args[0]->getType()))
4674 return ExprError();
4675
4676 bool Dependent = false;
4677 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4678 if (Args[I]->getType()->isDependentType()) {
4679 Dependent = true;
4680 break;
4681 }
4682 }
4683
4684 bool Result = false;
4685 if (!Dependent)
4686 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4687
4688 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4689 RParenLoc, Result);
4690}
4691
4692ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4693 ArrayRef<ParsedType> Args,
4694 SourceLocation RParenLoc) {
4695 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
4696 ConvertedArgs.reserve(Args.size());
4697
4698 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4699 TypeSourceInfo *TInfo;
4700 QualType T = GetTypeFromParser(Args[I], &TInfo);
4701 if (!TInfo)
4702 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
4703
4704 ConvertedArgs.push_back(TInfo);
4705 }
4706
4707 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4708}
4709
4710static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4711 QualType RhsT, SourceLocation KeyLoc) {
4712 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&((!LhsT->isDependentType() && !RhsT->isDependentType
() && "Cannot evaluate traits of dependent types") ? static_cast
<void> (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4713, __PRETTY_FUNCTION__))
4713 "Cannot evaluate traits of dependent types")((!LhsT->isDependentType() && !RhsT->isDependentType
() && "Cannot evaluate traits of dependent types") ? static_cast
<void> (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4713, __PRETTY_FUNCTION__))
;
4714
4715 switch(BTT) {
4716 case BTT_IsBaseOf: {
4717 // C++0x [meta.rel]p2
4718 // Base is a base class of Derived without regard to cv-qualifiers or
4719 // Base and Derived are not unions and name the same class type without
4720 // regard to cv-qualifiers.
4721
4722 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4723 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4724 if (!rhsRecord || !lhsRecord) {
4725 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4726 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4727 if (!LHSObjTy || !RHSObjTy)
4728 return false;
4729
4730 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4731 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4732 if (!BaseInterface || !DerivedInterface)
4733 return false;
4734
4735 if (Self.RequireCompleteType(
4736 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4737 return false;
4738
4739 return BaseInterface->isSuperClassOf(DerivedInterface);
4740 }
4741
4742 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)((Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord
== rhsRecord)) ? static_cast<void> (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4743, __PRETTY_FUNCTION__))
4743 == (lhsRecord == rhsRecord))((Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord
== rhsRecord)) ? static_cast<void> (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4743, __PRETTY_FUNCTION__))
;
4744
4745 if (lhsRecord == rhsRecord)
4746 return !lhsRecord->getDecl()->isUnion();
4747
4748 // C++0x [meta.rel]p2:
4749 // If Base and Derived are class types and are different types
4750 // (ignoring possible cv-qualifiers) then Derived shall be a
4751 // complete type.
4752 if (Self.RequireCompleteType(KeyLoc, RhsT,
4753 diag::err_incomplete_type_used_in_type_trait_expr))
4754 return false;
4755
4756 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4757 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4758 }
4759 case BTT_IsSame:
4760 return Self.Context.hasSameType(LhsT, RhsT);
4761 case BTT_TypeCompatible:
4762 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4763 RhsT.getUnqualifiedType());
4764 case BTT_IsConvertible:
4765 case BTT_IsConvertibleTo: {
4766 // C++0x [meta.rel]p4:
4767 // Given the following function prototype:
4768 //
4769 // template <class T>
4770 // typename add_rvalue_reference<T>::type create();
4771 //
4772 // the predicate condition for a template specialization
4773 // is_convertible<From, To> shall be satisfied if and only if
4774 // the return expression in the following code would be
4775 // well-formed, including any implicit conversions to the return
4776 // type of the function:
4777 //
4778 // To test() {
4779 // return create<From>();
4780 // }
4781 //
4782 // Access checking is performed as if in a context unrelated to To and
4783 // From. Only the validity of the immediate context of the expression
4784 // of the return-statement (including conversions to the return type)
4785 // is considered.
4786 //
4787 // We model the initialization as a copy-initialization of a temporary
4788 // of the appropriate type, which for this expression is identical to the
4789 // return statement (since NRVO doesn't apply).
4790
4791 // Functions aren't allowed to return function or array types.
4792 if (RhsT->isFunctionType() || RhsT->isArrayType())
4793 return false;
4794
4795 // A return statement in a void function must have void type.
4796 if (RhsT->isVoidType())
4797 return LhsT->isVoidType();
4798
4799 // A function definition requires a complete, non-abstract return type.
4800 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
4801 return false;
4802
4803 // Compute the result of add_rvalue_reference.
4804 if (LhsT->isObjectType() || LhsT->isFunctionType())
4805 LhsT = Self.Context.getRValueReferenceType(LhsT);
4806
4807 // Build a fake source and destination for initialization.
4808 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
4809 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4810 Expr::getValueKindForType(LhsT));
4811 Expr *FromPtr = &From;
4812 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
4813 SourceLocation()));
4814
4815 // Perform the initialization in an unevaluated context within a SFINAE
4816 // trap at translation unit scope.
4817 EnterExpressionEvaluationContext Unevaluated(
4818 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4819 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4820 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4821 InitializationSequence Init(Self, To, Kind, FromPtr);
4822 if (Init.Failed())
4823 return false;
4824
4825 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
4826 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4827 }
4828
4829 case BTT_IsAssignable:
4830 case BTT_IsNothrowAssignable:
4831 case BTT_IsTriviallyAssignable: {
4832 // C++11 [meta.unary.prop]p3:
4833 // is_trivially_assignable is defined as:
4834 // is_assignable<T, U>::value is true and the assignment, as defined by
4835 // is_assignable, is known to call no operation that is not trivial
4836 //
4837 // is_assignable is defined as:
4838 // The expression declval<T>() = declval<U>() is well-formed when
4839 // treated as an unevaluated operand (Clause 5).
4840 //
4841 // For both, T and U shall be complete types, (possibly cv-qualified)
4842 // void, or arrays of unknown bound.
4843 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
4844 Self.RequireCompleteType(KeyLoc, LhsT,
4845 diag::err_incomplete_type_used_in_type_trait_expr))
4846 return false;
4847 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
4848 Self.RequireCompleteType(KeyLoc, RhsT,
4849 diag::err_incomplete_type_used_in_type_trait_expr))
4850 return false;
4851
4852 // cv void is never assignable.
4853 if (LhsT->isVoidType() || RhsT->isVoidType())
4854 return false;
4855
4856 // Build expressions that emulate the effect of declval<T>() and
4857 // declval<U>().
4858 if (LhsT->isObjectType() || LhsT->isFunctionType())
4859 LhsT = Self.Context.getRValueReferenceType(LhsT);
4860 if (RhsT->isObjectType() || RhsT->isFunctionType())
4861 RhsT = Self.Context.getRValueReferenceType(RhsT);
4862 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4863 Expr::getValueKindForType(LhsT));
4864 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4865 Expr::getValueKindForType(RhsT));
4866
4867 // Attempt the assignment in an unevaluated context within a SFINAE
4868 // trap at translation unit scope.
4869 EnterExpressionEvaluationContext Unevaluated(
4870 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4871 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4872 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4873 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4874 &Rhs);
4875 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4876 return false;
4877
4878 if (BTT == BTT_IsAssignable)
4879 return true;
4880
4881 if (BTT == BTT_IsNothrowAssignable)
4882 return Self.canThrow(Result.get()) == CT_Cannot;
4883
4884 if (BTT == BTT_IsTriviallyAssignable) {
4885 // Under Objective-C ARC and Weak, if the destination has non-trivial
4886 // Objective-C lifetime, this is a non-trivial assignment.
4887 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
4888 return false;
4889
4890 return !Result.get()->hasNonTrivialCall(Self.Context);
4891 }
4892
4893 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4893)
;
4894 return false;
4895 }
4896 default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4896)
;
4897 }
4898 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4898)
;
4899}
4900
4901ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4902 SourceLocation KWLoc,
4903 ParsedType Ty,
4904 Expr* DimExpr,
4905 SourceLocation RParen) {
4906 TypeSourceInfo *TSInfo;
4907 QualType T = GetTypeFromParser(Ty, &TSInfo);
4908 if (!TSInfo)
4909 TSInfo = Context.getTrivialTypeSourceInfo(T);
4910
4911 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4912}
4913
4914static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4915 QualType T, Expr *DimExpr,
4916 SourceLocation KeyLoc) {
4917 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")((!T->isDependentType() && "Cannot evaluate traits of dependent type"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4917, __PRETTY_FUNCTION__))
;
4918
4919 switch(ATT) {
4920 case ATT_ArrayRank:
4921 if (T->isArrayType()) {
4922 unsigned Dim = 0;
4923 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4924 ++Dim;
4925 T = AT->getElementType();
4926 }
4927 return Dim;
4928 }
4929 return 0;
4930
4931 case ATT_ArrayExtent: {
4932 llvm::APSInt Value;
4933 uint64_t Dim;
4934 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
4935 diag::err_dimension_expr_not_constant_integer,
4936 false).isInvalid())
4937 return 0;
4938 if (Value.isSigned() && Value.isNegative()) {
4939 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4940 << DimExpr->getSourceRange();
4941 return 0;
4942 }
4943 Dim = Value.getLimitedValue();
4944
4945 if (T->isArrayType()) {
4946 unsigned D = 0;
4947 bool Matched = false;
4948 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4949 if (Dim == D) {
4950 Matched = true;
4951 break;
4952 }
4953 ++D;
4954 T = AT->getElementType();
4955 }
4956
4957 if (Matched && T->isArrayType()) {
4958 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4959 return CAT->getSize().getLimitedValue();
4960 }
4961 }
4962 return 0;
4963 }
4964 }
4965 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4965)
;
4966}
4967
4968ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4969 SourceLocation KWLoc,
4970 TypeSourceInfo *TSInfo,
4971 Expr* DimExpr,
4972 SourceLocation RParen) {
4973 QualType T = TSInfo->getType();
4974
4975 // FIXME: This should likely be tracked as an APInt to remove any host
4976 // assumptions about the width of size_t on the target.
4977 uint64_t Value = 0;
4978 if (!T->isDependentType())
4979 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4980
4981 // While the specification for these traits from the Embarcadero C++
4982 // compiler's documentation says the return type is 'unsigned int', Clang
4983 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4984 // compiler, there is no difference. On several other platforms this is an
4985 // important distinction.
4986 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4987 RParen, Context.getSizeType());
4988}
4989
4990ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4991 SourceLocation KWLoc,
4992 Expr *Queried,
4993 SourceLocation RParen) {
4994 // If error parsing the expression, ignore.
4995 if (!Queried)
4996 return ExprError();
4997
4998 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
4999
5000 return Result;
5001}
5002
5003static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5004 switch (ET) {
5005 case ET_IsLValueExpr: return E->isLValue();
5006 case ET_IsRValueExpr: return E->isRValue();
5007 }
5008 llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5008)
;
5009}
5010
5011ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5012 SourceLocation KWLoc,
5013 Expr *Queried,
5014 SourceLocation RParen) {
5015 if (Queried->isTypeDependent()) {
5016 // Delay type-checking for type-dependent expressions.
5017 } else if (Queried->getType()->isPlaceholderType()) {
5018 ExprResult PE = CheckPlaceholderExpr(Queried);
5019 if (PE.isInvalid()) return ExprError();
5020 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5021 }
5022
5023 bool Value = EvaluateExpressionTrait(ET, Queried);
5024
5025 return new (Context)
5026 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5027}
5028
5029QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5030 ExprValueKind &VK,
5031 SourceLocation Loc,
5032 bool isIndirect) {
5033 assert(!LHS.get()->getType()->isPlaceholderType() &&((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5035, __PRETTY_FUNCTION__))
5034 !RHS.get()->getType()->isPlaceholderType() &&((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5035, __PRETTY_FUNCTION__))
5035 "placeholders should have been weeded out by now")((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5035, __PRETTY_FUNCTION__))
;
5036
5037 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5038 // temporary materialization conversion otherwise.
5039 if (isIndirect)
5040 LHS = DefaultLvalueConversion(LHS.get());
5041 else if (LHS.get()->isRValue())
5042 LHS = TemporaryMaterializationConversion(LHS.get());
5043 if (LHS.isInvalid())
5044 return QualType();
5045
5046 // The RHS always undergoes lvalue conversions.
5047 RHS = DefaultLvalueConversion(RHS.get());
5048 if (RHS.isInvalid()) return QualType();
5049
5050 const char *OpSpelling = isIndirect ? "->*" : ".*";
5051 // C++ 5.5p2
5052 // The binary operator .* [p3: ->*] binds its second operand, which shall
5053 // be of type "pointer to member of T" (where T is a completely-defined
5054 // class type) [...]
5055 QualType RHSType = RHS.get()->getType();
5056 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5057 if (!MemPtr) {
5058 Diag(Loc, diag::err_bad_memptr_rhs)
5059 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5060 return QualType();
5061 }
5062
5063 QualType Class(MemPtr->getClass(), 0);
5064
5065 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5066 // member pointer points must be completely-defined. However, there is no
5067 // reason for this semantic distinction, and the rule is not enforced by
5068 // other compilers. Therefore, we do not check this property, as it is
5069 // likely to be considered a defect.
5070
5071 // C++ 5.5p2
5072 // [...] to its first operand, which shall be of class T or of a class of
5073 // which T is an unambiguous and accessible base class. [p3: a pointer to
5074 // such a class]
5075 QualType LHSType = LHS.get()->getType();
5076 if (isIndirect) {
5077 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5078 LHSType = Ptr->getPointeeType();
5079 else {
5080 Diag(Loc, diag::err_bad_memptr_lhs)
5081 << OpSpelling << 1 << LHSType
5082 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5083 return QualType();
5084 }
5085 }
5086
5087 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5088 // If we want to check the hierarchy, we need a complete type.
5089 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5090 OpSpelling, (int)isIndirect)) {
5091 return QualType();
5092 }
5093
5094 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5095 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5096 << (int)isIndirect << LHS.get()->getType();
5097 return QualType();
5098 }
5099
5100 CXXCastPath BasePath;
5101 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5102 SourceRange(LHS.get()->getLocStart(),
5103 RHS.get()->getLocEnd()),
5104 &BasePath))
5105 return QualType();
5106
5107 // Cast LHS to type of use.
5108 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
5109 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5110 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5111 &BasePath);
5112 }
5113
5114 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5115 // Diagnose use of pointer-to-member type which when used as
5116 // the functional cast in a pointer-to-member expression.
5117 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5118 return QualType();
5119 }
5120
5121 // C++ 5.5p2
5122 // The result is an object or a function of the type specified by the
5123 // second operand.
5124 // The cv qualifiers are the union of those in the pointer and the left side,
5125 // in accordance with 5.5p5 and 5.2.5.
5126 QualType Result = MemPtr->getPointeeType();
5127 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5128
5129 // C++0x [expr.mptr.oper]p6:
5130 // In a .* expression whose object expression is an rvalue, the program is
5131 // ill-formed if the second operand is a pointer to member function with
5132 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5133 // expression is an lvalue, the program is ill-formed if the second operand
5134 // is a pointer to member function with ref-qualifier &&.
5135 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5136 switch (Proto->getRefQualifier()) {
5137 case RQ_None:
5138 // Do nothing
5139 break;
5140
5141 case RQ_LValue:
5142 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
5143 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5144 << RHSType << 1 << LHS.get()->getSourceRange();
5145 break;
5146
5147 case RQ_RValue:
5148 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5149 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5150 << RHSType << 0 << LHS.get()->getSourceRange();
5151 break;
5152 }
5153 }
5154
5155 // C++ [expr.mptr.oper]p6:
5156 // The result of a .* expression whose second operand is a pointer
5157 // to a data member is of the same value category as its
5158 // first operand. The result of a .* expression whose second
5159 // operand is a pointer to a member function is a prvalue. The
5160 // result of an ->* expression is an lvalue if its second operand
5161 // is a pointer to data member and a prvalue otherwise.
5162 if (Result->isFunctionType()) {
5163 VK = VK_RValue;
5164 return Context.BoundMemberTy;
5165 } else if (isIndirect) {
5166 VK = VK_LValue;
5167 } else {
5168 VK = LHS.get()->getValueKind();
5169 }
5170
5171 return Result;
5172}
5173
5174/// \brief Try to convert a type to another according to C++11 5.16p3.
5175///
5176/// This is part of the parameter validation for the ? operator. If either
5177/// value operand is a class type, the two operands are attempted to be
5178/// converted to each other. This function does the conversion in one direction.
5179/// It returns true if the program is ill-formed and has already been diagnosed
5180/// as such.
5181static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5182 SourceLocation QuestionLoc,
5183 bool &HaveConversion,
5184 QualType &ToType) {
5185 HaveConversion = false;
5186 ToType = To->getType();
5187
5188 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
5189 SourceLocation());
5190 // C++11 5.16p3
5191 // The process for determining whether an operand expression E1 of type T1
5192 // can be converted to match an operand expression E2 of type T2 is defined
5193 // as follows:
5194 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5195 // implicitly converted to type "lvalue reference to T2", subject to the
5196 // constraint that in the conversion the reference must bind directly to
5197 // an lvalue.
5198 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5199 // implicitly conveted to the type "rvalue reference to R2", subject to
5200 // the constraint that the reference must bind directly.
5201 if (To->isLValue() || To->isXValue()) {
5202 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5203 : Self.Context.getRValueReferenceType(ToType);
5204
5205 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5206
5207 InitializationSequence InitSeq(Self, Entity, Kind, From);
5208 if (InitSeq.isDirectReferenceBinding()) {
5209 ToType = T;
5210 HaveConversion = true;
5211 return false;
5212 }
5213
5214 if (InitSeq.isAmbiguous())
5215 return InitSeq.Diagnose(Self, Entity, Kind, From);
5216 }
5217
5218 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5219 // -- if E1 and E2 have class type, and the underlying class types are
5220 // the same or one is a base class of the other:
5221 QualType FTy = From->getType();
5222 QualType TTy = To->getType();
5223 const RecordType *FRec = FTy->getAs<RecordType>();
5224 const RecordType *TRec = TTy->getAs<RecordType>();
5225 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5226 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5227 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5228 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5229 // E1 can be converted to match E2 if the class of T2 is the
5230 // same type as, or a base class of, the class of T1, and
5231 // [cv2 > cv1].
5232 if (FRec == TRec || FDerivedFromT) {
5233 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5234 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5235 InitializationSequence InitSeq(Self, Entity, Kind, From);
5236 if (InitSeq) {
5237 HaveConversion = true;
5238 return false;
5239 }
5240
5241 if (InitSeq.isAmbiguous())
5242 return InitSeq.Diagnose(Self, Entity, Kind, From);
5243 }
5244 }
5245
5246 return false;
5247 }
5248
5249 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5250 // implicitly converted to the type that expression E2 would have
5251 // if E2 were converted to an rvalue (or the type it has, if E2 is
5252 // an rvalue).
5253 //
5254 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5255 // to the array-to-pointer or function-to-pointer conversions.
5256 TTy = TTy.getNonLValueExprType(Self.Context);
5257
5258 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5259 InitializationSequence InitSeq(Self, Entity, Kind, From);
5260 HaveConversion = !InitSeq.Failed();
5261 ToType = TTy;
5262 if (InitSeq.isAmbiguous())
5263 return InitSeq.Diagnose(Self, Entity, Kind, From);
5264
5265 return false;
5266}
5267
5268/// \brief Try to find a common type for two according to C++0x 5.16p5.
5269///
5270/// This is part of the parameter validation for the ? operator. If either
5271/// value operand is a class type, overload resolution is used to find a
5272/// conversion to a common type.
5273static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5274 SourceLocation QuestionLoc) {
5275 Expr *Args[2] = { LHS.get(), RHS.get() };
5276 OverloadCandidateSet CandidateSet(QuestionLoc,
5277 OverloadCandidateSet::CSK_Operator);
5278 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5279 CandidateSet);
5280
5281 OverloadCandidateSet::iterator Best;
5282 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5283 case OR_Success: {
5284 // We found a match. Perform the conversions on the arguments and move on.
5285 ExprResult LHSRes =
5286 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5287 Best->Conversions[0], Sema::AA_Converting);
5288 if (LHSRes.isInvalid())
5289 break;
5290 LHS = LHSRes;
5291
5292 ExprResult RHSRes =
5293 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5294 Best->Conversions[1], Sema::AA_Converting);
5295 if (RHSRes.isInvalid())
5296 break;
5297 RHS = RHSRes;
5298 if (Best->Function)
5299 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5300 return false;
5301 }
5302
5303 case OR_No_Viable_Function:
5304
5305 // Emit a better diagnostic if one of the expressions is a null pointer
5306 // constant and the other is a pointer type. In this case, the user most
5307 // likely forgot to take the address of the other expression.
5308 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5309 return true;
5310
5311 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5312 << LHS.get()->getType() << RHS.get()->getType()
5313 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5314 return true;
5315
5316 case OR_Ambiguous:
5317 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5318 << LHS.get()->getType() << RHS.get()->getType()
5319 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5320 // FIXME: Print the possible common types by printing the return types of
5321 // the viable candidates.
5322 break;
5323
5324 case OR_Deleted:
5325 llvm_unreachable("Conditional operator has only built-in overloads")::llvm::llvm_unreachable_internal("Conditional operator has only built-in overloads"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5325)
;
5326 }
5327 return true;
5328}
5329
5330/// \brief Perform an "extended" implicit conversion as returned by
5331/// TryClassUnification.
5332static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5333 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5334 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
5335 SourceLocation());
5336 Expr *Arg = E.get();
5337 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5338 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5339 if (Result.isInvalid())
5340 return true;
5341
5342 E = Result;
5343 return false;
5344}
5345
5346/// \brief Check the operands of ?: under C++ semantics.
5347///
5348/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5349/// extension. In this case, LHS == Cond. (But they're not aliases.)
5350QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5351 ExprResult &RHS, ExprValueKind &VK,
5352 ExprObjectKind &OK,
5353 SourceLocation QuestionLoc) {
5354 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5355 // interface pointers.
5356
5357 // C++11 [expr.cond]p1
5358 // The first expression is contextually converted to bool.
5359 //
5360 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5361 // a is that of a integer vector with the same number of elements and
5362 // size as the vectors of b and c. If one of either b or c is a scalar
5363 // it is implicitly converted to match the type of the vector.
5364 // Otherwise the expression is ill-formed. If both b and c are scalars,
5365 // then b and c are checked and converted to the type of a if possible.
5366 // Unlike the OpenCL ?: operator, the expression is evaluated as
5367 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5368 if (!Cond.get()->isTypeDependent()) {
5369 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5370 if (CondRes.isInvalid())
5371 return QualType();
5372 Cond = CondRes;
5373 }
5374
5375 // Assume r-value.
5376 VK = VK_RValue;
5377 OK = OK_Ordinary;
5378
5379 // Either of the arguments dependent?
5380 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5381 return Context.DependentTy;
5382
5383 // C++11 [expr.cond]p2
5384 // If either the second or the third operand has type (cv) void, ...
5385 QualType LTy = LHS.get()->getType();
5386 QualType RTy = RHS.get()->getType();
5387 bool LVoid = LTy->isVoidType();
5388 bool RVoid = RTy->isVoidType();
5389 if (LVoid || RVoid) {
5390 // ... one of the following shall hold:
5391 // -- The second or the third operand (but not both) is a (possibly
5392 // parenthesized) throw-expression; the result is of the type
5393 // and value category of the other.
5394 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5395 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5396 if (LThrow != RThrow) {
5397 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5398 VK = NonThrow->getValueKind();
5399 // DR (no number yet): the result is a bit-field if the
5400 // non-throw-expression operand is a bit-field.
5401 OK = NonThrow->getObjectKind();
5402 return NonThrow->getType();
5403 }
5404
5405 // -- Both the second and third operands have type void; the result is of
5406 // type void and is a prvalue.
5407 if (LVoid && RVoid)
5408 return Context.VoidTy;
5409
5410 // Neither holds, error.
5411 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5412 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5413 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5414 return QualType();
5415 }
5416
5417 // Neither is void.
5418
5419 // C++11 [expr.cond]p3
5420 // Otherwise, if the second and third operand have different types, and
5421 // either has (cv) class type [...] an attempt is made to convert each of
5422 // those operands to the type of the other.
5423 if (!Context.hasSameType(LTy, RTy) &&
5424 (LTy->isRecordType() || RTy->isRecordType())) {
5425 // These return true if a single direction is already ambiguous.
5426 QualType L2RType, R2LType;
5427 bool HaveL2R, HaveR2L;
5428 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5429 return QualType();
5430 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5431 return QualType();
5432
5433 // If both can be converted, [...] the program is ill-formed.
5434 if (HaveL2R && HaveR2L) {
5435 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5436 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5437 return QualType();
5438 }
5439
5440 // If exactly one conversion is possible, that conversion is applied to
5441 // the chosen operand and the converted operands are used in place of the
5442 // original operands for the remainder of this section.
5443 if (HaveL2R) {
5444 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5445 return QualType();
5446 LTy = LHS.get()->getType();
5447 } else if (HaveR2L) {
5448 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5449 return QualType();
5450 RTy = RHS.get()->getType();
5451 }
5452 }
5453
5454 // C++11 [expr.cond]p3
5455 // if both are glvalues of the same value category and the same type except
5456 // for cv-qualification, an attempt is made to convert each of those
5457 // operands to the type of the other.
5458 // FIXME:
5459 // Resolving a defect in P0012R1: we extend this to cover all cases where
5460 // one of the operands is reference-compatible with the other, in order
5461 // to support conditionals between functions differing in noexcept.
5462 ExprValueKind LVK = LHS.get()->getValueKind();
5463 ExprValueKind RVK = RHS.get()->getValueKind();
5464 if (!Context.hasSameType(LTy, RTy) &&
5465 LVK == RVK && LVK != VK_RValue) {
5466 // DerivedToBase was already handled by the class-specific case above.
5467 // FIXME: Should we allow ObjC conversions here?
5468 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5469 if (CompareReferenceRelationship(
5470 QuestionLoc, LTy, RTy, DerivedToBase,
5471 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5472 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5473 // [...] subject to the constraint that the reference must bind
5474 // directly [...]
5475 !RHS.get()->refersToBitField() &&
5476 !RHS.get()->refersToVectorElement()) {
5477 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5478 RTy = RHS.get()->getType();
5479 } else if (CompareReferenceRelationship(
5480 QuestionLoc, RTy, LTy, DerivedToBase,
5481 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5482 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5483 !LHS.get()->refersToBitField() &&
5484 !LHS.get()->refersToVectorElement()) {
5485 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5486 LTy = LHS.get()->getType();
5487 }
5488 }
5489
5490 // C++11 [expr.cond]p4
5491 // If the second and third operands are glvalues of the same value
5492 // category and have the same type, the result is of that type and
5493 // value category and it is a bit-field if the second or the third
5494 // operand is a bit-field, or if both are bit-fields.
5495 // We only extend this to bitfields, not to the crazy other kinds of
5496 // l-values.
5497 bool Same = Context.hasSameType(LTy, RTy);
5498 if (Same && LVK == RVK && LVK != VK_RValue &&
5499 LHS.get()->isOrdinaryOrBitFieldObject() &&
5500 RHS.get()->isOrdinaryOrBitFieldObject()) {
5501 VK = LHS.get()->getValueKind();
5502 if (LHS.get()->getObjectKind() == OK_BitField ||
5503 RHS.get()->getObjectKind() == OK_BitField)
5504 OK = OK_BitField;
5505
5506 // If we have function pointer types, unify them anyway to unify their
5507 // exception specifications, if any.
5508 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5509 Qualifiers Qs = LTy.getQualifiers();
5510 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
5511 /*ConvertArgs*/false);
5512 LTy = Context.getQualifiedType(LTy, Qs);
5513
5514 assert(!LTy.isNull() && "failed to find composite pointer type for "((!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? static_cast<
void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5515, __PRETTY_FUNCTION__))
5515 "canonically equivalent function ptr types")((!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? static_cast<
void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5515, __PRETTY_FUNCTION__))
;
5516 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type")((Context.hasSameType(LTy, RTy) && "bad composite pointer type"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(LTy, RTy) && \"bad composite pointer type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5516, __PRETTY_FUNCTION__))
;
5517 }
5518
5519 return LTy;
5520 }
5521
5522 // C++11 [expr.cond]p5
5523 // Otherwise, the result is a prvalue. If the second and third operands
5524 // do not have the same type, and either has (cv) class type, ...
5525 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5526 // ... overload resolution is used to determine the conversions (if any)
5527 // to be applied to the operands. If the overload resolution fails, the
5528 // program is ill-formed.
5529 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5530 return QualType();
5531 }
5532
5533 // C++11 [expr.cond]p6
5534 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5535 // conversions are performed on the second and third operands.
5536 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5537 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5538 if (LHS.isInvalid() || RHS.isInvalid())
5539 return QualType();
5540 LTy = LHS.get()->getType();
5541 RTy = RHS.get()->getType();
5542
5543 // After those conversions, one of the following shall hold:
5544 // -- The second and third operands have the same type; the result
5545 // is of that type. If the operands have class type, the result
5546 // is a prvalue temporary of the result type, which is
5547 // copy-initialized from either the second operand or the third
5548 // operand depending on the value of the first operand.
5549 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5550 if (LTy->isRecordType()) {
5551 // The operands have class type. Make a temporary copy.
5552 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5553
5554 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5555 SourceLocation(),
5556 LHS);
5557 if (LHSCopy.isInvalid())
5558 return QualType();
5559
5560 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5561 SourceLocation(),
5562 RHS);
5563 if (RHSCopy.isInvalid())
5564 return QualType();
5565
5566 LHS = LHSCopy;
5567 RHS = RHSCopy;
5568 }
5569
5570 // If we have function pointer types, unify them anyway to unify their
5571 // exception specifications, if any.
5572 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5573 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5574 assert(!LTy.isNull() && "failed to find composite pointer type for "((!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? static_cast<
void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5575, __PRETTY_FUNCTION__))
5575 "canonically equivalent function ptr types")((!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? static_cast<
void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5575, __PRETTY_FUNCTION__))
;
5576 }
5577
5578 return LTy;
5579 }
5580
5581 // Extension: conditional operator involving vector types.
5582 if (LTy->isVectorType() || RTy->isVectorType())
5583 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5584 /*AllowBothBool*/true,
5585 /*AllowBoolConversions*/false);
5586
5587 // -- The second and third operands have arithmetic or enumeration type;
5588 // the usual arithmetic conversions are performed to bring them to a
5589 // common type, and the result is of that type.
5590 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5591 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5592 if (LHS.isInvalid() || RHS.isInvalid())
5593 return QualType();
5594 if (ResTy.isNull()) {
5595 Diag(QuestionLoc,
5596 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5597 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5598 return QualType();
5599 }
5600
5601 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5602 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5603
5604 return ResTy;
5605 }
5606
5607 // -- The second and third operands have pointer type, or one has pointer
5608 // type and the other is a null pointer constant, or both are null
5609 // pointer constants, at least one of which is non-integral; pointer
5610 // conversions and qualification conversions are performed to bring them
5611 // to their composite pointer type. The result is of the composite
5612 // pointer type.
5613 // -- The second and third operands have pointer to member type, or one has
5614 // pointer to member type and the other is a null pointer constant;
5615 // pointer to member conversions and qualification conversions are
5616 // performed to bring them to a common type, whose cv-qualification
5617 // shall match the cv-qualification of either the second or the third
5618 // operand. The result is of the common type.
5619 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5620 if (!Composite.isNull())
5621 return Composite;
5622
5623 // Similarly, attempt to find composite type of two objective-c pointers.
5624 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5625 if (!Composite.isNull())
5626 return Composite;
5627
5628 // Check if we are using a null with a non-pointer type.
5629 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5630 return QualType();
5631
5632 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5633 << LHS.get()->getType() << RHS.get()->getType()
5634 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5635 return QualType();
5636}
5637
5638static FunctionProtoType::ExceptionSpecInfo
5639mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5640 FunctionProtoType::ExceptionSpecInfo ESI2,
5641 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5642 ExceptionSpecificationType EST1 = ESI1.Type;
5643 ExceptionSpecificationType EST2 = ESI2.Type;
5644
5645 // If either of them can throw anything, that is the result.
5646 if (EST1 == EST_None) return ESI1;
5647 if (EST2 == EST_None) return ESI2;
5648 if (EST1 == EST_MSAny) return ESI1;
5649 if (EST2 == EST_MSAny) return ESI2;
5650
5651 // If either of them is non-throwing, the result is the other.
5652 if (EST1 == EST_DynamicNone) return ESI2;
5653 if (EST2 == EST_DynamicNone) return ESI1;
5654 if (EST1 == EST_BasicNoexcept) return ESI2;
5655 if (EST2 == EST_BasicNoexcept) return ESI1;
5656
5657 // If either of them is a non-value-dependent computed noexcept, that
5658 // determines the result.
5659 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5660 !ESI2.NoexceptExpr->isValueDependent())
5661 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5662 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5663 !ESI1.NoexceptExpr->isValueDependent())
5664 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5665 // If we're left with value-dependent computed noexcept expressions, we're
5666 // stuck. Before C++17, we can just drop the exception specification entirely,
5667 // since it's not actually part of the canonical type. And this should never
5668 // happen in C++17, because it would mean we were computing the composite
5669 // pointer type of dependent types, which should never happen.
5670 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5671 assert(!S.getLangOpts().CPlusPlus1z &&((!S.getLangOpts().CPlusPlus1z && "computing composite pointer type of dependent types"
) ? static_cast<void> (0) : __assert_fail ("!S.getLangOpts().CPlusPlus1z && \"computing composite pointer type of dependent types\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5672, __PRETTY_FUNCTION__))
5672 "computing composite pointer type of dependent types")((!S.getLangOpts().CPlusPlus1z && "computing composite pointer type of dependent types"
) ? static_cast<void> (0) : __assert_fail ("!S.getLangOpts().CPlusPlus1z && \"computing composite pointer type of dependent types\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5672, __PRETTY_FUNCTION__))
;
5673 return FunctionProtoType::ExceptionSpecInfo();
5674 }
5675
5676 // Switch over the possibilities so that people adding new values know to
5677 // update this function.
5678 switch (EST1) {
5679 case EST_None:
5680 case EST_DynamicNone:
5681 case EST_MSAny:
5682 case EST_BasicNoexcept:
5683 case EST_ComputedNoexcept:
5684 llvm_unreachable("handled above")::llvm::llvm_unreachable_internal("handled above", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5684)
;
5685
5686 case EST_Dynamic: {
5687 // This is the fun case: both exception specifications are dynamic. Form
5688 // the union of the two lists.
5689 assert(EST2 == EST_Dynamic && "other cases should already be handled")((EST2 == EST_Dynamic && "other cases should already be handled"
) ? static_cast<void> (0) : __assert_fail ("EST2 == EST_Dynamic && \"other cases should already be handled\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5689, __PRETTY_FUNCTION__))
;
5690 llvm::SmallPtrSet<QualType, 8> Found;
5691 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5692 for (QualType E : Exceptions)
5693 if (Found.insert(S.Context.getCanonicalType(E)).second)
5694 ExceptionTypeStorage.push_back(E);
5695
5696 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5697 Result.Exceptions = ExceptionTypeStorage;
5698 return Result;
5699 }
5700
5701 case EST_Unevaluated:
5702 case EST_Uninstantiated:
5703 case EST_Unparsed:
5704 llvm_unreachable("shouldn't see unresolved exception specifications here")::llvm::llvm_unreachable_internal("shouldn't see unresolved exception specifications here"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5704)
;
5705 }
5706
5707 llvm_unreachable("invalid ExceptionSpecificationType")::llvm::llvm_unreachable_internal("invalid ExceptionSpecificationType"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5707)
;
5708}
5709
5710/// \brief Find a merged pointer type and convert the two expressions to it.
5711///
5712/// This finds the composite pointer type (or member pointer type) for @p E1
5713/// and @p E2 according to C++1z 5p14. It converts both expressions to this
5714/// type and returns it.
5715/// It does not emit diagnostics.
5716///
5717/// \param Loc The location of the operator requiring these two expressions to
5718/// be converted to the composite pointer type.
5719///
5720/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
5721QualType Sema::FindCompositePointerType(SourceLocation Loc,
5722 Expr *&E1, Expr *&E2,
5723 bool ConvertArgs) {
5724 assert(getLangOpts().CPlusPlus && "This function assumes C++")((getLangOpts().CPlusPlus && "This function assumes C++"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"This function assumes C++\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5724, __PRETTY_FUNCTION__))
;
5725
5726 // C++1z [expr]p14:
5727 // The composite pointer type of two operands p1 and p2 having types T1
5728 // and T2
5729 QualType T1 = E1->getType(), T2 = E2->getType();
5730
5731 // where at least one is a pointer or pointer to member type or
5732 // std::nullptr_t is:
5733 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5734 T1->isNullPtrType();
5735 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5736 T2->isNullPtrType();
5737 if (!T1IsPointerLike && !T2IsPointerLike)
5738 return QualType();
5739
5740 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5741 // This can't actually happen, following the standard, but we also use this
5742 // to implement the end of [expr.conv], which hits this case.
5743 //
5744 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5745 if (T1IsPointerLike &&
5746 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5747 if (ConvertArgs)
5748 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5749 ? CK_NullToMemberPointer
5750 : CK_NullToPointer).get();
5751 return T1;
5752 }
5753 if (T2IsPointerLike &&
5754 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5755 if (ConvertArgs)
5756 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5757 ? CK_NullToMemberPointer
5758 : CK_NullToPointer).get();
5759 return T2;
5760 }
5761
5762 // Now both have to be pointers or member pointers.
5763 if (!T1IsPointerLike || !T2IsPointerLike)
5764 return QualType();
5765 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&((!T1->isNullPtrType() && !T2->isNullPtrType() &&
"nullptr_t should be a null pointer constant") ? static_cast
<void> (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5766, __PRETTY_FUNCTION__))
5766 "nullptr_t should be a null pointer constant")((!T1->isNullPtrType() && !T2->isNullPtrType() &&
"nullptr_t should be a null pointer constant") ? static_cast
<void> (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5766, __PRETTY_FUNCTION__))
;
5767
5768 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5769 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5770 // the union of cv1 and cv2;
5771 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5772 // "pointer to function", where the function types are otherwise the same,
5773 // "pointer to function";
5774 // FIXME: This rule is defective: it should also permit removing noexcept
5775 // from a pointer to member function. As a Clang extension, we also
5776 // permit removing 'noreturn', so we generalize this rule to;
5777 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5778 // "pointer to member function" and the pointee types can be unified
5779 // by a function pointer conversion, that conversion is applied
5780 // before checking the following rules.
5781 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5782 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5783 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5784 // respectively;
5785 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5786 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5787 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5788 // T1 or the cv-combined type of T1 and T2, respectively;
5789 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5790 // T2;
5791 //
5792 // If looked at in the right way, these bullets all do the same thing.
5793 // What we do here is, we build the two possible cv-combined types, and try
5794 // the conversions in both directions. If only one works, or if the two
5795 // composite types are the same, we have succeeded.
5796 // FIXME: extended qualifiers?
5797 //
5798 // Note that this will fail to find a composite pointer type for "pointer
5799 // to void" and "pointer to function". We can't actually perform the final
5800 // conversion in this case, even though a composite pointer type formally
5801 // exists.
5802 SmallVector<unsigned, 4> QualifierUnion;
5803 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
5804 QualType Composite1 = T1;
5805 QualType Composite2 = T2;
5806 unsigned NeedConstBefore = 0;
5807 while (true) {
5808 const PointerType *Ptr1, *Ptr2;
5809 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5810 (Ptr2 = Composite2->getAs<PointerType>())) {
5811 Composite1 = Ptr1->getPointeeType();
5812 Composite2 = Ptr2->getPointeeType();
5813
5814 // If we're allowed to create a non-standard composite type, keep track
5815 // of where we need to fill in additional 'const' qualifiers.
5816 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5817 NeedConstBefore = QualifierUnion.size();
5818
5819 QualifierUnion.push_back(
5820 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5821 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
5822 continue;
5823 }
5824
5825 const MemberPointerType *MemPtr1, *MemPtr2;
5826 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5827 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5828 Composite1 = MemPtr1->getPointeeType();
5829 Composite2 = MemPtr2->getPointeeType();
5830
5831 // If we're allowed to create a non-standard composite type, keep track
5832 // of where we need to fill in additional 'const' qualifiers.
5833 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5834 NeedConstBefore = QualifierUnion.size();
5835
5836 QualifierUnion.push_back(
5837 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5838 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5839 MemPtr2->getClass()));
5840 continue;
5841 }
5842
5843 // FIXME: block pointer types?
5844
5845 // Cannot unwrap any more types.
5846 break;
5847 }
5848
5849 // Apply the function pointer conversion to unify the types. We've already
5850 // unwrapped down to the function types, and we want to merge rather than
5851 // just convert, so do this ourselves rather than calling
5852 // IsFunctionConversion.
5853 //
5854 // FIXME: In order to match the standard wording as closely as possible, we
5855 // currently only do this under a single level of pointers. Ideally, we would
5856 // allow this in general, and set NeedConstBefore to the relevant depth on
5857 // the side(s) where we changed anything.
5858 if (QualifierUnion.size() == 1) {
5859 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5860 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5861 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5862 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5863
5864 // The result is noreturn if both operands are.
5865 bool Noreturn =
5866 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5867 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5868 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5869
5870 // The result is nothrow if both operands are.
5871 SmallVector<QualType, 8> ExceptionTypeStorage;
5872 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5873 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5874 ExceptionTypeStorage);
5875
5876 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5877 FPT1->getParamTypes(), EPI1);
5878 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5879 FPT2->getParamTypes(), EPI2);
5880 }
5881 }
5882 }
5883
5884 if (NeedConstBefore) {
5885 // Extension: Add 'const' to qualifiers that come before the first qualifier
5886 // mismatch, so that our (non-standard!) composite type meets the
5887 // requirements of C++ [conv.qual]p4 bullet 3.
5888 for (unsigned I = 0; I != NeedConstBefore; ++I)
5889 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
5890 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5891 }
5892
5893 // Rewrap the composites as pointers or member pointers with the union CVRs.
5894 auto MOC = MemberOfClass.rbegin();
5895 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5896 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5897 auto Classes = *MOC++;
5898 if (Classes.first && Classes.second) {
5899 // Rebuild member pointer type
5900 Composite1 = Context.getMemberPointerType(
5901 Context.getQualifiedType(Composite1, Quals), Classes.first);
5902 Composite2 = Context.getMemberPointerType(
5903 Context.getQualifiedType(Composite2, Quals), Classes.second);
5904 } else {
5905 // Rebuild pointer type
5906 Composite1 =
5907 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5908 Composite2 =
5909 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
5910 }
5911 }
5912
5913 struct Conversion {
5914 Sema &S;
5915 Expr *&E1, *&E2;
5916 QualType Composite;
5917 InitializedEntity Entity;
5918 InitializationKind Kind;
5919 InitializationSequence E1ToC, E2ToC;
5920 bool Viable;
5921
5922 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5923 QualType Composite)
5924 : S(S), E1(E1), E2(E2), Composite(Composite),
5925 Entity(InitializedEntity::InitializeTemporary(Composite)),
5926 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5927 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5928 Viable(E1ToC && E2ToC) {}
5929
5930 bool perform() {
5931 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5932 if (E1Result.isInvalid())
5933 return true;
5934 E1 = E1Result.getAs<Expr>();
5935
5936 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5937 if (E2Result.isInvalid())
5938 return true;
5939 E2 = E2Result.getAs<Expr>();
5940
5941 return false;
5942 }
5943 };
5944
5945 // Try to convert to each composite pointer type.
5946 Conversion C1(*this, Loc, E1, E2, Composite1);
5947 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5948 if (ConvertArgs && C1.perform())
5949 return QualType();
5950 return C1.Composite;
5951 }
5952 Conversion C2(*this, Loc, E1, E2, Composite2);
5953
5954 if (C1.Viable == C2.Viable) {
5955 // Either Composite1 and Composite2 are viable and are different, or
5956 // neither is viable.
5957 // FIXME: How both be viable and different?
5958 return QualType();
5959 }
5960
5961 // Convert to the chosen type.
5962 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
5963 return QualType();
5964
5965 return C1.Viable ? C1.Composite : C2.Composite;
5966}
5967
5968ExprResult Sema::MaybeBindToTemporary(Expr *E) {
5969 if (!E)
5970 return ExprError();
5971
5972 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?")((!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXBindTemporaryExpr>(E) && \"Double-bound temporary?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5972, __PRETTY_FUNCTION__))
;
5973
5974 // If the result is a glvalue, we shouldn't bind it.
5975 if (!E->isRValue())
5976 return E;
5977
5978 // In ARC, calls that return a retainable type can return retained,
5979 // in which case we have to insert a consuming cast.
5980 if (getLangOpts().ObjCAutoRefCount &&
5981 E->getType()->isObjCRetainableType()) {
5982
5983 bool ReturnsRetained;
5984
5985 // For actual calls, we compute this by examining the type of the
5986 // called value.
5987 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5988 Expr *Callee = Call->getCallee()->IgnoreParens();
5989 QualType T = Callee->getType();
5990
5991 if (T == Context.BoundMemberTy) {
5992 // Handle pointer-to-members.
5993 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5994 T = BinOp->getRHS()->getType();
5995 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5996 T = Mem->getMemberDecl()->getType();
5997 }
5998
5999 if (const PointerType *Ptr = T->getAs<PointerType>())
6000 T = Ptr->getPointeeType();
6001 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6002 T = Ptr->getPointeeType();
6003 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6004 T = MemPtr->getPointeeType();
6005
6006 const FunctionType *FTy = T->getAs<FunctionType>();
6007 assert(FTy && "call to value not of function type?")((FTy && "call to value not of function type?") ? static_cast
<void> (0) : __assert_fail ("FTy && \"call to value not of function type?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6007, __PRETTY_FUNCTION__))
;
6008 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6009
6010 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6011 // type always produce a +1 object.
6012 } else if (isa<StmtExpr>(E)) {
6013 ReturnsRetained = true;
6014
6015 // We hit this case with the lambda conversion-to-block optimization;
6016 // we don't want any extra casts here.
6017 } else if (isa<CastExpr>(E) &&
6018 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6019 return E;
6020
6021 // For message sends and property references, we try to find an
6022 // actual method. FIXME: we should infer retention by selector in
6023 // cases where we don't have an actual method.
6024 } else {
6025 ObjCMethodDecl *D = nullptr;
6026 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6027 D = Send->getMethodDecl();
6028 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6029 D = BoxedExpr->getBoxingMethod();
6030 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6031 // Don't do reclaims if we're using the zero-element array
6032 // constant.
6033 if (ArrayLit->getNumElements() == 0 &&
6034 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6035 return E;
6036
6037 D = ArrayLit->getArrayWithObjectsMethod();
6038 } else if (ObjCDictionaryLiteral *DictLit
6039 = dyn_cast<ObjCDictionaryLiteral>(E)) {
6040 // Don't do reclaims if we're using the zero-element dictionary
6041 // constant.
6042 if (DictLit->getNumElements() == 0 &&
6043 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6044 return E;
6045
6046 D = DictLit->getDictWithObjectsMethod();
6047 }
6048
6049 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6050
6051 // Don't do reclaims on performSelector calls; despite their
6052 // return type, the invoked method doesn't necessarily actually
6053 // return an object.
6054 if (!ReturnsRetained &&
6055 D && D->getMethodFamily() == OMF_performSelector)
6056 return E;
6057 }
6058
6059 // Don't reclaim an object of Class type.
6060 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6061 return E;
6062
6063 Cleanup.setExprNeedsCleanups(true);
6064
6065 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6066 : CK_ARCReclaimReturnedObject);
6067 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6068 VK_RValue);
6069 }
6070
6071 if (!getLangOpts().CPlusPlus)
6072 return E;
6073
6074 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6075 // a fast path for the common case that the type is directly a RecordType.
6076 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6077 const RecordType *RT = nullptr;
6078 while (!RT) {
6079 switch (T->getTypeClass()) {
6080 case Type::Record:
6081 RT = cast<RecordType>(T);
6082 break;
6083 case Type::ConstantArray:
6084 case Type::IncompleteArray:
6085 case Type::VariableArray:
6086 case Type::DependentSizedArray:
6087 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6088 break;
6089 default:
6090 return E;
6091 }
6092 }
6093
6094 // That should be enough to guarantee that this type is complete, if we're
6095 // not processing a decltype expression.
6096 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6097 if (RD->isInvalidDecl() || RD->isDependentContext())
6098 return E;
6099
6100 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
6101 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6102
6103 if (Destructor) {
6104 MarkFunctionReferenced(E->getExprLoc(), Destructor);
6105 CheckDestructorAccess(E->getExprLoc(), Destructor,
6106 PDiag(diag::err_access_dtor_temp)
6107 << E->getType());
6108 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6109 return ExprError();
6110
6111 // If destructor is trivial, we can avoid the extra copy.
6112 if (Destructor->isTrivial())
6113 return E;
6114
6115 // We need a cleanup, but we don't need to remember the temporary.
6116 Cleanup.setExprNeedsCleanups(true);
6117 }
6118
6119 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6120 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6121
6122 if (IsDecltype)
6123 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6124
6125 return Bind;
6126}
6127
6128ExprResult
6129Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
6130 if (SubExpr.isInvalid())
6131 return ExprError();
6132
6133 return MaybeCreateExprWithCleanups(SubExpr.get());
6134}
6135
6136Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
6137 assert(SubExpr && "subexpression can't be null!")((SubExpr && "subexpression can't be null!") ? static_cast
<void> (0) : __assert_fail ("SubExpr && \"subexpression can't be null!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6137, __PRETTY_FUNCTION__))
;
6138
6139 CleanupVarDeclMarking();
6140
6141 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6142 assert(ExprCleanupObjects.size() >= FirstCleanup)((ExprCleanupObjects.size() >= FirstCleanup) ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() >= FirstCleanup"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6142, __PRETTY_FUNCTION__))
;
6143 assert(Cleanup.exprNeedsCleanups() ||((Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() ==
FirstCleanup) ? static_cast<void> (0) : __assert_fail (
"Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6144, __PRETTY_FUNCTION__))
6144 ExprCleanupObjects.size() == FirstCleanup)((Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() ==
FirstCleanup) ? static_cast<void> (0) : __assert_fail (
"Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6144, __PRETTY_FUNCTION__))
;
6145 if (!Cleanup.exprNeedsCleanups())
6146 return SubExpr;
6147
6148 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6149 ExprCleanupObjects.size() - FirstCleanup);
6150
6151 auto *E = ExprWithCleanups::Create(
6152 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6153 DiscardCleanupsInEvaluationContext();
6154
6155 return E;
6156}
6157
6158Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
6159 assert(SubStmt && "sub-statement can't be null!")((SubStmt && "sub-statement can't be null!") ? static_cast
<void> (0) : __assert_fail ("SubStmt && \"sub-statement can't be null!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6159, __PRETTY_FUNCTION__))
;
6160
6161 CleanupVarDeclMarking();
6162
6163 if (!Cleanup.exprNeedsCleanups())
6164 return SubStmt;
6165
6166 // FIXME: In order to attach the temporaries, wrap the statement into
6167 // a StmtExpr; currently this is only used for asm statements.
6168 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6169 // a new AsmStmtWithTemporaries.
6170 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
6171 SourceLocation(),
6172 SourceLocation());
6173 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6174 SourceLocation());
6175 return MaybeCreateExprWithCleanups(E);
6176}
6177
6178/// Process the expression contained within a decltype. For such expressions,
6179/// certain semantic checks on temporaries are delayed until this point, and
6180/// are omitted for the 'topmost' call in the decltype expression. If the
6181/// topmost call bound a temporary, strip that temporary off the expression.
6182ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
6183 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression")((ExprEvalContexts.back().IsDecltype && "not in a decltype expression"
) ? static_cast<void> (0) : __assert_fail ("ExprEvalContexts.back().IsDecltype && \"not in a decltype expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6183, __PRETTY_FUNCTION__))
;
6184
6185 // C++11 [expr.call]p11:
6186 // If a function call is a prvalue of object type,
6187 // -- if the function call is either
6188 // -- the operand of a decltype-specifier, or
6189 // -- the right operand of a comma operator that is the operand of a
6190 // decltype-specifier,
6191 // a temporary object is not introduced for the prvalue.
6192
6193 // Recursively rebuild ParenExprs and comma expressions to strip out the
6194 // outermost CXXBindTemporaryExpr, if any.
6195 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6196 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6197 if (SubExpr.isInvalid())
6198 return ExprError();
6199 if (SubExpr.get() == PE->getSubExpr())
6200 return E;
6201 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6202 }
6203 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6204 if (BO->getOpcode() == BO_Comma) {
6205 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6206 if (RHS.isInvalid())
6207 return ExprError();
6208 if (RHS.get() == BO->getRHS())
6209 return E;
6210 return new (Context) BinaryOperator(
6211 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6212 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
6213 }
6214 }
6215
6216 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6217 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6218 : nullptr;
6219 if (TopCall)
6220 E = TopCall;
6221 else
6222 TopBind = nullptr;
6223
6224 // Disable the special decltype handling now.
6225 ExprEvalContexts.back().IsDecltype = false;
6226
6227 // In MS mode, don't perform any extra checking of call return types within a
6228 // decltype expression.
6229 if (getLangOpts().MSVCCompat)
6230 return E;
6231
6232 // Perform the semantic checks we delayed until this point.
6233 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6234 I != N; ++I) {
6235 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6236 if (Call == TopCall)
6237 continue;
6238
6239 if (CheckCallReturnType(Call->getCallReturnType(Context),
6240 Call->getLocStart(),
6241 Call, Call->getDirectCallee()))
6242 return ExprError();
6243 }
6244
6245 // Now all relevant types are complete, check the destructors are accessible
6246 // and non-deleted, and annotate them on the temporaries.
6247 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6248 I != N; ++I) {
6249 CXXBindTemporaryExpr *Bind =
6250 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6251 if (Bind == TopBind)
6252 continue;
6253
6254 CXXTemporary *Temp = Bind->getTemporary();
6255
6256 CXXRecordDecl *RD =
6257 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6258 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6259 Temp->setDestructor(Destructor);
6260
6261 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6262 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6263 PDiag(diag::err_access_dtor_temp)
6264 << Bind->getType());
6265 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6266 return ExprError();
6267
6268 // We need a cleanup, but we don't need to remember the temporary.
6269 Cleanup.setExprNeedsCleanups(true);
6270 }
6271
6272 // Possibly strip off the top CXXBindTemporaryExpr.
6273 return E;
6274}
6275
6276/// Note a set of 'operator->' functions that were used for a member access.
6277static void noteOperatorArrows(Sema &S,
6278 ArrayRef<FunctionDecl *> OperatorArrows) {
6279 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6280 // FIXME: Make this configurable?
6281 unsigned Limit = 9;
6282 if (OperatorArrows.size() > Limit) {
6283 // Produce Limit-1 normal notes and one 'skipping' note.
6284 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6285 SkipCount = OperatorArrows.size() - (Limit - 1);
6286 }
6287
6288 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6289 if (I == SkipStart) {
6290 S.Diag(OperatorArrows[I]->getLocation(),
6291 diag::note_operator_arrows_suppressed)
6292 << SkipCount;
6293 I += SkipCount;
6294 } else {
6295 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6296 << OperatorArrows[I]->getCallResultType();
6297 ++I;
6298 }
6299 }
6300}
6301
6302ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6303 SourceLocation OpLoc,
6304 tok::TokenKind OpKind,
6305 ParsedType &ObjectType,
6306 bool &MayBePseudoDestructor) {
6307 // Since this might be a postfix expression, get rid of ParenListExprs.
6308 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
6309 if (Result.isInvalid()) return ExprError();
6310 Base = Result.get();
6311
6312 Result = CheckPlaceholderExpr(Base);
6313 if (Result.isInvalid()) return ExprError();
6314 Base = Result.get();
6315
6316 QualType BaseType = Base->getType();
6317 MayBePseudoDestructor = false;
6318 if (BaseType->isDependentType()) {
6319 // If we have a pointer to a dependent type and are using the -> operator,
6320 // the object type is the type that the pointer points to. We might still
6321 // have enough information about that type to do something useful.
6322 if (OpKind == tok::arrow)
6323 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6324 BaseType = Ptr->getPointeeType();
6325
6326 ObjectType = ParsedType::make(BaseType);
6327 MayBePseudoDestructor = true;
6328 return Base;
6329 }
6330
6331 // C++ [over.match.oper]p8:
6332 // [...] When operator->returns, the operator-> is applied to the value
6333 // returned, with the original second operand.
6334 if (OpKind == tok::arrow) {
6335 QualType StartingType = BaseType;
6336 bool NoArrowOperatorFound = false;
6337 bool FirstIteration = true;
6338 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6339 // The set of types we've considered so far.
6340 llvm::SmallPtrSet<CanQualType,8> CTypes;
6341 SmallVector<FunctionDecl*, 8> OperatorArrows;
6342 CTypes.insert(Context.getCanonicalType(BaseType));
6343
6344 while (BaseType->isRecordType()) {
6345 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6346 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6347 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6348 noteOperatorArrows(*this, OperatorArrows);
6349 Diag(OpLoc, diag::note_operator_arrow_depth)
6350 << getLangOpts().ArrowDepth;
6351 return ExprError();
6352 }
6353
6354 Result = BuildOverloadedArrowExpr(
6355 S, Base, OpLoc,
6356 // When in a template specialization and on the first loop iteration,
6357 // potentially give the default diagnostic (with the fixit in a
6358 // separate note) instead of having the error reported back to here
6359 // and giving a diagnostic with a fixit attached to the error itself.
6360 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6361 ? nullptr
6362 : &NoArrowOperatorFound);
6363 if (Result.isInvalid()) {
6364 if (NoArrowOperatorFound) {
6365 if (FirstIteration) {
6366 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6367 << BaseType << 1 << Base->getSourceRange()
6368 << FixItHint::CreateReplacement(OpLoc, ".");
6369 OpKind = tok::period;
6370 break;
6371 }
6372 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6373 << BaseType << Base->getSourceRange();
6374 CallExpr *CE = dyn_cast<CallExpr>(Base);
6375 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
6376 Diag(CD->getLocStart(),
6377 diag::note_member_reference_arrow_from_operator_arrow);
6378 }
6379 }
6380 return ExprError();
6381 }
6382 Base = Result.get();
6383 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
6384 OperatorArrows.push_back(OpCall->getDirectCallee());
6385 BaseType = Base->getType();
6386 CanQualType CBaseType = Context.getCanonicalType(BaseType);
6387 if (!CTypes.insert(CBaseType).second) {
6388 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6389 noteOperatorArrows(*this, OperatorArrows);
6390 return ExprError();
6391 }
6392 FirstIteration = false;
6393 }
6394
6395 if (OpKind == tok::arrow &&
6396 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
6397 BaseType = BaseType->getPointeeType();
6398 }
6399
6400 // Objective-C properties allow "." access on Objective-C pointer types,
6401 // so adjust the base type to the object type itself.
6402 if (BaseType->isObjCObjectPointerType())
6403 BaseType = BaseType->getPointeeType();
6404
6405 // C++ [basic.lookup.classref]p2:
6406 // [...] If the type of the object expression is of pointer to scalar
6407 // type, the unqualified-id is looked up in the context of the complete
6408 // postfix-expression.
6409 //
6410 // This also indicates that we could be parsing a pseudo-destructor-name.
6411 // Note that Objective-C class and object types can be pseudo-destructor
6412 // expressions or normal member (ivar or property) access expressions, and
6413 // it's legal for the type to be incomplete if this is a pseudo-destructor
6414 // call. We'll do more incomplete-type checks later in the lookup process,
6415 // so just skip this check for ObjC types.
6416 if (BaseType->isObjCObjectOrInterfaceType()) {
6417 ObjectType = ParsedType::make(BaseType);
6418 MayBePseudoDestructor = true;
6419 return Base;
6420 } else if (!BaseType->isRecordType()) {
6421 ObjectType = nullptr;
6422 MayBePseudoDestructor = true;
6423 return Base;
6424 }
6425
6426 // The object type must be complete (or dependent), or
6427 // C++11 [expr.prim.general]p3:
6428 // Unlike the object expression in other contexts, *this is not required to
6429 // be of complete type for purposes of class member access (5.2.5) outside
6430 // the member function body.
6431 if (!BaseType->isDependentType() &&
6432 !isThisOutsideMemberFunctionBody(BaseType) &&
6433 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6434 return ExprError();
6435
6436 // C++ [basic.lookup.classref]p2:
6437 // If the id-expression in a class member access (5.2.5) is an
6438 // unqualified-id, and the type of the object expression is of a class
6439 // type C (or of pointer to a class type C), the unqualified-id is looked
6440 // up in the scope of class C. [...]
6441 ObjectType = ParsedType::make(BaseType);
6442 return Base;
6443}
6444
6445static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
6446 tok::TokenKind& OpKind, SourceLocation OpLoc) {
6447 if (Base->hasPlaceholderType()) {
6448 ExprResult result = S.CheckPlaceholderExpr(Base);
6449 if (result.isInvalid()) return true;
6450 Base = result.get();
6451 }
6452 ObjectType = Base->getType();
6453
6454 // C++ [expr.pseudo]p2:
6455 // The left-hand side of the dot operator shall be of scalar type. The
6456 // left-hand side of the arrow operator shall be of pointer to scalar type.
6457 // This scalar type is the object type.
6458 // Note that this is rather different from the normal handling for the
6459 // arrow operator.
6460 if (OpKind == tok::arrow) {
6461 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6462 ObjectType = Ptr->getPointeeType();
6463 } else if (!Base->isTypeDependent()) {
6464 // The user wrote "p->" when they probably meant "p."; fix it.
6465 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6466 << ObjectType << true
6467 << FixItHint::CreateReplacement(OpLoc, ".");
6468 if (S.isSFINAEContext())
6469 return true;
6470
6471 OpKind = tok::period;
6472 }
6473 }
6474
6475 return false;
6476}
6477
6478/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6479/// pointer objects.
6480static bool
6481canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6482 QualType DestructedType) {
6483 // If this is a record type, check if its destructor is callable.
6484 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6485 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6486 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6487 return false;
6488 }
6489
6490 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6491 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6492 DestructedType->isVectorType();
6493}
6494
6495ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
6496 SourceLocation OpLoc,
6497 tok::TokenKind OpKind,
6498 const CXXScopeSpec &SS,
6499 TypeSourceInfo *ScopeTypeInfo,
6500 SourceLocation CCLoc,
6501 SourceLocation TildeLoc,
6502 PseudoDestructorTypeStorage Destructed) {
6503 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6504
6505 QualType ObjectType;
6506 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6507 return ExprError();
6508
6509 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6510 !ObjectType->isVectorType()) {
6511 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6512 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6513 else {
6514 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6515 << ObjectType << Base->getSourceRange();
6516 return ExprError();
6517 }
6518 }
6519
6520 // C++ [expr.pseudo]p2:
6521 // [...] The cv-unqualified versions of the object type and of the type
6522 // designated by the pseudo-destructor-name shall be the same type.
6523 if (DestructedTypeInfo) {
6524 QualType DestructedType = DestructedTypeInfo->getType();
6525 SourceLocation DestructedTypeStart
6526 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6527 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6528 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6529 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6530 // Foo *foo;
6531 // foo.~Foo();
6532 if (OpKind == tok::period && ObjectType->isPointerType() &&
6533 Context.hasSameUnqualifiedType(DestructedType,
6534 ObjectType->getPointeeType())) {
6535 auto Diagnostic =
6536 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6537 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
6538
6539 // Issue a fixit only when the destructor is valid.
6540 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6541 *this, DestructedType))
6542 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6543
6544 // Recover by setting the object type to the destructed type and the
6545 // operator to '->'.
6546 ObjectType = DestructedType;
6547 OpKind = tok::arrow;
6548 } else {
6549 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6550 << ObjectType << DestructedType << Base->getSourceRange()
6551 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6552
6553 // Recover by setting the destructed type to the object type.
6554 DestructedType = ObjectType;
6555 DestructedTypeInfo =
6556 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6557 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6558 }
6559 } else if (DestructedType.getObjCLifetime() !=
6560 ObjectType.getObjCLifetime()) {
6561
6562 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6563 // Okay: just pretend that the user provided the correctly-qualified
6564 // type.
6565 } else {
6566 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6567 << ObjectType << DestructedType << Base->getSourceRange()
6568 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6569 }
6570
6571 // Recover by setting the destructed type to the object type.
6572 DestructedType = ObjectType;
6573 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6574 DestructedTypeStart);
6575 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6576 }
6577 }
6578 }
6579
6580 // C++ [expr.pseudo]p2:
6581 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6582 // form
6583 //
6584 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6585 //
6586 // shall designate the same scalar type.
6587 if (ScopeTypeInfo) {
6588 QualType ScopeType = ScopeTypeInfo->getType();
6589 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6590 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6591
6592 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6593 diag::err_pseudo_dtor_type_mismatch)
6594 << ObjectType << ScopeType << Base->getSourceRange()
6595 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6596
6597 ScopeType = QualType();
6598 ScopeTypeInfo = nullptr;
6599 }
6600 }
6601
6602 Expr *Result
6603 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6604 OpKind == tok::arrow, OpLoc,
6605 SS.getWithLocInContext(Context),
6606 ScopeTypeInfo,
6607 CCLoc,
6608 TildeLoc,
6609 Destructed);
6610
6611 return Result;
6612}
6613
6614ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6615 SourceLocation OpLoc,
6616 tok::TokenKind OpKind,
6617 CXXScopeSpec &SS,
6618 UnqualifiedId &FirstTypeName,
6619 SourceLocation CCLoc,
6620 SourceLocation TildeLoc,
6621 UnqualifiedId &SecondTypeName) {
6622 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||(((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
"Invalid first type name in pseudo-destructor") ? static_cast
<void> (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6624, __PRETTY_FUNCTION__))
6623 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&(((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
"Invalid first type name in pseudo-destructor") ? static_cast
<void> (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6624, __PRETTY_FUNCTION__))
6624 "Invalid first type name in pseudo-destructor")(((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
"Invalid first type name in pseudo-destructor") ? static_cast
<void> (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6624, __PRETTY_FUNCTION__))
;
6625 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||(((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
"Invalid second type name in pseudo-destructor") ? static_cast
<void> (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6627, __PRETTY_FUNCTION__))
6626 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&(((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
"Invalid second type name in pseudo-destructor") ? static_cast
<void> (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6627, __PRETTY_FUNCTION__))
6627 "Invalid second type name in pseudo-destructor")(((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
"Invalid second type name in pseudo-destructor") ? static_cast
<void> (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6627, __PRETTY_FUNCTION__))
;
6628
6629 QualType ObjectType;
6630 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6631 return ExprError();
6632
6633 // Compute the object type that we should use for name lookup purposes. Only
6634 // record types and dependent types matter.
6635 ParsedType ObjectTypePtrForLookup;
6636 if (!SS.isSet()) {
6637 if (ObjectType->isRecordType())
6638 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
6639 else if (ObjectType->isDependentType())
6640 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
6641 }
6642
6643 // Convert the name of the type being destructed (following the ~) into a
6644 // type (with source-location information).
6645 QualType DestructedType;
6646 TypeSourceInfo *DestructedTypeInfo = nullptr;
6647 PseudoDestructorTypeStorage Destructed;
6648 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6649 ParsedType T = getTypeName(*SecondTypeName.Identifier,
6650 SecondTypeName.StartLocation,
6651 S, &SS, true, false, ObjectTypePtrForLookup,
6652 /*IsCtorOrDtorName*/true);
6653 if (!T &&
6654 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6655 (!SS.isSet() && ObjectType->isDependentType()))) {
6656 // The name of the type being destroyed is a dependent name, and we
6657 // couldn't find anything useful in scope. Just store the identifier and
6658 // it's location, and we'll perform (qualified) name lookup again at
6659 // template instantiation time.
6660 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6661 SecondTypeName.StartLocation);
6662 } else if (!T) {
6663 Diag(SecondTypeName.StartLocation,
6664 diag::err_pseudo_dtor_destructor_non_type)
6665 << SecondTypeName.Identifier << ObjectType;
6666 if (isSFINAEContext())
6667 return ExprError();
6668
6669 // Recover by assuming we had the right type all along.
6670 DestructedType = ObjectType;
6671 } else
6672 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
6673 } else {
6674 // Resolve the template-id to a type.
6675 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
6676 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6677 TemplateId->NumArgs);
6678 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6679 TemplateId->TemplateKWLoc,
6680 TemplateId->Template,
6681 TemplateId->Name,
6682 TemplateId->TemplateNameLoc,
6683 TemplateId->LAngleLoc,
6684 TemplateArgsPtr,
6685 TemplateId->RAngleLoc,
6686 /*IsCtorOrDtorName*/true);
6687 if (T.isInvalid() || !T.get()) {
6688 // Recover by assuming we had the right type all along.
6689 DestructedType = ObjectType;
6690 } else
6691 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
6692 }
6693
6694 // If we've performed some kind of recovery, (re-)build the type source
6695 // information.
6696 if (!DestructedType.isNull()) {
6697 if (!DestructedTypeInfo)
6698 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
6699 SecondTypeName.StartLocation);
6700 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6701 }
6702
6703 // Convert the name of the scope type (the type prior to '::') into a type.
6704 TypeSourceInfo *ScopeTypeInfo = nullptr;
6705 QualType ScopeType;
6706 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6707 FirstTypeName.Identifier) {
6708 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6709 ParsedType T = getTypeName(*FirstTypeName.Identifier,
6710 FirstTypeName.StartLocation,
6711 S, &SS, true, false, ObjectTypePtrForLookup,
6712 /*IsCtorOrDtorName*/true);
6713 if (!T) {
6714 Diag(FirstTypeName.StartLocation,
6715 diag::err_pseudo_dtor_destructor_non_type)
6716 << FirstTypeName.Identifier << ObjectType;
6717
6718 if (isSFINAEContext())
6719 return ExprError();
6720
6721 // Just drop this type. It's unnecessary anyway.
6722 ScopeType = QualType();
6723 } else
6724 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
6725 } else {
6726 // Resolve the template-id to a type.
6727 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
6728 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6729 TemplateId->NumArgs);
6730 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6731 TemplateId->TemplateKWLoc,
6732 TemplateId->Template,
6733 TemplateId->Name,
6734 TemplateId->TemplateNameLoc,
6735 TemplateId->LAngleLoc,
6736 TemplateArgsPtr,
6737 TemplateId->RAngleLoc,
6738 /*IsCtorOrDtorName*/true);
6739 if (T.isInvalid() || !T.get()) {
6740 // Recover by dropping this type.
6741 ScopeType = QualType();
6742 } else
6743 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
6744 }
6745 }
6746
6747 if (!ScopeType.isNull() && !ScopeTypeInfo)
6748 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6749 FirstTypeName.StartLocation);
6750
6751
6752 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
6753 ScopeTypeInfo, CCLoc, TildeLoc,
6754 Destructed);
6755}
6756
6757ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6758 SourceLocation OpLoc,
6759 tok::TokenKind OpKind,
6760 SourceLocation TildeLoc,
6761 const DeclSpec& DS) {
6762 QualType ObjectType;
6763 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6764 return ExprError();
6765
6766 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6767 false);
6768
6769 TypeLocBuilder TLB;
6770 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6771 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6772 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6773 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6774
6775 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
6776 nullptr, SourceLocation(), TildeLoc,
6777 Destructed);
6778}
6779
6780ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
6781 CXXConversionDecl *Method,
6782 bool HadMultipleCandidates) {
6783 if (Method->getParent()->isLambda() &&
6784 Method->getConversionType()->isBlockPointerType()) {
6785 // This is a lambda coversion to block pointer; check if the argument
6786 // is a LambdaExpr.
6787 Expr *SubE = E;
6788 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6789 if (CE && CE->getCastKind() == CK_NoOp)
6790 SubE = CE->getSubExpr();
6791 SubE = SubE->IgnoreParens();
6792 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6793 SubE = BE->getSubExpr();
6794 if (isa<LambdaExpr>(SubE)) {
6795 // For the conversion to block pointer on a lambda expression, we
6796 // construct a special BlockLiteral instead; this doesn't really make
6797 // a difference in ARC, but outside of ARC the resulting block literal
6798 // follows the normal lifetime rules for block literals instead of being
6799 // autoreleased.
6800 DiagnosticErrorTrap Trap(Diags);
6801 PushExpressionEvaluationContext(
6802 ExpressionEvaluationContext::PotentiallyEvaluated);
6803 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6804 E->getExprLoc(),
6805 Method, E);
6806 PopExpressionEvaluationContext();
6807
6808 if (Exp.isInvalid())
6809 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6810 return Exp;
6811 }
6812 }
6813
6814 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
6815 FoundDecl, Method);
6816 if (Exp.isInvalid())
6817 return true;
6818
6819 MemberExpr *ME = new (Context) MemberExpr(
6820 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6821 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
6822 if (HadMultipleCandidates)
6823 ME->setHadMultipleCandidates(true);
6824 MarkMemberReferenced(ME);
6825
6826 QualType ResultType = Method->getReturnType();
6827 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6828 ResultType = ResultType.getNonLValueExprType(Context);
6829
6830 CXXMemberCallExpr *CE =
6831 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
6832 Exp.get()->getLocEnd());
6833
6834 if (CheckFunctionCall(Method, CE,
6835 Method->getType()->castAs<FunctionProtoType>()))
6836 return ExprError();
6837
6838 return CE;
6839}
6840
6841ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6842 SourceLocation RParen) {
6843 // If the operand is an unresolved lookup expression, the expression is ill-
6844 // formed per [over.over]p1, because overloaded function names cannot be used
6845 // without arguments except in explicit contexts.
6846 ExprResult R = CheckPlaceholderExpr(Operand);
6847 if (R.isInvalid())
6848 return R;
6849
6850 // The operand may have been modified when checking the placeholder type.
6851 Operand = R.get();
6852
6853 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
6854 // The expression operand for noexcept is in an unevaluated expression
6855 // context, so side effects could result in unintended consequences.
6856 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6857 }
6858
6859 CanThrowResult CanThrow = canThrow(Operand);
6860 return new (Context)
6861 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
6862}
6863
6864ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6865 Expr *Operand, SourceLocation RParen) {
6866 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
6867}
6868
6869static bool IsSpecialDiscardedValue(Expr *E) {
6870 // In C++11, discarded-value expressions of a certain form are special,
6871 // according to [expr]p10:
6872 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6873 // expression is an lvalue of volatile-qualified type and it has
6874 // one of the following forms:
6875 E = E->IgnoreParens();
6876
6877 // - id-expression (5.1.1),
6878 if (isa<DeclRefExpr>(E))
6879 return true;
6880
6881 // - subscripting (5.2.1),
6882 if (isa<ArraySubscriptExpr>(E))
6883 return true;
6884
6885 // - class member access (5.2.5),
6886 if (isa<MemberExpr>(E))
6887 return true;
6888
6889 // - indirection (5.3.1),
6890 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6891 if (UO->getOpcode() == UO_Deref)
6892 return true;
6893
6894 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6895 // - pointer-to-member operation (5.5),
6896 if (BO->isPtrMemOp())
6897 return true;
6898
6899 // - comma expression (5.18) where the right operand is one of the above.
6900 if (BO->getOpcode() == BO_Comma)
6901 return IsSpecialDiscardedValue(BO->getRHS());
6902 }
6903
6904 // - conditional expression (5.16) where both the second and the third
6905 // operands are one of the above, or
6906 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6907 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6908 IsSpecialDiscardedValue(CO->getFalseExpr());
6909 // The related edge case of "*x ?: *x".
6910 if (BinaryConditionalOperator *BCO =
6911 dyn_cast<BinaryConditionalOperator>(E)) {
6912 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6913 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6914 IsSpecialDiscardedValue(BCO->getFalseExpr());
6915 }
6916
6917 // Objective-C++ extensions to the rule.
6918 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6919 return true;
6920
6921 return false;
6922}
6923
6924/// Perform the conversions required for an expression used in a
6925/// context that ignores the result.
6926ExprResult Sema::IgnoredValueConversions(Expr *E) {
6927 if (E->hasPlaceholderType()) {
6928 ExprResult result = CheckPlaceholderExpr(E);
6929 if (result.isInvalid()) return E;
6930 E = result.get();
6931 }
6932
6933 // C99 6.3.2.1:
6934 // [Except in specific positions,] an lvalue that does not have
6935 // array type is converted to the value stored in the
6936 // designated object (and is no longer an lvalue).
6937 if (E->isRValue()) {
6938 // In C, function designators (i.e. expressions of function type)
6939 // are r-values, but we still want to do function-to-pointer decay
6940 // on them. This is both technically correct and convenient for
6941 // some clients.
6942 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
6943 return DefaultFunctionArrayConversion(E);
6944
6945 return E;
6946 }
6947
6948 if (getLangOpts().CPlusPlus) {
6949 // The C++11 standard defines the notion of a discarded-value expression;
6950 // normally, we don't need to do anything to handle it, but if it is a
6951 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6952 // conversion.
6953 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
6954 E->getType().isVolatileQualified() &&
6955 IsSpecialDiscardedValue(E)) {
6956 ExprResult Res = DefaultLvalueConversion(E);
6957 if (Res.isInvalid())
6958 return E;
6959 E = Res.get();
6960 }
6961
6962 // C++1z:
6963 // If the expression is a prvalue after this optional conversion, the
6964 // temporary materialization conversion is applied.
6965 //
6966 // We skip this step: IR generation is able to synthesize the storage for
6967 // itself in the aggregate case, and adding the extra node to the AST is
6968 // just clutter.
6969 // FIXME: We don't emit lifetime markers for the temporaries due to this.
6970 // FIXME: Do any other AST consumers care about this?
6971 return E;
6972 }
6973
6974 // GCC seems to also exclude expressions of incomplete enum type.
6975 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6976 if (!T->getDecl()->isComplete()) {
6977 // FIXME: stupid workaround for a codegen bug!
6978 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
6979 return E;
6980 }
6981 }
6982
6983 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6984 if (Res.isInvalid())
6985 return E;
6986 E = Res.get();
6987
6988 if (!E->getType()->isVoidType())
6989 RequireCompleteType(E->getExprLoc(), E->getType(),
6990 diag::err_incomplete_type);
6991 return E;
6992}
6993
6994// If we can unambiguously determine whether Var can never be used
6995// in a constant expression, return true.
6996// - if the variable and its initializer are non-dependent, then
6997// we can unambiguously check if the variable is a constant expression.
6998// - if the initializer is not value dependent - we can determine whether
6999// it can be used to initialize a constant expression. If Init can not
7000// be used to initialize a constant expression we conclude that Var can
7001// never be a constant expression.
7002// - FXIME: if the initializer is dependent, we can still do some analysis and
7003// identify certain cases unambiguously as non-const by using a Visitor:
7004// - such as those that involve odr-use of a ParmVarDecl, involve a new
7005// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7006static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
7007 ASTContext &Context) {
7008 if (isa<ParmVarDecl>(Var)) return true;
7009 const VarDecl *DefVD = nullptr;
7010
7011 // If there is no initializer - this can not be a constant expression.
7012 if (!Var->getAnyInitializer(DefVD)) return true;
7013 assert(DefVD)((DefVD) ? static_cast<void> (0) : __assert_fail ("DefVD"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7013, __PRETTY_FUNCTION__))
;
7014 if (DefVD->isWeak()) return false;
7015 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7016
7017 Expr *Init = cast<Expr>(Eval->Value);
7018
7019 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7020 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7021 // of value-dependent expressions, and use it here to determine whether the
7022 // initializer is a potential constant expression.
7023 return false;
7024 }
7025
7026 return !IsVariableAConstantExpression(Var, Context);
7027}
7028
7029/// \brief Check if the current lambda has any potential captures
7030/// that must be captured by any of its enclosing lambdas that are ready to
7031/// capture. If there is a lambda that can capture a nested
7032/// potential-capture, go ahead and do so. Also, check to see if any
7033/// variables are uncaptureable or do not involve an odr-use so do not
7034/// need to be captured.
7035
7036static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7037 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7038
7039 assert(!S.isUnevaluatedContext())((!S.isUnevaluatedContext()) ? static_cast<void> (0) : __assert_fail
("!S.isUnevaluatedContext()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7039, __PRETTY_FUNCTION__))
;
7040 assert(S.CurContext->isDependentContext())((S.CurContext->isDependentContext()) ? static_cast<void
> (0) : __assert_fail ("S.CurContext->isDependentContext()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7040, __PRETTY_FUNCTION__))
;
7041#ifndef NDEBUG
7042 DeclContext *DC = S.CurContext;
7043 while (DC && isa<CapturedDecl>(DC))
7044 DC = DC->getParent();
7045 assert(((CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext"
) ? static_cast<void> (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7047, __PRETTY_FUNCTION__))
7046 CurrentLSI->CallOperator == DC &&((CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext"
) ? static_cast<void> (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7047, __PRETTY_FUNCTION__))
7047 "The current call operator must be synchronized with Sema's CurContext")((CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext"
) ? static_cast<void> (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7047, __PRETTY_FUNCTION__))
;
7048#endif // NDEBUG
7049
7050 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7051
7052 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
7053 S.FunctionScopes.data(), S.FunctionScopes.size());
7054
7055 // All the potentially captureable variables in the current nested
7056 // lambda (within a generic outer lambda), must be captured by an
7057 // outer lambda that is enclosed within a non-dependent context.
7058 const unsigned NumPotentialCaptures =
7059 CurrentLSI->getNumPotentialVariableCaptures();
7060 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
7061 Expr *VarExpr = nullptr;
7062 VarDecl *Var = nullptr;
7063 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
7064 // If the variable is clearly identified as non-odr-used and the full
7065 // expression is not instantiation dependent, only then do we not
7066 // need to check enclosing lambda's for speculative captures.
7067 // For e.g.:
7068 // Even though 'x' is not odr-used, it should be captured.
7069 // int test() {
7070 // const int x = 10;
7071 // auto L = [=](auto a) {
7072 // (void) +x + a;
7073 // };
7074 // }
7075 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7076 !IsFullExprInstantiationDependent)
7077 continue;
7078
7079 // If we have a capture-capable lambda for the variable, go ahead and
7080 // capture the variable in that lambda (and all its enclosing lambdas).
7081 if (const Optional<unsigned> Index =
7082 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7083 FunctionScopesArrayRef, Var, S)) {
7084 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7085 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7086 &FunctionScopeIndexOfCapturableLambda);
7087 }
7088 const bool IsVarNeverAConstantExpression =
7089 VariableCanNeverBeAConstantExpression(Var, S.Context);
7090 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7091 // This full expression is not instantiation dependent or the variable
7092 // can not be used in a constant expression - which means
7093 // this variable must be odr-used here, so diagnose a
7094 // capture violation early, if the variable is un-captureable.
7095 // This is purely for diagnosing errors early. Otherwise, this
7096 // error would get diagnosed when the lambda becomes capture ready.
7097 QualType CaptureType, DeclRefType;
7098 SourceLocation ExprLoc = VarExpr->getExprLoc();
7099 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7100 /*EllipsisLoc*/ SourceLocation(),
7101 /*BuildAndDiagnose*/false, CaptureType,
7102 DeclRefType, nullptr)) {
7103 // We will never be able to capture this variable, and we need
7104 // to be able to in any and all instantiations, so diagnose it.
7105 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7106 /*EllipsisLoc*/ SourceLocation(),
7107 /*BuildAndDiagnose*/true, CaptureType,
7108 DeclRefType, nullptr);
7109 }
7110 }
7111 }
7112
7113 // Check if 'this' needs to be captured.
7114 if (CurrentLSI->hasPotentialThisCapture()) {
7115 // If we have a capture-capable lambda for 'this', go ahead and capture
7116 // 'this' in that lambda (and all its enclosing lambdas).
7117 if (const Optional<unsigned> Index =
7118 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7119 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
7120 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7121 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7122 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7123 &FunctionScopeIndexOfCapturableLambda);
7124 }
7125 }
7126
7127 // Reset all the potential captures at the end of each full-expression.
7128 CurrentLSI->clearPotentialCaptures();
7129}
7130
7131static ExprResult attemptRecovery(Sema &SemaRef,
7132 const TypoCorrectionConsumer &Consumer,
7133 const TypoCorrection &TC) {
7134 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7135 Consumer.getLookupResult().getLookupKind());
7136 const CXXScopeSpec *SS = Consumer.getSS();
7137 CXXScopeSpec NewSS;
7138
7139 // Use an approprate CXXScopeSpec for building the expr.
7140 if (auto *NNS = TC.getCorrectionSpecifier())
7141 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7142 else if (SS && !TC.WillReplaceSpecifier())
7143 NewSS = *SS;
7144
7145 if (auto *ND = TC.getFoundDecl()) {
7146 R.setLookupName(ND->getDeclName());
7147 R.addDecl(ND);
7148 if (ND->isCXXClassMember()) {
7149 // Figure out the correct naming class to add to the LookupResult.
7150 CXXRecordDecl *Record = nullptr;
7151 if (auto *NNS = TC.getCorrectionSpecifier())
7152 Record = NNS->getAsType()->getAsCXXRecordDecl();
7153 if (!Record)
7154 Record =
7155 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7156 if (Record)
7157 R.setNamingClass(Record);
7158
7159 // Detect and handle the case where the decl might be an implicit
7160 // member.
7161 bool MightBeImplicitMember;
7162 if (!Consumer.isAddressOfOperand())
7163 MightBeImplicitMember = true;
7164 else if (!NewSS.isEmpty())
7165 MightBeImplicitMember = false;
7166 else if (R.isOverloadedResult())
7167 MightBeImplicitMember = false;
7168 else if (R.isUnresolvableResult())
7169 MightBeImplicitMember = true;
7170 else
7171 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7172 isa<IndirectFieldDecl>(ND) ||
7173 isa<MSPropertyDecl>(ND);
7174
7175 if (MightBeImplicitMember)
7176 return SemaRef.BuildPossibleImplicitMemberExpr(
7177 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7178 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7179 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7180 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7181 Ivar->getIdentifier());
7182 }
7183 }
7184
7185 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7186 /*AcceptInvalidDecl*/ true);
7187}
7188
7189namespace {
7190class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7191 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7192
7193public:
7194 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7195 : TypoExprs(TypoExprs) {}
7196 bool VisitTypoExpr(TypoExpr *TE) {
7197 TypoExprs.insert(TE);
7198 return true;
7199 }
7200};
7201
7202class TransformTypos : public TreeTransform<TransformTypos> {
7203 typedef TreeTransform<TransformTypos> BaseTransform;
7204
7205 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7206 // process of being initialized.
7207 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7208 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7209 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7210 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7211
7212 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7213 /// If the TypoExprs were successfully corrected, then the diagnostics should
7214 /// suggest the corrections. Otherwise the diagnostics will not suggest
7215 /// anything (having been passed an empty TypoCorrection).
7216 void EmitAllDiagnostics() {
7217 for (auto E : TypoExprs) {
7218 TypoExpr *TE = cast<TypoExpr>(E);
7219 auto &State = SemaRef.getTypoExprState(TE);
7220 if (State.DiagHandler) {
7221 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7222 ExprResult Replacement = TransformCache[TE];
7223
7224 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7225 // TypoCorrection, replacing the existing decls. This ensures the right
7226 // NamedDecl is used in diagnostics e.g. in the case where overload
7227 // resolution was used to select one from several possible decls that
7228 // had been stored in the TypoCorrection.
7229 if (auto *ND = getDeclFromExpr(
7230 Replacement.isInvalid() ? nullptr : Replacement.get()))
7231 TC.setCorrectionDecl(ND);
7232
7233 State.DiagHandler(TC);
7234 }
7235 SemaRef.clearDelayedTypo(TE);
7236 }
7237 }
7238
7239 /// \brief If corrections for the first TypoExpr have been exhausted for a
7240 /// given combination of the other TypoExprs, retry those corrections against
7241 /// the next combination of substitutions for the other TypoExprs by advancing
7242 /// to the next potential correction of the second TypoExpr. For the second
7243 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7244 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7245 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7246 /// TransformCache). Returns true if there is still any untried combinations
7247 /// of corrections.
7248 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7249 for (auto TE : TypoExprs) {
7250 auto &State = SemaRef.getTypoExprState(TE);
7251 TransformCache.erase(TE);
7252 if (!State.Consumer->finished())
7253 return true;
7254 State.Consumer->resetCorrectionStream();
7255 }
7256 return false;
7257 }
7258
7259 NamedDecl *getDeclFromExpr(Expr *E) {
7260 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7261 E = OverloadResolution[OE];
7262
7263 if (!E)
7264 return nullptr;
7265 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
7266 return DRE->getFoundDecl();
7267 if (auto *ME = dyn_cast<MemberExpr>(E))
7268 return ME->getFoundDecl();
7269 // FIXME: Add any other expr types that could be be seen by the delayed typo
7270 // correction TreeTransform for which the corresponding TypoCorrection could
7271 // contain multiple decls.
7272 return nullptr;
7273 }
7274
7275 ExprResult TryTransform(Expr *E) {
7276 Sema::SFINAETrap Trap(SemaRef);
7277 ExprResult Res = TransformExpr(E);
7278 if (Trap.hasErrorOccurred() || Res.isInvalid())
7279 return ExprError();
7280
7281 return ExprFilter(Res.get());
7282 }
7283
7284public:
7285 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7286 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
7287
7288 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7289 MultiExprArg Args,
7290 SourceLocation RParenLoc,
7291 Expr *ExecConfig = nullptr) {
7292 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7293 RParenLoc, ExecConfig);
7294 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
7295 if (Result.isUsable()) {
7296 Expr *ResultCall = Result.get();
7297 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7298 ResultCall = BE->getSubExpr();
7299 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7300 OverloadResolution[OE] = CE->getCallee();
7301 }
7302 }
7303 return Result;
7304 }
7305
7306 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7307
7308 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7309
7310 ExprResult Transform(Expr *E) {
7311 ExprResult Res;
7312 while (true) {
7313 Res = TryTransform(E);
7314
7315 // Exit if either the transform was valid or if there were no TypoExprs
7316 // to transform that still have any untried correction candidates..
7317 if (!Res.isInvalid() ||
7318 !CheckAndAdvanceTypoExprCorrectionStreams())
7319 break;
7320 }
7321
7322 // Ensure none of the TypoExprs have multiple typo correction candidates
7323 // with the same edit length that pass all the checks and filters.
7324 // TODO: Properly handle various permutations of possible corrections when
7325 // there is more than one potentially ambiguous typo correction.
7326 // Also, disable typo correction while attempting the transform when
7327 // handling potentially ambiguous typo corrections as any new TypoExprs will
7328 // have been introduced by the application of one of the correction
7329 // candidates and add little to no value if corrected.
7330 SemaRef.DisableTypoCorrection = true;
7331 while (!AmbiguousTypoExprs.empty()) {
7332 auto TE = AmbiguousTypoExprs.back();
7333 auto Cached = TransformCache[TE];
7334 auto &State = SemaRef.getTypoExprState(TE);
7335 State.Consumer->saveCurrentPosition();
7336 TransformCache.erase(TE);
7337 if (!TryTransform(E).isInvalid()) {
7338 State.Consumer->resetCorrectionStream();
7339 TransformCache.erase(TE);
7340 Res = ExprError();
7341 break;
7342 }
7343 AmbiguousTypoExprs.remove(TE);
7344 State.Consumer->restoreSavedPosition();
7345 TransformCache[TE] = Cached;
7346 }
7347 SemaRef.DisableTypoCorrection = false;
7348
7349 // Ensure that all of the TypoExprs within the current Expr have been found.
7350 if (!Res.isUsable())
7351 FindTypoExprs(TypoExprs).TraverseStmt(E);
7352
7353 EmitAllDiagnostics();
7354
7355 return Res;
7356 }
7357
7358 ExprResult TransformTypoExpr(TypoExpr *E) {
7359 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7360 // cached transformation result if there is one and the TypoExpr isn't the
7361 // first one that was encountered.
7362 auto &CacheEntry = TransformCache[E];
7363 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7364 return CacheEntry;
7365 }
7366
7367 auto &State = SemaRef.getTypoExprState(E);
7368 assert(State.Consumer && "Cannot transform a cleared TypoExpr")((State.Consumer && "Cannot transform a cleared TypoExpr"
) ? static_cast<void> (0) : __assert_fail ("State.Consumer && \"Cannot transform a cleared TypoExpr\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7368, __PRETTY_FUNCTION__))
;
7369
7370 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7371 // typo correction and return it.
7372 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
7373 if (InitDecl && TC.getFoundDecl() == InitDecl)
7374 continue;
7375 // FIXME: If we would typo-correct to an invalid declaration, it's
7376 // probably best to just suppress all errors from this typo correction.
7377 ExprResult NE = State.RecoveryHandler ?
7378 State.RecoveryHandler(SemaRef, E, TC) :
7379 attemptRecovery(SemaRef, *State.Consumer, TC);
7380 if (!NE.isInvalid()) {
7381 // Check whether there may be a second viable correction with the same
7382 // edit distance; if so, remember this TypoExpr may have an ambiguous
7383 // correction so it can be more thoroughly vetted later.
7384 TypoCorrection Next;
7385 if ((Next = State.Consumer->peekNextCorrection()) &&
7386 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7387 AmbiguousTypoExprs.insert(E);
7388 } else {
7389 AmbiguousTypoExprs.remove(E);
7390 }
7391 assert(!NE.isUnset() &&((!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult"
) ? static_cast<void> (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7392, __PRETTY_FUNCTION__))
7392 "Typo was transformed into a valid-but-null ExprResult")((!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult"
) ? static_cast<void> (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7392, __PRETTY_FUNCTION__))
;
7393 return CacheEntry = NE;
7394 }
7395 }
7396 return CacheEntry = ExprError();
7397 }
7398};
7399}
7400
7401ExprResult
7402Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7403 llvm::function_ref<ExprResult(Expr *)> Filter) {
7404 // If the current evaluation context indicates there are uncorrected typos
7405 // and the current expression isn't guaranteed to not have typos, try to
7406 // resolve any TypoExpr nodes that might be in the expression.
7407 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
7408 (E->isTypeDependent() || E->isValueDependent() ||
7409 E->isInstantiationDependent())) {
7410 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7411 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr")((TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr"
) ? static_cast<void> (0) : __assert_fail ("TyposInContext < ~0U && \"Recursive call of CorrectDelayedTyposInExpr\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7411, __PRETTY_FUNCTION__))
;
7412 ExprEvalContexts.back().NumTypos = ~0U;
7413 auto TyposResolved = DelayedTypos.size();
7414 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
7415 ExprEvalContexts.back().NumTypos = TyposInContext;
7416 TyposResolved -= DelayedTypos.size();
7417 if (Result.isInvalid() || Result.get() != E) {
7418 ExprEvalContexts.back().NumTypos -= TyposResolved;
7419 return Result;
7420 }
7421 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?")((TyposResolved == 0 && "Corrected typo but got same Expr back?"
) ? static_cast<void> (0) : __assert_fail ("TyposResolved == 0 && \"Corrected typo but got same Expr back?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7421, __PRETTY_FUNCTION__))
;
7422 }
7423 return E;
7424}
7425
7426ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
7427 bool DiscardedValue,
7428 bool IsConstexpr,
7429 bool IsLambdaInitCaptureInitializer) {
7430 ExprResult FullExpr = FE;
7431
7432 if (!FullExpr.get())
7433 return ExprError();
7434
7435 // If we are an init-expression in a lambdas init-capture, we should not
7436 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
7437 // containing full-expression is done).
7438 // template<class ... Ts> void test(Ts ... t) {
7439 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7440 // return a;
7441 // }() ...);
7442 // }
7443 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7444 // when we parse the lambda introducer, and teach capturing (but not
7445 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7446 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7447 // lambda where we've entered the introducer but not the body, or represent a
7448 // lambda where we've entered the body, depending on where the
7449 // parser/instantiation has got to).
7450 if (!IsLambdaInitCaptureInitializer &&
7451 DiagnoseUnexpandedParameterPack(FullExpr.get()))
7452 return ExprError();
7453
7454 // Top-level expressions default to 'id' when we're in a debugger.
7455 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
7456 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7457 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7458 if (FullExpr.isInvalid())
7459 return ExprError();
7460 }
7461
7462 if (DiscardedValue) {
7463 FullExpr = CheckPlaceholderExpr(FullExpr.get());
7464 if (FullExpr.isInvalid())
7465 return ExprError();
7466
7467 FullExpr = IgnoredValueConversions(FullExpr.get());
7468 if (FullExpr.isInvalid())
7469 return ExprError();
7470 }
7471
7472 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7473 if (FullExpr.isInvalid())
7474 return ExprError();
7475
7476 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7477
7478 // At the end of this full expression (which could be a deeply nested
7479 // lambda), if there is a potential capture within the nested lambda,
7480 // have the outer capture-able lambda try and capture it.
7481 // Consider the following code:
7482 // void f(int, int);
7483 // void f(const int&, double);
7484 // void foo() {
7485 // const int x = 10, y = 20;
7486 // auto L = [=](auto a) {
7487 // auto M = [=](auto b) {
7488 // f(x, b); <-- requires x to be captured by L and M
7489 // f(y, a); <-- requires y to be captured by L, but not all Ms
7490 // };
7491 // };
7492 // }
7493
7494 // FIXME: Also consider what happens for something like this that involves
7495 // the gnu-extension statement-expressions or even lambda-init-captures:
7496 // void f() {
7497 // const int n = 0;
7498 // auto L = [&](auto a) {
7499 // +n + ({ 0; a; });
7500 // };
7501 // }
7502 //
7503 // Here, we see +n, and then the full-expression 0; ends, so we don't
7504 // capture n (and instead remove it from our list of potential captures),
7505 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7506 // for us to see that we need to capture n after all.
7507
7508 LambdaScopeInfo *const CurrentLSI =
7509 getCurLambda(/*IgnoreCapturedRegions=*/true);
7510 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7511 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7512 // for an example of the code that might cause this asynchrony.
7513 // By ensuring we are in the context of a lambda's call operator
7514 // we can fix the bug (we only need to check whether we need to capture
7515 // if we are within a lambda's body); but per the comments in that
7516 // PR, a proper fix would entail :
7517 // "Alternative suggestion:
7518 // - Add to Sema an integer holding the smallest (outermost) scope
7519 // index that we are *lexically* within, and save/restore/set to
7520 // FunctionScopes.size() in InstantiatingTemplate's
7521 // constructor/destructor.
7522 // - Teach the handful of places that iterate over FunctionScopes to
7523 // stop at the outermost enclosing lexical scope."
7524 DeclContext *DC = CurContext;
7525 while (DC && isa<CapturedDecl>(DC))
7526 DC = DC->getParent();
7527 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7528 if (IsInLambdaDeclContext && CurrentLSI &&
7529 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7530 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7531 *this);
7532 return MaybeCreateExprWithCleanups(FullExpr);
7533}
7534
7535StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7536 if (!FullStmt) return StmtError();
7537
7538 return MaybeCreateStmtWithCleanups(FullStmt);
7539}
7540
7541Sema::IfExistsResult
7542Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7543 CXXScopeSpec &SS,
7544 const DeclarationNameInfo &TargetNameInfo) {
7545 DeclarationName TargetName = TargetNameInfo.getName();
7546 if (!TargetName)
7547 return IER_DoesNotExist;
7548
7549 // If the name itself is dependent, then the result is dependent.
7550 if (TargetName.isDependentName())
7551 return IER_Dependent;
7552
7553 // Do the redeclaration lookup in the current scope.
7554 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7555 Sema::NotForRedeclaration);
7556 LookupParsedName(R, S, &SS);
7557 R.suppressDiagnostics();
7558
7559 switch (R.getResultKind()) {
7560 case LookupResult::Found:
7561 case LookupResult::FoundOverloaded:
7562 case LookupResult::FoundUnresolvedValue:
7563 case LookupResult::Ambiguous:
7564 return IER_Exists;
7565
7566 case LookupResult::NotFound:
7567 return IER_DoesNotExist;
7568
7569 case LookupResult::NotFoundInCurrentInstantiation:
7570 return IER_Dependent;
7571 }
7572
7573 llvm_unreachable("Invalid LookupResult Kind!")::llvm::llvm_unreachable_internal("Invalid LookupResult Kind!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7573)
;
7574}
7575
7576Sema::IfExistsResult
7577Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7578 bool IsIfExists, CXXScopeSpec &SS,
7579 UnqualifiedId &Name) {
7580 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7581
7582 // Check for an unexpanded parameter pack.
7583 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7584 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7585 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
7586 return IER_Error;
7587
7588 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7589}