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