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