SemaExprCXX.cpp revision ccb4ecf9b11d7b652515780253253db976d0447f
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/Sema/DeclSpec.h"
16#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
18#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "clang/Sema/TemplateDeduction.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/CXXInheritance.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/Preprocessor.h"
30#include "llvm/ADT/STLExtras.h"
31using namespace clang;
32using namespace sema;
33
34ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
35                                   IdentifierInfo &II,
36                                   SourceLocation NameLoc,
37                                   Scope *S, CXXScopeSpec &SS,
38                                   ParsedType ObjectTypePtr,
39                                   bool EnteringContext) {
40  // Determine where to perform name lookup.
41
42  // FIXME: This area of the standard is very messy, and the current
43  // wording is rather unclear about which scopes we search for the
44  // destructor name; see core issues 399 and 555. Issue 399 in
45  // particular shows where the current description of destructor name
46  // lookup is completely out of line with existing practice, e.g.,
47  // this appears to be ill-formed:
48  //
49  //   namespace N {
50  //     template <typename T> struct S {
51  //       ~S();
52  //     };
53  //   }
54  //
55  //   void f(N::S<int>* s) {
56  //     s->N::S<int>::~S();
57  //   }
58  //
59  // See also PR6358 and PR6359.
60  // For this reason, we're currently only doing the C++03 version of this
61  // code; the C++0x version has to wait until we get a proper spec.
62  QualType SearchType;
63  DeclContext *LookupCtx = 0;
64  bool isDependent = false;
65  bool LookInScope = false;
66
67  // If we have an object type, it's because we are in a
68  // pseudo-destructor-expression or a member access expression, and
69  // we know what type we're looking for.
70  if (ObjectTypePtr)
71    SearchType = GetTypeFromParser(ObjectTypePtr);
72
73  if (SS.isSet()) {
74    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
75
76    bool AlreadySearched = false;
77    bool LookAtPrefix = true;
78    // C++ [basic.lookup.qual]p6:
79    //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
80    //   the type-names are looked up as types in the scope designated by the
81    //   nested-name-specifier. In a qualified-id of the form:
82    //
83    //     ::[opt] nested-name-specifier  ~ class-name
84    //
85    //   where the nested-name-specifier designates a namespace scope, and in
86    //   a qualified-id of the form:
87    //
88    //     ::opt nested-name-specifier class-name ::  ~ class-name
89    //
90    //   the class-names are looked up as types in the scope designated by
91    //   the nested-name-specifier.
92    //
93    // Here, we check the first case (completely) and determine whether the
94    // code below is permitted to look at the prefix of the
95    // nested-name-specifier.
96    DeclContext *DC = computeDeclContext(SS, EnteringContext);
97    if (DC && DC->isFileContext()) {
98      AlreadySearched = true;
99      LookupCtx = DC;
100      isDependent = false;
101    } else if (DC && isa<CXXRecordDecl>(DC))
102      LookAtPrefix = false;
103
104    // The second case from the C++03 rules quoted further above.
105    NestedNameSpecifier *Prefix = 0;
106    if (AlreadySearched) {
107      // Nothing left to do.
108    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
109      CXXScopeSpec PrefixSS;
110      PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
111      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
112      isDependent = isDependentScopeSpecifier(PrefixSS);
113    } else if (ObjectTypePtr) {
114      LookupCtx = computeDeclContext(SearchType);
115      isDependent = SearchType->isDependentType();
116    } else {
117      LookupCtx = computeDeclContext(SS, EnteringContext);
118      isDependent = LookupCtx && LookupCtx->isDependentContext();
119    }
120
121    LookInScope = false;
122  } else if (ObjectTypePtr) {
123    // C++ [basic.lookup.classref]p3:
124    //   If the unqualified-id is ~type-name, the type-name is looked up
125    //   in the context of the entire postfix-expression. If the type T
126    //   of the object expression is of a class type C, the type-name is
127    //   also looked up in the scope of class C. At least one of the
128    //   lookups shall find a name that refers to (possibly
129    //   cv-qualified) T.
130    LookupCtx = computeDeclContext(SearchType);
131    isDependent = SearchType->isDependentType();
132    assert((isDependent || !SearchType->isIncompleteType()) &&
133           "Caller should have completed object type");
134
135    LookInScope = true;
136  } else {
137    // Perform lookup into the current scope (only).
138    LookInScope = true;
139  }
140
141  TypeDecl *NonMatchingTypeDecl = 0;
142  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
143  for (unsigned Step = 0; Step != 2; ++Step) {
144    // Look for the name first in the computed lookup context (if we
145    // have one) and, if that fails to find a match, in the scope (if
146    // we're allowed to look there).
147    Found.clear();
148    if (Step == 0 && LookupCtx)
149      LookupQualifiedName(Found, LookupCtx);
150    else if (Step == 1 && LookInScope && S)
151      LookupName(Found, S);
152    else
153      continue;
154
155    // FIXME: Should we be suppressing ambiguities here?
156    if (Found.isAmbiguous())
157      return ParsedType();
158
159    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
160      QualType T = Context.getTypeDeclType(Type);
161
162      if (SearchType.isNull() || SearchType->isDependentType() ||
163          Context.hasSameUnqualifiedType(T, SearchType)) {
164        // We found our type!
165
166        return ParsedType::make(T);
167      }
168
169      if (!SearchType.isNull())
170        NonMatchingTypeDecl = Type;
171    }
172
173    // If the name that we found is a class template name, and it is
174    // the same name as the template name in the last part of the
175    // nested-name-specifier (if present) or the object type, then
176    // this is the destructor for that class.
177    // FIXME: This is a workaround until we get real drafting for core
178    // issue 399, for which there isn't even an obvious direction.
179    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
180      QualType MemberOfType;
181      if (SS.isSet()) {
182        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
183          // Figure out the type of the context, if it has one.
184          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
185            MemberOfType = Context.getTypeDeclType(Record);
186        }
187      }
188      if (MemberOfType.isNull())
189        MemberOfType = SearchType;
190
191      if (MemberOfType.isNull())
192        continue;
193
194      // We're referring into a class template specialization. If the
195      // class template we found is the same as the template being
196      // specialized, we found what we are looking for.
197      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
198        if (ClassTemplateSpecializationDecl *Spec
199              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
200          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
201                Template->getCanonicalDecl())
202            return ParsedType::make(MemberOfType);
203        }
204
205        continue;
206      }
207
208      // We're referring to an unresolved class template
209      // specialization. Determine whether we class template we found
210      // is the same as the template being specialized or, if we don't
211      // know which template is being specialized, that it at least
212      // has the same name.
213      if (const TemplateSpecializationType *SpecType
214            = MemberOfType->getAs<TemplateSpecializationType>()) {
215        TemplateName SpecName = SpecType->getTemplateName();
216
217        // The class template we found is the same template being
218        // specialized.
219        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
220          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
221            return ParsedType::make(MemberOfType);
222
223          continue;
224        }
225
226        // The class template we found has the same name as the
227        // (dependent) template name being specialized.
228        if (DependentTemplateName *DepTemplate
229                                    = SpecName.getAsDependentTemplateName()) {
230          if (DepTemplate->isIdentifier() &&
231              DepTemplate->getIdentifier() == Template->getIdentifier())
232            return ParsedType::make(MemberOfType);
233
234          continue;
235        }
236      }
237    }
238  }
239
240  if (isDependent) {
241    // We didn't find our type, but that's okay: it's dependent
242    // anyway.
243
244    // FIXME: What if we have no nested-name-specifier?
245    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
246                                   SS.getWithLocInContext(Context),
247                                   II, NameLoc);
248    return ParsedType::make(T);
249  }
250
251  if (NonMatchingTypeDecl) {
252    QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
253    Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
254      << T << SearchType;
255    Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
256      << T;
257  } else if (ObjectTypePtr)
258    Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
259      << &II;
260  else
261    Diag(NameLoc, diag::err_destructor_class_name);
262
263  return ParsedType();
264}
265
266/// \brief Build a C++ typeid expression with a type operand.
267ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
268                                SourceLocation TypeidLoc,
269                                TypeSourceInfo *Operand,
270                                SourceLocation RParenLoc) {
271  // C++ [expr.typeid]p4:
272  //   The top-level cv-qualifiers of the lvalue expression or the type-id
273  //   that is the operand of typeid are always ignored.
274  //   If the type of the type-id is a class type or a reference to a class
275  //   type, the class shall be completely-defined.
276  Qualifiers Quals;
277  QualType T
278    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
279                                      Quals);
280  if (T->getAs<RecordType>() &&
281      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
282    return ExprError();
283
284  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
285                                           Operand,
286                                           SourceRange(TypeidLoc, RParenLoc)));
287}
288
289/// \brief Build a C++ typeid expression with an expression operand.
290ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
291                                SourceLocation TypeidLoc,
292                                Expr *E,
293                                SourceLocation RParenLoc) {
294  bool isUnevaluatedOperand = true;
295  if (E && !E->isTypeDependent()) {
296    QualType T = E->getType();
297    if (const RecordType *RecordT = T->getAs<RecordType>()) {
298      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
299      // C++ [expr.typeid]p3:
300      //   [...] If the type of the expression is a class type, the class
301      //   shall be completely-defined.
302      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
303        return ExprError();
304
305      // C++ [expr.typeid]p3:
306      //   When typeid is applied to an expression other than an glvalue of a
307      //   polymorphic class type [...] [the] expression is an unevaluated
308      //   operand. [...]
309      if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
310        isUnevaluatedOperand = false;
311
312        // We require a vtable to query the type at run time.
313        MarkVTableUsed(TypeidLoc, RecordD);
314      }
315    }
316
317    // C++ [expr.typeid]p4:
318    //   [...] If the type of the type-id is a reference to a possibly
319    //   cv-qualified type, the result of the typeid expression refers to a
320    //   std::type_info object representing the cv-unqualified referenced
321    //   type.
322    Qualifiers Quals;
323    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
324    if (!Context.hasSameType(T, UnqualT)) {
325      T = UnqualT;
326      E = ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)).take();
327    }
328  }
329
330  // If this is an unevaluated operand, clear out the set of
331  // declaration references we have been computing and eliminate any
332  // temporaries introduced in its computation.
333  if (isUnevaluatedOperand)
334    ExprEvalContexts.back().Context = Unevaluated;
335
336  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
337                                           E,
338                                           SourceRange(TypeidLoc, RParenLoc)));
339}
340
341/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
342ExprResult
343Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
344                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
345  // Find the std::type_info type.
346  if (!getStdNamespace())
347    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
348
349  if (!CXXTypeInfoDecl) {
350    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
351    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
352    LookupQualifiedName(R, getStdNamespace());
353    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
354    if (!CXXTypeInfoDecl)
355      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
356  }
357
358  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
359
360  if (isType) {
361    // The operand is a type; handle it as such.
362    TypeSourceInfo *TInfo = 0;
363    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
364                                   &TInfo);
365    if (T.isNull())
366      return ExprError();
367
368    if (!TInfo)
369      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
370
371    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
372  }
373
374  // The operand is an expression.
375  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
376}
377
378/// Retrieve the UuidAttr associated with QT.
379static UuidAttr *GetUuidAttrOfType(QualType QT) {
380  // Optionally remove one level of pointer, reference or array indirection.
381  const Type *Ty = QT.getTypePtr();;
382  if (QT->isPointerType() || QT->isReferenceType())
383    Ty = QT->getPointeeType().getTypePtr();
384  else if (QT->isArrayType())
385    Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
386
387  // Loop all class definition and declaration looking for an uuid attribute.
388  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
389  while (RD) {
390    if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
391      return Uuid;
392    RD = RD->getPreviousDeclaration();
393  }
394  return 0;
395}
396
397/// \brief Build a Microsoft __uuidof expression with a type operand.
398ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
399                                SourceLocation TypeidLoc,
400                                TypeSourceInfo *Operand,
401                                SourceLocation RParenLoc) {
402  if (!Operand->getType()->isDependentType()) {
403    if (!GetUuidAttrOfType(Operand->getType()))
404      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
405  }
406
407  // FIXME: add __uuidof semantic analysis for type operand.
408  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
409                                           Operand,
410                                           SourceRange(TypeidLoc, RParenLoc)));
411}
412
413/// \brief Build a Microsoft __uuidof expression with an expression operand.
414ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
415                                SourceLocation TypeidLoc,
416                                Expr *E,
417                                SourceLocation RParenLoc) {
418  if (!E->getType()->isDependentType()) {
419    if (!GetUuidAttrOfType(E->getType()) &&
420        !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
421      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
422  }
423  // FIXME: add __uuidof semantic analysis for type operand.
424  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
425                                           E,
426                                           SourceRange(TypeidLoc, RParenLoc)));
427}
428
429/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
430ExprResult
431Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
432                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
433  // If MSVCGuidDecl has not been cached, do the lookup.
434  if (!MSVCGuidDecl) {
435    IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
436    LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
437    LookupQualifiedName(R, Context.getTranslationUnitDecl());
438    MSVCGuidDecl = R.getAsSingle<RecordDecl>();
439    if (!MSVCGuidDecl)
440      return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
441  }
442
443  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
444
445  if (isType) {
446    // The operand is a type; handle it as such.
447    TypeSourceInfo *TInfo = 0;
448    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
449                                   &TInfo);
450    if (T.isNull())
451      return ExprError();
452
453    if (!TInfo)
454      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
455
456    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
457  }
458
459  // The operand is an expression.
460  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
461}
462
463/// ActOnCXXBoolLiteral - Parse {true,false} literals.
464ExprResult
465Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
466  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
467         "Unknown C++ Boolean value!");
468  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
469                                                Context.BoolTy, OpLoc));
470}
471
472/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
473ExprResult
474Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
475  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
476}
477
478/// ActOnCXXThrow - Parse throw expressions.
479ExprResult
480Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
481  // Don't report an error if 'throw' is used in system headers.
482  if (!getLangOptions().CXXExceptions &&
483      !getSourceManager().isInSystemHeader(OpLoc))
484    Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
485
486  if (Ex && !Ex->isTypeDependent()) {
487    ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex);
488    if (ExRes.isInvalid())
489      return ExprError();
490    Ex = ExRes.take();
491  }
492  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
493}
494
495/// CheckCXXThrowOperand - Validate the operand of a throw.
496ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E) {
497  // C++ [except.throw]p3:
498  //   A throw-expression initializes a temporary object, called the exception
499  //   object, the type of which is determined by removing any top-level
500  //   cv-qualifiers from the static type of the operand of throw and adjusting
501  //   the type from "array of T" or "function returning T" to "pointer to T"
502  //   or "pointer to function returning T", [...]
503  if (E->getType().hasQualifiers())
504    E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
505                      CastCategory(E)).take();
506
507  ExprResult Res = DefaultFunctionArrayConversion(E);
508  if (Res.isInvalid())
509    return ExprError();
510  E = Res.take();
511
512  //   If the type of the exception would be an incomplete type or a pointer
513  //   to an incomplete type other than (cv) void the program is ill-formed.
514  QualType Ty = E->getType();
515  bool isPointer = false;
516  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
517    Ty = Ptr->getPointeeType();
518    isPointer = true;
519  }
520  if (!isPointer || !Ty->isVoidType()) {
521    if (RequireCompleteType(ThrowLoc, Ty,
522                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
523                                            : diag::err_throw_incomplete)
524                              << E->getSourceRange()))
525      return ExprError();
526
527    if (RequireNonAbstractType(ThrowLoc, E->getType(),
528                               PDiag(diag::err_throw_abstract_type)
529                                 << E->getSourceRange()))
530      return ExprError();
531  }
532
533  // Initialize the exception result.  This implicitly weeds out
534  // abstract types or types with inaccessible copy constructors.
535  const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
536
537  // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
538  InitializedEntity Entity =
539      InitializedEntity::InitializeException(ThrowLoc, E->getType(),
540                                             /*NRVO=*/false);
541  Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
542                                        QualType(), E);
543  if (Res.isInvalid())
544    return ExprError();
545  E = Res.take();
546
547  // If the exception has class type, we need additional handling.
548  const RecordType *RecordTy = Ty->getAs<RecordType>();
549  if (!RecordTy)
550    return Owned(E);
551  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
552
553  // If we are throwing a polymorphic class type or pointer thereof,
554  // exception handling will make use of the vtable.
555  MarkVTableUsed(ThrowLoc, RD);
556
557  // If a pointer is thrown, the referenced object will not be destroyed.
558  if (isPointer)
559    return Owned(E);
560
561  // If the class has a non-trivial destructor, we must be able to call it.
562  if (RD->hasTrivialDestructor())
563    return Owned(E);
564
565  CXXDestructorDecl *Destructor
566    = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
567  if (!Destructor)
568    return Owned(E);
569
570  MarkDeclarationReferenced(E->getExprLoc(), Destructor);
571  CheckDestructorAccess(E->getExprLoc(), Destructor,
572                        PDiag(diag::err_access_dtor_exception) << Ty);
573  return Owned(E);
574}
575
576CXXMethodDecl *Sema::tryCaptureCXXThis() {
577  // Ignore block scopes: we can capture through them.
578  // Ignore nested enum scopes: we'll diagnose non-constant expressions
579  // where they're invalid, and other uses are legitimate.
580  // Don't ignore nested class scopes: you can't use 'this' in a local class.
581  DeclContext *DC = CurContext;
582  while (true) {
583    if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
584    else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
585    else break;
586  }
587
588  // If we're not in an instance method, error out.
589  CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
590  if (!method || !method->isInstance())
591    return 0;
592
593  // Mark that we're closing on 'this' in all the block scopes, if applicable.
594  for (unsigned idx = FunctionScopes.size() - 1;
595       isa<BlockScopeInfo>(FunctionScopes[idx]);
596       --idx)
597    cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
598
599  return method;
600}
601
602ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
603  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
604  /// is a non-lvalue expression whose value is the address of the object for
605  /// which the function is called.
606
607  CXXMethodDecl *method = tryCaptureCXXThis();
608  if (!method) return Diag(loc, diag::err_invalid_this_use);
609
610  return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
611                                         /*isImplicit=*/false));
612}
613
614ExprResult
615Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
616                                SourceLocation LParenLoc,
617                                MultiExprArg exprs,
618                                SourceLocation RParenLoc) {
619  if (!TypeRep)
620    return ExprError();
621
622  TypeSourceInfo *TInfo;
623  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
624  if (!TInfo)
625    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
626
627  return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
628}
629
630/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
631/// Can be interpreted either as function-style casting ("int(x)")
632/// or class type construction ("ClassType(x,y,z)")
633/// or creation of a value-initialized type ("int()").
634ExprResult
635Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
636                                SourceLocation LParenLoc,
637                                MultiExprArg exprs,
638                                SourceLocation RParenLoc) {
639  QualType Ty = TInfo->getType();
640  unsigned NumExprs = exprs.size();
641  Expr **Exprs = (Expr**)exprs.get();
642  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
643  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
644
645  if (Ty->isDependentType() ||
646      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
647    exprs.release();
648
649    return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
650                                                    LParenLoc,
651                                                    Exprs, NumExprs,
652                                                    RParenLoc));
653  }
654
655  if (Ty->isArrayType())
656    return ExprError(Diag(TyBeginLoc,
657                          diag::err_value_init_for_array_type) << FullRange);
658  if (!Ty->isVoidType() &&
659      RequireCompleteType(TyBeginLoc, Ty,
660                          PDiag(diag::err_invalid_incomplete_type_use)
661                            << FullRange))
662    return ExprError();
663
664  if (RequireNonAbstractType(TyBeginLoc, Ty,
665                             diag::err_allocation_of_abstract_type))
666    return ExprError();
667
668
669  // C++ [expr.type.conv]p1:
670  // If the expression list is a single expression, the type conversion
671  // expression is equivalent (in definedness, and if defined in meaning) to the
672  // corresponding cast expression.
673  //
674  if (NumExprs == 1) {
675    CastKind Kind = CK_Invalid;
676    ExprValueKind VK = VK_RValue;
677    CXXCastPath BasePath;
678    ExprResult CastExpr =
679      CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
680                     Kind, VK, BasePath,
681                     /*FunctionalStyle=*/true);
682    if (CastExpr.isInvalid())
683      return ExprError();
684    Exprs[0] = CastExpr.take();
685
686    exprs.release();
687
688    return Owned(CXXFunctionalCastExpr::Create(Context,
689                                               Ty.getNonLValueExprType(Context),
690                                               VK, TInfo, TyBeginLoc, Kind,
691                                               Exprs[0], &BasePath,
692                                               RParenLoc));
693  }
694
695  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
696  InitializationKind Kind
697    = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
698                                                  LParenLoc, RParenLoc)
699               : InitializationKind::CreateValue(TyBeginLoc,
700                                                 LParenLoc, RParenLoc);
701  InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
702  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
703
704  // FIXME: Improve AST representation?
705  return move(Result);
706}
707
708/// doesUsualArrayDeleteWantSize - Answers whether the usual
709/// operator delete[] for the given type has a size_t parameter.
710static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
711                                         QualType allocType) {
712  const RecordType *record =
713    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
714  if (!record) return false;
715
716  // Try to find an operator delete[] in class scope.
717
718  DeclarationName deleteName =
719    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
720  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
721  S.LookupQualifiedName(ops, record->getDecl());
722
723  // We're just doing this for information.
724  ops.suppressDiagnostics();
725
726  // Very likely: there's no operator delete[].
727  if (ops.empty()) return false;
728
729  // If it's ambiguous, it should be illegal to call operator delete[]
730  // on this thing, so it doesn't matter if we allocate extra space or not.
731  if (ops.isAmbiguous()) return false;
732
733  LookupResult::Filter filter = ops.makeFilter();
734  while (filter.hasNext()) {
735    NamedDecl *del = filter.next()->getUnderlyingDecl();
736
737    // C++0x [basic.stc.dynamic.deallocation]p2:
738    //   A template instance is never a usual deallocation function,
739    //   regardless of its signature.
740    if (isa<FunctionTemplateDecl>(del)) {
741      filter.erase();
742      continue;
743    }
744
745    // C++0x [basic.stc.dynamic.deallocation]p2:
746    //   If class T does not declare [an operator delete[] with one
747    //   parameter] but does declare a member deallocation function
748    //   named operator delete[] with exactly two parameters, the
749    //   second of which has type std::size_t, then this function
750    //   is a usual deallocation function.
751    if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
752      filter.erase();
753      continue;
754    }
755  }
756  filter.done();
757
758  if (!ops.isSingleResult()) return false;
759
760  const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
761  return (del->getNumParams() == 2);
762}
763
764/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
765/// @code new (memory) int[size][4] @endcode
766/// or
767/// @code ::new Foo(23, "hello") @endcode
768/// For the interpretation of this heap of arguments, consult the base version.
769ExprResult
770Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
771                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
772                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
773                  Declarator &D, SourceLocation ConstructorLParen,
774                  MultiExprArg ConstructorArgs,
775                  SourceLocation ConstructorRParen) {
776  bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
777
778  Expr *ArraySize = 0;
779  // If the specified type is an array, unwrap it and save the expression.
780  if (D.getNumTypeObjects() > 0 &&
781      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
782    DeclaratorChunk &Chunk = D.getTypeObject(0);
783    if (TypeContainsAuto)
784      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
785        << D.getSourceRange());
786    if (Chunk.Arr.hasStatic)
787      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
788        << D.getSourceRange());
789    if (!Chunk.Arr.NumElts)
790      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
791        << D.getSourceRange());
792
793    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
794    D.DropFirstTypeObject();
795  }
796
797  // Every dimension shall be of constant size.
798  if (ArraySize) {
799    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
800      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
801        break;
802
803      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
804      if (Expr *NumElts = (Expr *)Array.NumElts) {
805        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
806            !NumElts->isIntegerConstantExpr(Context)) {
807          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
808            << NumElts->getSourceRange();
809          return ExprError();
810        }
811      }
812    }
813  }
814
815  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
816                                               /*AllowAuto=*/true);
817  QualType AllocType = TInfo->getType();
818  if (D.isInvalidType())
819    return ExprError();
820
821  return BuildCXXNew(StartLoc, UseGlobal,
822                     PlacementLParen,
823                     move(PlacementArgs),
824                     PlacementRParen,
825                     TypeIdParens,
826                     AllocType,
827                     TInfo,
828                     ArraySize,
829                     ConstructorLParen,
830                     move(ConstructorArgs),
831                     ConstructorRParen,
832                     TypeContainsAuto);
833}
834
835ExprResult
836Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
837                  SourceLocation PlacementLParen,
838                  MultiExprArg PlacementArgs,
839                  SourceLocation PlacementRParen,
840                  SourceRange TypeIdParens,
841                  QualType AllocType,
842                  TypeSourceInfo *AllocTypeInfo,
843                  Expr *ArraySize,
844                  SourceLocation ConstructorLParen,
845                  MultiExprArg ConstructorArgs,
846                  SourceLocation ConstructorRParen,
847                  bool TypeMayContainAuto) {
848  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
849
850  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
851  if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
852    if (ConstructorArgs.size() == 0)
853      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
854                       << AllocType << TypeRange);
855    if (ConstructorArgs.size() != 1) {
856      Expr *FirstBad = ConstructorArgs.get()[1];
857      return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
858                            diag::err_auto_new_ctor_multiple_expressions)
859                       << AllocType << TypeRange);
860    }
861    TypeSourceInfo *DeducedType = 0;
862    if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
863      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
864                       << AllocType
865                       << ConstructorArgs.get()[0]->getType()
866                       << TypeRange
867                       << ConstructorArgs.get()[0]->getSourceRange());
868    if (!DeducedType)
869      return ExprError();
870
871    AllocTypeInfo = DeducedType;
872    AllocType = AllocTypeInfo->getType();
873  }
874
875  // Per C++0x [expr.new]p5, the type being constructed may be a
876  // typedef of an array type.
877  if (!ArraySize) {
878    if (const ConstantArrayType *Array
879                              = Context.getAsConstantArrayType(AllocType)) {
880      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
881                                         Context.getSizeType(),
882                                         TypeRange.getEnd());
883      AllocType = Array->getElementType();
884    }
885  }
886
887  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
888    return ExprError();
889
890  QualType ResultType = Context.getPointerType(AllocType);
891
892  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
893  //   or enumeration type with a non-negative value."
894  if (ArraySize && !ArraySize->isTypeDependent()) {
895
896    QualType SizeType = ArraySize->getType();
897
898    ExprResult ConvertedSize
899      = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
900                                       PDiag(diag::err_array_size_not_integral),
901                                     PDiag(diag::err_array_size_incomplete_type)
902                                       << ArraySize->getSourceRange(),
903                               PDiag(diag::err_array_size_explicit_conversion),
904                                       PDiag(diag::note_array_size_conversion),
905                               PDiag(diag::err_array_size_ambiguous_conversion),
906                                       PDiag(diag::note_array_size_conversion),
907                          PDiag(getLangOptions().CPlusPlus0x? 0
908                                            : diag::ext_array_size_conversion));
909    if (ConvertedSize.isInvalid())
910      return ExprError();
911
912    ArraySize = ConvertedSize.take();
913    SizeType = ArraySize->getType();
914    if (!SizeType->isIntegralOrUnscopedEnumerationType())
915      return ExprError();
916
917    // Let's see if this is a constant < 0. If so, we reject it out of hand.
918    // We don't care about special rules, so we tell the machinery it's not
919    // evaluated - it gives us a result in more cases.
920    if (!ArraySize->isValueDependent()) {
921      llvm::APSInt Value;
922      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
923        if (Value < llvm::APSInt(
924                        llvm::APInt::getNullValue(Value.getBitWidth()),
925                                 Value.isUnsigned()))
926          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
927                                diag::err_typecheck_negative_array_size)
928            << ArraySize->getSourceRange());
929
930        if (!AllocType->isDependentType()) {
931          unsigned ActiveSizeBits
932            = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
933          if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
934            Diag(ArraySize->getSourceRange().getBegin(),
935                 diag::err_array_too_large)
936              << Value.toString(10)
937              << ArraySize->getSourceRange();
938            return ExprError();
939          }
940        }
941      } else if (TypeIdParens.isValid()) {
942        // Can't have dynamic array size when the type-id is in parentheses.
943        Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
944          << ArraySize->getSourceRange()
945          << FixItHint::CreateRemoval(TypeIdParens.getBegin())
946          << FixItHint::CreateRemoval(TypeIdParens.getEnd());
947
948        TypeIdParens = SourceRange();
949      }
950    }
951
952    ArraySize = ImpCastExprToType(ArraySize, Context.getSizeType(),
953                      CK_IntegralCast).take();
954  }
955
956  FunctionDecl *OperatorNew = 0;
957  FunctionDecl *OperatorDelete = 0;
958  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
959  unsigned NumPlaceArgs = PlacementArgs.size();
960
961  if (!AllocType->isDependentType() &&
962      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
963      FindAllocationFunctions(StartLoc,
964                              SourceRange(PlacementLParen, PlacementRParen),
965                              UseGlobal, AllocType, ArraySize, PlaceArgs,
966                              NumPlaceArgs, OperatorNew, OperatorDelete))
967    return ExprError();
968
969  // If this is an array allocation, compute whether the usual array
970  // deallocation function for the type has a size_t parameter.
971  bool UsualArrayDeleteWantsSize = false;
972  if (ArraySize && !AllocType->isDependentType())
973    UsualArrayDeleteWantsSize
974      = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
975
976  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
977  if (OperatorNew) {
978    // Add default arguments, if any.
979    const FunctionProtoType *Proto =
980      OperatorNew->getType()->getAs<FunctionProtoType>();
981    VariadicCallType CallType =
982      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
983
984    if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
985                               Proto, 1, PlaceArgs, NumPlaceArgs,
986                               AllPlaceArgs, CallType))
987      return ExprError();
988
989    NumPlaceArgs = AllPlaceArgs.size();
990    if (NumPlaceArgs > 0)
991      PlaceArgs = &AllPlaceArgs[0];
992  }
993
994  bool Init = ConstructorLParen.isValid();
995  // --- Choosing a constructor ---
996  CXXConstructorDecl *Constructor = 0;
997  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
998  unsigned NumConsArgs = ConstructorArgs.size();
999  ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
1000
1001  // Array 'new' can't have any initializers.
1002  if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
1003    SourceRange InitRange(ConsArgs[0]->getLocStart(),
1004                          ConsArgs[NumConsArgs - 1]->getLocEnd());
1005
1006    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1007    return ExprError();
1008  }
1009
1010  if (!AllocType->isDependentType() &&
1011      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1012    // C++0x [expr.new]p15:
1013    //   A new-expression that creates an object of type T initializes that
1014    //   object as follows:
1015    InitializationKind Kind
1016    //     - If the new-initializer is omitted, the object is default-
1017    //       initialized (8.5); if no initialization is performed,
1018    //       the object has indeterminate value
1019      = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
1020    //     - Otherwise, the new-initializer is interpreted according to the
1021    //       initialization rules of 8.5 for direct-initialization.
1022             : InitializationKind::CreateDirect(TypeRange.getBegin(),
1023                                                ConstructorLParen,
1024                                                ConstructorRParen);
1025
1026    InitializedEntity Entity
1027      = InitializedEntity::InitializeNew(StartLoc, AllocType);
1028    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
1029    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1030                                                move(ConstructorArgs));
1031    if (FullInit.isInvalid())
1032      return ExprError();
1033
1034    // FullInit is our initializer; walk through it to determine if it's a
1035    // constructor call, which CXXNewExpr handles directly.
1036    if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1037      if (CXXBindTemporaryExpr *Binder
1038            = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1039        FullInitExpr = Binder->getSubExpr();
1040      if (CXXConstructExpr *Construct
1041                    = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1042        Constructor = Construct->getConstructor();
1043        for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1044                                         AEnd = Construct->arg_end();
1045             A != AEnd; ++A)
1046          ConvertedConstructorArgs.push_back(*A);
1047      } else {
1048        // Take the converted initializer.
1049        ConvertedConstructorArgs.push_back(FullInit.release());
1050      }
1051    } else {
1052      // No initialization required.
1053    }
1054
1055    // Take the converted arguments and use them for the new expression.
1056    NumConsArgs = ConvertedConstructorArgs.size();
1057    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
1058  }
1059
1060  // Mark the new and delete operators as referenced.
1061  if (OperatorNew)
1062    MarkDeclarationReferenced(StartLoc, OperatorNew);
1063  if (OperatorDelete)
1064    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1065
1066  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
1067
1068  PlacementArgs.release();
1069  ConstructorArgs.release();
1070
1071  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1072                                        PlaceArgs, NumPlaceArgs, TypeIdParens,
1073                                        ArraySize, Constructor, Init,
1074                                        ConsArgs, NumConsArgs, OperatorDelete,
1075                                        UsualArrayDeleteWantsSize,
1076                                        ResultType, AllocTypeInfo,
1077                                        StartLoc,
1078                                        Init ? ConstructorRParen :
1079                                               TypeRange.getEnd(),
1080                                        ConstructorLParen, ConstructorRParen));
1081}
1082
1083/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1084/// in a new-expression.
1085/// dimension off and stores the size expression in ArraySize.
1086bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1087                              SourceRange R) {
1088  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1089  //   abstract class type or array thereof.
1090  if (AllocType->isFunctionType())
1091    return Diag(Loc, diag::err_bad_new_type)
1092      << AllocType << 0 << R;
1093  else if (AllocType->isReferenceType())
1094    return Diag(Loc, diag::err_bad_new_type)
1095      << AllocType << 1 << R;
1096  else if (!AllocType->isDependentType() &&
1097           RequireCompleteType(Loc, AllocType,
1098                               PDiag(diag::err_new_incomplete_type)
1099                                 << R))
1100    return true;
1101  else if (RequireNonAbstractType(Loc, AllocType,
1102                                  diag::err_allocation_of_abstract_type))
1103    return true;
1104  else if (AllocType->isVariablyModifiedType())
1105    return Diag(Loc, diag::err_variably_modified_new_type)
1106             << AllocType;
1107  else if (unsigned AddressSpace = AllocType.getAddressSpace())
1108    return Diag(Loc, diag::err_address_space_qualified_new)
1109      << AllocType.getUnqualifiedType() << AddressSpace;
1110
1111  return false;
1112}
1113
1114/// \brief Determine whether the given function is a non-placement
1115/// deallocation function.
1116static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1117  if (FD->isInvalidDecl())
1118    return false;
1119
1120  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1121    return Method->isUsualDeallocationFunction();
1122
1123  return ((FD->getOverloadedOperator() == OO_Delete ||
1124           FD->getOverloadedOperator() == OO_Array_Delete) &&
1125          FD->getNumParams() == 1);
1126}
1127
1128/// FindAllocationFunctions - Finds the overloads of operator new and delete
1129/// that are appropriate for the allocation.
1130bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1131                                   bool UseGlobal, QualType AllocType,
1132                                   bool IsArray, Expr **PlaceArgs,
1133                                   unsigned NumPlaceArgs,
1134                                   FunctionDecl *&OperatorNew,
1135                                   FunctionDecl *&OperatorDelete) {
1136  // --- Choosing an allocation function ---
1137  // C++ 5.3.4p8 - 14 & 18
1138  // 1) If UseGlobal is true, only look in the global scope. Else, also look
1139  //   in the scope of the allocated class.
1140  // 2) If an array size is given, look for operator new[], else look for
1141  //   operator new.
1142  // 3) The first argument is always size_t. Append the arguments from the
1143  //   placement form.
1144
1145  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1146  // We don't care about the actual value of this argument.
1147  // FIXME: Should the Sema create the expression and embed it in the syntax
1148  // tree? Or should the consumer just recalculate the value?
1149  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1150                      Context.Target.getPointerWidth(0)),
1151                      Context.getSizeType(),
1152                      SourceLocation());
1153  AllocArgs[0] = &Size;
1154  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1155
1156  // C++ [expr.new]p8:
1157  //   If the allocated type is a non-array type, the allocation
1158  //   function's name is operator new and the deallocation function's
1159  //   name is operator delete. If the allocated type is an array
1160  //   type, the allocation function's name is operator new[] and the
1161  //   deallocation function's name is operator delete[].
1162  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1163                                        IsArray ? OO_Array_New : OO_New);
1164  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1165                                        IsArray ? OO_Array_Delete : OO_Delete);
1166
1167  QualType AllocElemType = Context.getBaseElementType(AllocType);
1168
1169  if (AllocElemType->isRecordType() && !UseGlobal) {
1170    CXXRecordDecl *Record
1171      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1172    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1173                          AllocArgs.size(), Record, /*AllowMissing=*/true,
1174                          OperatorNew))
1175      return true;
1176  }
1177  if (!OperatorNew) {
1178    // Didn't find a member overload. Look for a global one.
1179    DeclareGlobalNewDelete();
1180    DeclContext *TUDecl = Context.getTranslationUnitDecl();
1181    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1182                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1183                          OperatorNew))
1184      return true;
1185  }
1186
1187  // We don't need an operator delete if we're running under
1188  // -fno-exceptions.
1189  if (!getLangOptions().Exceptions) {
1190    OperatorDelete = 0;
1191    return false;
1192  }
1193
1194  // FindAllocationOverload can change the passed in arguments, so we need to
1195  // copy them back.
1196  if (NumPlaceArgs > 0)
1197    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1198
1199  // C++ [expr.new]p19:
1200  //
1201  //   If the new-expression begins with a unary :: operator, the
1202  //   deallocation function's name is looked up in the global
1203  //   scope. Otherwise, if the allocated type is a class type T or an
1204  //   array thereof, the deallocation function's name is looked up in
1205  //   the scope of T. If this lookup fails to find the name, or if
1206  //   the allocated type is not a class type or array thereof, the
1207  //   deallocation function's name is looked up in the global scope.
1208  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1209  if (AllocElemType->isRecordType() && !UseGlobal) {
1210    CXXRecordDecl *RD
1211      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1212    LookupQualifiedName(FoundDelete, RD);
1213  }
1214  if (FoundDelete.isAmbiguous())
1215    return true; // FIXME: clean up expressions?
1216
1217  if (FoundDelete.empty()) {
1218    DeclareGlobalNewDelete();
1219    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1220  }
1221
1222  FoundDelete.suppressDiagnostics();
1223
1224  llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1225
1226  // Whether we're looking for a placement operator delete is dictated
1227  // by whether we selected a placement operator new, not by whether
1228  // we had explicit placement arguments.  This matters for things like
1229  //   struct A { void *operator new(size_t, int = 0); ... };
1230  //   A *a = new A()
1231  bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1232
1233  if (isPlacementNew) {
1234    // C++ [expr.new]p20:
1235    //   A declaration of a placement deallocation function matches the
1236    //   declaration of a placement allocation function if it has the
1237    //   same number of parameters and, after parameter transformations
1238    //   (8.3.5), all parameter types except the first are
1239    //   identical. [...]
1240    //
1241    // To perform this comparison, we compute the function type that
1242    // the deallocation function should have, and use that type both
1243    // for template argument deduction and for comparison purposes.
1244    //
1245    // FIXME: this comparison should ignore CC and the like.
1246    QualType ExpectedFunctionType;
1247    {
1248      const FunctionProtoType *Proto
1249        = OperatorNew->getType()->getAs<FunctionProtoType>();
1250
1251      llvm::SmallVector<QualType, 4> ArgTypes;
1252      ArgTypes.push_back(Context.VoidPtrTy);
1253      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1254        ArgTypes.push_back(Proto->getArgType(I));
1255
1256      FunctionProtoType::ExtProtoInfo EPI;
1257      EPI.Variadic = Proto->isVariadic();
1258
1259      ExpectedFunctionType
1260        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1261                                  ArgTypes.size(), EPI);
1262    }
1263
1264    for (LookupResult::iterator D = FoundDelete.begin(),
1265                             DEnd = FoundDelete.end();
1266         D != DEnd; ++D) {
1267      FunctionDecl *Fn = 0;
1268      if (FunctionTemplateDecl *FnTmpl
1269            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1270        // Perform template argument deduction to try to match the
1271        // expected function type.
1272        TemplateDeductionInfo Info(Context, StartLoc);
1273        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1274          continue;
1275      } else
1276        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1277
1278      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1279        Matches.push_back(std::make_pair(D.getPair(), Fn));
1280    }
1281  } else {
1282    // C++ [expr.new]p20:
1283    //   [...] Any non-placement deallocation function matches a
1284    //   non-placement allocation function. [...]
1285    for (LookupResult::iterator D = FoundDelete.begin(),
1286                             DEnd = FoundDelete.end();
1287         D != DEnd; ++D) {
1288      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1289        if (isNonPlacementDeallocationFunction(Fn))
1290          Matches.push_back(std::make_pair(D.getPair(), Fn));
1291    }
1292  }
1293
1294  // C++ [expr.new]p20:
1295  //   [...] If the lookup finds a single matching deallocation
1296  //   function, that function will be called; otherwise, no
1297  //   deallocation function will be called.
1298  if (Matches.size() == 1) {
1299    OperatorDelete = Matches[0].second;
1300
1301    // C++0x [expr.new]p20:
1302    //   If the lookup finds the two-parameter form of a usual
1303    //   deallocation function (3.7.4.2) and that function, considered
1304    //   as a placement deallocation function, would have been
1305    //   selected as a match for the allocation function, the program
1306    //   is ill-formed.
1307    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1308        isNonPlacementDeallocationFunction(OperatorDelete)) {
1309      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1310        << SourceRange(PlaceArgs[0]->getLocStart(),
1311                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1312      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1313        << DeleteName;
1314    } else {
1315      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1316                            Matches[0].first);
1317    }
1318  }
1319
1320  return false;
1321}
1322
1323/// FindAllocationOverload - Find an fitting overload for the allocation
1324/// function in the specified scope.
1325bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1326                                  DeclarationName Name, Expr** Args,
1327                                  unsigned NumArgs, DeclContext *Ctx,
1328                                  bool AllowMissing, FunctionDecl *&Operator) {
1329  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1330  LookupQualifiedName(R, Ctx);
1331  if (R.empty()) {
1332    if (AllowMissing)
1333      return false;
1334    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1335      << Name << Range;
1336  }
1337
1338  if (R.isAmbiguous())
1339    return true;
1340
1341  R.suppressDiagnostics();
1342
1343  OverloadCandidateSet Candidates(StartLoc);
1344  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1345       Alloc != AllocEnd; ++Alloc) {
1346    // Even member operator new/delete are implicitly treated as
1347    // static, so don't use AddMemberCandidate.
1348    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1349
1350    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1351      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1352                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1353                                   Candidates,
1354                                   /*SuppressUserConversions=*/false);
1355      continue;
1356    }
1357
1358    FunctionDecl *Fn = cast<FunctionDecl>(D);
1359    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1360                         /*SuppressUserConversions=*/false);
1361  }
1362
1363  // Do the resolution.
1364  OverloadCandidateSet::iterator Best;
1365  switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1366  case OR_Success: {
1367    // Got one!
1368    FunctionDecl *FnDecl = Best->Function;
1369    MarkDeclarationReferenced(StartLoc, FnDecl);
1370    // The first argument is size_t, and the first parameter must be size_t,
1371    // too. This is checked on declaration and can be assumed. (It can't be
1372    // asserted on, though, since invalid decls are left in there.)
1373    // Watch out for variadic allocator function.
1374    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1375    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1376      ExprResult Result
1377        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1378                                                       Context,
1379                                                       FnDecl->getParamDecl(i)),
1380                                    SourceLocation(),
1381                                    Owned(Args[i]));
1382      if (Result.isInvalid())
1383        return true;
1384
1385      Args[i] = Result.takeAs<Expr>();
1386    }
1387    Operator = FnDecl;
1388    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1389    return false;
1390  }
1391
1392  case OR_No_Viable_Function:
1393    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1394      << Name << Range;
1395    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1396    return true;
1397
1398  case OR_Ambiguous:
1399    Diag(StartLoc, diag::err_ovl_ambiguous_call)
1400      << Name << Range;
1401    Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1402    return true;
1403
1404  case OR_Deleted: {
1405    Diag(StartLoc, diag::err_ovl_deleted_call)
1406      << Best->Function->isDeleted()
1407      << Name
1408      << getDeletedOrUnavailableSuffix(Best->Function)
1409      << Range;
1410    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1411    return true;
1412  }
1413  }
1414  assert(false && "Unreachable, bad result from BestViableFunction");
1415  return true;
1416}
1417
1418
1419/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1420/// delete. These are:
1421/// @code
1422///   // C++03:
1423///   void* operator new(std::size_t) throw(std::bad_alloc);
1424///   void* operator new[](std::size_t) throw(std::bad_alloc);
1425///   void operator delete(void *) throw();
1426///   void operator delete[](void *) throw();
1427///   // C++0x:
1428///   void* operator new(std::size_t);
1429///   void* operator new[](std::size_t);
1430///   void operator delete(void *);
1431///   void operator delete[](void *);
1432/// @endcode
1433/// C++0x operator delete is implicitly noexcept.
1434/// Note that the placement and nothrow forms of new are *not* implicitly
1435/// declared. Their use requires including \<new\>.
1436void Sema::DeclareGlobalNewDelete() {
1437  if (GlobalNewDeleteDeclared)
1438    return;
1439
1440  // C++ [basic.std.dynamic]p2:
1441  //   [...] The following allocation and deallocation functions (18.4) are
1442  //   implicitly declared in global scope in each translation unit of a
1443  //   program
1444  //
1445  //     C++03:
1446  //     void* operator new(std::size_t) throw(std::bad_alloc);
1447  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1448  //     void  operator delete(void*) throw();
1449  //     void  operator delete[](void*) throw();
1450  //     C++0x:
1451  //     void* operator new(std::size_t);
1452  //     void* operator new[](std::size_t);
1453  //     void  operator delete(void*);
1454  //     void  operator delete[](void*);
1455  //
1456  //   These implicit declarations introduce only the function names operator
1457  //   new, operator new[], operator delete, operator delete[].
1458  //
1459  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1460  // "std" or "bad_alloc" as necessary to form the exception specification.
1461  // However, we do not make these implicit declarations visible to name
1462  // lookup.
1463  // Note that the C++0x versions of operator delete are deallocation functions,
1464  // and thus are implicitly noexcept.
1465  if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
1466    // The "std::bad_alloc" class has not yet been declared, so build it
1467    // implicitly.
1468    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1469                                        getOrCreateStdNamespace(),
1470                                        SourceLocation(), SourceLocation(),
1471                                      &PP.getIdentifierTable().get("bad_alloc"),
1472                                        0);
1473    getStdBadAlloc()->setImplicit(true);
1474  }
1475
1476  GlobalNewDeleteDeclared = true;
1477
1478  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1479  QualType SizeT = Context.getSizeType();
1480  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1481
1482  DeclareGlobalAllocationFunction(
1483      Context.DeclarationNames.getCXXOperatorName(OO_New),
1484      VoidPtr, SizeT, AssumeSaneOperatorNew);
1485  DeclareGlobalAllocationFunction(
1486      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1487      VoidPtr, SizeT, AssumeSaneOperatorNew);
1488  DeclareGlobalAllocationFunction(
1489      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1490      Context.VoidTy, VoidPtr);
1491  DeclareGlobalAllocationFunction(
1492      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1493      Context.VoidTy, VoidPtr);
1494}
1495
1496/// DeclareGlobalAllocationFunction - Declares a single implicit global
1497/// allocation function if it doesn't already exist.
1498void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1499                                           QualType Return, QualType Argument,
1500                                           bool AddMallocAttr) {
1501  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1502
1503  // Check if this function is already declared.
1504  {
1505    DeclContext::lookup_iterator Alloc, AllocEnd;
1506    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1507         Alloc != AllocEnd; ++Alloc) {
1508      // Only look at non-template functions, as it is the predefined,
1509      // non-templated allocation function we are trying to declare here.
1510      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1511        QualType InitialParamType =
1512          Context.getCanonicalType(
1513            Func->getParamDecl(0)->getType().getUnqualifiedType());
1514        // FIXME: Do we need to check for default arguments here?
1515        if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1516          if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1517            Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1518          return;
1519        }
1520      }
1521    }
1522  }
1523
1524  QualType BadAllocType;
1525  bool HasBadAllocExceptionSpec
1526    = (Name.getCXXOverloadedOperator() == OO_New ||
1527       Name.getCXXOverloadedOperator() == OO_Array_New);
1528  if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
1529    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1530    BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1531  }
1532
1533  FunctionProtoType::ExtProtoInfo EPI;
1534  if (HasBadAllocExceptionSpec) {
1535    if (!getLangOptions().CPlusPlus0x) {
1536      EPI.ExceptionSpecType = EST_Dynamic;
1537      EPI.NumExceptions = 1;
1538      EPI.Exceptions = &BadAllocType;
1539    }
1540  } else {
1541    EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1542                                EST_BasicNoexcept : EST_DynamicNone;
1543  }
1544
1545  QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1546  FunctionDecl *Alloc =
1547    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1548                         SourceLocation(), Name,
1549                         FnType, /*TInfo=*/0, SC_None,
1550                         SC_None, false, true);
1551  Alloc->setImplicit();
1552
1553  if (AddMallocAttr)
1554    Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1555
1556  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1557                                           SourceLocation(), 0,
1558                                           Argument, /*TInfo=*/0,
1559                                           SC_None, SC_None, 0);
1560  Alloc->setParams(&Param, 1);
1561
1562  // FIXME: Also add this declaration to the IdentifierResolver, but
1563  // make sure it is at the end of the chain to coincide with the
1564  // global scope.
1565  Context.getTranslationUnitDecl()->addDecl(Alloc);
1566}
1567
1568bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1569                                    DeclarationName Name,
1570                                    FunctionDecl* &Operator) {
1571  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1572  // Try to find operator delete/operator delete[] in class scope.
1573  LookupQualifiedName(Found, RD);
1574
1575  if (Found.isAmbiguous())
1576    return true;
1577
1578  Found.suppressDiagnostics();
1579
1580  llvm::SmallVector<DeclAccessPair,4> Matches;
1581  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1582       F != FEnd; ++F) {
1583    NamedDecl *ND = (*F)->getUnderlyingDecl();
1584
1585    // Ignore template operator delete members from the check for a usual
1586    // deallocation function.
1587    if (isa<FunctionTemplateDecl>(ND))
1588      continue;
1589
1590    if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1591      Matches.push_back(F.getPair());
1592  }
1593
1594  // There's exactly one suitable operator;  pick it.
1595  if (Matches.size() == 1) {
1596    Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1597    CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1598                          Matches[0]);
1599    return false;
1600
1601  // We found multiple suitable operators;  complain about the ambiguity.
1602  } else if (!Matches.empty()) {
1603    Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1604      << Name << RD;
1605
1606    for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1607           F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1608      Diag((*F)->getUnderlyingDecl()->getLocation(),
1609           diag::note_member_declared_here) << Name;
1610    return true;
1611  }
1612
1613  // We did find operator delete/operator delete[] declarations, but
1614  // none of them were suitable.
1615  if (!Found.empty()) {
1616    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1617      << Name << RD;
1618
1619    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1620         F != FEnd; ++F)
1621      Diag((*F)->getUnderlyingDecl()->getLocation(),
1622           diag::note_member_declared_here) << Name;
1623
1624    return true;
1625  }
1626
1627  // Look for a global declaration.
1628  DeclareGlobalNewDelete();
1629  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1630
1631  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1632  Expr* DeallocArgs[1];
1633  DeallocArgs[0] = &Null;
1634  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1635                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1636                             Operator))
1637    return true;
1638
1639  assert(Operator && "Did not find a deallocation function!");
1640  return false;
1641}
1642
1643/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1644/// @code ::delete ptr; @endcode
1645/// or
1646/// @code delete [] ptr; @endcode
1647ExprResult
1648Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1649                     bool ArrayForm, Expr *ExE) {
1650  // C++ [expr.delete]p1:
1651  //   The operand shall have a pointer type, or a class type having a single
1652  //   conversion function to a pointer type. The result has type void.
1653  //
1654  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1655
1656  ExprResult Ex = Owned(ExE);
1657  FunctionDecl *OperatorDelete = 0;
1658  bool ArrayFormAsWritten = ArrayForm;
1659  bool UsualArrayDeleteWantsSize = false;
1660
1661  if (!Ex.get()->isTypeDependent()) {
1662    QualType Type = Ex.get()->getType();
1663
1664    if (const RecordType *Record = Type->getAs<RecordType>()) {
1665      if (RequireCompleteType(StartLoc, Type,
1666                              PDiag(diag::err_delete_incomplete_class_type)))
1667        return ExprError();
1668
1669      llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1670
1671      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1672      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1673      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1674             E = Conversions->end(); I != E; ++I) {
1675        NamedDecl *D = I.getDecl();
1676        if (isa<UsingShadowDecl>(D))
1677          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1678
1679        // Skip over templated conversion functions; they aren't considered.
1680        if (isa<FunctionTemplateDecl>(D))
1681          continue;
1682
1683        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1684
1685        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1686        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1687          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
1688            ObjectPtrConversions.push_back(Conv);
1689      }
1690      if (ObjectPtrConversions.size() == 1) {
1691        // We have a single conversion to a pointer-to-object type. Perform
1692        // that conversion.
1693        // TODO: don't redo the conversion calculation.
1694        ExprResult Res =
1695          PerformImplicitConversion(Ex.get(),
1696                            ObjectPtrConversions.front()->getConversionType(),
1697                                    AA_Converting);
1698        if (Res.isUsable()) {
1699          Ex = move(Res);
1700          Type = Ex.get()->getType();
1701        }
1702      }
1703      else if (ObjectPtrConversions.size() > 1) {
1704        Diag(StartLoc, diag::err_ambiguous_delete_operand)
1705              << Type << Ex.get()->getSourceRange();
1706        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1707          NoteOverloadCandidate(ObjectPtrConversions[i]);
1708        return ExprError();
1709      }
1710    }
1711
1712    if (!Type->isPointerType())
1713      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1714        << Type << Ex.get()->getSourceRange());
1715
1716    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1717    if (Pointee->isVoidType() && !isSFINAEContext()) {
1718      // The C++ standard bans deleting a pointer to a non-object type, which
1719      // effectively bans deletion of "void*". However, most compilers support
1720      // this, so we treat it as a warning unless we're in a SFINAE context.
1721      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1722        << Type << Ex.get()->getSourceRange();
1723    } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1724      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1725        << Type << Ex.get()->getSourceRange());
1726    else if (!Pointee->isDependentType() &&
1727             RequireCompleteType(StartLoc, Pointee,
1728                                 PDiag(diag::warn_delete_incomplete)
1729                                   << Ex.get()->getSourceRange()))
1730      return ExprError();
1731    else if (unsigned AddressSpace = Pointee.getAddressSpace())
1732      return Diag(Ex.get()->getLocStart(),
1733                  diag::err_address_space_qualified_delete)
1734               << Pointee.getUnqualifiedType() << AddressSpace;
1735    // C++ [expr.delete]p2:
1736    //   [Note: a pointer to a const type can be the operand of a
1737    //   delete-expression; it is not necessary to cast away the constness
1738    //   (5.2.11) of the pointer expression before it is used as the operand
1739    //   of the delete-expression. ]
1740    Ex = ImpCastExprToType(Ex.take(), Context.getPointerType(Context.VoidTy),
1741                      CK_NoOp);
1742
1743    if (Pointee->isArrayType() && !ArrayForm) {
1744      Diag(StartLoc, diag::warn_delete_array_type)
1745          << Type << Ex.get()->getSourceRange()
1746          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1747      ArrayForm = true;
1748    }
1749
1750    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1751                                      ArrayForm ? OO_Array_Delete : OO_Delete);
1752
1753    QualType PointeeElem = Context.getBaseElementType(Pointee);
1754    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1755      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1756
1757      if (!UseGlobal &&
1758          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1759        return ExprError();
1760
1761      // If we're allocating an array of records, check whether the
1762      // usual operator delete[] has a size_t parameter.
1763      if (ArrayForm) {
1764        // If the user specifically asked to use the global allocator,
1765        // we'll need to do the lookup into the class.
1766        if (UseGlobal)
1767          UsualArrayDeleteWantsSize =
1768            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1769
1770        // Otherwise, the usual operator delete[] should be the
1771        // function we just found.
1772        else if (isa<CXXMethodDecl>(OperatorDelete))
1773          UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1774      }
1775
1776      if (!RD->hasTrivialDestructor())
1777        if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1778          MarkDeclarationReferenced(StartLoc,
1779                                    const_cast<CXXDestructorDecl*>(Dtor));
1780          DiagnoseUseOfDecl(Dtor, StartLoc);
1781        }
1782    }
1783
1784    if (!OperatorDelete) {
1785      // Look for a global declaration.
1786      DeclareGlobalNewDelete();
1787      DeclContext *TUDecl = Context.getTranslationUnitDecl();
1788      Expr *Arg = Ex.get();
1789      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1790                                 &Arg, 1, TUDecl, /*AllowMissing=*/false,
1791                                 OperatorDelete))
1792        return ExprError();
1793    }
1794
1795    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1796
1797    // Check access and ambiguity of operator delete and destructor.
1798    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1799      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1800      if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1801          CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
1802                      PDiag(diag::err_access_dtor) << PointeeElem);
1803      }
1804    }
1805
1806  }
1807
1808  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1809                                           ArrayFormAsWritten,
1810                                           UsualArrayDeleteWantsSize,
1811                                           OperatorDelete, Ex.take(), StartLoc));
1812}
1813
1814/// \brief Check the use of the given variable as a C++ condition in an if,
1815/// while, do-while, or switch statement.
1816ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1817                                        SourceLocation StmtLoc,
1818                                        bool ConvertToBoolean) {
1819  QualType T = ConditionVar->getType();
1820
1821  // C++ [stmt.select]p2:
1822  //   The declarator shall not specify a function or an array.
1823  if (T->isFunctionType())
1824    return ExprError(Diag(ConditionVar->getLocation(),
1825                          diag::err_invalid_use_of_function_type)
1826                       << ConditionVar->getSourceRange());
1827  else if (T->isArrayType())
1828    return ExprError(Diag(ConditionVar->getLocation(),
1829                          diag::err_invalid_use_of_array_type)
1830                     << ConditionVar->getSourceRange());
1831
1832  ExprResult Condition =
1833    Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1834                                        ConditionVar,
1835                                        ConditionVar->getLocation(),
1836                            ConditionVar->getType().getNonReferenceType(),
1837                              VK_LValue));
1838  if (ConvertToBoolean) {
1839    Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1840    if (Condition.isInvalid())
1841      return ExprError();
1842  }
1843
1844  return move(Condition);
1845}
1846
1847/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1848ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
1849  // C++ 6.4p4:
1850  // The value of a condition that is an initialized declaration in a statement
1851  // other than a switch statement is the value of the declared variable
1852  // implicitly converted to type bool. If that conversion is ill-formed, the
1853  // program is ill-formed.
1854  // The value of a condition that is an expression is the value of the
1855  // expression, implicitly converted to bool.
1856  //
1857  return PerformContextuallyConvertToBool(CondExpr);
1858}
1859
1860/// Helper function to determine whether this is the (deprecated) C++
1861/// conversion from a string literal to a pointer to non-const char or
1862/// non-const wchar_t (for narrow and wide string literals,
1863/// respectively).
1864bool
1865Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1866  // Look inside the implicit cast, if it exists.
1867  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1868    From = Cast->getSubExpr();
1869
1870  // A string literal (2.13.4) that is not a wide string literal can
1871  // be converted to an rvalue of type "pointer to char"; a wide
1872  // string literal can be converted to an rvalue of type "pointer
1873  // to wchar_t" (C++ 4.2p2).
1874  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
1875    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1876      if (const BuiltinType *ToPointeeType
1877          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1878        // This conversion is considered only when there is an
1879        // explicit appropriate pointer target type (C++ 4.2p2).
1880        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1881            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1882             (!StrLit->isWide() &&
1883              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1884               ToPointeeType->getKind() == BuiltinType::Char_S))))
1885          return true;
1886      }
1887
1888  return false;
1889}
1890
1891static ExprResult BuildCXXCastArgument(Sema &S,
1892                                       SourceLocation CastLoc,
1893                                       QualType Ty,
1894                                       CastKind Kind,
1895                                       CXXMethodDecl *Method,
1896                                       NamedDecl *FoundDecl,
1897                                       Expr *From) {
1898  switch (Kind) {
1899  default: assert(0 && "Unhandled cast kind!");
1900  case CK_ConstructorConversion: {
1901    ASTOwningVector<Expr*> ConstructorArgs(S);
1902
1903    if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1904                                  MultiExprArg(&From, 1),
1905                                  CastLoc, ConstructorArgs))
1906      return ExprError();
1907
1908    ExprResult Result =
1909    S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1910                            move_arg(ConstructorArgs),
1911                            /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1912                            SourceRange());
1913    if (Result.isInvalid())
1914      return ExprError();
1915
1916    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1917  }
1918
1919  case CK_UserDefinedConversion: {
1920    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1921
1922    // Create an implicit call expr that calls it.
1923    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
1924    if (Result.isInvalid())
1925      return ExprError();
1926
1927    return S.MaybeBindToTemporary(Result.get());
1928  }
1929  }
1930}
1931
1932/// PerformImplicitConversion - Perform an implicit conversion of the
1933/// expression From to the type ToType using the pre-computed implicit
1934/// conversion sequence ICS. Returns the converted
1935/// expression. Action is the kind of conversion we're performing,
1936/// used in the error message.
1937ExprResult
1938Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1939                                const ImplicitConversionSequence &ICS,
1940                                AssignmentAction Action, bool CStyle) {
1941  switch (ICS.getKind()) {
1942  case ImplicitConversionSequence::StandardConversion: {
1943    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
1944                                               Action, CStyle);
1945    if (Res.isInvalid())
1946      return ExprError();
1947    From = Res.take();
1948    break;
1949  }
1950
1951  case ImplicitConversionSequence::UserDefinedConversion: {
1952
1953      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1954      CastKind CastKind;
1955      QualType BeforeToType;
1956      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1957        CastKind = CK_UserDefinedConversion;
1958
1959        // If the user-defined conversion is specified by a conversion function,
1960        // the initial standard conversion sequence converts the source type to
1961        // the implicit object parameter of the conversion function.
1962        BeforeToType = Context.getTagDeclType(Conv->getParent());
1963      } else {
1964        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
1965        CastKind = CK_ConstructorConversion;
1966        // Do no conversion if dealing with ... for the first conversion.
1967        if (!ICS.UserDefined.EllipsisConversion) {
1968          // If the user-defined conversion is specified by a constructor, the
1969          // initial standard conversion sequence converts the source type to the
1970          // type required by the argument of the constructor
1971          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1972        }
1973      }
1974      // Watch out for elipsis conversion.
1975      if (!ICS.UserDefined.EllipsisConversion) {
1976        ExprResult Res =
1977          PerformImplicitConversion(From, BeforeToType,
1978                                    ICS.UserDefined.Before, AA_Converting,
1979                                    CStyle);
1980        if (Res.isInvalid())
1981          return ExprError();
1982        From = Res.take();
1983      }
1984
1985      ExprResult CastArg
1986        = BuildCXXCastArgument(*this,
1987                               From->getLocStart(),
1988                               ToType.getNonReferenceType(),
1989                               CastKind, cast<CXXMethodDecl>(FD),
1990                               ICS.UserDefined.FoundConversionFunction,
1991                               From);
1992
1993      if (CastArg.isInvalid())
1994        return ExprError();
1995
1996      From = CastArg.take();
1997
1998      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1999                                       AA_Converting, CStyle);
2000  }
2001
2002  case ImplicitConversionSequence::AmbiguousConversion:
2003    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2004                          PDiag(diag::err_typecheck_ambiguous_condition)
2005                            << From->getSourceRange());
2006     return ExprError();
2007
2008  case ImplicitConversionSequence::EllipsisConversion:
2009    assert(false && "Cannot perform an ellipsis conversion");
2010    return Owned(From);
2011
2012  case ImplicitConversionSequence::BadConversion:
2013    return ExprError();
2014  }
2015
2016  // Everything went well.
2017  return Owned(From);
2018}
2019
2020/// PerformImplicitConversion - Perform an implicit conversion of the
2021/// expression From to the type ToType by following the standard
2022/// conversion sequence SCS. Returns the converted
2023/// expression. Flavor is the context in which we're performing this
2024/// conversion, for use in error messages.
2025ExprResult
2026Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2027                                const StandardConversionSequence& SCS,
2028                                AssignmentAction Action, bool CStyle) {
2029  // Overall FIXME: we are recomputing too many types here and doing far too
2030  // much extra work. What this means is that we need to keep track of more
2031  // information that is computed when we try the implicit conversion initially,
2032  // so that we don't need to recompute anything here.
2033  QualType FromType = From->getType();
2034
2035  if (SCS.CopyConstructor) {
2036    // FIXME: When can ToType be a reference type?
2037    assert(!ToType->isReferenceType());
2038    if (SCS.Second == ICK_Derived_To_Base) {
2039      ASTOwningVector<Expr*> ConstructorArgs(*this);
2040      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2041                                  MultiExprArg(*this, &From, 1),
2042                                  /*FIXME:ConstructLoc*/SourceLocation(),
2043                                  ConstructorArgs))
2044        return ExprError();
2045      return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2046                                   ToType, SCS.CopyConstructor,
2047                                   move_arg(ConstructorArgs),
2048                                   /*ZeroInit*/ false,
2049                                   CXXConstructExpr::CK_Complete,
2050                                   SourceRange());
2051    }
2052    return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2053                                 ToType, SCS.CopyConstructor,
2054                                 MultiExprArg(*this, &From, 1),
2055                                 /*ZeroInit*/ false,
2056                                 CXXConstructExpr::CK_Complete,
2057                                 SourceRange());
2058  }
2059
2060  // Resolve overloaded function references.
2061  if (Context.hasSameType(FromType, Context.OverloadTy)) {
2062    DeclAccessPair Found;
2063    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2064                                                          true, Found);
2065    if (!Fn)
2066      return ExprError();
2067
2068    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2069      return ExprError();
2070
2071    From = FixOverloadedFunctionReference(From, Found, Fn);
2072    FromType = From->getType();
2073  }
2074
2075  // Perform the first implicit conversion.
2076  switch (SCS.First) {
2077  case ICK_Identity:
2078    // Nothing to do.
2079    break;
2080
2081  case ICK_Lvalue_To_Rvalue:
2082    // Should this get its own ICK?
2083    if (From->getObjectKind() == OK_ObjCProperty) {
2084      ExprResult FromRes = ConvertPropertyForRValue(From);
2085      if (FromRes.isInvalid())
2086        return ExprError();
2087      From = FromRes.take();
2088      if (!From->isGLValue()) break;
2089    }
2090
2091    // Check for trivial buffer overflows.
2092    CheckArrayAccess(From);
2093
2094    FromType = FromType.getUnqualifiedType();
2095    From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2096                                    From, 0, VK_RValue);
2097    break;
2098
2099  case ICK_Array_To_Pointer:
2100    FromType = Context.getArrayDecayedType(FromType);
2101    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay).take();
2102    break;
2103
2104  case ICK_Function_To_Pointer:
2105    FromType = Context.getPointerType(FromType);
2106    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay).take();
2107    break;
2108
2109  default:
2110    assert(false && "Improper first standard conversion");
2111    break;
2112  }
2113
2114  // Perform the second implicit conversion
2115  switch (SCS.Second) {
2116  case ICK_Identity:
2117    // If both sides are functions (or pointers/references to them), there could
2118    // be incompatible exception declarations.
2119    if (CheckExceptionSpecCompatibility(From, ToType))
2120      return ExprError();
2121    // Nothing else to do.
2122    break;
2123
2124  case ICK_NoReturn_Adjustment:
2125    // If both sides are functions (or pointers/references to them), there could
2126    // be incompatible exception declarations.
2127    if (CheckExceptionSpecCompatibility(From, ToType))
2128      return ExprError();
2129
2130    From = ImpCastExprToType(From, ToType, CK_NoOp).take();
2131    break;
2132
2133  case ICK_Integral_Promotion:
2134  case ICK_Integral_Conversion:
2135    From = ImpCastExprToType(From, ToType, CK_IntegralCast).take();
2136    break;
2137
2138  case ICK_Floating_Promotion:
2139  case ICK_Floating_Conversion:
2140    From = ImpCastExprToType(From, ToType, CK_FloatingCast).take();
2141    break;
2142
2143  case ICK_Complex_Promotion:
2144  case ICK_Complex_Conversion: {
2145    QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2146    QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2147    CastKind CK;
2148    if (FromEl->isRealFloatingType()) {
2149      if (ToEl->isRealFloatingType())
2150        CK = CK_FloatingComplexCast;
2151      else
2152        CK = CK_FloatingComplexToIntegralComplex;
2153    } else if (ToEl->isRealFloatingType()) {
2154      CK = CK_IntegralComplexToFloatingComplex;
2155    } else {
2156      CK = CK_IntegralComplexCast;
2157    }
2158    From = ImpCastExprToType(From, ToType, CK).take();
2159    break;
2160  }
2161
2162  case ICK_Floating_Integral:
2163    if (ToType->isRealFloatingType())
2164      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating).take();
2165    else
2166      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral).take();
2167    break;
2168
2169  case ICK_Compatible_Conversion:
2170    From = ImpCastExprToType(From, ToType, CK_NoOp).take();
2171    break;
2172
2173  case ICK_Pointer_Conversion: {
2174    if (SCS.IncompatibleObjC && Action != AA_Casting) {
2175      // Diagnose incompatible Objective-C conversions
2176      if (Action == AA_Initializing)
2177        Diag(From->getSourceRange().getBegin(),
2178             diag::ext_typecheck_convert_incompatible_pointer)
2179          << ToType << From->getType() << Action
2180          << From->getSourceRange();
2181      else
2182        Diag(From->getSourceRange().getBegin(),
2183             diag::ext_typecheck_convert_incompatible_pointer)
2184          << From->getType() << ToType << Action
2185          << From->getSourceRange();
2186    }
2187
2188    CastKind Kind = CK_Invalid;
2189    CXXCastPath BasePath;
2190    if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2191      return ExprError();
2192    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
2193    break;
2194  }
2195
2196  case ICK_Pointer_Member: {
2197    CastKind Kind = CK_Invalid;
2198    CXXCastPath BasePath;
2199    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2200      return ExprError();
2201    if (CheckExceptionSpecCompatibility(From, ToType))
2202      return ExprError();
2203    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
2204    break;
2205  }
2206
2207  case ICK_Boolean_Conversion:
2208    From = ImpCastExprToType(From, Context.BoolTy,
2209                             ScalarTypeToBooleanCastKind(FromType)).take();
2210    break;
2211
2212  case ICK_Derived_To_Base: {
2213    CXXCastPath BasePath;
2214    if (CheckDerivedToBaseConversion(From->getType(),
2215                                     ToType.getNonReferenceType(),
2216                                     From->getLocStart(),
2217                                     From->getSourceRange(),
2218                                     &BasePath,
2219                                     CStyle))
2220      return ExprError();
2221
2222    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2223                      CK_DerivedToBase, CastCategory(From),
2224                      &BasePath).take();
2225    break;
2226  }
2227
2228  case ICK_Vector_Conversion:
2229    From = ImpCastExprToType(From, ToType, CK_BitCast).take();
2230    break;
2231
2232  case ICK_Vector_Splat:
2233    From = ImpCastExprToType(From, ToType, CK_VectorSplat).take();
2234    break;
2235
2236  case ICK_Complex_Real:
2237    // Case 1.  x -> _Complex y
2238    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2239      QualType ElType = ToComplex->getElementType();
2240      bool isFloatingComplex = ElType->isRealFloatingType();
2241
2242      // x -> y
2243      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2244        // do nothing
2245      } else if (From->getType()->isRealFloatingType()) {
2246        From = ImpCastExprToType(From, ElType,
2247                isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2248      } else {
2249        assert(From->getType()->isIntegerType());
2250        From = ImpCastExprToType(From, ElType,
2251                isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2252      }
2253      // y -> _Complex y
2254      From = ImpCastExprToType(From, ToType,
2255                   isFloatingComplex ? CK_FloatingRealToComplex
2256                                     : CK_IntegralRealToComplex).take();
2257
2258    // Case 2.  _Complex x -> y
2259    } else {
2260      const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2261      assert(FromComplex);
2262
2263      QualType ElType = FromComplex->getElementType();
2264      bool isFloatingComplex = ElType->isRealFloatingType();
2265
2266      // _Complex x -> x
2267      From = ImpCastExprToType(From, ElType,
2268                   isFloatingComplex ? CK_FloatingComplexToReal
2269                                     : CK_IntegralComplexToReal).take();
2270
2271      // x -> y
2272      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2273        // do nothing
2274      } else if (ToType->isRealFloatingType()) {
2275        From = ImpCastExprToType(From, ToType,
2276                isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating).take();
2277      } else {
2278        assert(ToType->isIntegerType());
2279        From = ImpCastExprToType(From, ToType,
2280                isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast).take();
2281      }
2282    }
2283    break;
2284
2285  case ICK_Block_Pointer_Conversion: {
2286      From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2287                               VK_RValue).take();
2288      break;
2289    }
2290
2291  case ICK_TransparentUnionConversion: {
2292    ExprResult FromRes = Owned(From);
2293    Sema::AssignConvertType ConvTy =
2294      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2295    if (FromRes.isInvalid())
2296      return ExprError();
2297    From = FromRes.take();
2298    assert ((ConvTy == Sema::Compatible) &&
2299            "Improper transparent union conversion");
2300    (void)ConvTy;
2301    break;
2302  }
2303
2304  case ICK_Lvalue_To_Rvalue:
2305  case ICK_Array_To_Pointer:
2306  case ICK_Function_To_Pointer:
2307  case ICK_Qualification:
2308  case ICK_Num_Conversion_Kinds:
2309    assert(false && "Improper second standard conversion");
2310    break;
2311  }
2312
2313  switch (SCS.Third) {
2314  case ICK_Identity:
2315    // Nothing to do.
2316    break;
2317
2318  case ICK_Qualification: {
2319    // The qualification keeps the category of the inner expression, unless the
2320    // target type isn't a reference.
2321    ExprValueKind VK = ToType->isReferenceType() ?
2322                                  CastCategory(From) : VK_RValue;
2323    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2324                             CK_NoOp, VK).take();
2325
2326    if (SCS.DeprecatedStringLiteralToCharPtr &&
2327        !getLangOptions().WritableStrings)
2328      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2329        << ToType.getNonReferenceType();
2330
2331    break;
2332    }
2333
2334  default:
2335    assert(false && "Improper third standard conversion");
2336    break;
2337  }
2338
2339  return Owned(From);
2340}
2341
2342ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2343                                     SourceLocation KWLoc,
2344                                     ParsedType Ty,
2345                                     SourceLocation RParen) {
2346  TypeSourceInfo *TSInfo;
2347  QualType T = GetTypeFromParser(Ty, &TSInfo);
2348
2349  if (!TSInfo)
2350    TSInfo = Context.getTrivialTypeSourceInfo(T);
2351  return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2352}
2353
2354/// \brief Check the completeness of a type in a unary type trait.
2355///
2356/// If the particular type trait requires a complete type, tries to complete
2357/// it. If completing the type fails, a diagnostic is emitted and false
2358/// returned. If completing the type succeeds or no completion was required,
2359/// returns true.
2360static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2361                                                UnaryTypeTrait UTT,
2362                                                SourceLocation Loc,
2363                                                QualType ArgTy) {
2364  // C++0x [meta.unary.prop]p3:
2365  //   For all of the class templates X declared in this Clause, instantiating
2366  //   that template with a template argument that is a class template
2367  //   specialization may result in the implicit instantiation of the template
2368  //   argument if and only if the semantics of X require that the argument
2369  //   must be a complete type.
2370  // We apply this rule to all the type trait expressions used to implement
2371  // these class templates. We also try to follow any GCC documented behavior
2372  // in these expressions to ensure portability of standard libraries.
2373  switch (UTT) {
2374    // FIXME: These shouldn't be UnaryTypeTraits as they aren't traits on types.
2375  case UTT_IsLvalueExpr:
2376  case UTT_IsRvalueExpr:
2377    assert(0 && "Expression traits found in type trait handling code.");
2378
2379    // is_complete_type somewhat obviously cannot require a complete type.
2380  case UTT_IsCompleteType:
2381    // Fallthrough
2382
2383    // These traits are modeled on the type predicates in C++0x
2384    // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2385    // requiring a complete type, as whether or not they return true cannot be
2386    // impacted by the completeness of the type.
2387  case UTT_IsVoid:
2388  case UTT_IsIntegral:
2389  case UTT_IsFloatingPoint:
2390  case UTT_IsArray:
2391  case UTT_IsPointer:
2392  case UTT_IsLvalueReference:
2393  case UTT_IsRvalueReference:
2394  case UTT_IsMemberFunctionPointer:
2395  case UTT_IsMemberObjectPointer:
2396  case UTT_IsEnum:
2397  case UTT_IsUnion:
2398  case UTT_IsClass:
2399  case UTT_IsFunction:
2400  case UTT_IsReference:
2401  case UTT_IsArithmetic:
2402  case UTT_IsFundamental:
2403  case UTT_IsObject:
2404  case UTT_IsScalar:
2405  case UTT_IsCompound:
2406  case UTT_IsMemberPointer:
2407    // Fallthrough
2408
2409    // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2410    // which requires some of its traits to have the complete type. However,
2411    // the completeness of the type cannot impact these traits' semantics, and
2412    // so they don't require it. This matches the comments on these traits in
2413    // Table 49.
2414  case UTT_IsConst:
2415  case UTT_IsVolatile:
2416  case UTT_IsSigned:
2417  case UTT_IsUnsigned:
2418    return true;
2419
2420    // C++0x [meta.unary.prop] Table 49 requires the following traits to be
2421    // applied to a complete type, so we enumerate theme here even though the
2422    // default for non-Borland compilers is to require completeness for any
2423    // other traits than the ones specifically allowed to work on incomplete
2424    // types.
2425  case UTT_IsTrivial:
2426  case UTT_IsStandardLayout:
2427  case UTT_IsPOD:
2428  case UTT_IsLiteral:
2429  case UTT_IsEmpty:
2430  case UTT_IsPolymorphic:
2431  case UTT_IsAbstract:
2432    // Fallthrough
2433
2434    // These trait expressions are designed to help implement predicats in
2435    // [meta.unary.prop] despite not being named the same. They are specified
2436    // by both GCC and the Embarcadero C++ compiler, and require the complete
2437    // type due to the overarching C++0x type predicates being implemented
2438    // requiring the complete type.
2439  case UTT_HasNothrowAssign:
2440  case UTT_HasNothrowConstructor:
2441  case UTT_HasNothrowCopy:
2442  case UTT_HasTrivialAssign:
2443  case UTT_HasTrivialConstructor:
2444  case UTT_HasTrivialCopy:
2445  case UTT_HasTrivialDestructor:
2446  case UTT_HasVirtualDestructor:
2447    // Arrays of unknown bound are expressly allowed.
2448    QualType ElTy = ArgTy;
2449    if (ArgTy->isIncompleteArrayType())
2450      ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2451
2452    // The void type is expressly allowed.
2453    if (ElTy->isVoidType())
2454      return true;
2455
2456    return !S.RequireCompleteType(
2457      Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
2458  }
2459}
2460
2461static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2462                                   SourceLocation KeyLoc, QualType T) {
2463  assert(!T->isDependentType() &&
2464         "Cannot evaluate type trait on dependent type");
2465
2466  ASTContext &C = Self.Context;
2467  switch(UTT) {
2468  default: assert(false && "Unknown type trait or not implemented");
2469
2470    // Type trait expressions corresponding to the primary type category
2471    // predicates in C++0x [meta.unary.cat].
2472  case UTT_IsVoid:
2473    return T->isVoidType();
2474  case UTT_IsIntegral:
2475    return T->isIntegralType(C);
2476  case UTT_IsFloatingPoint:
2477    return T->isFloatingType();
2478  case UTT_IsArray:
2479    return T->isArrayType();
2480  case UTT_IsPointer:
2481    return T->isPointerType();
2482  case UTT_IsLvalueReference:
2483    return T->isLValueReferenceType();
2484  case UTT_IsRvalueReference:
2485    return T->isRValueReferenceType();
2486  case UTT_IsMemberFunctionPointer:
2487    return T->isMemberFunctionPointerType();
2488  case UTT_IsMemberObjectPointer:
2489    return T->isMemberDataPointerType();
2490  case UTT_IsEnum:
2491    return T->isEnumeralType();
2492  case UTT_IsUnion:
2493    if (const RecordType *Record = T->getAs<RecordType>())
2494      return Record->getDecl()->isUnion();
2495    return false;
2496  case UTT_IsClass:
2497    if (const RecordType *Record = T->getAs<RecordType>())
2498      return !Record->getDecl()->isUnion();
2499    return false;
2500  case UTT_IsFunction:
2501    return T->isFunctionType();
2502
2503    // Type trait expressions which correspond to the convenient composition
2504    // predicates in C++0x [meta.unary.comp].
2505  case UTT_IsReference:
2506    return T->isReferenceType();
2507  case UTT_IsArithmetic:
2508    return T->isArithmeticType() && ! T->isEnumeralType();
2509  case UTT_IsFundamental:
2510    return T->isVoidType() || (T->isArithmeticType() && ! T->isEnumeralType());
2511  case UTT_IsObject:
2512    // Defined in Section 3.9 p8 of the Working Draft, essentially:
2513    // !__is_reference(T) && !__is_function(T) && !__is_void(T).
2514    return ! (T->isReferenceType() || T->isFunctionType() || T->isVoidType());
2515  case UTT_IsScalar:
2516    // Scalar type is defined in Section 3.9 p10 of the Working Draft.
2517    // Essentially:
2518    // __is_arithmetic( T ) || __is_enumeration(T) ||
2519    // __is_pointer(T) || __is_member_pointer(T)
2520    return (T->isArithmeticType() || T->isEnumeralType() ||
2521            T->isPointerType() || T->isMemberPointerType());
2522  case UTT_IsCompound:
2523    return ! (T->isVoidType() || T->isArithmeticType()) || T->isEnumeralType();
2524  case UTT_IsMemberPointer:
2525    return T->isMemberPointerType();
2526
2527    // Type trait expressions which correspond to the type property predicates
2528    // in C++0x [meta.unary.prop].
2529  case UTT_IsConst:
2530    return T.isConstQualified();
2531  case UTT_IsVolatile:
2532    return T.isVolatileQualified();
2533  case UTT_IsTrivial:
2534    return T->isTrivialType();
2535  case UTT_IsStandardLayout:
2536    return T->isStandardLayoutType();
2537  case UTT_IsPOD:
2538    return T->isPODType();
2539  case UTT_IsLiteral:
2540    return T->isLiteralType();
2541  case UTT_IsEmpty:
2542    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2543      return !RD->isUnion() && RD->isEmpty();
2544    return false;
2545  case UTT_IsPolymorphic:
2546    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2547      return RD->isPolymorphic();
2548    return false;
2549  case UTT_IsAbstract:
2550    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2551      return RD->isAbstract();
2552    return false;
2553  case UTT_IsSigned:
2554    return T->isSignedIntegerType();
2555  case UTT_IsUnsigned:
2556    return T->isUnsignedIntegerType();
2557
2558    // Type trait expressions which query classes regarding their construction,
2559    // destruction, and copying. Rather than being based directly on the
2560    // related type predicates in the standard, they are specified by both
2561    // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2562    // specifications.
2563    //
2564    //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2565    //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2566  case UTT_HasTrivialConstructor:
2567    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2568    //   If __is_pod (type) is true then the trait is true, else if type is
2569    //   a cv class or union type (or array thereof) with a trivial default
2570    //   constructor ([class.ctor]) then the trait is true, else it is false.
2571    if (T->isPODType())
2572      return true;
2573    if (const RecordType *RT =
2574          C.getBaseElementType(T)->getAs<RecordType>())
2575      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2576    return false;
2577  case UTT_HasTrivialCopy:
2578    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2579    //   If __is_pod (type) is true or type is a reference type then
2580    //   the trait is true, else if type is a cv class or union type
2581    //   with a trivial copy constructor ([class.copy]) then the trait
2582    //   is true, else it is false.
2583    if (T->isPODType() || T->isReferenceType())
2584      return true;
2585    if (const RecordType *RT = T->getAs<RecordType>())
2586      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2587    return false;
2588  case UTT_HasTrivialAssign:
2589    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2590    //   If type is const qualified or is a reference type then the
2591    //   trait is false. Otherwise if __is_pod (type) is true then the
2592    //   trait is true, else if type is a cv class or union type with
2593    //   a trivial copy assignment ([class.copy]) then the trait is
2594    //   true, else it is false.
2595    // Note: the const and reference restrictions are interesting,
2596    // given that const and reference members don't prevent a class
2597    // from having a trivial copy assignment operator (but do cause
2598    // errors if the copy assignment operator is actually used, q.v.
2599    // [class.copy]p12).
2600
2601    if (C.getBaseElementType(T).isConstQualified())
2602      return false;
2603    if (T->isPODType())
2604      return true;
2605    if (const RecordType *RT = T->getAs<RecordType>())
2606      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2607    return false;
2608  case UTT_HasTrivialDestructor:
2609    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2610    //   If __is_pod (type) is true or type is a reference type
2611    //   then the trait is true, else if type is a cv class or union
2612    //   type (or array thereof) with a trivial destructor
2613    //   ([class.dtor]) then the trait is true, else it is
2614    //   false.
2615    if (T->isPODType() || T->isReferenceType())
2616      return true;
2617    if (const RecordType *RT =
2618          C.getBaseElementType(T)->getAs<RecordType>())
2619      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2620    return false;
2621  // TODO: Propagate nothrowness for implicitly declared special members.
2622  case UTT_HasNothrowAssign:
2623    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2624    //   If type is const qualified or is a reference type then the
2625    //   trait is false. Otherwise if __has_trivial_assign (type)
2626    //   is true then the trait is true, else if type is a cv class
2627    //   or union type with copy assignment operators that are known
2628    //   not to throw an exception then the trait is true, else it is
2629    //   false.
2630    if (C.getBaseElementType(T).isConstQualified())
2631      return false;
2632    if (T->isReferenceType())
2633      return false;
2634    if (T->isPODType())
2635      return true;
2636    if (const RecordType *RT = T->getAs<RecordType>()) {
2637      CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2638      if (RD->hasTrivialCopyAssignment())
2639        return true;
2640
2641      bool FoundAssign = false;
2642      bool AllNoThrow = true;
2643      DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
2644      LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2645                       Sema::LookupOrdinaryName);
2646      if (Self.LookupQualifiedName(Res, RD)) {
2647        for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2648             Op != OpEnd; ++Op) {
2649          CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2650          if (Operator->isCopyAssignmentOperator()) {
2651            FoundAssign = true;
2652            const FunctionProtoType *CPT
2653                = Operator->getType()->getAs<FunctionProtoType>();
2654            if (!CPT->isNothrow(Self.Context)) {
2655              AllNoThrow = false;
2656              break;
2657            }
2658          }
2659        }
2660      }
2661
2662      return FoundAssign && AllNoThrow;
2663    }
2664    return false;
2665  case UTT_HasNothrowCopy:
2666    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2667    //   If __has_trivial_copy (type) is true then the trait is true, else
2668    //   if type is a cv class or union type with copy constructors that are
2669    //   known not to throw an exception then the trait is true, else it is
2670    //   false.
2671    if (T->isPODType() || T->isReferenceType())
2672      return true;
2673    if (const RecordType *RT = T->getAs<RecordType>()) {
2674      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2675      if (RD->hasTrivialCopyConstructor())
2676        return true;
2677
2678      bool FoundConstructor = false;
2679      bool AllNoThrow = true;
2680      unsigned FoundTQs;
2681      DeclContext::lookup_const_iterator Con, ConEnd;
2682      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2683           Con != ConEnd; ++Con) {
2684        // A template constructor is never a copy constructor.
2685        // FIXME: However, it may actually be selected at the actual overload
2686        // resolution point.
2687        if (isa<FunctionTemplateDecl>(*Con))
2688          continue;
2689        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2690        if (Constructor->isCopyConstructor(FoundTQs)) {
2691          FoundConstructor = true;
2692          const FunctionProtoType *CPT
2693              = Constructor->getType()->getAs<FunctionProtoType>();
2694          // FIXME: check whether evaluating default arguments can throw.
2695          // For now, we'll be conservative and assume that they can throw.
2696          if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) {
2697            AllNoThrow = false;
2698            break;
2699          }
2700        }
2701      }
2702
2703      return FoundConstructor && AllNoThrow;
2704    }
2705    return false;
2706  case UTT_HasNothrowConstructor:
2707    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2708    //   If __has_trivial_constructor (type) is true then the trait is
2709    //   true, else if type is a cv class or union type (or array
2710    //   thereof) with a default constructor that is known not to
2711    //   throw an exception then the trait is true, else it is false.
2712    if (T->isPODType())
2713      return true;
2714    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2715      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2716      if (RD->hasTrivialConstructor())
2717        return true;
2718
2719      DeclContext::lookup_const_iterator Con, ConEnd;
2720      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2721           Con != ConEnd; ++Con) {
2722        // FIXME: In C++0x, a constructor template can be a default constructor.
2723        if (isa<FunctionTemplateDecl>(*Con))
2724          continue;
2725        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2726        if (Constructor->isDefaultConstructor()) {
2727          const FunctionProtoType *CPT
2728              = Constructor->getType()->getAs<FunctionProtoType>();
2729          // TODO: check whether evaluating default arguments can throw.
2730          // For now, we'll be conservative and assume that they can throw.
2731          return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
2732        }
2733      }
2734    }
2735    return false;
2736  case UTT_HasVirtualDestructor:
2737    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2738    //   If type is a class type with a virtual destructor ([class.dtor])
2739    //   then the trait is true, else it is false.
2740    if (const RecordType *Record = T->getAs<RecordType>()) {
2741      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2742      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
2743        return Destructor->isVirtual();
2744    }
2745    return false;
2746
2747    // These type trait expressions are modeled on the specifications for the
2748    // Embarcadero C++0x type trait functions:
2749    //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2750  case UTT_IsCompleteType:
2751    // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2752    //   Returns True if and only if T is a complete type at the point of the
2753    //   function call.
2754    return !T->isIncompleteType();
2755  }
2756}
2757
2758
2759ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
2760                                     SourceLocation KWLoc,
2761                                     TypeSourceInfo *TSInfo,
2762                                     SourceLocation RParen) {
2763  QualType T = TSInfo->getType();
2764  if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2765    return ExprError();
2766
2767  bool Value = false;
2768  if (!T->isDependentType())
2769    Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
2770
2771  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
2772                                                RParen, Context.BoolTy));
2773}
2774
2775ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2776                                      SourceLocation KWLoc,
2777                                      ParsedType LhsTy,
2778                                      ParsedType RhsTy,
2779                                      SourceLocation RParen) {
2780  TypeSourceInfo *LhsTSInfo;
2781  QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2782  if (!LhsTSInfo)
2783    LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2784
2785  TypeSourceInfo *RhsTSInfo;
2786  QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2787  if (!RhsTSInfo)
2788    RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2789
2790  return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2791}
2792
2793static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2794                                    QualType LhsT, QualType RhsT,
2795                                    SourceLocation KeyLoc) {
2796  if (LhsT->isDependentType()) {
2797    Self.Diag(KeyLoc, diag::err_dependent_type_used_in_type_trait_expr) << LhsT;
2798    return false;
2799  }
2800  else if (RhsT->isDependentType()) {
2801    Self.Diag(KeyLoc, diag::err_dependent_type_used_in_type_trait_expr) << RhsT;
2802    return false;
2803  }
2804
2805  switch(BTT) {
2806  case BTT_IsBaseOf: {
2807    // C++0x [meta.rel]p2
2808    // Base is a base class of Derived without regard to cv-qualifiers or
2809    // Base and Derived are not unions and name the same class type without
2810    // regard to cv-qualifiers.
2811
2812    const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2813    if (!lhsRecord) return false;
2814
2815    const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2816    if (!rhsRecord) return false;
2817
2818    assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2819             == (lhsRecord == rhsRecord));
2820
2821    if (lhsRecord == rhsRecord)
2822      return !lhsRecord->getDecl()->isUnion();
2823
2824    // C++0x [meta.rel]p2:
2825    //   If Base and Derived are class types and are different types
2826    //   (ignoring possible cv-qualifiers) then Derived shall be a
2827    //   complete type.
2828    if (Self.RequireCompleteType(KeyLoc, RhsT,
2829                          diag::err_incomplete_type_used_in_type_trait_expr))
2830      return false;
2831
2832    return cast<CXXRecordDecl>(rhsRecord->getDecl())
2833      ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2834  }
2835  case BTT_IsSame:
2836    return Self.Context.hasSameType(LhsT, RhsT);
2837  case BTT_TypeCompatible:
2838    return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2839                                           RhsT.getUnqualifiedType());
2840  case BTT_IsConvertible:
2841  case BTT_IsConvertibleTo: {
2842    // C++0x [meta.rel]p4:
2843    //   Given the following function prototype:
2844    //
2845    //     template <class T>
2846    //       typename add_rvalue_reference<T>::type create();
2847    //
2848    //   the predicate condition for a template specialization
2849    //   is_convertible<From, To> shall be satisfied if and only if
2850    //   the return expression in the following code would be
2851    //   well-formed, including any implicit conversions to the return
2852    //   type of the function:
2853    //
2854    //     To test() {
2855    //       return create<From>();
2856    //     }
2857    //
2858    //   Access checking is performed as if in a context unrelated to To and
2859    //   From. Only the validity of the immediate context of the expression
2860    //   of the return-statement (including conversions to the return type)
2861    //   is considered.
2862    //
2863    // We model the initialization as a copy-initialization of a temporary
2864    // of the appropriate type, which for this expression is identical to the
2865    // return statement (since NRVO doesn't apply).
2866    if (LhsT->isObjectType() || LhsT->isFunctionType())
2867      LhsT = Self.Context.getRValueReferenceType(LhsT);
2868
2869    InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
2870    OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
2871                         Expr::getValueKindForType(LhsT));
2872    Expr *FromPtr = &From;
2873    InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2874                                                           SourceLocation()));
2875
2876    // Perform the initialization within a SFINAE trap at translation unit
2877    // scope.
2878    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2879    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
2880    InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2881    if (Init.getKind() == InitializationSequence::FailedSequence)
2882      return false;
2883
2884    ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2885    return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2886  }
2887  }
2888  llvm_unreachable("Unknown type trait or not implemented");
2889}
2890
2891ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2892                                      SourceLocation KWLoc,
2893                                      TypeSourceInfo *LhsTSInfo,
2894                                      TypeSourceInfo *RhsTSInfo,
2895                                      SourceLocation RParen) {
2896  QualType LhsT = LhsTSInfo->getType();
2897  QualType RhsT = RhsTSInfo->getType();
2898
2899  if (BTT == BTT_TypeCompatible) {
2900    if (getLangOptions().CPlusPlus) {
2901      Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2902        << SourceRange(KWLoc, RParen);
2903      return ExprError();
2904    }
2905  }
2906
2907  bool Value = false;
2908  if (!LhsT->isDependentType() && !RhsT->isDependentType())
2909    Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2910
2911  // Select trait result type.
2912  QualType ResultType;
2913  switch (BTT) {
2914  case BTT_IsBaseOf:       ResultType = Context.BoolTy; break;
2915  case BTT_IsConvertible:  ResultType = Context.BoolTy; break;
2916  case BTT_IsSame:         ResultType = Context.BoolTy; break;
2917  case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2918  case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
2919  }
2920
2921  return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2922                                                 RhsTSInfo, Value, RParen,
2923                                                 ResultType));
2924}
2925
2926ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
2927                                     SourceLocation KWLoc,
2928                                     ParsedType Ty,
2929                                     Expr* DimExpr,
2930                                     SourceLocation RParen) {
2931  TypeSourceInfo *TSInfo;
2932  QualType T = GetTypeFromParser(Ty, &TSInfo);
2933  if (!TSInfo)
2934    TSInfo = Context.getTrivialTypeSourceInfo(T);
2935
2936  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
2937}
2938
2939static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
2940                                           QualType T, Expr *DimExpr,
2941                                           SourceLocation KeyLoc) {
2942  if (T->isDependentType()) {
2943    Self.Diag(KeyLoc, diag::err_dependent_type_used_in_type_trait_expr) << T;
2944    return false;
2945  }
2946
2947  switch(ATT) {
2948  case ATT_ArrayRank:
2949    if (T->isArrayType()) {
2950      unsigned Dim = 0;
2951      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2952        ++Dim;
2953        T = AT->getElementType();
2954      }
2955      return Dim;
2956    }
2957    return 0;
2958
2959  case ATT_ArrayExtent: {
2960    llvm::APSInt Value;
2961    uint64_t Dim;
2962    if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
2963      if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
2964        Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2965          DimExpr->getSourceRange();
2966        return false;
2967      }
2968      Dim = Value.getLimitedValue();
2969    } else {
2970      Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2971        DimExpr->getSourceRange();
2972      return false;
2973    }
2974
2975    if (T->isArrayType()) {
2976      unsigned D = 0;
2977      bool Matched = false;
2978      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2979        if (Dim == D) {
2980          Matched = true;
2981          break;
2982        }
2983        ++D;
2984        T = AT->getElementType();
2985      }
2986
2987      if (Matched && T->isArrayType()) {
2988        if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
2989          return CAT->getSize().getLimitedValue();
2990      }
2991    }
2992    return 0;
2993  }
2994  }
2995  llvm_unreachable("Unknown type trait or not implemented");
2996}
2997
2998ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
2999                                     SourceLocation KWLoc,
3000                                     TypeSourceInfo *TSInfo,
3001                                     Expr* DimExpr,
3002                                     SourceLocation RParen) {
3003  QualType T = TSInfo->getType();
3004
3005  uint64_t Value;
3006  if (!T->isDependentType())
3007    Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3008  else
3009    return ExprError();
3010
3011  // Select trait result type.
3012  QualType ResultType;
3013  switch (ATT) {
3014  case ATT_ArrayRank:    ResultType = Context.IntTy; break;
3015  case ATT_ArrayExtent:  ResultType = Context.IntTy; break;
3016  }
3017
3018  return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
3019                                                DimExpr, RParen, ResultType));
3020}
3021
3022ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
3023                                     SourceLocation KWLoc,
3024                                     Expr* Queried,
3025                                     SourceLocation RParen) {
3026  // If error parsing the expression, ignore.
3027  if (!Queried)
3028      return ExprError();
3029
3030  ExprResult Result
3031    = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
3032
3033  return move(Result);
3034}
3035
3036ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
3037                                     SourceLocation KWLoc,
3038                                     Expr* Queried,
3039                                     SourceLocation RParen) {
3040  if (Queried->isTypeDependent()) {
3041    // Delay type-checking for type-dependent expressions.
3042  } else if (Queried->getType()->isPlaceholderType()) {
3043    ExprResult PE = CheckPlaceholderExpr(Queried);
3044    if (PE.isInvalid()) return ExprError();
3045    return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3046  }
3047
3048  bool Value = false;
3049  switch (ET) {
3050  default: llvm_unreachable("Unknown or unimplemented expression trait");
3051  case ET_IsLValueExpr:       Value = Queried->isLValue(); break;
3052  case ET_IsRValueExpr:       Value = Queried->isRValue(); break;
3053  }
3054
3055  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3056  return Owned(
3057      new (Context) ExpressionTraitExpr(
3058          KWLoc, ET, Queried, Value, RParen, Context.BoolTy));
3059}
3060
3061QualType Sema::CheckPointerToMemberOperands(ExprResult &lex, ExprResult &rex,
3062                                            ExprValueKind &VK,
3063                                            SourceLocation Loc,
3064                                            bool isIndirect) {
3065  const char *OpSpelling = isIndirect ? "->*" : ".*";
3066  // C++ 5.5p2
3067  //   The binary operator .* [p3: ->*] binds its second operand, which shall
3068  //   be of type "pointer to member of T" (where T is a completely-defined
3069  //   class type) [...]
3070  QualType RType = rex.get()->getType();
3071  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
3072  if (!MemPtr) {
3073    Diag(Loc, diag::err_bad_memptr_rhs)
3074      << OpSpelling << RType << rex.get()->getSourceRange();
3075    return QualType();
3076  }
3077
3078  QualType Class(MemPtr->getClass(), 0);
3079
3080  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3081  // member pointer points must be completely-defined. However, there is no
3082  // reason for this semantic distinction, and the rule is not enforced by
3083  // other compilers. Therefore, we do not check this property, as it is
3084  // likely to be considered a defect.
3085
3086  // C++ 5.5p2
3087  //   [...] to its first operand, which shall be of class T or of a class of
3088  //   which T is an unambiguous and accessible base class. [p3: a pointer to
3089  //   such a class]
3090  QualType LType = lex.get()->getType();
3091  if (isIndirect) {
3092    if (const PointerType *Ptr = LType->getAs<PointerType>())
3093      LType = Ptr->getPointeeType();
3094    else {
3095      Diag(Loc, diag::err_bad_memptr_lhs)
3096        << OpSpelling << 1 << LType
3097        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
3098      return QualType();
3099    }
3100  }
3101
3102  if (!Context.hasSameUnqualifiedType(Class, LType)) {
3103    // If we want to check the hierarchy, we need a complete type.
3104    if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
3105        << OpSpelling << (int)isIndirect)) {
3106      return QualType();
3107    }
3108    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3109                       /*DetectVirtual=*/false);
3110    // FIXME: Would it be useful to print full ambiguity paths, or is that
3111    // overkill?
3112    if (!IsDerivedFrom(LType, Class, Paths) ||
3113        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3114      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
3115        << (int)isIndirect << lex.get()->getType();
3116      return QualType();
3117    }
3118    // Cast LHS to type of use.
3119    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
3120    ExprValueKind VK =
3121        isIndirect ? VK_RValue : CastCategory(lex.get());
3122
3123    CXXCastPath BasePath;
3124    BuildBasePathArray(Paths, BasePath);
3125    lex = ImpCastExprToType(lex.take(), UseType, CK_DerivedToBase, VK, &BasePath);
3126  }
3127
3128  if (isa<CXXScalarValueInitExpr>(rex.get()->IgnoreParens())) {
3129    // Diagnose use of pointer-to-member type which when used as
3130    // the functional cast in a pointer-to-member expression.
3131    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3132     return QualType();
3133  }
3134
3135  // C++ 5.5p2
3136  //   The result is an object or a function of the type specified by the
3137  //   second operand.
3138  // The cv qualifiers are the union of those in the pointer and the left side,
3139  // in accordance with 5.5p5 and 5.2.5.
3140  QualType Result = MemPtr->getPointeeType();
3141  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
3142
3143  // C++0x [expr.mptr.oper]p6:
3144  //   In a .* expression whose object expression is an rvalue, the program is
3145  //   ill-formed if the second operand is a pointer to member function with
3146  //   ref-qualifier &. In a ->* expression or in a .* expression whose object
3147  //   expression is an lvalue, the program is ill-formed if the second operand
3148  //   is a pointer to member function with ref-qualifier &&.
3149  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3150    switch (Proto->getRefQualifier()) {
3151    case RQ_None:
3152      // Do nothing
3153      break;
3154
3155    case RQ_LValue:
3156      if (!isIndirect && !lex.get()->Classify(Context).isLValue())
3157        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3158          << RType << 1 << lex.get()->getSourceRange();
3159      break;
3160
3161    case RQ_RValue:
3162      if (isIndirect || !lex.get()->Classify(Context).isRValue())
3163        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3164          << RType << 0 << lex.get()->getSourceRange();
3165      break;
3166    }
3167  }
3168
3169  // C++ [expr.mptr.oper]p6:
3170  //   The result of a .* expression whose second operand is a pointer
3171  //   to a data member is of the same value category as its
3172  //   first operand. The result of a .* expression whose second
3173  //   operand is a pointer to a member function is a prvalue. The
3174  //   result of an ->* expression is an lvalue if its second operand
3175  //   is a pointer to data member and a prvalue otherwise.
3176  if (Result->isFunctionType()) {
3177    VK = VK_RValue;
3178    return Context.BoundMemberTy;
3179  } else if (isIndirect) {
3180    VK = VK_LValue;
3181  } else {
3182    VK = lex.get()->getValueKind();
3183  }
3184
3185  return Result;
3186}
3187
3188/// \brief Try to convert a type to another according to C++0x 5.16p3.
3189///
3190/// This is part of the parameter validation for the ? operator. If either
3191/// value operand is a class type, the two operands are attempted to be
3192/// converted to each other. This function does the conversion in one direction.
3193/// It returns true if the program is ill-formed and has already been diagnosed
3194/// as such.
3195static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3196                                SourceLocation QuestionLoc,
3197                                bool &HaveConversion,
3198                                QualType &ToType) {
3199  HaveConversion = false;
3200  ToType = To->getType();
3201
3202  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
3203                                                           SourceLocation());
3204  // C++0x 5.16p3
3205  //   The process for determining whether an operand expression E1 of type T1
3206  //   can be converted to match an operand expression E2 of type T2 is defined
3207  //   as follows:
3208  //   -- If E2 is an lvalue:
3209  bool ToIsLvalue = To->isLValue();
3210  if (ToIsLvalue) {
3211    //   E1 can be converted to match E2 if E1 can be implicitly converted to
3212    //   type "lvalue reference to T2", subject to the constraint that in the
3213    //   conversion the reference must bind directly to E1.
3214    QualType T = Self.Context.getLValueReferenceType(ToType);
3215    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3216
3217    InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3218    if (InitSeq.isDirectReferenceBinding()) {
3219      ToType = T;
3220      HaveConversion = true;
3221      return false;
3222    }
3223
3224    if (InitSeq.isAmbiguous())
3225      return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3226  }
3227
3228  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
3229  //      -- if E1 and E2 have class type, and the underlying class types are
3230  //         the same or one is a base class of the other:
3231  QualType FTy = From->getType();
3232  QualType TTy = To->getType();
3233  const RecordType *FRec = FTy->getAs<RecordType>();
3234  const RecordType *TRec = TTy->getAs<RecordType>();
3235  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
3236                       Self.IsDerivedFrom(FTy, TTy);
3237  if (FRec && TRec &&
3238      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
3239    //         E1 can be converted to match E2 if the class of T2 is the
3240    //         same type as, or a base class of, the class of T1, and
3241    //         [cv2 > cv1].
3242    if (FRec == TRec || FDerivedFromT) {
3243      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
3244        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3245        InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3246        if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
3247          HaveConversion = true;
3248          return false;
3249        }
3250
3251        if (InitSeq.isAmbiguous())
3252          return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3253      }
3254    }
3255
3256    return false;
3257  }
3258
3259  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
3260  //        implicitly converted to the type that expression E2 would have
3261  //        if E2 were converted to an rvalue (or the type it has, if E2 is
3262  //        an rvalue).
3263  //
3264  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3265  // to the array-to-pointer or function-to-pointer conversions.
3266  if (!TTy->getAs<TagType>())
3267    TTy = TTy.getUnqualifiedType();
3268
3269  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3270  InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3271  HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
3272  ToType = TTy;
3273  if (InitSeq.isAmbiguous())
3274    return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3275
3276  return false;
3277}
3278
3279/// \brief Try to find a common type for two according to C++0x 5.16p5.
3280///
3281/// This is part of the parameter validation for the ? operator. If either
3282/// value operand is a class type, overload resolution is used to find a
3283/// conversion to a common type.
3284static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
3285                                    SourceLocation QuestionLoc) {
3286  Expr *Args[2] = { LHS.get(), RHS.get() };
3287  OverloadCandidateSet CandidateSet(QuestionLoc);
3288  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3289                                    CandidateSet);
3290
3291  OverloadCandidateSet::iterator Best;
3292  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
3293    case OR_Success: {
3294      // We found a match. Perform the conversions on the arguments and move on.
3295      ExprResult LHSRes =
3296        Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3297                                       Best->Conversions[0], Sema::AA_Converting);
3298      if (LHSRes.isInvalid())
3299        break;
3300      LHS = move(LHSRes);
3301
3302      ExprResult RHSRes =
3303        Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3304                                       Best->Conversions[1], Sema::AA_Converting);
3305      if (RHSRes.isInvalid())
3306        break;
3307      RHS = move(RHSRes);
3308      if (Best->Function)
3309        Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
3310      return false;
3311    }
3312
3313    case OR_No_Viable_Function:
3314
3315      // Emit a better diagnostic if one of the expressions is a null pointer
3316      // constant and the other is a pointer type. In this case, the user most
3317      // likely forgot to take the address of the other expression.
3318      if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3319        return true;
3320
3321      Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3322        << LHS.get()->getType() << RHS.get()->getType()
3323        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3324      return true;
3325
3326    case OR_Ambiguous:
3327      Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
3328        << LHS.get()->getType() << RHS.get()->getType()
3329        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3330      // FIXME: Print the possible common types by printing the return types of
3331      // the viable candidates.
3332      break;
3333
3334    case OR_Deleted:
3335      assert(false && "Conditional operator has only built-in overloads");
3336      break;
3337  }
3338  return true;
3339}
3340
3341/// \brief Perform an "extended" implicit conversion as returned by
3342/// TryClassUnification.
3343static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
3344  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3345  InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
3346                                                           SourceLocation());
3347  Expr *Arg = E.take();
3348  InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3349  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
3350  if (Result.isInvalid())
3351    return true;
3352
3353  E = Result;
3354  return false;
3355}
3356
3357/// \brief Check the operands of ?: under C++ semantics.
3358///
3359/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3360/// extension. In this case, LHS == Cond. (But they're not aliases.)
3361QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
3362                                           ExprValueKind &VK, ExprObjectKind &OK,
3363                                           SourceLocation QuestionLoc) {
3364  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3365  // interface pointers.
3366
3367  // C++0x 5.16p1
3368  //   The first expression is contextually converted to bool.
3369  if (!Cond.get()->isTypeDependent()) {
3370    ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3371    if (CondRes.isInvalid())
3372      return QualType();
3373    Cond = move(CondRes);
3374  }
3375
3376  // Assume r-value.
3377  VK = VK_RValue;
3378  OK = OK_Ordinary;
3379
3380  // Either of the arguments dependent?
3381  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
3382    return Context.DependentTy;
3383
3384  // C++0x 5.16p2
3385  //   If either the second or the third operand has type (cv) void, ...
3386  QualType LTy = LHS.get()->getType();
3387  QualType RTy = RHS.get()->getType();
3388  bool LVoid = LTy->isVoidType();
3389  bool RVoid = RTy->isVoidType();
3390  if (LVoid || RVoid) {
3391    //   ... then the [l2r] conversions are performed on the second and third
3392    //   operands ...
3393    LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3394    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3395    if (LHS.isInvalid() || RHS.isInvalid())
3396      return QualType();
3397    LTy = LHS.get()->getType();
3398    RTy = RHS.get()->getType();
3399
3400    //   ... and one of the following shall hold:
3401    //   -- The second or the third operand (but not both) is a throw-
3402    //      expression; the result is of the type of the other and is an rvalue.
3403    bool LThrow = isa<CXXThrowExpr>(LHS.get());
3404    bool RThrow = isa<CXXThrowExpr>(RHS.get());
3405    if (LThrow && !RThrow)
3406      return RTy;
3407    if (RThrow && !LThrow)
3408      return LTy;
3409
3410    //   -- Both the second and third operands have type void; the result is of
3411    //      type void and is an rvalue.
3412    if (LVoid && RVoid)
3413      return Context.VoidTy;
3414
3415    // Neither holds, error.
3416    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3417      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3418      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3419    return QualType();
3420  }
3421
3422  // Neither is void.
3423
3424  // C++0x 5.16p3
3425  //   Otherwise, if the second and third operand have different types, and
3426  //   either has (cv) class type, and attempt is made to convert each of those
3427  //   operands to the other.
3428  if (!Context.hasSameType(LTy, RTy) &&
3429      (LTy->isRecordType() || RTy->isRecordType())) {
3430    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3431    // These return true if a single direction is already ambiguous.
3432    QualType L2RType, R2LType;
3433    bool HaveL2R, HaveR2L;
3434    if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
3435      return QualType();
3436    if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
3437      return QualType();
3438
3439    //   If both can be converted, [...] the program is ill-formed.
3440    if (HaveL2R && HaveR2L) {
3441      Diag(QuestionLoc, diag::err_conditional_ambiguous)
3442        << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3443      return QualType();
3444    }
3445
3446    //   If exactly one conversion is possible, that conversion is applied to
3447    //   the chosen operand and the converted operands are used in place of the
3448    //   original operands for the remainder of this section.
3449    if (HaveL2R) {
3450      if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
3451        return QualType();
3452      LTy = LHS.get()->getType();
3453    } else if (HaveR2L) {
3454      if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
3455        return QualType();
3456      RTy = RHS.get()->getType();
3457    }
3458  }
3459
3460  // C++0x 5.16p4
3461  //   If the second and third operands are glvalues of the same value
3462  //   category and have the same type, the result is of that type and
3463  //   value category and it is a bit-field if the second or the third
3464  //   operand is a bit-field, or if both are bit-fields.
3465  // We only extend this to bitfields, not to the crazy other kinds of
3466  // l-values.
3467  bool Same = Context.hasSameType(LTy, RTy);
3468  if (Same &&
3469      LHS.get()->isGLValue() &&
3470      LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3471      LHS.get()->isOrdinaryOrBitFieldObject() &&
3472      RHS.get()->isOrdinaryOrBitFieldObject()) {
3473    VK = LHS.get()->getValueKind();
3474    if (LHS.get()->getObjectKind() == OK_BitField ||
3475        RHS.get()->getObjectKind() == OK_BitField)
3476      OK = OK_BitField;
3477    return LTy;
3478  }
3479
3480  // C++0x 5.16p5
3481  //   Otherwise, the result is an rvalue. If the second and third operands
3482  //   do not have the same type, and either has (cv) class type, ...
3483  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3484    //   ... overload resolution is used to determine the conversions (if any)
3485    //   to be applied to the operands. If the overload resolution fails, the
3486    //   program is ill-formed.
3487    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3488      return QualType();
3489  }
3490
3491  // C++0x 5.16p6
3492  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3493  //   conversions are performed on the second and third operands.
3494  LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3495  RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3496  if (LHS.isInvalid() || RHS.isInvalid())
3497    return QualType();
3498  LTy = LHS.get()->getType();
3499  RTy = RHS.get()->getType();
3500
3501  //   After those conversions, one of the following shall hold:
3502  //   -- The second and third operands have the same type; the result
3503  //      is of that type. If the operands have class type, the result
3504  //      is a prvalue temporary of the result type, which is
3505  //      copy-initialized from either the second operand or the third
3506  //      operand depending on the value of the first operand.
3507  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3508    if (LTy->isRecordType()) {
3509      // The operands have class type. Make a temporary copy.
3510      InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
3511      ExprResult LHSCopy = PerformCopyInitialization(Entity,
3512                                                     SourceLocation(),
3513                                                     LHS);
3514      if (LHSCopy.isInvalid())
3515        return QualType();
3516
3517      ExprResult RHSCopy = PerformCopyInitialization(Entity,
3518                                                     SourceLocation(),
3519                                                     RHS);
3520      if (RHSCopy.isInvalid())
3521        return QualType();
3522
3523      LHS = LHSCopy;
3524      RHS = RHSCopy;
3525    }
3526
3527    return LTy;
3528  }
3529
3530  // Extension: conditional operator involving vector types.
3531  if (LTy->isVectorType() || RTy->isVectorType())
3532    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3533
3534  //   -- The second and third operands have arithmetic or enumeration type;
3535  //      the usual arithmetic conversions are performed to bring them to a
3536  //      common type, and the result is of that type.
3537  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3538    UsualArithmeticConversions(LHS, RHS);
3539    if (LHS.isInvalid() || RHS.isInvalid())
3540      return QualType();
3541    return LHS.get()->getType();
3542  }
3543
3544  //   -- The second and third operands have pointer type, or one has pointer
3545  //      type and the other is a null pointer constant; pointer conversions
3546  //      and qualification conversions are performed to bring them to their
3547  //      composite pointer type. The result is of the composite pointer type.
3548  //   -- The second and third operands have pointer to member type, or one has
3549  //      pointer to member type and the other is a null pointer constant;
3550  //      pointer to member conversions and qualification conversions are
3551  //      performed to bring them to a common type, whose cv-qualification
3552  //      shall match the cv-qualification of either the second or the third
3553  //      operand. The result is of the common type.
3554  bool NonStandardCompositeType = false;
3555  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
3556                              isSFINAEContext()? 0 : &NonStandardCompositeType);
3557  if (!Composite.isNull()) {
3558    if (NonStandardCompositeType)
3559      Diag(QuestionLoc,
3560           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3561        << LTy << RTy << Composite
3562        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3563
3564    return Composite;
3565  }
3566
3567  // Similarly, attempt to find composite type of two objective-c pointers.
3568  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3569  if (!Composite.isNull())
3570    return Composite;
3571
3572  // Check if we are using a null with a non-pointer type.
3573  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3574    return QualType();
3575
3576  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3577    << LHS.get()->getType() << RHS.get()->getType()
3578    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3579  return QualType();
3580}
3581
3582/// \brief Find a merged pointer type and convert the two expressions to it.
3583///
3584/// This finds the composite pointer type (or member pointer type) for @p E1
3585/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3586/// type and returns it.
3587/// It does not emit diagnostics.
3588///
3589/// \param Loc The location of the operator requiring these two expressions to
3590/// be converted to the composite pointer type.
3591///
3592/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3593/// a non-standard (but still sane) composite type to which both expressions
3594/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3595/// will be set true.
3596QualType Sema::FindCompositePointerType(SourceLocation Loc,
3597                                        Expr *&E1, Expr *&E2,
3598                                        bool *NonStandardCompositeType) {
3599  if (NonStandardCompositeType)
3600    *NonStandardCompositeType = false;
3601
3602  assert(getLangOptions().CPlusPlus && "This function assumes C++");
3603  QualType T1 = E1->getType(), T2 = E2->getType();
3604
3605  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3606      !T2->isAnyPointerType() && !T2->isMemberPointerType())
3607   return QualType();
3608
3609  // C++0x 5.9p2
3610  //   Pointer conversions and qualification conversions are performed on
3611  //   pointer operands to bring them to their composite pointer type. If
3612  //   one operand is a null pointer constant, the composite pointer type is
3613  //   the type of the other operand.
3614  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3615    if (T2->isMemberPointerType())
3616      E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
3617    else
3618      E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
3619    return T2;
3620  }
3621  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3622    if (T1->isMemberPointerType())
3623      E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
3624    else
3625      E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
3626    return T1;
3627  }
3628
3629  // Now both have to be pointers or member pointers.
3630  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3631      (!T2->isPointerType() && !T2->isMemberPointerType()))
3632    return QualType();
3633
3634  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
3635  //   the other has type "pointer to cv2 T" and the composite pointer type is
3636  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3637  //   Otherwise, the composite pointer type is a pointer type similar to the
3638  //   type of one of the operands, with a cv-qualification signature that is
3639  //   the union of the cv-qualification signatures of the operand types.
3640  // In practice, the first part here is redundant; it's subsumed by the second.
3641  // What we do here is, we build the two possible composite types, and try the
3642  // conversions in both directions. If only one works, or if the two composite
3643  // types are the same, we have succeeded.
3644  // FIXME: extended qualifiers?
3645  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3646  QualifierVector QualifierUnion;
3647  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3648      ContainingClassVector;
3649  ContainingClassVector MemberOfClass;
3650  QualType Composite1 = Context.getCanonicalType(T1),
3651           Composite2 = Context.getCanonicalType(T2);
3652  unsigned NeedConstBefore = 0;
3653  do {
3654    const PointerType *Ptr1, *Ptr2;
3655    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3656        (Ptr2 = Composite2->getAs<PointerType>())) {
3657      Composite1 = Ptr1->getPointeeType();
3658      Composite2 = Ptr2->getPointeeType();
3659
3660      // If we're allowed to create a non-standard composite type, keep track
3661      // of where we need to fill in additional 'const' qualifiers.
3662      if (NonStandardCompositeType &&
3663          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3664        NeedConstBefore = QualifierUnion.size();
3665
3666      QualifierUnion.push_back(
3667                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3668      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3669      continue;
3670    }
3671
3672    const MemberPointerType *MemPtr1, *MemPtr2;
3673    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3674        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3675      Composite1 = MemPtr1->getPointeeType();
3676      Composite2 = MemPtr2->getPointeeType();
3677
3678      // If we're allowed to create a non-standard composite type, keep track
3679      // of where we need to fill in additional 'const' qualifiers.
3680      if (NonStandardCompositeType &&
3681          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3682        NeedConstBefore = QualifierUnion.size();
3683
3684      QualifierUnion.push_back(
3685                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3686      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3687                                             MemPtr2->getClass()));
3688      continue;
3689    }
3690
3691    // FIXME: block pointer types?
3692
3693    // Cannot unwrap any more types.
3694    break;
3695  } while (true);
3696
3697  if (NeedConstBefore && NonStandardCompositeType) {
3698    // Extension: Add 'const' to qualifiers that come before the first qualifier
3699    // mismatch, so that our (non-standard!) composite type meets the
3700    // requirements of C++ [conv.qual]p4 bullet 3.
3701    for (unsigned I = 0; I != NeedConstBefore; ++I) {
3702      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3703        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3704        *NonStandardCompositeType = true;
3705      }
3706    }
3707  }
3708
3709  // Rewrap the composites as pointers or member pointers with the union CVRs.
3710  ContainingClassVector::reverse_iterator MOC
3711    = MemberOfClass.rbegin();
3712  for (QualifierVector::reverse_iterator
3713         I = QualifierUnion.rbegin(),
3714         E = QualifierUnion.rend();
3715       I != E; (void)++I, ++MOC) {
3716    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
3717    if (MOC->first && MOC->second) {
3718      // Rebuild member pointer type
3719      Composite1 = Context.getMemberPointerType(
3720                                    Context.getQualifiedType(Composite1, Quals),
3721                                    MOC->first);
3722      Composite2 = Context.getMemberPointerType(
3723                                    Context.getQualifiedType(Composite2, Quals),
3724                                    MOC->second);
3725    } else {
3726      // Rebuild pointer type
3727      Composite1
3728        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3729      Composite2
3730        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
3731    }
3732  }
3733
3734  // Try to convert to the first composite pointer type.
3735  InitializedEntity Entity1
3736    = InitializedEntity::InitializeTemporary(Composite1);
3737  InitializationKind Kind
3738    = InitializationKind::CreateCopy(Loc, SourceLocation());
3739  InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3740  InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
3741
3742  if (E1ToC1 && E2ToC1) {
3743    // Conversion to Composite1 is viable.
3744    if (!Context.hasSameType(Composite1, Composite2)) {
3745      // Composite2 is a different type from Composite1. Check whether
3746      // Composite2 is also viable.
3747      InitializedEntity Entity2
3748        = InitializedEntity::InitializeTemporary(Composite2);
3749      InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3750      InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3751      if (E1ToC2 && E2ToC2) {
3752        // Both Composite1 and Composite2 are viable and are different;
3753        // this is an ambiguity.
3754        return QualType();
3755      }
3756    }
3757
3758    // Convert E1 to Composite1
3759    ExprResult E1Result
3760      = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
3761    if (E1Result.isInvalid())
3762      return QualType();
3763    E1 = E1Result.takeAs<Expr>();
3764
3765    // Convert E2 to Composite1
3766    ExprResult E2Result
3767      = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
3768    if (E2Result.isInvalid())
3769      return QualType();
3770    E2 = E2Result.takeAs<Expr>();
3771
3772    return Composite1;
3773  }
3774
3775  // Check whether Composite2 is viable.
3776  InitializedEntity Entity2
3777    = InitializedEntity::InitializeTemporary(Composite2);
3778  InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3779  InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3780  if (!E1ToC2 || !E2ToC2)
3781    return QualType();
3782
3783  // Convert E1 to Composite2
3784  ExprResult E1Result
3785    = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
3786  if (E1Result.isInvalid())
3787    return QualType();
3788  E1 = E1Result.takeAs<Expr>();
3789
3790  // Convert E2 to Composite2
3791  ExprResult E2Result
3792    = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
3793  if (E2Result.isInvalid())
3794    return QualType();
3795  E2 = E2Result.takeAs<Expr>();
3796
3797  return Composite2;
3798}
3799
3800ExprResult Sema::MaybeBindToTemporary(Expr *E) {
3801  if (!E)
3802    return ExprError();
3803
3804  if (!Context.getLangOptions().CPlusPlus)
3805    return Owned(E);
3806
3807  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3808
3809  const RecordType *RT = E->getType()->getAs<RecordType>();
3810  if (!RT)
3811    return Owned(E);
3812
3813  // If the result is a glvalue, we shouldn't bind it.
3814  if (E->Classify(Context).isGLValue())
3815    return Owned(E);
3816
3817  // That should be enough to guarantee that this type is complete.
3818  // If it has a trivial destructor, we can avoid the extra copy.
3819  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3820  if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
3821    return Owned(E);
3822
3823  CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
3824  ExprTemporaries.push_back(Temp);
3825  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
3826    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
3827    CheckDestructorAccess(E->getExprLoc(), Destructor,
3828                          PDiag(diag::err_access_dtor_temp)
3829                            << E->getType());
3830  }
3831  // FIXME: Add the temporary to the temporaries vector.
3832  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3833}
3834
3835Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
3836  assert(SubExpr && "sub expression can't be null!");
3837
3838  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3839  assert(ExprTemporaries.size() >= FirstTemporary);
3840  if (ExprTemporaries.size() == FirstTemporary)
3841    return SubExpr;
3842
3843  Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3844                                     &ExprTemporaries[FirstTemporary],
3845                                     ExprTemporaries.size() - FirstTemporary);
3846  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3847                        ExprTemporaries.end());
3848
3849  return E;
3850}
3851
3852ExprResult
3853Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
3854  if (SubExpr.isInvalid())
3855    return ExprError();
3856
3857  return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
3858}
3859
3860Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
3861  assert(SubStmt && "sub statement can't be null!");
3862
3863  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3864  assert(ExprTemporaries.size() >= FirstTemporary);
3865  if (ExprTemporaries.size() == FirstTemporary)
3866    return SubStmt;
3867
3868  // FIXME: In order to attach the temporaries, wrap the statement into
3869  // a StmtExpr; currently this is only used for asm statements.
3870  // This is hacky, either create a new CXXStmtWithTemporaries statement or
3871  // a new AsmStmtWithTemporaries.
3872  CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3873                                                      SourceLocation(),
3874                                                      SourceLocation());
3875  Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3876                                   SourceLocation());
3877  return MaybeCreateExprWithCleanups(E);
3878}
3879
3880ExprResult
3881Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
3882                                   tok::TokenKind OpKind, ParsedType &ObjectType,
3883                                   bool &MayBePseudoDestructor) {
3884  // Since this might be a postfix expression, get rid of ParenListExprs.
3885  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3886  if (Result.isInvalid()) return ExprError();
3887  Base = Result.get();
3888
3889  QualType BaseType = Base->getType();
3890  MayBePseudoDestructor = false;
3891  if (BaseType->isDependentType()) {
3892    // If we have a pointer to a dependent type and are using the -> operator,
3893    // the object type is the type that the pointer points to. We might still
3894    // have enough information about that type to do something useful.
3895    if (OpKind == tok::arrow)
3896      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3897        BaseType = Ptr->getPointeeType();
3898
3899    ObjectType = ParsedType::make(BaseType);
3900    MayBePseudoDestructor = true;
3901    return Owned(Base);
3902  }
3903
3904  // C++ [over.match.oper]p8:
3905  //   [...] When operator->returns, the operator-> is applied  to the value
3906  //   returned, with the original second operand.
3907  if (OpKind == tok::arrow) {
3908    // The set of types we've considered so far.
3909    llvm::SmallPtrSet<CanQualType,8> CTypes;
3910    llvm::SmallVector<SourceLocation, 8> Locations;
3911    CTypes.insert(Context.getCanonicalType(BaseType));
3912
3913    while (BaseType->isRecordType()) {
3914      Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3915      if (Result.isInvalid())
3916        return ExprError();
3917      Base = Result.get();
3918      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
3919        Locations.push_back(OpCall->getDirectCallee()->getLocation());
3920      BaseType = Base->getType();
3921      CanQualType CBaseType = Context.getCanonicalType(BaseType);
3922      if (!CTypes.insert(CBaseType)) {
3923        Diag(OpLoc, diag::err_operator_arrow_circular);
3924        for (unsigned i = 0; i < Locations.size(); i++)
3925          Diag(Locations[i], diag::note_declared_at);
3926        return ExprError();
3927      }
3928    }
3929
3930    if (BaseType->isPointerType())
3931      BaseType = BaseType->getPointeeType();
3932  }
3933
3934  // We could end up with various non-record types here, such as extended
3935  // vector types or Objective-C interfaces. Just return early and let
3936  // ActOnMemberReferenceExpr do the work.
3937  if (!BaseType->isRecordType()) {
3938    // C++ [basic.lookup.classref]p2:
3939    //   [...] If the type of the object expression is of pointer to scalar
3940    //   type, the unqualified-id is looked up in the context of the complete
3941    //   postfix-expression.
3942    //
3943    // This also indicates that we should be parsing a
3944    // pseudo-destructor-name.
3945    ObjectType = ParsedType();
3946    MayBePseudoDestructor = true;
3947    return Owned(Base);
3948  }
3949
3950  // The object type must be complete (or dependent).
3951  if (!BaseType->isDependentType() &&
3952      RequireCompleteType(OpLoc, BaseType,
3953                          PDiag(diag::err_incomplete_member_access)))
3954    return ExprError();
3955
3956  // C++ [basic.lookup.classref]p2:
3957  //   If the id-expression in a class member access (5.2.5) is an
3958  //   unqualified-id, and the type of the object expression is of a class
3959  //   type C (or of pointer to a class type C), the unqualified-id is looked
3960  //   up in the scope of class C. [...]
3961  ObjectType = ParsedType::make(BaseType);
3962  return move(Base);
3963}
3964
3965ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
3966                                                   Expr *MemExpr) {
3967  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
3968  Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3969    << isa<CXXPseudoDestructorExpr>(MemExpr)
3970    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
3971
3972  return ActOnCallExpr(/*Scope*/ 0,
3973                       MemExpr,
3974                       /*LPLoc*/ ExpectedLParenLoc,
3975                       MultiExprArg(),
3976                       /*RPLoc*/ ExpectedLParenLoc);
3977}
3978
3979ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
3980                                           SourceLocation OpLoc,
3981                                           tok::TokenKind OpKind,
3982                                           const CXXScopeSpec &SS,
3983                                           TypeSourceInfo *ScopeTypeInfo,
3984                                           SourceLocation CCLoc,
3985                                           SourceLocation TildeLoc,
3986                                         PseudoDestructorTypeStorage Destructed,
3987                                           bool HasTrailingLParen) {
3988  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
3989
3990  // C++ [expr.pseudo]p2:
3991  //   The left-hand side of the dot operator shall be of scalar type. The
3992  //   left-hand side of the arrow operator shall be of pointer to scalar type.
3993  //   This scalar type is the object type.
3994  QualType ObjectType = Base->getType();
3995  if (OpKind == tok::arrow) {
3996    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3997      ObjectType = Ptr->getPointeeType();
3998    } else if (!Base->isTypeDependent()) {
3999      // The user wrote "p->" when she probably meant "p."; fix it.
4000      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4001        << ObjectType << true
4002        << FixItHint::CreateReplacement(OpLoc, ".");
4003      if (isSFINAEContext())
4004        return ExprError();
4005
4006      OpKind = tok::period;
4007    }
4008  }
4009
4010  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
4011    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4012      << ObjectType << Base->getSourceRange();
4013    return ExprError();
4014  }
4015
4016  // C++ [expr.pseudo]p2:
4017  //   [...] The cv-unqualified versions of the object type and of the type
4018  //   designated by the pseudo-destructor-name shall be the same type.
4019  if (DestructedTypeInfo) {
4020    QualType DestructedType = DestructedTypeInfo->getType();
4021    SourceLocation DestructedTypeStart
4022      = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
4023    if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
4024        !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4025      Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4026        << ObjectType << DestructedType << Base->getSourceRange()
4027        << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4028
4029      // Recover by setting the destructed type to the object type.
4030      DestructedType = ObjectType;
4031      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4032                                                           DestructedTypeStart);
4033      Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4034    }
4035  }
4036
4037  // C++ [expr.pseudo]p2:
4038  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4039  //   form
4040  //
4041  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
4042  //
4043  //   shall designate the same scalar type.
4044  if (ScopeTypeInfo) {
4045    QualType ScopeType = ScopeTypeInfo->getType();
4046    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
4047        !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
4048
4049      Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
4050           diag::err_pseudo_dtor_type_mismatch)
4051        << ObjectType << ScopeType << Base->getSourceRange()
4052        << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
4053
4054      ScopeType = QualType();
4055      ScopeTypeInfo = 0;
4056    }
4057  }
4058
4059  Expr *Result
4060    = new (Context) CXXPseudoDestructorExpr(Context, Base,
4061                                            OpKind == tok::arrow, OpLoc,
4062                                            SS.getWithLocInContext(Context),
4063                                            ScopeTypeInfo,
4064                                            CCLoc,
4065                                            TildeLoc,
4066                                            Destructed);
4067
4068  if (HasTrailingLParen)
4069    return Owned(Result);
4070
4071  return DiagnoseDtorReference(Destructed.getLocation(), Result);
4072}
4073
4074ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4075                                           SourceLocation OpLoc,
4076                                           tok::TokenKind OpKind,
4077                                           CXXScopeSpec &SS,
4078                                           UnqualifiedId &FirstTypeName,
4079                                           SourceLocation CCLoc,
4080                                           SourceLocation TildeLoc,
4081                                           UnqualifiedId &SecondTypeName,
4082                                           bool HasTrailingLParen) {
4083  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4084          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4085         "Invalid first type name in pseudo-destructor");
4086  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4087          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4088         "Invalid second type name in pseudo-destructor");
4089
4090  // C++ [expr.pseudo]p2:
4091  //   The left-hand side of the dot operator shall be of scalar type. The
4092  //   left-hand side of the arrow operator shall be of pointer to scalar type.
4093  //   This scalar type is the object type.
4094  QualType ObjectType = Base->getType();
4095  if (OpKind == tok::arrow) {
4096    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4097      ObjectType = Ptr->getPointeeType();
4098    } else if (!ObjectType->isDependentType()) {
4099      // The user wrote "p->" when she probably meant "p."; fix it.
4100      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4101        << ObjectType << true
4102        << FixItHint::CreateReplacement(OpLoc, ".");
4103      if (isSFINAEContext())
4104        return ExprError();
4105
4106      OpKind = tok::period;
4107    }
4108  }
4109
4110  // Compute the object type that we should use for name lookup purposes. Only
4111  // record types and dependent types matter.
4112  ParsedType ObjectTypePtrForLookup;
4113  if (!SS.isSet()) {
4114    if (ObjectType->isRecordType())
4115      ObjectTypePtrForLookup = ParsedType::make(ObjectType);
4116    else if (ObjectType->isDependentType())
4117      ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
4118  }
4119
4120  // Convert the name of the type being destructed (following the ~) into a
4121  // type (with source-location information).
4122  QualType DestructedType;
4123  TypeSourceInfo *DestructedTypeInfo = 0;
4124  PseudoDestructorTypeStorage Destructed;
4125  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4126    ParsedType T = getTypeName(*SecondTypeName.Identifier,
4127                               SecondTypeName.StartLocation,
4128                               S, &SS, true, false, ObjectTypePtrForLookup);
4129    if (!T &&
4130        ((SS.isSet() && !computeDeclContext(SS, false)) ||
4131         (!SS.isSet() && ObjectType->isDependentType()))) {
4132      // The name of the type being destroyed is a dependent name, and we
4133      // couldn't find anything useful in scope. Just store the identifier and
4134      // it's location, and we'll perform (qualified) name lookup again at
4135      // template instantiation time.
4136      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4137                                               SecondTypeName.StartLocation);
4138    } else if (!T) {
4139      Diag(SecondTypeName.StartLocation,
4140           diag::err_pseudo_dtor_destructor_non_type)
4141        << SecondTypeName.Identifier << ObjectType;
4142      if (isSFINAEContext())
4143        return ExprError();
4144
4145      // Recover by assuming we had the right type all along.
4146      DestructedType = ObjectType;
4147    } else
4148      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
4149  } else {
4150    // Resolve the template-id to a type.
4151    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
4152    ASTTemplateArgsPtr TemplateArgsPtr(*this,
4153                                       TemplateId->getTemplateArgs(),
4154                                       TemplateId->NumArgs);
4155    TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4156                                       TemplateId->Template,
4157                                       TemplateId->TemplateNameLoc,
4158                                       TemplateId->LAngleLoc,
4159                                       TemplateArgsPtr,
4160                                       TemplateId->RAngleLoc);
4161    if (T.isInvalid() || !T.get()) {
4162      // Recover by assuming we had the right type all along.
4163      DestructedType = ObjectType;
4164    } else
4165      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
4166  }
4167
4168  // If we've performed some kind of recovery, (re-)build the type source
4169  // information.
4170  if (!DestructedType.isNull()) {
4171    if (!DestructedTypeInfo)
4172      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
4173                                                  SecondTypeName.StartLocation);
4174    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4175  }
4176
4177  // Convert the name of the scope type (the type prior to '::') into a type.
4178  TypeSourceInfo *ScopeTypeInfo = 0;
4179  QualType ScopeType;
4180  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4181      FirstTypeName.Identifier) {
4182    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4183      ParsedType T = getTypeName(*FirstTypeName.Identifier,
4184                                 FirstTypeName.StartLocation,
4185                                 S, &SS, true, false, ObjectTypePtrForLookup);
4186      if (!T) {
4187        Diag(FirstTypeName.StartLocation,
4188             diag::err_pseudo_dtor_destructor_non_type)
4189          << FirstTypeName.Identifier << ObjectType;
4190
4191        if (isSFINAEContext())
4192          return ExprError();
4193
4194        // Just drop this type. It's unnecessary anyway.
4195        ScopeType = QualType();
4196      } else
4197        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
4198    } else {
4199      // Resolve the template-id to a type.
4200      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
4201      ASTTemplateArgsPtr TemplateArgsPtr(*this,
4202                                         TemplateId->getTemplateArgs(),
4203                                         TemplateId->NumArgs);
4204      TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4205                                         TemplateId->Template,
4206                                         TemplateId->TemplateNameLoc,
4207                                         TemplateId->LAngleLoc,
4208                                         TemplateArgsPtr,
4209                                         TemplateId->RAngleLoc);
4210      if (T.isInvalid() || !T.get()) {
4211        // Recover by dropping this type.
4212        ScopeType = QualType();
4213      } else
4214        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
4215    }
4216  }
4217
4218  if (!ScopeType.isNull() && !ScopeTypeInfo)
4219    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4220                                                  FirstTypeName.StartLocation);
4221
4222
4223  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
4224                                   ScopeTypeInfo, CCLoc, TildeLoc,
4225                                   Destructed, HasTrailingLParen);
4226}
4227
4228ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
4229                                        CXXMethodDecl *Method) {
4230  ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4231                                          FoundDecl, Method);
4232  if (Exp.isInvalid())
4233    return true;
4234
4235  MemberExpr *ME =
4236      new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
4237                               SourceLocation(), Method->getType(),
4238                               VK_RValue, OK_Ordinary);
4239  QualType ResultType = Method->getResultType();
4240  ExprValueKind VK = Expr::getValueKindForType(ResultType);
4241  ResultType = ResultType.getNonLValueExprType(Context);
4242
4243  MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
4244  CXXMemberCallExpr *CE =
4245    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
4246                                    Exp.get()->getLocEnd());
4247  return CE;
4248}
4249
4250ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4251                                      SourceLocation RParen) {
4252  return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4253                                             Operand->CanThrow(Context),
4254                                             KeyLoc, RParen));
4255}
4256
4257ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4258                                   Expr *Operand, SourceLocation RParen) {
4259  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
4260}
4261
4262/// Perform the conversions required for an expression used in a
4263/// context that ignores the result.
4264ExprResult Sema::IgnoredValueConversions(Expr *E) {
4265  // C99 6.3.2.1:
4266  //   [Except in specific positions,] an lvalue that does not have
4267  //   array type is converted to the value stored in the
4268  //   designated object (and is no longer an lvalue).
4269  if (E->isRValue()) return Owned(E);
4270
4271  // We always want to do this on ObjC property references.
4272  if (E->getObjectKind() == OK_ObjCProperty) {
4273    ExprResult Res = ConvertPropertyForRValue(E);
4274    if (Res.isInvalid()) return Owned(E);
4275    E = Res.take();
4276    if (E->isRValue()) return Owned(E);
4277  }
4278
4279  // Otherwise, this rule does not apply in C++, at least not for the moment.
4280  if (getLangOptions().CPlusPlus) return Owned(E);
4281
4282  // GCC seems to also exclude expressions of incomplete enum type.
4283  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4284    if (!T->getDecl()->isComplete()) {
4285      // FIXME: stupid workaround for a codegen bug!
4286      E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4287      return Owned(E);
4288    }
4289  }
4290
4291  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4292  if (Res.isInvalid())
4293    return Owned(E);
4294  E = Res.take();
4295
4296  if (!E->getType()->isVoidType())
4297    RequireCompleteType(E->getExprLoc(), E->getType(),
4298                        diag::err_incomplete_type);
4299  return Owned(E);
4300}
4301
4302ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4303  ExprResult FullExpr = Owned(FE);
4304
4305  if (!FullExpr.get())
4306    return ExprError();
4307
4308  if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
4309    return ExprError();
4310
4311  FullExpr = CheckPlaceholderExpr(FullExpr.take());
4312  if (FullExpr.isInvalid())
4313    return ExprError();
4314
4315  FullExpr = IgnoredValueConversions(FullExpr.take());
4316  if (FullExpr.isInvalid())
4317    return ExprError();
4318
4319  CheckImplicitConversions(FullExpr.get());
4320  return MaybeCreateExprWithCleanups(FullExpr);
4321}
4322
4323StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4324  if (!FullStmt) return StmtError();
4325
4326  return MaybeCreateStmtWithCleanups(FullStmt);
4327}
4328