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