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