SemaExprCXX.cpp revision ebc07d57be9e0722b4b9c66625e1fca43dcc2ee0
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/Parse/DeclSpec.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Basic/TargetInfo.h"
20#include "llvm/ADT/STLExtras.h"
21using namespace clang;
22
23/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
24/// name (e.g., operator void const *) as an expression. This is
25/// very similar to ActOnIdentifierExpr, except that instead of
26/// providing an identifier the parser provides the type of the
27/// conversion function.
28Sema::OwningExprResult
29Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
30                                     TypeTy *Ty, bool HasTrailingLParen,
31                                     const CXXScopeSpec &SS,
32                                     bool isAddressOfOperand) {
33  QualType ConvType = QualType::getFromOpaquePtr(Ty);
34  QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
35  DeclarationName ConvName
36    = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
37  return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
38                                  &SS, /*ForceRes*/false, isAddressOfOperand);
39}
40
41/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
42/// name (e.g., @c operator+ ) as an expression. This is very
43/// similar to ActOnIdentifierExpr, except that instead of providing
44/// an identifier the parser provides the kind of overloaded
45/// operator that was parsed.
46Sema::OwningExprResult
47Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
48                                     OverloadedOperatorKind Op,
49                                     bool HasTrailingLParen,
50                                     const CXXScopeSpec &SS,
51                                     bool isAddressOfOperand) {
52  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
53  return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
54                                  /*ForceRes*/false, isAddressOfOperand);
55}
56
57/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
58Action::ExprResult
59Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
60                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
61  NamespaceDecl *StdNs = GetStdNamespace();
62  if (!StdNs)
63    return Diag(OpLoc, diag::err_need_header_before_typeid);
64
65  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
66  Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
67  RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
68  if (!TypeInfoRecordDecl)
69    return Diag(OpLoc, diag::err_need_header_before_typeid);
70
71  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
72
73  return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
74                           SourceRange(OpLoc, RParenLoc));
75}
76
77/// ActOnCXXBoolLiteral - Parse {true,false} literals.
78Action::ExprResult
79Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
80  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
81         "Unknown C++ Boolean value!");
82  return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
83}
84
85/// ActOnCXXThrow - Parse throw expressions.
86Action::ExprResult
87Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
88  return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
89}
90
91Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
92  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
93  /// is a non-lvalue expression whose value is the address of the object for
94  /// which the function is called.
95
96  if (!isa<FunctionDecl>(CurContext)) {
97    Diag(ThisLoc, diag::err_invalid_this_use);
98    return ExprResult(true);
99  }
100
101  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
102    if (MD->isInstance())
103      return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
104
105  return Diag(ThisLoc, diag::err_invalid_this_use);
106}
107
108/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
109/// Can be interpreted either as function-style casting ("int(x)")
110/// or class type construction ("ClassType(x,y,z)")
111/// or creation of a value-initialized type ("int()").
112Action::ExprResult
113Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
114                                SourceLocation LParenLoc,
115                                ExprTy **ExprTys, unsigned NumExprs,
116                                SourceLocation *CommaLocs,
117                                SourceLocation RParenLoc) {
118  assert(TypeRep && "Missing type!");
119  QualType Ty = QualType::getFromOpaquePtr(TypeRep);
120  Expr **Exprs = (Expr**)ExprTys;
121  SourceLocation TyBeginLoc = TypeRange.getBegin();
122  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
123
124  // C++ [expr.type.conv]p1:
125  // If the expression list is a single expression, the type conversion
126  // expression is equivalent (in definedness, and if defined in meaning) to the
127  // corresponding cast expression.
128  //
129  if (NumExprs == 1) {
130    if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
131      return true;
132    return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
133                                     Exprs[0], RParenLoc);
134  }
135
136  if (const RecordType *RT = Ty->getAsRecordType()) {
137    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
138
139    if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
140      CXXConstructorDecl *Constructor
141        = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
142                                             TypeRange.getBegin(),
143                                             SourceRange(TypeRange.getBegin(),
144                                                         RParenLoc),
145                                             DeclarationName(),
146                                             IK_Direct);
147
148      if (!Constructor)
149        return true;
150
151      return new CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
152                                        Exprs, NumExprs, RParenLoc);
153    }
154
155    // Fall through to value-initialize an object of class type that
156    // doesn't have a user-declared default constructor.
157  }
158
159  // C++ [expr.type.conv]p1:
160  // If the expression list specifies more than a single value, the type shall
161  // be a class with a suitably declared constructor.
162  //
163  if (NumExprs > 1)
164    return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg)
165      << FullRange;
166
167  assert(NumExprs == 0 && "Expected 0 expressions");
168
169  // C++ [expr.type.conv]p2:
170  // The expression T(), where T is a simple-type-specifier for a non-array
171  // complete object type or the (possibly cv-qualified) void type, creates an
172  // rvalue of the specified type, which is value-initialized.
173  //
174  if (Ty->isArrayType())
175    return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange;
176  if (!Ty->isDependentType() && !Ty->isVoidType() &&
177      DiagnoseIncompleteType(TyBeginLoc, Ty,
178                             diag::err_invalid_incomplete_type_use, FullRange))
179    return true;
180
181  return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
182}
183
184
185/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
186/// @code new (memory) int[size][4] @endcode
187/// or
188/// @code ::new Foo(23, "hello") @endcode
189/// For the interpretation of this heap of arguments, consult the base version.
190Action::ExprResult
191Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
192                  SourceLocation PlacementLParen,
193                  ExprTy **PlacementArgs, unsigned NumPlaceArgs,
194                  SourceLocation PlacementRParen, bool ParenTypeId,
195                  Declarator &D, SourceLocation ConstructorLParen,
196                  ExprTy **ConstructorArgs, unsigned NumConsArgs,
197                  SourceLocation ConstructorRParen)
198{
199  // FIXME: Throughout this function, we have rather bad location information.
200  // Implementing Declarator::getSourceRange() would go a long way toward
201  // fixing that.
202
203  Expr *ArraySize = 0;
204  unsigned Skip = 0;
205  // If the specified type is an array, unwrap it and save the expression.
206  if (D.getNumTypeObjects() > 0 &&
207      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
208    DeclaratorChunk &Chunk = D.getTypeObject(0);
209    if (Chunk.Arr.hasStatic)
210      return Diag(Chunk.Loc, diag::err_static_illegal_in_new);
211    if (!Chunk.Arr.NumElts)
212      return Diag(Chunk.Loc, diag::err_array_new_needs_size);
213    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
214    Skip = 1;
215  }
216
217  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
218  if (D.getInvalidType())
219    return true;
220
221  if (CheckAllocatedType(AllocType, D))
222    return true;
223
224  QualType ResultType = Context.getPointerType(AllocType);
225
226  // That every array dimension except the first is constant was already
227  // checked by the type check above.
228
229  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
230  //   or enumeration type with a non-negative value."
231  if (ArraySize) {
232    QualType SizeType = ArraySize->getType();
233    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
234      return Diag(ArraySize->getSourceRange().getBegin(),
235                  diag::err_array_size_not_integral)
236        << SizeType << ArraySize->getSourceRange();
237    // Let's see if this is a constant < 0. If so, we reject it out of hand.
238    // We don't care about special rules, so we tell the machinery it's not
239    // evaluated - it gives us a result in more cases.
240    llvm::APSInt Value;
241    if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
242      if (Value < llvm::APSInt(
243                      llvm::APInt::getNullValue(Value.getBitWidth()), false))
244        return Diag(ArraySize->getSourceRange().getBegin(),
245                    diag::err_typecheck_negative_array_size)
246          << ArraySize->getSourceRange();
247    }
248  }
249
250  FunctionDecl *OperatorNew = 0;
251  FunctionDecl *OperatorDelete = 0;
252  Expr **PlaceArgs = (Expr**)PlacementArgs;
253  if (FindAllocationFunctions(StartLoc, UseGlobal, AllocType, ArraySize,
254                              PlaceArgs, NumPlaceArgs, OperatorNew,
255                              OperatorDelete))
256    return true;
257
258  bool Init = ConstructorLParen.isValid();
259  // --- Choosing a constructor ---
260  // C++ 5.3.4p15
261  // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
262  //   the object is not initialized. If the object, or any part of it, is
263  //   const-qualified, it's an error.
264  // 2) If T is a POD and there's an empty initializer, the object is value-
265  //   initialized.
266  // 3) If T is a POD and there's one initializer argument, the object is copy-
267  //   constructed.
268  // 4) If T is a POD and there's more initializer arguments, it's an error.
269  // 5) If T is not a POD, the initializer arguments are used as constructor
270  //   arguments.
271  //
272  // Or by the C++0x formulation:
273  // 1) If there's no initializer, the object is default-initialized according
274  //    to C++0x rules.
275  // 2) Otherwise, the object is direct-initialized.
276  CXXConstructorDecl *Constructor = 0;
277  Expr **ConsArgs = (Expr**)ConstructorArgs;
278  if (const RecordType *RT = AllocType->getAsRecordType()) {
279    // FIXME: This is incorrect for when there is an empty initializer and
280    // no user-defined constructor. Must zero-initialize, not default-construct.
281    Constructor = PerformInitializationByConstructor(
282                      AllocType, ConsArgs, NumConsArgs,
283                      D.getDeclSpec().getSourceRange().getBegin(),
284                      SourceRange(D.getDeclSpec().getSourceRange().getBegin(),
285                                  ConstructorRParen),
286                      RT->getDecl()->getDeclName(),
287                      NumConsArgs != 0 ? IK_Direct : IK_Default);
288    if (!Constructor)
289      return true;
290  } else {
291    if (!Init) {
292      // FIXME: Check that no subpart is const.
293      if (AllocType.isConstQualified()) {
294        Diag(StartLoc, diag::err_new_uninitialized_const)
295          << D.getSourceRange();
296        return true;
297      }
298    } else if (NumConsArgs == 0) {
299      // Object is value-initialized. Do nothing.
300    } else if (NumConsArgs == 1) {
301      // Object is direct-initialized.
302      // FIXME: WHAT DeclarationName do we pass in here?
303      if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
304                                DeclarationName() /*AllocType.getAsString()*/,
305                                /*DirectInit=*/true))
306        return true;
307    } else {
308      Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg)
309        << SourceRange(ConstructorLParen, ConstructorRParen);
310    }
311  }
312
313  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
314
315  return new CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs,
316                        ParenTypeId, ArraySize, Constructor, Init,
317                        ConsArgs, NumConsArgs, OperatorDelete, ResultType,
318                        StartLoc, Init ? ConstructorRParen : SourceLocation());
319}
320
321/// CheckAllocatedType - Checks that a type is suitable as the allocated type
322/// in a new-expression.
323/// dimension off and stores the size expression in ArraySize.
324bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
325{
326  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
327  //   abstract class type or array thereof.
328  // FIXME: We don't have abstract types yet.
329  // FIXME: Under C++ semantics, an incomplete object type is still an object
330  // type. This code assumes the C semantics, where it's not.
331  if (!AllocType->isObjectType()) {
332    unsigned type; // For the select in the message.
333    if (AllocType->isFunctionType()) {
334      type = 0;
335    } else if(AllocType->isIncompleteType()) {
336      type = 1;
337    } else {
338      assert(AllocType->isReferenceType() && "What else could it be?");
339      type = 2;
340    }
341    SourceRange TyR = D.getDeclSpec().getSourceRange();
342    // FIXME: This is very much a guess and won't work for, e.g., pointers.
343    if (D.getNumTypeObjects() > 0)
344      TyR.setEnd(D.getTypeObject(0).Loc);
345    Diag(TyR.getBegin(), diag::err_bad_new_type)
346      << AllocType.getAsString() << type << TyR;
347    return true;
348  }
349
350  // Every dimension shall be of constant size.
351  unsigned i = 1;
352  while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
353    if (!Array->isConstantArrayType()) {
354      Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
355        << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
356      return true;
357    }
358    AllocType = Array->getElementType();
359    ++i;
360  }
361
362  return false;
363}
364
365/// FindAllocationFunctions - Finds the overloads of operator new and delete
366/// that are appropriate for the allocation.
367bool Sema::FindAllocationFunctions(SourceLocation StartLoc, bool UseGlobal,
368                                   QualType AllocType, bool IsArray,
369                                   Expr **PlaceArgs, unsigned NumPlaceArgs,
370                                   FunctionDecl *&OperatorNew,
371                                   FunctionDecl *&OperatorDelete)
372{
373  // --- Choosing an allocation function ---
374  // C++ 5.3.4p8 - 14 & 18
375  // 1) If UseGlobal is true, only look in the global scope. Else, also look
376  //   in the scope of the allocated class.
377  // 2) If an array size is given, look for operator new[], else look for
378  //   operator new.
379  // 3) The first argument is always size_t. Append the arguments from the
380  //   placement form.
381  // FIXME: Also find the appropriate delete operator.
382
383  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
384  // We don't care about the actual value of this argument.
385  // FIXME: Should the Sema create the expression and embed it in the syntax
386  // tree? Or should the consumer just recalculate the value?
387  AllocArgs[0] = new IntegerLiteral(llvm::APInt::getNullValue(
388                                        Context.Target.getPointerWidth(0)),
389                                    Context.getSizeType(),
390                                    SourceLocation());
391  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
392
393  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
394                                        IsArray ? OO_Array_New : OO_New);
395  if (AllocType->isRecordType() && !UseGlobal) {
396    CXXRecordDecl *Record = cast<CXXRecordType>(AllocType->getAsRecordType())
397                                ->getDecl();
398    // FIXME: We fail to find inherited overloads.
399    if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
400                          AllocArgs.size(), Record, /*AllowMissing=*/true,
401                          OperatorNew))
402      return true;
403  }
404  if (!OperatorNew) {
405    // Didn't find a member overload. Look for a global one.
406    DeclareGlobalNewDelete();
407    DeclContext *TUDecl = Context.getTranslationUnitDecl();
408    if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
409                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
410                          OperatorNew))
411      return true;
412  }
413
414  // FIXME: This is leaked on error. But so much is currently in Sema that it's
415  // easier to clean it in one go.
416  AllocArgs[0]->Destroy(Context);
417  return false;
418}
419
420/// FindAllocationOverload - Find an fitting overload for the allocation
421/// function in the specified scope.
422bool Sema::FindAllocationOverload(SourceLocation StartLoc, DeclarationName Name,
423                                  Expr** Args, unsigned NumArgs,
424                                  DeclContext *Ctx, bool AllowMissing,
425                                  FunctionDecl *&Operator)
426{
427  DeclContext::lookup_iterator Alloc, AllocEnd;
428  llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
429  if (Alloc == AllocEnd) {
430    if (AllowMissing)
431      return false;
432    // FIXME: Bad location information.
433    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
434      << Name << 0;
435  }
436
437  OverloadCandidateSet Candidates;
438  for (; Alloc != AllocEnd; ++Alloc) {
439    // Even member operator new/delete are implicitly treated as
440    // static, so don't use AddMemberCandidate.
441    if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
442      AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
443                           /*SuppressUserConversions=*/false);
444  }
445
446  // Do the resolution.
447  OverloadCandidateSet::iterator Best;
448  switch(BestViableFunction(Candidates, Best)) {
449  case OR_Success: {
450    // Got one!
451    FunctionDecl *FnDecl = Best->Function;
452    // The first argument is size_t, and the first parameter must be size_t,
453    // too. This is checked on declaration and can be assumed. (It can't be
454    // asserted on, though, since invalid decls are left in there.)
455    for (unsigned i = 1; i < NumArgs; ++i) {
456      // FIXME: Passing word to diagnostic.
457      if (PerformCopyInitialization(Args[i-1],
458                                    FnDecl->getParamDecl(i)->getType(),
459                                    "passing"))
460        return true;
461    }
462    Operator = FnDecl;
463    return false;
464  }
465
466  case OR_No_Viable_Function:
467    if (AllowMissing)
468      return false;
469    // FIXME: Bad location information.
470    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
471      << Name << (unsigned)Candidates.size();
472    PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
473    return true;
474
475  case OR_Ambiguous:
476    // FIXME: Bad location information.
477    Diag(StartLoc, diag::err_ovl_ambiguous_call)
478      << Name;
479    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
480    return true;
481  }
482  assert(false && "Unreachable, bad result from BestViableFunction");
483  return true;
484}
485
486
487/// DeclareGlobalNewDelete - Declare the global forms of operator new and
488/// delete. These are:
489/// @code
490///   void* operator new(std::size_t) throw(std::bad_alloc);
491///   void* operator new[](std::size_t) throw(std::bad_alloc);
492///   void operator delete(void *) throw();
493///   void operator delete[](void *) throw();
494/// @endcode
495/// Note that the placement and nothrow forms of new are *not* implicitly
496/// declared. Their use requires including \<new\>.
497void Sema::DeclareGlobalNewDelete()
498{
499  if (GlobalNewDeleteDeclared)
500    return;
501  GlobalNewDeleteDeclared = true;
502
503  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
504  QualType SizeT = Context.getSizeType();
505
506  // FIXME: Exception specifications are not added.
507  DeclareGlobalAllocationFunction(
508      Context.DeclarationNames.getCXXOperatorName(OO_New),
509      VoidPtr, SizeT);
510  DeclareGlobalAllocationFunction(
511      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
512      VoidPtr, SizeT);
513  DeclareGlobalAllocationFunction(
514      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
515      Context.VoidTy, VoidPtr);
516  DeclareGlobalAllocationFunction(
517      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
518      Context.VoidTy, VoidPtr);
519}
520
521/// DeclareGlobalAllocationFunction - Declares a single implicit global
522/// allocation function if it doesn't already exist.
523void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
524                                           QualType Return, QualType Argument)
525{
526  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
527
528  // Check if this function is already declared.
529  {
530    DeclContext::lookup_iterator Alloc, AllocEnd;
531    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
532         Alloc != AllocEnd; ++Alloc) {
533      // FIXME: Do we need to check for default arguments here?
534      FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
535      if (Func->getNumParams() == 1 &&
536          Context.getCanonicalType(Func->getParamDecl(0)->getType()) == Argument)
537        return;
538    }
539  }
540
541  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
542  FunctionDecl *Alloc =
543    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
544                         FnType, FunctionDecl::None, false,
545                         SourceLocation());
546  Alloc->setImplicit();
547  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
548                                           0, Argument, VarDecl::None, 0);
549  Alloc->setParams(Context, &Param, 1);
550
551  // FIXME: Also add this declaration to the IdentifierResolver, but
552  // make sure it is at the end of the chain to coincide with the
553  // global scope.
554  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
555}
556
557/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
558/// @code ::delete ptr; @endcode
559/// or
560/// @code delete [] ptr; @endcode
561Action::ExprResult
562Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
563                     bool ArrayForm, ExprTy *Operand)
564{
565  // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
566  //   having a single conversion function to a pointer type. The result has
567  //   type void."
568  // DR599 amends "pointer type" to "pointer to object type" in both cases.
569
570  Expr *Ex = (Expr *)Operand;
571  QualType Type = Ex->getType();
572
573  if (Type->isRecordType()) {
574    // FIXME: Find that one conversion function and amend the type.
575  }
576
577  if (!Type->isPointerType()) {
578    Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange();
579    return true;
580  }
581
582  QualType Pointee = Type->getAsPointerType()->getPointeeType();
583  if (!Pointee->isVoidType() &&
584      DiagnoseIncompleteType(StartLoc, Pointee, diag::warn_delete_incomplete,
585                             Ex->getSourceRange()))
586    return true;
587  else if (!Pointee->isObjectType()) {
588    Diag(StartLoc, diag::err_delete_operand)
589      << Type << Ex->getSourceRange();
590    return true;
591  }
592
593  // FIXME: Look up the correct operator delete overload and pass a pointer
594  // along.
595  // FIXME: Check access and ambiguity of operator delete and destructor.
596
597  return new CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, Ex,
598                           StartLoc);
599}
600
601
602/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
603/// C++ if/switch/while/for statement.
604/// e.g: "if (int x = f()) {...}"
605Action::ExprResult
606Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
607                                       Declarator &D,
608                                       SourceLocation EqualLoc,
609                                       ExprTy *AssignExprVal) {
610  assert(AssignExprVal && "Null assignment expression");
611
612  // C++ 6.4p2:
613  // The declarator shall not specify a function or an array.
614  // The type-specifier-seq shall not contain typedef and shall not declare a
615  // new class or enumeration.
616
617  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
618         "Parser allowed 'typedef' as storage class of condition decl.");
619
620  QualType Ty = GetTypeForDeclarator(D, S);
621
622  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
623    // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
624    // would be created and CXXConditionDeclExpr wants a VarDecl.
625    return Diag(StartLoc, diag::err_invalid_use_of_function_type)
626      << SourceRange(StartLoc, EqualLoc);
627  } else if (Ty->isArrayType()) { // ...or an array.
628    Diag(StartLoc, diag::err_invalid_use_of_array_type)
629      << SourceRange(StartLoc, EqualLoc);
630  } else if (const RecordType *RT = Ty->getAsRecordType()) {
631    RecordDecl *RD = RT->getDecl();
632    // The type-specifier-seq shall not declare a new class...
633    if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
634      Diag(RD->getLocation(), diag::err_type_defined_in_condition);
635  } else if (const EnumType *ET = Ty->getAsEnumType()) {
636    EnumDecl *ED = ET->getDecl();
637    // ...or enumeration.
638    if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
639      Diag(ED->getLocation(), diag::err_type_defined_in_condition);
640  }
641
642  DeclTy *Dcl = ActOnDeclarator(S, D, 0);
643  if (!Dcl)
644    return true;
645  AddInitializerToDecl(Dcl, ExprArg(*this, AssignExprVal));
646
647  // Mark this variable as one that is declared within a conditional.
648  if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl))
649    VD->setDeclaredInCondition(true);
650
651  return new CXXConditionDeclExpr(StartLoc, EqualLoc,
652                                       cast<VarDecl>(static_cast<Decl *>(Dcl)));
653}
654
655/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
656bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
657  // C++ 6.4p4:
658  // The value of a condition that is an initialized declaration in a statement
659  // other than a switch statement is the value of the declared variable
660  // implicitly converted to type bool. If that conversion is ill-formed, the
661  // program is ill-formed.
662  // The value of a condition that is an expression is the value of the
663  // expression, implicitly converted to bool.
664  //
665  return PerformContextuallyConvertToBool(CondExpr);
666}
667
668/// Helper function to determine whether this is the (deprecated) C++
669/// conversion from a string literal to a pointer to non-const char or
670/// non-const wchar_t (for narrow and wide string literals,
671/// respectively).
672bool
673Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
674  // Look inside the implicit cast, if it exists.
675  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
676    From = Cast->getSubExpr();
677
678  // A string literal (2.13.4) that is not a wide string literal can
679  // be converted to an rvalue of type "pointer to char"; a wide
680  // string literal can be converted to an rvalue of type "pointer
681  // to wchar_t" (C++ 4.2p2).
682  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
683    if (const PointerType *ToPtrType = ToType->getAsPointerType())
684      if (const BuiltinType *ToPointeeType
685          = ToPtrType->getPointeeType()->getAsBuiltinType()) {
686        // This conversion is considered only when there is an
687        // explicit appropriate pointer target type (C++ 4.2p2).
688        if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
689            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
690             (!StrLit->isWide() &&
691              (ToPointeeType->getKind() == BuiltinType::Char_U ||
692               ToPointeeType->getKind() == BuiltinType::Char_S))))
693          return true;
694      }
695
696  return false;
697}
698
699/// PerformImplicitConversion - Perform an implicit conversion of the
700/// expression From to the type ToType. Returns true if there was an
701/// error, false otherwise. The expression From is replaced with the
702/// converted expression. Flavor is the kind of conversion we're
703/// performing, used in the error message. If @p AllowExplicit,
704/// explicit user-defined conversions are permitted.
705bool
706Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
707                                const char *Flavor, bool AllowExplicit)
708{
709  ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType, false,
710                                                         AllowExplicit);
711  return PerformImplicitConversion(From, ToType, ICS, Flavor);
712}
713
714/// PerformImplicitConversion - Perform an implicit conversion of the
715/// expression From to the type ToType using the pre-computed implicit
716/// conversion sequence ICS. Returns true if there was an error, false
717/// otherwise. The expression From is replaced with the converted
718/// expression. Flavor is the kind of conversion we're performing,
719/// used in the error message.
720bool
721Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
722                                const ImplicitConversionSequence &ICS,
723                                const char* Flavor) {
724  switch (ICS.ConversionKind) {
725  case ImplicitConversionSequence::StandardConversion:
726    if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
727      return true;
728    break;
729
730  case ImplicitConversionSequence::UserDefinedConversion:
731    // FIXME: This is, of course, wrong. We'll need to actually call
732    // the constructor or conversion operator, and then cope with the
733    // standard conversions.
734    ImpCastExprToType(From, ToType.getNonReferenceType(),
735                      ToType->isReferenceType());
736    return false;
737
738  case ImplicitConversionSequence::EllipsisConversion:
739    assert(false && "Cannot perform an ellipsis conversion");
740    return false;
741
742  case ImplicitConversionSequence::BadConversion:
743    return true;
744  }
745
746  // Everything went well.
747  return false;
748}
749
750/// PerformImplicitConversion - Perform an implicit conversion of the
751/// expression From to the type ToType by following the standard
752/// conversion sequence SCS. Returns true if there was an error, false
753/// otherwise. The expression From is replaced with the converted
754/// expression. Flavor is the context in which we're performing this
755/// conversion, for use in error messages.
756bool
757Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
758                                const StandardConversionSequence& SCS,
759                                const char *Flavor) {
760  // Overall FIXME: we are recomputing too many types here and doing
761  // far too much extra work. What this means is that we need to keep
762  // track of more information that is computed when we try the
763  // implicit conversion initially, so that we don't need to recompute
764  // anything here.
765  QualType FromType = From->getType();
766
767  if (SCS.CopyConstructor) {
768    // FIXME: Create a temporary object by calling the copy
769    // constructor.
770    ImpCastExprToType(From, ToType.getNonReferenceType(),
771                      ToType->isReferenceType());
772    return false;
773  }
774
775  // Perform the first implicit conversion.
776  switch (SCS.First) {
777  case ICK_Identity:
778  case ICK_Lvalue_To_Rvalue:
779    // Nothing to do.
780    break;
781
782  case ICK_Array_To_Pointer:
783    if (FromType->isOverloadType()) {
784      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
785      if (!Fn)
786        return true;
787
788      FixOverloadedFunctionReference(From, Fn);
789      FromType = From->getType();
790    } else {
791      FromType = Context.getArrayDecayedType(FromType);
792    }
793    ImpCastExprToType(From, FromType);
794    break;
795
796  case ICK_Function_To_Pointer:
797    FromType = Context.getPointerType(FromType);
798    ImpCastExprToType(From, FromType);
799    break;
800
801  default:
802    assert(false && "Improper first standard conversion");
803    break;
804  }
805
806  // Perform the second implicit conversion
807  switch (SCS.Second) {
808  case ICK_Identity:
809    // Nothing to do.
810    break;
811
812  case ICK_Integral_Promotion:
813  case ICK_Floating_Promotion:
814  case ICK_Integral_Conversion:
815  case ICK_Floating_Conversion:
816  case ICK_Floating_Integral:
817    FromType = ToType.getUnqualifiedType();
818    ImpCastExprToType(From, FromType);
819    break;
820
821  case ICK_Pointer_Conversion:
822    if (SCS.IncompatibleObjC) {
823      // Diagnose incompatible Objective-C conversions
824      Diag(From->getSourceRange().getBegin(),
825           diag::ext_typecheck_convert_incompatible_pointer)
826        << From->getType() << ToType << Flavor
827        << From->getSourceRange();
828    }
829
830    if (CheckPointerConversion(From, ToType))
831      return true;
832    ImpCastExprToType(From, ToType);
833    break;
834
835  case ICK_Pointer_Member:
836    if (CheckMemberPointerConversion(From, ToType))
837      return true;
838    ImpCastExprToType(From, ToType);
839    break;
840
841  case ICK_Boolean_Conversion:
842    FromType = Context.BoolTy;
843    ImpCastExprToType(From, FromType);
844    break;
845
846  default:
847    assert(false && "Improper second standard conversion");
848    break;
849  }
850
851  switch (SCS.Third) {
852  case ICK_Identity:
853    // Nothing to do.
854    break;
855
856  case ICK_Qualification:
857    ImpCastExprToType(From, ToType.getNonReferenceType(),
858                      ToType->isReferenceType());
859    break;
860
861  default:
862    assert(false && "Improper second standard conversion");
863    break;
864  }
865
866  return false;
867}
868
869Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
870                                                 SourceLocation KWLoc,
871                                                 SourceLocation LParen,
872                                                 TypeTy *Ty,
873                                                 SourceLocation RParen) {
874  // FIXME: Some of the type traits have requirements. Interestingly, only the
875  // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
876  // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
877  // type is indeed a POD.
878
879  // There is no point in eagerly computing the value. The traits are designed
880  // to be used from type trait templates, so Ty will be a template parameter
881  // 99% of the time.
882  return Owned(new UnaryTypeTraitExpr(KWLoc, OTT,
883                                      QualType::getFromOpaquePtr(Ty),
884                                      RParen, Context.BoolTy));
885}
886