SemaExprCXX.cpp revision ef8fd086af176ffa48d21a505eb64b09e0b7a47c
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 "SemaInherit.h"
15#include "Sema.h"
16#include "clang/AST/ASTContext.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  NamespaceDecl *StdNs = GetStdNamespace();
65  if (!StdNs)
66    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
67
68  if (isType)
69    // FIXME: Preserve type source info.
70    TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
71
72  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
73  Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
74  RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
75  if (!TypeInfoRecordDecl)
76    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
77
78  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
79
80  if (!isType) {
81    // C++0x [expr.typeid]p3:
82    //   When typeid is applied to an expression other than an lvalue of a
83    //   polymorphic class type [...] [the] expression is an unevaluated
84    //   operand.
85
86    // FIXME: if the type of the expression is a class type, the class
87    // shall be completely defined.
88    bool isUnevaluatedOperand = true;
89    Expr *E = static_cast<Expr *>(TyOrExpr);
90    if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
91      QualType T = E->getType();
92      if (const RecordType *RecordT = T->getAs<RecordType>()) {
93        CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
94        if (RecordD->isPolymorphic())
95          isUnevaluatedOperand = false;
96      }
97    }
98
99    // If this is an unevaluated operand, clear out the set of declaration
100    // references we have been computing.
101    if (isUnevaluatedOperand)
102      PotentiallyReferencedDeclStack.back().clear();
103  }
104
105  return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
106                                           TypeInfoType.withConst(),
107                                           SourceRange(OpLoc, RParenLoc)));
108}
109
110/// ActOnCXXBoolLiteral - Parse {true,false} literals.
111Action::OwningExprResult
112Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
113  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
114         "Unknown C++ Boolean value!");
115  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
116                                                Context.BoolTy, OpLoc));
117}
118
119/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
120Action::OwningExprResult
121Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
122  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
123}
124
125/// ActOnCXXThrow - Parse throw expressions.
126Action::OwningExprResult
127Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
128  Expr *Ex = E.takeAs<Expr>();
129  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
130    return ExprError();
131  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
132}
133
134/// CheckCXXThrowOperand - Validate the operand of a throw.
135bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
136  // C++ [except.throw]p3:
137  //   [...] adjusting the type from "array of T" or "function returning T"
138  //   to "pointer to T" or "pointer to function returning T", [...]
139  DefaultFunctionArrayConversion(E);
140
141  //   If the type of the exception would be an incomplete type or a pointer
142  //   to an incomplete type other than (cv) void the program is ill-formed.
143  QualType Ty = E->getType();
144  int isPointer = 0;
145  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
146    Ty = Ptr->getPointeeType();
147    isPointer = 1;
148  }
149  if (!isPointer || !Ty->isVoidType()) {
150    if (RequireCompleteType(ThrowLoc, Ty,
151                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
152                                            : diag::err_throw_incomplete)
153                              << E->getSourceRange()))
154      return true;
155  }
156
157  // FIXME: Construct a temporary here.
158  return false;
159}
160
161Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
162  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
163  /// is a non-lvalue expression whose value is the address of the object for
164  /// which the function is called.
165
166  if (!isa<FunctionDecl>(CurContext))
167    return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
168
169  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
170    if (MD->isInstance())
171      return Owned(new (Context) CXXThisExpr(ThisLoc,
172                                             MD->getThisType(Context)));
173
174  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
175}
176
177/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
178/// Can be interpreted either as function-style casting ("int(x)")
179/// or class type construction ("ClassType(x,y,z)")
180/// or creation of a value-initialized type ("int()").
181Action::OwningExprResult
182Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
183                                SourceLocation LParenLoc,
184                                MultiExprArg exprs,
185                                SourceLocation *CommaLocs,
186                                SourceLocation RParenLoc) {
187  assert(TypeRep && "Missing type!");
188  // FIXME: Preserve type source info.
189  QualType Ty = GetTypeFromParser(TypeRep);
190  unsigned NumExprs = exprs.size();
191  Expr **Exprs = (Expr**)exprs.get();
192  SourceLocation TyBeginLoc = TypeRange.getBegin();
193  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
194
195  if (Ty->isDependentType() ||
196      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
197    exprs.release();
198
199    return Owned(CXXUnresolvedConstructExpr::Create(Context,
200                                                    TypeRange.getBegin(), Ty,
201                                                    LParenLoc,
202                                                    Exprs, NumExprs,
203                                                    RParenLoc));
204  }
205
206  if (Ty->isArrayType())
207    return ExprError(Diag(TyBeginLoc,
208                          diag::err_value_init_for_array_type) << FullRange);
209  if (!Ty->isVoidType() &&
210      RequireCompleteType(TyBeginLoc, Ty,
211                          PDiag(diag::err_invalid_incomplete_type_use)
212                            << FullRange))
213    return ExprError();
214
215  if (RequireNonAbstractType(TyBeginLoc, Ty,
216                             diag::err_allocation_of_abstract_type))
217    return ExprError();
218
219
220  // C++ [expr.type.conv]p1:
221  // If the expression list is a single expression, the type conversion
222  // expression is equivalent (in definedness, and if defined in meaning) to the
223  // corresponding cast expression.
224  //
225  if (NumExprs == 1) {
226    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
227    CXXMethodDecl *ConversionDecl = 0;
228    if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, ConversionDecl,
229                       /*functional-style*/true))
230      return ExprError();
231    exprs.release();
232    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
233                                          Ty, TyBeginLoc,
234                                          CastExpr::CK_UserDefinedConversion,
235                                          Exprs[0], ConversionDecl,
236                                          RParenLoc));
237  }
238
239  if (const RecordType *RT = Ty->getAs<RecordType>()) {
240    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
241
242    if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
243        !Record->hasTrivialDestructor()) {
244      CXXConstructorDecl *Constructor
245        = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
246                                             TypeRange.getBegin(),
247                                             SourceRange(TypeRange.getBegin(),
248                                                         RParenLoc),
249                                             DeclarationName(),
250                                             IK_Direct);
251
252      if (!Constructor)
253        return ExprError();
254
255      OwningExprResult Result =
256        BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
257                                    move(exprs), RParenLoc);
258      if (Result.isInvalid())
259        return ExprError();
260
261      return MaybeBindToTemporary(Result.takeAs<Expr>());
262    }
263
264    // Fall through to value-initialize an object of class type that
265    // doesn't have a user-declared default constructor.
266  }
267
268  // C++ [expr.type.conv]p1:
269  // If the expression list specifies more than a single value, the type shall
270  // be a class with a suitably declared constructor.
271  //
272  if (NumExprs > 1)
273    return ExprError(Diag(CommaLocs[0],
274                          diag::err_builtin_func_cast_more_than_one_arg)
275      << FullRange);
276
277  assert(NumExprs == 0 && "Expected 0 expressions");
278
279  // C++ [expr.type.conv]p2:
280  // The expression T(), where T is a simple-type-specifier for a non-array
281  // complete object type or the (possibly cv-qualified) void type, creates an
282  // rvalue of the specified type, which is value-initialized.
283  //
284  exprs.release();
285  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
286}
287
288
289/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
290/// @code new (memory) int[size][4] @endcode
291/// or
292/// @code ::new Foo(23, "hello") @endcode
293/// For the interpretation of this heap of arguments, consult the base version.
294Action::OwningExprResult
295Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
296                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
297                  SourceLocation PlacementRParen, bool ParenTypeId,
298                  Declarator &D, SourceLocation ConstructorLParen,
299                  MultiExprArg ConstructorArgs,
300                  SourceLocation ConstructorRParen)
301{
302  Expr *ArraySize = 0;
303  unsigned Skip = 0;
304  // If the specified type is an array, unwrap it and save the expression.
305  if (D.getNumTypeObjects() > 0 &&
306      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
307    DeclaratorChunk &Chunk = D.getTypeObject(0);
308    if (Chunk.Arr.hasStatic)
309      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
310        << D.getSourceRange());
311    if (!Chunk.Arr.NumElts)
312      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
313        << D.getSourceRange());
314    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
315    Skip = 1;
316  }
317
318  //FIXME: Store DeclaratorInfo in CXXNew expression.
319  DeclaratorInfo *DInfo = 0;
320  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
321  if (D.isInvalidType())
322    return ExprError();
323
324  // Every dimension shall be of constant size.
325  unsigned i = 1;
326  QualType ElementType = AllocType;
327  while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
328    if (!Array->isConstantArrayType()) {
329      Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
330        << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
331      return ExprError();
332    }
333    ElementType = Array->getElementType();
334    ++i;
335  }
336
337  return BuildCXXNew(StartLoc, UseGlobal,
338                     PlacementLParen,
339                     move(PlacementArgs),
340                     PlacementRParen,
341                     ParenTypeId,
342                     AllocType,
343                     D.getSourceRange().getBegin(),
344                     D.getSourceRange(),
345                     Owned(ArraySize),
346                     ConstructorLParen,
347                     move(ConstructorArgs),
348                     ConstructorRParen);
349}
350
351Sema::OwningExprResult
352Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
353                  SourceLocation PlacementLParen,
354                  MultiExprArg PlacementArgs,
355                  SourceLocation PlacementRParen,
356                  bool ParenTypeId,
357                  QualType AllocType,
358                  SourceLocation TypeLoc,
359                  SourceRange TypeRange,
360                  ExprArg ArraySizeE,
361                  SourceLocation ConstructorLParen,
362                  MultiExprArg ConstructorArgs,
363                  SourceLocation ConstructorRParen) {
364  if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
365    return ExprError();
366
367  QualType ResultType = Context.getPointerType(AllocType);
368
369  // That every array dimension except the first is constant was already
370  // checked by the type check above.
371
372  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
373  //   or enumeration type with a non-negative value."
374  Expr *ArraySize = (Expr *)ArraySizeE.get();
375  if (ArraySize && !ArraySize->isTypeDependent()) {
376    QualType SizeType = ArraySize->getType();
377    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
378      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
379                            diag::err_array_size_not_integral)
380        << SizeType << ArraySize->getSourceRange());
381    // Let's see if this is a constant < 0. If so, we reject it out of hand.
382    // We don't care about special rules, so we tell the machinery it's not
383    // evaluated - it gives us a result in more cases.
384    if (!ArraySize->isValueDependent()) {
385      llvm::APSInt Value;
386      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
387        if (Value < llvm::APSInt(
388                        llvm::APInt::getNullValue(Value.getBitWidth()), false))
389          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
390                           diag::err_typecheck_negative_array_size)
391            << ArraySize->getSourceRange());
392      }
393    }
394  }
395
396  FunctionDecl *OperatorNew = 0;
397  FunctionDecl *OperatorDelete = 0;
398  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
399  unsigned NumPlaceArgs = PlacementArgs.size();
400  if (!AllocType->isDependentType() &&
401      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
402      FindAllocationFunctions(StartLoc,
403                              SourceRange(PlacementLParen, PlacementRParen),
404                              UseGlobal, AllocType, ArraySize, PlaceArgs,
405                              NumPlaceArgs, OperatorNew, OperatorDelete))
406    return ExprError();
407
408  bool Init = ConstructorLParen.isValid();
409  // --- Choosing a constructor ---
410  // C++ 5.3.4p15
411  // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
412  //   the object is not initialized. If the object, or any part of it, is
413  //   const-qualified, it's an error.
414  // 2) If T is a POD and there's an empty initializer, the object is value-
415  //   initialized.
416  // 3) If T is a POD and there's one initializer argument, the object is copy-
417  //   constructed.
418  // 4) If T is a POD and there's more initializer arguments, it's an error.
419  // 5) If T is not a POD, the initializer arguments are used as constructor
420  //   arguments.
421  //
422  // Or by the C++0x formulation:
423  // 1) If there's no initializer, the object is default-initialized according
424  //    to C++0x rules.
425  // 2) Otherwise, the object is direct-initialized.
426  CXXConstructorDecl *Constructor = 0;
427  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
428  const RecordType *RT;
429  unsigned NumConsArgs = ConstructorArgs.size();
430  if (AllocType->isDependentType()) {
431    // Skip all the checks.
432  } else if ((RT = AllocType->getAs<RecordType>()) &&
433             !AllocType->isAggregateType()) {
434    Constructor = PerformInitializationByConstructor(
435                      AllocType, ConsArgs, NumConsArgs,
436                      TypeLoc,
437                      SourceRange(TypeLoc, ConstructorRParen),
438                      RT->getDecl()->getDeclName(),
439                      NumConsArgs != 0 ? IK_Direct : IK_Default);
440    if (!Constructor)
441      return ExprError();
442  } else {
443    if (!Init) {
444      // FIXME: Check that no subpart is const.
445      if (AllocType.isConstQualified())
446        return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
447                           << TypeRange);
448    } else if (NumConsArgs == 0) {
449      // Object is value-initialized. Do nothing.
450    } else if (NumConsArgs == 1) {
451      // Object is direct-initialized.
452      // FIXME: What DeclarationName do we pass in here?
453      if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
454                                DeclarationName() /*AllocType.getAsString()*/,
455                                /*DirectInit=*/true))
456        return ExprError();
457    } else {
458      return ExprError(Diag(StartLoc,
459                            diag::err_builtin_direct_init_more_than_one_arg)
460        << SourceRange(ConstructorLParen, ConstructorRParen));
461    }
462  }
463
464  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
465
466  PlacementArgs.release();
467  ConstructorArgs.release();
468  ArraySizeE.release();
469  return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
470                        NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
471                        ConsArgs, NumConsArgs, OperatorDelete, ResultType,
472                        StartLoc, Init ? ConstructorRParen : SourceLocation()));
473}
474
475/// CheckAllocatedType - Checks that a type is suitable as the allocated type
476/// in a new-expression.
477/// dimension off and stores the size expression in ArraySize.
478bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
479                              SourceRange R)
480{
481  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
482  //   abstract class type or array thereof.
483  if (AllocType->isFunctionType())
484    return Diag(Loc, diag::err_bad_new_type)
485      << AllocType << 0 << R;
486  else if (AllocType->isReferenceType())
487    return Diag(Loc, diag::err_bad_new_type)
488      << AllocType << 1 << R;
489  else if (!AllocType->isDependentType() &&
490           RequireCompleteType(Loc, AllocType,
491                               PDiag(diag::err_new_incomplete_type)
492                                 << R))
493    return true;
494  else if (RequireNonAbstractType(Loc, AllocType,
495                                  diag::err_allocation_of_abstract_type))
496    return true;
497
498  return false;
499}
500
501/// FindAllocationFunctions - Finds the overloads of operator new and delete
502/// that are appropriate for the allocation.
503bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
504                                   bool UseGlobal, QualType AllocType,
505                                   bool IsArray, Expr **PlaceArgs,
506                                   unsigned NumPlaceArgs,
507                                   FunctionDecl *&OperatorNew,
508                                   FunctionDecl *&OperatorDelete)
509{
510  // --- Choosing an allocation function ---
511  // C++ 5.3.4p8 - 14 & 18
512  // 1) If UseGlobal is true, only look in the global scope. Else, also look
513  //   in the scope of the allocated class.
514  // 2) If an array size is given, look for operator new[], else look for
515  //   operator new.
516  // 3) The first argument is always size_t. Append the arguments from the
517  //   placement form.
518  // FIXME: Also find the appropriate delete operator.
519
520  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
521  // We don't care about the actual value of this argument.
522  // FIXME: Should the Sema create the expression and embed it in the syntax
523  // tree? Or should the consumer just recalculate the value?
524  IntegerLiteral Size(llvm::APInt::getNullValue(
525                      Context.Target.getPointerWidth(0)),
526                      Context.getSizeType(),
527                      SourceLocation());
528  AllocArgs[0] = &Size;
529  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
530
531  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
532                                        IsArray ? OO_Array_New : OO_New);
533  if (AllocType->isRecordType() && !UseGlobal) {
534    CXXRecordDecl *Record
535      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
536    // FIXME: We fail to find inherited overloads.
537    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
538                          AllocArgs.size(), Record, /*AllowMissing=*/true,
539                          OperatorNew))
540      return true;
541  }
542  if (!OperatorNew) {
543    // Didn't find a member overload. Look for a global one.
544    DeclareGlobalNewDelete();
545    DeclContext *TUDecl = Context.getTranslationUnitDecl();
546    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
547                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
548                          OperatorNew))
549      return true;
550  }
551
552  // FindAllocationOverload can change the passed in arguments, so we need to
553  // copy them back.
554  if (NumPlaceArgs > 0)
555    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
556
557  return false;
558}
559
560/// FindAllocationOverload - Find an fitting overload for the allocation
561/// function in the specified scope.
562bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
563                                  DeclarationName Name, Expr** Args,
564                                  unsigned NumArgs, DeclContext *Ctx,
565                                  bool AllowMissing, FunctionDecl *&Operator)
566{
567  DeclContext::lookup_iterator Alloc, AllocEnd;
568  llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
569  if (Alloc == AllocEnd) {
570    if (AllowMissing)
571      return false;
572    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
573      << Name << Range;
574  }
575
576  OverloadCandidateSet Candidates;
577  for (; Alloc != AllocEnd; ++Alloc) {
578    // Even member operator new/delete are implicitly treated as
579    // static, so don't use AddMemberCandidate.
580    if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
581      AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
582                           /*SuppressUserConversions=*/false);
583  }
584
585  // Do the resolution.
586  OverloadCandidateSet::iterator Best;
587  switch(BestViableFunction(Candidates, StartLoc, Best)) {
588  case OR_Success: {
589    // Got one!
590    FunctionDecl *FnDecl = Best->Function;
591    // The first argument is size_t, and the first parameter must be size_t,
592    // too. This is checked on declaration and can be assumed. (It can't be
593    // asserted on, though, since invalid decls are left in there.)
594    for (unsigned i = 1; i < NumArgs; ++i) {
595      // FIXME: Passing word to diagnostic.
596      if (PerformCopyInitialization(Args[i],
597                                    FnDecl->getParamDecl(i)->getType(),
598                                    "passing"))
599        return true;
600    }
601    Operator = FnDecl;
602    return false;
603  }
604
605  case OR_No_Viable_Function:
606    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
607      << Name << Range;
608    PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
609    return true;
610
611  case OR_Ambiguous:
612    Diag(StartLoc, diag::err_ovl_ambiguous_call)
613      << Name << Range;
614    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
615    return true;
616
617  case OR_Deleted:
618    Diag(StartLoc, diag::err_ovl_deleted_call)
619      << Best->Function->isDeleted()
620      << Name << Range;
621    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
622    return true;
623  }
624  assert(false && "Unreachable, bad result from BestViableFunction");
625  return true;
626}
627
628
629/// DeclareGlobalNewDelete - Declare the global forms of operator new and
630/// delete. These are:
631/// @code
632///   void* operator new(std::size_t) throw(std::bad_alloc);
633///   void* operator new[](std::size_t) throw(std::bad_alloc);
634///   void operator delete(void *) throw();
635///   void operator delete[](void *) throw();
636/// @endcode
637/// Note that the placement and nothrow forms of new are *not* implicitly
638/// declared. Their use requires including \<new\>.
639void Sema::DeclareGlobalNewDelete()
640{
641  if (GlobalNewDeleteDeclared)
642    return;
643  GlobalNewDeleteDeclared = true;
644
645  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
646  QualType SizeT = Context.getSizeType();
647
648  // FIXME: Exception specifications are not added.
649  DeclareGlobalAllocationFunction(
650      Context.DeclarationNames.getCXXOperatorName(OO_New),
651      VoidPtr, SizeT);
652  DeclareGlobalAllocationFunction(
653      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
654      VoidPtr, SizeT);
655  DeclareGlobalAllocationFunction(
656      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
657      Context.VoidTy, VoidPtr);
658  DeclareGlobalAllocationFunction(
659      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
660      Context.VoidTy, VoidPtr);
661}
662
663/// DeclareGlobalAllocationFunction - Declares a single implicit global
664/// allocation function if it doesn't already exist.
665void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
666                                           QualType Return, QualType Argument)
667{
668  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
669
670  // Check if this function is already declared.
671  {
672    DeclContext::lookup_iterator Alloc, AllocEnd;
673    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
674         Alloc != AllocEnd; ++Alloc) {
675      // FIXME: Do we need to check for default arguments here?
676      FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
677      if (Func->getNumParams() == 1 &&
678          Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
679        return;
680    }
681  }
682
683  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
684  FunctionDecl *Alloc =
685    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
686                         FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
687  Alloc->setImplicit();
688  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
689                                           0, Argument, /*DInfo=*/0,
690                                           VarDecl::None, 0);
691  Alloc->setParams(Context, &Param, 1);
692
693  // FIXME: Also add this declaration to the IdentifierResolver, but
694  // make sure it is at the end of the chain to coincide with the
695  // global scope.
696  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
697}
698
699/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
700/// @code ::delete ptr; @endcode
701/// or
702/// @code delete [] ptr; @endcode
703Action::OwningExprResult
704Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
705                     bool ArrayForm, ExprArg Operand)
706{
707  // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
708  //   having a single conversion function to a pointer type. The result has
709  //   type void."
710  // DR599 amends "pointer type" to "pointer to object type" in both cases.
711
712  FunctionDecl *OperatorDelete = 0;
713
714  Expr *Ex = (Expr *)Operand.get();
715  if (!Ex->isTypeDependent()) {
716    QualType Type = Ex->getType();
717
718    if (Type->isRecordType()) {
719      // FIXME: Find that one conversion function and amend the type.
720    }
721
722    if (!Type->isPointerType())
723      return ExprError(Diag(StartLoc, diag::err_delete_operand)
724        << Type << Ex->getSourceRange());
725
726    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
727    if (Pointee->isFunctionType() || Pointee->isVoidType())
728      return ExprError(Diag(StartLoc, diag::err_delete_operand)
729        << Type << Ex->getSourceRange());
730    else if (!Pointee->isDependentType() &&
731             RequireCompleteType(StartLoc, Pointee,
732                                 PDiag(diag::warn_delete_incomplete)
733                                   << Ex->getSourceRange()))
734      return ExprError();
735
736    // FIXME: This should be shared with the code for finding the delete
737    // operator in ActOnCXXNew.
738    IntegerLiteral Size(llvm::APInt::getNullValue(
739                        Context.Target.getPointerWidth(0)),
740                        Context.getSizeType(),
741                        SourceLocation());
742    ImplicitCastExpr Cast(Context.getPointerType(Context.VoidTy),
743                          CastExpr::CK_Unknown, &Size, false);
744    Expr *DeleteArg = &Cast;
745
746    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
747                                      ArrayForm ? OO_Array_Delete : OO_Delete);
748
749    if (Pointee->isRecordType() && !UseGlobal) {
750      CXXRecordDecl *Record
751        = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
752      // FIXME: We fail to find inherited overloads.
753      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
754                                 &DeleteArg, 1, Record, /*AllowMissing=*/true,
755                                 OperatorDelete))
756        return ExprError();
757    }
758
759    if (!OperatorDelete) {
760      // Didn't find a member overload. Look for a global one.
761      DeclareGlobalNewDelete();
762      DeclContext *TUDecl = Context.getTranslationUnitDecl();
763      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
764                                 &DeleteArg, 1, TUDecl, /*AllowMissing=*/false,
765                                 OperatorDelete))
766        return ExprError();
767    }
768
769    // FIXME: Check access and ambiguity of operator delete and destructor.
770  }
771
772  Operand.release();
773  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
774                                           OperatorDelete, Ex, StartLoc));
775}
776
777
778/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
779/// C++ if/switch/while/for statement.
780/// e.g: "if (int x = f()) {...}"
781Action::OwningExprResult
782Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
783                                       Declarator &D,
784                                       SourceLocation EqualLoc,
785                                       ExprArg AssignExprVal) {
786  assert(AssignExprVal.get() && "Null assignment expression");
787
788  // C++ 6.4p2:
789  // The declarator shall not specify a function or an array.
790  // The type-specifier-seq shall not contain typedef and shall not declare a
791  // new class or enumeration.
792
793  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
794         "Parser allowed 'typedef' as storage class of condition decl.");
795
796  // FIXME: Store DeclaratorInfo in the expression.
797  DeclaratorInfo *DInfo = 0;
798  TagDecl *OwnedTag = 0;
799  QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
800
801  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
802    // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
803    // would be created and CXXConditionDeclExpr wants a VarDecl.
804    return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
805      << SourceRange(StartLoc, EqualLoc));
806  } else if (Ty->isArrayType()) { // ...or an array.
807    Diag(StartLoc, diag::err_invalid_use_of_array_type)
808      << SourceRange(StartLoc, EqualLoc);
809  } else if (OwnedTag && OwnedTag->isDefinition()) {
810    // The type-specifier-seq shall not declare a new class or enumeration.
811    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
812  }
813
814  DeclPtrTy Dcl = ActOnDeclarator(S, D);
815  if (!Dcl)
816    return ExprError();
817  AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
818
819  // Mark this variable as one that is declared within a conditional.
820  // We know that the decl had to be a VarDecl because that is the only type of
821  // decl that can be assigned and the grammar requires an '='.
822  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
823  VD->setDeclaredInCondition(true);
824  return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
825}
826
827/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
828bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
829  // C++ 6.4p4:
830  // The value of a condition that is an initialized declaration in a statement
831  // other than a switch statement is the value of the declared variable
832  // implicitly converted to type bool. If that conversion is ill-formed, the
833  // program is ill-formed.
834  // The value of a condition that is an expression is the value of the
835  // expression, implicitly converted to bool.
836  //
837  return PerformContextuallyConvertToBool(CondExpr);
838}
839
840/// Helper function to determine whether this is the (deprecated) C++
841/// conversion from a string literal to a pointer to non-const char or
842/// non-const wchar_t (for narrow and wide string literals,
843/// respectively).
844bool
845Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
846  // Look inside the implicit cast, if it exists.
847  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
848    From = Cast->getSubExpr();
849
850  // A string literal (2.13.4) that is not a wide string literal can
851  // be converted to an rvalue of type "pointer to char"; a wide
852  // string literal can be converted to an rvalue of type "pointer
853  // to wchar_t" (C++ 4.2p2).
854  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
855    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
856      if (const BuiltinType *ToPointeeType
857          = ToPtrType->getPointeeType()->getAsBuiltinType()) {
858        // This conversion is considered only when there is an
859        // explicit appropriate pointer target type (C++ 4.2p2).
860        if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
861            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
862             (!StrLit->isWide() &&
863              (ToPointeeType->getKind() == BuiltinType::Char_U ||
864               ToPointeeType->getKind() == BuiltinType::Char_S))))
865          return true;
866      }
867
868  return false;
869}
870
871/// PerformImplicitConversion - Perform an implicit conversion of the
872/// expression From to the type ToType. Returns true if there was an
873/// error, false otherwise. The expression From is replaced with the
874/// converted expression. Flavor is the kind of conversion we're
875/// performing, used in the error message. If @p AllowExplicit,
876/// explicit user-defined conversions are permitted. @p Elidable should be true
877/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
878/// resolution works differently in that case.
879bool
880Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
881                                const char *Flavor, bool AllowExplicit,
882                                bool Elidable)
883{
884  ImplicitConversionSequence ICS;
885  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
886  if (Elidable && getLangOptions().CPlusPlus0x) {
887    ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
888                                AllowExplicit, /*ForceRValue*/true);
889  }
890  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
891    ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
892  }
893  return PerformImplicitConversion(From, ToType, ICS, Flavor);
894}
895
896/// PerformImplicitConversion - Perform an implicit conversion of the
897/// expression From to the type ToType using the pre-computed implicit
898/// conversion sequence ICS. Returns true if there was an error, false
899/// otherwise. The expression From is replaced with the converted
900/// expression. Flavor is the kind of conversion we're performing,
901/// used in the error message.
902bool
903Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
904                                const ImplicitConversionSequence &ICS,
905                                const char* Flavor) {
906  switch (ICS.ConversionKind) {
907  case ImplicitConversionSequence::StandardConversion:
908    if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
909      return true;
910    break;
911
912  case ImplicitConversionSequence::UserDefinedConversion:
913      // FIXME. Support other kinds of user defined convesions.
914      if (CXXConversionDecl *CV =
915            dyn_cast<CXXConversionDecl>(ICS.UserDefined.ConversionFunction))
916        // FIXME. Get actual Source Location.
917        From =
918          new (Context) CXXFunctionalCastExpr(ToType.getNonReferenceType(),
919                                            ToType, SourceLocation(),
920                                            CastExpr::CK_UserDefinedConversion,
921                                            From, CV,
922                                            SourceLocation());
923    ImpCastExprToType(From, ToType.getNonReferenceType(),
924                      CastExpr::CK_Unknown,
925                      ToType->isLValueReferenceType());
926    return false;
927
928  case ImplicitConversionSequence::EllipsisConversion:
929    assert(false && "Cannot perform an ellipsis conversion");
930    return false;
931
932  case ImplicitConversionSequence::BadConversion:
933    return true;
934  }
935
936  // Everything went well.
937  return false;
938}
939
940/// PerformImplicitConversion - Perform an implicit conversion of the
941/// expression From to the type ToType by following the standard
942/// conversion sequence SCS. Returns true if there was an error, false
943/// otherwise. The expression From is replaced with the converted
944/// expression. Flavor is the context in which we're performing this
945/// conversion, for use in error messages.
946bool
947Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
948                                const StandardConversionSequence& SCS,
949                                const char *Flavor) {
950  // Overall FIXME: we are recomputing too many types here and doing far too
951  // much extra work. What this means is that we need to keep track of more
952  // information that is computed when we try the implicit conversion initially,
953  // so that we don't need to recompute anything here.
954  QualType FromType = From->getType();
955
956  if (SCS.CopyConstructor) {
957    // FIXME: When can ToType be a reference type?
958    assert(!ToType->isReferenceType());
959
960    OwningExprResult FromResult =
961      BuildCXXConstructExpr(ToType, SCS.CopyConstructor, &From, 1);
962
963    if (FromResult.isInvalid())
964      return true;
965
966    From = FromResult.takeAs<Expr>();
967    return false;
968  }
969
970  // Perform the first implicit conversion.
971  switch (SCS.First) {
972  case ICK_Identity:
973  case ICK_Lvalue_To_Rvalue:
974    // Nothing to do.
975    break;
976
977  case ICK_Array_To_Pointer:
978    FromType = Context.getArrayDecayedType(FromType);
979    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
980    break;
981
982  case ICK_Function_To_Pointer:
983    if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
984      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
985      if (!Fn)
986        return true;
987
988      if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
989        return true;
990
991      FixOverloadedFunctionReference(From, Fn);
992      FromType = From->getType();
993    }
994    FromType = Context.getPointerType(FromType);
995    ImpCastExprToType(From, FromType);
996    break;
997
998  default:
999    assert(false && "Improper first standard conversion");
1000    break;
1001  }
1002
1003  // Perform the second implicit conversion
1004  switch (SCS.Second) {
1005  case ICK_Identity:
1006    // Nothing to do.
1007    break;
1008
1009  case ICK_Integral_Promotion:
1010  case ICK_Floating_Promotion:
1011  case ICK_Complex_Promotion:
1012  case ICK_Integral_Conversion:
1013  case ICK_Floating_Conversion:
1014  case ICK_Complex_Conversion:
1015  case ICK_Floating_Integral:
1016  case ICK_Complex_Real:
1017  case ICK_Compatible_Conversion:
1018      // FIXME: Go deeper to get the unqualified type!
1019    FromType = ToType.getUnqualifiedType();
1020    ImpCastExprToType(From, FromType);
1021    break;
1022
1023  case ICK_Pointer_Conversion:
1024    if (SCS.IncompatibleObjC) {
1025      // Diagnose incompatible Objective-C conversions
1026      Diag(From->getSourceRange().getBegin(),
1027           diag::ext_typecheck_convert_incompatible_pointer)
1028        << From->getType() << ToType << Flavor
1029        << From->getSourceRange();
1030    }
1031
1032    if (CheckPointerConversion(From, ToType))
1033      return true;
1034    ImpCastExprToType(From, ToType);
1035    break;
1036
1037    case ICK_Pointer_Member: {
1038      CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1039      if (CheckMemberPointerConversion(From, ToType, Kind))
1040        return true;
1041      ImpCastExprToType(From, ToType, Kind);
1042      break;
1043    }
1044  case ICK_Boolean_Conversion:
1045    FromType = Context.BoolTy;
1046    ImpCastExprToType(From, FromType);
1047    break;
1048
1049  default:
1050    assert(false && "Improper second standard conversion");
1051    break;
1052  }
1053
1054  switch (SCS.Third) {
1055  case ICK_Identity:
1056    // Nothing to do.
1057    break;
1058
1059  case ICK_Qualification:
1060    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1061    // references.
1062    ImpCastExprToType(From, ToType.getNonReferenceType(),
1063                      CastExpr::CK_Unknown,
1064                      ToType->isLValueReferenceType());
1065    break;
1066
1067  default:
1068    assert(false && "Improper second standard conversion");
1069    break;
1070  }
1071
1072  return false;
1073}
1074
1075Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1076                                                 SourceLocation KWLoc,
1077                                                 SourceLocation LParen,
1078                                                 TypeTy *Ty,
1079                                                 SourceLocation RParen) {
1080  QualType T = GetTypeFromParser(Ty);
1081
1082  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1083  // all traits except __is_class, __is_enum and __is_union require a the type
1084  // to be complete.
1085  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1086    if (RequireCompleteType(KWLoc, T,
1087                            diag::err_incomplete_type_used_in_type_trait_expr))
1088      return ExprError();
1089  }
1090
1091  // There is no point in eagerly computing the value. The traits are designed
1092  // to be used from type trait templates, so Ty will be a template parameter
1093  // 99% of the time.
1094  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1095                                                RParen, Context.BoolTy));
1096}
1097
1098QualType Sema::CheckPointerToMemberOperands(
1099  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1100{
1101  const char *OpSpelling = isIndirect ? "->*" : ".*";
1102  // C++ 5.5p2
1103  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1104  //   be of type "pointer to member of T" (where T is a completely-defined
1105  //   class type) [...]
1106  QualType RType = rex->getType();
1107  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1108  if (!MemPtr) {
1109    Diag(Loc, diag::err_bad_memptr_rhs)
1110      << OpSpelling << RType << rex->getSourceRange();
1111    return QualType();
1112  }
1113
1114  QualType Class(MemPtr->getClass(), 0);
1115
1116  // C++ 5.5p2
1117  //   [...] to its first operand, which shall be of class T or of a class of
1118  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1119  //   such a class]
1120  QualType LType = lex->getType();
1121  if (isIndirect) {
1122    if (const PointerType *Ptr = LType->getAs<PointerType>())
1123      LType = Ptr->getPointeeType().getNonReferenceType();
1124    else {
1125      Diag(Loc, diag::err_bad_memptr_lhs)
1126        << OpSpelling << 1 << LType << lex->getSourceRange();
1127      return QualType();
1128    }
1129  }
1130
1131  if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1132      Context.getCanonicalType(LType).getUnqualifiedType()) {
1133    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1134                    /*DetectVirtual=*/false);
1135    // FIXME: Would it be useful to print full ambiguity paths, or is that
1136    // overkill?
1137    if (!IsDerivedFrom(LType, Class, Paths) ||
1138        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1139      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1140        << (int)isIndirect << lex->getType() << lex->getSourceRange();
1141      return QualType();
1142    }
1143  }
1144
1145  // C++ 5.5p2
1146  //   The result is an object or a function of the type specified by the
1147  //   second operand.
1148  // The cv qualifiers are the union of those in the pointer and the left side,
1149  // in accordance with 5.5p5 and 5.2.5.
1150  // FIXME: This returns a dereferenced member function pointer as a normal
1151  // function type. However, the only operation valid on such functions is
1152  // calling them. There's also a GCC extension to get a function pointer to the
1153  // thing, which is another complication, because this type - unlike the type
1154  // that is the result of this expression - takes the class as the first
1155  // argument.
1156  // We probably need a "MemberFunctionClosureType" or something like that.
1157  QualType Result = MemPtr->getPointeeType();
1158  if (LType.isConstQualified())
1159    Result.addConst();
1160  if (LType.isVolatileQualified())
1161    Result.addVolatile();
1162  return Result;
1163}
1164
1165/// \brief Get the target type of a standard or user-defined conversion.
1166static QualType TargetType(const ImplicitConversionSequence &ICS) {
1167  assert((ICS.ConversionKind ==
1168              ImplicitConversionSequence::StandardConversion ||
1169          ICS.ConversionKind ==
1170              ImplicitConversionSequence::UserDefinedConversion) &&
1171         "function only valid for standard or user-defined conversions");
1172  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1173    return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1174  return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1175}
1176
1177/// \brief Try to convert a type to another according to C++0x 5.16p3.
1178///
1179/// This is part of the parameter validation for the ? operator. If either
1180/// value operand is a class type, the two operands are attempted to be
1181/// converted to each other. This function does the conversion in one direction.
1182/// It emits a diagnostic and returns true only if it finds an ambiguous
1183/// conversion.
1184static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1185                                SourceLocation QuestionLoc,
1186                                ImplicitConversionSequence &ICS)
1187{
1188  // C++0x 5.16p3
1189  //   The process for determining whether an operand expression E1 of type T1
1190  //   can be converted to match an operand expression E2 of type T2 is defined
1191  //   as follows:
1192  //   -- If E2 is an lvalue:
1193  if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1194    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1195    //   type "lvalue reference to T2", subject to the constraint that in the
1196    //   conversion the reference must bind directly to E1.
1197    if (!Self.CheckReferenceInit(From,
1198                            Self.Context.getLValueReferenceType(To->getType()),
1199                            &ICS))
1200    {
1201      assert((ICS.ConversionKind ==
1202                  ImplicitConversionSequence::StandardConversion ||
1203              ICS.ConversionKind ==
1204                  ImplicitConversionSequence::UserDefinedConversion) &&
1205             "expected a definite conversion");
1206      bool DirectBinding =
1207        ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1208        ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1209      if (DirectBinding)
1210        return false;
1211    }
1212  }
1213  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1214  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1215  //      -- if E1 and E2 have class type, and the underlying class types are
1216  //         the same or one is a base class of the other:
1217  QualType FTy = From->getType();
1218  QualType TTy = To->getType();
1219  const RecordType *FRec = FTy->getAs<RecordType>();
1220  const RecordType *TRec = TTy->getAs<RecordType>();
1221  bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1222  if (FRec && TRec && (FRec == TRec ||
1223        FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1224    //         E1 can be converted to match E2 if the class of T2 is the
1225    //         same type as, or a base class of, the class of T1, and
1226    //         [cv2 > cv1].
1227    if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1228      // Could still fail if there's no copy constructor.
1229      // FIXME: Is this a hard error then, or just a conversion failure? The
1230      // standard doesn't say.
1231      ICS = Self.TryCopyInitialization(From, TTy);
1232    }
1233  } else {
1234    //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1235    //        implicitly converted to the type that expression E2 would have
1236    //        if E2 were converted to an rvalue.
1237    // First find the decayed type.
1238    if (TTy->isFunctionType())
1239      TTy = Self.Context.getPointerType(TTy);
1240    else if(TTy->isArrayType())
1241      TTy = Self.Context.getArrayDecayedType(TTy);
1242
1243    // Now try the implicit conversion.
1244    // FIXME: This doesn't detect ambiguities.
1245    ICS = Self.TryImplicitConversion(From, TTy);
1246  }
1247  return false;
1248}
1249
1250/// \brief Try to find a common type for two according to C++0x 5.16p5.
1251///
1252/// This is part of the parameter validation for the ? operator. If either
1253/// value operand is a class type, overload resolution is used to find a
1254/// conversion to a common type.
1255static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1256                                    SourceLocation Loc) {
1257  Expr *Args[2] = { LHS, RHS };
1258  OverloadCandidateSet CandidateSet;
1259  Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1260
1261  OverloadCandidateSet::iterator Best;
1262  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
1263    case Sema::OR_Success:
1264      // We found a match. Perform the conversions on the arguments and move on.
1265      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1266                                         Best->Conversions[0], "converting") ||
1267          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1268                                         Best->Conversions[1], "converting"))
1269        break;
1270      return false;
1271
1272    case Sema::OR_No_Viable_Function:
1273      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1274        << LHS->getType() << RHS->getType()
1275        << LHS->getSourceRange() << RHS->getSourceRange();
1276      return true;
1277
1278    case Sema::OR_Ambiguous:
1279      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1280        << LHS->getType() << RHS->getType()
1281        << LHS->getSourceRange() << RHS->getSourceRange();
1282      // FIXME: Print the possible common types by printing the return types of
1283      // the viable candidates.
1284      break;
1285
1286    case Sema::OR_Deleted:
1287      assert(false && "Conditional operator has only built-in overloads");
1288      break;
1289  }
1290  return true;
1291}
1292
1293/// \brief Perform an "extended" implicit conversion as returned by
1294/// TryClassUnification.
1295///
1296/// TryClassUnification generates ICSs that include reference bindings.
1297/// PerformImplicitConversion is not suitable for this; it chokes if the
1298/// second part of a standard conversion is ICK_DerivedToBase. This function
1299/// handles the reference binding specially.
1300static bool ConvertForConditional(Sema &Self, Expr *&E,
1301                                  const ImplicitConversionSequence &ICS)
1302{
1303  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1304      ICS.Standard.ReferenceBinding) {
1305    assert(ICS.Standard.DirectBinding &&
1306           "TryClassUnification should never generate indirect ref bindings");
1307    // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1308    // redoing all the work.
1309    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1310                                        TargetType(ICS)));
1311  }
1312  if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1313      ICS.UserDefined.After.ReferenceBinding) {
1314    assert(ICS.UserDefined.After.DirectBinding &&
1315           "TryClassUnification should never generate indirect ref bindings");
1316    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1317                                        TargetType(ICS)));
1318  }
1319  if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1320    return true;
1321  return false;
1322}
1323
1324/// \brief Check the operands of ?: under C++ semantics.
1325///
1326/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1327/// extension. In this case, LHS == Cond. (But they're not aliases.)
1328QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1329                                           SourceLocation QuestionLoc) {
1330  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1331  // interface pointers.
1332
1333  // C++0x 5.16p1
1334  //   The first expression is contextually converted to bool.
1335  if (!Cond->isTypeDependent()) {
1336    if (CheckCXXBooleanCondition(Cond))
1337      return QualType();
1338  }
1339
1340  // Either of the arguments dependent?
1341  if (LHS->isTypeDependent() || RHS->isTypeDependent())
1342    return Context.DependentTy;
1343
1344  // C++0x 5.16p2
1345  //   If either the second or the third operand has type (cv) void, ...
1346  QualType LTy = LHS->getType();
1347  QualType RTy = RHS->getType();
1348  bool LVoid = LTy->isVoidType();
1349  bool RVoid = RTy->isVoidType();
1350  if (LVoid || RVoid) {
1351    //   ... then the [l2r] conversions are performed on the second and third
1352    //   operands ...
1353    DefaultFunctionArrayConversion(LHS);
1354    DefaultFunctionArrayConversion(RHS);
1355    LTy = LHS->getType();
1356    RTy = RHS->getType();
1357
1358    //   ... and one of the following shall hold:
1359    //   -- The second or the third operand (but not both) is a throw-
1360    //      expression; the result is of the type of the other and is an rvalue.
1361    bool LThrow = isa<CXXThrowExpr>(LHS);
1362    bool RThrow = isa<CXXThrowExpr>(RHS);
1363    if (LThrow && !RThrow)
1364      return RTy;
1365    if (RThrow && !LThrow)
1366      return LTy;
1367
1368    //   -- Both the second and third operands have type void; the result is of
1369    //      type void and is an rvalue.
1370    if (LVoid && RVoid)
1371      return Context.VoidTy;
1372
1373    // Neither holds, error.
1374    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1375      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1376      << LHS->getSourceRange() << RHS->getSourceRange();
1377    return QualType();
1378  }
1379
1380  // Neither is void.
1381
1382  // C++0x 5.16p3
1383  //   Otherwise, if the second and third operand have different types, and
1384  //   either has (cv) class type, and attempt is made to convert each of those
1385  //   operands to the other.
1386  if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1387      (LTy->isRecordType() || RTy->isRecordType())) {
1388    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1389    // These return true if a single direction is already ambiguous.
1390    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1391      return QualType();
1392    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1393      return QualType();
1394
1395    bool HaveL2R = ICSLeftToRight.ConversionKind !=
1396      ImplicitConversionSequence::BadConversion;
1397    bool HaveR2L = ICSRightToLeft.ConversionKind !=
1398      ImplicitConversionSequence::BadConversion;
1399    //   If both can be converted, [...] the program is ill-formed.
1400    if (HaveL2R && HaveR2L) {
1401      Diag(QuestionLoc, diag::err_conditional_ambiguous)
1402        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1403      return QualType();
1404    }
1405
1406    //   If exactly one conversion is possible, that conversion is applied to
1407    //   the chosen operand and the converted operands are used in place of the
1408    //   original operands for the remainder of this section.
1409    if (HaveL2R) {
1410      if (ConvertForConditional(*this, LHS, ICSLeftToRight))
1411        return QualType();
1412      LTy = LHS->getType();
1413    } else if (HaveR2L) {
1414      if (ConvertForConditional(*this, RHS, ICSRightToLeft))
1415        return QualType();
1416      RTy = RHS->getType();
1417    }
1418  }
1419
1420  // C++0x 5.16p4
1421  //   If the second and third operands are lvalues and have the same type,
1422  //   the result is of that type [...]
1423  bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1424  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1425      RHS->isLvalue(Context) == Expr::LV_Valid)
1426    return LTy;
1427
1428  // C++0x 5.16p5
1429  //   Otherwise, the result is an rvalue. If the second and third operands
1430  //   do not have the same type, and either has (cv) class type, ...
1431  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1432    //   ... overload resolution is used to determine the conversions (if any)
1433    //   to be applied to the operands. If the overload resolution fails, the
1434    //   program is ill-formed.
1435    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1436      return QualType();
1437  }
1438
1439  // C++0x 5.16p6
1440  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1441  //   conversions are performed on the second and third operands.
1442  DefaultFunctionArrayConversion(LHS);
1443  DefaultFunctionArrayConversion(RHS);
1444  LTy = LHS->getType();
1445  RTy = RHS->getType();
1446
1447  //   After those conversions, one of the following shall hold:
1448  //   -- The second and third operands have the same type; the result
1449  //      is of that type.
1450  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1451    return LTy;
1452
1453  //   -- The second and third operands have arithmetic or enumeration type;
1454  //      the usual arithmetic conversions are performed to bring them to a
1455  //      common type, and the result is of that type.
1456  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1457    UsualArithmeticConversions(LHS, RHS);
1458    return LHS->getType();
1459  }
1460
1461  //   -- The second and third operands have pointer type, or one has pointer
1462  //      type and the other is a null pointer constant; pointer conversions
1463  //      and qualification conversions are performed to bring them to their
1464  //      composite pointer type. The result is of the composite pointer type.
1465  QualType Composite = FindCompositePointerType(LHS, RHS);
1466  if (!Composite.isNull())
1467    return Composite;
1468
1469  // Fourth bullet is same for pointers-to-member. However, the possible
1470  // conversions are far more limited: we have null-to-pointer, upcast of
1471  // containing class, and second-level cv-ness.
1472  // cv-ness is not a union, but must match one of the two operands. (Which,
1473  // frankly, is stupid.)
1474  const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1475  const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
1476  if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1477    ImpCastExprToType(RHS, LTy);
1478    return LTy;
1479  }
1480  if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1481    ImpCastExprToType(LHS, RTy);
1482    return RTy;
1483  }
1484  if (LMemPtr && RMemPtr) {
1485    QualType LPointee = LMemPtr->getPointeeType();
1486    QualType RPointee = RMemPtr->getPointeeType();
1487    // First, we check that the unqualified pointee type is the same. If it's
1488    // not, there's no conversion that will unify the two pointers.
1489    if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1490        Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1491      // Second, we take the greater of the two cv qualifications. If neither
1492      // is greater than the other, the conversion is not possible.
1493      unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1494      if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1495        // Third, we check if either of the container classes is derived from
1496        // the other.
1497        QualType LContainer(LMemPtr->getClass(), 0);
1498        QualType RContainer(RMemPtr->getClass(), 0);
1499        QualType MoreDerived;
1500        if (Context.getCanonicalType(LContainer) ==
1501            Context.getCanonicalType(RContainer))
1502          MoreDerived = LContainer;
1503        else if (IsDerivedFrom(LContainer, RContainer))
1504          MoreDerived = LContainer;
1505        else if (IsDerivedFrom(RContainer, LContainer))
1506          MoreDerived = RContainer;
1507
1508        if (!MoreDerived.isNull()) {
1509          // The type 'Q Pointee (MoreDerived::*)' is the common type.
1510          // We don't use ImpCastExprToType here because this could still fail
1511          // for ambiguous or inaccessible conversions.
1512          QualType Common = Context.getMemberPointerType(
1513            LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1514          if (PerformImplicitConversion(LHS, Common, "converting"))
1515            return QualType();
1516          if (PerformImplicitConversion(RHS, Common, "converting"))
1517            return QualType();
1518          return Common;
1519        }
1520      }
1521    }
1522  }
1523
1524  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1525    << LHS->getType() << RHS->getType()
1526    << LHS->getSourceRange() << RHS->getSourceRange();
1527  return QualType();
1528}
1529
1530/// \brief Find a merged pointer type and convert the two expressions to it.
1531///
1532/// This finds the composite pointer type (or member pointer type) for @p E1
1533/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1534/// type and returns it.
1535/// It does not emit diagnostics.
1536QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1537  assert(getLangOptions().CPlusPlus && "This function assumes C++");
1538  QualType T1 = E1->getType(), T2 = E2->getType();
1539
1540  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1541      !T2->isPointerType() && !T2->isMemberPointerType())
1542   return QualType();
1543
1544  // FIXME: Do we need to work on the canonical types?
1545
1546  // C++0x 5.9p2
1547  //   Pointer conversions and qualification conversions are performed on
1548  //   pointer operands to bring them to their composite pointer type. If
1549  //   one operand is a null pointer constant, the composite pointer type is
1550  //   the type of the other operand.
1551  if (E1->isNullPointerConstant(Context)) {
1552    ImpCastExprToType(E1, T2);
1553    return T2;
1554  }
1555  if (E2->isNullPointerConstant(Context)) {
1556    ImpCastExprToType(E2, T1);
1557    return T1;
1558  }
1559
1560  // Now both have to be pointers or member pointers.
1561  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1562      !T2->isPointerType() && !T2->isMemberPointerType())
1563    return QualType();
1564
1565  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
1566  //   the other has type "pointer to cv2 T" and the composite pointer type is
1567  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1568  //   Otherwise, the composite pointer type is a pointer type similar to the
1569  //   type of one of the operands, with a cv-qualification signature that is
1570  //   the union of the cv-qualification signatures of the operand types.
1571  // In practice, the first part here is redundant; it's subsumed by the second.
1572  // What we do here is, we build the two possible composite types, and try the
1573  // conversions in both directions. If only one works, or if the two composite
1574  // types are the same, we have succeeded.
1575  llvm::SmallVector<unsigned, 4> QualifierUnion;
1576  llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
1577  QualType Composite1 = T1, Composite2 = T2;
1578  do {
1579    const PointerType *Ptr1, *Ptr2;
1580    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1581        (Ptr2 = Composite2->getAs<PointerType>())) {
1582      Composite1 = Ptr1->getPointeeType();
1583      Composite2 = Ptr2->getPointeeType();
1584      QualifierUnion.push_back(
1585                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1586      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1587      continue;
1588    }
1589
1590    const MemberPointerType *MemPtr1, *MemPtr2;
1591    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1592        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1593      Composite1 = MemPtr1->getPointeeType();
1594      Composite2 = MemPtr2->getPointeeType();
1595      QualifierUnion.push_back(
1596                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1597      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1598                                             MemPtr2->getClass()));
1599      continue;
1600    }
1601
1602    // FIXME: block pointer types?
1603
1604    // Cannot unwrap any more types.
1605    break;
1606  } while (true);
1607
1608  // Rewrap the composites as pointers or member pointers with the union CVRs.
1609  llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1610    = MemberOfClass.begin();
1611  for (llvm::SmallVector<unsigned, 4>::iterator
1612         I = QualifierUnion.begin(),
1613         E = QualifierUnion.end();
1614       I != E; (void)++I, ++MOC) {
1615    if (MOC->first && MOC->second) {
1616      // Rebuild member pointer type
1617      Composite1 = Context.getMemberPointerType(Composite1.getQualifiedType(*I),
1618                                                MOC->first);
1619      Composite2 = Context.getMemberPointerType(Composite2.getQualifiedType(*I),
1620                                                MOC->second);
1621    } else {
1622      // Rebuild pointer type
1623      Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1624      Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1625    }
1626  }
1627
1628  ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1629  ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1630  ImplicitConversionSequence E1ToC2, E2ToC2;
1631  E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1632  E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1633  if (Context.getCanonicalType(Composite1) !=
1634      Context.getCanonicalType(Composite2)) {
1635    E1ToC2 = TryImplicitConversion(E1, Composite2);
1636    E2ToC2 = TryImplicitConversion(E2, Composite2);
1637  }
1638
1639  bool ToC1Viable = E1ToC1.ConversionKind !=
1640                      ImplicitConversionSequence::BadConversion
1641                 && E2ToC1.ConversionKind !=
1642                      ImplicitConversionSequence::BadConversion;
1643  bool ToC2Viable = E1ToC2.ConversionKind !=
1644                      ImplicitConversionSequence::BadConversion
1645                 && E2ToC2.ConversionKind !=
1646                      ImplicitConversionSequence::BadConversion;
1647  if (ToC1Viable && !ToC2Viable) {
1648    if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1649        !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1650      return Composite1;
1651  }
1652  if (ToC2Viable && !ToC1Viable) {
1653    if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1654        !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1655      return Composite2;
1656  }
1657  return QualType();
1658}
1659
1660Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
1661  if (!Context.getLangOptions().CPlusPlus)
1662    return Owned(E);
1663
1664  const RecordType *RT = E->getType()->getAs<RecordType>();
1665  if (!RT)
1666    return Owned(E);
1667
1668  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1669  if (RD->hasTrivialDestructor())
1670    return Owned(E);
1671
1672  CXXTemporary *Temp = CXXTemporary::Create(Context,
1673                                            RD->getDestructor(Context));
1674  ExprTemporaries.push_back(Temp);
1675  if (CXXDestructorDecl *Destructor =
1676        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1677    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
1678  // FIXME: Add the temporary to the temporaries vector.
1679  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1680}
1681
1682Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
1683                                              bool ShouldDestroyTemps) {
1684  assert(SubExpr && "sub expression can't be null!");
1685
1686  if (ExprTemporaries.empty())
1687    return SubExpr;
1688
1689  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1690                                           &ExprTemporaries[0],
1691                                           ExprTemporaries.size(),
1692                                           ShouldDestroyTemps);
1693  ExprTemporaries.clear();
1694
1695  return E;
1696}
1697
1698Sema::OwningExprResult
1699Sema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
1700                                   SourceLocation OpLoc,
1701                                   tok::TokenKind OpKind,
1702                                   SourceLocation ClassNameLoc,
1703                                   IdentifierInfo *ClassName,
1704                                   const CXXScopeSpec *SS) {
1705  if (SS && SS->isInvalid())
1706    return ExprError();
1707
1708  Expr *BaseExpr = (Expr *)Base.get();
1709
1710  if (BaseExpr->isTypeDependent() ||
1711      (SS && isDependentScopeSpecifier(*SS))) {
1712    // FIXME: Return an unresolved ref expr.
1713    return ExprError();
1714  }
1715
1716  TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, SS);
1717  if (!BaseTy) {
1718    Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
1719      << ClassName;
1720    return ExprError();
1721  }
1722
1723  QualType BaseType = GetTypeFromParser(BaseTy);
1724  if (!BaseType->isRecordType()) {
1725    Diag(ClassNameLoc, diag::err_type_in_pseudo_dtor_not_a_class_type)
1726      << BaseType;
1727    return ExprError();
1728  }
1729
1730  CanQualType CanBaseType = Context.getCanonicalType(BaseType);
1731  DeclarationName DtorName =
1732    Context.DeclarationNames.getCXXDestructorName(CanBaseType);
1733
1734  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
1735                                  DtorName, DeclPtrTy(), SS);
1736}
1737
1738Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1739  Expr *FullExpr = Arg.takeAs<Expr>();
1740  if (FullExpr)
1741    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1742                                                 /*ShouldDestroyTemps=*/true);
1743
1744
1745  return Owned(FullExpr);
1746}
1747