SemaExprCXX.cpp revision dd7031f9abb330acaca44755b499988cba487f00
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/TypeLoc.h"
21#include "clang/Basic/PartialDiagnostic.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Template.h"
26#include "llvm/ADT/STLExtras.h"
27using namespace clang;
28
29Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30                                        IdentifierInfo &II,
31                                        SourceLocation NameLoc,
32                                        Scope *S, CXXScopeSpec &SS,
33                                        TypeTy *ObjectTypePtr,
34                                        bool EnteringContext) {
35  // Determine where to perform name lookup.
36
37  // FIXME: This area of the standard is very messy, and the current
38  // wording is rather unclear about which scopes we search for the
39  // destructor name; see core issues 399 and 555. Issue 399 in
40  // particular shows where the current description of destructor name
41  // lookup is completely out of line with existing practice, e.g.,
42  // this appears to be ill-formed:
43  //
44  //   namespace N {
45  //     template <typename T> struct S {
46  //       ~S();
47  //     };
48  //   }
49  //
50  //   void f(N::S<int>* s) {
51  //     s->N::S<int>::~S();
52  //   }
53  //
54  // See also PR6358 and PR6359.
55  QualType SearchType;
56  DeclContext *LookupCtx = 0;
57  bool isDependent = false;
58  bool LookInScope = false;
59
60  // If we have an object type, it's because we are in a
61  // pseudo-destructor-expression or a member access expression, and
62  // we know what type we're looking for.
63  if (ObjectTypePtr)
64    SearchType = GetTypeFromParser(ObjectTypePtr);
65
66  if (SS.isSet()) {
67    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68
69    bool AlreadySearched = false;
70    bool LookAtPrefix = true;
71    if (!getLangOptions().CPlusPlus0x) {
72      // C++ [basic.lookup.qual]p6:
73      //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74      //   the type-names are looked up as types in the scope designated by the
75      //   nested-name-specifier. In a qualified-id of the form:
76      //
77      //     ::[opt] nested-name-specifier  ̃ class-name
78      //
79      //   where the nested-name-specifier designates a namespace scope, and in
80      //   a qualified-id of the form:
81      //
82      //     ::opt nested-name-specifier class-name ::  ̃ class-name
83      //
84      //   the class-names are looked up as types in the scope designated by
85      //   the nested-name-specifier.
86      //
87      // Here, we check the first case (completely) and determine whether the
88      // code below is permitted to look at the prefix of the
89      // nested-name-specifier (as we do in C++0x).
90      DeclContext *DC = computeDeclContext(SS, EnteringContext);
91      if (DC && DC->isFileContext()) {
92        AlreadySearched = true;
93        LookupCtx = DC;
94        isDependent = false;
95      } else if (DC && isa<CXXRecordDecl>(DC))
96        LookAtPrefix = false;
97    }
98
99    // C++0x [basic.lookup.qual]p6:
100    //   If a pseudo-destructor-name (5.2.4) contains a
101    //   nested-name-specifier, the type-names are looked up as types
102    //   in the scope designated by the nested-name-specifier. Similarly, in
103    //   a qualified-id of the form:
104    //
105    //     :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106    //
107    //   the second class-name is looked up in the same scope as the first.
108    //
109    // To implement this, we look at the prefix of the
110    // nested-name-specifier we were given, and determine the lookup
111    // context from that.
112    //
113    // We also fold in the second case from the C++03 rules quoted further
114    // above.
115    NestedNameSpecifier *Prefix = 0;
116    if (AlreadySearched) {
117      // Nothing left to do.
118    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119      CXXScopeSpec PrefixSS;
120      PrefixSS.setScopeRep(Prefix);
121      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122      isDependent = isDependentScopeSpecifier(PrefixSS);
123    } else if (getLangOptions().CPlusPlus0x &&
124               (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125      if (!LookupCtx->isTranslationUnit())
126        LookupCtx = LookupCtx->getParent();
127      isDependent = LookupCtx && LookupCtx->isDependentContext();
128    } else if (ObjectTypePtr) {
129      LookupCtx = computeDeclContext(SearchType);
130      isDependent = SearchType->isDependentType();
131    } else {
132      LookupCtx = computeDeclContext(SS, EnteringContext);
133      isDependent = LookupCtx && LookupCtx->isDependentContext();
134    }
135
136    LookInScope = false;
137  } else if (ObjectTypePtr) {
138    // C++ [basic.lookup.classref]p3:
139    //   If the unqualified-id is ~type-name, the type-name is looked up
140    //   in the context of the entire postfix-expression. If the type T
141    //   of the object expression is of a class type C, the type-name is
142    //   also looked up in the scope of class C. At least one of the
143    //   lookups shall find a name that refers to (possibly
144    //   cv-qualified) T.
145    LookupCtx = computeDeclContext(SearchType);
146    isDependent = SearchType->isDependentType();
147    assert((isDependent || !SearchType->isIncompleteType()) &&
148           "Caller should have completed object type");
149
150    LookInScope = true;
151  } else {
152    // Perform lookup into the current scope (only).
153    LookInScope = true;
154  }
155
156  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157  for (unsigned Step = 0; Step != 2; ++Step) {
158    // Look for the name first in the computed lookup context (if we
159    // have one) and, if that fails to find a match, in the sope (if
160    // we're allowed to look there).
161    Found.clear();
162    if (Step == 0 && LookupCtx)
163      LookupQualifiedName(Found, LookupCtx);
164    else if (Step == 1 && LookInScope && S)
165      LookupName(Found, S);
166    else
167      continue;
168
169    // FIXME: Should we be suppressing ambiguities here?
170    if (Found.isAmbiguous())
171      return 0;
172
173    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174      QualType T = Context.getTypeDeclType(Type);
175
176      if (SearchType.isNull() || SearchType->isDependentType() ||
177          Context.hasSameUnqualifiedType(T, SearchType)) {
178        // We found our type!
179
180        return T.getAsOpaquePtr();
181      }
182    }
183
184    // If the name that we found is a class template name, and it is
185    // the same name as the template name in the last part of the
186    // nested-name-specifier (if present) or the object type, then
187    // this is the destructor for that class.
188    // FIXME: This is a workaround until we get real drafting for core
189    // issue 399, for which there isn't even an obvious direction.
190    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191      QualType MemberOfType;
192      if (SS.isSet()) {
193        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194          // Figure out the type of the context, if it has one.
195          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196            MemberOfType = Context.getTypeDeclType(Record);
197        }
198      }
199      if (MemberOfType.isNull())
200        MemberOfType = SearchType;
201
202      if (MemberOfType.isNull())
203        continue;
204
205      // We're referring into a class template specialization. If the
206      // class template we found is the same as the template being
207      // specialized, we found what we are looking for.
208      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209        if (ClassTemplateSpecializationDecl *Spec
210              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212                Template->getCanonicalDecl())
213            return MemberOfType.getAsOpaquePtr();
214        }
215
216        continue;
217      }
218
219      // We're referring to an unresolved class template
220      // specialization. Determine whether we class template we found
221      // is the same as the template being specialized or, if we don't
222      // know which template is being specialized, that it at least
223      // has the same name.
224      if (const TemplateSpecializationType *SpecType
225            = MemberOfType->getAs<TemplateSpecializationType>()) {
226        TemplateName SpecName = SpecType->getTemplateName();
227
228        // The class template we found is the same template being
229        // specialized.
230        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232            return MemberOfType.getAsOpaquePtr();
233
234          continue;
235        }
236
237        // The class template we found has the same name as the
238        // (dependent) template name being specialized.
239        if (DependentTemplateName *DepTemplate
240                                    = SpecName.getAsDependentTemplateName()) {
241          if (DepTemplate->isIdentifier() &&
242              DepTemplate->getIdentifier() == Template->getIdentifier())
243            return MemberOfType.getAsOpaquePtr();
244
245          continue;
246        }
247      }
248    }
249  }
250
251  if (isDependent) {
252    // We didn't find our type, but that's okay: it's dependent
253    // anyway.
254    NestedNameSpecifier *NNS = 0;
255    SourceRange Range;
256    if (SS.isSet()) {
257      NNS = (NestedNameSpecifier *)SS.getScopeRep();
258      Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259    } else {
260      NNS = NestedNameSpecifier::Create(Context, &II);
261      Range = SourceRange(NameLoc);
262    }
263
264    return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
265                             Range, NameLoc).getAsOpaquePtr();
266  }
267
268  if (ObjectTypePtr)
269    Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
270      << &II;
271  else
272    Diag(NameLoc, diag::err_destructor_class_name);
273
274  return 0;
275}
276
277/// \brief Build a C++ typeid expression with a type operand.
278Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
279                                            SourceLocation TypeidLoc,
280                                            TypeSourceInfo *Operand,
281                                            SourceLocation RParenLoc) {
282  // C++ [expr.typeid]p4:
283  //   The top-level cv-qualifiers of the lvalue expression or the type-id
284  //   that is the operand of typeid are always ignored.
285  //   If the type of the type-id is a class type or a reference to a class
286  //   type, the class shall be completely-defined.
287  Qualifiers Quals;
288  QualType T
289    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
290                                      Quals);
291  if (T->getAs<RecordType>() &&
292      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
293    return ExprError();
294
295  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
296                                           Operand,
297                                           SourceRange(TypeidLoc, RParenLoc)));
298}
299
300/// \brief Build a C++ typeid expression with an expression operand.
301Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
302                                            SourceLocation TypeidLoc,
303                                            ExprArg Operand,
304                                            SourceLocation RParenLoc) {
305  bool isUnevaluatedOperand = true;
306  Expr *E = static_cast<Expr *>(Operand.get());
307  if (E && !E->isTypeDependent()) {
308    QualType T = E->getType();
309    if (const RecordType *RecordT = T->getAs<RecordType>()) {
310      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
311      // C++ [expr.typeid]p3:
312      //   [...] If the type of the expression is a class type, the class
313      //   shall be completely-defined.
314      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
315        return ExprError();
316
317      // C++ [expr.typeid]p3:
318      //   When typeid is applied to an expression other than an lvalue of a
319      //   polymorphic class type [...] [the] expression is an unevaluated
320      //   operand. [...]
321      if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) {
322        isUnevaluatedOperand = false;
323
324        // We require a vtable to query the type at run time.
325        MarkVTableUsed(TypeidLoc, RecordD);
326      }
327    }
328
329    // C++ [expr.typeid]p4:
330    //   [...] If the type of the type-id is a reference to a possibly
331    //   cv-qualified type, the result of the typeid expression refers to a
332    //   std::type_info object representing the cv-unqualified referenced
333    //   type.
334    Qualifiers Quals;
335    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
336    if (!Context.hasSameType(T, UnqualT)) {
337      T = UnqualT;
338      ImpCastExprToType(E, UnqualT, CastExpr::CK_NoOp, E->isLvalue(Context));
339      Operand.release();
340      Operand = Owned(E);
341    }
342  }
343
344  // If this is an unevaluated operand, clear out the set of
345  // declaration references we have been computing and eliminate any
346  // temporaries introduced in its computation.
347  if (isUnevaluatedOperand)
348    ExprEvalContexts.back().Context = Unevaluated;
349
350  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
351                                           Operand.takeAs<Expr>(),
352                                           SourceRange(TypeidLoc, RParenLoc)));
353}
354
355/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
356Action::OwningExprResult
357Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
358                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
359  // Find the std::type_info type.
360  if (!StdNamespace)
361    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
362
363  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
364  LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
365  LookupQualifiedName(R, StdNamespace);
366  RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
367  if (!TypeInfoRecordDecl)
368    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
369
370  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
371
372  if (isType) {
373    // The operand is a type; handle it as such.
374    TypeSourceInfo *TInfo = 0;
375    QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
376    if (T.isNull())
377      return ExprError();
378
379    if (!TInfo)
380      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
381
382    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
383  }
384
385  // The operand is an expression.
386  return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
387}
388
389/// ActOnCXXBoolLiteral - Parse {true,false} literals.
390Action::OwningExprResult
391Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
392  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
393         "Unknown C++ Boolean value!");
394  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
395                                                Context.BoolTy, OpLoc));
396}
397
398/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
399Action::OwningExprResult
400Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
401  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
402}
403
404/// ActOnCXXThrow - Parse throw expressions.
405Action::OwningExprResult
406Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
407  Expr *Ex = E.takeAs<Expr>();
408  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
409    return ExprError();
410  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
411}
412
413/// CheckCXXThrowOperand - Validate the operand of a throw.
414bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
415  // C++ [except.throw]p3:
416  //   A throw-expression initializes a temporary object, called the exception
417  //   object, the type of which is determined by removing any top-level
418  //   cv-qualifiers from the static type of the operand of throw and adjusting
419  //   the type from "array of T" or "function returning T" to "pointer to T"
420  //   or "pointer to function returning T", [...]
421  if (E->getType().hasQualifiers())
422    ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
423                      E->isLvalue(Context) == Expr::LV_Valid);
424
425  DefaultFunctionArrayConversion(E);
426
427  //   If the type of the exception would be an incomplete type or a pointer
428  //   to an incomplete type other than (cv) void the program is ill-formed.
429  QualType Ty = E->getType();
430  bool isPointer = false;
431  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
432    Ty = Ptr->getPointeeType();
433    isPointer = true;
434  }
435  if (!isPointer || !Ty->isVoidType()) {
436    if (RequireCompleteType(ThrowLoc, Ty,
437                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
438                                            : diag::err_throw_incomplete)
439                              << E->getSourceRange()))
440      return true;
441
442    if (RequireNonAbstractType(ThrowLoc, E->getType(),
443                               PDiag(diag::err_throw_abstract_type)
444                                 << E->getSourceRange()))
445      return true;
446  }
447
448  // Initialize the exception result.  This implicitly weeds out
449  // abstract types or types with inaccessible copy constructors.
450  // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
451  InitializedEntity Entity =
452    InitializedEntity::InitializeException(ThrowLoc, E->getType(),
453                                           /*NRVO=*/false);
454  OwningExprResult Res = PerformCopyInitialization(Entity,
455                                                   SourceLocation(),
456                                                   Owned(E));
457  if (Res.isInvalid())
458    return true;
459  E = Res.takeAs<Expr>();
460
461  // If the exception has class type, we need additional handling.
462  const RecordType *RecordTy = Ty->getAs<RecordType>();
463  if (!RecordTy)
464    return false;
465  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
466
467  // If we are throwing a polymorphic class type or pointer thereof,
468  // exception handling will make use of the vtable.
469  MarkVTableUsed(ThrowLoc, RD);
470
471  // If the class has a non-trivial destructor, we must be able to call it.
472  if (RD->hasTrivialDestructor())
473    return false;
474
475  CXXDestructorDecl *Destructor =
476    const_cast<CXXDestructorDecl*>(RD->getDestructor(Context));
477  if (!Destructor)
478    return false;
479
480  MarkDeclarationReferenced(E->getExprLoc(), Destructor);
481  CheckDestructorAccess(E->getExprLoc(), Destructor,
482                        PDiag(diag::err_access_dtor_temp) << Ty);
483  return false;
484}
485
486Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
487  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
488  /// is a non-lvalue expression whose value is the address of the object for
489  /// which the function is called.
490
491  DeclContext *DC = getFunctionLevelDeclContext();
492  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
493    if (MD->isInstance())
494      return Owned(new (Context) CXXThisExpr(ThisLoc,
495                                             MD->getThisType(Context),
496                                             /*isImplicit=*/false));
497
498  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
499}
500
501/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
502/// Can be interpreted either as function-style casting ("int(x)")
503/// or class type construction ("ClassType(x,y,z)")
504/// or creation of a value-initialized type ("int()").
505Action::OwningExprResult
506Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
507                                SourceLocation LParenLoc,
508                                MultiExprArg exprs,
509                                SourceLocation *CommaLocs,
510                                SourceLocation RParenLoc) {
511  if (!TypeRep)
512    return ExprError();
513
514  TypeSourceInfo *TInfo;
515  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
516  if (!TInfo)
517    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
518  unsigned NumExprs = exprs.size();
519  Expr **Exprs = (Expr**)exprs.get();
520  SourceLocation TyBeginLoc = TypeRange.getBegin();
521  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
522
523  if (Ty->isDependentType() ||
524      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
525    exprs.release();
526
527    return Owned(CXXUnresolvedConstructExpr::Create(Context,
528                                                    TypeRange.getBegin(), Ty,
529                                                    LParenLoc,
530                                                    Exprs, NumExprs,
531                                                    RParenLoc));
532  }
533
534  if (Ty->isArrayType())
535    return ExprError(Diag(TyBeginLoc,
536                          diag::err_value_init_for_array_type) << FullRange);
537  if (!Ty->isVoidType() &&
538      RequireCompleteType(TyBeginLoc, Ty,
539                          PDiag(diag::err_invalid_incomplete_type_use)
540                            << FullRange))
541    return ExprError();
542
543  if (RequireNonAbstractType(TyBeginLoc, Ty,
544                             diag::err_allocation_of_abstract_type))
545    return ExprError();
546
547
548  // C++ [expr.type.conv]p1:
549  // If the expression list is a single expression, the type conversion
550  // expression is equivalent (in definedness, and if defined in meaning) to the
551  // corresponding cast expression.
552  //
553  if (NumExprs == 1) {
554    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
555    CXXBaseSpecifierArray BasePath;
556    if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
557                       /*FunctionalStyle=*/true))
558      return ExprError();
559
560    exprs.release();
561
562    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
563                                                     TInfo, TyBeginLoc, Kind,
564                                                     Exprs[0], BasePath,
565                                                     RParenLoc));
566  }
567
568  if (const RecordType *RT = Ty->getAs<RecordType>()) {
569    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
570
571    if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
572        !Record->hasTrivialDestructor()) {
573      InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
574      InitializationKind Kind
575        = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
576                                                      LParenLoc, RParenLoc)
577                   : InitializationKind::CreateValue(TypeRange.getBegin(),
578                                                     LParenLoc, RParenLoc);
579      InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
580      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
581                                                move(exprs));
582
583      // FIXME: Improve AST representation?
584      return move(Result);
585    }
586
587    // Fall through to value-initialize an object of class type that
588    // doesn't have a user-declared default constructor.
589  }
590
591  // C++ [expr.type.conv]p1:
592  // If the expression list specifies more than a single value, the type shall
593  // be a class with a suitably declared constructor.
594  //
595  if (NumExprs > 1)
596    return ExprError(Diag(CommaLocs[0],
597                          diag::err_builtin_func_cast_more_than_one_arg)
598      << FullRange);
599
600  assert(NumExprs == 0 && "Expected 0 expressions");
601  // C++ [expr.type.conv]p2:
602  // The expression T(), where T is a simple-type-specifier for a non-array
603  // complete object type or the (possibly cv-qualified) void type, creates an
604  // rvalue of the specified type, which is value-initialized.
605  //
606  exprs.release();
607  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
608}
609
610
611/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
612/// @code new (memory) int[size][4] @endcode
613/// or
614/// @code ::new Foo(23, "hello") @endcode
615/// For the interpretation of this heap of arguments, consult the base version.
616Action::OwningExprResult
617Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
618                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
619                  SourceLocation PlacementRParen, bool ParenTypeId,
620                  Declarator &D, SourceLocation ConstructorLParen,
621                  MultiExprArg ConstructorArgs,
622                  SourceLocation ConstructorRParen) {
623  Expr *ArraySize = 0;
624  // If the specified type is an array, unwrap it and save the expression.
625  if (D.getNumTypeObjects() > 0 &&
626      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
627    DeclaratorChunk &Chunk = D.getTypeObject(0);
628    if (Chunk.Arr.hasStatic)
629      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
630        << D.getSourceRange());
631    if (!Chunk.Arr.NumElts)
632      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
633        << D.getSourceRange());
634
635    if (ParenTypeId) {
636      // Can't have dynamic array size when the type-id is in parentheses.
637      Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
638      if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
639          !NumElts->isIntegerConstantExpr(Context)) {
640        Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
641          << NumElts->getSourceRange();
642        return ExprError();
643      }
644    }
645
646    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
647    D.DropFirstTypeObject();
648  }
649
650  // Every dimension shall be of constant size.
651  if (ArraySize) {
652    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
653      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
654        break;
655
656      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
657      if (Expr *NumElts = (Expr *)Array.NumElts) {
658        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
659            !NumElts->isIntegerConstantExpr(Context)) {
660          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
661            << NumElts->getSourceRange();
662          return ExprError();
663        }
664      }
665    }
666  }
667
668  //FIXME: Store TypeSourceInfo in CXXNew expression.
669  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
670  QualType AllocType = TInfo->getType();
671  if (D.isInvalidType())
672    return ExprError();
673
674  return BuildCXXNew(StartLoc, UseGlobal,
675                     PlacementLParen,
676                     move(PlacementArgs),
677                     PlacementRParen,
678                     ParenTypeId,
679                     AllocType,
680                     D.getSourceRange().getBegin(),
681                     D.getSourceRange(),
682                     Owned(ArraySize),
683                     ConstructorLParen,
684                     move(ConstructorArgs),
685                     ConstructorRParen);
686}
687
688Sema::OwningExprResult
689Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
690                  SourceLocation PlacementLParen,
691                  MultiExprArg PlacementArgs,
692                  SourceLocation PlacementRParen,
693                  bool ParenTypeId,
694                  QualType AllocType,
695                  SourceLocation TypeLoc,
696                  SourceRange TypeRange,
697                  ExprArg ArraySizeE,
698                  SourceLocation ConstructorLParen,
699                  MultiExprArg ConstructorArgs,
700                  SourceLocation ConstructorRParen) {
701  if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
702    return ExprError();
703
704  // Per C++0x [expr.new]p5, the type being constructed may be a
705  // typedef of an array type.
706  if (!ArraySizeE.get()) {
707    if (const ConstantArrayType *Array
708                              = Context.getAsConstantArrayType(AllocType)) {
709      ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
710                                                      Context.getSizeType(),
711                                                      TypeRange.getEnd()));
712      AllocType = Array->getElementType();
713    }
714  }
715
716  QualType ResultType = Context.getPointerType(AllocType);
717
718  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
719  //   or enumeration type with a non-negative value."
720  Expr *ArraySize = (Expr *)ArraySizeE.get();
721  if (ArraySize && !ArraySize->isTypeDependent()) {
722    QualType SizeType = ArraySize->getType();
723    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
724      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
725                            diag::err_array_size_not_integral)
726        << SizeType << ArraySize->getSourceRange());
727    // Let's see if this is a constant < 0. If so, we reject it out of hand.
728    // We don't care about special rules, so we tell the machinery it's not
729    // evaluated - it gives us a result in more cases.
730    if (!ArraySize->isValueDependent()) {
731      llvm::APSInt Value;
732      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
733        if (Value < llvm::APSInt(
734                        llvm::APInt::getNullValue(Value.getBitWidth()),
735                                 Value.isUnsigned()))
736          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
737                           diag::err_typecheck_negative_array_size)
738            << ArraySize->getSourceRange());
739      }
740    }
741
742    ImpCastExprToType(ArraySize, Context.getSizeType(),
743                      CastExpr::CK_IntegralCast);
744  }
745
746  FunctionDecl *OperatorNew = 0;
747  FunctionDecl *OperatorDelete = 0;
748  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
749  unsigned NumPlaceArgs = PlacementArgs.size();
750
751  if (!AllocType->isDependentType() &&
752      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
753      FindAllocationFunctions(StartLoc,
754                              SourceRange(PlacementLParen, PlacementRParen),
755                              UseGlobal, AllocType, ArraySize, PlaceArgs,
756                              NumPlaceArgs, OperatorNew, OperatorDelete))
757    return ExprError();
758  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
759  if (OperatorNew) {
760    // Add default arguments, if any.
761    const FunctionProtoType *Proto =
762      OperatorNew->getType()->getAs<FunctionProtoType>();
763    VariadicCallType CallType =
764      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
765
766    if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
767                               Proto, 1, PlaceArgs, NumPlaceArgs,
768                               AllPlaceArgs, CallType))
769      return ExprError();
770
771    NumPlaceArgs = AllPlaceArgs.size();
772    if (NumPlaceArgs > 0)
773      PlaceArgs = &AllPlaceArgs[0];
774  }
775
776  bool Init = ConstructorLParen.isValid();
777  // --- Choosing a constructor ---
778  CXXConstructorDecl *Constructor = 0;
779  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
780  unsigned NumConsArgs = ConstructorArgs.size();
781  ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
782
783  // Array 'new' can't have any initializers.
784  if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
785    SourceRange InitRange(ConsArgs[0]->getLocStart(),
786                          ConsArgs[NumConsArgs - 1]->getLocEnd());
787
788    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
789    return ExprError();
790  }
791
792  if (!AllocType->isDependentType() &&
793      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
794    // C++0x [expr.new]p15:
795    //   A new-expression that creates an object of type T initializes that
796    //   object as follows:
797    InitializationKind Kind
798    //     - If the new-initializer is omitted, the object is default-
799    //       initialized (8.5); if no initialization is performed,
800    //       the object has indeterminate value
801      = !Init? InitializationKind::CreateDefault(TypeLoc)
802    //     - Otherwise, the new-initializer is interpreted according to the
803    //       initialization rules of 8.5 for direct-initialization.
804             : InitializationKind::CreateDirect(TypeLoc,
805                                                ConstructorLParen,
806                                                ConstructorRParen);
807
808    InitializedEntity Entity
809      = InitializedEntity::InitializeNew(StartLoc, AllocType);
810    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
811    OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
812                                                move(ConstructorArgs));
813    if (FullInit.isInvalid())
814      return ExprError();
815
816    // FullInit is our initializer; walk through it to determine if it's a
817    // constructor call, which CXXNewExpr handles directly.
818    if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
819      if (CXXBindTemporaryExpr *Binder
820            = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
821        FullInitExpr = Binder->getSubExpr();
822      if (CXXConstructExpr *Construct
823                    = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
824        Constructor = Construct->getConstructor();
825        for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
826                                         AEnd = Construct->arg_end();
827             A != AEnd; ++A)
828          ConvertedConstructorArgs.push_back(A->Retain());
829      } else {
830        // Take the converted initializer.
831        ConvertedConstructorArgs.push_back(FullInit.release());
832      }
833    } else {
834      // No initialization required.
835    }
836
837    // Take the converted arguments and use them for the new expression.
838    NumConsArgs = ConvertedConstructorArgs.size();
839    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
840  }
841
842  // Mark the new and delete operators as referenced.
843  if (OperatorNew)
844    MarkDeclarationReferenced(StartLoc, OperatorNew);
845  if (OperatorDelete)
846    MarkDeclarationReferenced(StartLoc, OperatorDelete);
847
848  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
849
850  PlacementArgs.release();
851  ConstructorArgs.release();
852  ArraySizeE.release();
853  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
854                                        PlaceArgs, NumPlaceArgs, ParenTypeId,
855                                        ArraySize, Constructor, Init,
856                                        ConsArgs, NumConsArgs, OperatorDelete,
857                                        ResultType, StartLoc,
858                                        Init ? ConstructorRParen :
859                                               SourceLocation()));
860}
861
862/// CheckAllocatedType - Checks that a type is suitable as the allocated type
863/// in a new-expression.
864/// dimension off and stores the size expression in ArraySize.
865bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
866                              SourceRange R) {
867  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
868  //   abstract class type or array thereof.
869  if (AllocType->isFunctionType())
870    return Diag(Loc, diag::err_bad_new_type)
871      << AllocType << 0 << R;
872  else if (AllocType->isReferenceType())
873    return Diag(Loc, diag::err_bad_new_type)
874      << AllocType << 1 << R;
875  else if (!AllocType->isDependentType() &&
876           RequireCompleteType(Loc, AllocType,
877                               PDiag(diag::err_new_incomplete_type)
878                                 << R))
879    return true;
880  else if (RequireNonAbstractType(Loc, AllocType,
881                                  diag::err_allocation_of_abstract_type))
882    return true;
883
884  return false;
885}
886
887/// \brief Determine whether the given function is a non-placement
888/// deallocation function.
889static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
890  if (FD->isInvalidDecl())
891    return false;
892
893  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
894    return Method->isUsualDeallocationFunction();
895
896  return ((FD->getOverloadedOperator() == OO_Delete ||
897           FD->getOverloadedOperator() == OO_Array_Delete) &&
898          FD->getNumParams() == 1);
899}
900
901/// FindAllocationFunctions - Finds the overloads of operator new and delete
902/// that are appropriate for the allocation.
903bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
904                                   bool UseGlobal, QualType AllocType,
905                                   bool IsArray, Expr **PlaceArgs,
906                                   unsigned NumPlaceArgs,
907                                   FunctionDecl *&OperatorNew,
908                                   FunctionDecl *&OperatorDelete) {
909  // --- Choosing an allocation function ---
910  // C++ 5.3.4p8 - 14 & 18
911  // 1) If UseGlobal is true, only look in the global scope. Else, also look
912  //   in the scope of the allocated class.
913  // 2) If an array size is given, look for operator new[], else look for
914  //   operator new.
915  // 3) The first argument is always size_t. Append the arguments from the
916  //   placement form.
917
918  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
919  // We don't care about the actual value of this argument.
920  // FIXME: Should the Sema create the expression and embed it in the syntax
921  // tree? Or should the consumer just recalculate the value?
922  IntegerLiteral Size(llvm::APInt::getNullValue(
923                      Context.Target.getPointerWidth(0)),
924                      Context.getSizeType(),
925                      SourceLocation());
926  AllocArgs[0] = &Size;
927  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
928
929  // C++ [expr.new]p8:
930  //   If the allocated type is a non-array type, the allocation
931  //   function’s name is operator new and the deallocation function’s
932  //   name is operator delete. If the allocated type is an array
933  //   type, the allocation function’s name is operator new[] and the
934  //   deallocation function’s name is operator delete[].
935  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
936                                        IsArray ? OO_Array_New : OO_New);
937  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
938                                        IsArray ? OO_Array_Delete : OO_Delete);
939
940  if (AllocType->isRecordType() && !UseGlobal) {
941    CXXRecordDecl *Record
942      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
943    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
944                          AllocArgs.size(), Record, /*AllowMissing=*/true,
945                          OperatorNew))
946      return true;
947  }
948  if (!OperatorNew) {
949    // Didn't find a member overload. Look for a global one.
950    DeclareGlobalNewDelete();
951    DeclContext *TUDecl = Context.getTranslationUnitDecl();
952    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
953                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
954                          OperatorNew))
955      return true;
956  }
957
958  // We don't need an operator delete if we're running under
959  // -fno-exceptions.
960  if (!getLangOptions().Exceptions) {
961    OperatorDelete = 0;
962    return false;
963  }
964
965  // FindAllocationOverload can change the passed in arguments, so we need to
966  // copy them back.
967  if (NumPlaceArgs > 0)
968    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
969
970  // C++ [expr.new]p19:
971  //
972  //   If the new-expression begins with a unary :: operator, the
973  //   deallocation function’s name is looked up in the global
974  //   scope. Otherwise, if the allocated type is a class type T or an
975  //   array thereof, the deallocation function’s name is looked up in
976  //   the scope of T. If this lookup fails to find the name, or if
977  //   the allocated type is not a class type or array thereof, the
978  //   deallocation function’s name is looked up in the global scope.
979  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
980  if (AllocType->isRecordType() && !UseGlobal) {
981    CXXRecordDecl *RD
982      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
983    LookupQualifiedName(FoundDelete, RD);
984  }
985  if (FoundDelete.isAmbiguous())
986    return true; // FIXME: clean up expressions?
987
988  if (FoundDelete.empty()) {
989    DeclareGlobalNewDelete();
990    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
991  }
992
993  FoundDelete.suppressDiagnostics();
994
995  llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
996
997  if (NumPlaceArgs > 0) {
998    // C++ [expr.new]p20:
999    //   A declaration of a placement deallocation function matches the
1000    //   declaration of a placement allocation function if it has the
1001    //   same number of parameters and, after parameter transformations
1002    //   (8.3.5), all parameter types except the first are
1003    //   identical. [...]
1004    //
1005    // To perform this comparison, we compute the function type that
1006    // the deallocation function should have, and use that type both
1007    // for template argument deduction and for comparison purposes.
1008    QualType ExpectedFunctionType;
1009    {
1010      const FunctionProtoType *Proto
1011        = OperatorNew->getType()->getAs<FunctionProtoType>();
1012      llvm::SmallVector<QualType, 4> ArgTypes;
1013      ArgTypes.push_back(Context.VoidPtrTy);
1014      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1015        ArgTypes.push_back(Proto->getArgType(I));
1016
1017      ExpectedFunctionType
1018        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1019                                  ArgTypes.size(),
1020                                  Proto->isVariadic(),
1021                                  0, false, false, 0, 0,
1022                                  FunctionType::ExtInfo());
1023    }
1024
1025    for (LookupResult::iterator D = FoundDelete.begin(),
1026                             DEnd = FoundDelete.end();
1027         D != DEnd; ++D) {
1028      FunctionDecl *Fn = 0;
1029      if (FunctionTemplateDecl *FnTmpl
1030            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1031        // Perform template argument deduction to try to match the
1032        // expected function type.
1033        TemplateDeductionInfo Info(Context, StartLoc);
1034        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1035          continue;
1036      } else
1037        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1038
1039      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1040        Matches.push_back(std::make_pair(D.getPair(), Fn));
1041    }
1042  } else {
1043    // C++ [expr.new]p20:
1044    //   [...] Any non-placement deallocation function matches a
1045    //   non-placement allocation function. [...]
1046    for (LookupResult::iterator D = FoundDelete.begin(),
1047                             DEnd = FoundDelete.end();
1048         D != DEnd; ++D) {
1049      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1050        if (isNonPlacementDeallocationFunction(Fn))
1051          Matches.push_back(std::make_pair(D.getPair(), Fn));
1052    }
1053  }
1054
1055  // C++ [expr.new]p20:
1056  //   [...] If the lookup finds a single matching deallocation
1057  //   function, that function will be called; otherwise, no
1058  //   deallocation function will be called.
1059  if (Matches.size() == 1) {
1060    OperatorDelete = Matches[0].second;
1061
1062    // C++0x [expr.new]p20:
1063    //   If the lookup finds the two-parameter form of a usual
1064    //   deallocation function (3.7.4.2) and that function, considered
1065    //   as a placement deallocation function, would have been
1066    //   selected as a match for the allocation function, the program
1067    //   is ill-formed.
1068    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1069        isNonPlacementDeallocationFunction(OperatorDelete)) {
1070      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1071        << SourceRange(PlaceArgs[0]->getLocStart(),
1072                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1073      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1074        << DeleteName;
1075    } else {
1076      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1077                            Matches[0].first);
1078    }
1079  }
1080
1081  return false;
1082}
1083
1084/// FindAllocationOverload - Find an fitting overload for the allocation
1085/// function in the specified scope.
1086bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1087                                  DeclarationName Name, Expr** Args,
1088                                  unsigned NumArgs, DeclContext *Ctx,
1089                                  bool AllowMissing, FunctionDecl *&Operator) {
1090  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1091  LookupQualifiedName(R, Ctx);
1092  if (R.empty()) {
1093    if (AllowMissing)
1094      return false;
1095    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1096      << Name << Range;
1097  }
1098
1099  if (R.isAmbiguous())
1100    return true;
1101
1102  R.suppressDiagnostics();
1103
1104  OverloadCandidateSet Candidates(StartLoc);
1105  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1106       Alloc != AllocEnd; ++Alloc) {
1107    // Even member operator new/delete are implicitly treated as
1108    // static, so don't use AddMemberCandidate.
1109    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1110
1111    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1112      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1113                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1114                                   Candidates,
1115                                   /*SuppressUserConversions=*/false);
1116      continue;
1117    }
1118
1119    FunctionDecl *Fn = cast<FunctionDecl>(D);
1120    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1121                         /*SuppressUserConversions=*/false);
1122  }
1123
1124  // Do the resolution.
1125  OverloadCandidateSet::iterator Best;
1126  switch(BestViableFunction(Candidates, StartLoc, Best)) {
1127  case OR_Success: {
1128    // Got one!
1129    FunctionDecl *FnDecl = Best->Function;
1130    // The first argument is size_t, and the first parameter must be size_t,
1131    // too. This is checked on declaration and can be assumed. (It can't be
1132    // asserted on, though, since invalid decls are left in there.)
1133    // Watch out for variadic allocator function.
1134    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1135    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1136      OwningExprResult Result
1137        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1138                                                       FnDecl->getParamDecl(i)),
1139                                    SourceLocation(),
1140                                    Owned(Args[i]->Retain()));
1141      if (Result.isInvalid())
1142        return true;
1143
1144      Args[i] = Result.takeAs<Expr>();
1145    }
1146    Operator = FnDecl;
1147    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1148    return false;
1149  }
1150
1151  case OR_No_Viable_Function:
1152    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1153      << Name << Range;
1154    PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
1155    return true;
1156
1157  case OR_Ambiguous:
1158    Diag(StartLoc, diag::err_ovl_ambiguous_call)
1159      << Name << Range;
1160    PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
1161    return true;
1162
1163  case OR_Deleted:
1164    Diag(StartLoc, diag::err_ovl_deleted_call)
1165      << Best->Function->isDeleted()
1166      << Name << Range;
1167    PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
1168    return true;
1169  }
1170  assert(false && "Unreachable, bad result from BestViableFunction");
1171  return true;
1172}
1173
1174
1175/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1176/// delete. These are:
1177/// @code
1178///   void* operator new(std::size_t) throw(std::bad_alloc);
1179///   void* operator new[](std::size_t) throw(std::bad_alloc);
1180///   void operator delete(void *) throw();
1181///   void operator delete[](void *) throw();
1182/// @endcode
1183/// Note that the placement and nothrow forms of new are *not* implicitly
1184/// declared. Their use requires including \<new\>.
1185void Sema::DeclareGlobalNewDelete() {
1186  if (GlobalNewDeleteDeclared)
1187    return;
1188
1189  // C++ [basic.std.dynamic]p2:
1190  //   [...] The following allocation and deallocation functions (18.4) are
1191  //   implicitly declared in global scope in each translation unit of a
1192  //   program
1193  //
1194  //     void* operator new(std::size_t) throw(std::bad_alloc);
1195  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1196  //     void  operator delete(void*) throw();
1197  //     void  operator delete[](void*) throw();
1198  //
1199  //   These implicit declarations introduce only the function names operator
1200  //   new, operator new[], operator delete, operator delete[].
1201  //
1202  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1203  // "std" or "bad_alloc" as necessary to form the exception specification.
1204  // However, we do not make these implicit declarations visible to name
1205  // lookup.
1206  if (!StdNamespace) {
1207    // The "std" namespace has not yet been defined, so build one implicitly.
1208    StdNamespace = NamespaceDecl::Create(Context,
1209                                         Context.getTranslationUnitDecl(),
1210                                         SourceLocation(),
1211                                         &PP.getIdentifierTable().get("std"));
1212    StdNamespace->setImplicit(true);
1213  }
1214
1215  if (!StdBadAlloc) {
1216    // The "std::bad_alloc" class has not yet been declared, so build it
1217    // implicitly.
1218    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1219                                        StdNamespace,
1220                                        SourceLocation(),
1221                                      &PP.getIdentifierTable().get("bad_alloc"),
1222                                        SourceLocation(), 0);
1223    StdBadAlloc->setImplicit(true);
1224  }
1225
1226  GlobalNewDeleteDeclared = true;
1227
1228  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1229  QualType SizeT = Context.getSizeType();
1230  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1231
1232  DeclareGlobalAllocationFunction(
1233      Context.DeclarationNames.getCXXOperatorName(OO_New),
1234      VoidPtr, SizeT, AssumeSaneOperatorNew);
1235  DeclareGlobalAllocationFunction(
1236      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1237      VoidPtr, SizeT, AssumeSaneOperatorNew);
1238  DeclareGlobalAllocationFunction(
1239      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1240      Context.VoidTy, VoidPtr);
1241  DeclareGlobalAllocationFunction(
1242      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1243      Context.VoidTy, VoidPtr);
1244}
1245
1246/// DeclareGlobalAllocationFunction - Declares a single implicit global
1247/// allocation function if it doesn't already exist.
1248void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1249                                           QualType Return, QualType Argument,
1250                                           bool AddMallocAttr) {
1251  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1252
1253  // Check if this function is already declared.
1254  {
1255    DeclContext::lookup_iterator Alloc, AllocEnd;
1256    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1257         Alloc != AllocEnd; ++Alloc) {
1258      // Only look at non-template functions, as it is the predefined,
1259      // non-templated allocation function we are trying to declare here.
1260      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1261        QualType InitialParamType =
1262          Context.getCanonicalType(
1263            Func->getParamDecl(0)->getType().getUnqualifiedType());
1264        // FIXME: Do we need to check for default arguments here?
1265        if (Func->getNumParams() == 1 && InitialParamType == Argument)
1266          return;
1267      }
1268    }
1269  }
1270
1271  QualType BadAllocType;
1272  bool HasBadAllocExceptionSpec
1273    = (Name.getCXXOverloadedOperator() == OO_New ||
1274       Name.getCXXOverloadedOperator() == OO_Array_New);
1275  if (HasBadAllocExceptionSpec) {
1276    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1277    BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1278  }
1279
1280  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1281                                            true, false,
1282                                            HasBadAllocExceptionSpec? 1 : 0,
1283                                            &BadAllocType,
1284                                            FunctionType::ExtInfo());
1285  FunctionDecl *Alloc =
1286    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
1287                         FnType, /*TInfo=*/0, FunctionDecl::None,
1288                         FunctionDecl::None, false, true);
1289  Alloc->setImplicit();
1290
1291  if (AddMallocAttr)
1292    Alloc->addAttr(::new (Context) MallocAttr());
1293
1294  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1295                                           0, Argument, /*TInfo=*/0,
1296                                           VarDecl::None,
1297                                           VarDecl::None, 0);
1298  Alloc->setParams(&Param, 1);
1299
1300  // FIXME: Also add this declaration to the IdentifierResolver, but
1301  // make sure it is at the end of the chain to coincide with the
1302  // global scope.
1303  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
1304}
1305
1306bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1307                                    DeclarationName Name,
1308                                    FunctionDecl* &Operator) {
1309  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1310  // Try to find operator delete/operator delete[] in class scope.
1311  LookupQualifiedName(Found, RD);
1312
1313  if (Found.isAmbiguous())
1314    return true;
1315
1316  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1317       F != FEnd; ++F) {
1318    if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1319      if (Delete->isUsualDeallocationFunction()) {
1320        Operator = Delete;
1321        return false;
1322      }
1323  }
1324
1325  // We did find operator delete/operator delete[] declarations, but
1326  // none of them were suitable.
1327  if (!Found.empty()) {
1328    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1329      << Name << RD;
1330
1331    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1332         F != FEnd; ++F) {
1333      Diag((*F)->getLocation(), diag::note_member_declared_here)
1334        << Name;
1335    }
1336
1337    return true;
1338  }
1339
1340  // Look for a global declaration.
1341  DeclareGlobalNewDelete();
1342  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1343
1344  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1345  Expr* DeallocArgs[1];
1346  DeallocArgs[0] = &Null;
1347  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1348                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1349                             Operator))
1350    return true;
1351
1352  assert(Operator && "Did not find a deallocation function!");
1353  return false;
1354}
1355
1356/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1357/// @code ::delete ptr; @endcode
1358/// or
1359/// @code delete [] ptr; @endcode
1360Action::OwningExprResult
1361Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1362                     bool ArrayForm, ExprArg Operand) {
1363  // C++ [expr.delete]p1:
1364  //   The operand shall have a pointer type, or a class type having a single
1365  //   conversion function to a pointer type. The result has type void.
1366  //
1367  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1368
1369  FunctionDecl *OperatorDelete = 0;
1370
1371  Expr *Ex = (Expr *)Operand.get();
1372  if (!Ex->isTypeDependent()) {
1373    QualType Type = Ex->getType();
1374
1375    if (const RecordType *Record = Type->getAs<RecordType>()) {
1376      llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1377
1378      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1379      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1380      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1381             E = Conversions->end(); I != E; ++I) {
1382        NamedDecl *D = I.getDecl();
1383        if (isa<UsingShadowDecl>(D))
1384          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1385
1386        // Skip over templated conversion functions; they aren't considered.
1387        if (isa<FunctionTemplateDecl>(D))
1388          continue;
1389
1390        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1391
1392        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1393        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1394          if (ConvPtrType->getPointeeType()->isObjectType())
1395            ObjectPtrConversions.push_back(Conv);
1396      }
1397      if (ObjectPtrConversions.size() == 1) {
1398        // We have a single conversion to a pointer-to-object type. Perform
1399        // that conversion.
1400        // TODO: don't redo the conversion calculation.
1401        Operand.release();
1402        if (!PerformImplicitConversion(Ex,
1403                            ObjectPtrConversions.front()->getConversionType(),
1404                                      AA_Converting)) {
1405          Operand = Owned(Ex);
1406          Type = Ex->getType();
1407        }
1408      }
1409      else if (ObjectPtrConversions.size() > 1) {
1410        Diag(StartLoc, diag::err_ambiguous_delete_operand)
1411              << Type << Ex->getSourceRange();
1412        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1413          NoteOverloadCandidate(ObjectPtrConversions[i]);
1414        return ExprError();
1415      }
1416    }
1417
1418    if (!Type->isPointerType())
1419      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1420        << Type << Ex->getSourceRange());
1421
1422    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1423    if (Pointee->isVoidType() && !isSFINAEContext()) {
1424      // The C++ standard bans deleting a pointer to a non-object type, which
1425      // effectively bans deletion of "void*". However, most compilers support
1426      // this, so we treat it as a warning unless we're in a SFINAE context.
1427      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1428        << Type << Ex->getSourceRange();
1429    } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1430      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1431        << Type << Ex->getSourceRange());
1432    else if (!Pointee->isDependentType() &&
1433             RequireCompleteType(StartLoc, Pointee,
1434                                 PDiag(diag::warn_delete_incomplete)
1435                                   << Ex->getSourceRange()))
1436      return ExprError();
1437
1438    // C++ [expr.delete]p2:
1439    //   [Note: a pointer to a const type can be the operand of a
1440    //   delete-expression; it is not necessary to cast away the constness
1441    //   (5.2.11) of the pointer expression before it is used as the operand
1442    //   of the delete-expression. ]
1443    ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1444                      CastExpr::CK_NoOp);
1445
1446    // Update the operand.
1447    Operand.take();
1448    Operand = ExprArg(*this, Ex);
1449
1450    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1451                                      ArrayForm ? OO_Array_Delete : OO_Delete);
1452
1453    if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1454      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1455
1456      if (!UseGlobal &&
1457          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1458        return ExprError();
1459
1460      if (!RD->hasTrivialDestructor())
1461        if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
1462          MarkDeclarationReferenced(StartLoc,
1463                                    const_cast<CXXDestructorDecl*>(Dtor));
1464    }
1465
1466    if (!OperatorDelete) {
1467      // Look for a global declaration.
1468      DeclareGlobalNewDelete();
1469      DeclContext *TUDecl = Context.getTranslationUnitDecl();
1470      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1471                                 &Ex, 1, TUDecl, /*AllowMissing=*/false,
1472                                 OperatorDelete))
1473        return ExprError();
1474    }
1475
1476    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1477
1478    // FIXME: Check access and ambiguity of operator delete and destructor.
1479  }
1480
1481  Operand.release();
1482  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1483                                           OperatorDelete, Ex, StartLoc));
1484}
1485
1486/// \brief Check the use of the given variable as a C++ condition in an if,
1487/// while, do-while, or switch statement.
1488Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1489                                                      SourceLocation StmtLoc,
1490                                                      bool ConvertToBoolean) {
1491  QualType T = ConditionVar->getType();
1492
1493  // C++ [stmt.select]p2:
1494  //   The declarator shall not specify a function or an array.
1495  if (T->isFunctionType())
1496    return ExprError(Diag(ConditionVar->getLocation(),
1497                          diag::err_invalid_use_of_function_type)
1498                       << ConditionVar->getSourceRange());
1499  else if (T->isArrayType())
1500    return ExprError(Diag(ConditionVar->getLocation(),
1501                          diag::err_invalid_use_of_array_type)
1502                     << ConditionVar->getSourceRange());
1503
1504  Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1505                                        ConditionVar->getLocation(),
1506                                 ConditionVar->getType().getNonReferenceType());
1507  if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1508    Condition->Destroy(Context);
1509    return ExprError();
1510  }
1511
1512  return Owned(Condition);
1513}
1514
1515/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1516bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1517  // C++ 6.4p4:
1518  // The value of a condition that is an initialized declaration in a statement
1519  // other than a switch statement is the value of the declared variable
1520  // implicitly converted to type bool. If that conversion is ill-formed, the
1521  // program is ill-formed.
1522  // The value of a condition that is an expression is the value of the
1523  // expression, implicitly converted to bool.
1524  //
1525  return PerformContextuallyConvertToBool(CondExpr);
1526}
1527
1528/// Helper function to determine whether this is the (deprecated) C++
1529/// conversion from a string literal to a pointer to non-const char or
1530/// non-const wchar_t (for narrow and wide string literals,
1531/// respectively).
1532bool
1533Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1534  // Look inside the implicit cast, if it exists.
1535  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1536    From = Cast->getSubExpr();
1537
1538  // A string literal (2.13.4) that is not a wide string literal can
1539  // be converted to an rvalue of type "pointer to char"; a wide
1540  // string literal can be converted to an rvalue of type "pointer
1541  // to wchar_t" (C++ 4.2p2).
1542  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
1543    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1544      if (const BuiltinType *ToPointeeType
1545          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1546        // This conversion is considered only when there is an
1547        // explicit appropriate pointer target type (C++ 4.2p2).
1548        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1549            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1550             (!StrLit->isWide() &&
1551              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1552               ToPointeeType->getKind() == BuiltinType::Char_S))))
1553          return true;
1554      }
1555
1556  return false;
1557}
1558
1559static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1560                                                   SourceLocation CastLoc,
1561                                                   QualType Ty,
1562                                                   CastExpr::CastKind Kind,
1563                                                   CXXMethodDecl *Method,
1564                                                   Sema::ExprArg Arg) {
1565  Expr *From = Arg.takeAs<Expr>();
1566
1567  switch (Kind) {
1568  default: assert(0 && "Unhandled cast kind!");
1569  case CastExpr::CK_ConstructorConversion: {
1570    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1571
1572    if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1573                                  Sema::MultiExprArg(S, (void **)&From, 1),
1574                                  CastLoc, ConstructorArgs))
1575      return S.ExprError();
1576
1577    Sema::OwningExprResult Result =
1578    S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1579                            move_arg(ConstructorArgs));
1580    if (Result.isInvalid())
1581      return S.ExprError();
1582
1583    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1584  }
1585
1586  case CastExpr::CK_UserDefinedConversion: {
1587    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1588
1589    // Create an implicit call expr that calls it.
1590    // FIXME: pass the FoundDecl for the user-defined conversion here
1591    CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1592    return S.MaybeBindToTemporary(CE);
1593  }
1594  }
1595}
1596
1597/// PerformImplicitConversion - Perform an implicit conversion of the
1598/// expression From to the type ToType using the pre-computed implicit
1599/// conversion sequence ICS. Returns true if there was an error, false
1600/// otherwise. The expression From is replaced with the converted
1601/// expression. Action is the kind of conversion we're performing,
1602/// used in the error message.
1603bool
1604Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1605                                const ImplicitConversionSequence &ICS,
1606                                AssignmentAction Action, bool IgnoreBaseAccess) {
1607  switch (ICS.getKind()) {
1608  case ImplicitConversionSequence::StandardConversion:
1609    if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
1610                                  IgnoreBaseAccess))
1611      return true;
1612    break;
1613
1614  case ImplicitConversionSequence::UserDefinedConversion: {
1615
1616      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1617      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
1618      QualType BeforeToType;
1619      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1620        CastKind = CastExpr::CK_UserDefinedConversion;
1621
1622        // If the user-defined conversion is specified by a conversion function,
1623        // the initial standard conversion sequence converts the source type to
1624        // the implicit object parameter of the conversion function.
1625        BeforeToType = Context.getTagDeclType(Conv->getParent());
1626      } else if (const CXXConstructorDecl *Ctor =
1627                  dyn_cast<CXXConstructorDecl>(FD)) {
1628        CastKind = CastExpr::CK_ConstructorConversion;
1629        // Do no conversion if dealing with ... for the first conversion.
1630        if (!ICS.UserDefined.EllipsisConversion) {
1631          // If the user-defined conversion is specified by a constructor, the
1632          // initial standard conversion sequence converts the source type to the
1633          // type required by the argument of the constructor
1634          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1635        }
1636      }
1637      else
1638        assert(0 && "Unknown conversion function kind!");
1639      // Whatch out for elipsis conversion.
1640      if (!ICS.UserDefined.EllipsisConversion) {
1641        if (PerformImplicitConversion(From, BeforeToType,
1642                                      ICS.UserDefined.Before, AA_Converting,
1643                                      IgnoreBaseAccess))
1644          return true;
1645      }
1646
1647      OwningExprResult CastArg
1648        = BuildCXXCastArgument(*this,
1649                               From->getLocStart(),
1650                               ToType.getNonReferenceType(),
1651                               CastKind, cast<CXXMethodDecl>(FD),
1652                               Owned(From));
1653
1654      if (CastArg.isInvalid())
1655        return true;
1656
1657      From = CastArg.takeAs<Expr>();
1658
1659      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1660                                       AA_Converting, IgnoreBaseAccess);
1661  }
1662
1663  case ImplicitConversionSequence::AmbiguousConversion:
1664    DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1665                          PDiag(diag::err_typecheck_ambiguous_condition)
1666                            << From->getSourceRange());
1667     return true;
1668
1669  case ImplicitConversionSequence::EllipsisConversion:
1670    assert(false && "Cannot perform an ellipsis conversion");
1671    return false;
1672
1673  case ImplicitConversionSequence::BadConversion:
1674    return true;
1675  }
1676
1677  // Everything went well.
1678  return false;
1679}
1680
1681/// PerformImplicitConversion - Perform an implicit conversion of the
1682/// expression From to the type ToType by following the standard
1683/// conversion sequence SCS. Returns true if there was an error, false
1684/// otherwise. The expression From is replaced with the converted
1685/// expression. Flavor is the context in which we're performing this
1686/// conversion, for use in error messages.
1687bool
1688Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1689                                const StandardConversionSequence& SCS,
1690                                AssignmentAction Action, bool IgnoreBaseAccess) {
1691  // Overall FIXME: we are recomputing too many types here and doing far too
1692  // much extra work. What this means is that we need to keep track of more
1693  // information that is computed when we try the implicit conversion initially,
1694  // so that we don't need to recompute anything here.
1695  QualType FromType = From->getType();
1696
1697  if (SCS.CopyConstructor) {
1698    // FIXME: When can ToType be a reference type?
1699    assert(!ToType->isReferenceType());
1700    if (SCS.Second == ICK_Derived_To_Base) {
1701      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1702      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1703                                  MultiExprArg(*this, (void **)&From, 1),
1704                                  /*FIXME:ConstructLoc*/SourceLocation(),
1705                                  ConstructorArgs))
1706        return true;
1707      OwningExprResult FromResult =
1708        BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1709                              ToType, SCS.CopyConstructor,
1710                              move_arg(ConstructorArgs));
1711      if (FromResult.isInvalid())
1712        return true;
1713      From = FromResult.takeAs<Expr>();
1714      return false;
1715    }
1716    OwningExprResult FromResult =
1717      BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1718                            ToType, SCS.CopyConstructor,
1719                            MultiExprArg(*this, (void**)&From, 1));
1720
1721    if (FromResult.isInvalid())
1722      return true;
1723
1724    From = FromResult.takeAs<Expr>();
1725    return false;
1726  }
1727
1728  // Resolve overloaded function references.
1729  if (Context.hasSameType(FromType, Context.OverloadTy)) {
1730    DeclAccessPair Found;
1731    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1732                                                          true, Found);
1733    if (!Fn)
1734      return true;
1735
1736    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1737      return true;
1738
1739    From = FixOverloadedFunctionReference(From, Found, Fn);
1740    FromType = From->getType();
1741  }
1742
1743  // Perform the first implicit conversion.
1744  switch (SCS.First) {
1745  case ICK_Identity:
1746  case ICK_Lvalue_To_Rvalue:
1747    // Nothing to do.
1748    break;
1749
1750  case ICK_Array_To_Pointer:
1751    FromType = Context.getArrayDecayedType(FromType);
1752    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
1753    break;
1754
1755  case ICK_Function_To_Pointer:
1756    FromType = Context.getPointerType(FromType);
1757    ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
1758    break;
1759
1760  default:
1761    assert(false && "Improper first standard conversion");
1762    break;
1763  }
1764
1765  // Perform the second implicit conversion
1766  switch (SCS.Second) {
1767  case ICK_Identity:
1768    // If both sides are functions (or pointers/references to them), there could
1769    // be incompatible exception declarations.
1770    if (CheckExceptionSpecCompatibility(From, ToType))
1771      return true;
1772    // Nothing else to do.
1773    break;
1774
1775  case ICK_NoReturn_Adjustment:
1776    // If both sides are functions (or pointers/references to them), there could
1777    // be incompatible exception declarations.
1778    if (CheckExceptionSpecCompatibility(From, ToType))
1779      return true;
1780
1781    ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1782                      CastExpr::CK_NoOp);
1783    break;
1784
1785  case ICK_Integral_Promotion:
1786  case ICK_Integral_Conversion:
1787    ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1788    break;
1789
1790  case ICK_Floating_Promotion:
1791  case ICK_Floating_Conversion:
1792    ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1793    break;
1794
1795  case ICK_Complex_Promotion:
1796  case ICK_Complex_Conversion:
1797    ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1798    break;
1799
1800  case ICK_Floating_Integral:
1801    if (ToType->isFloatingType())
1802      ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1803    else
1804      ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1805    break;
1806
1807  case ICK_Compatible_Conversion:
1808    ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
1809    break;
1810
1811  case ICK_Pointer_Conversion: {
1812    if (SCS.IncompatibleObjC) {
1813      // Diagnose incompatible Objective-C conversions
1814      Diag(From->getSourceRange().getBegin(),
1815           diag::ext_typecheck_convert_incompatible_pointer)
1816        << From->getType() << ToType << Action
1817        << From->getSourceRange();
1818    }
1819
1820
1821    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1822    CXXBaseSpecifierArray BasePath;
1823    if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
1824      return true;
1825    ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
1826    break;
1827  }
1828
1829  case ICK_Pointer_Member: {
1830    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1831    CXXBaseSpecifierArray BasePath;
1832    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1833                                     IgnoreBaseAccess))
1834      return true;
1835    if (CheckExceptionSpecCompatibility(From, ToType))
1836      return true;
1837    ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
1838    break;
1839  }
1840  case ICK_Boolean_Conversion: {
1841    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1842    if (FromType->isMemberPointerType())
1843      Kind = CastExpr::CK_MemberPointerToBoolean;
1844
1845    ImpCastExprToType(From, Context.BoolTy, Kind);
1846    break;
1847  }
1848
1849  case ICK_Derived_To_Base: {
1850    CXXBaseSpecifierArray BasePath;
1851    if (CheckDerivedToBaseConversion(From->getType(),
1852                                     ToType.getNonReferenceType(),
1853                                     From->getLocStart(),
1854                                     From->getSourceRange(),
1855                                     &BasePath,
1856                                     IgnoreBaseAccess))
1857      return true;
1858
1859    ImpCastExprToType(From, ToType.getNonReferenceType(),
1860                      CastExpr::CK_DerivedToBase,
1861                      /*isLvalue=*/(From->getType()->isRecordType() &&
1862                                    From->isLvalue(Context) == Expr::LV_Valid),
1863                      BasePath);
1864    break;
1865  }
1866
1867  case ICK_Vector_Conversion:
1868    ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1869    break;
1870
1871  case ICK_Vector_Splat:
1872    ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1873    break;
1874
1875  case ICK_Complex_Real:
1876    ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1877    break;
1878
1879  case ICK_Lvalue_To_Rvalue:
1880  case ICK_Array_To_Pointer:
1881  case ICK_Function_To_Pointer:
1882  case ICK_Qualification:
1883  case ICK_Num_Conversion_Kinds:
1884    assert(false && "Improper second standard conversion");
1885    break;
1886  }
1887
1888  switch (SCS.Third) {
1889  case ICK_Identity:
1890    // Nothing to do.
1891    break;
1892
1893  case ICK_Qualification:
1894    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1895    // references.
1896    ImpCastExprToType(From, ToType.getNonReferenceType(),
1897                      CastExpr::CK_NoOp, ToType->isLValueReferenceType());
1898
1899    if (SCS.DeprecatedStringLiteralToCharPtr)
1900      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1901        << ToType.getNonReferenceType();
1902
1903    break;
1904
1905  default:
1906    assert(false && "Improper third standard conversion");
1907    break;
1908  }
1909
1910  return false;
1911}
1912
1913Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1914                                                 SourceLocation KWLoc,
1915                                                 SourceLocation LParen,
1916                                                 TypeTy *Ty,
1917                                                 SourceLocation RParen) {
1918  QualType T = GetTypeFromParser(Ty);
1919
1920  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1921  // all traits except __is_class, __is_enum and __is_union require a the type
1922  // to be complete.
1923  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1924    if (RequireCompleteType(KWLoc, T,
1925                            diag::err_incomplete_type_used_in_type_trait_expr))
1926      return ExprError();
1927  }
1928
1929  // There is no point in eagerly computing the value. The traits are designed
1930  // to be used from type trait templates, so Ty will be a template parameter
1931  // 99% of the time.
1932  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1933                                                RParen, Context.BoolTy));
1934}
1935
1936QualType Sema::CheckPointerToMemberOperands(
1937  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1938  const char *OpSpelling = isIndirect ? "->*" : ".*";
1939  // C++ 5.5p2
1940  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1941  //   be of type "pointer to member of T" (where T is a completely-defined
1942  //   class type) [...]
1943  QualType RType = rex->getType();
1944  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1945  if (!MemPtr) {
1946    Diag(Loc, diag::err_bad_memptr_rhs)
1947      << OpSpelling << RType << rex->getSourceRange();
1948    return QualType();
1949  }
1950
1951  QualType Class(MemPtr->getClass(), 0);
1952
1953  if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1954    return QualType();
1955
1956  // C++ 5.5p2
1957  //   [...] to its first operand, which shall be of class T or of a class of
1958  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1959  //   such a class]
1960  QualType LType = lex->getType();
1961  if (isIndirect) {
1962    if (const PointerType *Ptr = LType->getAs<PointerType>())
1963      LType = Ptr->getPointeeType().getNonReferenceType();
1964    else {
1965      Diag(Loc, diag::err_bad_memptr_lhs)
1966        << OpSpelling << 1 << LType
1967        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
1968      return QualType();
1969    }
1970  }
1971
1972  if (!Context.hasSameUnqualifiedType(Class, LType)) {
1973    // If we want to check the hierarchy, we need a complete type.
1974    if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1975        << OpSpelling << (int)isIndirect)) {
1976      return QualType();
1977    }
1978    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1979                       /*DetectVirtual=*/false);
1980    // FIXME: Would it be useful to print full ambiguity paths, or is that
1981    // overkill?
1982    if (!IsDerivedFrom(LType, Class, Paths) ||
1983        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1984      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1985        << (int)isIndirect << lex->getType();
1986      return QualType();
1987    }
1988    // Cast LHS to type of use.
1989    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1990    bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1991
1992    CXXBaseSpecifierArray BasePath;
1993    BuildBasePathArray(Paths, BasePath);
1994    ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1995                      BasePath);
1996  }
1997
1998  if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
1999    // Diagnose use of pointer-to-member type which when used as
2000    // the functional cast in a pointer-to-member expression.
2001    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2002     return QualType();
2003  }
2004  // C++ 5.5p2
2005  //   The result is an object or a function of the type specified by the
2006  //   second operand.
2007  // The cv qualifiers are the union of those in the pointer and the left side,
2008  // in accordance with 5.5p5 and 5.2.5.
2009  // FIXME: This returns a dereferenced member function pointer as a normal
2010  // function type. However, the only operation valid on such functions is
2011  // calling them. There's also a GCC extension to get a function pointer to the
2012  // thing, which is another complication, because this type - unlike the type
2013  // that is the result of this expression - takes the class as the first
2014  // argument.
2015  // We probably need a "MemberFunctionClosureType" or something like that.
2016  QualType Result = MemPtr->getPointeeType();
2017  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
2018  return Result;
2019}
2020
2021/// \brief Try to convert a type to another according to C++0x 5.16p3.
2022///
2023/// This is part of the parameter validation for the ? operator. If either
2024/// value operand is a class type, the two operands are attempted to be
2025/// converted to each other. This function does the conversion in one direction.
2026/// It returns true if the program is ill-formed and has already been diagnosed
2027/// as such.
2028static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2029                                SourceLocation QuestionLoc,
2030                                bool &HaveConversion,
2031                                QualType &ToType) {
2032  HaveConversion = false;
2033  ToType = To->getType();
2034
2035  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2036                                                           SourceLocation());
2037  // C++0x 5.16p3
2038  //   The process for determining whether an operand expression E1 of type T1
2039  //   can be converted to match an operand expression E2 of type T2 is defined
2040  //   as follows:
2041  //   -- If E2 is an lvalue:
2042  bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2043  if (ToIsLvalue) {
2044    //   E1 can be converted to match E2 if E1 can be implicitly converted to
2045    //   type "lvalue reference to T2", subject to the constraint that in the
2046    //   conversion the reference must bind directly to E1.
2047    QualType T = Self.Context.getLValueReferenceType(ToType);
2048    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2049
2050    InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2051    if (InitSeq.isDirectReferenceBinding()) {
2052      ToType = T;
2053      HaveConversion = true;
2054      return false;
2055    }
2056
2057    if (InitSeq.isAmbiguous())
2058      return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2059  }
2060
2061  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
2062  //      -- if E1 and E2 have class type, and the underlying class types are
2063  //         the same or one is a base class of the other:
2064  QualType FTy = From->getType();
2065  QualType TTy = To->getType();
2066  const RecordType *FRec = FTy->getAs<RecordType>();
2067  const RecordType *TRec = TTy->getAs<RecordType>();
2068  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2069                       Self.IsDerivedFrom(FTy, TTy);
2070  if (FRec && TRec &&
2071      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
2072    //         E1 can be converted to match E2 if the class of T2 is the
2073    //         same type as, or a base class of, the class of T1, and
2074    //         [cv2 > cv1].
2075    if (FRec == TRec || FDerivedFromT) {
2076      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
2077        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2078        InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2079        if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2080          HaveConversion = true;
2081          return false;
2082        }
2083
2084        if (InitSeq.isAmbiguous())
2085          return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2086      }
2087    }
2088
2089    return false;
2090  }
2091
2092  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
2093  //        implicitly converted to the type that expression E2 would have
2094  //        if E2 were converted to an rvalue (or the type it has, if E2 is
2095  //        an rvalue).
2096  //
2097  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2098  // to the array-to-pointer or function-to-pointer conversions.
2099  if (!TTy->getAs<TagType>())
2100    TTy = TTy.getUnqualifiedType();
2101
2102  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2103  InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2104  HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2105  ToType = TTy;
2106  if (InitSeq.isAmbiguous())
2107    return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2108
2109  return false;
2110}
2111
2112/// \brief Try to find a common type for two according to C++0x 5.16p5.
2113///
2114/// This is part of the parameter validation for the ? operator. If either
2115/// value operand is a class type, overload resolution is used to find a
2116/// conversion to a common type.
2117static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2118                                    SourceLocation Loc) {
2119  Expr *Args[2] = { LHS, RHS };
2120  OverloadCandidateSet CandidateSet(Loc);
2121  Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
2122
2123  OverloadCandidateSet::iterator Best;
2124  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
2125    case OR_Success:
2126      // We found a match. Perform the conversions on the arguments and move on.
2127      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
2128                                         Best->Conversions[0], Sema::AA_Converting) ||
2129          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
2130                                         Best->Conversions[1], Sema::AA_Converting))
2131        break;
2132      return false;
2133
2134    case OR_No_Viable_Function:
2135      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2136        << LHS->getType() << RHS->getType()
2137        << LHS->getSourceRange() << RHS->getSourceRange();
2138      return true;
2139
2140    case OR_Ambiguous:
2141      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2142        << LHS->getType() << RHS->getType()
2143        << LHS->getSourceRange() << RHS->getSourceRange();
2144      // FIXME: Print the possible common types by printing the return types of
2145      // the viable candidates.
2146      break;
2147
2148    case OR_Deleted:
2149      assert(false && "Conditional operator has only built-in overloads");
2150      break;
2151  }
2152  return true;
2153}
2154
2155/// \brief Perform an "extended" implicit conversion as returned by
2156/// TryClassUnification.
2157static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2158  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2159  InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2160                                                           SourceLocation());
2161  InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2162  Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2163                                    Sema::MultiExprArg(Self, (void **)&E, 1));
2164  if (Result.isInvalid())
2165    return true;
2166
2167  E = Result.takeAs<Expr>();
2168  return false;
2169}
2170
2171/// \brief Check the operands of ?: under C++ semantics.
2172///
2173/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2174/// extension. In this case, LHS == Cond. (But they're not aliases.)
2175QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2176                                           SourceLocation QuestionLoc) {
2177  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2178  // interface pointers.
2179
2180  // C++0x 5.16p1
2181  //   The first expression is contextually converted to bool.
2182  if (!Cond->isTypeDependent()) {
2183    if (CheckCXXBooleanCondition(Cond))
2184      return QualType();
2185  }
2186
2187  // Either of the arguments dependent?
2188  if (LHS->isTypeDependent() || RHS->isTypeDependent())
2189    return Context.DependentTy;
2190
2191  // C++0x 5.16p2
2192  //   If either the second or the third operand has type (cv) void, ...
2193  QualType LTy = LHS->getType();
2194  QualType RTy = RHS->getType();
2195  bool LVoid = LTy->isVoidType();
2196  bool RVoid = RTy->isVoidType();
2197  if (LVoid || RVoid) {
2198    //   ... then the [l2r] conversions are performed on the second and third
2199    //   operands ...
2200    DefaultFunctionArrayLvalueConversion(LHS);
2201    DefaultFunctionArrayLvalueConversion(RHS);
2202    LTy = LHS->getType();
2203    RTy = RHS->getType();
2204
2205    //   ... and one of the following shall hold:
2206    //   -- The second or the third operand (but not both) is a throw-
2207    //      expression; the result is of the type of the other and is an rvalue.
2208    bool LThrow = isa<CXXThrowExpr>(LHS);
2209    bool RThrow = isa<CXXThrowExpr>(RHS);
2210    if (LThrow && !RThrow)
2211      return RTy;
2212    if (RThrow && !LThrow)
2213      return LTy;
2214
2215    //   -- Both the second and third operands have type void; the result is of
2216    //      type void and is an rvalue.
2217    if (LVoid && RVoid)
2218      return Context.VoidTy;
2219
2220    // Neither holds, error.
2221    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2222      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2223      << LHS->getSourceRange() << RHS->getSourceRange();
2224    return QualType();
2225  }
2226
2227  // Neither is void.
2228
2229  // C++0x 5.16p3
2230  //   Otherwise, if the second and third operand have different types, and
2231  //   either has (cv) class type, and attempt is made to convert each of those
2232  //   operands to the other.
2233  if (!Context.hasSameType(LTy, RTy) &&
2234      (LTy->isRecordType() || RTy->isRecordType())) {
2235    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2236    // These return true if a single direction is already ambiguous.
2237    QualType L2RType, R2LType;
2238    bool HaveL2R, HaveR2L;
2239    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
2240      return QualType();
2241    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
2242      return QualType();
2243
2244    //   If both can be converted, [...] the program is ill-formed.
2245    if (HaveL2R && HaveR2L) {
2246      Diag(QuestionLoc, diag::err_conditional_ambiguous)
2247        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2248      return QualType();
2249    }
2250
2251    //   If exactly one conversion is possible, that conversion is applied to
2252    //   the chosen operand and the converted operands are used in place of the
2253    //   original operands for the remainder of this section.
2254    if (HaveL2R) {
2255      if (ConvertForConditional(*this, LHS, L2RType))
2256        return QualType();
2257      LTy = LHS->getType();
2258    } else if (HaveR2L) {
2259      if (ConvertForConditional(*this, RHS, R2LType))
2260        return QualType();
2261      RTy = RHS->getType();
2262    }
2263  }
2264
2265  // C++0x 5.16p4
2266  //   If the second and third operands are lvalues and have the same type,
2267  //   the result is of that type [...]
2268  bool Same = Context.hasSameType(LTy, RTy);
2269  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2270      RHS->isLvalue(Context) == Expr::LV_Valid)
2271    return LTy;
2272
2273  // C++0x 5.16p5
2274  //   Otherwise, the result is an rvalue. If the second and third operands
2275  //   do not have the same type, and either has (cv) class type, ...
2276  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2277    //   ... overload resolution is used to determine the conversions (if any)
2278    //   to be applied to the operands. If the overload resolution fails, the
2279    //   program is ill-formed.
2280    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2281      return QualType();
2282  }
2283
2284  // C++0x 5.16p6
2285  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2286  //   conversions are performed on the second and third operands.
2287  DefaultFunctionArrayLvalueConversion(LHS);
2288  DefaultFunctionArrayLvalueConversion(RHS);
2289  LTy = LHS->getType();
2290  RTy = RHS->getType();
2291
2292  //   After those conversions, one of the following shall hold:
2293  //   -- The second and third operands have the same type; the result
2294  //      is of that type. If the operands have class type, the result
2295  //      is a prvalue temporary of the result type, which is
2296  //      copy-initialized from either the second operand or the third
2297  //      operand depending on the value of the first operand.
2298  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2299    if (LTy->isRecordType()) {
2300      // The operands have class type. Make a temporary copy.
2301      InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2302      OwningExprResult LHSCopy = PerformCopyInitialization(Entity,
2303                                                           SourceLocation(),
2304                                                           Owned(LHS));
2305      if (LHSCopy.isInvalid())
2306        return QualType();
2307
2308      OwningExprResult RHSCopy = PerformCopyInitialization(Entity,
2309                                                           SourceLocation(),
2310                                                           Owned(RHS));
2311      if (RHSCopy.isInvalid())
2312        return QualType();
2313
2314      LHS = LHSCopy.takeAs<Expr>();
2315      RHS = RHSCopy.takeAs<Expr>();
2316    }
2317
2318    return LTy;
2319  }
2320
2321  // Extension: conditional operator involving vector types.
2322  if (LTy->isVectorType() || RTy->isVectorType())
2323    return CheckVectorOperands(QuestionLoc, LHS, RHS);
2324
2325  //   -- The second and third operands have arithmetic or enumeration type;
2326  //      the usual arithmetic conversions are performed to bring them to a
2327  //      common type, and the result is of that type.
2328  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2329    UsualArithmeticConversions(LHS, RHS);
2330    return LHS->getType();
2331  }
2332
2333  //   -- The second and third operands have pointer type, or one has pointer
2334  //      type and the other is a null pointer constant; pointer conversions
2335  //      and qualification conversions are performed to bring them to their
2336  //      composite pointer type. The result is of the composite pointer type.
2337  //   -- The second and third operands have pointer to member type, or one has
2338  //      pointer to member type and the other is a null pointer constant;
2339  //      pointer to member conversions and qualification conversions are
2340  //      performed to bring them to a common type, whose cv-qualification
2341  //      shall match the cv-qualification of either the second or the third
2342  //      operand. The result is of the common type.
2343  bool NonStandardCompositeType = false;
2344  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
2345                              isSFINAEContext()? 0 : &NonStandardCompositeType);
2346  if (!Composite.isNull()) {
2347    if (NonStandardCompositeType)
2348      Diag(QuestionLoc,
2349           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2350        << LTy << RTy << Composite
2351        << LHS->getSourceRange() << RHS->getSourceRange();
2352
2353    return Composite;
2354  }
2355
2356  // Similarly, attempt to find composite type of two objective-c pointers.
2357  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2358  if (!Composite.isNull())
2359    return Composite;
2360
2361  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2362    << LHS->getType() << RHS->getType()
2363    << LHS->getSourceRange() << RHS->getSourceRange();
2364  return QualType();
2365}
2366
2367/// \brief Find a merged pointer type and convert the two expressions to it.
2368///
2369/// This finds the composite pointer type (or member pointer type) for @p E1
2370/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2371/// type and returns it.
2372/// It does not emit diagnostics.
2373///
2374/// \param Loc The location of the operator requiring these two expressions to
2375/// be converted to the composite pointer type.
2376///
2377/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2378/// a non-standard (but still sane) composite type to which both expressions
2379/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2380/// will be set true.
2381QualType Sema::FindCompositePointerType(SourceLocation Loc,
2382                                        Expr *&E1, Expr *&E2,
2383                                        bool *NonStandardCompositeType) {
2384  if (NonStandardCompositeType)
2385    *NonStandardCompositeType = false;
2386
2387  assert(getLangOptions().CPlusPlus && "This function assumes C++");
2388  QualType T1 = E1->getType(), T2 = E2->getType();
2389
2390  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2391      !T2->isAnyPointerType() && !T2->isMemberPointerType())
2392   return QualType();
2393
2394  // C++0x 5.9p2
2395  //   Pointer conversions and qualification conversions are performed on
2396  //   pointer operands to bring them to their composite pointer type. If
2397  //   one operand is a null pointer constant, the composite pointer type is
2398  //   the type of the other operand.
2399  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2400    if (T2->isMemberPointerType())
2401      ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2402    else
2403      ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
2404    return T2;
2405  }
2406  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2407    if (T1->isMemberPointerType())
2408      ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2409    else
2410      ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
2411    return T1;
2412  }
2413
2414  // Now both have to be pointers or member pointers.
2415  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2416      (!T2->isPointerType() && !T2->isMemberPointerType()))
2417    return QualType();
2418
2419  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
2420  //   the other has type "pointer to cv2 T" and the composite pointer type is
2421  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2422  //   Otherwise, the composite pointer type is a pointer type similar to the
2423  //   type of one of the operands, with a cv-qualification signature that is
2424  //   the union of the cv-qualification signatures of the operand types.
2425  // In practice, the first part here is redundant; it's subsumed by the second.
2426  // What we do here is, we build the two possible composite types, and try the
2427  // conversions in both directions. If only one works, or if the two composite
2428  // types are the same, we have succeeded.
2429  // FIXME: extended qualifiers?
2430  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2431  QualifierVector QualifierUnion;
2432  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2433      ContainingClassVector;
2434  ContainingClassVector MemberOfClass;
2435  QualType Composite1 = Context.getCanonicalType(T1),
2436           Composite2 = Context.getCanonicalType(T2);
2437  unsigned NeedConstBefore = 0;
2438  do {
2439    const PointerType *Ptr1, *Ptr2;
2440    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2441        (Ptr2 = Composite2->getAs<PointerType>())) {
2442      Composite1 = Ptr1->getPointeeType();
2443      Composite2 = Ptr2->getPointeeType();
2444
2445      // If we're allowed to create a non-standard composite type, keep track
2446      // of where we need to fill in additional 'const' qualifiers.
2447      if (NonStandardCompositeType &&
2448          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2449        NeedConstBefore = QualifierUnion.size();
2450
2451      QualifierUnion.push_back(
2452                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2453      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2454      continue;
2455    }
2456
2457    const MemberPointerType *MemPtr1, *MemPtr2;
2458    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2459        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2460      Composite1 = MemPtr1->getPointeeType();
2461      Composite2 = MemPtr2->getPointeeType();
2462
2463      // If we're allowed to create a non-standard composite type, keep track
2464      // of where we need to fill in additional 'const' qualifiers.
2465      if (NonStandardCompositeType &&
2466          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2467        NeedConstBefore = QualifierUnion.size();
2468
2469      QualifierUnion.push_back(
2470                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2471      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2472                                             MemPtr2->getClass()));
2473      continue;
2474    }
2475
2476    // FIXME: block pointer types?
2477
2478    // Cannot unwrap any more types.
2479    break;
2480  } while (true);
2481
2482  if (NeedConstBefore && NonStandardCompositeType) {
2483    // Extension: Add 'const' to qualifiers that come before the first qualifier
2484    // mismatch, so that our (non-standard!) composite type meets the
2485    // requirements of C++ [conv.qual]p4 bullet 3.
2486    for (unsigned I = 0; I != NeedConstBefore; ++I) {
2487      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2488        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2489        *NonStandardCompositeType = true;
2490      }
2491    }
2492  }
2493
2494  // Rewrap the composites as pointers or member pointers with the union CVRs.
2495  ContainingClassVector::reverse_iterator MOC
2496    = MemberOfClass.rbegin();
2497  for (QualifierVector::reverse_iterator
2498         I = QualifierUnion.rbegin(),
2499         E = QualifierUnion.rend();
2500       I != E; (void)++I, ++MOC) {
2501    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
2502    if (MOC->first && MOC->second) {
2503      // Rebuild member pointer type
2504      Composite1 = Context.getMemberPointerType(
2505                                    Context.getQualifiedType(Composite1, Quals),
2506                                    MOC->first);
2507      Composite2 = Context.getMemberPointerType(
2508                                    Context.getQualifiedType(Composite2, Quals),
2509                                    MOC->second);
2510    } else {
2511      // Rebuild pointer type
2512      Composite1
2513        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2514      Composite2
2515        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
2516    }
2517  }
2518
2519  // Try to convert to the first composite pointer type.
2520  InitializedEntity Entity1
2521    = InitializedEntity::InitializeTemporary(Composite1);
2522  InitializationKind Kind
2523    = InitializationKind::CreateCopy(Loc, SourceLocation());
2524  InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2525  InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
2526
2527  if (E1ToC1 && E2ToC1) {
2528    // Conversion to Composite1 is viable.
2529    if (!Context.hasSameType(Composite1, Composite2)) {
2530      // Composite2 is a different type from Composite1. Check whether
2531      // Composite2 is also viable.
2532      InitializedEntity Entity2
2533        = InitializedEntity::InitializeTemporary(Composite2);
2534      InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2535      InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2536      if (E1ToC2 && E2ToC2) {
2537        // Both Composite1 and Composite2 are viable and are different;
2538        // this is an ambiguity.
2539        return QualType();
2540      }
2541    }
2542
2543    // Convert E1 to Composite1
2544    OwningExprResult E1Result
2545      = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2546    if (E1Result.isInvalid())
2547      return QualType();
2548    E1 = E1Result.takeAs<Expr>();
2549
2550    // Convert E2 to Composite1
2551    OwningExprResult E2Result
2552      = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2553    if (E2Result.isInvalid())
2554      return QualType();
2555    E2 = E2Result.takeAs<Expr>();
2556
2557    return Composite1;
2558  }
2559
2560  // Check whether Composite2 is viable.
2561  InitializedEntity Entity2
2562    = InitializedEntity::InitializeTemporary(Composite2);
2563  InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2564  InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2565  if (!E1ToC2 || !E2ToC2)
2566    return QualType();
2567
2568  // Convert E1 to Composite2
2569  OwningExprResult E1Result
2570    = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2571  if (E1Result.isInvalid())
2572    return QualType();
2573  E1 = E1Result.takeAs<Expr>();
2574
2575  // Convert E2 to Composite2
2576  OwningExprResult E2Result
2577    = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2578  if (E2Result.isInvalid())
2579    return QualType();
2580  E2 = E2Result.takeAs<Expr>();
2581
2582  return Composite2;
2583}
2584
2585Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
2586  if (!Context.getLangOptions().CPlusPlus)
2587    return Owned(E);
2588
2589  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2590
2591  const RecordType *RT = E->getType()->getAs<RecordType>();
2592  if (!RT)
2593    return Owned(E);
2594
2595  // If this is the result of a call expression, our source might
2596  // actually be a reference, in which case we shouldn't bind.
2597  if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2598    QualType Ty = CE->getCallee()->getType();
2599    if (const PointerType *PT = Ty->getAs<PointerType>())
2600      Ty = PT->getPointeeType();
2601    else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2602      Ty = BPT->getPointeeType();
2603
2604    const FunctionType *FTy = Ty->getAs<FunctionType>();
2605    if (FTy->getResultType()->isReferenceType())
2606      return Owned(E);
2607  }
2608
2609  // That should be enough to guarantee that this type is complete.
2610  // If it has a trivial destructor, we can avoid the extra copy.
2611  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2612  if (RD->hasTrivialDestructor())
2613    return Owned(E);
2614
2615  CXXTemporary *Temp = CXXTemporary::Create(Context,
2616                                            RD->getDestructor(Context));
2617  ExprTemporaries.push_back(Temp);
2618  if (CXXDestructorDecl *Destructor =
2619        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
2620    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
2621    CheckDestructorAccess(E->getExprLoc(), Destructor,
2622                          PDiag(diag::err_access_dtor_temp)
2623                            << E->getType());
2624  }
2625  // FIXME: Add the temporary to the temporaries vector.
2626  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2627}
2628
2629Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
2630  assert(SubExpr && "sub expression can't be null!");
2631
2632  // Check any implicit conversions within the expression.
2633  CheckImplicitConversions(SubExpr);
2634
2635  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2636  assert(ExprTemporaries.size() >= FirstTemporary);
2637  if (ExprTemporaries.size() == FirstTemporary)
2638    return SubExpr;
2639
2640  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
2641                                           &ExprTemporaries[FirstTemporary],
2642                                       ExprTemporaries.size() - FirstTemporary);
2643  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2644                        ExprTemporaries.end());
2645
2646  return E;
2647}
2648
2649Sema::OwningExprResult
2650Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2651  if (SubExpr.isInvalid())
2652    return ExprError();
2653
2654  return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2655}
2656
2657FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2658  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2659  assert(ExprTemporaries.size() >= FirstTemporary);
2660
2661  unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2662  CXXTemporary **Temporaries =
2663    NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2664
2665  FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2666
2667  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2668                        ExprTemporaries.end());
2669
2670  return E;
2671}
2672
2673Sema::OwningExprResult
2674Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2675                                   tok::TokenKind OpKind, TypeTy *&ObjectType,
2676                                   bool &MayBePseudoDestructor) {
2677  // Since this might be a postfix expression, get rid of ParenListExprs.
2678  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2679
2680  Expr *BaseExpr = (Expr*)Base.get();
2681  assert(BaseExpr && "no record expansion");
2682
2683  QualType BaseType = BaseExpr->getType();
2684  MayBePseudoDestructor = false;
2685  if (BaseType->isDependentType()) {
2686    // If we have a pointer to a dependent type and are using the -> operator,
2687    // the object type is the type that the pointer points to. We might still
2688    // have enough information about that type to do something useful.
2689    if (OpKind == tok::arrow)
2690      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2691        BaseType = Ptr->getPointeeType();
2692
2693    ObjectType = BaseType.getAsOpaquePtr();
2694    MayBePseudoDestructor = true;
2695    return move(Base);
2696  }
2697
2698  // C++ [over.match.oper]p8:
2699  //   [...] When operator->returns, the operator-> is applied  to the value
2700  //   returned, with the original second operand.
2701  if (OpKind == tok::arrow) {
2702    // The set of types we've considered so far.
2703    llvm::SmallPtrSet<CanQualType,8> CTypes;
2704    llvm::SmallVector<SourceLocation, 8> Locations;
2705    CTypes.insert(Context.getCanonicalType(BaseType));
2706
2707    while (BaseType->isRecordType()) {
2708      Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
2709      BaseExpr = (Expr*)Base.get();
2710      if (BaseExpr == NULL)
2711        return ExprError();
2712      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
2713        Locations.push_back(OpCall->getDirectCallee()->getLocation());
2714      BaseType = BaseExpr->getType();
2715      CanQualType CBaseType = Context.getCanonicalType(BaseType);
2716      if (!CTypes.insert(CBaseType)) {
2717        Diag(OpLoc, diag::err_operator_arrow_circular);
2718        for (unsigned i = 0; i < Locations.size(); i++)
2719          Diag(Locations[i], diag::note_declared_at);
2720        return ExprError();
2721      }
2722    }
2723
2724    if (BaseType->isPointerType())
2725      BaseType = BaseType->getPointeeType();
2726  }
2727
2728  // We could end up with various non-record types here, such as extended
2729  // vector types or Objective-C interfaces. Just return early and let
2730  // ActOnMemberReferenceExpr do the work.
2731  if (!BaseType->isRecordType()) {
2732    // C++ [basic.lookup.classref]p2:
2733    //   [...] If the type of the object expression is of pointer to scalar
2734    //   type, the unqualified-id is looked up in the context of the complete
2735    //   postfix-expression.
2736    //
2737    // This also indicates that we should be parsing a
2738    // pseudo-destructor-name.
2739    ObjectType = 0;
2740    MayBePseudoDestructor = true;
2741    return move(Base);
2742  }
2743
2744  // The object type must be complete (or dependent).
2745  if (!BaseType->isDependentType() &&
2746      RequireCompleteType(OpLoc, BaseType,
2747                          PDiag(diag::err_incomplete_member_access)))
2748    return ExprError();
2749
2750  // C++ [basic.lookup.classref]p2:
2751  //   If the id-expression in a class member access (5.2.5) is an
2752  //   unqualified-id, and the type of the object expression is of a class
2753  //   type C (or of pointer to a class type C), the unqualified-id is looked
2754  //   up in the scope of class C. [...]
2755  ObjectType = BaseType.getAsOpaquePtr();
2756  return move(Base);
2757}
2758
2759Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2760                                                   ExprArg MemExpr) {
2761  Expr *E = (Expr *) MemExpr.get();
2762  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2763  Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2764    << isa<CXXPseudoDestructorExpr>(E)
2765    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
2766
2767  return ActOnCallExpr(/*Scope*/ 0,
2768                       move(MemExpr),
2769                       /*LPLoc*/ ExpectedLParenLoc,
2770                       Sema::MultiExprArg(*this, 0, 0),
2771                       /*CommaLocs*/ 0,
2772                       /*RPLoc*/ ExpectedLParenLoc);
2773}
2774
2775Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2776                                                       SourceLocation OpLoc,
2777                                                       tok::TokenKind OpKind,
2778                                                       const CXXScopeSpec &SS,
2779                                                 TypeSourceInfo *ScopeTypeInfo,
2780                                                       SourceLocation CCLoc,
2781                                                       SourceLocation TildeLoc,
2782                                         PseudoDestructorTypeStorage Destructed,
2783                                                       bool HasTrailingLParen) {
2784  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
2785
2786  // C++ [expr.pseudo]p2:
2787  //   The left-hand side of the dot operator shall be of scalar type. The
2788  //   left-hand side of the arrow operator shall be of pointer to scalar type.
2789  //   This scalar type is the object type.
2790  Expr *BaseE = (Expr *)Base.get();
2791  QualType ObjectType = BaseE->getType();
2792  if (OpKind == tok::arrow) {
2793    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2794      ObjectType = Ptr->getPointeeType();
2795    } else if (!BaseE->isTypeDependent()) {
2796      // The user wrote "p->" when she probably meant "p."; fix it.
2797      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2798        << ObjectType << true
2799        << FixItHint::CreateReplacement(OpLoc, ".");
2800      if (isSFINAEContext())
2801        return ExprError();
2802
2803      OpKind = tok::period;
2804    }
2805  }
2806
2807  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2808    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2809      << ObjectType << BaseE->getSourceRange();
2810    return ExprError();
2811  }
2812
2813  // C++ [expr.pseudo]p2:
2814  //   [...] The cv-unqualified versions of the object type and of the type
2815  //   designated by the pseudo-destructor-name shall be the same type.
2816  if (DestructedTypeInfo) {
2817    QualType DestructedType = DestructedTypeInfo->getType();
2818    SourceLocation DestructedTypeStart
2819      = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
2820    if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2821        !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2822      Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2823        << ObjectType << DestructedType << BaseE->getSourceRange()
2824        << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
2825
2826      // Recover by setting the destructed type to the object type.
2827      DestructedType = ObjectType;
2828      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2829                                                           DestructedTypeStart);
2830      Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2831    }
2832  }
2833
2834  // C++ [expr.pseudo]p2:
2835  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2836  //   form
2837  //
2838  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2839  //
2840  //   shall designate the same scalar type.
2841  if (ScopeTypeInfo) {
2842    QualType ScopeType = ScopeTypeInfo->getType();
2843    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2844        !Context.hasSameType(ScopeType, ObjectType)) {
2845
2846      Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
2847           diag::err_pseudo_dtor_type_mismatch)
2848        << ObjectType << ScopeType << BaseE->getSourceRange()
2849        << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
2850
2851      ScopeType = QualType();
2852      ScopeTypeInfo = 0;
2853    }
2854  }
2855
2856  OwningExprResult Result
2857    = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2858                                                  Base.takeAs<Expr>(),
2859                                                  OpKind == tok::arrow,
2860                                                  OpLoc,
2861                                       (NestedNameSpecifier *) SS.getScopeRep(),
2862                                                  SS.getRange(),
2863                                                  ScopeTypeInfo,
2864                                                  CCLoc,
2865                                                  TildeLoc,
2866                                                  Destructed));
2867
2868  if (HasTrailingLParen)
2869    return move(Result);
2870
2871  return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
2872}
2873
2874Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2875                                                       SourceLocation OpLoc,
2876                                                       tok::TokenKind OpKind,
2877                                                       CXXScopeSpec &SS,
2878                                                  UnqualifiedId &FirstTypeName,
2879                                                       SourceLocation CCLoc,
2880                                                       SourceLocation TildeLoc,
2881                                                 UnqualifiedId &SecondTypeName,
2882                                                       bool HasTrailingLParen) {
2883  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2884          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2885         "Invalid first type name in pseudo-destructor");
2886  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2887          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2888         "Invalid second type name in pseudo-destructor");
2889
2890  Expr *BaseE = (Expr *)Base.get();
2891
2892  // C++ [expr.pseudo]p2:
2893  //   The left-hand side of the dot operator shall be of scalar type. The
2894  //   left-hand side of the arrow operator shall be of pointer to scalar type.
2895  //   This scalar type is the object type.
2896  QualType ObjectType = BaseE->getType();
2897  if (OpKind == tok::arrow) {
2898    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2899      ObjectType = Ptr->getPointeeType();
2900    } else if (!ObjectType->isDependentType()) {
2901      // The user wrote "p->" when she probably meant "p."; fix it.
2902      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2903        << ObjectType << true
2904        << FixItHint::CreateReplacement(OpLoc, ".");
2905      if (isSFINAEContext())
2906        return ExprError();
2907
2908      OpKind = tok::period;
2909    }
2910  }
2911
2912  // Compute the object type that we should use for name lookup purposes. Only
2913  // record types and dependent types matter.
2914  void *ObjectTypePtrForLookup = 0;
2915  if (!SS.isSet()) {
2916    ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2917    if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2918      ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2919  }
2920
2921  // Convert the name of the type being destructed (following the ~) into a
2922  // type (with source-location information).
2923  QualType DestructedType;
2924  TypeSourceInfo *DestructedTypeInfo = 0;
2925  PseudoDestructorTypeStorage Destructed;
2926  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2927    TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2928                            SecondTypeName.StartLocation,
2929                            S, &SS, true, ObjectTypePtrForLookup);
2930    if (!T &&
2931        ((SS.isSet() && !computeDeclContext(SS, false)) ||
2932         (!SS.isSet() && ObjectType->isDependentType()))) {
2933      // The name of the type being destroyed is a dependent name, and we
2934      // couldn't find anything useful in scope. Just store the identifier and
2935      // it's location, and we'll perform (qualified) name lookup again at
2936      // template instantiation time.
2937      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2938                                               SecondTypeName.StartLocation);
2939    } else if (!T) {
2940      Diag(SecondTypeName.StartLocation,
2941           diag::err_pseudo_dtor_destructor_non_type)
2942        << SecondTypeName.Identifier << ObjectType;
2943      if (isSFINAEContext())
2944        return ExprError();
2945
2946      // Recover by assuming we had the right type all along.
2947      DestructedType = ObjectType;
2948    } else
2949      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
2950  } else {
2951    // Resolve the template-id to a type.
2952    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
2953    ASTTemplateArgsPtr TemplateArgsPtr(*this,
2954                                       TemplateId->getTemplateArgs(),
2955                                       TemplateId->NumArgs);
2956    TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2957                                       TemplateId->TemplateNameLoc,
2958                                       TemplateId->LAngleLoc,
2959                                       TemplateArgsPtr,
2960                                       TemplateId->RAngleLoc);
2961    if (T.isInvalid() || !T.get()) {
2962      // Recover by assuming we had the right type all along.
2963      DestructedType = ObjectType;
2964    } else
2965      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
2966  }
2967
2968  // If we've performed some kind of recovery, (re-)build the type source
2969  // information.
2970  if (!DestructedType.isNull()) {
2971    if (!DestructedTypeInfo)
2972      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
2973                                                  SecondTypeName.StartLocation);
2974    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2975  }
2976
2977  // Convert the name of the scope type (the type prior to '::') into a type.
2978  TypeSourceInfo *ScopeTypeInfo = 0;
2979  QualType ScopeType;
2980  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2981      FirstTypeName.Identifier) {
2982    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2983      TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2984                              FirstTypeName.StartLocation,
2985                              S, &SS, false, ObjectTypePtrForLookup);
2986      if (!T) {
2987        Diag(FirstTypeName.StartLocation,
2988             diag::err_pseudo_dtor_destructor_non_type)
2989          << FirstTypeName.Identifier << ObjectType;
2990
2991        if (isSFINAEContext())
2992          return ExprError();
2993
2994        // Just drop this type. It's unnecessary anyway.
2995        ScopeType = QualType();
2996      } else
2997        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
2998    } else {
2999      // Resolve the template-id to a type.
3000      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
3001      ASTTemplateArgsPtr TemplateArgsPtr(*this,
3002                                         TemplateId->getTemplateArgs(),
3003                                         TemplateId->NumArgs);
3004      TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
3005                                         TemplateId->TemplateNameLoc,
3006                                         TemplateId->LAngleLoc,
3007                                         TemplateArgsPtr,
3008                                         TemplateId->RAngleLoc);
3009      if (T.isInvalid() || !T.get()) {
3010        // Recover by dropping this type.
3011        ScopeType = QualType();
3012      } else
3013        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
3014    }
3015  }
3016
3017  if (!ScopeType.isNull() && !ScopeTypeInfo)
3018    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3019                                                  FirstTypeName.StartLocation);
3020
3021
3022  return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
3023                                   ScopeTypeInfo, CCLoc, TildeLoc,
3024                                   Destructed, HasTrailingLParen);
3025}
3026
3027CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
3028                                                NamedDecl *FoundDecl,
3029                                                CXXMethodDecl *Method) {
3030  if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3031                                          FoundDecl, Method))
3032    assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3033
3034  MemberExpr *ME =
3035      new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3036                               SourceLocation(), Method->getType());
3037  QualType ResultType = Method->getResultType().getNonReferenceType();
3038  MarkDeclarationReferenced(Exp->getLocStart(), Method);
3039  CXXMemberCallExpr *CE =
3040    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3041                                    Exp->getLocEnd());
3042  return CE;
3043}
3044
3045Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
3046  Expr *FullExpr = Arg.takeAs<Expr>();
3047  if (FullExpr)
3048    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
3049  else
3050    return ExprError();
3051
3052  return Owned(FullExpr);
3053}
3054