1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ expressions.
12 //===----------------------------------------------------------------------===//
14 #include "SemaInherit.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/Parse/DeclSpec.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/ADT/STLExtras.h"
22 using namespace clang;
24 /// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
25 /// name (e.g., operator void const *) as an expression. This is
26 /// very similar to ActOnIdentifierExpr, except that instead of
27 /// providing an identifier the parser provides the type of the
28 /// conversion function.
29 Sema::OwningExprResult
30 Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
32 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
34 QualType ConvType = QualType::getFromOpaquePtr(Ty);
35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36 DeclarationName ConvName
37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
38 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
39 &SS, isAddressOfOperand);
42 /// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
43 /// name (e.g., @c operator+ ) as an expression. This is very
44 /// similar to ActOnIdentifierExpr, except that instead of providing
45 /// an identifier the parser provides the kind of overloaded
46 /// operator that was parsed.
47 Sema::OwningExprResult
48 Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49 OverloadedOperatorKind Op,
50 bool HasTrailingLParen,
51 const CXXScopeSpec &SS,
52 bool isAddressOfOperand) {
53 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
54 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
58 /// ActOnCXXTypeidOfType - Parse typeid( type-id ).
59 Action::OwningExprResult
60 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
62 NamespaceDecl *StdNs = GetStdNamespace();
64 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
67 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
68 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
69 if (!TypeInfoRecordDecl)
70 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
75 // C++0x [expr.typeid]p3:
76 // When typeid is applied to an expression other than an lvalue of a
77 // polymorphic class type [...] [the] expression is an unevaluated
80 // FIXME: if the type of the expression is a class type, the class
81 // shall be completely defined.
82 bool isUnevaluatedOperand = true;
83 Expr *E = static_cast<Expr *>(TyOrExpr);
84 if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
85 QualType T = E->getType();
86 if (const RecordType *RecordT = T->getAsRecordType()) {
87 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
88 if (RecordD->isPolymorphic())
89 isUnevaluatedOperand = false;
93 // If this is an unevaluated operand, clear out the set of declaration
94 // references we have been computing.
95 if (isUnevaluatedOperand)
96 PotentiallyReferencedDeclStack.back().clear();
99 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
100 TypeInfoType.withConst(),
101 SourceRange(OpLoc, RParenLoc)));
104 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
105 Action::OwningExprResult
106 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
107 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
108 "Unknown C++ Boolean value!");
109 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
110 Context.BoolTy, OpLoc));
113 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
114 Action::OwningExprResult
115 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
116 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
119 /// ActOnCXXThrow - Parse throw expressions.
120 Action::OwningExprResult
121 Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
122 Expr *Ex = E.takeAs<Expr>();
123 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
125 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
128 /// CheckCXXThrowOperand - Validate the operand of a throw.
129 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
130 // C++ [except.throw]p3:
131 // [...] adjusting the type from "array of T" or "function returning T"
132 // to "pointer to T" or "pointer to function returning T", [...]
133 DefaultFunctionArrayConversion(E);
135 // If the type of the exception would be an incomplete type or a pointer
136 // to an incomplete type other than (cv) void the program is ill-formed.
137 QualType Ty = E->getType();
139 if (const PointerType* Ptr = Ty->getAsPointerType()) {
140 Ty = Ptr->getPointeeType();
143 if (!isPointer || !Ty->isVoidType()) {
144 if (RequireCompleteType(ThrowLoc, Ty,
145 isPointer ? diag::err_throw_incomplete_ptr
146 : diag::err_throw_incomplete,
147 E->getSourceRange(), SourceRange(), QualType()))
151 // FIXME: Construct a temporary here.
155 Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
156 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
157 /// is a non-lvalue expression whose value is the address of the object for
158 /// which the function is called.
160 if (!isa<FunctionDecl>(CurContext))
161 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
163 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
164 if (MD->isInstance())
165 return Owned(new (Context) CXXThisExpr(ThisLoc,
166 MD->getThisType(Context)));
168 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
171 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
172 /// Can be interpreted either as function-style casting ("int(x)")
173 /// or class type construction ("ClassType(x,y,z)")
174 /// or creation of a value-initialized type ("int()").
175 Action::OwningExprResult
176 Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
177 SourceLocation LParenLoc,
179 SourceLocation *CommaLocs,
180 SourceLocation RParenLoc) {
181 assert(TypeRep && "Missing type!");
182 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
183 unsigned NumExprs = exprs.size();
184 Expr **Exprs = (Expr**)exprs.get();
185 SourceLocation TyBeginLoc = TypeRange.getBegin();
186 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
188 if (Ty->isDependentType() ||
189 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
192 return Owned(CXXUnresolvedConstructExpr::Create(Context,
193 TypeRange.getBegin(), Ty,
200 // C++ [expr.type.conv]p1:
201 // If the expression list is a single expression, the type conversion
202 // expression is equivalent (in definedness, and if defined in meaning) to the
203 // corresponding cast expression.
206 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
209 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
210 Ty, TyBeginLoc, Exprs[0],
214 if (const RecordType *RT = Ty->getAsRecordType()) {
215 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
217 // FIXME: We should always create a CXXTemporaryObjectExpr here unless
218 // both the ctor and dtor are trivial.
219 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
220 CXXConstructorDecl *Constructor
221 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
222 TypeRange.getBegin(),
223 SourceRange(TypeRange.getBegin(),
232 Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
233 Ty, TyBeginLoc, Exprs,
234 NumExprs, RParenLoc);
235 return MaybeBindToTemporary(E);
238 // Fall through to value-initialize an object of class type that
239 // doesn't have a user-declared default constructor.
242 // C++ [expr.type.conv]p1:
243 // If the expression list specifies more than a single value, the type shall
244 // be a class with a suitably declared constructor.
247 return ExprError(Diag(CommaLocs[0],
248 diag::err_builtin_func_cast_more_than_one_arg)
251 assert(NumExprs == 0 && "Expected 0 expressions");
253 // C++ [expr.type.conv]p2:
254 // The expression T(), where T is a simple-type-specifier for a non-array
255 // complete object type or the (possibly cv-qualified) void type, creates an
256 // rvalue of the specified type, which is value-initialized.
258 if (Ty->isArrayType())
259 return ExprError(Diag(TyBeginLoc,
260 diag::err_value_init_for_array_type) << FullRange);
261 if (!Ty->isDependentType() && !Ty->isVoidType() &&
262 RequireCompleteType(TyBeginLoc, Ty,
263 diag::err_invalid_incomplete_type_use, FullRange))
266 if (RequireNonAbstractType(TyBeginLoc, Ty,
267 diag::err_allocation_of_abstract_type))
271 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
275 /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
276 /// @code new (memory) int[size][4] @endcode
278 /// @code ::new Foo(23, "hello") @endcode
279 /// For the interpretation of this heap of arguments, consult the base version.
280 Action::OwningExprResult
281 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
282 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
283 SourceLocation PlacementRParen, bool ParenTypeId,
284 Declarator &D, SourceLocation ConstructorLParen,
285 MultiExprArg ConstructorArgs,
286 SourceLocation ConstructorRParen)
290 // If the specified type is an array, unwrap it and save the expression.
291 if (D.getNumTypeObjects() > 0 &&
292 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
293 DeclaratorChunk &Chunk = D.getTypeObject(0);
294 if (Chunk.Arr.hasStatic)
295 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
296 << D.getSourceRange());
297 if (!Chunk.Arr.NumElts)
298 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
299 << D.getSourceRange());
300 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
304 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
305 if (D.isInvalidType())
308 // Every dimension shall be of constant size.
310 QualType ElementType = AllocType;
311 while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
312 if (!Array->isConstantArrayType()) {
313 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
314 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
317 ElementType = Array->getElementType();
321 return BuildCXXNew(StartLoc, UseGlobal,
327 D.getSourceRange().getBegin(),
331 move(ConstructorArgs),
335 Sema::OwningExprResult
336 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
337 SourceLocation PlacementLParen,
338 MultiExprArg PlacementArgs,
339 SourceLocation PlacementRParen,
342 SourceLocation TypeLoc,
343 SourceRange TypeRange,
345 SourceLocation ConstructorLParen,
346 MultiExprArg ConstructorArgs,
347 SourceLocation ConstructorRParen) {
348 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
351 QualType ResultType = Context.getPointerType(AllocType);
353 // That every array dimension except the first is constant was already
354 // checked by the type check above.
356 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
357 // or enumeration type with a non-negative value."
358 Expr *ArraySize = (Expr *)ArraySizeE.get();
359 if (ArraySize && !ArraySize->isTypeDependent()) {
360 QualType SizeType = ArraySize->getType();
361 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
362 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
363 diag::err_array_size_not_integral)
364 << SizeType << ArraySize->getSourceRange());
365 // Let's see if this is a constant < 0. If so, we reject it out of hand.
366 // We don't care about special rules, so we tell the machinery it's not
367 // evaluated - it gives us a result in more cases.
368 if (!ArraySize->isValueDependent()) {
370 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
371 if (Value < llvm::APSInt(
372 llvm::APInt::getNullValue(Value.getBitWidth()), false))
373 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
374 diag::err_typecheck_negative_array_size)
375 << ArraySize->getSourceRange());
380 FunctionDecl *OperatorNew = 0;
381 FunctionDecl *OperatorDelete = 0;
382 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
383 unsigned NumPlaceArgs = PlacementArgs.size();
384 if (!AllocType->isDependentType() &&
385 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
386 FindAllocationFunctions(StartLoc,
387 SourceRange(PlacementLParen, PlacementRParen),
388 UseGlobal, AllocType, ArraySize, PlaceArgs,
389 NumPlaceArgs, OperatorNew, OperatorDelete))
392 bool Init = ConstructorLParen.isValid();
393 // --- Choosing a constructor ---
395 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
396 // the object is not initialized. If the object, or any part of it, is
397 // const-qualified, it's an error.
398 // 2) If T is a POD and there's an empty initializer, the object is value-
400 // 3) If T is a POD and there's one initializer argument, the object is copy-
402 // 4) If T is a POD and there's more initializer arguments, it's an error.
403 // 5) If T is not a POD, the initializer arguments are used as constructor
406 // Or by the C++0x formulation:
407 // 1) If there's no initializer, the object is default-initialized according
409 // 2) Otherwise, the object is direct-initialized.
410 CXXConstructorDecl *Constructor = 0;
411 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
412 const RecordType *RT;
413 unsigned NumConsArgs = ConstructorArgs.size();
414 if (AllocType->isDependentType()) {
415 // Skip all the checks.
417 else if ((RT = AllocType->getAsRecordType()) &&
418 !AllocType->isAggregateType()) {
419 Constructor = PerformInitializationByConstructor(
420 AllocType, ConsArgs, NumConsArgs,
422 SourceRange(TypeLoc, ConstructorRParen),
423 RT->getDecl()->getDeclName(),
424 NumConsArgs != 0 ? IK_Direct : IK_Default);
429 // FIXME: Check that no subpart is const.
430 if (AllocType.isConstQualified())
431 return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
433 } else if (NumConsArgs == 0) {
434 // Object is value-initialized. Do nothing.
435 } else if (NumConsArgs == 1) {
436 // Object is direct-initialized.
437 // FIXME: What DeclarationName do we pass in here?
438 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
439 DeclarationName() /*AllocType.getAsString()*/,
440 /*DirectInit=*/true))
443 return ExprError(Diag(StartLoc,
444 diag::err_builtin_direct_init_more_than_one_arg)
445 << SourceRange(ConstructorLParen, ConstructorRParen));
449 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
451 PlacementArgs.release();
452 ConstructorArgs.release();
453 ArraySizeE.release();
454 return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
455 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
456 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
457 StartLoc, Init ? ConstructorRParen : SourceLocation()));
460 /// CheckAllocatedType - Checks that a type is suitable as the allocated type
461 /// in a new-expression.
462 /// dimension off and stores the size expression in ArraySize.
463 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
466 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
467 // abstract class type or array thereof.
468 if (AllocType->isFunctionType())
469 return Diag(Loc, diag::err_bad_new_type)
470 << AllocType << 0 << R;
471 else if (AllocType->isReferenceType())
472 return Diag(Loc, diag::err_bad_new_type)
473 << AllocType << 1 << R;
474 else if (!AllocType->isDependentType() &&
475 RequireCompleteType(Loc, AllocType,
476 diag::err_new_incomplete_type,
479 else if (RequireNonAbstractType(Loc, AllocType,
480 diag::err_allocation_of_abstract_type))
486 /// FindAllocationFunctions - Finds the overloads of operator new and delete
487 /// that are appropriate for the allocation.
488 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
489 bool UseGlobal, QualType AllocType,
490 bool IsArray, Expr **PlaceArgs,
491 unsigned NumPlaceArgs,
492 FunctionDecl *&OperatorNew,
493 FunctionDecl *&OperatorDelete)
495 // --- Choosing an allocation function ---
496 // C++ 5.3.4p8 - 14 & 18
497 // 1) If UseGlobal is true, only look in the global scope. Else, also look
498 // in the scope of the allocated class.
499 // 2) If an array size is given, look for operator new[], else look for
501 // 3) The first argument is always size_t. Append the arguments from the
503 // FIXME: Also find the appropriate delete operator.
505 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
506 // We don't care about the actual value of this argument.
507 // FIXME: Should the Sema create the expression and embed it in the syntax
508 // tree? Or should the consumer just recalculate the value?
509 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
510 Context.Target.getPointerWidth(0)),
511 Context.getSizeType(),
513 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
515 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
516 IsArray ? OO_Array_New : OO_New);
517 if (AllocType->isRecordType() && !UseGlobal) {
518 CXXRecordDecl *Record
519 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
520 // FIXME: We fail to find inherited overloads.
521 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
522 AllocArgs.size(), Record, /*AllowMissing=*/true,
527 // Didn't find a member overload. Look for a global one.
528 DeclareGlobalNewDelete();
529 DeclContext *TUDecl = Context.getTranslationUnitDecl();
530 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
531 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
536 // FindAllocationOverload can change the passed in arguments, so we need to
538 if (NumPlaceArgs > 0)
539 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
541 // FIXME: This is leaked on error. But so much is currently in Sema that it's
542 // easier to clean it in one go.
543 AllocArgs[0]->Destroy(Context);
547 /// FindAllocationOverload - Find an fitting overload for the allocation
548 /// function in the specified scope.
549 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
550 DeclarationName Name, Expr** Args,
551 unsigned NumArgs, DeclContext *Ctx,
552 bool AllowMissing, FunctionDecl *&Operator)
554 DeclContext::lookup_iterator Alloc, AllocEnd;
555 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
556 if (Alloc == AllocEnd) {
559 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
563 OverloadCandidateSet Candidates;
564 for (; Alloc != AllocEnd; ++Alloc) {
565 // Even member operator new/delete are implicitly treated as
566 // static, so don't use AddMemberCandidate.
567 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
568 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
569 /*SuppressUserConversions=*/false);
572 // Do the resolution.
573 OverloadCandidateSet::iterator Best;
574 switch(BestViableFunction(Candidates, StartLoc, Best)) {
577 FunctionDecl *FnDecl = Best->Function;
578 // The first argument is size_t, and the first parameter must be size_t,
579 // too. This is checked on declaration and can be assumed. (It can't be
580 // asserted on, though, since invalid decls are left in there.)
581 for (unsigned i = 1; i < NumArgs; ++i) {
582 // FIXME: Passing word to diagnostic.
583 if (PerformCopyInitialization(Args[i],
584 FnDecl->getParamDecl(i)->getType(),
592 case OR_No_Viable_Function:
593 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
595 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
599 Diag(StartLoc, diag::err_ovl_ambiguous_call)
601 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
605 Diag(StartLoc, diag::err_ovl_deleted_call)
606 << Best->Function->isDeleted()
608 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
611 assert(false && "Unreachable, bad result from BestViableFunction");
616 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
617 /// delete. These are:
619 /// void* operator new(std::size_t) throw(std::bad_alloc);
620 /// void* operator new[](std::size_t) throw(std::bad_alloc);
621 /// void operator delete(void *) throw();
622 /// void operator delete[](void *) throw();
624 /// Note that the placement and nothrow forms of new are *not* implicitly
625 /// declared. Their use requires including \<new\>.
626 void Sema::DeclareGlobalNewDelete()
628 if (GlobalNewDeleteDeclared)
630 GlobalNewDeleteDeclared = true;
632 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
633 QualType SizeT = Context.getSizeType();
635 // FIXME: Exception specifications are not added.
636 DeclareGlobalAllocationFunction(
637 Context.DeclarationNames.getCXXOperatorName(OO_New),
639 DeclareGlobalAllocationFunction(
640 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
642 DeclareGlobalAllocationFunction(
643 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
644 Context.VoidTy, VoidPtr);
645 DeclareGlobalAllocationFunction(
646 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
647 Context.VoidTy, VoidPtr);
650 /// DeclareGlobalAllocationFunction - Declares a single implicit global
651 /// allocation function if it doesn't already exist.
652 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
653 QualType Return, QualType Argument)
655 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
657 // Check if this function is already declared.
659 DeclContext::lookup_iterator Alloc, AllocEnd;
660 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Context, Name);
661 Alloc != AllocEnd; ++Alloc) {
662 // FIXME: Do we need to check for default arguments here?
663 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
664 if (Func->getNumParams() == 1 &&
665 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
670 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
671 FunctionDecl *Alloc =
672 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
673 FnType, FunctionDecl::None, false, true,
675 Alloc->setImplicit();
676 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
677 0, Argument, VarDecl::None, 0);
678 Alloc->setParams(Context, &Param, 1);
680 // FIXME: Also add this declaration to the IdentifierResolver, but
681 // make sure it is at the end of the chain to coincide with the
683 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
686 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
687 /// @code ::delete ptr; @endcode
689 /// @code delete [] ptr; @endcode
690 Action::OwningExprResult
691 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
692 bool ArrayForm, ExprArg Operand)
694 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
695 // having a single conversion function to a pointer type. The result has
697 // DR599 amends "pointer type" to "pointer to object type" in both cases.
699 Expr *Ex = (Expr *)Operand.get();
700 if (!Ex->isTypeDependent()) {
701 QualType Type = Ex->getType();
703 if (Type->isRecordType()) {
704 // FIXME: Find that one conversion function and amend the type.
707 if (!Type->isPointerType())
708 return ExprError(Diag(StartLoc, diag::err_delete_operand)
709 << Type << Ex->getSourceRange());
711 QualType Pointee = Type->getAsPointerType()->getPointeeType();
712 if (Pointee->isFunctionType() || Pointee->isVoidType())
713 return ExprError(Diag(StartLoc, diag::err_delete_operand)
714 << Type << Ex->getSourceRange());
715 else if (!Pointee->isDependentType() &&
716 RequireCompleteType(StartLoc, Pointee,
717 diag::warn_delete_incomplete,
718 Ex->getSourceRange()))
721 // FIXME: Look up the correct operator delete overload and pass a pointer
723 // FIXME: Check access and ambiguity of operator delete and destructor.
727 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
732 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
733 /// C++ if/switch/while/for statement.
734 /// e.g: "if (int x = f()) {...}"
735 Action::OwningExprResult
736 Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
738 SourceLocation EqualLoc,
739 ExprArg AssignExprVal) {
740 assert(AssignExprVal.get() && "Null assignment expression");
743 // The declarator shall not specify a function or an array.
744 // The type-specifier-seq shall not contain typedef and shall not declare a
745 // new class or enumeration.
747 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
748 "Parser allowed 'typedef' as storage class of condition decl.");
750 QualType Ty = GetTypeForDeclarator(D, S);
752 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
753 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
754 // would be created and CXXConditionDeclExpr wants a VarDecl.
755 return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
756 << SourceRange(StartLoc, EqualLoc));
757 } else if (Ty->isArrayType()) { // ...or an array.
758 Diag(StartLoc, diag::err_invalid_use_of_array_type)
759 << SourceRange(StartLoc, EqualLoc);
760 } else if (const RecordType *RT = Ty->getAsRecordType()) {
761 RecordDecl *RD = RT->getDecl();
762 // The type-specifier-seq shall not declare a new class...
763 if (RD->isDefinition() &&
764 (RD->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(RD))))
765 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
766 } else if (const EnumType *ET = Ty->getAsEnumType()) {
767 EnumDecl *ED = ET->getDecl();
768 // ...or enumeration.
769 if (ED->isDefinition() &&
770 (ED->getIdentifier() == 0 || S->isDeclScope(DeclPtrTy::make(ED))))
771 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
774 DeclPtrTy Dcl = ActOnDeclarator(S, D, DeclPtrTy());
777 AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
779 // Mark this variable as one that is declared within a conditional.
780 // We know that the decl had to be a VarDecl because that is the only type of
781 // decl that can be assigned and the grammar requires an '='.
782 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
783 VD->setDeclaredInCondition(true);
784 return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
787 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
788 bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
790 // The value of a condition that is an initialized declaration in a statement
791 // other than a switch statement is the value of the declared variable
792 // implicitly converted to type bool. If that conversion is ill-formed, the
793 // program is ill-formed.
794 // The value of a condition that is an expression is the value of the
795 // expression, implicitly converted to bool.
797 return PerformContextuallyConvertToBool(CondExpr);
800 /// Helper function to determine whether this is the (deprecated) C++
801 /// conversion from a string literal to a pointer to non-const char or
802 /// non-const wchar_t (for narrow and wide string literals,
805 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
806 // Look inside the implicit cast, if it exists.
807 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
808 From = Cast->getSubExpr();
810 // A string literal (2.13.4) that is not a wide string literal can
811 // be converted to an rvalue of type "pointer to char"; a wide
812 // string literal can be converted to an rvalue of type "pointer
813 // to wchar_t" (C++ 4.2p2).
814 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
815 if (const PointerType *ToPtrType = ToType->getAsPointerType())
816 if (const BuiltinType *ToPointeeType
817 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
818 // This conversion is considered only when there is an
819 // explicit appropriate pointer target type (C++ 4.2p2).
820 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
821 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
822 (!StrLit->isWide() &&
823 (ToPointeeType->getKind() == BuiltinType::Char_U ||
824 ToPointeeType->getKind() == BuiltinType::Char_S))))
831 /// PerformImplicitConversion - Perform an implicit conversion of the
832 /// expression From to the type ToType. Returns true if there was an
833 /// error, false otherwise. The expression From is replaced with the
834 /// converted expression. Flavor is the kind of conversion we're
835 /// performing, used in the error message. If @p AllowExplicit,
836 /// explicit user-defined conversions are permitted. @p Elidable should be true
837 /// when called for copies which may be elided (C++ 12.8p15). C++0x overload
838 /// resolution works differently in that case.
840 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
841 const char *Flavor, bool AllowExplicit,
844 ImplicitConversionSequence ICS;
845 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
846 if (Elidable && getLangOptions().CPlusPlus0x) {
847 ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
848 AllowExplicit, /*ForceRValue*/true);
850 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
851 ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
853 return PerformImplicitConversion(From, ToType, ICS, Flavor);
856 /// PerformImplicitConversion - Perform an implicit conversion of the
857 /// expression From to the type ToType using the pre-computed implicit
858 /// conversion sequence ICS. Returns true if there was an error, false
859 /// otherwise. The expression From is replaced with the converted
860 /// expression. Flavor is the kind of conversion we're performing,
861 /// used in the error message.
863 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
864 const ImplicitConversionSequence &ICS,
865 const char* Flavor) {
866 switch (ICS.ConversionKind) {
867 case ImplicitConversionSequence::StandardConversion:
868 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
872 case ImplicitConversionSequence::UserDefinedConversion:
873 // FIXME: This is, of course, wrong. We'll need to actually call the
874 // constructor or conversion operator, and then cope with the standard
876 ImpCastExprToType(From, ToType.getNonReferenceType(),
877 ToType->isLValueReferenceType());
880 case ImplicitConversionSequence::EllipsisConversion:
881 assert(false && "Cannot perform an ellipsis conversion");
884 case ImplicitConversionSequence::BadConversion:
888 // Everything went well.
892 /// PerformImplicitConversion - Perform an implicit conversion of the
893 /// expression From to the type ToType by following the standard
894 /// conversion sequence SCS. Returns true if there was an error, false
895 /// otherwise. The expression From is replaced with the converted
896 /// expression. Flavor is the context in which we're performing this
897 /// conversion, for use in error messages.
899 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
900 const StandardConversionSequence& SCS,
901 const char *Flavor) {
902 // Overall FIXME: we are recomputing too many types here and doing far too
903 // much extra work. What this means is that we need to keep track of more
904 // information that is computed when we try the implicit conversion initially,
905 // so that we don't need to recompute anything here.
906 QualType FromType = From->getType();
908 if (SCS.CopyConstructor) {
909 // FIXME: When can ToType be a reference type?
910 assert(!ToType->isReferenceType());
912 // FIXME: Keep track of whether the copy constructor is elidable or not.
913 From = CXXConstructExpr::Create(Context, ToType,
914 SCS.CopyConstructor, false, &From, 1);
918 // Perform the first implicit conversion.
921 case ICK_Lvalue_To_Rvalue:
925 case ICK_Array_To_Pointer:
926 FromType = Context.getArrayDecayedType(FromType);
927 ImpCastExprToType(From, FromType);
930 case ICK_Function_To_Pointer:
931 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
932 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
936 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
939 FixOverloadedFunctionReference(From, Fn);
940 FromType = From->getType();
942 FromType = Context.getPointerType(FromType);
943 ImpCastExprToType(From, FromType);
947 assert(false && "Improper first standard conversion");
951 // Perform the second implicit conversion
952 switch (SCS.Second) {
957 case ICK_Integral_Promotion:
958 case ICK_Floating_Promotion:
959 case ICK_Complex_Promotion:
960 case ICK_Integral_Conversion:
961 case ICK_Floating_Conversion:
962 case ICK_Complex_Conversion:
963 case ICK_Floating_Integral:
964 case ICK_Complex_Real:
965 case ICK_Compatible_Conversion:
966 // FIXME: Go deeper to get the unqualified type!
967 FromType = ToType.getUnqualifiedType();
968 ImpCastExprToType(From, FromType);
971 case ICK_Pointer_Conversion:
972 if (SCS.IncompatibleObjC) {
973 // Diagnose incompatible Objective-C conversions
974 Diag(From->getSourceRange().getBegin(),
975 diag::ext_typecheck_convert_incompatible_pointer)
976 << From->getType() << ToType << Flavor
977 << From->getSourceRange();
980 if (CheckPointerConversion(From, ToType))
982 ImpCastExprToType(From, ToType);
985 case ICK_Pointer_Member:
986 if (CheckMemberPointerConversion(From, ToType))
988 ImpCastExprToType(From, ToType);
991 case ICK_Boolean_Conversion:
992 FromType = Context.BoolTy;
993 ImpCastExprToType(From, FromType);
997 assert(false && "Improper second standard conversion");
1001 switch (SCS.Third) {
1006 case ICK_Qualification:
1007 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1009 ImpCastExprToType(From, ToType.getNonReferenceType(),
1010 ToType->isLValueReferenceType());
1014 assert(false && "Improper second standard conversion");
1021 Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1022 SourceLocation KWLoc,
1023 SourceLocation LParen,
1025 SourceLocation RParen) {
1026 // FIXME: Some of the type traits have requirements. Interestingly, only the
1027 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed, G++
1028 // accepts __is_pod(Incomplete) without complaints, and claims that the type
1031 // There is no point in eagerly computing the value. The traits are designed
1032 // to be used from type trait templates, so Ty will be a template parameter
1034 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
1035 QualType::getFromOpaquePtr(Ty),
1036 RParen, Context.BoolTy));
1039 QualType Sema::CheckPointerToMemberOperands(
1040 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1042 const char *OpSpelling = isIndirect ? "->*" : ".*";
1044 // The binary operator .* [p3: ->*] binds its second operand, which shall
1045 // be of type "pointer to member of T" (where T is a completely-defined
1046 // class type) [...]
1047 QualType RType = rex->getType();
1048 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
1050 Diag(Loc, diag::err_bad_memptr_rhs)
1051 << OpSpelling << RType << rex->getSourceRange();
1055 QualType Class(MemPtr->getClass(), 0);
1058 // [...] to its first operand, which shall be of class T or of a class of
1059 // which T is an unambiguous and accessible base class. [p3: a pointer to
1061 QualType LType = lex->getType();
1063 if (const PointerType *Ptr = LType->getAsPointerType())
1064 LType = Ptr->getPointeeType().getNonReferenceType();
1066 Diag(Loc, diag::err_bad_memptr_lhs)
1067 << OpSpelling << 1 << LType << lex->getSourceRange();
1072 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1073 Context.getCanonicalType(LType).getUnqualifiedType()) {
1074 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1075 /*DetectVirtual=*/false);
1076 // FIXME: Would it be useful to print full ambiguity paths, or is that
1078 if (!IsDerivedFrom(LType, Class, Paths) ||
1079 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1080 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1081 << (int)isIndirect << lex->getType() << lex->getSourceRange();
1087 // The result is an object or a function of the type specified by the
1089 // The cv qualifiers are the union of those in the pointer and the left side,
1090 // in accordance with 5.5p5 and 5.2.5.
1091 // FIXME: This returns a dereferenced member function pointer as a normal
1092 // function type. However, the only operation valid on such functions is
1093 // calling them. There's also a GCC extension to get a function pointer to the
1094 // thing, which is another complication, because this type - unlike the type
1095 // that is the result of this expression - takes the class as the first
1097 // We probably need a "MemberFunctionClosureType" or something like that.
1098 QualType Result = MemPtr->getPointeeType();
1099 if (LType.isConstQualified())
1101 if (LType.isVolatileQualified())
1102 Result.addVolatile();
1106 /// \brief Get the target type of a standard or user-defined conversion.
1107 static QualType TargetType(const ImplicitConversionSequence &ICS) {
1108 assert((ICS.ConversionKind ==
1109 ImplicitConversionSequence::StandardConversion ||
1110 ICS.ConversionKind ==
1111 ImplicitConversionSequence::UserDefinedConversion) &&
1112 "function only valid for standard or user-defined conversions");
1113 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1114 return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1115 return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1118 /// \brief Try to convert a type to another according to C++0x 5.16p3.
1120 /// This is part of the parameter validation for the ? operator. If either
1121 /// value operand is a class type, the two operands are attempted to be
1122 /// converted to each other. This function does the conversion in one direction.
1123 /// It emits a diagnostic and returns true only if it finds an ambiguous
1125 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1126 SourceLocation QuestionLoc,
1127 ImplicitConversionSequence &ICS)
1130 // The process for determining whether an operand expression E1 of type T1
1131 // can be converted to match an operand expression E2 of type T2 is defined
1133 // -- If E2 is an lvalue:
1134 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1135 // E1 can be converted to match E2 if E1 can be implicitly converted to
1136 // type "lvalue reference to T2", subject to the constraint that in the
1137 // conversion the reference must bind directly to E1.
1138 if (!Self.CheckReferenceInit(From,
1139 Self.Context.getLValueReferenceType(To->getType()),
1142 assert((ICS.ConversionKind ==
1143 ImplicitConversionSequence::StandardConversion ||
1144 ICS.ConversionKind ==
1145 ImplicitConversionSequence::UserDefinedConversion) &&
1146 "expected a definite conversion");
1147 bool DirectBinding =
1148 ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1149 ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1154 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1155 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1156 // -- if E1 and E2 have class type, and the underlying class types are
1157 // the same or one is a base class of the other:
1158 QualType FTy = From->getType();
1159 QualType TTy = To->getType();
1160 const RecordType *FRec = FTy->getAsRecordType();
1161 const RecordType *TRec = TTy->getAsRecordType();
1162 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1163 if (FRec && TRec && (FRec == TRec ||
1164 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1165 // E1 can be converted to match E2 if the class of T2 is the
1166 // same type as, or a base class of, the class of T1, and
1168 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1169 // Could still fail if there's no copy constructor.
1170 // FIXME: Is this a hard error then, or just a conversion failure? The
1171 // standard doesn't say.
1172 ICS = Self.TryCopyInitialization(From, TTy);
1175 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1176 // implicitly converted to the type that expression E2 would have
1177 // if E2 were converted to an rvalue.
1178 // First find the decayed type.
1179 if (TTy->isFunctionType())
1180 TTy = Self.Context.getPointerType(TTy);
1181 else if(TTy->isArrayType())
1182 TTy = Self.Context.getArrayDecayedType(TTy);
1184 // Now try the implicit conversion.
1185 // FIXME: This doesn't detect ambiguities.
1186 ICS = Self.TryImplicitConversion(From, TTy);
1191 /// \brief Try to find a common type for two according to C++0x 5.16p5.
1193 /// This is part of the parameter validation for the ? operator. If either
1194 /// value operand is a class type, overload resolution is used to find a
1195 /// conversion to a common type.
1196 static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1197 SourceLocation Loc) {
1198 Expr *Args[2] = { LHS, RHS };
1199 OverloadCandidateSet CandidateSet;
1200 Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1202 OverloadCandidateSet::iterator Best;
1203 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
1204 case Sema::OR_Success:
1205 // We found a match. Perform the conversions on the arguments and move on.
1206 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1207 Best->Conversions[0], "converting") ||
1208 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1209 Best->Conversions[1], "converting"))
1213 case Sema::OR_No_Viable_Function:
1214 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1215 << LHS->getType() << RHS->getType()
1216 << LHS->getSourceRange() << RHS->getSourceRange();
1219 case Sema::OR_Ambiguous:
1220 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1221 << LHS->getType() << RHS->getType()
1222 << LHS->getSourceRange() << RHS->getSourceRange();
1223 // FIXME: Print the possible common types by printing the return types of
1224 // the viable candidates.
1227 case Sema::OR_Deleted:
1228 assert(false && "Conditional operator has only built-in overloads");
1234 /// \brief Perform an "extended" implicit conversion as returned by
1235 /// TryClassUnification.
1237 /// TryClassUnification generates ICSs that include reference bindings.
1238 /// PerformImplicitConversion is not suitable for this; it chokes if the
1239 /// second part of a standard conversion is ICK_DerivedToBase. This function
1240 /// handles the reference binding specially.
1241 static bool ConvertForConditional(Sema &Self, Expr *&E,
1242 const ImplicitConversionSequence &ICS)
1244 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1245 ICS.Standard.ReferenceBinding) {
1246 assert(ICS.Standard.DirectBinding &&
1247 "TryClassUnification should never generate indirect ref bindings");
1248 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1249 // redoing all the work.
1250 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1253 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1254 ICS.UserDefined.After.ReferenceBinding) {
1255 assert(ICS.UserDefined.After.DirectBinding &&
1256 "TryClassUnification should never generate indirect ref bindings");
1257 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1260 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1265 /// \brief Check the operands of ?: under C++ semantics.
1267 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1268 /// extension. In this case, LHS == Cond. (But they're not aliases.)
1269 QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1270 SourceLocation QuestionLoc) {
1271 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1272 // interface pointers.
1275 // The first expression is contextually converted to bool.
1276 if (!Cond->isTypeDependent()) {
1277 if (CheckCXXBooleanCondition(Cond))
1281 // Either of the arguments dependent?
1282 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1283 return Context.DependentTy;
1286 // If either the second or the third operand has type (cv) void, ...
1287 QualType LTy = LHS->getType();
1288 QualType RTy = RHS->getType();
1289 bool LVoid = LTy->isVoidType();
1290 bool RVoid = RTy->isVoidType();
1291 if (LVoid || RVoid) {
1292 // ... then the [l2r] conversions are performed on the second and third
1294 DefaultFunctionArrayConversion(LHS);
1295 DefaultFunctionArrayConversion(RHS);
1296 LTy = LHS->getType();
1297 RTy = RHS->getType();
1299 // ... and one of the following shall hold:
1300 // -- The second or the third operand (but not both) is a throw-
1301 // expression; the result is of the type of the other and is an rvalue.
1302 bool LThrow = isa<CXXThrowExpr>(LHS);
1303 bool RThrow = isa<CXXThrowExpr>(RHS);
1304 if (LThrow && !RThrow)
1306 if (RThrow && !LThrow)
1309 // -- Both the second and third operands have type void; the result is of
1310 // type void and is an rvalue.
1312 return Context.VoidTy;
1314 // Neither holds, error.
1315 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1316 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1317 << LHS->getSourceRange() << RHS->getSourceRange();
1324 // Otherwise, if the second and third operand have different types, and
1325 // either has (cv) class type, and attempt is made to convert each of those
1326 // operands to the other.
1327 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1328 (LTy->isRecordType() || RTy->isRecordType())) {
1329 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1330 // These return true if a single direction is already ambiguous.
1331 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1333 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1336 bool HaveL2R = ICSLeftToRight.ConversionKind !=
1337 ImplicitConversionSequence::BadConversion;
1338 bool HaveR2L = ICSRightToLeft.ConversionKind !=
1339 ImplicitConversionSequence::BadConversion;
1340 // If both can be converted, [...] the program is ill-formed.
1341 if (HaveL2R && HaveR2L) {
1342 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1343 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1347 // If exactly one conversion is possible, that conversion is applied to
1348 // the chosen operand and the converted operands are used in place of the
1349 // original operands for the remainder of this section.
1351 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
1353 LTy = LHS->getType();
1354 } else if (HaveR2L) {
1355 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
1357 RTy = RHS->getType();
1362 // If the second and third operands are lvalues and have the same type,
1363 // the result is of that type [...]
1364 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1365 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1366 RHS->isLvalue(Context) == Expr::LV_Valid)
1370 // Otherwise, the result is an rvalue. If the second and third operands
1371 // do not have the same type, and either has (cv) class type, ...
1372 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1373 // ... overload resolution is used to determine the conversions (if any)
1374 // to be applied to the operands. If the overload resolution fails, the
1375 // program is ill-formed.
1376 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1381 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1382 // conversions are performed on the second and third operands.
1383 DefaultFunctionArrayConversion(LHS);
1384 DefaultFunctionArrayConversion(RHS);
1385 LTy = LHS->getType();
1386 RTy = RHS->getType();
1388 // After those conversions, one of the following shall hold:
1389 // -- The second and third operands have the same type; the result
1391 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1394 // -- The second and third operands have arithmetic or enumeration type;
1395 // the usual arithmetic conversions are performed to bring them to a
1396 // common type, and the result is of that type.
1397 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1398 UsualArithmeticConversions(LHS, RHS);
1399 return LHS->getType();
1402 // -- The second and third operands have pointer type, or one has pointer
1403 // type and the other is a null pointer constant; pointer conversions
1404 // and qualification conversions are performed to bring them to their
1405 // composite pointer type. The result is of the composite pointer type.
1406 QualType Composite = FindCompositePointerType(LHS, RHS);
1407 if (!Composite.isNull())
1410 // Fourth bullet is same for pointers-to-member. However, the possible
1411 // conversions are far more limited: we have null-to-pointer, upcast of
1412 // containing class, and second-level cv-ness.
1413 // cv-ness is not a union, but must match one of the two operands. (Which,
1414 // frankly, is stupid.)
1415 const MemberPointerType *LMemPtr = LTy->getAsMemberPointerType();
1416 const MemberPointerType *RMemPtr = RTy->getAsMemberPointerType();
1417 if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1418 ImpCastExprToType(RHS, LTy);
1421 if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1422 ImpCastExprToType(LHS, RTy);
1425 if (LMemPtr && RMemPtr) {
1426 QualType LPointee = LMemPtr->getPointeeType();
1427 QualType RPointee = RMemPtr->getPointeeType();
1428 // First, we check that the unqualified pointee type is the same. If it's
1429 // not, there's no conversion that will unify the two pointers.
1430 if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1431 Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1432 // Second, we take the greater of the two cv qualifications. If neither
1433 // is greater than the other, the conversion is not possible.
1434 unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1435 if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1436 // Third, we check if either of the container classes is derived from
1438 QualType LContainer(LMemPtr->getClass(), 0);
1439 QualType RContainer(RMemPtr->getClass(), 0);
1440 QualType MoreDerived;
1441 if (Context.getCanonicalType(LContainer) ==
1442 Context.getCanonicalType(RContainer))
1443 MoreDerived = LContainer;
1444 else if (IsDerivedFrom(LContainer, RContainer))
1445 MoreDerived = LContainer;
1446 else if (IsDerivedFrom(RContainer, LContainer))
1447 MoreDerived = RContainer;
1449 if (!MoreDerived.isNull()) {
1450 // The type 'Q Pointee (MoreDerived::*)' is the common type.
1451 // We don't use ImpCastExprToType here because this could still fail
1452 // for ambiguous or inaccessible conversions.
1453 QualType Common = Context.getMemberPointerType(
1454 LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1455 if (PerformImplicitConversion(LHS, Common, "converting"))
1457 if (PerformImplicitConversion(RHS, Common, "converting"))
1465 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1466 << LHS->getType() << RHS->getType()
1467 << LHS->getSourceRange() << RHS->getSourceRange();
1471 /// \brief Find a merged pointer type and convert the two expressions to it.
1473 /// This finds the composite pointer type for @p E1 and @p E2 according to
1474 /// C++0x 5.9p2. It converts both expressions to this type and returns it.
1475 /// It does not emit diagnostics.
1476 QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1477 assert(getLangOptions().CPlusPlus && "This function assumes C++");
1478 QualType T1 = E1->getType(), T2 = E2->getType();
1479 if(!T1->isPointerType() && !T2->isPointerType())
1483 // Pointer conversions and qualification conversions are performed on
1484 // pointer operands to bring them to their composite pointer type. If
1485 // one operand is a null pointer constant, the composite pointer type is
1486 // the type of the other operand.
1487 if (E1->isNullPointerConstant(Context)) {
1488 ImpCastExprToType(E1, T2);
1491 if (E2->isNullPointerConstant(Context)) {
1492 ImpCastExprToType(E2, T1);
1495 // Now both have to be pointers.
1496 if(!T1->isPointerType() || !T2->isPointerType())
1499 // Otherwise, of one of the operands has type "pointer to cv1 void," then
1500 // the other has type "pointer to cv2 T" and the composite pointer type is
1501 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1502 // Otherwise, the composite pointer type is a pointer type similar to the
1503 // type of one of the operands, with a cv-qualification signature that is
1504 // the union of the cv-qualification signatures of the operand types.
1505 // In practice, the first part here is redundant; it's subsumed by the second.
1506 // What we do here is, we build the two possible composite types, and try the
1507 // conversions in both directions. If only one works, or if the two composite
1508 // types are the same, we have succeeded.
1509 llvm::SmallVector<unsigned, 4> QualifierUnion;
1510 QualType Composite1 = T1, Composite2 = T2;
1511 const PointerType *Ptr1, *Ptr2;
1512 while ((Ptr1 = Composite1->getAsPointerType()) &&
1513 (Ptr2 = Composite2->getAsPointerType())) {
1514 Composite1 = Ptr1->getPointeeType();
1515 Composite2 = Ptr2->getPointeeType();
1516 QualifierUnion.push_back(
1517 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1519 // Rewrap the composites as pointers with the union CVRs.
1520 for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1521 E = QualifierUnion.end(); I != E; ++I) {
1522 Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1523 Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1526 ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1527 ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1528 ImplicitConversionSequence E1ToC2, E2ToC2;
1529 E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1530 E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1531 if (Context.getCanonicalType(Composite1) !=
1532 Context.getCanonicalType(Composite2)) {
1533 E1ToC2 = TryImplicitConversion(E1, Composite2);
1534 E2ToC2 = TryImplicitConversion(E2, Composite2);
1537 bool ToC1Viable = E1ToC1.ConversionKind !=
1538 ImplicitConversionSequence::BadConversion
1539 && E2ToC1.ConversionKind !=
1540 ImplicitConversionSequence::BadConversion;
1541 bool ToC2Viable = E1ToC2.ConversionKind !=
1542 ImplicitConversionSequence::BadConversion
1543 && E2ToC2.ConversionKind !=
1544 ImplicitConversionSequence::BadConversion;
1545 if (ToC1Viable && !ToC2Viable) {
1546 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1547 !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1550 if (ToC2Viable && !ToC1Viable) {
1551 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1552 !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1558 Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
1559 const RecordType *RT = E->getType()->getAsRecordType();
1563 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1564 if (RD->hasTrivialDestructor())
1567 CXXTemporary *Temp = CXXTemporary::Create(Context,
1568 RD->getDestructor(Context));
1569 ExprTemporaries.push_back(Temp);
1571 // FIXME: Add the temporary to the temporaries vector.
1572 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1575 // FIXME: This doesn't handle casts yet.
1576 Expr *Sema::RemoveOutermostTemporaryBinding(Expr *E) {
1577 const RecordType *RT = E->getType()->getAsRecordType();
1581 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1582 if (RD->hasTrivialDestructor())
1585 /// The expr passed in must be a CXXExprWithTemporaries.
1586 CXXExprWithTemporaries *TempExpr = dyn_cast<CXXExprWithTemporaries>(E);
1590 Expr *SubExpr = TempExpr->getSubExpr();
1591 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) {
1592 assert(BE->getTemporary() ==
1593 TempExpr->getTemporary(TempExpr->getNumTemporaries() - 1) &&
1594 "Found temporary is not last in list!");
1596 Expr *BindSubExpr = BE->getSubExpr();
1599 if (TempExpr->getNumTemporaries() == 1) {
1600 // There's just one temporary left, so we don't need the TempExpr node.
1601 TempExpr->Destroy(Context);
1604 TempExpr->removeLastTemporary();
1605 TempExpr->setSubExpr(BindSubExpr);
1606 BE->Destroy(Context);
1612 // FIXME: We might need to handle other expressions here.
1616 Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
1617 bool ShouldDestroyTemps) {
1618 assert(SubExpr && "sub expression can't be null!");
1620 if (ExprTemporaries.empty())
1623 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1624 &ExprTemporaries[0],
1625 ExprTemporaries.size(),
1626 ShouldDestroyTemps);
1627 ExprTemporaries.clear();
1632 Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1633 Expr *FullExpr = Arg.takeAs<Expr>();
1635 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1636 /*ShouldDestroyTemps=*/true);
1638 return Owned(FullExpr);