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