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