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