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