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