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