SemaExprCXX.cpp revision 759986e85990281ea741820822809ac57fd28c40
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//  This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/Basic/PartialDiagnostic.h"
19#include "clang/Basic/TargetInfo.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
22#include "llvm/ADT/STLExtras.h"
23using namespace clang;
24
25/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
26/// name (e.g., operator void const *) as an expression. This is
27/// very similar to ActOnIdentifierExpr, except that instead of
28/// providing an identifier the parser provides the type of the
29/// conversion function.
30Sema::OwningExprResult
31Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
32                                     TypeTy *Ty, bool HasTrailingLParen,
33                                     const CXXScopeSpec &SS,
34                                     bool isAddressOfOperand) {
35  //FIXME: Preserve type source info.
36  QualType ConvType = GetTypeFromParser(Ty);
37  CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
38  DeclarationName ConvName
39    = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
40  return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
41                                  &SS, isAddressOfOperand);
42}
43
44/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
45/// name (e.g., @c operator+ ) as an expression. This is very
46/// similar to ActOnIdentifierExpr, except that instead of providing
47/// an identifier the parser provides the kind of overloaded
48/// operator that was parsed.
49Sema::OwningExprResult
50Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
51                                     OverloadedOperatorKind Op,
52                                     bool HasTrailingLParen,
53                                     const CXXScopeSpec &SS,
54                                     bool isAddressOfOperand) {
55  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
56  return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
57                                  isAddressOfOperand);
58}
59
60/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
61Action::OwningExprResult
62Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
63                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
64  if (!StdNamespace)
65    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
66
67  if (isType)
68    // FIXME: Preserve type source info.
69    TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
70
71  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
72  LookupResult R;
73  LookupQualifiedName(R, StdNamespace, TypeInfoII, LookupTagName);
74  Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
75  RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
76  if (!TypeInfoRecordDecl)
77    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
78
79  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
80
81  if (!isType) {
82    // C++0x [expr.typeid]p3:
83    //   When typeid is applied to an expression other than an lvalue of a
84    //   polymorphic class type [...] [the] expression is an unevaluated
85    //   operand.
86
87    // FIXME: if the type of the expression is a class type, the class
88    // shall be completely defined.
89    bool isUnevaluatedOperand = true;
90    Expr *E = static_cast<Expr *>(TyOrExpr);
91    if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
92      QualType T = E->getType();
93      if (const RecordType *RecordT = T->getAs<RecordType>()) {
94        CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
95        if (RecordD->isPolymorphic())
96          isUnevaluatedOperand = false;
97      }
98    }
99
100    // If this is an unevaluated operand, clear out the set of declaration
101    // references we have been computing.
102    if (isUnevaluatedOperand)
103      PotentiallyReferencedDeclStack.back().clear();
104  }
105
106  return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
107                                           TypeInfoType.withConst(),
108                                           SourceRange(OpLoc, RParenLoc)));
109}
110
111/// ActOnCXXBoolLiteral - Parse {true,false} literals.
112Action::OwningExprResult
113Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
114  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
115         "Unknown C++ Boolean value!");
116  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
117                                                Context.BoolTy, OpLoc));
118}
119
120/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
121Action::OwningExprResult
122Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
123  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
124}
125
126/// ActOnCXXThrow - Parse throw expressions.
127Action::OwningExprResult
128Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
129  Expr *Ex = E.takeAs<Expr>();
130  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
131    return ExprError();
132  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
133}
134
135/// CheckCXXThrowOperand - Validate the operand of a throw.
136bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
137  // C++ [except.throw]p3:
138  //   [...] adjusting the type from "array of T" or "function returning T"
139  //   to "pointer to T" or "pointer to function returning T", [...]
140  DefaultFunctionArrayConversion(E);
141
142  //   If the type of the exception would be an incomplete type or a pointer
143  //   to an incomplete type other than (cv) void the program is ill-formed.
144  QualType Ty = E->getType();
145  int isPointer = 0;
146  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
147    Ty = Ptr->getPointeeType();
148    isPointer = 1;
149  }
150  if (!isPointer || !Ty->isVoidType()) {
151    if (RequireCompleteType(ThrowLoc, Ty,
152                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
153                                            : diag::err_throw_incomplete)
154                              << E->getSourceRange()))
155      return true;
156  }
157
158  // FIXME: Construct a temporary here.
159  return false;
160}
161
162Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
163  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
164  /// is a non-lvalue expression whose value is the address of the object for
165  /// which the function is called.
166
167  if (!isa<FunctionDecl>(CurContext))
168    return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
169
170  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
171    if (MD->isInstance())
172      return Owned(new (Context) CXXThisExpr(ThisLoc,
173                                             MD->getThisType(Context)));
174
175  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
176}
177
178/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
179/// Can be interpreted either as function-style casting ("int(x)")
180/// or class type construction ("ClassType(x,y,z)")
181/// or creation of a value-initialized type ("int()").
182Action::OwningExprResult
183Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
184                                SourceLocation LParenLoc,
185                                MultiExprArg exprs,
186                                SourceLocation *CommaLocs,
187                                SourceLocation RParenLoc) {
188  assert(TypeRep && "Missing type!");
189  // FIXME: Preserve type source info.
190  QualType Ty = GetTypeFromParser(TypeRep);
191  unsigned NumExprs = exprs.size();
192  Expr **Exprs = (Expr**)exprs.get();
193  SourceLocation TyBeginLoc = TypeRange.getBegin();
194  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
195
196  if (Ty->isDependentType() ||
197      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
198    exprs.release();
199
200    return Owned(CXXUnresolvedConstructExpr::Create(Context,
201                                                    TypeRange.getBegin(), Ty,
202                                                    LParenLoc,
203                                                    Exprs, NumExprs,
204                                                    RParenLoc));
205  }
206
207  if (Ty->isArrayType())
208    return ExprError(Diag(TyBeginLoc,
209                          diag::err_value_init_for_array_type) << FullRange);
210  if (!Ty->isVoidType() &&
211      RequireCompleteType(TyBeginLoc, Ty,
212                          PDiag(diag::err_invalid_incomplete_type_use)
213                            << FullRange))
214    return ExprError();
215
216  if (RequireNonAbstractType(TyBeginLoc, Ty,
217                             diag::err_allocation_of_abstract_type))
218    return ExprError();
219
220
221  // C++ [expr.type.conv]p1:
222  // If the expression list is a single expression, the type conversion
223  // expression is equivalent (in definedness, and if defined in meaning) to the
224  // corresponding cast expression.
225  //
226  if (NumExprs == 1) {
227    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
228    CXXMethodDecl *Method = 0;
229    if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
230                       /*FunctionalStyle=*/true))
231      return ExprError();
232
233    exprs.release();
234    if (Method) {
235      OwningExprResult CastArg
236        = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
237                               Kind, Method, Owned(Exprs[0]));
238      if (CastArg.isInvalid())
239        return ExprError();
240
241      Exprs[0] = CastArg.takeAs<Expr>();
242    }
243
244    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
245                                                     Ty, TyBeginLoc, Kind,
246                                                     Exprs[0], RParenLoc));
247  }
248
249  if (const RecordType *RT = Ty->getAs<RecordType>()) {
250    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
251
252    if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
253        !Record->hasTrivialDestructor()) {
254      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
255
256      CXXConstructorDecl *Constructor
257        = PerformInitializationByConstructor(Ty, move(exprs),
258                                             TypeRange.getBegin(),
259                                             SourceRange(TypeRange.getBegin(),
260                                                         RParenLoc),
261                                             DeclarationName(),
262                                             IK_Direct,
263                                             ConstructorArgs);
264
265      if (!Constructor)
266        return ExprError();
267
268      OwningExprResult Result =
269        BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
270                                    move_arg(ConstructorArgs), RParenLoc);
271      if (Result.isInvalid())
272        return ExprError();
273
274      return MaybeBindToTemporary(Result.takeAs<Expr>());
275    }
276
277    // Fall through to value-initialize an object of class type that
278    // doesn't have a user-declared default constructor.
279  }
280
281  // C++ [expr.type.conv]p1:
282  // If the expression list specifies more than a single value, the type shall
283  // be a class with a suitably declared constructor.
284  //
285  if (NumExprs > 1)
286    return ExprError(Diag(CommaLocs[0],
287                          diag::err_builtin_func_cast_more_than_one_arg)
288      << FullRange);
289
290  assert(NumExprs == 0 && "Expected 0 expressions");
291
292  // C++ [expr.type.conv]p2:
293  // The expression T(), where T is a simple-type-specifier for a non-array
294  // complete object type or the (possibly cv-qualified) void type, creates an
295  // rvalue of the specified type, which is value-initialized.
296  //
297  exprs.release();
298  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
299}
300
301
302/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
303/// @code new (memory) int[size][4] @endcode
304/// or
305/// @code ::new Foo(23, "hello") @endcode
306/// For the interpretation of this heap of arguments, consult the base version.
307Action::OwningExprResult
308Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
309                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
310                  SourceLocation PlacementRParen, bool ParenTypeId,
311                  Declarator &D, SourceLocation ConstructorLParen,
312                  MultiExprArg ConstructorArgs,
313                  SourceLocation ConstructorRParen) {
314  Expr *ArraySize = 0;
315  unsigned Skip = 0;
316  // If the specified type is an array, unwrap it and save the expression.
317  if (D.getNumTypeObjects() > 0 &&
318      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
319    DeclaratorChunk &Chunk = D.getTypeObject(0);
320    if (Chunk.Arr.hasStatic)
321      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
322        << D.getSourceRange());
323    if (!Chunk.Arr.NumElts)
324      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
325        << D.getSourceRange());
326    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
327    Skip = 1;
328  }
329
330  // Every dimension shall be of constant size.
331  if (D.getNumTypeObjects() > 0 &&
332      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
333    for (unsigned I = 1, N = D.getNumTypeObjects(); I < N; ++I) {
334      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
335        break;
336
337      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
338      if (Expr *NumElts = (Expr *)Array.NumElts) {
339        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
340            !NumElts->isIntegerConstantExpr(Context)) {
341          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
342            << NumElts->getSourceRange();
343          return ExprError();
344        }
345      }
346    }
347  }
348
349  //FIXME: Store DeclaratorInfo in CXXNew expression.
350  DeclaratorInfo *DInfo = 0;
351  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
352  if (D.isInvalidType())
353    return ExprError();
354
355  return BuildCXXNew(StartLoc, UseGlobal,
356                     PlacementLParen,
357                     move(PlacementArgs),
358                     PlacementRParen,
359                     ParenTypeId,
360                     AllocType,
361                     D.getSourceRange().getBegin(),
362                     D.getSourceRange(),
363                     Owned(ArraySize),
364                     ConstructorLParen,
365                     move(ConstructorArgs),
366                     ConstructorRParen);
367}
368
369Sema::OwningExprResult
370Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
371                  SourceLocation PlacementLParen,
372                  MultiExprArg PlacementArgs,
373                  SourceLocation PlacementRParen,
374                  bool ParenTypeId,
375                  QualType AllocType,
376                  SourceLocation TypeLoc,
377                  SourceRange TypeRange,
378                  ExprArg ArraySizeE,
379                  SourceLocation ConstructorLParen,
380                  MultiExprArg ConstructorArgs,
381                  SourceLocation ConstructorRParen) {
382  if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
383    return ExprError();
384
385  QualType ResultType = Context.getPointerType(AllocType);
386
387  // That every array dimension except the first is constant was already
388  // checked by the type check above.
389
390  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
391  //   or enumeration type with a non-negative value."
392  Expr *ArraySize = (Expr *)ArraySizeE.get();
393  if (ArraySize && !ArraySize->isTypeDependent()) {
394    QualType SizeType = ArraySize->getType();
395    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
396      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
397                            diag::err_array_size_not_integral)
398        << SizeType << ArraySize->getSourceRange());
399    // Let's see if this is a constant < 0. If so, we reject it out of hand.
400    // We don't care about special rules, so we tell the machinery it's not
401    // evaluated - it gives us a result in more cases.
402    if (!ArraySize->isValueDependent()) {
403      llvm::APSInt Value;
404      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
405        if (Value < llvm::APSInt(
406                        llvm::APInt::getNullValue(Value.getBitWidth()),
407                                 Value.isUnsigned()))
408          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
409                           diag::err_typecheck_negative_array_size)
410            << ArraySize->getSourceRange());
411      }
412    }
413
414    ImpCastExprToType(ArraySize, Context.getSizeType());
415  }
416
417  FunctionDecl *OperatorNew = 0;
418  FunctionDecl *OperatorDelete = 0;
419  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
420  unsigned NumPlaceArgs = PlacementArgs.size();
421  if (!AllocType->isDependentType() &&
422      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
423      FindAllocationFunctions(StartLoc,
424                              SourceRange(PlacementLParen, PlacementRParen),
425                              UseGlobal, AllocType, ArraySize, PlaceArgs,
426                              NumPlaceArgs, OperatorNew, OperatorDelete))
427    return ExprError();
428
429  bool Init = ConstructorLParen.isValid();
430  // --- Choosing a constructor ---
431  // C++ 5.3.4p15
432  // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
433  //   the object is not initialized. If the object, or any part of it, is
434  //   const-qualified, it's an error.
435  // 2) If T is a POD and there's an empty initializer, the object is value-
436  //   initialized.
437  // 3) If T is a POD and there's one initializer argument, the object is copy-
438  //   constructed.
439  // 4) If T is a POD and there's more initializer arguments, it's an error.
440  // 5) If T is not a POD, the initializer arguments are used as constructor
441  //   arguments.
442  //
443  // Or by the C++0x formulation:
444  // 1) If there's no initializer, the object is default-initialized according
445  //    to C++0x rules.
446  // 2) Otherwise, the object is direct-initialized.
447  CXXConstructorDecl *Constructor = 0;
448  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
449  const RecordType *RT;
450  unsigned NumConsArgs = ConstructorArgs.size();
451  if (AllocType->isDependentType()) {
452    // Skip all the checks.
453  } else if ((RT = AllocType->getAs<RecordType>()) &&
454             !AllocType->isAggregateType()) {
455    ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
456
457    Constructor = PerformInitializationByConstructor(
458                      AllocType, move(ConstructorArgs),
459                      TypeLoc,
460                      SourceRange(TypeLoc, ConstructorRParen),
461                      RT->getDecl()->getDeclName(),
462                      NumConsArgs != 0 ? IK_Direct : IK_Default,
463                      ConvertedConstructorArgs);
464    if (!Constructor)
465      return ExprError();
466
467    // Take the converted constructor arguments and use them for the new
468    // expression.
469    NumConsArgs = ConvertedConstructorArgs.size();
470    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
471  } else {
472    if (!Init) {
473      // FIXME: Check that no subpart is const.
474      if (AllocType.isConstQualified())
475        return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
476                           << TypeRange);
477    } else if (NumConsArgs == 0) {
478      // Object is value-initialized. Do nothing.
479    } else if (NumConsArgs == 1) {
480      // Object is direct-initialized.
481      // FIXME: What DeclarationName do we pass in here?
482      if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
483                                DeclarationName() /*AllocType.getAsString()*/,
484                                /*DirectInit=*/true))
485        return ExprError();
486    } else {
487      return ExprError(Diag(StartLoc,
488                            diag::err_builtin_direct_init_more_than_one_arg)
489        << SourceRange(ConstructorLParen, ConstructorRParen));
490    }
491  }
492
493  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
494
495  PlacementArgs.release();
496  ConstructorArgs.release();
497  ArraySizeE.release();
498  return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
499                        NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
500                        ConsArgs, NumConsArgs, OperatorDelete, ResultType,
501                        StartLoc, Init ? ConstructorRParen : SourceLocation()));
502}
503
504/// CheckAllocatedType - Checks that a type is suitable as the allocated type
505/// in a new-expression.
506/// dimension off and stores the size expression in ArraySize.
507bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
508                              SourceRange R) {
509  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
510  //   abstract class type or array thereof.
511  if (AllocType->isFunctionType())
512    return Diag(Loc, diag::err_bad_new_type)
513      << AllocType << 0 << R;
514  else if (AllocType->isReferenceType())
515    return Diag(Loc, diag::err_bad_new_type)
516      << AllocType << 1 << R;
517  else if (!AllocType->isDependentType() &&
518           RequireCompleteType(Loc, AllocType,
519                               PDiag(diag::err_new_incomplete_type)
520                                 << R))
521    return true;
522  else if (RequireNonAbstractType(Loc, AllocType,
523                                  diag::err_allocation_of_abstract_type))
524    return true;
525
526  return false;
527}
528
529/// FindAllocationFunctions - Finds the overloads of operator new and delete
530/// that are appropriate for the allocation.
531bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
532                                   bool UseGlobal, QualType AllocType,
533                                   bool IsArray, Expr **PlaceArgs,
534                                   unsigned NumPlaceArgs,
535                                   FunctionDecl *&OperatorNew,
536                                   FunctionDecl *&OperatorDelete) {
537  // --- Choosing an allocation function ---
538  // C++ 5.3.4p8 - 14 & 18
539  // 1) If UseGlobal is true, only look in the global scope. Else, also look
540  //   in the scope of the allocated class.
541  // 2) If an array size is given, look for operator new[], else look for
542  //   operator new.
543  // 3) The first argument is always size_t. Append the arguments from the
544  //   placement form.
545  // FIXME: Also find the appropriate delete operator.
546
547  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
548  // We don't care about the actual value of this argument.
549  // FIXME: Should the Sema create the expression and embed it in the syntax
550  // tree? Or should the consumer just recalculate the value?
551  IntegerLiteral Size(llvm::APInt::getNullValue(
552                      Context.Target.getPointerWidth(0)),
553                      Context.getSizeType(),
554                      SourceLocation());
555  AllocArgs[0] = &Size;
556  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
557
558  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
559                                        IsArray ? OO_Array_New : OO_New);
560  if (AllocType->isRecordType() && !UseGlobal) {
561    CXXRecordDecl *Record
562      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
563    // FIXME: We fail to find inherited overloads.
564    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
565                          AllocArgs.size(), Record, /*AllowMissing=*/true,
566                          OperatorNew))
567      return true;
568  }
569  if (!OperatorNew) {
570    // Didn't find a member overload. Look for a global one.
571    DeclareGlobalNewDelete();
572    DeclContext *TUDecl = Context.getTranslationUnitDecl();
573    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
574                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
575                          OperatorNew))
576      return true;
577  }
578
579  // FindAllocationOverload can change the passed in arguments, so we need to
580  // copy them back.
581  if (NumPlaceArgs > 0)
582    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
583
584  return false;
585}
586
587/// FindAllocationOverload - Find an fitting overload for the allocation
588/// function in the specified scope.
589bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
590                                  DeclarationName Name, Expr** Args,
591                                  unsigned NumArgs, DeclContext *Ctx,
592                                  bool AllowMissing, FunctionDecl *&Operator) {
593  LookupResult R;
594  LookupQualifiedName(R, Ctx, Name, LookupOrdinaryName);
595  if (R.empty()) {
596    if (AllowMissing)
597      return false;
598    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
599      << Name << Range;
600  }
601
602  // FIXME: handle ambiguity
603
604  OverloadCandidateSet Candidates;
605  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
606       Alloc != AllocEnd; ++Alloc) {
607    // Even member operator new/delete are implicitly treated as
608    // static, so don't use AddMemberCandidate.
609    if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
610      AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
611                           /*SuppressUserConversions=*/false);
612      continue;
613    }
614
615    // FIXME: Handle function templates
616  }
617
618  // Do the resolution.
619  OverloadCandidateSet::iterator Best;
620  switch(BestViableFunction(Candidates, StartLoc, Best)) {
621  case OR_Success: {
622    // Got one!
623    FunctionDecl *FnDecl = Best->Function;
624    // The first argument is size_t, and the first parameter must be size_t,
625    // too. This is checked on declaration and can be assumed. (It can't be
626    // asserted on, though, since invalid decls are left in there.)
627    for (unsigned i = 0; i < NumArgs; ++i) {
628      // FIXME: Passing word to diagnostic.
629      if (PerformCopyInitialization(Args[i],
630                                    FnDecl->getParamDecl(i)->getType(),
631                                    "passing"))
632        return true;
633    }
634    Operator = FnDecl;
635    return false;
636  }
637
638  case OR_No_Viable_Function:
639    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
640      << Name << Range;
641    PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
642    return true;
643
644  case OR_Ambiguous:
645    Diag(StartLoc, diag::err_ovl_ambiguous_call)
646      << Name << Range;
647    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
648    return true;
649
650  case OR_Deleted:
651    Diag(StartLoc, diag::err_ovl_deleted_call)
652      << Best->Function->isDeleted()
653      << Name << Range;
654    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
655    return true;
656  }
657  assert(false && "Unreachable, bad result from BestViableFunction");
658  return true;
659}
660
661
662/// DeclareGlobalNewDelete - Declare the global forms of operator new and
663/// delete. These are:
664/// @code
665///   void* operator new(std::size_t) throw(std::bad_alloc);
666///   void* operator new[](std::size_t) throw(std::bad_alloc);
667///   void operator delete(void *) throw();
668///   void operator delete[](void *) throw();
669/// @endcode
670/// Note that the placement and nothrow forms of new are *not* implicitly
671/// declared. Their use requires including \<new\>.
672void Sema::DeclareGlobalNewDelete() {
673  if (GlobalNewDeleteDeclared)
674    return;
675
676  // C++ [basic.std.dynamic]p2:
677  //   [...] The following allocation and deallocation functions (18.4) are
678  //   implicitly declared in global scope in each translation unit of a
679  //   program
680  //
681  //     void* operator new(std::size_t) throw(std::bad_alloc);
682  //     void* operator new[](std::size_t) throw(std::bad_alloc);
683  //     void  operator delete(void*) throw();
684  //     void  operator delete[](void*) throw();
685  //
686  //   These implicit declarations introduce only the function names operator
687  //   new, operator new[], operator delete, operator delete[].
688  //
689  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
690  // "std" or "bad_alloc" as necessary to form the exception specification.
691  // However, we do not make these implicit declarations visible to name
692  // lookup.
693  if (!StdNamespace) {
694    // The "std" namespace has not yet been defined, so build one implicitly.
695    StdNamespace = NamespaceDecl::Create(Context,
696                                         Context.getTranslationUnitDecl(),
697                                         SourceLocation(),
698                                         &PP.getIdentifierTable().get("std"));
699    StdNamespace->setImplicit(true);
700  }
701
702  if (!StdBadAlloc) {
703    // The "std::bad_alloc" class has not yet been declared, so build it
704    // implicitly.
705    StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
706                                        StdNamespace,
707                                        SourceLocation(),
708                                      &PP.getIdentifierTable().get("bad_alloc"),
709                                        SourceLocation(), 0);
710    StdBadAlloc->setImplicit(true);
711  }
712
713  GlobalNewDeleteDeclared = true;
714
715  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
716  QualType SizeT = Context.getSizeType();
717
718  DeclareGlobalAllocationFunction(
719      Context.DeclarationNames.getCXXOperatorName(OO_New),
720      VoidPtr, SizeT);
721  DeclareGlobalAllocationFunction(
722      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
723      VoidPtr, SizeT);
724  DeclareGlobalAllocationFunction(
725      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
726      Context.VoidTy, VoidPtr);
727  DeclareGlobalAllocationFunction(
728      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
729      Context.VoidTy, VoidPtr);
730}
731
732/// DeclareGlobalAllocationFunction - Declares a single implicit global
733/// allocation function if it doesn't already exist.
734void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
735                                           QualType Return, QualType Argument) {
736  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
737
738  // Check if this function is already declared.
739  {
740    DeclContext::lookup_iterator Alloc, AllocEnd;
741    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
742         Alloc != AllocEnd; ++Alloc) {
743      // FIXME: Do we need to check for default arguments here?
744      FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
745      if (Func->getNumParams() == 1 &&
746          Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
747        return;
748    }
749  }
750
751  QualType BadAllocType;
752  bool HasBadAllocExceptionSpec
753    = (Name.getCXXOverloadedOperator() == OO_New ||
754       Name.getCXXOverloadedOperator() == OO_Array_New);
755  if (HasBadAllocExceptionSpec) {
756    assert(StdBadAlloc && "Must have std::bad_alloc declared");
757    BadAllocType = Context.getTypeDeclType(StdBadAlloc);
758  }
759
760  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
761                                            true, false,
762                                            HasBadAllocExceptionSpec? 1 : 0,
763                                            &BadAllocType);
764  FunctionDecl *Alloc =
765    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
766                         FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
767  Alloc->setImplicit();
768  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
769                                           0, Argument, /*DInfo=*/0,
770                                           VarDecl::None, 0);
771  Alloc->setParams(Context, &Param, 1);
772
773  // FIXME: Also add this declaration to the IdentifierResolver, but
774  // make sure it is at the end of the chain to coincide with the
775  // global scope.
776  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
777}
778
779/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
780/// @code ::delete ptr; @endcode
781/// or
782/// @code delete [] ptr; @endcode
783Action::OwningExprResult
784Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
785                     bool ArrayForm, ExprArg Operand) {
786  // C++ [expr.delete]p1:
787  //   The operand shall have a pointer type, or a class type having a single
788  //   conversion function to a pointer type. The result has type void.
789  //
790  // DR599 amends "pointer type" to "pointer to object type" in both cases.
791
792  FunctionDecl *OperatorDelete = 0;
793
794  Expr *Ex = (Expr *)Operand.get();
795  if (!Ex->isTypeDependent()) {
796    QualType Type = Ex->getType();
797
798    if (const RecordType *Record = Type->getAs<RecordType>()) {
799      llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
800      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
801      OverloadedFunctionDecl *Conversions =
802        RD->getVisibleConversionFunctions();
803
804      for (OverloadedFunctionDecl::function_iterator
805             Func = Conversions->function_begin(),
806             FuncEnd = Conversions->function_end();
807           Func != FuncEnd; ++Func) {
808        // Skip over templated conversion functions; they aren't considered.
809        if (isa<FunctionTemplateDecl>(*Func))
810          continue;
811
812        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
813
814        QualType ConvType = Conv->getConversionType().getNonReferenceType();
815        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
816          if (ConvPtrType->getPointeeType()->isObjectType())
817            ObjectPtrConversions.push_back(Conv);
818      }
819      if (ObjectPtrConversions.size() == 1) {
820        // We have a single conversion to a pointer-to-object type. Perform
821        // that conversion.
822        Operand.release();
823        if (!PerformImplicitConversion(Ex,
824                            ObjectPtrConversions.front()->getConversionType(),
825                                      "converting")) {
826          Operand = Owned(Ex);
827          Type = Ex->getType();
828        }
829      }
830      else if (ObjectPtrConversions.size() > 1) {
831        Diag(StartLoc, diag::err_ambiguous_delete_operand)
832              << Type << Ex->getSourceRange();
833        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
834          CXXConversionDecl *Conv = ObjectPtrConversions[i];
835          Diag(Conv->getLocation(), diag::err_ovl_candidate);
836        }
837        return ExprError();
838      }
839    }
840
841    if (!Type->isPointerType())
842      return ExprError(Diag(StartLoc, diag::err_delete_operand)
843        << Type << Ex->getSourceRange());
844
845    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
846    if (Pointee->isFunctionType() || Pointee->isVoidType())
847      return ExprError(Diag(StartLoc, diag::err_delete_operand)
848        << Type << Ex->getSourceRange());
849    else if (!Pointee->isDependentType() &&
850             RequireCompleteType(StartLoc, Pointee,
851                                 PDiag(diag::warn_delete_incomplete)
852                                   << Ex->getSourceRange()))
853      return ExprError();
854
855    // C++ [expr.delete]p2:
856    //   [Note: a pointer to a const type can be the operand of a
857    //   delete-expression; it is not necessary to cast away the constness
858    //   (5.2.11) of the pointer expression before it is used as the operand
859    //   of the delete-expression. ]
860    ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
861                      CastExpr::CK_NoOp);
862
863    // Update the operand.
864    Operand.take();
865    Operand = ExprArg(*this, Ex);
866
867    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
868                                      ArrayForm ? OO_Array_Delete : OO_Delete);
869
870    if (Pointee->isRecordType() && !UseGlobal) {
871      CXXRecordDecl *Record
872        = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
873
874      // Try to find operator delete/operator delete[] in class scope.
875      LookupResult Found;
876      LookupQualifiedName(Found, Record, DeleteName, LookupOrdinaryName);
877      // FIXME: Diagnose ambiguity properly
878      assert(!Found.isAmbiguous() && "Ambiguous delete/delete[] not handled");
879      for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
880           F != FEnd; ++F) {
881        if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
882          if (Delete->isUsualDeallocationFunction()) {
883            OperatorDelete = Delete;
884            break;
885          }
886      }
887
888      if (!Record->hasTrivialDestructor())
889        if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
890          MarkDeclarationReferenced(StartLoc,
891                                    const_cast<CXXDestructorDecl*>(Dtor));
892    }
893
894    if (!OperatorDelete) {
895      // Didn't find a member overload. Look for a global one.
896      DeclareGlobalNewDelete();
897      DeclContext *TUDecl = Context.getTranslationUnitDecl();
898      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
899                                 &Ex, 1, TUDecl, /*AllowMissing=*/false,
900                                 OperatorDelete))
901        return ExprError();
902    }
903
904    // FIXME: Check access and ambiguity of operator delete and destructor.
905  }
906
907  Operand.release();
908  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
909                                           OperatorDelete, Ex, StartLoc));
910}
911
912
913/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
914/// C++ if/switch/while/for statement.
915/// e.g: "if (int x = f()) {...}"
916Action::OwningExprResult
917Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
918                                       Declarator &D,
919                                       SourceLocation EqualLoc,
920                                       ExprArg AssignExprVal) {
921  assert(AssignExprVal.get() && "Null assignment expression");
922
923  // C++ 6.4p2:
924  // The declarator shall not specify a function or an array.
925  // The type-specifier-seq shall not contain typedef and shall not declare a
926  // new class or enumeration.
927
928  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
929         "Parser allowed 'typedef' as storage class of condition decl.");
930
931  // FIXME: Store DeclaratorInfo in the expression.
932  DeclaratorInfo *DInfo = 0;
933  TagDecl *OwnedTag = 0;
934  QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
935
936  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
937    // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
938    // would be created and CXXConditionDeclExpr wants a VarDecl.
939    return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
940      << SourceRange(StartLoc, EqualLoc));
941  } else if (Ty->isArrayType()) { // ...or an array.
942    Diag(StartLoc, diag::err_invalid_use_of_array_type)
943      << SourceRange(StartLoc, EqualLoc);
944  } else if (OwnedTag && OwnedTag->isDefinition()) {
945    // The type-specifier-seq shall not declare a new class or enumeration.
946    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
947  }
948
949  DeclPtrTy Dcl = ActOnDeclarator(S, D);
950  if (!Dcl)
951    return ExprError();
952  AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
953
954  // Mark this variable as one that is declared within a conditional.
955  // We know that the decl had to be a VarDecl because that is the only type of
956  // decl that can be assigned and the grammar requires an '='.
957  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
958  VD->setDeclaredInCondition(true);
959  return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
960}
961
962/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
963bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
964  // C++ 6.4p4:
965  // The value of a condition that is an initialized declaration in a statement
966  // other than a switch statement is the value of the declared variable
967  // implicitly converted to type bool. If that conversion is ill-formed, the
968  // program is ill-formed.
969  // The value of a condition that is an expression is the value of the
970  // expression, implicitly converted to bool.
971  //
972  return PerformContextuallyConvertToBool(CondExpr);
973}
974
975/// Helper function to determine whether this is the (deprecated) C++
976/// conversion from a string literal to a pointer to non-const char or
977/// non-const wchar_t (for narrow and wide string literals,
978/// respectively).
979bool
980Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
981  // Look inside the implicit cast, if it exists.
982  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
983    From = Cast->getSubExpr();
984
985  // A string literal (2.13.4) that is not a wide string literal can
986  // be converted to an rvalue of type "pointer to char"; a wide
987  // string literal can be converted to an rvalue of type "pointer
988  // to wchar_t" (C++ 4.2p2).
989  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
990    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
991      if (const BuiltinType *ToPointeeType
992          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
993        // This conversion is considered only when there is an
994        // explicit appropriate pointer target type (C++ 4.2p2).
995        if (!ToPtrType->getPointeeType().hasQualifiers() &&
996            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
997             (!StrLit->isWide() &&
998              (ToPointeeType->getKind() == BuiltinType::Char_U ||
999               ToPointeeType->getKind() == BuiltinType::Char_S))))
1000          return true;
1001      }
1002
1003  return false;
1004}
1005
1006/// PerformImplicitConversion - Perform an implicit conversion of the
1007/// expression From to the type ToType. Returns true if there was an
1008/// error, false otherwise. The expression From is replaced with the
1009/// converted expression. Flavor is the kind of conversion we're
1010/// performing, used in the error message. If @p AllowExplicit,
1011/// explicit user-defined conversions are permitted. @p Elidable should be true
1012/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1013/// resolution works differently in that case.
1014bool
1015Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1016                                const char *Flavor, bool AllowExplicit,
1017                                bool Elidable) {
1018  ImplicitConversionSequence ICS;
1019  return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1020                                   Elidable, ICS);
1021}
1022
1023bool
1024Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1025                                const char *Flavor, bool AllowExplicit,
1026                                bool Elidable,
1027                                ImplicitConversionSequence& ICS) {
1028  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1029  if (Elidable && getLangOptions().CPlusPlus0x) {
1030    ICS = TryImplicitConversion(From, ToType,
1031                                /*SuppressUserConversions=*/false,
1032                                AllowExplicit,
1033                                /*ForceRValue=*/true,
1034                                /*InOverloadResolution=*/false);
1035  }
1036  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
1037    ICS = TryImplicitConversion(From, ToType,
1038                                /*SuppressUserConversions=*/false,
1039                                AllowExplicit,
1040                                /*ForceRValue=*/false,
1041                                /*InOverloadResolution=*/false);
1042  }
1043  return PerformImplicitConversion(From, ToType, ICS, Flavor);
1044}
1045
1046/// BuildCXXDerivedToBaseExpr - This routine generates the suitable AST
1047/// for the derived to base conversion of the expression 'From'. All
1048/// necessary information is passed in ICS.
1049bool
1050Sema::BuildCXXDerivedToBaseExpr(Expr *&From, CastExpr::CastKind CastKind,
1051                                     const ImplicitConversionSequence& ICS,
1052                                     const char *Flavor) {
1053  QualType  BaseType =
1054    QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1055  // Must do additional defined to base conversion.
1056  QualType  DerivedType =
1057    QualType::getFromOpaquePtr(ICS.UserDefined.After.FromTypePtr);
1058
1059  From = new (Context) ImplicitCastExpr(
1060                                        DerivedType.getNonReferenceType(),
1061                                        CastKind,
1062                                        From,
1063                                        DerivedType->isLValueReferenceType());
1064  From = new (Context) ImplicitCastExpr(BaseType.getNonReferenceType(),
1065                                        CastExpr::CK_DerivedToBase, From,
1066                                        BaseType->isLValueReferenceType());
1067  ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1068  OwningExprResult FromResult =
1069  BuildCXXConstructExpr(
1070                        ICS.UserDefined.After.CopyConstructor->getLocation(),
1071                        BaseType,
1072                        ICS.UserDefined.After.CopyConstructor,
1073                        MultiExprArg(*this, (void **)&From, 1));
1074  if (FromResult.isInvalid())
1075    return true;
1076  From = FromResult.takeAs<Expr>();
1077  return false;
1078}
1079
1080/// PerformImplicitConversion - Perform an implicit conversion of the
1081/// expression From to the type ToType using the pre-computed implicit
1082/// conversion sequence ICS. Returns true if there was an error, false
1083/// otherwise. The expression From is replaced with the converted
1084/// expression. Flavor is the kind of conversion we're performing,
1085/// used in the error message.
1086bool
1087Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1088                                const ImplicitConversionSequence &ICS,
1089                                const char* Flavor) {
1090  switch (ICS.ConversionKind) {
1091  case ImplicitConversionSequence::StandardConversion:
1092    if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
1093      return true;
1094    break;
1095
1096  case ImplicitConversionSequence::UserDefinedConversion: {
1097
1098      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1099      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
1100      QualType BeforeToType;
1101      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1102        CastKind = CastExpr::CK_UserDefinedConversion;
1103
1104        // If the user-defined conversion is specified by a conversion function,
1105        // the initial standard conversion sequence converts the source type to
1106        // the implicit object parameter of the conversion function.
1107        BeforeToType = Context.getTagDeclType(Conv->getParent());
1108      } else if (const CXXConstructorDecl *Ctor =
1109                  dyn_cast<CXXConstructorDecl>(FD)) {
1110        CastKind = CastExpr::CK_ConstructorConversion;
1111
1112        // If the user-defined conversion is specified by a constructor, the
1113        // initial standard conversion sequence converts the source type to the
1114        // type required by the argument of the constructor
1115        BeforeToType = Ctor->getParamDecl(0)->getType();
1116      }
1117      else
1118        assert(0 && "Unknown conversion function kind!");
1119
1120      if (PerformImplicitConversion(From, BeforeToType,
1121                                    ICS.UserDefined.Before, "converting"))
1122        return true;
1123
1124      OwningExprResult CastArg
1125        = BuildCXXCastArgument(From->getLocStart(),
1126                               ToType.getNonReferenceType(),
1127                               CastKind, cast<CXXMethodDecl>(FD),
1128                               Owned(From));
1129
1130      if (CastArg.isInvalid())
1131        return true;
1132
1133      if (ICS.UserDefined.After.Second == ICK_Derived_To_Base &&
1134          ICS.UserDefined.After.CopyConstructor) {
1135        From = CastArg.takeAs<Expr>();
1136        return BuildCXXDerivedToBaseExpr(From, CastKind, ICS, Flavor);
1137      }
1138
1139      From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1140                                            CastKind, CastArg.takeAs<Expr>(),
1141                                            ToType->isLValueReferenceType());
1142      return false;
1143  }
1144
1145  case ImplicitConversionSequence::EllipsisConversion:
1146    assert(false && "Cannot perform an ellipsis conversion");
1147    return false;
1148
1149  case ImplicitConversionSequence::BadConversion:
1150    return true;
1151  }
1152
1153  // Everything went well.
1154  return false;
1155}
1156
1157/// PerformImplicitConversion - Perform an implicit conversion of the
1158/// expression From to the type ToType by following the standard
1159/// conversion sequence SCS. Returns true if there was an error, false
1160/// otherwise. The expression From is replaced with the converted
1161/// expression. Flavor is the context in which we're performing this
1162/// conversion, for use in error messages.
1163bool
1164Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1165                                const StandardConversionSequence& SCS,
1166                                const char *Flavor) {
1167  // Overall FIXME: we are recomputing too many types here and doing far too
1168  // much extra work. What this means is that we need to keep track of more
1169  // information that is computed when we try the implicit conversion initially,
1170  // so that we don't need to recompute anything here.
1171  QualType FromType = From->getType();
1172
1173  if (SCS.CopyConstructor) {
1174    // FIXME: When can ToType be a reference type?
1175    assert(!ToType->isReferenceType());
1176    if (SCS.Second == ICK_Derived_To_Base) {
1177      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1178      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1179                                  MultiExprArg(*this, (void **)&From, 1),
1180                                  /*FIXME:ConstructLoc*/SourceLocation(),
1181                                  ConstructorArgs))
1182        return true;
1183      OwningExprResult FromResult =
1184        BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1185                              ToType, SCS.CopyConstructor,
1186                              move_arg(ConstructorArgs));
1187      if (FromResult.isInvalid())
1188        return true;
1189      From = FromResult.takeAs<Expr>();
1190      return false;
1191    }
1192    OwningExprResult FromResult =
1193      BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1194                            ToType, SCS.CopyConstructor,
1195                            MultiExprArg(*this, (void**)&From, 1));
1196
1197    if (FromResult.isInvalid())
1198      return true;
1199
1200    From = FromResult.takeAs<Expr>();
1201    return false;
1202  }
1203
1204  // Perform the first implicit conversion.
1205  switch (SCS.First) {
1206  case ICK_Identity:
1207  case ICK_Lvalue_To_Rvalue:
1208    // Nothing to do.
1209    break;
1210
1211  case ICK_Array_To_Pointer:
1212    FromType = Context.getArrayDecayedType(FromType);
1213    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
1214    break;
1215
1216  case ICK_Function_To_Pointer:
1217    if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
1218      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1219      if (!Fn)
1220        return true;
1221
1222      if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1223        return true;
1224
1225      bool WasAddrOf = FixOverloadedFunctionReference(From, Fn);
1226      FromType = From->getType();
1227      // If there's already an address-of operator in the expression, we have
1228      // the right type already, and the code below would just introduce an
1229      // invalid additional pointer level.
1230      if (WasAddrOf)
1231        break;
1232    }
1233    FromType = Context.getPointerType(FromType);
1234    ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
1235    break;
1236
1237  default:
1238    assert(false && "Improper first standard conversion");
1239    break;
1240  }
1241
1242  // Perform the second implicit conversion
1243  switch (SCS.Second) {
1244  case ICK_Identity:
1245    // If both sides are functions (or pointers/references to them), there could
1246    // be incompatible exception declarations.
1247    if (CheckExceptionSpecCompatibility(From, ToType))
1248      return true;
1249    // Nothing else to do.
1250    break;
1251
1252  case ICK_Integral_Promotion:
1253  case ICK_Floating_Promotion:
1254  case ICK_Complex_Promotion:
1255  case ICK_Integral_Conversion:
1256  case ICK_Floating_Conversion:
1257  case ICK_Complex_Conversion:
1258  case ICK_Floating_Integral:
1259  case ICK_Complex_Real:
1260  case ICK_Compatible_Conversion:
1261      // FIXME: Go deeper to get the unqualified type!
1262    FromType = ToType.getUnqualifiedType();
1263    ImpCastExprToType(From, FromType);
1264    break;
1265
1266  case ICK_Pointer_Conversion: {
1267    if (SCS.IncompatibleObjC) {
1268      // Diagnose incompatible Objective-C conversions
1269      Diag(From->getSourceRange().getBegin(),
1270           diag::ext_typecheck_convert_incompatible_pointer)
1271        << From->getType() << ToType << Flavor
1272        << From->getSourceRange();
1273    }
1274
1275
1276    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1277    if (CheckPointerConversion(From, ToType, Kind))
1278      return true;
1279    ImpCastExprToType(From, ToType, Kind);
1280    break;
1281  }
1282
1283  case ICK_Pointer_Member: {
1284    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1285    if (CheckMemberPointerConversion(From, ToType, Kind))
1286      return true;
1287    if (CheckExceptionSpecCompatibility(From, ToType))
1288      return true;
1289    ImpCastExprToType(From, ToType, Kind);
1290    break;
1291  }
1292  case ICK_Boolean_Conversion:
1293    FromType = Context.BoolTy;
1294    ImpCastExprToType(From, FromType);
1295    break;
1296
1297  default:
1298    assert(false && "Improper second standard conversion");
1299    break;
1300  }
1301
1302  switch (SCS.Third) {
1303  case ICK_Identity:
1304    // Nothing to do.
1305    break;
1306
1307  case ICK_Qualification:
1308    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1309    // references.
1310    ImpCastExprToType(From, ToType.getNonReferenceType(),
1311                      CastExpr::CK_Unknown,
1312                      ToType->isLValueReferenceType());
1313    break;
1314
1315  default:
1316    assert(false && "Improper second standard conversion");
1317    break;
1318  }
1319
1320  return false;
1321}
1322
1323Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1324                                                 SourceLocation KWLoc,
1325                                                 SourceLocation LParen,
1326                                                 TypeTy *Ty,
1327                                                 SourceLocation RParen) {
1328  QualType T = GetTypeFromParser(Ty);
1329
1330  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1331  // all traits except __is_class, __is_enum and __is_union require a the type
1332  // to be complete.
1333  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1334    if (RequireCompleteType(KWLoc, T,
1335                            diag::err_incomplete_type_used_in_type_trait_expr))
1336      return ExprError();
1337  }
1338
1339  // There is no point in eagerly computing the value. The traits are designed
1340  // to be used from type trait templates, so Ty will be a template parameter
1341  // 99% of the time.
1342  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1343                                                RParen, Context.BoolTy));
1344}
1345
1346QualType Sema::CheckPointerToMemberOperands(
1347  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1348  const char *OpSpelling = isIndirect ? "->*" : ".*";
1349  // C++ 5.5p2
1350  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1351  //   be of type "pointer to member of T" (where T is a completely-defined
1352  //   class type) [...]
1353  QualType RType = rex->getType();
1354  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1355  if (!MemPtr) {
1356    Diag(Loc, diag::err_bad_memptr_rhs)
1357      << OpSpelling << RType << rex->getSourceRange();
1358    return QualType();
1359  }
1360
1361  QualType Class(MemPtr->getClass(), 0);
1362
1363  // C++ 5.5p2
1364  //   [...] to its first operand, which shall be of class T or of a class of
1365  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1366  //   such a class]
1367  QualType LType = lex->getType();
1368  if (isIndirect) {
1369    if (const PointerType *Ptr = LType->getAs<PointerType>())
1370      LType = Ptr->getPointeeType().getNonReferenceType();
1371    else {
1372      Diag(Loc, diag::err_bad_memptr_lhs)
1373        << OpSpelling << 1 << LType << lex->getSourceRange();
1374      return QualType();
1375    }
1376  }
1377
1378  if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1379      Context.getCanonicalType(LType).getUnqualifiedType()) {
1380    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1381                       /*DetectVirtual=*/false);
1382    // FIXME: Would it be useful to print full ambiguity paths, or is that
1383    // overkill?
1384    if (!IsDerivedFrom(LType, Class, Paths) ||
1385        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1386      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1387        << (int)isIndirect << lex->getType() << lex->getSourceRange();
1388      return QualType();
1389    }
1390  }
1391
1392  // C++ 5.5p2
1393  //   The result is an object or a function of the type specified by the
1394  //   second operand.
1395  // The cv qualifiers are the union of those in the pointer and the left side,
1396  // in accordance with 5.5p5 and 5.2.5.
1397  // FIXME: This returns a dereferenced member function pointer as a normal
1398  // function type. However, the only operation valid on such functions is
1399  // calling them. There's also a GCC extension to get a function pointer to the
1400  // thing, which is another complication, because this type - unlike the type
1401  // that is the result of this expression - takes the class as the first
1402  // argument.
1403  // We probably need a "MemberFunctionClosureType" or something like that.
1404  QualType Result = MemPtr->getPointeeType();
1405  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
1406  return Result;
1407}
1408
1409/// \brief Get the target type of a standard or user-defined conversion.
1410static QualType TargetType(const ImplicitConversionSequence &ICS) {
1411  assert((ICS.ConversionKind ==
1412              ImplicitConversionSequence::StandardConversion ||
1413          ICS.ConversionKind ==
1414              ImplicitConversionSequence::UserDefinedConversion) &&
1415         "function only valid for standard or user-defined conversions");
1416  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1417    return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1418  return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1419}
1420
1421/// \brief Try to convert a type to another according to C++0x 5.16p3.
1422///
1423/// This is part of the parameter validation for the ? operator. If either
1424/// value operand is a class type, the two operands are attempted to be
1425/// converted to each other. This function does the conversion in one direction.
1426/// It emits a diagnostic and returns true only if it finds an ambiguous
1427/// conversion.
1428static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1429                                SourceLocation QuestionLoc,
1430                                ImplicitConversionSequence &ICS) {
1431  // C++0x 5.16p3
1432  //   The process for determining whether an operand expression E1 of type T1
1433  //   can be converted to match an operand expression E2 of type T2 is defined
1434  //   as follows:
1435  //   -- If E2 is an lvalue:
1436  if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1437    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1438    //   type "lvalue reference to T2", subject to the constraint that in the
1439    //   conversion the reference must bind directly to E1.
1440    if (!Self.CheckReferenceInit(From,
1441                            Self.Context.getLValueReferenceType(To->getType()),
1442                                 To->getLocStart(),
1443                                 /*SuppressUserConversions=*/false,
1444                                 /*AllowExplicit=*/false,
1445                                 /*ForceRValue=*/false,
1446                                 &ICS))
1447    {
1448      assert((ICS.ConversionKind ==
1449                  ImplicitConversionSequence::StandardConversion ||
1450              ICS.ConversionKind ==
1451                  ImplicitConversionSequence::UserDefinedConversion) &&
1452             "expected a definite conversion");
1453      bool DirectBinding =
1454        ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1455        ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1456      if (DirectBinding)
1457        return false;
1458    }
1459  }
1460  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1461  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1462  //      -- if E1 and E2 have class type, and the underlying class types are
1463  //         the same or one is a base class of the other:
1464  QualType FTy = From->getType();
1465  QualType TTy = To->getType();
1466  const RecordType *FRec = FTy->getAs<RecordType>();
1467  const RecordType *TRec = TTy->getAs<RecordType>();
1468  bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1469  if (FRec && TRec && (FRec == TRec ||
1470        FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1471    //         E1 can be converted to match E2 if the class of T2 is the
1472    //         same type as, or a base class of, the class of T1, and
1473    //         [cv2 > cv1].
1474    if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1475      // Could still fail if there's no copy constructor.
1476      // FIXME: Is this a hard error then, or just a conversion failure? The
1477      // standard doesn't say.
1478      ICS = Self.TryCopyInitialization(From, TTy,
1479                                       /*SuppressUserConversions=*/false,
1480                                       /*ForceRValue=*/false,
1481                                       /*InOverloadResolution=*/false);
1482    }
1483  } else {
1484    //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1485    //        implicitly converted to the type that expression E2 would have
1486    //        if E2 were converted to an rvalue.
1487    // First find the decayed type.
1488    if (TTy->isFunctionType())
1489      TTy = Self.Context.getPointerType(TTy);
1490    else if (TTy->isArrayType())
1491      TTy = Self.Context.getArrayDecayedType(TTy);
1492
1493    // Now try the implicit conversion.
1494    // FIXME: This doesn't detect ambiguities.
1495    ICS = Self.TryImplicitConversion(From, TTy,
1496                                     /*SuppressUserConversions=*/false,
1497                                     /*AllowExplicit=*/false,
1498                                     /*ForceRValue=*/false,
1499                                     /*InOverloadResolution=*/false);
1500  }
1501  return false;
1502}
1503
1504/// \brief Try to find a common type for two according to C++0x 5.16p5.
1505///
1506/// This is part of the parameter validation for the ? operator. If either
1507/// value operand is a class type, overload resolution is used to find a
1508/// conversion to a common type.
1509static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1510                                    SourceLocation Loc) {
1511  Expr *Args[2] = { LHS, RHS };
1512  OverloadCandidateSet CandidateSet;
1513  Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1514
1515  OverloadCandidateSet::iterator Best;
1516  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
1517    case Sema::OR_Success:
1518      // We found a match. Perform the conversions on the arguments and move on.
1519      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1520                                         Best->Conversions[0], "converting") ||
1521          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1522                                         Best->Conversions[1], "converting"))
1523        break;
1524      return false;
1525
1526    case Sema::OR_No_Viable_Function:
1527      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1528        << LHS->getType() << RHS->getType()
1529        << LHS->getSourceRange() << RHS->getSourceRange();
1530      return true;
1531
1532    case Sema::OR_Ambiguous:
1533      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1534        << LHS->getType() << RHS->getType()
1535        << LHS->getSourceRange() << RHS->getSourceRange();
1536      // FIXME: Print the possible common types by printing the return types of
1537      // the viable candidates.
1538      break;
1539
1540    case Sema::OR_Deleted:
1541      assert(false && "Conditional operator has only built-in overloads");
1542      break;
1543  }
1544  return true;
1545}
1546
1547/// \brief Perform an "extended" implicit conversion as returned by
1548/// TryClassUnification.
1549///
1550/// TryClassUnification generates ICSs that include reference bindings.
1551/// PerformImplicitConversion is not suitable for this; it chokes if the
1552/// second part of a standard conversion is ICK_DerivedToBase. This function
1553/// handles the reference binding specially.
1554static bool ConvertForConditional(Sema &Self, Expr *&E,
1555                                  const ImplicitConversionSequence &ICS) {
1556  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1557      ICS.Standard.ReferenceBinding) {
1558    assert(ICS.Standard.DirectBinding &&
1559           "TryClassUnification should never generate indirect ref bindings");
1560    // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1561    // redoing all the work.
1562    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1563                                        TargetType(ICS)),
1564                                   /*FIXME:*/E->getLocStart(),
1565                                   /*SuppressUserConversions=*/false,
1566                                   /*AllowExplicit=*/false,
1567                                   /*ForceRValue=*/false);
1568  }
1569  if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1570      ICS.UserDefined.After.ReferenceBinding) {
1571    assert(ICS.UserDefined.After.DirectBinding &&
1572           "TryClassUnification should never generate indirect ref bindings");
1573    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1574                                        TargetType(ICS)),
1575                                   /*FIXME:*/E->getLocStart(),
1576                                   /*SuppressUserConversions=*/false,
1577                                   /*AllowExplicit=*/false,
1578                                   /*ForceRValue=*/false);
1579  }
1580  if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1581    return true;
1582  return false;
1583}
1584
1585/// \brief Check the operands of ?: under C++ semantics.
1586///
1587/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1588/// extension. In this case, LHS == Cond. (But they're not aliases.)
1589QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1590                                           SourceLocation QuestionLoc) {
1591  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1592  // interface pointers.
1593
1594  // C++0x 5.16p1
1595  //   The first expression is contextually converted to bool.
1596  if (!Cond->isTypeDependent()) {
1597    if (CheckCXXBooleanCondition(Cond))
1598      return QualType();
1599  }
1600
1601  // Either of the arguments dependent?
1602  if (LHS->isTypeDependent() || RHS->isTypeDependent())
1603    return Context.DependentTy;
1604
1605  // C++0x 5.16p2
1606  //   If either the second or the third operand has type (cv) void, ...
1607  QualType LTy = LHS->getType();
1608  QualType RTy = RHS->getType();
1609  bool LVoid = LTy->isVoidType();
1610  bool RVoid = RTy->isVoidType();
1611  if (LVoid || RVoid) {
1612    //   ... then the [l2r] conversions are performed on the second and third
1613    //   operands ...
1614    DefaultFunctionArrayConversion(LHS);
1615    DefaultFunctionArrayConversion(RHS);
1616    LTy = LHS->getType();
1617    RTy = RHS->getType();
1618
1619    //   ... and one of the following shall hold:
1620    //   -- The second or the third operand (but not both) is a throw-
1621    //      expression; the result is of the type of the other and is an rvalue.
1622    bool LThrow = isa<CXXThrowExpr>(LHS);
1623    bool RThrow = isa<CXXThrowExpr>(RHS);
1624    if (LThrow && !RThrow)
1625      return RTy;
1626    if (RThrow && !LThrow)
1627      return LTy;
1628
1629    //   -- Both the second and third operands have type void; the result is of
1630    //      type void and is an rvalue.
1631    if (LVoid && RVoid)
1632      return Context.VoidTy;
1633
1634    // Neither holds, error.
1635    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1636      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1637      << LHS->getSourceRange() << RHS->getSourceRange();
1638    return QualType();
1639  }
1640
1641  // Neither is void.
1642
1643  // C++0x 5.16p3
1644  //   Otherwise, if the second and third operand have different types, and
1645  //   either has (cv) class type, and attempt is made to convert each of those
1646  //   operands to the other.
1647  if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1648      (LTy->isRecordType() || RTy->isRecordType())) {
1649    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1650    // These return true if a single direction is already ambiguous.
1651    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1652      return QualType();
1653    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1654      return QualType();
1655
1656    bool HaveL2R = ICSLeftToRight.ConversionKind !=
1657      ImplicitConversionSequence::BadConversion;
1658    bool HaveR2L = ICSRightToLeft.ConversionKind !=
1659      ImplicitConversionSequence::BadConversion;
1660    //   If both can be converted, [...] the program is ill-formed.
1661    if (HaveL2R && HaveR2L) {
1662      Diag(QuestionLoc, diag::err_conditional_ambiguous)
1663        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1664      return QualType();
1665    }
1666
1667    //   If exactly one conversion is possible, that conversion is applied to
1668    //   the chosen operand and the converted operands are used in place of the
1669    //   original operands for the remainder of this section.
1670    if (HaveL2R) {
1671      if (ConvertForConditional(*this, LHS, ICSLeftToRight))
1672        return QualType();
1673      LTy = LHS->getType();
1674    } else if (HaveR2L) {
1675      if (ConvertForConditional(*this, RHS, ICSRightToLeft))
1676        return QualType();
1677      RTy = RHS->getType();
1678    }
1679  }
1680
1681  // C++0x 5.16p4
1682  //   If the second and third operands are lvalues and have the same type,
1683  //   the result is of that type [...]
1684  bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1685  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1686      RHS->isLvalue(Context) == Expr::LV_Valid)
1687    return LTy;
1688
1689  // C++0x 5.16p5
1690  //   Otherwise, the result is an rvalue. If the second and third operands
1691  //   do not have the same type, and either has (cv) class type, ...
1692  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1693    //   ... overload resolution is used to determine the conversions (if any)
1694    //   to be applied to the operands. If the overload resolution fails, the
1695    //   program is ill-formed.
1696    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1697      return QualType();
1698  }
1699
1700  // C++0x 5.16p6
1701  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1702  //   conversions are performed on the second and third operands.
1703  DefaultFunctionArrayConversion(LHS);
1704  DefaultFunctionArrayConversion(RHS);
1705  LTy = LHS->getType();
1706  RTy = RHS->getType();
1707
1708  //   After those conversions, one of the following shall hold:
1709  //   -- The second and third operands have the same type; the result
1710  //      is of that type.
1711  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1712    return LTy;
1713
1714  //   -- The second and third operands have arithmetic or enumeration type;
1715  //      the usual arithmetic conversions are performed to bring them to a
1716  //      common type, and the result is of that type.
1717  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1718    UsualArithmeticConversions(LHS, RHS);
1719    return LHS->getType();
1720  }
1721
1722  //   -- The second and third operands have pointer type, or one has pointer
1723  //      type and the other is a null pointer constant; pointer conversions
1724  //      and qualification conversions are performed to bring them to their
1725  //      composite pointer type. The result is of the composite pointer type.
1726  QualType Composite = FindCompositePointerType(LHS, RHS);
1727  if (!Composite.isNull())
1728    return Composite;
1729
1730  // Fourth bullet is same for pointers-to-member. However, the possible
1731  // conversions are far more limited: we have null-to-pointer, upcast of
1732  // containing class, and second-level cv-ness.
1733  // cv-ness is not a union, but must match one of the two operands. (Which,
1734  // frankly, is stupid.)
1735  const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1736  const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
1737  if (LMemPtr &&
1738      RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1739    ImpCastExprToType(RHS, LTy);
1740    return LTy;
1741  }
1742  if (RMemPtr &&
1743      LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1744    ImpCastExprToType(LHS, RTy);
1745    return RTy;
1746  }
1747  if (LMemPtr && RMemPtr) {
1748    QualType LPointee = LMemPtr->getPointeeType();
1749    QualType RPointee = RMemPtr->getPointeeType();
1750
1751    QualifierCollector LPQuals, RPQuals;
1752    const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1753    const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1754
1755    // First, we check that the unqualified pointee type is the same. If it's
1756    // not, there's no conversion that will unify the two pointers.
1757    if (LPCan == RPCan) {
1758
1759      // Second, we take the greater of the two qualifications. If neither
1760      // is greater than the other, the conversion is not possible.
1761
1762      Qualifiers MergedQuals = LPQuals + RPQuals;
1763
1764      bool CompatibleQuals = true;
1765      if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1766          MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1767        CompatibleQuals = false;
1768      else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1769        // FIXME:
1770        // C99 6.5.15 as modified by TR 18037:
1771        //   If the second and third operands are pointers into different
1772        //   address spaces, the address spaces must overlap.
1773        CompatibleQuals = false;
1774      // FIXME: GC qualifiers?
1775
1776      if (CompatibleQuals) {
1777        // Third, we check if either of the container classes is derived from
1778        // the other.
1779        QualType LContainer(LMemPtr->getClass(), 0);
1780        QualType RContainer(RMemPtr->getClass(), 0);
1781        QualType MoreDerived;
1782        if (Context.getCanonicalType(LContainer) ==
1783            Context.getCanonicalType(RContainer))
1784          MoreDerived = LContainer;
1785        else if (IsDerivedFrom(LContainer, RContainer))
1786          MoreDerived = LContainer;
1787        else if (IsDerivedFrom(RContainer, LContainer))
1788          MoreDerived = RContainer;
1789
1790        if (!MoreDerived.isNull()) {
1791          // The type 'Q Pointee (MoreDerived::*)' is the common type.
1792          // We don't use ImpCastExprToType here because this could still fail
1793          // for ambiguous or inaccessible conversions.
1794          LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1795          QualType Common
1796            = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
1797          if (PerformImplicitConversion(LHS, Common, "converting"))
1798            return QualType();
1799          if (PerformImplicitConversion(RHS, Common, "converting"))
1800            return QualType();
1801          return Common;
1802        }
1803      }
1804    }
1805  }
1806
1807  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1808    << LHS->getType() << RHS->getType()
1809    << LHS->getSourceRange() << RHS->getSourceRange();
1810  return QualType();
1811}
1812
1813/// \brief Find a merged pointer type and convert the two expressions to it.
1814///
1815/// This finds the composite pointer type (or member pointer type) for @p E1
1816/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1817/// type and returns it.
1818/// It does not emit diagnostics.
1819QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1820  assert(getLangOptions().CPlusPlus && "This function assumes C++");
1821  QualType T1 = E1->getType(), T2 = E2->getType();
1822
1823  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1824      !T2->isPointerType() && !T2->isMemberPointerType())
1825   return QualType();
1826
1827  // FIXME: Do we need to work on the canonical types?
1828
1829  // C++0x 5.9p2
1830  //   Pointer conversions and qualification conversions are performed on
1831  //   pointer operands to bring them to their composite pointer type. If
1832  //   one operand is a null pointer constant, the composite pointer type is
1833  //   the type of the other operand.
1834  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1835    ImpCastExprToType(E1, T2);
1836    return T2;
1837  }
1838  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1839    ImpCastExprToType(E2, T1);
1840    return T1;
1841  }
1842
1843  // Now both have to be pointers or member pointers.
1844  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1845      !T2->isPointerType() && !T2->isMemberPointerType())
1846    return QualType();
1847
1848  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
1849  //   the other has type "pointer to cv2 T" and the composite pointer type is
1850  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1851  //   Otherwise, the composite pointer type is a pointer type similar to the
1852  //   type of one of the operands, with a cv-qualification signature that is
1853  //   the union of the cv-qualification signatures of the operand types.
1854  // In practice, the first part here is redundant; it's subsumed by the second.
1855  // What we do here is, we build the two possible composite types, and try the
1856  // conversions in both directions. If only one works, or if the two composite
1857  // types are the same, we have succeeded.
1858  // FIXME: extended qualifiers?
1859  llvm::SmallVector<unsigned, 4> QualifierUnion;
1860  llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
1861  QualType Composite1 = T1, Composite2 = T2;
1862  do {
1863    const PointerType *Ptr1, *Ptr2;
1864    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1865        (Ptr2 = Composite2->getAs<PointerType>())) {
1866      Composite1 = Ptr1->getPointeeType();
1867      Composite2 = Ptr2->getPointeeType();
1868      QualifierUnion.push_back(
1869                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1870      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1871      continue;
1872    }
1873
1874    const MemberPointerType *MemPtr1, *MemPtr2;
1875    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1876        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1877      Composite1 = MemPtr1->getPointeeType();
1878      Composite2 = MemPtr2->getPointeeType();
1879      QualifierUnion.push_back(
1880                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1881      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1882                                             MemPtr2->getClass()));
1883      continue;
1884    }
1885
1886    // FIXME: block pointer types?
1887
1888    // Cannot unwrap any more types.
1889    break;
1890  } while (true);
1891
1892  // Rewrap the composites as pointers or member pointers with the union CVRs.
1893  llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1894    = MemberOfClass.begin();
1895  for (llvm::SmallVector<unsigned, 4>::iterator
1896         I = QualifierUnion.begin(),
1897         E = QualifierUnion.end();
1898       I != E; (void)++I, ++MOC) {
1899    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
1900    if (MOC->first && MOC->second) {
1901      // Rebuild member pointer type
1902      Composite1 = Context.getMemberPointerType(
1903                                    Context.getQualifiedType(Composite1, Quals),
1904                                    MOC->first);
1905      Composite2 = Context.getMemberPointerType(
1906                                    Context.getQualifiedType(Composite2, Quals),
1907                                    MOC->second);
1908    } else {
1909      // Rebuild pointer type
1910      Composite1
1911        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1912      Composite2
1913        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
1914    }
1915  }
1916
1917  ImplicitConversionSequence E1ToC1 =
1918    TryImplicitConversion(E1, Composite1,
1919                          /*SuppressUserConversions=*/false,
1920                          /*AllowExplicit=*/false,
1921                          /*ForceRValue=*/false,
1922                          /*InOverloadResolution=*/false);
1923  ImplicitConversionSequence E2ToC1 =
1924    TryImplicitConversion(E2, Composite1,
1925                          /*SuppressUserConversions=*/false,
1926                          /*AllowExplicit=*/false,
1927                          /*ForceRValue=*/false,
1928                          /*InOverloadResolution=*/false);
1929
1930  ImplicitConversionSequence E1ToC2, E2ToC2;
1931  E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1932  E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1933  if (Context.getCanonicalType(Composite1) !=
1934      Context.getCanonicalType(Composite2)) {
1935    E1ToC2 = TryImplicitConversion(E1, Composite2,
1936                                   /*SuppressUserConversions=*/false,
1937                                   /*AllowExplicit=*/false,
1938                                   /*ForceRValue=*/false,
1939                                   /*InOverloadResolution=*/false);
1940    E2ToC2 = TryImplicitConversion(E2, Composite2,
1941                                   /*SuppressUserConversions=*/false,
1942                                   /*AllowExplicit=*/false,
1943                                   /*ForceRValue=*/false,
1944                                   /*InOverloadResolution=*/false);
1945  }
1946
1947  bool ToC1Viable = E1ToC1.ConversionKind !=
1948                      ImplicitConversionSequence::BadConversion
1949                 && E2ToC1.ConversionKind !=
1950                      ImplicitConversionSequence::BadConversion;
1951  bool ToC2Viable = E1ToC2.ConversionKind !=
1952                      ImplicitConversionSequence::BadConversion
1953                 && E2ToC2.ConversionKind !=
1954                      ImplicitConversionSequence::BadConversion;
1955  if (ToC1Viable && !ToC2Viable) {
1956    if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1957        !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1958      return Composite1;
1959  }
1960  if (ToC2Viable && !ToC1Viable) {
1961    if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1962        !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1963      return Composite2;
1964  }
1965  return QualType();
1966}
1967
1968Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
1969  if (!Context.getLangOptions().CPlusPlus)
1970    return Owned(E);
1971
1972  const RecordType *RT = E->getType()->getAs<RecordType>();
1973  if (!RT)
1974    return Owned(E);
1975
1976  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1977  if (RD->hasTrivialDestructor())
1978    return Owned(E);
1979
1980  if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1981    QualType Ty = CE->getCallee()->getType();
1982    if (const PointerType *PT = Ty->getAs<PointerType>())
1983      Ty = PT->getPointeeType();
1984
1985    const FunctionType *FTy = Ty->getAs<FunctionType>();
1986    if (FTy->getResultType()->isReferenceType())
1987      return Owned(E);
1988  }
1989  CXXTemporary *Temp = CXXTemporary::Create(Context,
1990                                            RD->getDestructor(Context));
1991  ExprTemporaries.push_back(Temp);
1992  if (CXXDestructorDecl *Destructor =
1993        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1994    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
1995  // FIXME: Add the temporary to the temporaries vector.
1996  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1997}
1998
1999Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
2000                                              bool ShouldDestroyTemps) {
2001  assert(SubExpr && "sub expression can't be null!");
2002
2003  if (ExprTemporaries.empty())
2004    return SubExpr;
2005
2006  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
2007                                           &ExprTemporaries[0],
2008                                           ExprTemporaries.size(),
2009                                           ShouldDestroyTemps);
2010  ExprTemporaries.clear();
2011
2012  return E;
2013}
2014
2015Sema::OwningExprResult
2016Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2017                                   tok::TokenKind OpKind, TypeTy *&ObjectType) {
2018  // Since this might be a postfix expression, get rid of ParenListExprs.
2019  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2020
2021  Expr *BaseExpr = (Expr*)Base.get();
2022  assert(BaseExpr && "no record expansion");
2023
2024  QualType BaseType = BaseExpr->getType();
2025  if (BaseType->isDependentType()) {
2026    // FIXME: member of the current instantiation
2027    ObjectType = BaseType.getAsOpaquePtr();
2028    return move(Base);
2029  }
2030
2031  // C++ [over.match.oper]p8:
2032  //   [...] When operator->returns, the operator-> is applied  to the value
2033  //   returned, with the original second operand.
2034  if (OpKind == tok::arrow) {
2035    // The set of types we've considered so far.
2036    llvm::SmallPtrSet<CanQualType,8> CTypes;
2037    llvm::SmallVector<SourceLocation, 8> Locations;
2038    CTypes.insert(Context.getCanonicalType(BaseType));
2039
2040    while (BaseType->isRecordType()) {
2041      Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
2042      BaseExpr = (Expr*)Base.get();
2043      if (BaseExpr == NULL)
2044        return ExprError();
2045      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
2046        Locations.push_back(OpCall->getDirectCallee()->getLocation());
2047      BaseType = BaseExpr->getType();
2048      CanQualType CBaseType = Context.getCanonicalType(BaseType);
2049      if (!CTypes.insert(CBaseType)) {
2050        Diag(OpLoc, diag::err_operator_arrow_circular);
2051        for (unsigned i = 0; i < Locations.size(); i++)
2052          Diag(Locations[i], diag::note_declared_at);
2053        return ExprError();
2054      }
2055    }
2056  }
2057
2058  if (BaseType->isPointerType())
2059    BaseType = BaseType->getPointeeType();
2060
2061  // We could end up with various non-record types here, such as extended
2062  // vector types or Objective-C interfaces. Just return early and let
2063  // ActOnMemberReferenceExpr do the work.
2064  if (!BaseType->isRecordType()) {
2065    // C++ [basic.lookup.classref]p2:
2066    //   [...] If the type of the object expression is of pointer to scalar
2067    //   type, the unqualified-id is looked up in the context of the complete
2068    //   postfix-expression.
2069    ObjectType = 0;
2070    return move(Base);
2071  }
2072
2073  // C++ [basic.lookup.classref]p2:
2074  //   If the id-expression in a class member access (5.2.5) is an
2075  //   unqualified-id, and the type of the object expres- sion is of a class
2076  //   type C (or of pointer to a class type C), the unqualified-id is looked
2077  //   up in the scope of class C. [...]
2078  ObjectType = BaseType.getAsOpaquePtr();
2079  return move(Base);
2080}
2081
2082Sema::OwningExprResult
2083Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
2084                                   SourceLocation OpLoc,
2085                                   tok::TokenKind OpKind,
2086                                   SourceLocation ClassNameLoc,
2087                                   IdentifierInfo *ClassName,
2088                                   const CXXScopeSpec &SS,
2089                                   bool HasTrailingLParen) {
2090  if (SS.isInvalid())
2091    return ExprError();
2092
2093  QualType BaseType;
2094  if (isUnknownSpecialization(SS))
2095    BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
2096                                       ClassName);
2097  else {
2098    TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
2099    if (!BaseTy) {
2100      Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
2101        << ClassName;
2102      return ExprError();
2103    }
2104
2105    BaseType = GetTypeFromParser(BaseTy);
2106  }
2107
2108  CanQualType CanBaseType = Context.getCanonicalType(BaseType);
2109  DeclarationName DtorName =
2110    Context.DeclarationNames.getCXXDestructorName(CanBaseType);
2111
2112  OwningExprResult Result
2113    = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2114                               DtorName, DeclPtrTy(), &SS);
2115  if (Result.isInvalid() || HasTrailingLParen)
2116    return move(Result);
2117
2118  // The only way a reference to a destructor can be used is to
2119  // immediately call them. Since the next token is not a '(', produce a
2120  // diagnostic and build the call now.
2121  Expr *E = (Expr *)Result.get();
2122  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
2123  Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2124    << isa<CXXPseudoDestructorExpr>(E)
2125    << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2126
2127  return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2128                       MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
2129}
2130
2131Sema::OwningExprResult
2132Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
2133                                           SourceLocation OpLoc,
2134                                           tok::TokenKind OpKind,
2135                                           SourceLocation ClassNameLoc,
2136                                           OverloadedOperatorKind OverOpKind,
2137                                           const CXXScopeSpec *SS) {
2138  if (SS && SS->isInvalid())
2139    return ExprError();
2140
2141  DeclarationName Name =
2142    Context.DeclarationNames.getCXXOperatorName(OverOpKind);
2143
2144  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2145                                  Name, DeclPtrTy(), SS);
2146}
2147
2148Sema::OwningExprResult
2149Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
2150                                           SourceLocation OpLoc,
2151                                           tok::TokenKind OpKind,
2152                                           SourceLocation ClassNameLoc,
2153                                           TypeTy *Ty,
2154                                           const CXXScopeSpec *SS) {
2155  if (SS && SS->isInvalid())
2156    return ExprError();
2157
2158  //FIXME: Preserve type source info.
2159  QualType ConvType = GetTypeFromParser(Ty);
2160  CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
2161  DeclarationName ConvName =
2162    Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
2163
2164  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2165                                  ConvName, DeclPtrTy(), SS);
2166}
2167
2168CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2169                                                CXXMethodDecl *Method) {
2170  MemberExpr *ME =
2171      new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2172                               SourceLocation(), Method->getType());
2173  QualType ResultType;
2174  if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2175    ResultType = Conv->getConversionType().getNonReferenceType();
2176  else
2177    ResultType = Method->getResultType().getNonReferenceType();
2178
2179    CXXMemberCallExpr *CE =
2180      new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2181                                      ResultType,
2182                                      SourceLocation());
2183  return CE;
2184}
2185
2186Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2187                                                  QualType Ty,
2188                                                  CastExpr::CastKind Kind,
2189                                                  CXXMethodDecl *Method,
2190                                                  ExprArg Arg) {
2191  Expr *From = Arg.takeAs<Expr>();
2192
2193  switch (Kind) {
2194  default: assert(0 && "Unhandled cast kind!");
2195  case CastExpr::CK_ConstructorConversion: {
2196    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2197
2198    if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2199                                MultiExprArg(*this, (void **)&From, 1),
2200                                CastLoc, ConstructorArgs))
2201      return ExprError();
2202
2203    return BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2204                                 move_arg(ConstructorArgs));
2205  }
2206
2207  case CastExpr::CK_UserDefinedConversion: {
2208    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2209
2210    // Cast to base if needed.
2211    if (PerformObjectArgumentInitialization(From, Method))
2212      return ExprError();
2213
2214    // Create an implicit call expr that calls it.
2215    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
2216    return Owned(CE);
2217  }
2218  }
2219}
2220
2221Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2222  Expr *FullExpr = Arg.takeAs<Expr>();
2223  if (FullExpr)
2224    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
2225                                                 /*ShouldDestroyTemps=*/true);
2226
2227
2228  return Owned(FullExpr);
2229}
2230