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