SemaExprCXX.cpp revision 198092
1193326Sed//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements semantic analysis for C++ expressions.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "Sema.h"
15198092Srdivacky#include "clang/AST/ASTContext.h"
16198092Srdivacky#include "clang/AST/CXXInheritance.h"
17193326Sed#include "clang/AST/ExprCXX.h"
18198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
19198092Srdivacky#include "clang/Basic/TargetInfo.h"
20198092Srdivacky#include "clang/Lex/Preprocessor.h"
21193326Sed#include "clang/Parse/DeclSpec.h"
22193326Sed#include "llvm/ADT/STLExtras.h"
23193326Sedusing namespace clang;
24193326Sed
25193326Sed/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
26193326Sed/// name (e.g., operator void const *) as an expression. This is
27193326Sed/// very similar to ActOnIdentifierExpr, except that instead of
28193326Sed/// providing an identifier the parser provides the type of the
29193326Sed/// conversion function.
30193326SedSema::OwningExprResult
31193326SedSema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
32193326Sed                                     TypeTy *Ty, bool HasTrailingLParen,
33193326Sed                                     const CXXScopeSpec &SS,
34193326Sed                                     bool isAddressOfOperand) {
35198092Srdivacky  //FIXME: Preserve type source info.
36198092Srdivacky  QualType ConvType = GetTypeFromParser(Ty);
37198092Srdivacky  CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
38198092Srdivacky  DeclarationName ConvName
39193326Sed    = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
40193326Sed  return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
41193326Sed                                  &SS, isAddressOfOperand);
42193326Sed}
43193326Sed
44193326Sed/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
45193326Sed/// name (e.g., @c operator+ ) as an expression. This is very
46193326Sed/// similar to ActOnIdentifierExpr, except that instead of providing
47193326Sed/// an identifier the parser provides the kind of overloaded
48193326Sed/// operator that was parsed.
49193326SedSema::OwningExprResult
50193326SedSema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
51193326Sed                                     OverloadedOperatorKind Op,
52193326Sed                                     bool HasTrailingLParen,
53193326Sed                                     const CXXScopeSpec &SS,
54193326Sed                                     bool isAddressOfOperand) {
55193326Sed  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
56193326Sed  return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
57193326Sed                                  isAddressOfOperand);
58193326Sed}
59193326Sed
60193326Sed/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
61193326SedAction::OwningExprResult
62193326SedSema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
63193326Sed                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
64198092Srdivacky  if (!StdNamespace)
65193326Sed    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
66198092Srdivacky
67198092Srdivacky  if (isType)
68198092Srdivacky    // FIXME: Preserve type source info.
69198092Srdivacky    TyOrExpr = GetTypeFromParser(TyOrExpr).getAsOpaquePtr();
70198092Srdivacky
71193326Sed  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
72198092Srdivacky  LookupResult R;
73198092Srdivacky  LookupQualifiedName(R, StdNamespace, TypeInfoII, LookupTagName);
74198092Srdivacky  Decl *TypeInfoDecl = R.getAsSingleDecl(Context);
75193326Sed  RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
76193326Sed  if (!TypeInfoRecordDecl)
77193326Sed    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
78193326Sed
79193326Sed  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
80193326Sed
81194711Sed  if (!isType) {
82194711Sed    // C++0x [expr.typeid]p3:
83198092Srdivacky    //   When typeid is applied to an expression other than an lvalue of a
84198092Srdivacky    //   polymorphic class type [...] [the] expression is an unevaluated
85194711Sed    //   operand.
86198092Srdivacky
87194711Sed    // FIXME: if the type of the expression is a class type, the class
88194711Sed    // shall be completely defined.
89194711Sed    bool isUnevaluatedOperand = true;
90194711Sed    Expr *E = static_cast<Expr *>(TyOrExpr);
91194711Sed    if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
92194711Sed      QualType T = E->getType();
93198092Srdivacky      if (const RecordType *RecordT = T->getAs<RecordType>()) {
94194711Sed        CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
95194711Sed        if (RecordD->isPolymorphic())
96194711Sed          isUnevaluatedOperand = false;
97194711Sed      }
98194711Sed    }
99198092Srdivacky
100194711Sed    // If this is an unevaluated operand, clear out the set of declaration
101194711Sed    // references we have been computing.
102194711Sed    if (isUnevaluatedOperand)
103194711Sed      PotentiallyReferencedDeclStack.back().clear();
104194711Sed  }
105198092Srdivacky
106193326Sed  return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
107193326Sed                                           TypeInfoType.withConst(),
108193326Sed                                           SourceRange(OpLoc, RParenLoc)));
109193326Sed}
110193326Sed
111193326Sed/// ActOnCXXBoolLiteral - Parse {true,false} literals.
112193326SedAction::OwningExprResult
113193326SedSema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
114193326Sed  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
115193326Sed         "Unknown C++ Boolean value!");
116193326Sed  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
117193326Sed                                                Context.BoolTy, OpLoc));
118193326Sed}
119193326Sed
120193326Sed/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
121193326SedAction::OwningExprResult
122193326SedSema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
123193326Sed  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
124193326Sed}
125193326Sed
126193326Sed/// ActOnCXXThrow - Parse throw expressions.
127193326SedAction::OwningExprResult
128193326SedSema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
129193326Sed  Expr *Ex = E.takeAs<Expr>();
130193326Sed  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
131193326Sed    return ExprError();
132193326Sed  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
133193326Sed}
134193326Sed
135193326Sed/// CheckCXXThrowOperand - Validate the operand of a throw.
136193326Sedbool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
137193326Sed  // C++ [except.throw]p3:
138193326Sed  //   [...] adjusting the type from "array of T" or "function returning T"
139193326Sed  //   to "pointer to T" or "pointer to function returning T", [...]
140193326Sed  DefaultFunctionArrayConversion(E);
141193326Sed
142193326Sed  //   If the type of the exception would be an incomplete type or a pointer
143193326Sed  //   to an incomplete type other than (cv) void the program is ill-formed.
144193326Sed  QualType Ty = E->getType();
145193326Sed  int isPointer = 0;
146198092Srdivacky  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
147193326Sed    Ty = Ptr->getPointeeType();
148193326Sed    isPointer = 1;
149193326Sed  }
150193326Sed  if (!isPointer || !Ty->isVoidType()) {
151193326Sed    if (RequireCompleteType(ThrowLoc, Ty,
152198092Srdivacky                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
153198092Srdivacky                                            : diag::err_throw_incomplete)
154198092Srdivacky                              << E->getSourceRange()))
155193326Sed      return true;
156193326Sed  }
157193326Sed
158193326Sed  // FIXME: Construct a temporary here.
159193326Sed  return false;
160193326Sed}
161193326Sed
162193326SedAction::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
163193326Sed  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
164193326Sed  /// is a non-lvalue expression whose value is the address of the object for
165193326Sed  /// which the function is called.
166193326Sed
167193326Sed  if (!isa<FunctionDecl>(CurContext))
168193326Sed    return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
169193326Sed
170193326Sed  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
171193326Sed    if (MD->isInstance())
172193326Sed      return Owned(new (Context) CXXThisExpr(ThisLoc,
173193326Sed                                             MD->getThisType(Context)));
174193326Sed
175193326Sed  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
176193326Sed}
177193326Sed
178193326Sed/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
179193326Sed/// Can be interpreted either as function-style casting ("int(x)")
180193326Sed/// or class type construction ("ClassType(x,y,z)")
181193326Sed/// or creation of a value-initialized type ("int()").
182193326SedAction::OwningExprResult
183193326SedSema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
184193326Sed                                SourceLocation LParenLoc,
185193326Sed                                MultiExprArg exprs,
186193326Sed                                SourceLocation *CommaLocs,
187193326Sed                                SourceLocation RParenLoc) {
188193326Sed  assert(TypeRep && "Missing type!");
189198092Srdivacky  // FIXME: Preserve type source info.
190198092Srdivacky  QualType Ty = GetTypeFromParser(TypeRep);
191193326Sed  unsigned NumExprs = exprs.size();
192193326Sed  Expr **Exprs = (Expr**)exprs.get();
193193326Sed  SourceLocation TyBeginLoc = TypeRange.getBegin();
194193326Sed  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
195193326Sed
196193326Sed  if (Ty->isDependentType() ||
197193326Sed      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
198193326Sed    exprs.release();
199198092Srdivacky
200198092Srdivacky    return Owned(CXXUnresolvedConstructExpr::Create(Context,
201198092Srdivacky                                                    TypeRange.getBegin(), Ty,
202193326Sed                                                    LParenLoc,
203193326Sed                                                    Exprs, NumExprs,
204193326Sed                                                    RParenLoc));
205193326Sed  }
206193326Sed
207198092Srdivacky  if (Ty->isArrayType())
208198092Srdivacky    return ExprError(Diag(TyBeginLoc,
209198092Srdivacky                          diag::err_value_init_for_array_type) << FullRange);
210198092Srdivacky  if (!Ty->isVoidType() &&
211198092Srdivacky      RequireCompleteType(TyBeginLoc, Ty,
212198092Srdivacky                          PDiag(diag::err_invalid_incomplete_type_use)
213198092Srdivacky                            << FullRange))
214198092Srdivacky    return ExprError();
215193326Sed
216198092Srdivacky  if (RequireNonAbstractType(TyBeginLoc, Ty,
217198092Srdivacky                             diag::err_allocation_of_abstract_type))
218198092Srdivacky    return ExprError();
219198092Srdivacky
220198092Srdivacky
221193326Sed  // C++ [expr.type.conv]p1:
222193326Sed  // If the expression list is a single expression, the type conversion
223193326Sed  // expression is equivalent (in definedness, and if defined in meaning) to the
224193326Sed  // corresponding cast expression.
225193326Sed  //
226193326Sed  if (NumExprs == 1) {
227198092Srdivacky    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
228198092Srdivacky    CXXMethodDecl *Method = 0;
229198092Srdivacky    if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
230198092Srdivacky                       /*FunctionalStyle=*/true))
231193326Sed      return ExprError();
232198092Srdivacky
233193326Sed    exprs.release();
234198092Srdivacky    if (Method) {
235198092Srdivacky      OwningExprResult CastArg
236198092Srdivacky        = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
237198092Srdivacky                               Kind, Method, Owned(Exprs[0]));
238198092Srdivacky      if (CastArg.isInvalid())
239198092Srdivacky        return ExprError();
240198092Srdivacky
241198092Srdivacky      Exprs[0] = CastArg.takeAs<Expr>();
242198092Srdivacky    }
243198092Srdivacky
244193326Sed    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
245198092Srdivacky                                                     Ty, TyBeginLoc, Kind,
246198092Srdivacky                                                     Exprs[0], RParenLoc));
247193326Sed  }
248193326Sed
249198092Srdivacky  if (const RecordType *RT = Ty->getAs<RecordType>()) {
250193326Sed    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
251193326Sed
252198092Srdivacky    if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
253198092Srdivacky        !Record->hasTrivialDestructor()) {
254198092Srdivacky      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
255198092Srdivacky
256193326Sed      CXXConstructorDecl *Constructor
257198092Srdivacky        = PerformInitializationByConstructor(Ty, move(exprs),
258193326Sed                                             TypeRange.getBegin(),
259193326Sed                                             SourceRange(TypeRange.getBegin(),
260193326Sed                                                         RParenLoc),
261193326Sed                                             DeclarationName(),
262198092Srdivacky                                             IK_Direct,
263198092Srdivacky                                             ConstructorArgs);
264193326Sed
265193326Sed      if (!Constructor)
266193326Sed        return ExprError();
267193326Sed
268198092Srdivacky      OwningExprResult Result =
269198092Srdivacky        BuildCXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
270198092Srdivacky                                    move_arg(ConstructorArgs), RParenLoc);
271198092Srdivacky      if (Result.isInvalid())
272198092Srdivacky        return ExprError();
273198092Srdivacky
274198092Srdivacky      return MaybeBindToTemporary(Result.takeAs<Expr>());
275193326Sed    }
276193326Sed
277193326Sed    // Fall through to value-initialize an object of class type that
278193326Sed    // doesn't have a user-declared default constructor.
279193326Sed  }
280193326Sed
281193326Sed  // C++ [expr.type.conv]p1:
282193326Sed  // If the expression list specifies more than a single value, the type shall
283193326Sed  // be a class with a suitably declared constructor.
284193326Sed  //
285193326Sed  if (NumExprs > 1)
286193326Sed    return ExprError(Diag(CommaLocs[0],
287193326Sed                          diag::err_builtin_func_cast_more_than_one_arg)
288193326Sed      << FullRange);
289193326Sed
290193326Sed  assert(NumExprs == 0 && "Expected 0 expressions");
291193326Sed
292193326Sed  // C++ [expr.type.conv]p2:
293193326Sed  // The expression T(), where T is a simple-type-specifier for a non-array
294193326Sed  // complete object type or the (possibly cv-qualified) void type, creates an
295193326Sed  // rvalue of the specified type, which is value-initialized.
296193326Sed  //
297193326Sed  exprs.release();
298193326Sed  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
299193326Sed}
300193326Sed
301193326Sed
302193326Sed/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
303193326Sed/// @code new (memory) int[size][4] @endcode
304193326Sed/// or
305193326Sed/// @code ::new Foo(23, "hello") @endcode
306193326Sed/// For the interpretation of this heap of arguments, consult the base version.
307193326SedAction::OwningExprResult
308193326SedSema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
309193326Sed                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
310193326Sed                  SourceLocation PlacementRParen, bool ParenTypeId,
311193326Sed                  Declarator &D, SourceLocation ConstructorLParen,
312193326Sed                  MultiExprArg ConstructorArgs,
313198092Srdivacky                  SourceLocation ConstructorRParen) {
314193326Sed  Expr *ArraySize = 0;
315193326Sed  unsigned Skip = 0;
316193326Sed  // If the specified type is an array, unwrap it and save the expression.
317193326Sed  if (D.getNumTypeObjects() > 0 &&
318193326Sed      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
319193326Sed    DeclaratorChunk &Chunk = D.getTypeObject(0);
320193326Sed    if (Chunk.Arr.hasStatic)
321193326Sed      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
322193326Sed        << D.getSourceRange());
323193326Sed    if (!Chunk.Arr.NumElts)
324193326Sed      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
325193326Sed        << D.getSourceRange());
326193326Sed    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
327193326Sed    Skip = 1;
328193326Sed  }
329193326Sed
330198092Srdivacky  // Every dimension shall be of constant size.
331198092Srdivacky  if (D.getNumTypeObjects() > 0 &&
332198092Srdivacky      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
333198092Srdivacky    for (unsigned I = 1, N = D.getNumTypeObjects(); I < N; ++I) {
334198092Srdivacky      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
335198092Srdivacky        break;
336193326Sed
337198092Srdivacky      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
338198092Srdivacky      if (Expr *NumElts = (Expr *)Array.NumElts) {
339198092Srdivacky        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
340198092Srdivacky            !NumElts->isIntegerConstantExpr(Context)) {
341198092Srdivacky          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
342198092Srdivacky            << NumElts->getSourceRange();
343198092Srdivacky          return ExprError();
344198092Srdivacky        }
345198092Srdivacky      }
346193326Sed    }
347193326Sed  }
348198092Srdivacky
349198092Srdivacky  //FIXME: Store DeclaratorInfo in CXXNew expression.
350198092Srdivacky  DeclaratorInfo *DInfo = 0;
351198092Srdivacky  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &DInfo, Skip);
352198092Srdivacky  if (D.isInvalidType())
353198092Srdivacky    return ExprError();
354193326Sed
355198092Srdivacky  return BuildCXXNew(StartLoc, UseGlobal,
356193326Sed                     PlacementLParen,
357198092Srdivacky                     move(PlacementArgs),
358193326Sed                     PlacementRParen,
359193326Sed                     ParenTypeId,
360198092Srdivacky                     AllocType,
361193326Sed                     D.getSourceRange().getBegin(),
362193326Sed                     D.getSourceRange(),
363193326Sed                     Owned(ArraySize),
364193326Sed                     ConstructorLParen,
365193326Sed                     move(ConstructorArgs),
366193326Sed                     ConstructorRParen);
367193326Sed}
368193326Sed
369198092SrdivackySema::OwningExprResult
370193326SedSema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
371193326Sed                  SourceLocation PlacementLParen,
372193326Sed                  MultiExprArg PlacementArgs,
373193326Sed                  SourceLocation PlacementRParen,
374198092Srdivacky                  bool ParenTypeId,
375193326Sed                  QualType AllocType,
376193326Sed                  SourceLocation TypeLoc,
377193326Sed                  SourceRange TypeRange,
378193326Sed                  ExprArg ArraySizeE,
379193326Sed                  SourceLocation ConstructorLParen,
380193326Sed                  MultiExprArg ConstructorArgs,
381193326Sed                  SourceLocation ConstructorRParen) {
382193326Sed  if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
383193326Sed    return ExprError();
384193326Sed
385193326Sed  QualType ResultType = Context.getPointerType(AllocType);
386193326Sed
387193326Sed  // That every array dimension except the first is constant was already
388193326Sed  // checked by the type check above.
389193326Sed
390193326Sed  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
391193326Sed  //   or enumeration type with a non-negative value."
392193326Sed  Expr *ArraySize = (Expr *)ArraySizeE.get();
393193326Sed  if (ArraySize && !ArraySize->isTypeDependent()) {
394193326Sed    QualType SizeType = ArraySize->getType();
395193326Sed    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
396193326Sed      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
397193326Sed                            diag::err_array_size_not_integral)
398193326Sed        << SizeType << ArraySize->getSourceRange());
399193326Sed    // Let's see if this is a constant < 0. If so, we reject it out of hand.
400193326Sed    // We don't care about special rules, so we tell the machinery it's not
401193326Sed    // evaluated - it gives us a result in more cases.
402193326Sed    if (!ArraySize->isValueDependent()) {
403193326Sed      llvm::APSInt Value;
404193326Sed      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
405193326Sed        if (Value < llvm::APSInt(
406198092Srdivacky                        llvm::APInt::getNullValue(Value.getBitWidth()),
407198092Srdivacky                                 Value.isUnsigned()))
408193326Sed          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
409193326Sed                           diag::err_typecheck_negative_array_size)
410193326Sed            << ArraySize->getSourceRange());
411193326Sed      }
412193326Sed    }
413198092Srdivacky
414198092Srdivacky    ImpCastExprToType(ArraySize, Context.getSizeType());
415193326Sed  }
416193326Sed
417193326Sed  FunctionDecl *OperatorNew = 0;
418193326Sed  FunctionDecl *OperatorDelete = 0;
419193326Sed  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
420193326Sed  unsigned NumPlaceArgs = PlacementArgs.size();
421193326Sed  if (!AllocType->isDependentType() &&
422193326Sed      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
423193326Sed      FindAllocationFunctions(StartLoc,
424193326Sed                              SourceRange(PlacementLParen, PlacementRParen),
425193326Sed                              UseGlobal, AllocType, ArraySize, PlaceArgs,
426193326Sed                              NumPlaceArgs, OperatorNew, OperatorDelete))
427193326Sed    return ExprError();
428193326Sed
429193326Sed  bool Init = ConstructorLParen.isValid();
430193326Sed  // --- Choosing a constructor ---
431193326Sed  // C++ 5.3.4p15
432193326Sed  // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
433193326Sed  //   the object is not initialized. If the object, or any part of it, is
434193326Sed  //   const-qualified, it's an error.
435193326Sed  // 2) If T is a POD and there's an empty initializer, the object is value-
436193326Sed  //   initialized.
437193326Sed  // 3) If T is a POD and there's one initializer argument, the object is copy-
438193326Sed  //   constructed.
439193326Sed  // 4) If T is a POD and there's more initializer arguments, it's an error.
440193326Sed  // 5) If T is not a POD, the initializer arguments are used as constructor
441193326Sed  //   arguments.
442193326Sed  //
443193326Sed  // Or by the C++0x formulation:
444193326Sed  // 1) If there's no initializer, the object is default-initialized according
445193326Sed  //    to C++0x rules.
446193326Sed  // 2) Otherwise, the object is direct-initialized.
447193326Sed  CXXConstructorDecl *Constructor = 0;
448193326Sed  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
449193326Sed  const RecordType *RT;
450193326Sed  unsigned NumConsArgs = ConstructorArgs.size();
451193326Sed  if (AllocType->isDependentType()) {
452193326Sed    // Skip all the checks.
453198092Srdivacky  } else if ((RT = AllocType->getAs<RecordType>()) &&
454198092Srdivacky             !AllocType->isAggregateType()) {
455198092Srdivacky    ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
456198092Srdivacky
457193326Sed    Constructor = PerformInitializationByConstructor(
458198092Srdivacky                      AllocType, move(ConstructorArgs),
459193326Sed                      TypeLoc,
460193326Sed                      SourceRange(TypeLoc, ConstructorRParen),
461193326Sed                      RT->getDecl()->getDeclName(),
462198092Srdivacky                      NumConsArgs != 0 ? IK_Direct : IK_Default,
463198092Srdivacky                      ConvertedConstructorArgs);
464193326Sed    if (!Constructor)
465193326Sed      return ExprError();
466198092Srdivacky
467198092Srdivacky    // Take the converted constructor arguments and use them for the new
468198092Srdivacky    // expression.
469198092Srdivacky    NumConsArgs = ConvertedConstructorArgs.size();
470198092Srdivacky    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
471193326Sed  } else {
472193326Sed    if (!Init) {
473193326Sed      // FIXME: Check that no subpart is const.
474193326Sed      if (AllocType.isConstQualified())
475193326Sed        return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
476193326Sed                           << TypeRange);
477193326Sed    } else if (NumConsArgs == 0) {
478193326Sed      // Object is value-initialized. Do nothing.
479193326Sed    } else if (NumConsArgs == 1) {
480193326Sed      // Object is direct-initialized.
481193326Sed      // FIXME: What DeclarationName do we pass in here?
482193326Sed      if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
483193326Sed                                DeclarationName() /*AllocType.getAsString()*/,
484193326Sed                                /*DirectInit=*/true))
485193326Sed        return ExprError();
486193326Sed    } else {
487193326Sed      return ExprError(Diag(StartLoc,
488193326Sed                            diag::err_builtin_direct_init_more_than_one_arg)
489193326Sed        << SourceRange(ConstructorLParen, ConstructorRParen));
490193326Sed    }
491193326Sed  }
492193326Sed
493193326Sed  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
494193326Sed
495193326Sed  PlacementArgs.release();
496193326Sed  ConstructorArgs.release();
497193326Sed  ArraySizeE.release();
498193326Sed  return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
499193326Sed                        NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
500193326Sed                        ConsArgs, NumConsArgs, OperatorDelete, ResultType,
501198092Srdivacky                        StartLoc, Init ? ConstructorRParen : SourceLocation()));
502193326Sed}
503193326Sed
504193326Sed/// CheckAllocatedType - Checks that a type is suitable as the allocated type
505193326Sed/// in a new-expression.
506193326Sed/// dimension off and stores the size expression in ArraySize.
507193326Sedbool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
508198092Srdivacky                              SourceRange R) {
509193326Sed  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
510193326Sed  //   abstract class type or array thereof.
511193326Sed  if (AllocType->isFunctionType())
512193326Sed    return Diag(Loc, diag::err_bad_new_type)
513193326Sed      << AllocType << 0 << R;
514193326Sed  else if (AllocType->isReferenceType())
515193326Sed    return Diag(Loc, diag::err_bad_new_type)
516193326Sed      << AllocType << 1 << R;
517193326Sed  else if (!AllocType->isDependentType() &&
518193326Sed           RequireCompleteType(Loc, AllocType,
519198092Srdivacky                               PDiag(diag::err_new_incomplete_type)
520198092Srdivacky                                 << R))
521193326Sed    return true;
522193326Sed  else if (RequireNonAbstractType(Loc, AllocType,
523193326Sed                                  diag::err_allocation_of_abstract_type))
524193326Sed    return true;
525193326Sed
526193326Sed  return false;
527193326Sed}
528193326Sed
529193326Sed/// FindAllocationFunctions - Finds the overloads of operator new and delete
530193326Sed/// that are appropriate for the allocation.
531193326Sedbool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
532193326Sed                                   bool UseGlobal, QualType AllocType,
533193326Sed                                   bool IsArray, Expr **PlaceArgs,
534193326Sed                                   unsigned NumPlaceArgs,
535193326Sed                                   FunctionDecl *&OperatorNew,
536198092Srdivacky                                   FunctionDecl *&OperatorDelete) {
537193326Sed  // --- Choosing an allocation function ---
538193326Sed  // C++ 5.3.4p8 - 14 & 18
539193326Sed  // 1) If UseGlobal is true, only look in the global scope. Else, also look
540193326Sed  //   in the scope of the allocated class.
541193326Sed  // 2) If an array size is given, look for operator new[], else look for
542193326Sed  //   operator new.
543193326Sed  // 3) The first argument is always size_t. Append the arguments from the
544193326Sed  //   placement form.
545193326Sed  // FIXME: Also find the appropriate delete operator.
546193326Sed
547193326Sed  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
548193326Sed  // We don't care about the actual value of this argument.
549193326Sed  // FIXME: Should the Sema create the expression and embed it in the syntax
550193326Sed  // tree? Or should the consumer just recalculate the value?
551198092Srdivacky  IntegerLiteral Size(llvm::APInt::getNullValue(
552198092Srdivacky                      Context.Target.getPointerWidth(0)),
553198092Srdivacky                      Context.getSizeType(),
554198092Srdivacky                      SourceLocation());
555198092Srdivacky  AllocArgs[0] = &Size;
556193326Sed  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
557193326Sed
558193326Sed  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
559193326Sed                                        IsArray ? OO_Array_New : OO_New);
560193326Sed  if (AllocType->isRecordType() && !UseGlobal) {
561198092Srdivacky    CXXRecordDecl *Record
562198092Srdivacky      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
563193326Sed    // FIXME: We fail to find inherited overloads.
564193326Sed    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
565193326Sed                          AllocArgs.size(), Record, /*AllowMissing=*/true,
566193326Sed                          OperatorNew))
567193326Sed      return true;
568193326Sed  }
569193326Sed  if (!OperatorNew) {
570193326Sed    // Didn't find a member overload. Look for a global one.
571193326Sed    DeclareGlobalNewDelete();
572193326Sed    DeclContext *TUDecl = Context.getTranslationUnitDecl();
573193326Sed    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
574193326Sed                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
575193326Sed                          OperatorNew))
576193326Sed      return true;
577193326Sed  }
578193326Sed
579193326Sed  // FindAllocationOverload can change the passed in arguments, so we need to
580193326Sed  // copy them back.
581193326Sed  if (NumPlaceArgs > 0)
582193326Sed    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
583198092Srdivacky
584193326Sed  return false;
585193326Sed}
586193326Sed
587193326Sed/// FindAllocationOverload - Find an fitting overload for the allocation
588193326Sed/// function in the specified scope.
589193326Sedbool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
590193326Sed                                  DeclarationName Name, Expr** Args,
591193326Sed                                  unsigned NumArgs, DeclContext *Ctx,
592198092Srdivacky                                  bool AllowMissing, FunctionDecl *&Operator) {
593198092Srdivacky  LookupResult R;
594198092Srdivacky  LookupQualifiedName(R, Ctx, Name, LookupOrdinaryName);
595198092Srdivacky  if (R.empty()) {
596193326Sed    if (AllowMissing)
597193326Sed      return false;
598193326Sed    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
599193326Sed      << Name << Range;
600193326Sed  }
601193326Sed
602198092Srdivacky  // FIXME: handle ambiguity
603198092Srdivacky
604193326Sed  OverloadCandidateSet Candidates;
605198092Srdivacky  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
606198092Srdivacky       Alloc != AllocEnd; ++Alloc) {
607193326Sed    // Even member operator new/delete are implicitly treated as
608193326Sed    // static, so don't use AddMemberCandidate.
609198092Srdivacky    if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc)) {
610193326Sed      AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
611193326Sed                           /*SuppressUserConversions=*/false);
612198092Srdivacky      continue;
613198092Srdivacky    }
614198092Srdivacky
615198092Srdivacky    // FIXME: Handle function templates
616193326Sed  }
617193326Sed
618193326Sed  // Do the resolution.
619193326Sed  OverloadCandidateSet::iterator Best;
620194613Sed  switch(BestViableFunction(Candidates, StartLoc, Best)) {
621193326Sed  case OR_Success: {
622193326Sed    // Got one!
623193326Sed    FunctionDecl *FnDecl = Best->Function;
624193326Sed    // The first argument is size_t, and the first parameter must be size_t,
625193326Sed    // too. This is checked on declaration and can be assumed. (It can't be
626193326Sed    // asserted on, though, since invalid decls are left in there.)
627198092Srdivacky    for (unsigned i = 0; i < NumArgs; ++i) {
628193326Sed      // FIXME: Passing word to diagnostic.
629193326Sed      if (PerformCopyInitialization(Args[i],
630193326Sed                                    FnDecl->getParamDecl(i)->getType(),
631193326Sed                                    "passing"))
632193326Sed        return true;
633193326Sed    }
634193326Sed    Operator = FnDecl;
635193326Sed    return false;
636193326Sed  }
637193326Sed
638193326Sed  case OR_No_Viable_Function:
639193326Sed    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
640193326Sed      << Name << Range;
641193326Sed    PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
642193326Sed    return true;
643193326Sed
644193326Sed  case OR_Ambiguous:
645193326Sed    Diag(StartLoc, diag::err_ovl_ambiguous_call)
646193326Sed      << Name << Range;
647193326Sed    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
648193326Sed    return true;
649193326Sed
650193326Sed  case OR_Deleted:
651193326Sed    Diag(StartLoc, diag::err_ovl_deleted_call)
652193326Sed      << Best->Function->isDeleted()
653193326Sed      << Name << Range;
654193326Sed    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
655193326Sed    return true;
656193326Sed  }
657193326Sed  assert(false && "Unreachable, bad result from BestViableFunction");
658193326Sed  return true;
659193326Sed}
660193326Sed
661193326Sed
662193326Sed/// DeclareGlobalNewDelete - Declare the global forms of operator new and
663193326Sed/// delete. These are:
664193326Sed/// @code
665193326Sed///   void* operator new(std::size_t) throw(std::bad_alloc);
666193326Sed///   void* operator new[](std::size_t) throw(std::bad_alloc);
667193326Sed///   void operator delete(void *) throw();
668193326Sed///   void operator delete[](void *) throw();
669193326Sed/// @endcode
670193326Sed/// Note that the placement and nothrow forms of new are *not* implicitly
671193326Sed/// declared. Their use requires including \<new\>.
672198092Srdivackyvoid Sema::DeclareGlobalNewDelete() {
673193326Sed  if (GlobalNewDeleteDeclared)
674193326Sed    return;
675198092Srdivacky
676198092Srdivacky  // C++ [basic.std.dynamic]p2:
677198092Srdivacky  //   [...] The following allocation and deallocation functions (18.4) are
678198092Srdivacky  //   implicitly declared in global scope in each translation unit of a
679198092Srdivacky  //   program
680198092Srdivacky  //
681198092Srdivacky  //     void* operator new(std::size_t) throw(std::bad_alloc);
682198092Srdivacky  //     void* operator new[](std::size_t) throw(std::bad_alloc);
683198092Srdivacky  //     void  operator delete(void*) throw();
684198092Srdivacky  //     void  operator delete[](void*) throw();
685198092Srdivacky  //
686198092Srdivacky  //   These implicit declarations introduce only the function names operator
687198092Srdivacky  //   new, operator new[], operator delete, operator delete[].
688198092Srdivacky  //
689198092Srdivacky  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
690198092Srdivacky  // "std" or "bad_alloc" as necessary to form the exception specification.
691198092Srdivacky  // However, we do not make these implicit declarations visible to name
692198092Srdivacky  // lookup.
693198092Srdivacky  if (!StdNamespace) {
694198092Srdivacky    // The "std" namespace has not yet been defined, so build one implicitly.
695198092Srdivacky    StdNamespace = NamespaceDecl::Create(Context,
696198092Srdivacky                                         Context.getTranslationUnitDecl(),
697198092Srdivacky                                         SourceLocation(),
698198092Srdivacky                                         &PP.getIdentifierTable().get("std"));
699198092Srdivacky    StdNamespace->setImplicit(true);
700198092Srdivacky  }
701198092Srdivacky
702198092Srdivacky  if (!StdBadAlloc) {
703198092Srdivacky    // The "std::bad_alloc" class has not yet been declared, so build it
704198092Srdivacky    // implicitly.
705198092Srdivacky    StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
706198092Srdivacky                                        StdNamespace,
707198092Srdivacky                                        SourceLocation(),
708198092Srdivacky                                      &PP.getIdentifierTable().get("bad_alloc"),
709198092Srdivacky                                        SourceLocation(), 0);
710198092Srdivacky    StdBadAlloc->setImplicit(true);
711198092Srdivacky  }
712198092Srdivacky
713193326Sed  GlobalNewDeleteDeclared = true;
714193326Sed
715193326Sed  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
716193326Sed  QualType SizeT = Context.getSizeType();
717193326Sed
718193326Sed  DeclareGlobalAllocationFunction(
719193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_New),
720193326Sed      VoidPtr, SizeT);
721193326Sed  DeclareGlobalAllocationFunction(
722193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
723193326Sed      VoidPtr, SizeT);
724193326Sed  DeclareGlobalAllocationFunction(
725193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
726193326Sed      Context.VoidTy, VoidPtr);
727193326Sed  DeclareGlobalAllocationFunction(
728193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
729193326Sed      Context.VoidTy, VoidPtr);
730193326Sed}
731193326Sed
732193326Sed/// DeclareGlobalAllocationFunction - Declares a single implicit global
733193326Sed/// allocation function if it doesn't already exist.
734193326Sedvoid Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
735198092Srdivacky                                           QualType Return, QualType Argument) {
736193326Sed  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
737193326Sed
738193326Sed  // Check if this function is already declared.
739193326Sed  {
740193326Sed    DeclContext::lookup_iterator Alloc, AllocEnd;
741195341Sed    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
742193326Sed         Alloc != AllocEnd; ++Alloc) {
743193326Sed      // FIXME: Do we need to check for default arguments here?
744193326Sed      FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
745193326Sed      if (Func->getNumParams() == 1 &&
746193326Sed          Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
747193326Sed        return;
748193326Sed    }
749193326Sed  }
750193326Sed
751198092Srdivacky  QualType BadAllocType;
752198092Srdivacky  bool HasBadAllocExceptionSpec
753198092Srdivacky    = (Name.getCXXOverloadedOperator() == OO_New ||
754198092Srdivacky       Name.getCXXOverloadedOperator() == OO_Array_New);
755198092Srdivacky  if (HasBadAllocExceptionSpec) {
756198092Srdivacky    assert(StdBadAlloc && "Must have std::bad_alloc declared");
757198092Srdivacky    BadAllocType = Context.getTypeDeclType(StdBadAlloc);
758198092Srdivacky  }
759198092Srdivacky
760198092Srdivacky  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
761198092Srdivacky                                            true, false,
762198092Srdivacky                                            HasBadAllocExceptionSpec? 1 : 0,
763198092Srdivacky                                            &BadAllocType);
764193326Sed  FunctionDecl *Alloc =
765193326Sed    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
766198092Srdivacky                         FnType, /*DInfo=*/0, FunctionDecl::None, false, true);
767193326Sed  Alloc->setImplicit();
768193326Sed  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
769198092Srdivacky                                           0, Argument, /*DInfo=*/0,
770198092Srdivacky                                           VarDecl::None, 0);
771193326Sed  Alloc->setParams(Context, &Param, 1);
772193326Sed
773193326Sed  // FIXME: Also add this declaration to the IdentifierResolver, but
774193326Sed  // make sure it is at the end of the chain to coincide with the
775193326Sed  // global scope.
776195341Sed  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
777193326Sed}
778193326Sed
779193326Sed/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
780193326Sed/// @code ::delete ptr; @endcode
781193326Sed/// or
782193326Sed/// @code delete [] ptr; @endcode
783193326SedAction::OwningExprResult
784193326SedSema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
785198092Srdivacky                     bool ArrayForm, ExprArg Operand) {
786198092Srdivacky  // C++ [expr.delete]p1:
787198092Srdivacky  //   The operand shall have a pointer type, or a class type having a single
788198092Srdivacky  //   conversion function to a pointer type. The result has type void.
789198092Srdivacky  //
790193326Sed  // DR599 amends "pointer type" to "pointer to object type" in both cases.
791193326Sed
792198092Srdivacky  FunctionDecl *OperatorDelete = 0;
793198092Srdivacky
794193326Sed  Expr *Ex = (Expr *)Operand.get();
795193326Sed  if (!Ex->isTypeDependent()) {
796193326Sed    QualType Type = Ex->getType();
797193326Sed
798198092Srdivacky    if (const RecordType *Record = Type->getAs<RecordType>()) {
799198092Srdivacky      llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
800198092Srdivacky      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
801198092Srdivacky      OverloadedFunctionDecl *Conversions =
802198092Srdivacky        RD->getVisibleConversionFunctions();
803198092Srdivacky
804198092Srdivacky      for (OverloadedFunctionDecl::function_iterator
805198092Srdivacky             Func = Conversions->function_begin(),
806198092Srdivacky             FuncEnd = Conversions->function_end();
807198092Srdivacky           Func != FuncEnd; ++Func) {
808198092Srdivacky        // Skip over templated conversion functions; they aren't considered.
809198092Srdivacky        if (isa<FunctionTemplateDecl>(*Func))
810198092Srdivacky          continue;
811198092Srdivacky
812198092Srdivacky        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
813198092Srdivacky
814198092Srdivacky        QualType ConvType = Conv->getConversionType().getNonReferenceType();
815198092Srdivacky        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
816198092Srdivacky          if (ConvPtrType->getPointeeType()->isObjectType())
817198092Srdivacky            ObjectPtrConversions.push_back(Conv);
818198092Srdivacky      }
819198092Srdivacky      if (ObjectPtrConversions.size() == 1) {
820198092Srdivacky        // We have a single conversion to a pointer-to-object type. Perform
821198092Srdivacky        // that conversion.
822198092Srdivacky        Operand.release();
823198092Srdivacky        if (!PerformImplicitConversion(Ex,
824198092Srdivacky                            ObjectPtrConversions.front()->getConversionType(),
825198092Srdivacky                                      "converting")) {
826198092Srdivacky          Operand = Owned(Ex);
827198092Srdivacky          Type = Ex->getType();
828198092Srdivacky        }
829198092Srdivacky      }
830198092Srdivacky      else if (ObjectPtrConversions.size() > 1) {
831198092Srdivacky        Diag(StartLoc, diag::err_ambiguous_delete_operand)
832198092Srdivacky              << Type << Ex->getSourceRange();
833198092Srdivacky        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
834198092Srdivacky          CXXConversionDecl *Conv = ObjectPtrConversions[i];
835198092Srdivacky          Diag(Conv->getLocation(), diag::err_ovl_candidate);
836198092Srdivacky        }
837198092Srdivacky        return ExprError();
838198092Srdivacky      }
839193326Sed    }
840193326Sed
841193326Sed    if (!Type->isPointerType())
842193326Sed      return ExprError(Diag(StartLoc, diag::err_delete_operand)
843193326Sed        << Type << Ex->getSourceRange());
844193326Sed
845198092Srdivacky    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
846193326Sed    if (Pointee->isFunctionType() || Pointee->isVoidType())
847193326Sed      return ExprError(Diag(StartLoc, diag::err_delete_operand)
848193326Sed        << Type << Ex->getSourceRange());
849193326Sed    else if (!Pointee->isDependentType() &&
850198092Srdivacky             RequireCompleteType(StartLoc, Pointee,
851198092Srdivacky                                 PDiag(diag::warn_delete_incomplete)
852198092Srdivacky                                   << Ex->getSourceRange()))
853193326Sed      return ExprError();
854193326Sed
855198092Srdivacky    // C++ [expr.delete]p2:
856198092Srdivacky    //   [Note: a pointer to a const type can be the operand of a
857198092Srdivacky    //   delete-expression; it is not necessary to cast away the constness
858198092Srdivacky    //   (5.2.11) of the pointer expression before it is used as the operand
859198092Srdivacky    //   of the delete-expression. ]
860198092Srdivacky    ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
861198092Srdivacky                      CastExpr::CK_NoOp);
862198092Srdivacky
863198092Srdivacky    // Update the operand.
864198092Srdivacky    Operand.take();
865198092Srdivacky    Operand = ExprArg(*this, Ex);
866198092Srdivacky
867198092Srdivacky    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
868198092Srdivacky                                      ArrayForm ? OO_Array_Delete : OO_Delete);
869198092Srdivacky
870198092Srdivacky    if (Pointee->isRecordType() && !UseGlobal) {
871198092Srdivacky      CXXRecordDecl *Record
872198092Srdivacky        = cast<CXXRecordDecl>(Pointee->getAs<RecordType>()->getDecl());
873198092Srdivacky
874198092Srdivacky      // Try to find operator delete/operator delete[] in class scope.
875198092Srdivacky      LookupResult Found;
876198092Srdivacky      LookupQualifiedName(Found, Record, DeleteName, LookupOrdinaryName);
877198092Srdivacky      // FIXME: Diagnose ambiguity properly
878198092Srdivacky      assert(!Found.isAmbiguous() && "Ambiguous delete/delete[] not handled");
879198092Srdivacky      for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
880198092Srdivacky           F != FEnd; ++F) {
881198092Srdivacky        if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
882198092Srdivacky          if (Delete->isUsualDeallocationFunction()) {
883198092Srdivacky            OperatorDelete = Delete;
884198092Srdivacky            break;
885198092Srdivacky          }
886198092Srdivacky      }
887198092Srdivacky
888198092Srdivacky      if (!Record->hasTrivialDestructor())
889198092Srdivacky        if (const CXXDestructorDecl *Dtor = Record->getDestructor(Context))
890198092Srdivacky          MarkDeclarationReferenced(StartLoc,
891198092Srdivacky                                    const_cast<CXXDestructorDecl*>(Dtor));
892198092Srdivacky    }
893198092Srdivacky
894198092Srdivacky    if (!OperatorDelete) {
895198092Srdivacky      // Didn't find a member overload. Look for a global one.
896198092Srdivacky      DeclareGlobalNewDelete();
897198092Srdivacky      DeclContext *TUDecl = Context.getTranslationUnitDecl();
898198092Srdivacky      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
899198092Srdivacky                                 &Ex, 1, TUDecl, /*AllowMissing=*/false,
900198092Srdivacky                                 OperatorDelete))
901198092Srdivacky        return ExprError();
902198092Srdivacky    }
903198092Srdivacky
904193326Sed    // FIXME: Check access and ambiguity of operator delete and destructor.
905193326Sed  }
906193326Sed
907193326Sed  Operand.release();
908193326Sed  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
909198092Srdivacky                                           OperatorDelete, Ex, StartLoc));
910193326Sed}
911193326Sed
912193326Sed
913193326Sed/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
914193326Sed/// C++ if/switch/while/for statement.
915193326Sed/// e.g: "if (int x = f()) {...}"
916193326SedAction::OwningExprResult
917193326SedSema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
918193326Sed                                       Declarator &D,
919193326Sed                                       SourceLocation EqualLoc,
920193326Sed                                       ExprArg AssignExprVal) {
921193326Sed  assert(AssignExprVal.get() && "Null assignment expression");
922193326Sed
923193326Sed  // C++ 6.4p2:
924193326Sed  // The declarator shall not specify a function or an array.
925193326Sed  // The type-specifier-seq shall not contain typedef and shall not declare a
926193326Sed  // new class or enumeration.
927193326Sed
928193326Sed  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
929193326Sed         "Parser allowed 'typedef' as storage class of condition decl.");
930193326Sed
931198092Srdivacky  // FIXME: Store DeclaratorInfo in the expression.
932198092Srdivacky  DeclaratorInfo *DInfo = 0;
933198092Srdivacky  TagDecl *OwnedTag = 0;
934198092Srdivacky  QualType Ty = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
935198092Srdivacky
936193326Sed  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
937193326Sed    // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
938193326Sed    // would be created and CXXConditionDeclExpr wants a VarDecl.
939193326Sed    return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
940193326Sed      << SourceRange(StartLoc, EqualLoc));
941193326Sed  } else if (Ty->isArrayType()) { // ...or an array.
942193326Sed    Diag(StartLoc, diag::err_invalid_use_of_array_type)
943193326Sed      << SourceRange(StartLoc, EqualLoc);
944198092Srdivacky  } else if (OwnedTag && OwnedTag->isDefinition()) {
945198092Srdivacky    // The type-specifier-seq shall not declare a new class or enumeration.
946198092Srdivacky    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
947193326Sed  }
948193326Sed
949195099Sed  DeclPtrTy Dcl = ActOnDeclarator(S, D);
950193326Sed  if (!Dcl)
951193326Sed    return ExprError();
952193326Sed  AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
953193326Sed
954193326Sed  // Mark this variable as one that is declared within a conditional.
955193326Sed  // We know that the decl had to be a VarDecl because that is the only type of
956193326Sed  // decl that can be assigned and the grammar requires an '='.
957193326Sed  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
958193326Sed  VD->setDeclaredInCondition(true);
959193326Sed  return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
960193326Sed}
961193326Sed
962193326Sed/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
963193326Sedbool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
964193326Sed  // C++ 6.4p4:
965193326Sed  // The value of a condition that is an initialized declaration in a statement
966193326Sed  // other than a switch statement is the value of the declared variable
967193326Sed  // implicitly converted to type bool. If that conversion is ill-formed, the
968193326Sed  // program is ill-formed.
969193326Sed  // The value of a condition that is an expression is the value of the
970193326Sed  // expression, implicitly converted to bool.
971193326Sed  //
972193326Sed  return PerformContextuallyConvertToBool(CondExpr);
973193326Sed}
974193326Sed
975193326Sed/// Helper function to determine whether this is the (deprecated) C++
976193326Sed/// conversion from a string literal to a pointer to non-const char or
977193326Sed/// non-const wchar_t (for narrow and wide string literals,
978193326Sed/// respectively).
979198092Srdivackybool
980193326SedSema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
981193326Sed  // Look inside the implicit cast, if it exists.
982193326Sed  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
983193326Sed    From = Cast->getSubExpr();
984193326Sed
985193326Sed  // A string literal (2.13.4) that is not a wide string literal can
986193326Sed  // be converted to an rvalue of type "pointer to char"; a wide
987193326Sed  // string literal can be converted to an rvalue of type "pointer
988193326Sed  // to wchar_t" (C++ 4.2p2).
989193326Sed  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
990198092Srdivacky    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
991198092Srdivacky      if (const BuiltinType *ToPointeeType
992198092Srdivacky          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
993193326Sed        // This conversion is considered only when there is an
994193326Sed        // explicit appropriate pointer target type (C++ 4.2p2).
995198092Srdivacky        if (!ToPtrType->getPointeeType().hasQualifiers() &&
996193326Sed            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
997193326Sed             (!StrLit->isWide() &&
998193326Sed              (ToPointeeType->getKind() == BuiltinType::Char_U ||
999193326Sed               ToPointeeType->getKind() == BuiltinType::Char_S))))
1000193326Sed          return true;
1001193326Sed      }
1002193326Sed
1003193326Sed  return false;
1004193326Sed}
1005193326Sed
1006193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
1007193326Sed/// expression From to the type ToType. Returns true if there was an
1008193326Sed/// error, false otherwise. The expression From is replaced with the
1009193326Sed/// converted expression. Flavor is the kind of conversion we're
1010193326Sed/// performing, used in the error message. If @p AllowExplicit,
1011193326Sed/// explicit user-defined conversions are permitted. @p Elidable should be true
1012193326Sed/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1013193326Sed/// resolution works differently in that case.
1014193326Sedbool
1015193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType,
1016193326Sed                                const char *Flavor, bool AllowExplicit,
1017198092Srdivacky                                bool Elidable) {
1018193326Sed  ImplicitConversionSequence ICS;
1019198092Srdivacky  return PerformImplicitConversion(From, ToType, Flavor, AllowExplicit,
1020198092Srdivacky                                   Elidable, ICS);
1021198092Srdivacky}
1022198092Srdivacky
1023198092Srdivackybool
1024198092SrdivackySema::PerformImplicitConversion(Expr *&From, QualType ToType,
1025198092Srdivacky                                const char *Flavor, bool AllowExplicit,
1026198092Srdivacky                                bool Elidable,
1027198092Srdivacky                                ImplicitConversionSequence& ICS) {
1028193326Sed  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1029193326Sed  if (Elidable && getLangOptions().CPlusPlus0x) {
1030198092Srdivacky    ICS = TryImplicitConversion(From, ToType,
1031198092Srdivacky                                /*SuppressUserConversions=*/false,
1032198092Srdivacky                                AllowExplicit,
1033198092Srdivacky                                /*ForceRValue=*/true,
1034198092Srdivacky                                /*InOverloadResolution=*/false);
1035193326Sed  }
1036193326Sed  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
1037198092Srdivacky    ICS = TryImplicitConversion(From, ToType,
1038198092Srdivacky                                /*SuppressUserConversions=*/false,
1039198092Srdivacky                                AllowExplicit,
1040198092Srdivacky                                /*ForceRValue=*/false,
1041198092Srdivacky                                /*InOverloadResolution=*/false);
1042193326Sed  }
1043193326Sed  return PerformImplicitConversion(From, ToType, ICS, Flavor);
1044193326Sed}
1045193326Sed
1046193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
1047193326Sed/// expression From to the type ToType using the pre-computed implicit
1048193326Sed/// conversion sequence ICS. Returns true if there was an error, false
1049193326Sed/// otherwise. The expression From is replaced with the converted
1050193326Sed/// expression. Flavor is the kind of conversion we're performing,
1051193326Sed/// used in the error message.
1052193326Sedbool
1053193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType,
1054193326Sed                                const ImplicitConversionSequence &ICS,
1055193326Sed                                const char* Flavor) {
1056193326Sed  switch (ICS.ConversionKind) {
1057193326Sed  case ImplicitConversionSequence::StandardConversion:
1058193326Sed    if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
1059193326Sed      return true;
1060193326Sed    break;
1061193326Sed
1062198092Srdivacky  case ImplicitConversionSequence::UserDefinedConversion: {
1063198092Srdivacky
1064198092Srdivacky      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1065198092Srdivacky      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
1066198092Srdivacky      QualType BeforeToType;
1067198092Srdivacky      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1068198092Srdivacky        CastKind = CastExpr::CK_UserDefinedConversion;
1069198092Srdivacky
1070198092Srdivacky        // If the user-defined conversion is specified by a conversion function,
1071198092Srdivacky        // the initial standard conversion sequence converts the source type to
1072198092Srdivacky        // the implicit object parameter of the conversion function.
1073198092Srdivacky        BeforeToType = Context.getTagDeclType(Conv->getParent());
1074198092Srdivacky      } else if (const CXXConstructorDecl *Ctor =
1075198092Srdivacky                  dyn_cast<CXXConstructorDecl>(FD)) {
1076198092Srdivacky        CastKind = CastExpr::CK_ConstructorConversion;
1077193326Sed
1078198092Srdivacky        // If the user-defined conversion is specified by a constructor, the
1079198092Srdivacky        // initial standard conversion sequence converts the source type to the
1080198092Srdivacky        // type required by the argument of the constructor
1081198092Srdivacky        BeforeToType = Ctor->getParamDecl(0)->getType();
1082198092Srdivacky      }
1083198092Srdivacky      else
1084198092Srdivacky        assert(0 && "Unknown conversion function kind!");
1085198092Srdivacky
1086198092Srdivacky      if (PerformImplicitConversion(From, BeforeToType,
1087198092Srdivacky                                    ICS.UserDefined.Before, "converting"))
1088198092Srdivacky        return true;
1089198092Srdivacky
1090198092Srdivacky      OwningExprResult CastArg
1091198092Srdivacky        = BuildCXXCastArgument(From->getLocStart(),
1092198092Srdivacky                               ToType.getNonReferenceType(),
1093198092Srdivacky                               CastKind, cast<CXXMethodDecl>(FD),
1094198092Srdivacky                               Owned(From));
1095198092Srdivacky
1096198092Srdivacky      if (CastArg.isInvalid())
1097198092Srdivacky        return true;
1098198092Srdivacky
1099198092Srdivacky      From = new (Context) ImplicitCastExpr(ToType.getNonReferenceType(),
1100198092Srdivacky                                            CastKind, CastArg.takeAs<Expr>(),
1101198092Srdivacky                                            ToType->isLValueReferenceType());
1102198092Srdivacky      return false;
1103198092Srdivacky    }
1104198092Srdivacky
1105193326Sed  case ImplicitConversionSequence::EllipsisConversion:
1106193326Sed    assert(false && "Cannot perform an ellipsis conversion");
1107193326Sed    return false;
1108193326Sed
1109193326Sed  case ImplicitConversionSequence::BadConversion:
1110193326Sed    return true;
1111193326Sed  }
1112193326Sed
1113193326Sed  // Everything went well.
1114193326Sed  return false;
1115193326Sed}
1116193326Sed
1117193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
1118193326Sed/// expression From to the type ToType by following the standard
1119193326Sed/// conversion sequence SCS. Returns true if there was an error, false
1120193326Sed/// otherwise. The expression From is replaced with the converted
1121193326Sed/// expression. Flavor is the context in which we're performing this
1122193326Sed/// conversion, for use in error messages.
1123198092Srdivackybool
1124193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType,
1125193326Sed                                const StandardConversionSequence& SCS,
1126193326Sed                                const char *Flavor) {
1127193326Sed  // Overall FIXME: we are recomputing too many types here and doing far too
1128193326Sed  // much extra work. What this means is that we need to keep track of more
1129193326Sed  // information that is computed when we try the implicit conversion initially,
1130193326Sed  // so that we don't need to recompute anything here.
1131193326Sed  QualType FromType = From->getType();
1132193326Sed
1133193326Sed  if (SCS.CopyConstructor) {
1134193326Sed    // FIXME: When can ToType be a reference type?
1135193326Sed    assert(!ToType->isReferenceType());
1136198092Srdivacky    if (SCS.Second == ICK_Derived_To_Base) {
1137198092Srdivacky      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1138198092Srdivacky      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1139198092Srdivacky                                  MultiExprArg(*this, (void **)&From, 1),
1140198092Srdivacky                                  /*FIXME:ConstructLoc*/SourceLocation(),
1141198092Srdivacky                                  ConstructorArgs))
1142198092Srdivacky        return true;
1143198092Srdivacky      OwningExprResult FromResult =
1144198092Srdivacky        BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1145198092Srdivacky                              ToType, SCS.CopyConstructor,
1146198092Srdivacky                              move_arg(ConstructorArgs));
1147198092Srdivacky      if (FromResult.isInvalid())
1148198092Srdivacky        return true;
1149198092Srdivacky      From = FromResult.takeAs<Expr>();
1150198092Srdivacky      return false;
1151198092Srdivacky    }
1152198092Srdivacky    OwningExprResult FromResult =
1153198092Srdivacky      BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1154198092Srdivacky                            ToType, SCS.CopyConstructor,
1155198092Srdivacky                            MultiExprArg(*this, (void**)&From, 1));
1156198092Srdivacky
1157198092Srdivacky    if (FromResult.isInvalid())
1158198092Srdivacky      return true;
1159198092Srdivacky
1160198092Srdivacky    From = FromResult.takeAs<Expr>();
1161193326Sed    return false;
1162193326Sed  }
1163193326Sed
1164193326Sed  // Perform the first implicit conversion.
1165193326Sed  switch (SCS.First) {
1166193326Sed  case ICK_Identity:
1167193326Sed  case ICK_Lvalue_To_Rvalue:
1168193326Sed    // Nothing to do.
1169193326Sed    break;
1170193326Sed
1171193326Sed  case ICK_Array_To_Pointer:
1172193326Sed    FromType = Context.getArrayDecayedType(FromType);
1173198092Srdivacky    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
1174193326Sed    break;
1175193326Sed
1176193326Sed  case ICK_Function_To_Pointer:
1177193326Sed    if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
1178193326Sed      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1179193326Sed      if (!Fn)
1180193326Sed        return true;
1181193326Sed
1182193326Sed      if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1183193326Sed        return true;
1184193326Sed
1185193326Sed      FixOverloadedFunctionReference(From, Fn);
1186193326Sed      FromType = From->getType();
1187193326Sed    }
1188193326Sed    FromType = Context.getPointerType(FromType);
1189198092Srdivacky    ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
1190193326Sed    break;
1191193326Sed
1192193326Sed  default:
1193193326Sed    assert(false && "Improper first standard conversion");
1194193326Sed    break;
1195193326Sed  }
1196193326Sed
1197193326Sed  // Perform the second implicit conversion
1198193326Sed  switch (SCS.Second) {
1199193326Sed  case ICK_Identity:
1200198092Srdivacky    // If both sides are functions (or pointers/references to them), there could
1201198092Srdivacky    // be incompatible exception declarations.
1202198092Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
1203198092Srdivacky      return true;
1204198092Srdivacky    // Nothing else to do.
1205193326Sed    break;
1206193326Sed
1207193326Sed  case ICK_Integral_Promotion:
1208193326Sed  case ICK_Floating_Promotion:
1209193326Sed  case ICK_Complex_Promotion:
1210193326Sed  case ICK_Integral_Conversion:
1211193326Sed  case ICK_Floating_Conversion:
1212193326Sed  case ICK_Complex_Conversion:
1213193326Sed  case ICK_Floating_Integral:
1214193326Sed  case ICK_Complex_Real:
1215193326Sed  case ICK_Compatible_Conversion:
1216193326Sed      // FIXME: Go deeper to get the unqualified type!
1217193326Sed    FromType = ToType.getUnqualifiedType();
1218193326Sed    ImpCastExprToType(From, FromType);
1219193326Sed    break;
1220193326Sed
1221198092Srdivacky  case ICK_Pointer_Conversion: {
1222193326Sed    if (SCS.IncompatibleObjC) {
1223193326Sed      // Diagnose incompatible Objective-C conversions
1224198092Srdivacky      Diag(From->getSourceRange().getBegin(),
1225193326Sed           diag::ext_typecheck_convert_incompatible_pointer)
1226193326Sed        << From->getType() << ToType << Flavor
1227193326Sed        << From->getSourceRange();
1228193326Sed    }
1229193326Sed
1230198092Srdivacky
1231198092Srdivacky    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1232198092Srdivacky    if (CheckPointerConversion(From, ToType, Kind))
1233193326Sed      return true;
1234198092Srdivacky    ImpCastExprToType(From, ToType, Kind);
1235193326Sed    break;
1236198092Srdivacky  }
1237198092Srdivacky
1238198092Srdivacky  case ICK_Pointer_Member: {
1239198092Srdivacky    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1240198092Srdivacky    if (CheckMemberPointerConversion(From, ToType, Kind))
1241193326Sed      return true;
1242198092Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
1243198092Srdivacky      return true;
1244198092Srdivacky    ImpCastExprToType(From, ToType, Kind);
1245193326Sed    break;
1246198092Srdivacky  }
1247193326Sed  case ICK_Boolean_Conversion:
1248193326Sed    FromType = Context.BoolTy;
1249193326Sed    ImpCastExprToType(From, FromType);
1250193326Sed    break;
1251193326Sed
1252193326Sed  default:
1253193326Sed    assert(false && "Improper second standard conversion");
1254193326Sed    break;
1255193326Sed  }
1256193326Sed
1257193326Sed  switch (SCS.Third) {
1258193326Sed  case ICK_Identity:
1259193326Sed    // Nothing to do.
1260193326Sed    break;
1261193326Sed
1262193326Sed  case ICK_Qualification:
1263193326Sed    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1264193326Sed    // references.
1265198092Srdivacky    ImpCastExprToType(From, ToType.getNonReferenceType(),
1266198092Srdivacky                      CastExpr::CK_Unknown,
1267193326Sed                      ToType->isLValueReferenceType());
1268193326Sed    break;
1269193326Sed
1270193326Sed  default:
1271193326Sed    assert(false && "Improper second standard conversion");
1272193326Sed    break;
1273193326Sed  }
1274193326Sed
1275193326Sed  return false;
1276193326Sed}
1277193326Sed
1278193326SedSema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1279193326Sed                                                 SourceLocation KWLoc,
1280193326Sed                                                 SourceLocation LParen,
1281193326Sed                                                 TypeTy *Ty,
1282193326Sed                                                 SourceLocation RParen) {
1283198092Srdivacky  QualType T = GetTypeFromParser(Ty);
1284193326Sed
1285198092Srdivacky  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1286198092Srdivacky  // all traits except __is_class, __is_enum and __is_union require a the type
1287198092Srdivacky  // to be complete.
1288198092Srdivacky  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1289198092Srdivacky    if (RequireCompleteType(KWLoc, T,
1290198092Srdivacky                            diag::err_incomplete_type_used_in_type_trait_expr))
1291198092Srdivacky      return ExprError();
1292198092Srdivacky  }
1293198092Srdivacky
1294193326Sed  // There is no point in eagerly computing the value. The traits are designed
1295193326Sed  // to be used from type trait templates, so Ty will be a template parameter
1296193326Sed  // 99% of the time.
1297198092Srdivacky  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1298198092Srdivacky                                                RParen, Context.BoolTy));
1299193326Sed}
1300193326Sed
1301193326SedQualType Sema::CheckPointerToMemberOperands(
1302198092Srdivacky  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1303193326Sed  const char *OpSpelling = isIndirect ? "->*" : ".*";
1304193326Sed  // C++ 5.5p2
1305193326Sed  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1306193326Sed  //   be of type "pointer to member of T" (where T is a completely-defined
1307193326Sed  //   class type) [...]
1308193326Sed  QualType RType = rex->getType();
1309198092Srdivacky  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1310193326Sed  if (!MemPtr) {
1311193326Sed    Diag(Loc, diag::err_bad_memptr_rhs)
1312193326Sed      << OpSpelling << RType << rex->getSourceRange();
1313193326Sed    return QualType();
1314198092Srdivacky  }
1315193326Sed
1316193326Sed  QualType Class(MemPtr->getClass(), 0);
1317193326Sed
1318193326Sed  // C++ 5.5p2
1319193326Sed  //   [...] to its first operand, which shall be of class T or of a class of
1320193326Sed  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1321193326Sed  //   such a class]
1322193326Sed  QualType LType = lex->getType();
1323193326Sed  if (isIndirect) {
1324198092Srdivacky    if (const PointerType *Ptr = LType->getAs<PointerType>())
1325193326Sed      LType = Ptr->getPointeeType().getNonReferenceType();
1326193326Sed    else {
1327193326Sed      Diag(Loc, diag::err_bad_memptr_lhs)
1328193326Sed        << OpSpelling << 1 << LType << lex->getSourceRange();
1329193326Sed      return QualType();
1330193326Sed    }
1331193326Sed  }
1332193326Sed
1333193326Sed  if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1334193326Sed      Context.getCanonicalType(LType).getUnqualifiedType()) {
1335198092Srdivacky    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1336198092Srdivacky                       /*DetectVirtual=*/false);
1337193326Sed    // FIXME: Would it be useful to print full ambiguity paths, or is that
1338193326Sed    // overkill?
1339193326Sed    if (!IsDerivedFrom(LType, Class, Paths) ||
1340193326Sed        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1341193326Sed      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1342193326Sed        << (int)isIndirect << lex->getType() << lex->getSourceRange();
1343193326Sed      return QualType();
1344193326Sed    }
1345193326Sed  }
1346193326Sed
1347193326Sed  // C++ 5.5p2
1348193326Sed  //   The result is an object or a function of the type specified by the
1349193326Sed  //   second operand.
1350193326Sed  // The cv qualifiers are the union of those in the pointer and the left side,
1351193326Sed  // in accordance with 5.5p5 and 5.2.5.
1352193326Sed  // FIXME: This returns a dereferenced member function pointer as a normal
1353193326Sed  // function type. However, the only operation valid on such functions is
1354193326Sed  // calling them. There's also a GCC extension to get a function pointer to the
1355193326Sed  // thing, which is another complication, because this type - unlike the type
1356193326Sed  // that is the result of this expression - takes the class as the first
1357193326Sed  // argument.
1358193326Sed  // We probably need a "MemberFunctionClosureType" or something like that.
1359193326Sed  QualType Result = MemPtr->getPointeeType();
1360198092Srdivacky  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
1361193326Sed  return Result;
1362193326Sed}
1363193326Sed
1364193326Sed/// \brief Get the target type of a standard or user-defined conversion.
1365193326Sedstatic QualType TargetType(const ImplicitConversionSequence &ICS) {
1366193326Sed  assert((ICS.ConversionKind ==
1367193326Sed              ImplicitConversionSequence::StandardConversion ||
1368193326Sed          ICS.ConversionKind ==
1369193326Sed              ImplicitConversionSequence::UserDefinedConversion) &&
1370193326Sed         "function only valid for standard or user-defined conversions");
1371193326Sed  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1372193326Sed    return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1373193326Sed  return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1374193326Sed}
1375193326Sed
1376193326Sed/// \brief Try to convert a type to another according to C++0x 5.16p3.
1377193326Sed///
1378193326Sed/// This is part of the parameter validation for the ? operator. If either
1379193326Sed/// value operand is a class type, the two operands are attempted to be
1380193326Sed/// converted to each other. This function does the conversion in one direction.
1381193326Sed/// It emits a diagnostic and returns true only if it finds an ambiguous
1382193326Sed/// conversion.
1383193326Sedstatic bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1384193326Sed                                SourceLocation QuestionLoc,
1385198092Srdivacky                                ImplicitConversionSequence &ICS) {
1386193326Sed  // C++0x 5.16p3
1387193326Sed  //   The process for determining whether an operand expression E1 of type T1
1388193326Sed  //   can be converted to match an operand expression E2 of type T2 is defined
1389193326Sed  //   as follows:
1390193326Sed  //   -- If E2 is an lvalue:
1391193326Sed  if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1392193326Sed    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1393193326Sed    //   type "lvalue reference to T2", subject to the constraint that in the
1394193326Sed    //   conversion the reference must bind directly to E1.
1395193326Sed    if (!Self.CheckReferenceInit(From,
1396193326Sed                            Self.Context.getLValueReferenceType(To->getType()),
1397198092Srdivacky                                 To->getLocStart(),
1398198092Srdivacky                                 /*SuppressUserConversions=*/false,
1399198092Srdivacky                                 /*AllowExplicit=*/false,
1400198092Srdivacky                                 /*ForceRValue=*/false,
1401198092Srdivacky                                 &ICS))
1402193326Sed    {
1403193326Sed      assert((ICS.ConversionKind ==
1404193326Sed                  ImplicitConversionSequence::StandardConversion ||
1405193326Sed              ICS.ConversionKind ==
1406193326Sed                  ImplicitConversionSequence::UserDefinedConversion) &&
1407193326Sed             "expected a definite conversion");
1408193326Sed      bool DirectBinding =
1409193326Sed        ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1410193326Sed        ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1411193326Sed      if (DirectBinding)
1412193326Sed        return false;
1413193326Sed    }
1414193326Sed  }
1415193326Sed  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1416193326Sed  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1417193326Sed  //      -- if E1 and E2 have class type, and the underlying class types are
1418193326Sed  //         the same or one is a base class of the other:
1419193326Sed  QualType FTy = From->getType();
1420193326Sed  QualType TTy = To->getType();
1421198092Srdivacky  const RecordType *FRec = FTy->getAs<RecordType>();
1422198092Srdivacky  const RecordType *TRec = TTy->getAs<RecordType>();
1423193326Sed  bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1424193326Sed  if (FRec && TRec && (FRec == TRec ||
1425193326Sed        FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1426193326Sed    //         E1 can be converted to match E2 if the class of T2 is the
1427193326Sed    //         same type as, or a base class of, the class of T1, and
1428193326Sed    //         [cv2 > cv1].
1429193326Sed    if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1430193326Sed      // Could still fail if there's no copy constructor.
1431193326Sed      // FIXME: Is this a hard error then, or just a conversion failure? The
1432193326Sed      // standard doesn't say.
1433198092Srdivacky      ICS = Self.TryCopyInitialization(From, TTy,
1434198092Srdivacky                                       /*SuppressUserConversions=*/false,
1435198092Srdivacky                                       /*ForceRValue=*/false,
1436198092Srdivacky                                       /*InOverloadResolution=*/false);
1437193326Sed    }
1438193326Sed  } else {
1439193326Sed    //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1440193326Sed    //        implicitly converted to the type that expression E2 would have
1441193326Sed    //        if E2 were converted to an rvalue.
1442193326Sed    // First find the decayed type.
1443193326Sed    if (TTy->isFunctionType())
1444193326Sed      TTy = Self.Context.getPointerType(TTy);
1445198092Srdivacky    else if (TTy->isArrayType())
1446193326Sed      TTy = Self.Context.getArrayDecayedType(TTy);
1447193326Sed
1448193326Sed    // Now try the implicit conversion.
1449193326Sed    // FIXME: This doesn't detect ambiguities.
1450198092Srdivacky    ICS = Self.TryImplicitConversion(From, TTy,
1451198092Srdivacky                                     /*SuppressUserConversions=*/false,
1452198092Srdivacky                                     /*AllowExplicit=*/false,
1453198092Srdivacky                                     /*ForceRValue=*/false,
1454198092Srdivacky                                     /*InOverloadResolution=*/false);
1455193326Sed  }
1456193326Sed  return false;
1457193326Sed}
1458193326Sed
1459193326Sed/// \brief Try to find a common type for two according to C++0x 5.16p5.
1460193326Sed///
1461193326Sed/// This is part of the parameter validation for the ? operator. If either
1462193326Sed/// value operand is a class type, overload resolution is used to find a
1463193326Sed/// conversion to a common type.
1464193326Sedstatic bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1465193326Sed                                    SourceLocation Loc) {
1466193326Sed  Expr *Args[2] = { LHS, RHS };
1467193326Sed  OverloadCandidateSet CandidateSet;
1468193326Sed  Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1469193326Sed
1470193326Sed  OverloadCandidateSet::iterator Best;
1471194613Sed  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
1472193326Sed    case Sema::OR_Success:
1473193326Sed      // We found a match. Perform the conversions on the arguments and move on.
1474193326Sed      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1475193326Sed                                         Best->Conversions[0], "converting") ||
1476193326Sed          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1477193326Sed                                         Best->Conversions[1], "converting"))
1478193326Sed        break;
1479193326Sed      return false;
1480193326Sed
1481193326Sed    case Sema::OR_No_Viable_Function:
1482193326Sed      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1483193326Sed        << LHS->getType() << RHS->getType()
1484193326Sed        << LHS->getSourceRange() << RHS->getSourceRange();
1485193326Sed      return true;
1486193326Sed
1487193326Sed    case Sema::OR_Ambiguous:
1488193326Sed      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1489193326Sed        << LHS->getType() << RHS->getType()
1490193326Sed        << LHS->getSourceRange() << RHS->getSourceRange();
1491193326Sed      // FIXME: Print the possible common types by printing the return types of
1492193326Sed      // the viable candidates.
1493193326Sed      break;
1494193326Sed
1495193326Sed    case Sema::OR_Deleted:
1496193326Sed      assert(false && "Conditional operator has only built-in overloads");
1497193326Sed      break;
1498193326Sed  }
1499193326Sed  return true;
1500193326Sed}
1501193326Sed
1502193326Sed/// \brief Perform an "extended" implicit conversion as returned by
1503193326Sed/// TryClassUnification.
1504193326Sed///
1505193326Sed/// TryClassUnification generates ICSs that include reference bindings.
1506193326Sed/// PerformImplicitConversion is not suitable for this; it chokes if the
1507193326Sed/// second part of a standard conversion is ICK_DerivedToBase. This function
1508193326Sed/// handles the reference binding specially.
1509193326Sedstatic bool ConvertForConditional(Sema &Self, Expr *&E,
1510198092Srdivacky                                  const ImplicitConversionSequence &ICS) {
1511193326Sed  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1512193326Sed      ICS.Standard.ReferenceBinding) {
1513193326Sed    assert(ICS.Standard.DirectBinding &&
1514193326Sed           "TryClassUnification should never generate indirect ref bindings");
1515193326Sed    // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1516193326Sed    // redoing all the work.
1517193326Sed    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1518198092Srdivacky                                        TargetType(ICS)),
1519198092Srdivacky                                   /*FIXME:*/E->getLocStart(),
1520198092Srdivacky                                   /*SuppressUserConversions=*/false,
1521198092Srdivacky                                   /*AllowExplicit=*/false,
1522198092Srdivacky                                   /*ForceRValue=*/false);
1523193326Sed  }
1524193326Sed  if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1525193326Sed      ICS.UserDefined.After.ReferenceBinding) {
1526193326Sed    assert(ICS.UserDefined.After.DirectBinding &&
1527193326Sed           "TryClassUnification should never generate indirect ref bindings");
1528193326Sed    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1529198092Srdivacky                                        TargetType(ICS)),
1530198092Srdivacky                                   /*FIXME:*/E->getLocStart(),
1531198092Srdivacky                                   /*SuppressUserConversions=*/false,
1532198092Srdivacky                                   /*AllowExplicit=*/false,
1533198092Srdivacky                                   /*ForceRValue=*/false);
1534193326Sed  }
1535193326Sed  if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1536193326Sed    return true;
1537193326Sed  return false;
1538193326Sed}
1539193326Sed
1540193326Sed/// \brief Check the operands of ?: under C++ semantics.
1541193326Sed///
1542193326Sed/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1543193326Sed/// extension. In this case, LHS == Cond. (But they're not aliases.)
1544193326SedQualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1545193326Sed                                           SourceLocation QuestionLoc) {
1546193326Sed  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1547193326Sed  // interface pointers.
1548193326Sed
1549193326Sed  // C++0x 5.16p1
1550193326Sed  //   The first expression is contextually converted to bool.
1551193326Sed  if (!Cond->isTypeDependent()) {
1552193326Sed    if (CheckCXXBooleanCondition(Cond))
1553193326Sed      return QualType();
1554193326Sed  }
1555193326Sed
1556193326Sed  // Either of the arguments dependent?
1557193326Sed  if (LHS->isTypeDependent() || RHS->isTypeDependent())
1558193326Sed    return Context.DependentTy;
1559193326Sed
1560193326Sed  // C++0x 5.16p2
1561193326Sed  //   If either the second or the third operand has type (cv) void, ...
1562193326Sed  QualType LTy = LHS->getType();
1563193326Sed  QualType RTy = RHS->getType();
1564193326Sed  bool LVoid = LTy->isVoidType();
1565193326Sed  bool RVoid = RTy->isVoidType();
1566193326Sed  if (LVoid || RVoid) {
1567193326Sed    //   ... then the [l2r] conversions are performed on the second and third
1568193326Sed    //   operands ...
1569193326Sed    DefaultFunctionArrayConversion(LHS);
1570193326Sed    DefaultFunctionArrayConversion(RHS);
1571193326Sed    LTy = LHS->getType();
1572193326Sed    RTy = RHS->getType();
1573193326Sed
1574193326Sed    //   ... and one of the following shall hold:
1575193326Sed    //   -- The second or the third operand (but not both) is a throw-
1576193326Sed    //      expression; the result is of the type of the other and is an rvalue.
1577193326Sed    bool LThrow = isa<CXXThrowExpr>(LHS);
1578193326Sed    bool RThrow = isa<CXXThrowExpr>(RHS);
1579193326Sed    if (LThrow && !RThrow)
1580193326Sed      return RTy;
1581193326Sed    if (RThrow && !LThrow)
1582193326Sed      return LTy;
1583193326Sed
1584193326Sed    //   -- Both the second and third operands have type void; the result is of
1585193326Sed    //      type void and is an rvalue.
1586193326Sed    if (LVoid && RVoid)
1587193326Sed      return Context.VoidTy;
1588193326Sed
1589193326Sed    // Neither holds, error.
1590193326Sed    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1591193326Sed      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1592193326Sed      << LHS->getSourceRange() << RHS->getSourceRange();
1593193326Sed    return QualType();
1594193326Sed  }
1595193326Sed
1596193326Sed  // Neither is void.
1597193326Sed
1598193326Sed  // C++0x 5.16p3
1599193326Sed  //   Otherwise, if the second and third operand have different types, and
1600193326Sed  //   either has (cv) class type, and attempt is made to convert each of those
1601193326Sed  //   operands to the other.
1602193326Sed  if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1603193326Sed      (LTy->isRecordType() || RTy->isRecordType())) {
1604193326Sed    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1605193326Sed    // These return true if a single direction is already ambiguous.
1606193326Sed    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1607193326Sed      return QualType();
1608193326Sed    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1609193326Sed      return QualType();
1610193326Sed
1611193326Sed    bool HaveL2R = ICSLeftToRight.ConversionKind !=
1612193326Sed      ImplicitConversionSequence::BadConversion;
1613193326Sed    bool HaveR2L = ICSRightToLeft.ConversionKind !=
1614193326Sed      ImplicitConversionSequence::BadConversion;
1615193326Sed    //   If both can be converted, [...] the program is ill-formed.
1616193326Sed    if (HaveL2R && HaveR2L) {
1617193326Sed      Diag(QuestionLoc, diag::err_conditional_ambiguous)
1618193326Sed        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1619193326Sed      return QualType();
1620193326Sed    }
1621193326Sed
1622193326Sed    //   If exactly one conversion is possible, that conversion is applied to
1623193326Sed    //   the chosen operand and the converted operands are used in place of the
1624193326Sed    //   original operands for the remainder of this section.
1625193326Sed    if (HaveL2R) {
1626193326Sed      if (ConvertForConditional(*this, LHS, ICSLeftToRight))
1627193326Sed        return QualType();
1628193326Sed      LTy = LHS->getType();
1629193326Sed    } else if (HaveR2L) {
1630193326Sed      if (ConvertForConditional(*this, RHS, ICSRightToLeft))
1631193326Sed        return QualType();
1632193326Sed      RTy = RHS->getType();
1633193326Sed    }
1634193326Sed  }
1635193326Sed
1636193326Sed  // C++0x 5.16p4
1637193326Sed  //   If the second and third operands are lvalues and have the same type,
1638193326Sed  //   the result is of that type [...]
1639193326Sed  bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1640193326Sed  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1641193326Sed      RHS->isLvalue(Context) == Expr::LV_Valid)
1642193326Sed    return LTy;
1643193326Sed
1644193326Sed  // C++0x 5.16p5
1645193326Sed  //   Otherwise, the result is an rvalue. If the second and third operands
1646193326Sed  //   do not have the same type, and either has (cv) class type, ...
1647193326Sed  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1648193326Sed    //   ... overload resolution is used to determine the conversions (if any)
1649193326Sed    //   to be applied to the operands. If the overload resolution fails, the
1650193326Sed    //   program is ill-formed.
1651193326Sed    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1652193326Sed      return QualType();
1653193326Sed  }
1654193326Sed
1655193326Sed  // C++0x 5.16p6
1656193326Sed  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1657193326Sed  //   conversions are performed on the second and third operands.
1658193326Sed  DefaultFunctionArrayConversion(LHS);
1659193326Sed  DefaultFunctionArrayConversion(RHS);
1660193326Sed  LTy = LHS->getType();
1661193326Sed  RTy = RHS->getType();
1662193326Sed
1663193326Sed  //   After those conversions, one of the following shall hold:
1664193326Sed  //   -- The second and third operands have the same type; the result
1665193326Sed  //      is of that type.
1666193326Sed  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1667193326Sed    return LTy;
1668193326Sed
1669193326Sed  //   -- The second and third operands have arithmetic or enumeration type;
1670193326Sed  //      the usual arithmetic conversions are performed to bring them to a
1671193326Sed  //      common type, and the result is of that type.
1672193326Sed  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1673193326Sed    UsualArithmeticConversions(LHS, RHS);
1674193326Sed    return LHS->getType();
1675193326Sed  }
1676193326Sed
1677193326Sed  //   -- The second and third operands have pointer type, or one has pointer
1678193326Sed  //      type and the other is a null pointer constant; pointer conversions
1679193326Sed  //      and qualification conversions are performed to bring them to their
1680193326Sed  //      composite pointer type. The result is of the composite pointer type.
1681193326Sed  QualType Composite = FindCompositePointerType(LHS, RHS);
1682193326Sed  if (!Composite.isNull())
1683193326Sed    return Composite;
1684193326Sed
1685193326Sed  // Fourth bullet is same for pointers-to-member. However, the possible
1686193326Sed  // conversions are far more limited: we have null-to-pointer, upcast of
1687193326Sed  // containing class, and second-level cv-ness.
1688193326Sed  // cv-ness is not a union, but must match one of the two operands. (Which,
1689193326Sed  // frankly, is stupid.)
1690198092Srdivacky  const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1691198092Srdivacky  const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
1692198092Srdivacky  if (LMemPtr &&
1693198092Srdivacky      RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1694193326Sed    ImpCastExprToType(RHS, LTy);
1695193326Sed    return LTy;
1696193326Sed  }
1697198092Srdivacky  if (RMemPtr &&
1698198092Srdivacky      LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1699193326Sed    ImpCastExprToType(LHS, RTy);
1700193326Sed    return RTy;
1701193326Sed  }
1702193326Sed  if (LMemPtr && RMemPtr) {
1703193326Sed    QualType LPointee = LMemPtr->getPointeeType();
1704193326Sed    QualType RPointee = RMemPtr->getPointeeType();
1705198092Srdivacky
1706198092Srdivacky    QualifierCollector LPQuals, RPQuals;
1707198092Srdivacky    const Type *LPCan = LPQuals.strip(Context.getCanonicalType(LPointee));
1708198092Srdivacky    const Type *RPCan = RPQuals.strip(Context.getCanonicalType(RPointee));
1709198092Srdivacky
1710193326Sed    // First, we check that the unqualified pointee type is the same. If it's
1711193326Sed    // not, there's no conversion that will unify the two pointers.
1712198092Srdivacky    if (LPCan == RPCan) {
1713198092Srdivacky
1714198092Srdivacky      // Second, we take the greater of the two qualifications. If neither
1715193326Sed      // is greater than the other, the conversion is not possible.
1716198092Srdivacky
1717198092Srdivacky      Qualifiers MergedQuals = LPQuals + RPQuals;
1718198092Srdivacky
1719198092Srdivacky      bool CompatibleQuals = true;
1720198092Srdivacky      if (MergedQuals.getCVRQualifiers() != LPQuals.getCVRQualifiers() &&
1721198092Srdivacky          MergedQuals.getCVRQualifiers() != RPQuals.getCVRQualifiers())
1722198092Srdivacky        CompatibleQuals = false;
1723198092Srdivacky      else if (LPQuals.getAddressSpace() != RPQuals.getAddressSpace())
1724198092Srdivacky        // FIXME:
1725198092Srdivacky        // C99 6.5.15 as modified by TR 18037:
1726198092Srdivacky        //   If the second and third operands are pointers into different
1727198092Srdivacky        //   address spaces, the address spaces must overlap.
1728198092Srdivacky        CompatibleQuals = false;
1729198092Srdivacky      // FIXME: GC qualifiers?
1730198092Srdivacky
1731198092Srdivacky      if (CompatibleQuals) {
1732193326Sed        // Third, we check if either of the container classes is derived from
1733193326Sed        // the other.
1734193326Sed        QualType LContainer(LMemPtr->getClass(), 0);
1735193326Sed        QualType RContainer(RMemPtr->getClass(), 0);
1736193326Sed        QualType MoreDerived;
1737193326Sed        if (Context.getCanonicalType(LContainer) ==
1738193326Sed            Context.getCanonicalType(RContainer))
1739193326Sed          MoreDerived = LContainer;
1740193326Sed        else if (IsDerivedFrom(LContainer, RContainer))
1741193326Sed          MoreDerived = LContainer;
1742193326Sed        else if (IsDerivedFrom(RContainer, LContainer))
1743193326Sed          MoreDerived = RContainer;
1744193326Sed
1745193326Sed        if (!MoreDerived.isNull()) {
1746193326Sed          // The type 'Q Pointee (MoreDerived::*)' is the common type.
1747193326Sed          // We don't use ImpCastExprToType here because this could still fail
1748193326Sed          // for ambiguous or inaccessible conversions.
1749198092Srdivacky          LPointee = Context.getQualifiedType(LPointee, MergedQuals);
1750198092Srdivacky          QualType Common
1751198092Srdivacky            = Context.getMemberPointerType(LPointee, MoreDerived.getTypePtr());
1752193326Sed          if (PerformImplicitConversion(LHS, Common, "converting"))
1753193326Sed            return QualType();
1754193326Sed          if (PerformImplicitConversion(RHS, Common, "converting"))
1755193326Sed            return QualType();
1756193326Sed          return Common;
1757193326Sed        }
1758193326Sed      }
1759193326Sed    }
1760193326Sed  }
1761193326Sed
1762193326Sed  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1763193326Sed    << LHS->getType() << RHS->getType()
1764193326Sed    << LHS->getSourceRange() << RHS->getSourceRange();
1765193326Sed  return QualType();
1766193326Sed}
1767193326Sed
1768193326Sed/// \brief Find a merged pointer type and convert the two expressions to it.
1769193326Sed///
1770198092Srdivacky/// This finds the composite pointer type (or member pointer type) for @p E1
1771198092Srdivacky/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
1772198092Srdivacky/// type and returns it.
1773193326Sed/// It does not emit diagnostics.
1774193326SedQualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1775193326Sed  assert(getLangOptions().CPlusPlus && "This function assumes C++");
1776193326Sed  QualType T1 = E1->getType(), T2 = E2->getType();
1777193326Sed
1778198092Srdivacky  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1779198092Srdivacky      !T2->isPointerType() && !T2->isMemberPointerType())
1780198092Srdivacky   return QualType();
1781198092Srdivacky
1782198092Srdivacky  // FIXME: Do we need to work on the canonical types?
1783198092Srdivacky
1784193326Sed  // C++0x 5.9p2
1785193326Sed  //   Pointer conversions and qualification conversions are performed on
1786193326Sed  //   pointer operands to bring them to their composite pointer type. If
1787193326Sed  //   one operand is a null pointer constant, the composite pointer type is
1788193326Sed  //   the type of the other operand.
1789198092Srdivacky  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1790193326Sed    ImpCastExprToType(E1, T2);
1791193326Sed    return T2;
1792193326Sed  }
1793198092Srdivacky  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
1794193326Sed    ImpCastExprToType(E2, T1);
1795193326Sed    return T1;
1796193326Sed  }
1797198092Srdivacky
1798198092Srdivacky  // Now both have to be pointers or member pointers.
1799198092Srdivacky  if (!T1->isPointerType() && !T1->isMemberPointerType() &&
1800198092Srdivacky      !T2->isPointerType() && !T2->isMemberPointerType())
1801193326Sed    return QualType();
1802193326Sed
1803193326Sed  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
1804193326Sed  //   the other has type "pointer to cv2 T" and the composite pointer type is
1805193326Sed  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1806193326Sed  //   Otherwise, the composite pointer type is a pointer type similar to the
1807193326Sed  //   type of one of the operands, with a cv-qualification signature that is
1808193326Sed  //   the union of the cv-qualification signatures of the operand types.
1809193326Sed  // In practice, the first part here is redundant; it's subsumed by the second.
1810193326Sed  // What we do here is, we build the two possible composite types, and try the
1811193326Sed  // conversions in both directions. If only one works, or if the two composite
1812193326Sed  // types are the same, we have succeeded.
1813198092Srdivacky  // FIXME: extended qualifiers?
1814193326Sed  llvm::SmallVector<unsigned, 4> QualifierUnion;
1815198092Srdivacky  llvm::SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
1816193326Sed  QualType Composite1 = T1, Composite2 = T2;
1817198092Srdivacky  do {
1818198092Srdivacky    const PointerType *Ptr1, *Ptr2;
1819198092Srdivacky    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
1820198092Srdivacky        (Ptr2 = Composite2->getAs<PointerType>())) {
1821198092Srdivacky      Composite1 = Ptr1->getPointeeType();
1822198092Srdivacky      Composite2 = Ptr2->getPointeeType();
1823198092Srdivacky      QualifierUnion.push_back(
1824198092Srdivacky                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1825198092Srdivacky      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
1826198092Srdivacky      continue;
1827198092Srdivacky    }
1828198092Srdivacky
1829198092Srdivacky    const MemberPointerType *MemPtr1, *MemPtr2;
1830198092Srdivacky    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
1831198092Srdivacky        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
1832198092Srdivacky      Composite1 = MemPtr1->getPointeeType();
1833198092Srdivacky      Composite2 = MemPtr2->getPointeeType();
1834198092Srdivacky      QualifierUnion.push_back(
1835198092Srdivacky                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1836198092Srdivacky      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
1837198092Srdivacky                                             MemPtr2->getClass()));
1838198092Srdivacky      continue;
1839198092Srdivacky    }
1840198092Srdivacky
1841198092Srdivacky    // FIXME: block pointer types?
1842198092Srdivacky
1843198092Srdivacky    // Cannot unwrap any more types.
1844198092Srdivacky    break;
1845198092Srdivacky  } while (true);
1846198092Srdivacky
1847198092Srdivacky  // Rewrap the composites as pointers or member pointers with the union CVRs.
1848198092Srdivacky  llvm::SmallVector<std::pair<const Type *, const Type *>, 4>::iterator MOC
1849198092Srdivacky    = MemberOfClass.begin();
1850198092Srdivacky  for (llvm::SmallVector<unsigned, 4>::iterator
1851198092Srdivacky         I = QualifierUnion.begin(),
1852198092Srdivacky         E = QualifierUnion.end();
1853198092Srdivacky       I != E; (void)++I, ++MOC) {
1854198092Srdivacky    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
1855198092Srdivacky    if (MOC->first && MOC->second) {
1856198092Srdivacky      // Rebuild member pointer type
1857198092Srdivacky      Composite1 = Context.getMemberPointerType(
1858198092Srdivacky                                    Context.getQualifiedType(Composite1, Quals),
1859198092Srdivacky                                    MOC->first);
1860198092Srdivacky      Composite2 = Context.getMemberPointerType(
1861198092Srdivacky                                    Context.getQualifiedType(Composite2, Quals),
1862198092Srdivacky                                    MOC->second);
1863198092Srdivacky    } else {
1864198092Srdivacky      // Rebuild pointer type
1865198092Srdivacky      Composite1
1866198092Srdivacky        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
1867198092Srdivacky      Composite2
1868198092Srdivacky        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
1869198092Srdivacky    }
1870193326Sed  }
1871193326Sed
1872198092Srdivacky  ImplicitConversionSequence E1ToC1 =
1873198092Srdivacky    TryImplicitConversion(E1, Composite1,
1874198092Srdivacky                          /*SuppressUserConversions=*/false,
1875198092Srdivacky                          /*AllowExplicit=*/false,
1876198092Srdivacky                          /*ForceRValue=*/false,
1877198092Srdivacky                          /*InOverloadResolution=*/false);
1878198092Srdivacky  ImplicitConversionSequence E2ToC1 =
1879198092Srdivacky    TryImplicitConversion(E2, Composite1,
1880198092Srdivacky                          /*SuppressUserConversions=*/false,
1881198092Srdivacky                          /*AllowExplicit=*/false,
1882198092Srdivacky                          /*ForceRValue=*/false,
1883198092Srdivacky                          /*InOverloadResolution=*/false);
1884198092Srdivacky
1885193326Sed  ImplicitConversionSequence E1ToC2, E2ToC2;
1886193326Sed  E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1887193326Sed  E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1888193326Sed  if (Context.getCanonicalType(Composite1) !=
1889193326Sed      Context.getCanonicalType(Composite2)) {
1890198092Srdivacky    E1ToC2 = TryImplicitConversion(E1, Composite2,
1891198092Srdivacky                                   /*SuppressUserConversions=*/false,
1892198092Srdivacky                                   /*AllowExplicit=*/false,
1893198092Srdivacky                                   /*ForceRValue=*/false,
1894198092Srdivacky                                   /*InOverloadResolution=*/false);
1895198092Srdivacky    E2ToC2 = TryImplicitConversion(E2, Composite2,
1896198092Srdivacky                                   /*SuppressUserConversions=*/false,
1897198092Srdivacky                                   /*AllowExplicit=*/false,
1898198092Srdivacky                                   /*ForceRValue=*/false,
1899198092Srdivacky                                   /*InOverloadResolution=*/false);
1900193326Sed  }
1901193326Sed
1902193326Sed  bool ToC1Viable = E1ToC1.ConversionKind !=
1903193326Sed                      ImplicitConversionSequence::BadConversion
1904193326Sed                 && E2ToC1.ConversionKind !=
1905193326Sed                      ImplicitConversionSequence::BadConversion;
1906193326Sed  bool ToC2Viable = E1ToC2.ConversionKind !=
1907193326Sed                      ImplicitConversionSequence::BadConversion
1908193326Sed                 && E2ToC2.ConversionKind !=
1909193326Sed                      ImplicitConversionSequence::BadConversion;
1910193326Sed  if (ToC1Viable && !ToC2Viable) {
1911193326Sed    if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1912193326Sed        !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1913193326Sed      return Composite1;
1914193326Sed  }
1915193326Sed  if (ToC2Viable && !ToC1Viable) {
1916193326Sed    if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1917193326Sed        !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1918193326Sed      return Composite2;
1919193326Sed  }
1920193326Sed  return QualType();
1921193326Sed}
1922193326Sed
1923193326SedSema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
1924198092Srdivacky  if (!Context.getLangOptions().CPlusPlus)
1925198092Srdivacky    return Owned(E);
1926198092Srdivacky
1927198092Srdivacky  const RecordType *RT = E->getType()->getAs<RecordType>();
1928193326Sed  if (!RT)
1929193326Sed    return Owned(E);
1930198092Srdivacky
1931193326Sed  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1932193326Sed  if (RD->hasTrivialDestructor())
1933193326Sed    return Owned(E);
1934198092Srdivacky
1935198092Srdivacky  if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
1936198092Srdivacky    QualType Ty = CE->getCallee()->getType();
1937198092Srdivacky    if (const PointerType *PT = Ty->getAs<PointerType>())
1938198092Srdivacky      Ty = PT->getPointeeType();
1939198092Srdivacky
1940198092Srdivacky    const FunctionType *FTy = Ty->getAs<FunctionType>();
1941198092Srdivacky    if (FTy->getResultType()->isReferenceType())
1942198092Srdivacky      return Owned(E);
1943198092Srdivacky  }
1944198092Srdivacky  CXXTemporary *Temp = CXXTemporary::Create(Context,
1945193326Sed                                            RD->getDestructor(Context));
1946193326Sed  ExprTemporaries.push_back(Temp);
1947198092Srdivacky  if (CXXDestructorDecl *Destructor =
1948198092Srdivacky        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1949198092Srdivacky    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
1950193326Sed  // FIXME: Add the temporary to the temporaries vector.
1951193326Sed  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1952193326Sed}
1953193326Sed
1954198092SrdivackyExpr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
1955194613Sed                                              bool ShouldDestroyTemps) {
1956193576Sed  assert(SubExpr && "sub expression can't be null!");
1957198092Srdivacky
1958193576Sed  if (ExprTemporaries.empty())
1959193576Sed    return SubExpr;
1960198092Srdivacky
1961193576Sed  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1962198092Srdivacky                                           &ExprTemporaries[0],
1963193576Sed                                           ExprTemporaries.size(),
1964194613Sed                                           ShouldDestroyTemps);
1965193576Sed  ExprTemporaries.clear();
1966198092Srdivacky
1967193576Sed  return E;
1968193576Sed}
1969193576Sed
1970198092SrdivackySema::OwningExprResult
1971198092SrdivackySema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
1972198092Srdivacky                                   tok::TokenKind OpKind, TypeTy *&ObjectType) {
1973198092Srdivacky  // Since this might be a postfix expression, get rid of ParenListExprs.
1974198092Srdivacky  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1975198092Srdivacky
1976198092Srdivacky  Expr *BaseExpr = (Expr*)Base.get();
1977198092Srdivacky  assert(BaseExpr && "no record expansion");
1978198092Srdivacky
1979198092Srdivacky  QualType BaseType = BaseExpr->getType();
1980198092Srdivacky  if (BaseType->isDependentType()) {
1981198092Srdivacky    // FIXME: member of the current instantiation
1982198092Srdivacky    ObjectType = BaseType.getAsOpaquePtr();
1983198092Srdivacky    return move(Base);
1984198092Srdivacky  }
1985198092Srdivacky
1986198092Srdivacky  // C++ [over.match.oper]p8:
1987198092Srdivacky  //   [...] When operator->returns, the operator-> is applied  to the value
1988198092Srdivacky  //   returned, with the original second operand.
1989198092Srdivacky  if (OpKind == tok::arrow) {
1990198092Srdivacky    // The set of types we've considered so far.
1991198092Srdivacky    llvm::SmallPtrSet<CanQualType,8> CTypes;
1992198092Srdivacky    llvm::SmallVector<SourceLocation, 8> Locations;
1993198092Srdivacky    CTypes.insert(Context.getCanonicalType(BaseType));
1994198092Srdivacky
1995198092Srdivacky    while (BaseType->isRecordType()) {
1996198092Srdivacky      Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
1997198092Srdivacky      BaseExpr = (Expr*)Base.get();
1998198092Srdivacky      if (BaseExpr == NULL)
1999198092Srdivacky        return ExprError();
2000198092Srdivacky      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
2001198092Srdivacky        Locations.push_back(OpCall->getDirectCallee()->getLocation());
2002198092Srdivacky      BaseType = BaseExpr->getType();
2003198092Srdivacky      CanQualType CBaseType = Context.getCanonicalType(BaseType);
2004198092Srdivacky      if (!CTypes.insert(CBaseType)) {
2005198092Srdivacky        Diag(OpLoc, diag::err_operator_arrow_circular);
2006198092Srdivacky        for (unsigned i = 0; i < Locations.size(); i++)
2007198092Srdivacky          Diag(Locations[i], diag::note_declared_at);
2008198092Srdivacky        return ExprError();
2009198092Srdivacky      }
2010198092Srdivacky    }
2011198092Srdivacky  }
2012198092Srdivacky
2013198092Srdivacky  if (BaseType->isPointerType())
2014198092Srdivacky    BaseType = BaseType->getPointeeType();
2015198092Srdivacky
2016198092Srdivacky  // We could end up with various non-record types here, such as extended
2017198092Srdivacky  // vector types or Objective-C interfaces. Just return early and let
2018198092Srdivacky  // ActOnMemberReferenceExpr do the work.
2019198092Srdivacky  if (!BaseType->isRecordType()) {
2020198092Srdivacky    // C++ [basic.lookup.classref]p2:
2021198092Srdivacky    //   [...] If the type of the object expression is of pointer to scalar
2022198092Srdivacky    //   type, the unqualified-id is looked up in the context of the complete
2023198092Srdivacky    //   postfix-expression.
2024198092Srdivacky    ObjectType = 0;
2025198092Srdivacky    return move(Base);
2026198092Srdivacky  }
2027198092Srdivacky
2028198092Srdivacky  // C++ [basic.lookup.classref]p2:
2029198092Srdivacky  //   If the id-expression in a class member access (5.2.5) is an
2030198092Srdivacky  //   unqualified-id, and the type of the object expres- sion is of a class
2031198092Srdivacky  //   type C (or of pointer to a class type C), the unqualified-id is looked
2032198092Srdivacky  //   up in the scope of class C. [...]
2033198092Srdivacky  ObjectType = BaseType.getAsOpaquePtr();
2034198092Srdivacky  return move(Base);
2035198092Srdivacky}
2036198092Srdivacky
2037198092SrdivackySema::OwningExprResult
2038198092SrdivackySema::ActOnDestructorReferenceExpr(Scope *S, ExprArg Base,
2039198092Srdivacky                                   SourceLocation OpLoc,
2040198092Srdivacky                                   tok::TokenKind OpKind,
2041198092Srdivacky                                   SourceLocation ClassNameLoc,
2042198092Srdivacky                                   IdentifierInfo *ClassName,
2043198092Srdivacky                                   const CXXScopeSpec &SS,
2044198092Srdivacky                                   bool HasTrailingLParen) {
2045198092Srdivacky  if (SS.isInvalid())
2046198092Srdivacky    return ExprError();
2047198092Srdivacky
2048198092Srdivacky  QualType BaseType;
2049198092Srdivacky  if (isUnknownSpecialization(SS))
2050198092Srdivacky    BaseType = Context.getTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
2051198092Srdivacky                                       ClassName);
2052198092Srdivacky  else {
2053198092Srdivacky    TypeTy *BaseTy = getTypeName(*ClassName, ClassNameLoc, S, &SS);
2054198092Srdivacky    if (!BaseTy) {
2055198092Srdivacky      Diag(ClassNameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
2056198092Srdivacky        << ClassName;
2057198092Srdivacky      return ExprError();
2058198092Srdivacky    }
2059198092Srdivacky
2060198092Srdivacky    BaseType = GetTypeFromParser(BaseTy);
2061198092Srdivacky  }
2062198092Srdivacky
2063198092Srdivacky  CanQualType CanBaseType = Context.getCanonicalType(BaseType);
2064198092Srdivacky  DeclarationName DtorName =
2065198092Srdivacky    Context.DeclarationNames.getCXXDestructorName(CanBaseType);
2066198092Srdivacky
2067198092Srdivacky  OwningExprResult Result
2068198092Srdivacky    = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2069198092Srdivacky                               DtorName, DeclPtrTy(), &SS);
2070198092Srdivacky  if (Result.isInvalid() || HasTrailingLParen)
2071198092Srdivacky    return move(Result);
2072198092Srdivacky
2073198092Srdivacky  // The only way a reference to a destructor can be used is to
2074198092Srdivacky  // immediately call them. Since the next token is not a '(', produce a
2075198092Srdivacky  // diagnostic and build the call now.
2076198092Srdivacky  Expr *E = (Expr *)Result.get();
2077198092Srdivacky  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(E->getLocEnd());
2078198092Srdivacky  Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2079198092Srdivacky    << isa<CXXPseudoDestructorExpr>(E)
2080198092Srdivacky    << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2081198092Srdivacky
2082198092Srdivacky  return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2083198092Srdivacky                       MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
2084198092Srdivacky}
2085198092Srdivacky
2086198092SrdivackySema::OwningExprResult
2087198092SrdivackySema::ActOnOverloadedOperatorReferenceExpr(Scope *S, ExprArg Base,
2088198092Srdivacky                                           SourceLocation OpLoc,
2089198092Srdivacky                                           tok::TokenKind OpKind,
2090198092Srdivacky                                           SourceLocation ClassNameLoc,
2091198092Srdivacky                                           OverloadedOperatorKind OverOpKind,
2092198092Srdivacky                                           const CXXScopeSpec *SS) {
2093198092Srdivacky  if (SS && SS->isInvalid())
2094198092Srdivacky    return ExprError();
2095198092Srdivacky
2096198092Srdivacky  DeclarationName Name =
2097198092Srdivacky    Context.DeclarationNames.getCXXOperatorName(OverOpKind);
2098198092Srdivacky
2099198092Srdivacky  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2100198092Srdivacky                                  Name, DeclPtrTy(), SS);
2101198092Srdivacky}
2102198092Srdivacky
2103198092SrdivackySema::OwningExprResult
2104198092SrdivackySema::ActOnConversionOperatorReferenceExpr(Scope *S, ExprArg Base,
2105198092Srdivacky                                           SourceLocation OpLoc,
2106198092Srdivacky                                           tok::TokenKind OpKind,
2107198092Srdivacky                                           SourceLocation ClassNameLoc,
2108198092Srdivacky                                           TypeTy *Ty,
2109198092Srdivacky                                           const CXXScopeSpec *SS) {
2110198092Srdivacky  if (SS && SS->isInvalid())
2111198092Srdivacky    return ExprError();
2112198092Srdivacky
2113198092Srdivacky  //FIXME: Preserve type source info.
2114198092Srdivacky  QualType ConvType = GetTypeFromParser(Ty);
2115198092Srdivacky  CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
2116198092Srdivacky  DeclarationName ConvName =
2117198092Srdivacky    Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
2118198092Srdivacky
2119198092Srdivacky  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, ClassNameLoc,
2120198092Srdivacky                                  ConvName, DeclPtrTy(), SS);
2121198092Srdivacky}
2122198092Srdivacky
2123198092SrdivackyCXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2124198092Srdivacky                                                CXXMethodDecl *Method) {
2125198092Srdivacky  MemberExpr *ME =
2126198092Srdivacky      new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2127198092Srdivacky                               SourceLocation(), Method->getType());
2128198092Srdivacky  QualType ResultType;
2129198092Srdivacky  if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Method))
2130198092Srdivacky    ResultType = Conv->getConversionType().getNonReferenceType();
2131198092Srdivacky  else
2132198092Srdivacky    ResultType = Method->getResultType().getNonReferenceType();
2133198092Srdivacky
2134198092Srdivacky    CXXMemberCallExpr *CE =
2135198092Srdivacky      new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
2136198092Srdivacky                                      ResultType,
2137198092Srdivacky                                      SourceLocation());
2138198092Srdivacky  return CE;
2139198092Srdivacky}
2140198092Srdivacky
2141198092SrdivackySema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2142198092Srdivacky                                                  QualType Ty,
2143198092Srdivacky                                                  CastExpr::CastKind Kind,
2144198092Srdivacky                                                  CXXMethodDecl *Method,
2145198092Srdivacky                                                  ExprArg Arg) {
2146198092Srdivacky  Expr *From = Arg.takeAs<Expr>();
2147198092Srdivacky
2148198092Srdivacky  switch (Kind) {
2149198092Srdivacky  default: assert(0 && "Unhandled cast kind!");
2150198092Srdivacky  case CastExpr::CK_ConstructorConversion: {
2151198092Srdivacky    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2152198092Srdivacky
2153198092Srdivacky    if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2154198092Srdivacky                                MultiExprArg(*this, (void **)&From, 1),
2155198092Srdivacky                                CastLoc, ConstructorArgs))
2156198092Srdivacky      return ExprError();
2157198092Srdivacky
2158198092Srdivacky    return BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2159198092Srdivacky                                 move_arg(ConstructorArgs));
2160198092Srdivacky  }
2161198092Srdivacky
2162198092Srdivacky  case CastExpr::CK_UserDefinedConversion: {
2163198092Srdivacky    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2164198092Srdivacky
2165198092Srdivacky    // Cast to base if needed.
2166198092Srdivacky    if (PerformObjectArgumentInitialization(From, Method))
2167198092Srdivacky      return ExprError();
2168198092Srdivacky
2169198092Srdivacky    // Create an implicit call expr that calls it.
2170198092Srdivacky    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
2171198092Srdivacky    return Owned(CE);
2172198092Srdivacky  }
2173198092Srdivacky  }
2174198092Srdivacky}
2175198092Srdivacky
2176193326SedSema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2177193326Sed  Expr *FullExpr = Arg.takeAs<Expr>();
2178193576Sed  if (FullExpr)
2179198092Srdivacky    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
2180194613Sed                                                 /*ShouldDestroyTemps=*/true);
2181193326Sed
2182198092Srdivacky
2183193326Sed  return Owned(FullExpr);
2184193326Sed}
2185