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