SemaExprCXX.cpp revision 2c7588f1260c6655cfb73126b695d2f79ae170bb
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/// PerformImplicitConversion - Perform an implicit conversion of the
1047/// expression From to the type ToType using the pre-computed implicit
1048/// conversion sequence ICS. Returns true if there was an error, false
1049/// otherwise. The expression From is replaced with the converted
1050/// expression. Flavor is the kind of conversion we're performing,
1051/// used in the error message.
1052bool
1053Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1054                                const ImplicitConversionSequence &ICS,
1055                                const char* Flavor) {
1056  switch (ICS.ConversionKind) {
1057  case ImplicitConversionSequence::StandardConversion:
1058    if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
1059      return true;
1060    break;
1061
1062  case ImplicitConversionSequence::UserDefinedConversion: {
1063
1064      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1065      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
1066      QualType BeforeToType;
1067      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1068        CastKind = CastExpr::CK_UserDefinedConversion;
1069
1070        // If the user-defined conversion is specified by a conversion function,
1071        // the initial standard conversion sequence converts the source type to
1072        // the implicit object parameter of the conversion function.
1073        BeforeToType = Context.getTagDeclType(Conv->getParent());
1074      } else if (const CXXConstructorDecl *Ctor =
1075                  dyn_cast<CXXConstructorDecl>(FD)) {
1076        CastKind = CastExpr::CK_ConstructorConversion;
1077
1078        // If the user-defined conversion is specified by a constructor, the
1079        // initial standard conversion sequence converts the source type to the
1080        // type required by the argument of the constructor
1081        BeforeToType = Ctor->getParamDecl(0)->getType();
1082      }
1083      else
1084        assert(0 && "Unknown conversion function kind!");
1085
1086      if (PerformImplicitConversion(From, BeforeToType,
1087                                    ICS.UserDefined.Before, "converting"))
1088        return true;
1089
1090      OwningExprResult CastArg
1091        = BuildCXXCastArgument(From->getLocStart(),
1092                               ToType.getNonReferenceType(),
1093                               CastKind, cast<CXXMethodDecl>(FD),
1094                               Owned(From));
1095
1096      if (CastArg.isInvalid())
1097        return true;
1098
1099      From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1100                                            CastKind, CastArg.takeAs<Expr>(),
1101                                            ToType->isLValueReferenceType());
1102      return false;
1103    }
1104
1105  case ImplicitConversionSequence::EllipsisConversion:
1106    assert(false && "Cannot perform an ellipsis conversion");
1107    return false;
1108
1109  case ImplicitConversionSequence::BadConversion:
1110    return true;
1111  }
1112
1113  // Everything went well.
1114  return false;
1115}
1116
1117/// PerformImplicitConversion - Perform an implicit conversion of the
1118/// expression From to the type ToType by following the standard
1119/// conversion sequence SCS. Returns true if there was an error, false
1120/// otherwise. The expression From is replaced with the converted
1121/// expression. Flavor is the context in which we're performing this
1122/// conversion, for use in error messages.
1123bool
1124Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1125                                const StandardConversionSequence& SCS,
1126                                const char *Flavor) {
1127  // Overall FIXME: we are recomputing too many types here and doing far too
1128  // much extra work. What this means is that we need to keep track of more
1129  // information that is computed when we try the implicit conversion initially,
1130  // so that we don't need to recompute anything here.
1131  QualType FromType = From->getType();
1132
1133  if (SCS.CopyConstructor) {
1134    // FIXME: When can ToType be a reference type?
1135    assert(!ToType->isReferenceType());
1136    if (SCS.Second == ICK_Derived_To_Base) {
1137      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1138      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1139                                  MultiExprArg(*this, (void **)&From, 1),
1140                                  /*FIXME:ConstructLoc*/SourceLocation(),
1141                                  ConstructorArgs))
1142        return true;
1143      OwningExprResult FromResult =
1144        BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1145                              ToType, SCS.CopyConstructor,
1146                              move_arg(ConstructorArgs));
1147      if (FromResult.isInvalid())
1148        return true;
1149      From = FromResult.takeAs<Expr>();
1150      return false;
1151    }
1152    OwningExprResult FromResult =
1153      BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1154                            ToType, SCS.CopyConstructor,
1155                            MultiExprArg(*this, (void**)&From, 1));
1156
1157    if (FromResult.isInvalid())
1158      return true;
1159
1160    From = FromResult.takeAs<Expr>();
1161    return false;
1162  }
1163
1164  // Perform the first implicit conversion.
1165  switch (SCS.First) {
1166  case ICK_Identity:
1167  case ICK_Lvalue_To_Rvalue:
1168    // Nothing to do.
1169    break;
1170
1171  case ICK_Array_To_Pointer:
1172    FromType = Context.getArrayDecayedType(FromType);
1173    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
1174    break;
1175
1176  case ICK_Function_To_Pointer:
1177    if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
1178      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1179      if (!Fn)
1180        return true;
1181
1182      if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1183        return true;
1184
1185      FixOverloadedFunctionReference(From, Fn);
1186      FromType = From->getType();
1187    }
1188    FromType = Context.getPointerType(FromType);
1189    ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
1190    break;
1191
1192  default:
1193    assert(false && "Improper first standard conversion");
1194    break;
1195  }
1196
1197  // Perform the second implicit conversion
1198  switch (SCS.Second) {
1199  case ICK_Identity:
1200    // If both sides are functions (or pointers/references to them), there could
1201    // be incompatible exception declarations.
1202    if (CheckExceptionSpecCompatibility(From, ToType))
1203      return true;
1204    // Nothing else to do.
1205    break;
1206
1207  case ICK_Integral_Promotion:
1208  case ICK_Floating_Promotion:
1209  case ICK_Complex_Promotion:
1210  case ICK_Integral_Conversion:
1211  case ICK_Floating_Conversion:
1212  case ICK_Complex_Conversion:
1213  case ICK_Floating_Integral:
1214  case ICK_Complex_Real:
1215  case ICK_Compatible_Conversion:
1216      // FIXME: Go deeper to get the unqualified type!
1217    FromType = ToType.getUnqualifiedType();
1218    ImpCastExprToType(From, FromType);
1219    break;
1220
1221  case ICK_Pointer_Conversion: {
1222    if (SCS.IncompatibleObjC) {
1223      // Diagnose incompatible Objective-C conversions
1224      Diag(From->getSourceRange().getBegin(),
1225           diag::ext_typecheck_convert_incompatible_pointer)
1226        << From->getType() << ToType << Flavor
1227        << From->getSourceRange();
1228    }
1229
1230
1231    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1232    if (CheckPointerConversion(From, ToType, Kind))
1233      return true;
1234    ImpCastExprToType(From, ToType, Kind);
1235    break;
1236  }
1237
1238  case ICK_Pointer_Member: {
1239    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1240    if (CheckMemberPointerConversion(From, ToType, Kind))
1241      return true;
1242    if (CheckExceptionSpecCompatibility(From, ToType))
1243      return true;
1244    ImpCastExprToType(From, ToType, Kind);
1245    break;
1246  }
1247  case ICK_Boolean_Conversion:
1248    FromType = Context.BoolTy;
1249    ImpCastExprToType(From, FromType);
1250    break;
1251
1252  default:
1253    assert(false && "Improper second standard conversion");
1254    break;
1255  }
1256
1257  switch (SCS.Third) {
1258  case ICK_Identity:
1259    // Nothing to do.
1260    break;
1261
1262  case ICK_Qualification:
1263    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1264    // references.
1265    ImpCastExprToType(From, ToType.getNonReferenceType(),
1266                      CastExpr::CK_Unknown,
1267                      ToType->isLValueReferenceType());
1268    break;
1269
1270  default:
1271    assert(false && "Improper second standard conversion");
1272    break;
1273  }
1274
1275  return false;
1276}
1277
1278bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
1279{
1280  // First we check for applicability.
1281  // Target type must be a function, function pointer or function reference.
1282  if (const PointerType *PtrTy = ToType->getAs<PointerType>())
1283    ToType = PtrTy->getPointeeType();
1284  else if (const ReferenceType *RefTy = ToType->getAs<ReferenceType>())
1285    ToType = RefTy->getPointeeType();
1286
1287  const FunctionProtoType *ToFunc = ToType->getAs<FunctionProtoType>();
1288  if (!ToFunc)
1289    return false;
1290
1291  // SourceType must be a function or function pointer.
1292  // References are treated as functions.
1293  QualType FromType = From->getType();
1294  if (const PointerType *PtrTy = FromType->getAs<PointerType>())
1295    FromType = PtrTy->getPointeeType();
1296
1297  const FunctionProtoType *FromFunc = FromType->getAs<FunctionProtoType>();
1298  if (!FromFunc)
1299    return false;
1300
1301  // Now we've got the correct types on both sides, check their compatibility.
1302  // This means that the source of the conversion can only throw a subset of
1303  // the exceptions of the target, and any exception specs on arguments or
1304  // return types must be equivalent.
1305  return CheckExceptionSpecSubset(diag::err_incompatible_exception_specs,
1306                                  0, ToFunc, From->getSourceRange().getBegin(),
1307                                  FromFunc, SourceLocation());
1308}
1309
1310Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1311                                                 SourceLocation KWLoc,
1312                                                 SourceLocation LParen,
1313                                                 TypeTy *Ty,
1314                                                 SourceLocation RParen) {
1315  QualType T = GetTypeFromParser(Ty);
1316
1317  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1318  // all traits except __is_class, __is_enum and __is_union require a the type
1319  // to be complete.
1320  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1321    if (RequireCompleteType(KWLoc, T,
1322                            diag::err_incomplete_type_used_in_type_trait_expr))
1323      return ExprError();
1324  }
1325
1326  // There is no point in eagerly computing the value. The traits are designed
1327  // to be used from type trait templates, so Ty will be a template parameter
1328  // 99% of the time.
1329  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1330                                                RParen, Context.BoolTy));
1331}
1332
1333QualType Sema::CheckPointerToMemberOperands(
1334  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1335  const char *OpSpelling = isIndirect ? "->*" : ".*";
1336  // C++ 5.5p2
1337  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1338  //   be of type "pointer to member of T" (where T is a completely-defined
1339  //   class type) [...]
1340  QualType RType = rex->getType();
1341  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1342  if (!MemPtr) {
1343    Diag(Loc, diag::err_bad_memptr_rhs)
1344      << OpSpelling << RType << rex->getSourceRange();
1345    return QualType();
1346  }
1347
1348  QualType Class(MemPtr->getClass(), 0);
1349
1350  // C++ 5.5p2
1351  //   [...] to its first operand, which shall be of class T or of a class of
1352  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1353  //   such a class]
1354  QualType LType = lex->getType();
1355  if (isIndirect) {
1356    if (const PointerType *Ptr = LType->getAs<PointerType>())
1357      LType = Ptr->getPointeeType().getNonReferenceType();
1358    else {
1359      Diag(Loc, diag::err_bad_memptr_lhs)
1360        << OpSpelling << 1 << LType << lex->getSourceRange();
1361      return QualType();
1362    }
1363  }
1364
1365  if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1366      Context.getCanonicalType(LType).getUnqualifiedType()) {
1367    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1368                       /*DetectVirtual=*/false);
1369    // FIXME: Would it be useful to print full ambiguity paths, or is that
1370    // overkill?
1371    if (!IsDerivedFrom(LType, Class, Paths) ||
1372        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1373      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1374        << (int)isIndirect << lex->getType() << lex->getSourceRange();
1375      return QualType();
1376    }
1377  }
1378
1379  // C++ 5.5p2
1380  //   The result is an object or a function of the type specified by the
1381  //   second operand.
1382  // The cv qualifiers are the union of those in the pointer and the left side,
1383  // in accordance with 5.5p5 and 5.2.5.
1384  // FIXME: This returns a dereferenced member function pointer as a normal
1385  // function type. However, the only operation valid on such functions is
1386  // calling them. There's also a GCC extension to get a function pointer to the
1387  // thing, which is another complication, because this type - unlike the type
1388  // that is the result of this expression - takes the class as the first
1389  // argument.
1390  // We probably need a "MemberFunctionClosureType" or something like that.
1391  QualType Result = MemPtr->getPointeeType();
1392  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
1393  return Result;
1394}
1395
1396/// \brief Get the target type of a standard or user-defined conversion.
1397static QualType TargetType(const ImplicitConversionSequence &ICS) {
1398  assert((ICS.ConversionKind ==
1399              ImplicitConversionSequence::StandardConversion ||
1400          ICS.ConversionKind ==
1401              ImplicitConversionSequence::UserDefinedConversion) &&
1402         "function only valid for standard or user-defined conversions");
1403  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1404    return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1405  return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1406}
1407
1408/// \brief Try to convert a type to another according to C++0x 5.16p3.
1409///
1410/// This is part of the parameter validation for the ? operator. If either
1411/// value operand is a class type, the two operands are attempted to be
1412/// converted to each other. This function does the conversion in one direction.
1413/// It emits a diagnostic and returns true only if it finds an ambiguous
1414/// conversion.
1415static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1416                                SourceLocation QuestionLoc,
1417                                ImplicitConversionSequence &ICS) {
1418  // C++0x 5.16p3
1419  //   The process for determining whether an operand expression E1 of type T1
1420  //   can be converted to match an operand expression E2 of type T2 is defined
1421  //   as follows:
1422  //   -- If E2 is an lvalue:
1423  if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1424    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1425    //   type "lvalue reference to T2", subject to the constraint that in the
1426    //   conversion the reference must bind directly to E1.
1427    if (!Self.CheckReferenceInit(From,
1428                            Self.Context.getLValueReferenceType(To->getType()),
1429                                 To->getLocStart(),
1430                                 /*SuppressUserConversions=*/false,
1431                                 /*AllowExplicit=*/false,
1432                                 /*ForceRValue=*/false,
1433                                 &ICS))
1434    {
1435      assert((ICS.ConversionKind ==
1436                  ImplicitConversionSequence::StandardConversion ||
1437              ICS.ConversionKind ==
1438                  ImplicitConversionSequence::UserDefinedConversion) &&
1439             "expected a definite conversion");
1440      bool DirectBinding =
1441        ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1442        ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1443      if (DirectBinding)
1444        return false;
1445    }
1446  }
1447  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1448  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1449  //      -- if E1 and E2 have class type, and the underlying class types are
1450  //         the same or one is a base class of the other:
1451  QualType FTy = From->getType();
1452  QualType TTy = To->getType();
1453  const RecordType *FRec = FTy->getAs<RecordType>();
1454  const RecordType *TRec = TTy->getAs<RecordType>();
1455  bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1456  if (FRec && TRec && (FRec == TRec ||
1457        FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1458    //         E1 can be converted to match E2 if the class of T2 is the
1459    //         same type as, or a base class of, the class of T1, and
1460    //         [cv2 > cv1].
1461    if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1462      // Could still fail if there's no copy constructor.
1463      // FIXME: Is this a hard error then, or just a conversion failure? The
1464      // standard doesn't say.
1465      ICS = Self.TryCopyInitialization(From, TTy,
1466                                       /*SuppressUserConversions=*/false,
1467                                       /*ForceRValue=*/false,
1468                                       /*InOverloadResolution=*/false);
1469    }
1470  } else {
1471    //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1472    //        implicitly converted to the type that expression E2 would have
1473    //        if E2 were converted to an rvalue.
1474    // First find the decayed type.
1475    if (TTy->isFunctionType())
1476      TTy = Self.Context.getPointerType(TTy);
1477    else if (TTy->isArrayType())
1478      TTy = Self.Context.getArrayDecayedType(TTy);
1479
1480    // Now try the implicit conversion.
1481    // FIXME: This doesn't detect ambiguities.
1482    ICS = Self.TryImplicitConversion(From, TTy,
1483                                     /*SuppressUserConversions=*/false,
1484                                     /*AllowExplicit=*/false,
1485                                     /*ForceRValue=*/false,
1486                                     /*InOverloadResolution=*/false);
1487  }
1488  return false;
1489}
1490
1491/// \brief Try to find a common type for two according to C++0x 5.16p5.
1492///
1493/// This is part of the parameter validation for the ? operator. If either
1494/// value operand is a class type, overload resolution is used to find a
1495/// conversion to a common type.
1496static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1497                                    SourceLocation Loc) {
1498  Expr *Args[2] = { LHS, RHS };
1499  OverloadCandidateSet CandidateSet;
1500  Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1501
1502  OverloadCandidateSet::iterator Best;
1503  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
1504    case Sema::OR_Success:
1505      // We found a match. Perform the conversions on the arguments and move on.
1506      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1507                                         Best->Conversions[0], "converting") ||
1508          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1509                                         Best->Conversions[1], "converting"))
1510        break;
1511      return false;
1512
1513    case Sema::OR_No_Viable_Function:
1514      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1515        << LHS->getType() << RHS->getType()
1516        << LHS->getSourceRange() << RHS->getSourceRange();
1517      return true;
1518
1519    case Sema::OR_Ambiguous:
1520      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1521        << LHS->getType() << RHS->getType()
1522        << LHS->getSourceRange() << RHS->getSourceRange();
1523      // FIXME: Print the possible common types by printing the return types of
1524      // the viable candidates.
1525      break;
1526
1527    case Sema::OR_Deleted:
1528      assert(false && "Conditional operator has only built-in overloads");
1529      break;
1530  }
1531  return true;
1532}
1533
1534/// \brief Perform an "extended" implicit conversion as returned by
1535/// TryClassUnification.
1536///
1537/// TryClassUnification generates ICSs that include reference bindings.
1538/// PerformImplicitConversion is not suitable for this; it chokes if the
1539/// second part of a standard conversion is ICK_DerivedToBase. This function
1540/// handles the reference binding specially.
1541static bool ConvertForConditional(Sema &Self, Expr *&E,
1542                                  const ImplicitConversionSequence &ICS) {
1543  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1544      ICS.Standard.ReferenceBinding) {
1545    assert(ICS.Standard.DirectBinding &&
1546           "TryClassUnification should never generate indirect ref bindings");
1547    // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1548    // redoing all the work.
1549    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1550                                        TargetType(ICS)),
1551                                   /*FIXME:*/E->getLocStart(),
1552                                   /*SuppressUserConversions=*/false,
1553                                   /*AllowExplicit=*/false,
1554                                   /*ForceRValue=*/false);
1555  }
1556  if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1557      ICS.UserDefined.After.ReferenceBinding) {
1558    assert(ICS.UserDefined.After.DirectBinding &&
1559           "TryClassUnification should never generate indirect ref bindings");
1560    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1561                                        TargetType(ICS)),
1562                                   /*FIXME:*/E->getLocStart(),
1563                                   /*SuppressUserConversions=*/false,
1564                                   /*AllowExplicit=*/false,
1565                                   /*ForceRValue=*/false);
1566  }
1567  if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1568    return true;
1569  return false;
1570}
1571
1572/// \brief Check the operands of ?: under C++ semantics.
1573///
1574/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1575/// extension. In this case, LHS == Cond. (But they're not aliases.)
1576QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1577                                           SourceLocation QuestionLoc) {
1578  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1579  // interface pointers.
1580
1581  // C++0x 5.16p1
1582  //   The first expression is contextually converted to bool.
1583  if (!Cond->isTypeDependent()) {
1584    if (CheckCXXBooleanCondition(Cond))
1585      return QualType();
1586  }
1587
1588  // Either of the arguments dependent?
1589  if (LHS->isTypeDependent() || RHS->isTypeDependent())
1590    return Context.DependentTy;
1591
1592  // C++0x 5.16p2
1593  //   If either the second or the third operand has type (cv) void, ...
1594  QualType LTy = LHS->getType();
1595  QualType RTy = RHS->getType();
1596  bool LVoid = LTy->isVoidType();
1597  bool RVoid = RTy->isVoidType();
1598  if (LVoid || RVoid) {
1599    //   ... then the [l2r] conversions are performed on the second and third
1600    //   operands ...
1601    DefaultFunctionArrayConversion(LHS);
1602    DefaultFunctionArrayConversion(RHS);
1603    LTy = LHS->getType();
1604    RTy = RHS->getType();
1605
1606    //   ... and one of the following shall hold:
1607    //   -- The second or the third operand (but not both) is a throw-
1608    //      expression; the result is of the type of the other and is an rvalue.
1609    bool LThrow = isa<CXXThrowExpr>(LHS);
1610    bool RThrow = isa<CXXThrowExpr>(RHS);
1611    if (LThrow && !RThrow)
1612      return RTy;
1613    if (RThrow && !LThrow)
1614      return LTy;
1615
1616    //   -- Both the second and third operands have type void; the result is of
1617    //      type void and is an rvalue.
1618    if (LVoid && RVoid)
1619      return Context.VoidTy;
1620
1621    // Neither holds, error.
1622    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1623      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1624      << LHS->getSourceRange() << RHS->getSourceRange();
1625    return QualType();
1626  }
1627
1628  // Neither is void.
1629
1630  // C++0x 5.16p3
1631  //   Otherwise, if the second and third operand have different types, and
1632  //   either has (cv) class type, and attempt is made to convert each of those
1633  //   operands to the other.
1634  if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1635      (LTy->isRecordType() || RTy->isRecordType())) {
1636    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1637    // These return true if a single direction is already ambiguous.
1638    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1639      return QualType();
1640    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1641      return QualType();
1642
1643    bool HaveL2R = ICSLeftToRight.ConversionKind !=
1644      ImplicitConversionSequence::BadConversion;
1645    bool HaveR2L = ICSRightToLeft.ConversionKind !=
1646      ImplicitConversionSequence::BadConversion;
1647    //   If both can be converted, [...] the program is ill-formed.
1648    if (HaveL2R && HaveR2L) {
1649      Diag(QuestionLoc, diag::err_conditional_ambiguous)
1650        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1651      return QualType();
1652    }
1653
1654    //   If exactly one conversion is possible, that conversion is applied to
1655    //   the chosen operand and the converted operands are used in place of the
1656    //   original operands for the remainder of this section.
1657    if (HaveL2R) {
1658      if (ConvertForConditional(*this, LHS, ICSLeftToRight))
1659        return QualType();
1660      LTy = LHS->getType();
1661    } else if (HaveR2L) {
1662      if (ConvertForConditional(*this, RHS, ICSRightToLeft))
1663        return QualType();
1664      RTy = RHS->getType();
1665    }
1666  }
1667
1668  // C++0x 5.16p4
1669  //   If the second and third operands are lvalues and have the same type,
1670  //   the result is of that type [...]
1671  bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1672  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1673      RHS->isLvalue(Context) == Expr::LV_Valid)
1674    return LTy;
1675
1676  // C++0x 5.16p5
1677  //   Otherwise, the result is an rvalue. If the second and third operands
1678  //   do not have the same type, and either has (cv) class type, ...
1679  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1680    //   ... overload resolution is used to determine the conversions (if any)
1681    //   to be applied to the operands. If the overload resolution fails, the
1682    //   program is ill-formed.
1683    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1684      return QualType();
1685  }
1686
1687  // C++0x 5.16p6
1688  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1689  //   conversions are performed on the second and third operands.
1690  DefaultFunctionArrayConversion(LHS);
1691  DefaultFunctionArrayConversion(RHS);
1692  LTy = LHS->getType();
1693  RTy = RHS->getType();
1694
1695  //   After those conversions, one of the following shall hold:
1696  //   -- The second and third operands have the same type; the result
1697  //      is of that type.
1698  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1699    return LTy;
1700
1701  //   -- The second and third operands have arithmetic or enumeration type;
1702  //      the usual arithmetic conversions are performed to bring them to a
1703  //      common type, and the result is of that type.
1704  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1705    UsualArithmeticConversions(LHS, RHS);
1706    return LHS->getType();
1707  }
1708
1709  //   -- The second and third operands have pointer type, or one has pointer
1710  //      type and the other is a null pointer constant; pointer conversions
1711  //      and qualification conversions are performed to bring them to their
1712  //      composite pointer type. The result is of the composite pointer type.
1713  QualType Composite = FindCompositePointerType(LHS, RHS);
1714  if (!Composite.isNull())
1715    return Composite;
1716
1717  // Fourth bullet is same for pointers-to-member. However, the possible
1718  // conversions are far more limited: we have null-to-pointer, upcast of
1719  // containing class, and second-level cv-ness.
1720  // cv-ness is not a union, but must match one of the two operands. (Which,
1721  // frankly, is stupid.)
1722  const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1723  const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
1724  if (LMemPtr &&
1725      RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1726    ImpCastExprToType(RHS, LTy);
1727    return LTy;
1728  }
1729  if (RMemPtr &&
1730      LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1731    ImpCastExprToType(LHS, RTy);
1732    return RTy;
1733  }
1734  if (LMemPtr && RMemPtr) {
1735    QualType LPointee = LMemPtr->getPointeeType();
1736    QualType RPointee = RMemPtr->getPointeeType();
1737
1738    QualifierCollector LPQuals, RPQuals;
1739    const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1740    const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1741
1742    // First, we check that the unqualified pointee type is the same. If it's
1743    // not, there's no conversion that will unify the two pointers.
1744    if (LPCan == RPCan) {
1745
1746      // Second, we take the greater of the two qualifications. If neither
1747      // is greater than the other, the conversion is not possible.
1748
1749      Qualifiers MergedQuals = LPQuals + RPQuals;
1750
1751      bool CompatibleQuals = true;
1752      if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1753          MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1754        CompatibleQuals = false;
1755      else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1756        // FIXME:
1757        // C99 6.5.15 as modified by TR 18037:
1758        //   If the second and third operands are pointers into different
1759        //   address spaces, the address spaces must overlap.
1760        CompatibleQuals = false;
1761      // FIXME: GC qualifiers?
1762
1763      if (CompatibleQuals) {
1764        // Third, we check if either of the container classes is derived from
1765        // the other.
1766        QualType LContainer(LMemPtr->getClass(), 0);
1767        QualType RContainer(RMemPtr->getClass(), 0);
1768        QualType MoreDerived;
1769        if (Context.getCanonicalType(LContainer) ==
1770            Context.getCanonicalType(RContainer))
1771          MoreDerived = LContainer;
1772        else if (IsDerivedFrom(LContainer, RContainer))
1773          MoreDerived = LContainer;
1774        else if (IsDerivedFrom(RContainer, LContainer))
1775          MoreDerived = RContainer;
1776
1777        if (!MoreDerived.isNull()) {
1778          // The type 'Q Pointee (MoreDerived::*)' is the common type.
1779          // We don't use ImpCastExprToType here because this could still fail
1780          // for ambiguous or inaccessible conversions.
1781          LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1782          QualType Common
1783            = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
1784          if (PerformImplicitConversion(LHS, Common, "converting"))
1785            return QualType();
1786          if (PerformImplicitConversion(RHS, Common, "converting"))
1787            return QualType();
1788          return Common;
1789        }
1790      }
1791    }
1792  }
1793
1794  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1795    << LHS->getType() << RHS->getType()
1796    << LHS->getSourceRange() << RHS->getSourceRange();
1797  return QualType();
1798}
1799
1800/// \brief Find a merged pointer type and convert the two expressions to it.
1801///
1802/// This finds the composite pointer type (or member pointer type) for @p E1
1803/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1804/// type and returns it.
1805/// It does not emit diagnostics.
1806QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1807  assert(getLangOptions().CPlusPlus && "This function assumes C++");
1808  QualType T1 = E1->getType(), T2 = E2->getType();
1809
1810  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1811      !T2->isPointerType() && !T2->isMemberPointerType())
1812   return QualType();
1813
1814  // FIXME: Do we need to work on the canonical types?
1815
1816  // C++0x 5.9p2
1817  //   Pointer conversions and qualification conversions are performed on
1818  //   pointer operands to bring them to their composite pointer type. If
1819  //   one operand is a null pointer constant, the composite pointer type is
1820  //   the type of the other operand.
1821  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1822    ImpCastExprToType(E1, T2);
1823    return T2;
1824  }
1825  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1826    ImpCastExprToType(E2, T1);
1827    return T1;
1828  }
1829
1830  // Now both have to be pointers or member pointers.
1831  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1832      !T2->isPointerType() && !T2->isMemberPointerType())
1833    return QualType();
1834
1835  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
1836  //   the other has type "pointer to cv2 T" and the composite pointer type is
1837  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1838  //   Otherwise, the composite pointer type is a pointer type similar to the
1839  //   type of one of the operands, with a cv-qualification signature that is
1840  //   the union of the cv-qualification signatures of the operand types.
1841  // In practice, the first part here is redundant; it's subsumed by the second.
1842  // What we do here is, we build the two possible composite types, and try the
1843  // conversions in both directions. If only one works, or if the two composite
1844  // types are the same, we have succeeded.
1845  // FIXME: extended qualifiers?
1846  llvm::SmallVector<unsigned, 4> QualifierUnion;
1847  llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
1848  QualType Composite1 = T1, Composite2 = T2;
1849  do {
1850    const PointerType *Ptr1, *Ptr2;
1851    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1852        (Ptr2 = Composite2->getAs<PointerType>())) {
1853      Composite1 = Ptr1->getPointeeType();
1854      Composite2 = Ptr2->getPointeeType();
1855      QualifierUnion.push_back(
1856                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1857      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1858      continue;
1859    }
1860
1861    const MemberPointerType *MemPtr1, *MemPtr2;
1862    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1863        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1864      Composite1 = MemPtr1->getPointeeType();
1865      Composite2 = MemPtr2->getPointeeType();
1866      QualifierUnion.push_back(
1867                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1868      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1869                                             MemPtr2->getClass()));
1870      continue;
1871    }
1872
1873    // FIXME: block pointer types?
1874
1875    // Cannot unwrap any more types.
1876    break;
1877  } while (true);
1878
1879  // Rewrap the composites as pointers or member pointers with the union CVRs.
1880  llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1881    = MemberOfClass.begin();
1882  for (llvm::SmallVector<unsigned, 4>::iterator
1883         I = QualifierUnion.begin(),
1884         E = QualifierUnion.end();
1885       I != E; (void)++I, ++MOC) {
1886    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
1887    if (MOC->first && MOC->second) {
1888      // Rebuild member pointer type
1889      Composite1 = Context.getMemberPointerType(
1890                                    Context.getQualifiedType(Composite1, Quals),
1891                                    MOC->first);
1892      Composite2 = Context.getMemberPointerType(
1893                                    Context.getQualifiedType(Composite2, Quals),
1894                                    MOC->second);
1895    } else {
1896      // Rebuild pointer type
1897      Composite1
1898        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1899      Composite2
1900        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
1901    }
1902  }
1903
1904  ImplicitConversionSequence E1ToC1 =
1905    TryImplicitConversion(E1, Composite1,
1906                          /*SuppressUserConversions=*/false,
1907                          /*AllowExplicit=*/false,
1908                          /*ForceRValue=*/false,
1909                          /*InOverloadResolution=*/false);
1910  ImplicitConversionSequence E2ToC1 =
1911    TryImplicitConversion(E2, Composite1,
1912                          /*SuppressUserConversions=*/false,
1913                          /*AllowExplicit=*/false,
1914                          /*ForceRValue=*/false,
1915                          /*InOverloadResolution=*/false);
1916
1917  ImplicitConversionSequence E1ToC2, E2ToC2;
1918  E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1919  E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1920  if (Context.getCanonicalType(Composite1) !=
1921      Context.getCanonicalType(Composite2)) {
1922    E1ToC2 = TryImplicitConversion(E1, Composite2,
1923                                   /*SuppressUserConversions=*/false,
1924                                   /*AllowExplicit=*/false,
1925                                   /*ForceRValue=*/false,
1926                                   /*InOverloadResolution=*/false);
1927    E2ToC2 = TryImplicitConversion(E2, Composite2,
1928                                   /*SuppressUserConversions=*/false,
1929                                   /*AllowExplicit=*/false,
1930                                   /*ForceRValue=*/false,
1931                                   /*InOverloadResolution=*/false);
1932  }
1933
1934  bool ToC1Viable = E1ToC1.ConversionKind !=
1935                      ImplicitConversionSequence::BadConversion
1936                 && E2ToC1.ConversionKind !=
1937                      ImplicitConversionSequence::BadConversion;
1938  bool ToC2Viable = E1ToC2.ConversionKind !=
1939                      ImplicitConversionSequence::BadConversion
1940                 && E2ToC2.ConversionKind !=
1941                      ImplicitConversionSequence::BadConversion;
1942  if (ToC1Viable && !ToC2Viable) {
1943    if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1944        !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1945      return Composite1;
1946  }
1947  if (ToC2Viable && !ToC1Viable) {
1948    if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1949        !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1950      return Composite2;
1951  }
1952  return QualType();
1953}
1954
1955Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
1956  if (!Context.getLangOptions().CPlusPlus)
1957    return Owned(E);
1958
1959  const RecordType *RT = E->getType()->getAs<RecordType>();
1960  if (!RT)
1961    return Owned(E);
1962
1963  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1964  if (RD->hasTrivialDestructor())
1965    return Owned(E);
1966
1967  if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1968    QualType Ty = CE->getCallee()->getType();
1969    if (const PointerType *PT = Ty->getAs<PointerType>())
1970      Ty = PT->getPointeeType();
1971
1972    const FunctionType *FTy = Ty->getAs<FunctionType>();
1973    if (FTy->getResultType()->isReferenceType())
1974      return Owned(E);
1975  }
1976  CXXTemporary *Temp = CXXTemporary::Create(Context,
1977                                            RD->getDestructor(Context));
1978  ExprTemporaries.push_back(Temp);
1979  if (CXXDestructorDecl *Destructor =
1980        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1981    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
1982  // FIXME: Add the temporary to the temporaries vector.
1983  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1984}
1985
1986Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
1987                                              bool ShouldDestroyTemps) {
1988  assert(SubExpr && "sub expression can't be null!");
1989
1990  if (ExprTemporaries.empty())
1991    return SubExpr;
1992
1993  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1994                                           &ExprTemporaries[0],
1995                                           ExprTemporaries.size(),
1996                                           ShouldDestroyTemps);
1997  ExprTemporaries.clear();
1998
1999  return E;
2000}
2001
2002Sema::OwningExprResult
2003Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2004                                   tok::TokenKind OpKind, TypeTy *&ObjectType) {
2005  // Since this might be a postfix expression, get rid of ParenListExprs.
2006  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2007
2008  Expr *BaseExpr = (Expr*)Base.get();
2009  assert(BaseExpr && "no record expansion");
2010
2011  QualType BaseType = BaseExpr->getType();
2012  if (BaseType->isDependentType()) {
2013    // FIXME: member of the current instantiation
2014    ObjectType = BaseType.getAsOpaquePtr();
2015    return move(Base);
2016  }
2017
2018  // C++ [over.match.oper]p8:
2019  //   [...] When operator->returns, the operator-> is applied  to the value
2020  //   returned, with the original second operand.
2021  if (OpKind == tok::arrow) {
2022    // The set of types we've considered so far.
2023    llvm::SmallPtrSet<CanQualType,8> CTypes;
2024    llvm::SmallVector<SourceLocation, 8> Locations;
2025    CTypes.insert(Context.getCanonicalType(BaseType));
2026
2027    while (BaseType->isRecordType()) {
2028      Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
2029      BaseExpr = (Expr*)Base.get();
2030      if (BaseExpr == NULL)
2031        return ExprError();
2032      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
2033        Locations.push_back(OpCall->getOperatorLoc());
2034      BaseType = BaseExpr->getType();
2035      CanQualType CBaseType = Context.getCanonicalType(BaseType);
2036      if (!CTypes.insert(CBaseType)) {
2037        Diag(OpLoc, diag::err_operator_arrow_circular);
2038        for (unsigned i = 0; i < Locations.size(); i++)
2039          Diag(Locations[i], diag::note_declared_at);
2040        return ExprError();
2041      }
2042    }
2043  }
2044
2045  if (BaseType->isPointerType())
2046    BaseType = BaseType->getPointeeType();
2047
2048  // We could end up with various non-record types here, such as extended
2049  // vector types or Objective-C interfaces. Just return early and let
2050  // ActOnMemberReferenceExpr do the work.
2051  if (!BaseType->isRecordType()) {
2052    // C++ [basic.lookup.classref]p2:
2053    //   [...] If the type of the object expression is of pointer to scalar
2054    //   type, the unqualified-id is looked up in the context of the complete
2055    //   postfix-expression.
2056    ObjectType = 0;
2057    return move(Base);
2058  }
2059
2060  // C++ [basic.lookup.classref]p2:
2061  //   If the id-expression in a class member access (5.2.5) is an
2062  //   unqualified-id, and the type of the object expres- sion is of a class
2063  //   type C (or of pointer to a class type C), the unqualified-id is looked
2064  //   up in the scope of class C. [...]
2065  ObjectType = BaseType.getAsOpaquePtr();
2066  return move(Base);
2067}
2068
2069Sema::OwningExprResult
2070Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
2071                                   SourceLocation OpLoc,
2072                                   tok::TokenKind OpKind,
2073                                   SourceLocation ClassNameLoc,
2074                                   IdentifierInfo *ClassName,
2075                                   const CXXScopeSpec &SS,
2076                                   bool HasTrailingLParen) {
2077  if (SS.isInvalid())
2078    return ExprError();
2079
2080  QualType BaseType;
2081  if (isUnknownSpecialization(SS))
2082    BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
2083                                       ClassName);
2084  else {
2085    TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
2086    if (!BaseTy) {
2087      Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
2088        << ClassName;
2089      return ExprError();
2090    }
2091
2092    BaseType = GetTypeFromParser(BaseTy);
2093  }
2094
2095  CanQualType CanBaseType = Context.getCanonicalType(BaseType);
2096  DeclarationName DtorName =
2097    Context.DeclarationNames.getCXXDestructorName(CanBaseType);
2098
2099  OwningExprResult Result
2100    = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2101                               DtorName, DeclPtrTy(), &SS);
2102  if (Result.isInvalid() || HasTrailingLParen)
2103    return move(Result);
2104
2105  // The only way a reference to a destructor can be used is to
2106  // immediately call them. Since the next token is not a '(', produce a
2107  // diagnostic and build the call now.
2108  Expr *E = (Expr *)Result.get();
2109  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
2110  Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2111    << isa<CXXPseudoDestructorExpr>(E)
2112    << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2113
2114  return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2115                       MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
2116}
2117
2118Sema::OwningExprResult
2119Sema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
2120                                           SourceLocation OpLoc,
2121                                           tok::TokenKind OpKind,
2122                                           SourceLocation ClassNameLoc,
2123                                           OverloadedOperatorKind OverOpKind,
2124                                           const CXXScopeSpec *SS) {
2125  if (SS && SS->isInvalid())
2126    return ExprError();
2127
2128  DeclarationName Name =
2129    Context.DeclarationNames.getCXXOperatorName(OverOpKind);
2130
2131  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2132                                  Name, DeclPtrTy(), SS);
2133}
2134
2135Sema::OwningExprResult
2136Sema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
2137                                           SourceLocation OpLoc,
2138                                           tok::TokenKind OpKind,
2139                                           SourceLocation ClassNameLoc,
2140                                           TypeTy *Ty,
2141                                           const CXXScopeSpec *SS) {
2142  if (SS && SS->isInvalid())
2143    return ExprError();
2144
2145  //FIXME: Preserve type source info.
2146  QualType ConvType = GetTypeFromParser(Ty);
2147  CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
2148  DeclarationName ConvName =
2149    Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
2150
2151  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2152                                  ConvName, DeclPtrTy(), SS);
2153}
2154
2155CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2156                                                CXXMethodDecl *Method) {
2157  MemberExpr *ME =
2158      new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2159                               SourceLocation(), Method->getType());
2160  QualType ResultType;
2161  if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2162    ResultType = Conv->getConversionType().getNonReferenceType();
2163  else
2164    ResultType = Method->getResultType().getNonReferenceType();
2165
2166    CXXMemberCallExpr *CE =
2167      new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2168                                      ResultType,
2169                                      SourceLocation());
2170  return CE;
2171}
2172
2173Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2174                                                  QualType Ty,
2175                                                  CastExpr::CastKind Kind,
2176                                                  CXXMethodDecl *Method,
2177                                                  ExprArg Arg) {
2178  Expr *From = Arg.takeAs<Expr>();
2179
2180  switch (Kind) {
2181  default: assert(0 && "Unhandled cast kind!");
2182  case CastExpr::CK_ConstructorConversion: {
2183    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2184
2185    if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2186                                MultiExprArg(*this, (void **)&From, 1),
2187                                CastLoc, ConstructorArgs))
2188      return ExprError();
2189
2190    return BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2191                                 move_arg(ConstructorArgs));
2192  }
2193
2194  case CastExpr::CK_UserDefinedConversion: {
2195    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2196
2197    // Cast to base if needed.
2198    if (PerformObjectArgumentInitialization(From, Method))
2199      return ExprError();
2200
2201    // Create an implicit call expr that calls it.
2202    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
2203    return Owned(CE);
2204  }
2205  }
2206}
2207
2208Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2209  Expr *FullExpr = Arg.takeAs<Expr>();
2210  if (FullExpr)
2211    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
2212                                                 /*ShouldDestroyTemps=*/true);
2213
2214
2215  return Owned(FullExpr);
2216}
2217