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