]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/SemaExprCXX.cpp
Update clang to r104832.
[FreeBSD/FreeBSD.git] / 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 "Sema.h"
15 #include "SemaInit.h"
16 #include "Lookup.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/TypeLoc.h"
21 #include "clang/Basic/PartialDiagnostic.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Parse/DeclSpec.h"
25 #include "clang/Parse/Template.h"
26 #include "llvm/ADT/STLExtras.h"
27 using namespace clang;
28
29 Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30                                         IdentifierInfo &II, 
31                                         SourceLocation NameLoc,
32                                         Scope *S, CXXScopeSpec &SS,
33                                         TypeTy *ObjectTypePtr,
34                                         bool EnteringContext) {
35   // Determine where to perform name lookup.
36
37   // FIXME: This area of the standard is very messy, and the current
38   // wording is rather unclear about which scopes we search for the
39   // destructor name; see core issues 399 and 555. Issue 399 in
40   // particular shows where the current description of destructor name
41   // lookup is completely out of line with existing practice, e.g.,
42   // this appears to be ill-formed:
43   //
44   //   namespace N {
45   //     template <typename T> struct S {
46   //       ~S();
47   //     };
48   //   }
49   //
50   //   void f(N::S<int>* s) {
51   //     s->N::S<int>::~S();
52   //   }
53   //
54   // See also PR6358 and PR6359.
55   QualType SearchType;
56   DeclContext *LookupCtx = 0;
57   bool isDependent = false;
58   bool LookInScope = false;
59
60   // If we have an object type, it's because we are in a
61   // pseudo-destructor-expression or a member access expression, and
62   // we know what type we're looking for.
63   if (ObjectTypePtr)
64     SearchType = GetTypeFromParser(ObjectTypePtr);
65
66   if (SS.isSet()) {
67     NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68     
69     bool AlreadySearched = false;
70     bool LookAtPrefix = true;
71     if (!getLangOptions().CPlusPlus0x) {
72       // C++ [basic.lookup.qual]p6:
73       //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 
74       //   the type-names are looked up as types in the scope designated by the
75       //   nested-name-specifier. In a qualified-id of the form:
76       // 
77       //     ::[opt] nested-name-specifier  ̃ class-name 
78       //
79       //   where the nested-name-specifier designates a namespace scope, and in
80       //   a qualified-id of the form:
81       //
82       //     ::opt nested-name-specifier class-name ::  ̃ class-name 
83       //
84       //   the class-names are looked up as types in the scope designated by 
85       //   the nested-name-specifier.
86       //
87       // Here, we check the first case (completely) and determine whether the
88       // code below is permitted to look at the prefix of the 
89       // nested-name-specifier (as we do in C++0x).
90       DeclContext *DC = computeDeclContext(SS, EnteringContext);
91       if (DC && DC->isFileContext()) {
92         AlreadySearched = true;
93         LookupCtx = DC;
94         isDependent = false;
95       } else if (DC && isa<CXXRecordDecl>(DC))
96         LookAtPrefix = false;
97     }
98     
99     // C++0x [basic.lookup.qual]p6:
100     //   If a pseudo-destructor-name (5.2.4) contains a
101     //   nested-name-specifier, the type-names are looked up as types
102     //   in the scope designated by the nested-name-specifier. Similarly, in 
103     //   a qualified-id of the form:
104     //
105     //     :: [opt] nested-name-specifier[opt] class-name :: ~class-name 
106     //
107     //   the second class-name is looked up in the same scope as the first.
108     //
109     // To implement this, we look at the prefix of the
110     // nested-name-specifier we were given, and determine the lookup
111     // context from that.
112     //
113     // We also fold in the second case from the C++03 rules quoted further 
114     // above.
115     NestedNameSpecifier *Prefix = 0;
116     if (AlreadySearched) {
117       // Nothing left to do.
118     } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119       CXXScopeSpec PrefixSS;
120       PrefixSS.setScopeRep(Prefix);
121       LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122       isDependent = isDependentScopeSpecifier(PrefixSS);
123     } else if (getLangOptions().CPlusPlus0x &&
124                (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125       if (!LookupCtx->isTranslationUnit())
126         LookupCtx = LookupCtx->getParent();
127       isDependent = LookupCtx && LookupCtx->isDependentContext();
128     } else if (ObjectTypePtr) {
129       LookupCtx = computeDeclContext(SearchType);
130       isDependent = SearchType->isDependentType();
131     } else {
132       LookupCtx = computeDeclContext(SS, EnteringContext);
133       isDependent = LookupCtx && LookupCtx->isDependentContext();
134     }
135     
136     LookInScope = false;
137   } else if (ObjectTypePtr) {
138     // C++ [basic.lookup.classref]p3:
139     //   If the unqualified-id is ~type-name, the type-name is looked up
140     //   in the context of the entire postfix-expression. If the type T
141     //   of the object expression is of a class type C, the type-name is
142     //   also looked up in the scope of class C. At least one of the
143     //   lookups shall find a name that refers to (possibly
144     //   cv-qualified) T.
145     LookupCtx = computeDeclContext(SearchType);
146     isDependent = SearchType->isDependentType();
147     assert((isDependent || !SearchType->isIncompleteType()) && 
148            "Caller should have completed object type");
149
150     LookInScope = true;
151   } else {
152     // Perform lookup into the current scope (only).
153     LookInScope = true;
154   }
155
156   LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157   for (unsigned Step = 0; Step != 2; ++Step) {
158     // Look for the name first in the computed lookup context (if we
159     // have one) and, if that fails to find a match, in the sope (if
160     // we're allowed to look there).
161     Found.clear();
162     if (Step == 0 && LookupCtx)
163       LookupQualifiedName(Found, LookupCtx);
164     else if (Step == 1 && LookInScope && S)
165       LookupName(Found, S);
166     else
167       continue;
168
169     // FIXME: Should we be suppressing ambiguities here?
170     if (Found.isAmbiguous())
171       return 0;
172
173     if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174       QualType T = Context.getTypeDeclType(Type);
175
176       if (SearchType.isNull() || SearchType->isDependentType() ||
177           Context.hasSameUnqualifiedType(T, SearchType)) {
178         // We found our type!
179
180         return T.getAsOpaquePtr();
181       }
182     }
183
184     // If the name that we found is a class template name, and it is
185     // the same name as the template name in the last part of the
186     // nested-name-specifier (if present) or the object type, then
187     // this is the destructor for that class.
188     // FIXME: This is a workaround until we get real drafting for core
189     // issue 399, for which there isn't even an obvious direction. 
190     if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191       QualType MemberOfType;
192       if (SS.isSet()) {
193         if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194           // Figure out the type of the context, if it has one.
195           if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196             MemberOfType = Context.getTypeDeclType(Record);
197         }
198       }
199       if (MemberOfType.isNull())
200         MemberOfType = SearchType;
201       
202       if (MemberOfType.isNull())
203         continue;
204
205       // We're referring into a class template specialization. If the
206       // class template we found is the same as the template being
207       // specialized, we found what we are looking for.
208       if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209         if (ClassTemplateSpecializationDecl *Spec
210               = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211           if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212                 Template->getCanonicalDecl())
213             return MemberOfType.getAsOpaquePtr();
214         }
215
216         continue;
217       }
218       
219       // We're referring to an unresolved class template
220       // specialization. Determine whether we class template we found
221       // is the same as the template being specialized or, if we don't
222       // know which template is being specialized, that it at least
223       // has the same name.
224       if (const TemplateSpecializationType *SpecType
225             = MemberOfType->getAs<TemplateSpecializationType>()) {
226         TemplateName SpecName = SpecType->getTemplateName();
227
228         // The class template we found is the same template being
229         // specialized.
230         if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231           if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232             return MemberOfType.getAsOpaquePtr();
233
234           continue;
235         }
236
237         // The class template we found has the same name as the
238         // (dependent) template name being specialized.
239         if (DependentTemplateName *DepTemplate 
240                                     = SpecName.getAsDependentTemplateName()) {
241           if (DepTemplate->isIdentifier() &&
242               DepTemplate->getIdentifier() == Template->getIdentifier())
243             return MemberOfType.getAsOpaquePtr();
244
245           continue;
246         }
247       }
248     }
249   }
250
251   if (isDependent) {
252     // We didn't find our type, but that's okay: it's dependent
253     // anyway.
254     NestedNameSpecifier *NNS = 0;
255     SourceRange Range;
256     if (SS.isSet()) {
257       NNS = (NestedNameSpecifier *)SS.getScopeRep();
258       Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259     } else {
260       NNS = NestedNameSpecifier::Create(Context, &II);
261       Range = SourceRange(NameLoc);
262     }
263
264     return CheckTypenameType(ETK_None, NNS, II, SourceLocation(),
265                              Range, NameLoc).getAsOpaquePtr();
266   }
267
268   if (ObjectTypePtr)
269     Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
270       << &II;        
271   else
272     Diag(NameLoc, diag::err_destructor_class_name);
273
274   return 0;
275 }
276
277 /// \brief Build a C++ typeid expression with a type operand.
278 Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
279                                             SourceLocation TypeidLoc,
280                                             TypeSourceInfo *Operand,
281                                             SourceLocation RParenLoc) {
282   // C++ [expr.typeid]p4:
283   //   The top-level cv-qualifiers of the lvalue expression or the type-id 
284   //   that is the operand of typeid are always ignored.
285   //   If the type of the type-id is a class type or a reference to a class 
286   //   type, the class shall be completely-defined.
287   QualType T = Operand->getType().getNonReferenceType();
288   if (T->getAs<RecordType>() &&
289       RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
290     return ExprError();
291   
292   return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
293                                            Operand,
294                                            SourceRange(TypeidLoc, RParenLoc)));
295 }
296
297 /// \brief Build a C++ typeid expression with an expression operand.
298 Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
299                                             SourceLocation TypeidLoc,
300                                             ExprArg Operand,
301                                             SourceLocation RParenLoc) {
302   bool isUnevaluatedOperand = true;
303   Expr *E = static_cast<Expr *>(Operand.get());
304   if (E && !E->isTypeDependent()) {
305     QualType T = E->getType();
306     if (const RecordType *RecordT = T->getAs<RecordType>()) {
307       CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
308       // C++ [expr.typeid]p3:
309       //   [...] If the type of the expression is a class type, the class
310       //   shall be completely-defined.
311       if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
312         return ExprError();
313       
314       // C++ [expr.typeid]p3:
315       //   When typeid is applied to an expression other than an lvalue of a
316       //   polymorphic class type [...] [the] expression is an unevaluated
317       //   operand. [...]
318       if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) {
319         isUnevaluatedOperand = false;
320
321         // We require a vtable to query the type at run time.
322         MarkVTableUsed(TypeidLoc, RecordD);
323       }
324     }
325     
326     // C++ [expr.typeid]p4:
327     //   [...] If the type of the type-id is a reference to a possibly
328     //   cv-qualified type, the result of the typeid expression refers to a 
329     //   std::type_info object representing the cv-unqualified referenced 
330     //   type.
331     if (T.hasQualifiers()) {
332       ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
333                         E->isLvalue(Context));
334       Operand.release();
335       Operand = Owned(E);
336     }
337   }
338   
339   // If this is an unevaluated operand, clear out the set of
340   // declaration references we have been computing and eliminate any
341   // temporaries introduced in its computation.
342   if (isUnevaluatedOperand)
343     ExprEvalContexts.back().Context = Unevaluated;
344   
345   return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
346                                            Operand.takeAs<Expr>(),
347                                            SourceRange(TypeidLoc, RParenLoc)));  
348 }
349
350 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
351 Action::OwningExprResult
352 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
353                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
354   // Find the std::type_info type.
355   if (!StdNamespace)
356     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
357
358   IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
359   LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
360   LookupQualifiedName(R, StdNamespace);
361   RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
362   if (!TypeInfoRecordDecl)
363     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
364   
365   QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
366   
367   if (isType) {
368     // The operand is a type; handle it as such.
369     TypeSourceInfo *TInfo = 0;
370     QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
371     if (T.isNull())
372       return ExprError();
373     
374     if (!TInfo)
375       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
376
377     return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
378   }
379
380   // The operand is an expression.  
381   return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
382 }
383
384 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
385 Action::OwningExprResult
386 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
387   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
388          "Unknown C++ Boolean value!");
389   return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
390                                                 Context.BoolTy, OpLoc));
391 }
392
393 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
394 Action::OwningExprResult
395 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
396   return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
397 }
398
399 /// ActOnCXXThrow - Parse throw expressions.
400 Action::OwningExprResult
401 Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
402   Expr *Ex = E.takeAs<Expr>();
403   if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
404     return ExprError();
405   return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
406 }
407
408 /// CheckCXXThrowOperand - Validate the operand of a throw.
409 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
410   // C++ [except.throw]p3:
411   //   A throw-expression initializes a temporary object, called the exception
412   //   object, the type of which is determined by removing any top-level
413   //   cv-qualifiers from the static type of the operand of throw and adjusting
414   //   the type from "array of T" or "function returning T" to "pointer to T" 
415   //   or "pointer to function returning T", [...]
416   if (E->getType().hasQualifiers())
417     ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
418                       E->isLvalue(Context) == Expr::LV_Valid);
419   
420   DefaultFunctionArrayConversion(E);
421
422   //   If the type of the exception would be an incomplete type or a pointer
423   //   to an incomplete type other than (cv) void the program is ill-formed.
424   QualType Ty = E->getType();
425   bool isPointer = false;
426   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
427     Ty = Ptr->getPointeeType();
428     isPointer = true;
429   }
430   if (!isPointer || !Ty->isVoidType()) {
431     if (RequireCompleteType(ThrowLoc, Ty,
432                             PDiag(isPointer ? diag::err_throw_incomplete_ptr
433                                             : diag::err_throw_incomplete)
434                               << E->getSourceRange()))
435       return true;
436
437     if (RequireNonAbstractType(ThrowLoc, E->getType(),
438                                PDiag(diag::err_throw_abstract_type)
439                                  << E->getSourceRange()))
440       return true;
441   }
442
443   // Initialize the exception result.  This implicitly weeds out
444   // abstract types or types with inaccessible copy constructors.
445   // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
446   InitializedEntity Entity =
447     InitializedEntity::InitializeException(ThrowLoc, E->getType(),
448                                            /*NRVO=*/false);
449   OwningExprResult Res = PerformCopyInitialization(Entity,
450                                                    SourceLocation(),
451                                                    Owned(E));
452   if (Res.isInvalid())
453     return true;
454   E = Res.takeAs<Expr>();
455
456   // If we are throwing a polymorphic class type or pointer thereof,
457   // exception handling will make use of the vtable.
458   if (const RecordType *RecordTy = Ty->getAs<RecordType>())
459     MarkVTableUsed(ThrowLoc, cast<CXXRecordDecl>(RecordTy->getDecl()));
460     
461   return false;
462 }
463
464 Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
465   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
466   /// is a non-lvalue expression whose value is the address of the object for
467   /// which the function is called.
468
469   DeclContext *DC = getFunctionLevelDeclContext();
470   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
471     if (MD->isInstance())
472       return Owned(new (Context) CXXThisExpr(ThisLoc,
473                                              MD->getThisType(Context),
474                                              /*isImplicit=*/false));
475
476   return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
477 }
478
479 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
480 /// Can be interpreted either as function-style casting ("int(x)")
481 /// or class type construction ("ClassType(x,y,z)")
482 /// or creation of a value-initialized type ("int()").
483 Action::OwningExprResult
484 Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
485                                 SourceLocation LParenLoc,
486                                 MultiExprArg exprs,
487                                 SourceLocation *CommaLocs,
488                                 SourceLocation RParenLoc) {
489   if (!TypeRep)
490     return ExprError();
491
492   TypeSourceInfo *TInfo;
493   QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
494   if (!TInfo)
495     TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
496   unsigned NumExprs = exprs.size();
497   Expr **Exprs = (Expr**)exprs.get();
498   SourceLocation TyBeginLoc = TypeRange.getBegin();
499   SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
500
501   if (Ty->isDependentType() ||
502       CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
503     exprs.release();
504
505     return Owned(CXXUnresolvedConstructExpr::Create(Context,
506                                                     TypeRange.getBegin(), Ty,
507                                                     LParenLoc,
508                                                     Exprs, NumExprs,
509                                                     RParenLoc));
510   }
511
512   if (Ty->isArrayType())
513     return ExprError(Diag(TyBeginLoc,
514                           diag::err_value_init_for_array_type) << FullRange);
515   if (!Ty->isVoidType() &&
516       RequireCompleteType(TyBeginLoc, Ty,
517                           PDiag(diag::err_invalid_incomplete_type_use)
518                             << FullRange))
519     return ExprError();
520   
521   if (RequireNonAbstractType(TyBeginLoc, Ty,
522                              diag::err_allocation_of_abstract_type))
523     return ExprError();
524
525
526   // C++ [expr.type.conv]p1:
527   // If the expression list is a single expression, the type conversion
528   // expression is equivalent (in definedness, and if defined in meaning) to the
529   // corresponding cast expression.
530   //
531   if (NumExprs == 1) {
532     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
533     CXXBaseSpecifierArray BasePath;
534     if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
535                        /*FunctionalStyle=*/true))
536       return ExprError();
537
538     exprs.release();
539
540     return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
541                                                      TInfo, TyBeginLoc, Kind,
542                                                      Exprs[0], BasePath,
543                                                      RParenLoc));
544   }
545
546   if (const RecordType *RT = Ty->getAs<RecordType>()) {
547     CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
548
549     if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
550         !Record->hasTrivialDestructor()) {
551       InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
552       InitializationKind Kind
553         = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(), 
554                                                       LParenLoc, RParenLoc)
555                    : InitializationKind::CreateValue(TypeRange.getBegin(), 
556                                                      LParenLoc, RParenLoc);
557       InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
558       OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
559                                                 move(exprs));
560
561       // FIXME: Improve AST representation?
562       return move(Result);
563     }
564
565     // Fall through to value-initialize an object of class type that
566     // doesn't have a user-declared default constructor.
567   }
568
569   // C++ [expr.type.conv]p1:
570   // If the expression list specifies more than a single value, the type shall
571   // be a class with a suitably declared constructor.
572   //
573   if (NumExprs > 1)
574     return ExprError(Diag(CommaLocs[0],
575                           diag::err_builtin_func_cast_more_than_one_arg)
576       << FullRange);
577
578   assert(NumExprs == 0 && "Expected 0 expressions");
579   // C++ [expr.type.conv]p2:
580   // The expression T(), where T is a simple-type-specifier for a non-array
581   // complete object type or the (possibly cv-qualified) void type, creates an
582   // rvalue of the specified type, which is value-initialized.
583   //
584   exprs.release();
585   return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
586 }
587
588
589 /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
590 /// @code new (memory) int[size][4] @endcode
591 /// or
592 /// @code ::new Foo(23, "hello") @endcode
593 /// For the interpretation of this heap of arguments, consult the base version.
594 Action::OwningExprResult
595 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
596                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
597                   SourceLocation PlacementRParen, bool ParenTypeId,
598                   Declarator &D, SourceLocation ConstructorLParen,
599                   MultiExprArg ConstructorArgs,
600                   SourceLocation ConstructorRParen) {
601   Expr *ArraySize = 0;
602   // If the specified type is an array, unwrap it and save the expression.
603   if (D.getNumTypeObjects() > 0 &&
604       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
605     DeclaratorChunk &Chunk = D.getTypeObject(0);
606     if (Chunk.Arr.hasStatic)
607       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
608         << D.getSourceRange());
609     if (!Chunk.Arr.NumElts)
610       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
611         << D.getSourceRange());
612
613     if (ParenTypeId) {
614       // Can't have dynamic array size when the type-id is in parentheses.
615       Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
616       if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
617           !NumElts->isIntegerConstantExpr(Context)) {
618         Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
619           << NumElts->getSourceRange();
620         return ExprError();
621       }
622     }
623
624     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
625     D.DropFirstTypeObject();
626   }
627
628   // Every dimension shall be of constant size.
629   if (ArraySize) {
630     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
631       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
632         break;
633
634       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
635       if (Expr *NumElts = (Expr *)Array.NumElts) {
636         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
637             !NumElts->isIntegerConstantExpr(Context)) {
638           Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
639             << NumElts->getSourceRange();
640           return ExprError();
641         }
642       }
643     }
644   }
645
646   //FIXME: Store TypeSourceInfo in CXXNew expression.
647   TypeSourceInfo *TInfo = 0;
648   QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
649   if (D.isInvalidType())
650     return ExprError();
651     
652   return BuildCXXNew(StartLoc, UseGlobal,
653                      PlacementLParen,
654                      move(PlacementArgs),
655                      PlacementRParen,
656                      ParenTypeId,
657                      AllocType,
658                      D.getSourceRange().getBegin(),
659                      D.getSourceRange(),
660                      Owned(ArraySize),
661                      ConstructorLParen,
662                      move(ConstructorArgs),
663                      ConstructorRParen);
664 }
665
666 Sema::OwningExprResult
667 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
668                   SourceLocation PlacementLParen,
669                   MultiExprArg PlacementArgs,
670                   SourceLocation PlacementRParen,
671                   bool ParenTypeId,
672                   QualType AllocType,
673                   SourceLocation TypeLoc,
674                   SourceRange TypeRange,
675                   ExprArg ArraySizeE,
676                   SourceLocation ConstructorLParen,
677                   MultiExprArg ConstructorArgs,
678                   SourceLocation ConstructorRParen) {
679   if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
680     return ExprError();
681
682   // Per C++0x [expr.new]p5, the type being constructed may be a
683   // typedef of an array type.
684   if (!ArraySizeE.get()) {
685     if (const ConstantArrayType *Array
686                               = Context.getAsConstantArrayType(AllocType)) {
687       ArraySizeE = Owned(new (Context) IntegerLiteral(Array->getSize(),
688                                                       Context.getSizeType(),
689                                                       TypeRange.getEnd()));
690       AllocType = Array->getElementType();
691     }
692   }
693
694   QualType ResultType = Context.getPointerType(AllocType);
695
696   // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
697   //   or enumeration type with a non-negative value."
698   Expr *ArraySize = (Expr *)ArraySizeE.get();
699   if (ArraySize && !ArraySize->isTypeDependent()) {
700     QualType SizeType = ArraySize->getType();
701     if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
702       return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
703                             diag::err_array_size_not_integral)
704         << SizeType << ArraySize->getSourceRange());
705     // Let's see if this is a constant < 0. If so, we reject it out of hand.
706     // We don't care about special rules, so we tell the machinery it's not
707     // evaluated - it gives us a result in more cases.
708     if (!ArraySize->isValueDependent()) {
709       llvm::APSInt Value;
710       if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
711         if (Value < llvm::APSInt(
712                         llvm::APInt::getNullValue(Value.getBitWidth()), 
713                                  Value.isUnsigned()))
714           return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
715                            diag::err_typecheck_negative_array_size)
716             << ArraySize->getSourceRange());
717       }
718     }
719     
720     ImpCastExprToType(ArraySize, Context.getSizeType(),
721                       CastExpr::CK_IntegralCast);
722   }
723
724   FunctionDecl *OperatorNew = 0;
725   FunctionDecl *OperatorDelete = 0;
726   Expr **PlaceArgs = (Expr**)PlacementArgs.get();
727   unsigned NumPlaceArgs = PlacementArgs.size();
728   
729   if (!AllocType->isDependentType() &&
730       !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
731       FindAllocationFunctions(StartLoc,
732                               SourceRange(PlacementLParen, PlacementRParen),
733                               UseGlobal, AllocType, ArraySize, PlaceArgs,
734                               NumPlaceArgs, OperatorNew, OperatorDelete))
735     return ExprError();
736   llvm::SmallVector<Expr *, 8> AllPlaceArgs;
737   if (OperatorNew) {
738     // Add default arguments, if any.
739     const FunctionProtoType *Proto = 
740       OperatorNew->getType()->getAs<FunctionProtoType>();
741     VariadicCallType CallType = 
742       Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
743     
744     if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
745                                Proto, 1, PlaceArgs, NumPlaceArgs, 
746                                AllPlaceArgs, CallType))
747       return ExprError();
748     
749     NumPlaceArgs = AllPlaceArgs.size();
750     if (NumPlaceArgs > 0)
751       PlaceArgs = &AllPlaceArgs[0];
752   }
753   
754   bool Init = ConstructorLParen.isValid();
755   // --- Choosing a constructor ---
756   CXXConstructorDecl *Constructor = 0;
757   Expr **ConsArgs = (Expr**)ConstructorArgs.get();
758   unsigned NumConsArgs = ConstructorArgs.size();
759   ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
760
761   // Array 'new' can't have any initializers.
762   if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
763     SourceRange InitRange(ConsArgs[0]->getLocStart(),
764                           ConsArgs[NumConsArgs - 1]->getLocEnd());
765     
766     Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
767     return ExprError();
768   }
769
770   if (!AllocType->isDependentType() &&
771       !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
772     // C++0x [expr.new]p15:
773     //   A new-expression that creates an object of type T initializes that
774     //   object as follows:
775     InitializationKind Kind
776     //     - If the new-initializer is omitted, the object is default-
777     //       initialized (8.5); if no initialization is performed,
778     //       the object has indeterminate value
779       = !Init? InitializationKind::CreateDefault(TypeLoc)
780     //     - Otherwise, the new-initializer is interpreted according to the 
781     //       initialization rules of 8.5 for direct-initialization.
782              : InitializationKind::CreateDirect(TypeLoc,
783                                                 ConstructorLParen, 
784                                                 ConstructorRParen);
785     
786     InitializedEntity Entity
787       = InitializedEntity::InitializeNew(StartLoc, AllocType);
788     InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
789     OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 
790                                                 move(ConstructorArgs));
791     if (FullInit.isInvalid())
792       return ExprError();
793     
794     // FullInit is our initializer; walk through it to determine if it's a 
795     // constructor call, which CXXNewExpr handles directly.
796     if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
797       if (CXXBindTemporaryExpr *Binder
798             = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
799         FullInitExpr = Binder->getSubExpr();
800       if (CXXConstructExpr *Construct
801                     = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
802         Constructor = Construct->getConstructor();
803         for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
804                                          AEnd = Construct->arg_end();
805              A != AEnd; ++A)
806           ConvertedConstructorArgs.push_back(A->Retain());
807       } else {
808         // Take the converted initializer.
809         ConvertedConstructorArgs.push_back(FullInit.release());
810       }
811     } else {
812       // No initialization required.
813     }
814     
815     // Take the converted arguments and use them for the new expression.
816     NumConsArgs = ConvertedConstructorArgs.size();
817     ConsArgs = (Expr **)ConvertedConstructorArgs.take();
818   }
819   
820   // Mark the new and delete operators as referenced.
821   if (OperatorNew)
822     MarkDeclarationReferenced(StartLoc, OperatorNew);
823   if (OperatorDelete)
824     MarkDeclarationReferenced(StartLoc, OperatorDelete);
825
826   // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
827   
828   PlacementArgs.release();
829   ConstructorArgs.release();
830   ArraySizeE.release();
831   return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
832                                         PlaceArgs, NumPlaceArgs, ParenTypeId,
833                                         ArraySize, Constructor, Init,
834                                         ConsArgs, NumConsArgs, OperatorDelete,
835                                         ResultType, StartLoc,
836                                         Init ? ConstructorRParen :
837                                                SourceLocation()));
838 }
839
840 /// CheckAllocatedType - Checks that a type is suitable as the allocated type
841 /// in a new-expression.
842 /// dimension off and stores the size expression in ArraySize.
843 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
844                               SourceRange R) {
845   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
846   //   abstract class type or array thereof.
847   if (AllocType->isFunctionType())
848     return Diag(Loc, diag::err_bad_new_type)
849       << AllocType << 0 << R;
850   else if (AllocType->isReferenceType())
851     return Diag(Loc, diag::err_bad_new_type)
852       << AllocType << 1 << R;
853   else if (!AllocType->isDependentType() &&
854            RequireCompleteType(Loc, AllocType,
855                                PDiag(diag::err_new_incomplete_type)
856                                  << R))
857     return true;
858   else if (RequireNonAbstractType(Loc, AllocType,
859                                   diag::err_allocation_of_abstract_type))
860     return true;
861
862   return false;
863 }
864
865 /// \brief Determine whether the given function is a non-placement
866 /// deallocation function.
867 static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
868   if (FD->isInvalidDecl())
869     return false;
870
871   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
872     return Method->isUsualDeallocationFunction();
873
874   return ((FD->getOverloadedOperator() == OO_Delete ||
875            FD->getOverloadedOperator() == OO_Array_Delete) &&
876           FD->getNumParams() == 1);
877 }
878
879 /// FindAllocationFunctions - Finds the overloads of operator new and delete
880 /// that are appropriate for the allocation.
881 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
882                                    bool UseGlobal, QualType AllocType,
883                                    bool IsArray, Expr **PlaceArgs,
884                                    unsigned NumPlaceArgs,
885                                    FunctionDecl *&OperatorNew,
886                                    FunctionDecl *&OperatorDelete) {
887   // --- Choosing an allocation function ---
888   // C++ 5.3.4p8 - 14 & 18
889   // 1) If UseGlobal is true, only look in the global scope. Else, also look
890   //   in the scope of the allocated class.
891   // 2) If an array size is given, look for operator new[], else look for
892   //   operator new.
893   // 3) The first argument is always size_t. Append the arguments from the
894   //   placement form.
895
896   llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
897   // We don't care about the actual value of this argument.
898   // FIXME: Should the Sema create the expression and embed it in the syntax
899   // tree? Or should the consumer just recalculate the value?
900   IntegerLiteral Size(llvm::APInt::getNullValue(
901                       Context.Target.getPointerWidth(0)),
902                       Context.getSizeType(),
903                       SourceLocation());
904   AllocArgs[0] = &Size;
905   std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
906
907   // C++ [expr.new]p8:
908   //   If the allocated type is a non-array type, the allocation
909   //   function’s name is operator new and the deallocation function’s
910   //   name is operator delete. If the allocated type is an array
911   //   type, the allocation function’s name is operator new[] and the
912   //   deallocation function’s name is operator delete[].
913   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
914                                         IsArray ? OO_Array_New : OO_New);
915   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
916                                         IsArray ? OO_Array_Delete : OO_Delete);
917
918   if (AllocType->isRecordType() && !UseGlobal) {
919     CXXRecordDecl *Record
920       = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
921     if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
922                           AllocArgs.size(), Record, /*AllowMissing=*/true,
923                           OperatorNew))
924       return true;
925   }
926   if (!OperatorNew) {
927     // Didn't find a member overload. Look for a global one.
928     DeclareGlobalNewDelete();
929     DeclContext *TUDecl = Context.getTranslationUnitDecl();
930     if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
931                           AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
932                           OperatorNew))
933       return true;
934   }
935
936   // We don't need an operator delete if we're running under
937   // -fno-exceptions.
938   if (!getLangOptions().Exceptions) {
939     OperatorDelete = 0;
940     return false;
941   }
942
943   // FindAllocationOverload can change the passed in arguments, so we need to
944   // copy them back.
945   if (NumPlaceArgs > 0)
946     std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
947
948   // C++ [expr.new]p19:
949   //
950   //   If the new-expression begins with a unary :: operator, the
951   //   deallocation function’s name is looked up in the global
952   //   scope. Otherwise, if the allocated type is a class type T or an
953   //   array thereof, the deallocation function’s name is looked up in
954   //   the scope of T. If this lookup fails to find the name, or if
955   //   the allocated type is not a class type or array thereof, the
956   //   deallocation function’s name is looked up in the global scope.
957   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
958   if (AllocType->isRecordType() && !UseGlobal) {
959     CXXRecordDecl *RD
960       = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
961     LookupQualifiedName(FoundDelete, RD);
962   }
963   if (FoundDelete.isAmbiguous())
964     return true; // FIXME: clean up expressions?
965
966   if (FoundDelete.empty()) {
967     DeclareGlobalNewDelete();
968     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
969   }
970
971   FoundDelete.suppressDiagnostics();
972
973   llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
974
975   if (NumPlaceArgs > 0) {
976     // C++ [expr.new]p20:
977     //   A declaration of a placement deallocation function matches the
978     //   declaration of a placement allocation function if it has the
979     //   same number of parameters and, after parameter transformations
980     //   (8.3.5), all parameter types except the first are
981     //   identical. [...]
982     // 
983     // To perform this comparison, we compute the function type that
984     // the deallocation function should have, and use that type both
985     // for template argument deduction and for comparison purposes.
986     QualType ExpectedFunctionType;
987     {
988       const FunctionProtoType *Proto
989         = OperatorNew->getType()->getAs<FunctionProtoType>();
990       llvm::SmallVector<QualType, 4> ArgTypes;
991       ArgTypes.push_back(Context.VoidPtrTy); 
992       for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
993         ArgTypes.push_back(Proto->getArgType(I));
994
995       ExpectedFunctionType
996         = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
997                                   ArgTypes.size(),
998                                   Proto->isVariadic(),
999                                   0, false, false, 0, 0,
1000                                   FunctionType::ExtInfo());
1001     }
1002
1003     for (LookupResult::iterator D = FoundDelete.begin(), 
1004                              DEnd = FoundDelete.end();
1005          D != DEnd; ++D) {
1006       FunctionDecl *Fn = 0;
1007       if (FunctionTemplateDecl *FnTmpl 
1008             = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1009         // Perform template argument deduction to try to match the
1010         // expected function type.
1011         TemplateDeductionInfo Info(Context, StartLoc);
1012         if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1013           continue;
1014       } else
1015         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1016
1017       if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1018         Matches.push_back(std::make_pair(D.getPair(), Fn));
1019     }
1020   } else {
1021     // C++ [expr.new]p20:
1022     //   [...] Any non-placement deallocation function matches a
1023     //   non-placement allocation function. [...]
1024     for (LookupResult::iterator D = FoundDelete.begin(), 
1025                              DEnd = FoundDelete.end();
1026          D != DEnd; ++D) {
1027       if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1028         if (isNonPlacementDeallocationFunction(Fn))
1029           Matches.push_back(std::make_pair(D.getPair(), Fn));
1030     }
1031   }
1032
1033   // C++ [expr.new]p20:
1034   //   [...] If the lookup finds a single matching deallocation
1035   //   function, that function will be called; otherwise, no
1036   //   deallocation function will be called.
1037   if (Matches.size() == 1) {
1038     OperatorDelete = Matches[0].second;
1039
1040     // C++0x [expr.new]p20:
1041     //   If the lookup finds the two-parameter form of a usual
1042     //   deallocation function (3.7.4.2) and that function, considered
1043     //   as a placement deallocation function, would have been
1044     //   selected as a match for the allocation function, the program
1045     //   is ill-formed.
1046     if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1047         isNonPlacementDeallocationFunction(OperatorDelete)) {
1048       Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1049         << SourceRange(PlaceArgs[0]->getLocStart(), 
1050                        PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1051       Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1052         << DeleteName;
1053     } else {
1054       CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1055                             Matches[0].first);
1056     }
1057   }
1058
1059   return false;
1060 }
1061
1062 /// FindAllocationOverload - Find an fitting overload for the allocation
1063 /// function in the specified scope.
1064 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1065                                   DeclarationName Name, Expr** Args,
1066                                   unsigned NumArgs, DeclContext *Ctx,
1067                                   bool AllowMissing, FunctionDecl *&Operator) {
1068   LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1069   LookupQualifiedName(R, Ctx);
1070   if (R.empty()) {
1071     if (AllowMissing)
1072       return false;
1073     return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1074       << Name << Range;
1075   }
1076
1077   if (R.isAmbiguous())
1078     return true;
1079
1080   R.suppressDiagnostics();
1081
1082   OverloadCandidateSet Candidates(StartLoc);
1083   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 
1084        Alloc != AllocEnd; ++Alloc) {
1085     // Even member operator new/delete are implicitly treated as
1086     // static, so don't use AddMemberCandidate.
1087     NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1088
1089     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1090       AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1091                                    /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1092                                    Candidates,
1093                                    /*SuppressUserConversions=*/false);
1094       continue;
1095     }
1096
1097     FunctionDecl *Fn = cast<FunctionDecl>(D);
1098     AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1099                          /*SuppressUserConversions=*/false);
1100   }
1101
1102   // Do the resolution.
1103   OverloadCandidateSet::iterator Best;
1104   switch(BestViableFunction(Candidates, StartLoc, Best)) {
1105   case OR_Success: {
1106     // Got one!
1107     FunctionDecl *FnDecl = Best->Function;
1108     // The first argument is size_t, and the first parameter must be size_t,
1109     // too. This is checked on declaration and can be assumed. (It can't be
1110     // asserted on, though, since invalid decls are left in there.)
1111     // Watch out for variadic allocator function.
1112     unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1113     for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1114       OwningExprResult Result
1115         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1116                                                        FnDecl->getParamDecl(i)),
1117                                     SourceLocation(),
1118                                     Owned(Args[i]->Retain()));
1119       if (Result.isInvalid())
1120         return true;
1121       
1122       Args[i] = Result.takeAs<Expr>();
1123     }
1124     Operator = FnDecl;
1125     CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1126     return false;
1127   }
1128
1129   case OR_No_Viable_Function:
1130     Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1131       << Name << Range;
1132     PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
1133     return true;
1134
1135   case OR_Ambiguous:
1136     Diag(StartLoc, diag::err_ovl_ambiguous_call)
1137       << Name << Range;
1138     PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
1139     return true;
1140
1141   case OR_Deleted:
1142     Diag(StartLoc, diag::err_ovl_deleted_call)
1143       << Best->Function->isDeleted()
1144       << Name << Range;
1145     PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
1146     return true;
1147   }
1148   assert(false && "Unreachable, bad result from BestViableFunction");
1149   return true;
1150 }
1151
1152
1153 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
1154 /// delete. These are:
1155 /// @code
1156 ///   void* operator new(std::size_t) throw(std::bad_alloc);
1157 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
1158 ///   void operator delete(void *) throw();
1159 ///   void operator delete[](void *) throw();
1160 /// @endcode
1161 /// Note that the placement and nothrow forms of new are *not* implicitly
1162 /// declared. Their use requires including \<new\>.
1163 void Sema::DeclareGlobalNewDelete() {
1164   if (GlobalNewDeleteDeclared)
1165     return;
1166   
1167   // C++ [basic.std.dynamic]p2:
1168   //   [...] The following allocation and deallocation functions (18.4) are 
1169   //   implicitly declared in global scope in each translation unit of a 
1170   //   program
1171   //   
1172   //     void* operator new(std::size_t) throw(std::bad_alloc);
1173   //     void* operator new[](std::size_t) throw(std::bad_alloc); 
1174   //     void  operator delete(void*) throw(); 
1175   //     void  operator delete[](void*) throw();
1176   //
1177   //   These implicit declarations introduce only the function names operator 
1178   //   new, operator new[], operator delete, operator delete[].
1179   //
1180   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1181   // "std" or "bad_alloc" as necessary to form the exception specification.
1182   // However, we do not make these implicit declarations visible to name
1183   // lookup.
1184   if (!StdNamespace) {
1185     // The "std" namespace has not yet been defined, so build one implicitly.
1186     StdNamespace = NamespaceDecl::Create(Context, 
1187                                          Context.getTranslationUnitDecl(),
1188                                          SourceLocation(),
1189                                          &PP.getIdentifierTable().get("std"));
1190     StdNamespace->setImplicit(true);
1191   }
1192   
1193   if (!StdBadAlloc) {
1194     // The "std::bad_alloc" class has not yet been declared, so build it
1195     // implicitly.
1196     StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 
1197                                         StdNamespace, 
1198                                         SourceLocation(), 
1199                                       &PP.getIdentifierTable().get("bad_alloc"), 
1200                                         SourceLocation(), 0);
1201     StdBadAlloc->setImplicit(true);
1202   }
1203   
1204   GlobalNewDeleteDeclared = true;
1205
1206   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1207   QualType SizeT = Context.getSizeType();
1208   bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1209
1210   DeclareGlobalAllocationFunction(
1211       Context.DeclarationNames.getCXXOperatorName(OO_New),
1212       VoidPtr, SizeT, AssumeSaneOperatorNew);
1213   DeclareGlobalAllocationFunction(
1214       Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1215       VoidPtr, SizeT, AssumeSaneOperatorNew);
1216   DeclareGlobalAllocationFunction(
1217       Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1218       Context.VoidTy, VoidPtr);
1219   DeclareGlobalAllocationFunction(
1220       Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1221       Context.VoidTy, VoidPtr);
1222 }
1223
1224 /// DeclareGlobalAllocationFunction - Declares a single implicit global
1225 /// allocation function if it doesn't already exist.
1226 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1227                                            QualType Return, QualType Argument,
1228                                            bool AddMallocAttr) {
1229   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1230
1231   // Check if this function is already declared.
1232   {
1233     DeclContext::lookup_iterator Alloc, AllocEnd;
1234     for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1235          Alloc != AllocEnd; ++Alloc) {
1236       // Only look at non-template functions, as it is the predefined,
1237       // non-templated allocation function we are trying to declare here.
1238       if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1239         QualType InitialParamType =
1240           Context.getCanonicalType(
1241             Func->getParamDecl(0)->getType().getUnqualifiedType());
1242         // FIXME: Do we need to check for default arguments here?
1243         if (Func->getNumParams() == 1 && InitialParamType == Argument)
1244           return;
1245       }
1246     }
1247   }
1248
1249   QualType BadAllocType;
1250   bool HasBadAllocExceptionSpec 
1251     = (Name.getCXXOverloadedOperator() == OO_New ||
1252        Name.getCXXOverloadedOperator() == OO_Array_New);
1253   if (HasBadAllocExceptionSpec) {
1254     assert(StdBadAlloc && "Must have std::bad_alloc declared");
1255     BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1256   }
1257   
1258   QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1259                                             true, false,
1260                                             HasBadAllocExceptionSpec? 1 : 0,
1261                                             &BadAllocType,
1262                                             FunctionType::ExtInfo());
1263   FunctionDecl *Alloc =
1264     FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
1265                          FnType, /*TInfo=*/0, FunctionDecl::None,
1266                          FunctionDecl::None, false, true);
1267   Alloc->setImplicit();
1268   
1269   if (AddMallocAttr)
1270     Alloc->addAttr(::new (Context) MallocAttr());
1271   
1272   ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1273                                            0, Argument, /*TInfo=*/0,
1274                                            VarDecl::None,
1275                                            VarDecl::None, 0);
1276   Alloc->setParams(&Param, 1);
1277
1278   // FIXME: Also add this declaration to the IdentifierResolver, but
1279   // make sure it is at the end of the chain to coincide with the
1280   // global scope.
1281   ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
1282 }
1283
1284 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1285                                     DeclarationName Name,
1286                                     FunctionDecl* &Operator) {
1287   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1288   // Try to find operator delete/operator delete[] in class scope.
1289   LookupQualifiedName(Found, RD);
1290   
1291   if (Found.isAmbiguous())
1292     return true;
1293
1294   for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1295        F != FEnd; ++F) {
1296     if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1297       if (Delete->isUsualDeallocationFunction()) {
1298         Operator = Delete;
1299         return false;
1300       }
1301   }
1302
1303   // We did find operator delete/operator delete[] declarations, but
1304   // none of them were suitable.
1305   if (!Found.empty()) {
1306     Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1307       << Name << RD;
1308         
1309     for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1310          F != FEnd; ++F) {
1311       Diag((*F)->getLocation(), diag::note_member_declared_here)
1312         << Name;
1313     }
1314
1315     return true;
1316   }
1317
1318   // Look for a global declaration.
1319   DeclareGlobalNewDelete();
1320   DeclContext *TUDecl = Context.getTranslationUnitDecl();
1321   
1322   CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1323   Expr* DeallocArgs[1];
1324   DeallocArgs[0] = &Null;
1325   if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1326                              DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1327                              Operator))
1328     return true;
1329
1330   assert(Operator && "Did not find a deallocation function!");
1331   return false;
1332 }
1333
1334 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1335 /// @code ::delete ptr; @endcode
1336 /// or
1337 /// @code delete [] ptr; @endcode
1338 Action::OwningExprResult
1339 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1340                      bool ArrayForm, ExprArg Operand) {
1341   // C++ [expr.delete]p1:
1342   //   The operand shall have a pointer type, or a class type having a single
1343   //   conversion function to a pointer type. The result has type void.
1344   //
1345   // DR599 amends "pointer type" to "pointer to object type" in both cases.
1346
1347   FunctionDecl *OperatorDelete = 0;
1348
1349   Expr *Ex = (Expr *)Operand.get();
1350   if (!Ex->isTypeDependent()) {
1351     QualType Type = Ex->getType();
1352
1353     if (const RecordType *Record = Type->getAs<RecordType>()) {
1354       llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1355
1356       CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1357       const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();      
1358       for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1359              E = Conversions->end(); I != E; ++I) {
1360         NamedDecl *D = I.getDecl();
1361         if (isa<UsingShadowDecl>(D))
1362           D = cast<UsingShadowDecl>(D)->getTargetDecl();
1363
1364         // Skip over templated conversion functions; they aren't considered.
1365         if (isa<FunctionTemplateDecl>(D))
1366           continue;
1367         
1368         CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1369         
1370         QualType ConvType = Conv->getConversionType().getNonReferenceType();
1371         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1372           if (ConvPtrType->getPointeeType()->isObjectType())
1373             ObjectPtrConversions.push_back(Conv);
1374       }
1375       if (ObjectPtrConversions.size() == 1) {
1376         // We have a single conversion to a pointer-to-object type. Perform
1377         // that conversion.
1378         // TODO: don't redo the conversion calculation.
1379         Operand.release();
1380         if (!PerformImplicitConversion(Ex,
1381                             ObjectPtrConversions.front()->getConversionType(),
1382                                       AA_Converting)) {
1383           Operand = Owned(Ex);
1384           Type = Ex->getType();
1385         }
1386       }
1387       else if (ObjectPtrConversions.size() > 1) {
1388         Diag(StartLoc, diag::err_ambiguous_delete_operand)
1389               << Type << Ex->getSourceRange();
1390         for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1391           NoteOverloadCandidate(ObjectPtrConversions[i]);
1392         return ExprError();
1393       }
1394     }
1395
1396     if (!Type->isPointerType())
1397       return ExprError(Diag(StartLoc, diag::err_delete_operand)
1398         << Type << Ex->getSourceRange());
1399
1400     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1401     if (Pointee->isVoidType() && !isSFINAEContext()) {
1402       // The C++ standard bans deleting a pointer to a non-object type, which 
1403       // effectively bans deletion of "void*". However, most compilers support
1404       // this, so we treat it as a warning unless we're in a SFINAE context.
1405       Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1406         << Type << Ex->getSourceRange();
1407     } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1408       return ExprError(Diag(StartLoc, diag::err_delete_operand)
1409         << Type << Ex->getSourceRange());
1410     else if (!Pointee->isDependentType() &&
1411              RequireCompleteType(StartLoc, Pointee,
1412                                  PDiag(diag::warn_delete_incomplete)
1413                                    << Ex->getSourceRange()))
1414       return ExprError();
1415
1416     // C++ [expr.delete]p2:
1417     //   [Note: a pointer to a const type can be the operand of a 
1418     //   delete-expression; it is not necessary to cast away the constness 
1419     //   (5.2.11) of the pointer expression before it is used as the operand 
1420     //   of the delete-expression. ]
1421     ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), 
1422                       CastExpr::CK_NoOp);
1423     
1424     // Update the operand.
1425     Operand.take();
1426     Operand = ExprArg(*this, Ex);
1427     
1428     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1429                                       ArrayForm ? OO_Array_Delete : OO_Delete);
1430
1431     if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1432       CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1433
1434       if (!UseGlobal && 
1435           FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1436         return ExprError();
1437       
1438       if (!RD->hasTrivialDestructor())
1439         if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
1440           MarkDeclarationReferenced(StartLoc,
1441                                     const_cast<CXXDestructorDecl*>(Dtor));
1442     }
1443     
1444     if (!OperatorDelete) {
1445       // Look for a global declaration.
1446       DeclareGlobalNewDelete();
1447       DeclContext *TUDecl = Context.getTranslationUnitDecl();
1448       if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1449                                  &Ex, 1, TUDecl, /*AllowMissing=*/false,
1450                                  OperatorDelete))
1451         return ExprError();
1452     }
1453
1454     MarkDeclarationReferenced(StartLoc, OperatorDelete);
1455
1456     // FIXME: Check access and ambiguity of operator delete and destructor.
1457   }
1458
1459   Operand.release();
1460   return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1461                                            OperatorDelete, Ex, StartLoc));
1462 }
1463
1464 /// \brief Check the use of the given variable as a C++ condition in an if,
1465 /// while, do-while, or switch statement.
1466 Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1467                                                       SourceLocation StmtLoc,
1468                                                       bool ConvertToBoolean) {
1469   QualType T = ConditionVar->getType();
1470   
1471   // C++ [stmt.select]p2:
1472   //   The declarator shall not specify a function or an array.
1473   if (T->isFunctionType())
1474     return ExprError(Diag(ConditionVar->getLocation(), 
1475                           diag::err_invalid_use_of_function_type)
1476                        << ConditionVar->getSourceRange());
1477   else if (T->isArrayType())
1478     return ExprError(Diag(ConditionVar->getLocation(), 
1479                           diag::err_invalid_use_of_array_type)
1480                      << ConditionVar->getSourceRange());
1481
1482   Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1483                                         ConditionVar->getLocation(), 
1484                                  ConditionVar->getType().getNonReferenceType());
1485   if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1486     Condition->Destroy(Context);
1487     return ExprError();
1488   }
1489   
1490   return Owned(Condition);
1491 }
1492
1493 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1494 bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1495   // C++ 6.4p4:
1496   // The value of a condition that is an initialized declaration in a statement
1497   // other than a switch statement is the value of the declared variable
1498   // implicitly converted to type bool. If that conversion is ill-formed, the
1499   // program is ill-formed.
1500   // The value of a condition that is an expression is the value of the
1501   // expression, implicitly converted to bool.
1502   //
1503   return PerformContextuallyConvertToBool(CondExpr);
1504 }
1505
1506 /// Helper function to determine whether this is the (deprecated) C++
1507 /// conversion from a string literal to a pointer to non-const char or
1508 /// non-const wchar_t (for narrow and wide string literals,
1509 /// respectively).
1510 bool
1511 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1512   // Look inside the implicit cast, if it exists.
1513   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1514     From = Cast->getSubExpr();
1515
1516   // A string literal (2.13.4) that is not a wide string literal can
1517   // be converted to an rvalue of type "pointer to char"; a wide
1518   // string literal can be converted to an rvalue of type "pointer
1519   // to wchar_t" (C++ 4.2p2).
1520   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
1521     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1522       if (const BuiltinType *ToPointeeType
1523           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1524         // This conversion is considered only when there is an
1525         // explicit appropriate pointer target type (C++ 4.2p2).
1526         if (!ToPtrType->getPointeeType().hasQualifiers() &&
1527             ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1528              (!StrLit->isWide() &&
1529               (ToPointeeType->getKind() == BuiltinType::Char_U ||
1530                ToPointeeType->getKind() == BuiltinType::Char_S))))
1531           return true;
1532       }
1533
1534   return false;
1535 }
1536
1537 static Sema::OwningExprResult BuildCXXCastArgument(Sema &S, 
1538                                                    SourceLocation CastLoc,
1539                                                    QualType Ty,
1540                                                    CastExpr::CastKind Kind,
1541                                                    CXXMethodDecl *Method,
1542                                                    Sema::ExprArg Arg) {
1543   Expr *From = Arg.takeAs<Expr>();
1544   
1545   switch (Kind) {
1546   default: assert(0 && "Unhandled cast kind!");
1547   case CastExpr::CK_ConstructorConversion: {
1548     ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1549     
1550     if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1551                                   Sema::MultiExprArg(S, (void **)&From, 1),
1552                                   CastLoc, ConstructorArgs))
1553       return S.ExprError();
1554     
1555     Sema::OwningExprResult Result = 
1556     S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 
1557                             move_arg(ConstructorArgs));
1558     if (Result.isInvalid())
1559       return S.ExprError();
1560     
1561     return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1562   }
1563     
1564   case CastExpr::CK_UserDefinedConversion: {
1565     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1566     
1567     // Create an implicit call expr that calls it.
1568     // FIXME: pass the FoundDecl for the user-defined conversion here
1569     CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1570     return S.MaybeBindToTemporary(CE);
1571   }
1572   }
1573 }    
1574
1575 /// PerformImplicitConversion - Perform an implicit conversion of the
1576 /// expression From to the type ToType using the pre-computed implicit
1577 /// conversion sequence ICS. Returns true if there was an error, false
1578 /// otherwise. The expression From is replaced with the converted
1579 /// expression. Action is the kind of conversion we're performing,
1580 /// used in the error message.
1581 bool
1582 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1583                                 const ImplicitConversionSequence &ICS,
1584                                 AssignmentAction Action, bool IgnoreBaseAccess) {
1585   switch (ICS.getKind()) {
1586   case ImplicitConversionSequence::StandardConversion:
1587     if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
1588                                   IgnoreBaseAccess))
1589       return true;
1590     break;
1591
1592   case ImplicitConversionSequence::UserDefinedConversion: {
1593     
1594       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1595       CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
1596       QualType BeforeToType;
1597       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1598         CastKind = CastExpr::CK_UserDefinedConversion;
1599         
1600         // If the user-defined conversion is specified by a conversion function,
1601         // the initial standard conversion sequence converts the source type to
1602         // the implicit object parameter of the conversion function.
1603         BeforeToType = Context.getTagDeclType(Conv->getParent());
1604       } else if (const CXXConstructorDecl *Ctor = 
1605                   dyn_cast<CXXConstructorDecl>(FD)) {
1606         CastKind = CastExpr::CK_ConstructorConversion;
1607         // Do no conversion if dealing with ... for the first conversion.
1608         if (!ICS.UserDefined.EllipsisConversion) {
1609           // If the user-defined conversion is specified by a constructor, the 
1610           // initial standard conversion sequence converts the source type to the
1611           // type required by the argument of the constructor
1612           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1613         }
1614       }    
1615       else
1616         assert(0 && "Unknown conversion function kind!");
1617       // Whatch out for elipsis conversion.
1618       if (!ICS.UserDefined.EllipsisConversion) {
1619         if (PerformImplicitConversion(From, BeforeToType, 
1620                                       ICS.UserDefined.Before, AA_Converting,
1621                                       IgnoreBaseAccess))
1622           return true;
1623       }
1624     
1625       OwningExprResult CastArg 
1626         = BuildCXXCastArgument(*this,
1627                                From->getLocStart(),
1628                                ToType.getNonReferenceType(),
1629                                CastKind, cast<CXXMethodDecl>(FD), 
1630                                Owned(From));
1631
1632       if (CastArg.isInvalid())
1633         return true;
1634
1635       From = CastArg.takeAs<Expr>();
1636
1637       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1638                                        AA_Converting, IgnoreBaseAccess);
1639   }
1640
1641   case ImplicitConversionSequence::AmbiguousConversion:
1642     DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1643                           PDiag(diag::err_typecheck_ambiguous_condition)
1644                             << From->getSourceRange());
1645      return true;
1646       
1647   case ImplicitConversionSequence::EllipsisConversion:
1648     assert(false && "Cannot perform an ellipsis conversion");
1649     return false;
1650
1651   case ImplicitConversionSequence::BadConversion:
1652     return true;
1653   }
1654
1655   // Everything went well.
1656   return false;
1657 }
1658
1659 /// PerformImplicitConversion - Perform an implicit conversion of the
1660 /// expression From to the type ToType by following the standard
1661 /// conversion sequence SCS. Returns true if there was an error, false
1662 /// otherwise. The expression From is replaced with the converted
1663 /// expression. Flavor is the context in which we're performing this
1664 /// conversion, for use in error messages.
1665 bool
1666 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1667                                 const StandardConversionSequence& SCS,
1668                                 AssignmentAction Action, bool IgnoreBaseAccess) {
1669   // Overall FIXME: we are recomputing too many types here and doing far too
1670   // much extra work. What this means is that we need to keep track of more
1671   // information that is computed when we try the implicit conversion initially,
1672   // so that we don't need to recompute anything here.
1673   QualType FromType = From->getType();
1674
1675   if (SCS.CopyConstructor) {
1676     // FIXME: When can ToType be a reference type?
1677     assert(!ToType->isReferenceType());
1678     if (SCS.Second == ICK_Derived_To_Base) {
1679       ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1680       if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1681                                   MultiExprArg(*this, (void **)&From, 1),
1682                                   /*FIXME:ConstructLoc*/SourceLocation(), 
1683                                   ConstructorArgs))
1684         return true;
1685       OwningExprResult FromResult =
1686         BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1687                               ToType, SCS.CopyConstructor,
1688                               move_arg(ConstructorArgs));
1689       if (FromResult.isInvalid())
1690         return true;
1691       From = FromResult.takeAs<Expr>();
1692       return false;
1693     }
1694     OwningExprResult FromResult =
1695       BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1696                             ToType, SCS.CopyConstructor,
1697                             MultiExprArg(*this, (void**)&From, 1));
1698
1699     if (FromResult.isInvalid())
1700       return true;
1701
1702     From = FromResult.takeAs<Expr>();
1703     return false;
1704   }
1705
1706   // Resolve overloaded function references.
1707   if (Context.hasSameType(FromType, Context.OverloadTy)) {
1708     DeclAccessPair Found;
1709     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1710                                                           true, Found);
1711     if (!Fn)
1712       return true;
1713
1714     if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1715       return true;
1716
1717     From = FixOverloadedFunctionReference(From, Found, Fn);
1718     FromType = From->getType();
1719   }
1720
1721   // Perform the first implicit conversion.
1722   switch (SCS.First) {
1723   case ICK_Identity:
1724   case ICK_Lvalue_To_Rvalue:
1725     // Nothing to do.
1726     break;
1727
1728   case ICK_Array_To_Pointer:
1729     FromType = Context.getArrayDecayedType(FromType);
1730     ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
1731     break;
1732
1733   case ICK_Function_To_Pointer:
1734     FromType = Context.getPointerType(FromType);
1735     ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
1736     break;
1737
1738   default:
1739     assert(false && "Improper first standard conversion");
1740     break;
1741   }
1742
1743   // Perform the second implicit conversion
1744   switch (SCS.Second) {
1745   case ICK_Identity:
1746     // If both sides are functions (or pointers/references to them), there could
1747     // be incompatible exception declarations.
1748     if (CheckExceptionSpecCompatibility(From, ToType))
1749       return true;
1750     // Nothing else to do.
1751     break;
1752
1753   case ICK_NoReturn_Adjustment:
1754     // If both sides are functions (or pointers/references to them), there could
1755     // be incompatible exception declarations.
1756     if (CheckExceptionSpecCompatibility(From, ToType))
1757       return true;      
1758       
1759     ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1760                       CastExpr::CK_NoOp);
1761     break;
1762       
1763   case ICK_Integral_Promotion:
1764   case ICK_Integral_Conversion:
1765     ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1766     break;
1767
1768   case ICK_Floating_Promotion:
1769   case ICK_Floating_Conversion:
1770     ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1771     break;
1772
1773   case ICK_Complex_Promotion:
1774   case ICK_Complex_Conversion:
1775     ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1776     break;
1777
1778   case ICK_Floating_Integral:
1779     if (ToType->isFloatingType())
1780       ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1781     else
1782       ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1783     break;
1784
1785   case ICK_Compatible_Conversion:
1786     ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
1787     break;
1788
1789   case ICK_Pointer_Conversion: {
1790     if (SCS.IncompatibleObjC) {
1791       // Diagnose incompatible Objective-C conversions
1792       Diag(From->getSourceRange().getBegin(),
1793            diag::ext_typecheck_convert_incompatible_pointer)
1794         << From->getType() << ToType << Action
1795         << From->getSourceRange();
1796     }
1797
1798     
1799     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1800     CXXBaseSpecifierArray BasePath;
1801     if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
1802       return true;
1803     ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
1804     break;
1805   }
1806   
1807   case ICK_Pointer_Member: {
1808     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1809     CXXBaseSpecifierArray BasePath;
1810     if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1811                                      IgnoreBaseAccess))
1812       return true;
1813     if (CheckExceptionSpecCompatibility(From, ToType))
1814       return true;
1815     ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
1816     break;
1817   }
1818   case ICK_Boolean_Conversion: {
1819     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1820     if (FromType->isMemberPointerType())
1821       Kind = CastExpr::CK_MemberPointerToBoolean;
1822     
1823     ImpCastExprToType(From, Context.BoolTy, Kind);
1824     break;
1825   }
1826
1827   case ICK_Derived_To_Base: {
1828     CXXBaseSpecifierArray BasePath;
1829     if (CheckDerivedToBaseConversion(From->getType(), 
1830                                      ToType.getNonReferenceType(),
1831                                      From->getLocStart(),
1832                                      From->getSourceRange(), 
1833                                      &BasePath,
1834                                      IgnoreBaseAccess))
1835       return true;
1836
1837     ImpCastExprToType(From, ToType.getNonReferenceType(), 
1838                       CastExpr::CK_DerivedToBase, 
1839                       /*isLvalue=*/(From->getType()->isRecordType() &&
1840                                     From->isLvalue(Context) == Expr::LV_Valid),
1841                       BasePath);
1842     break;
1843   }
1844
1845   case ICK_Vector_Conversion:
1846     ImpCastExprToType(From, ToType, CastExpr::CK_BitCast);
1847     break;
1848
1849   case ICK_Vector_Splat:
1850     ImpCastExprToType(From, ToType, CastExpr::CK_VectorSplat);
1851     break;
1852       
1853   case ICK_Complex_Real:
1854     ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1855     break;
1856       
1857   case ICK_Lvalue_To_Rvalue:
1858   case ICK_Array_To_Pointer:
1859   case ICK_Function_To_Pointer:
1860   case ICK_Qualification:
1861   case ICK_Num_Conversion_Kinds:
1862     assert(false && "Improper second standard conversion");
1863     break;
1864   }
1865
1866   switch (SCS.Third) {
1867   case ICK_Identity:
1868     // Nothing to do.
1869     break;
1870
1871   case ICK_Qualification:
1872     // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1873     // references.
1874     ImpCastExprToType(From, ToType.getNonReferenceType(),
1875                       CastExpr::CK_NoOp, ToType->isLValueReferenceType());
1876
1877     if (SCS.DeprecatedStringLiteralToCharPtr)
1878       Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1879         << ToType.getNonReferenceType();
1880
1881     break;
1882       
1883   default:
1884     assert(false && "Improper third standard conversion");
1885     break;
1886   }
1887
1888   return false;
1889 }
1890
1891 Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1892                                                  SourceLocation KWLoc,
1893                                                  SourceLocation LParen,
1894                                                  TypeTy *Ty,
1895                                                  SourceLocation RParen) {
1896   QualType T = GetTypeFromParser(Ty);
1897
1898   // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1899   // all traits except __is_class, __is_enum and __is_union require a the type
1900   // to be complete.
1901   if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1902     if (RequireCompleteType(KWLoc, T,
1903                             diag::err_incomplete_type_used_in_type_trait_expr))
1904       return ExprError();
1905   }
1906
1907   // There is no point in eagerly computing the value. The traits are designed
1908   // to be used from type trait templates, so Ty will be a template parameter
1909   // 99% of the time.
1910   return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1911                                                 RParen, Context.BoolTy));
1912 }
1913
1914 QualType Sema::CheckPointerToMemberOperands(
1915   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1916   const char *OpSpelling = isIndirect ? "->*" : ".*";
1917   // C++ 5.5p2
1918   //   The binary operator .* [p3: ->*] binds its second operand, which shall
1919   //   be of type "pointer to member of T" (where T is a completely-defined
1920   //   class type) [...]
1921   QualType RType = rex->getType();
1922   const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1923   if (!MemPtr) {
1924     Diag(Loc, diag::err_bad_memptr_rhs)
1925       << OpSpelling << RType << rex->getSourceRange();
1926     return QualType();
1927   }
1928
1929   QualType Class(MemPtr->getClass(), 0);
1930
1931   if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1932     return QualType();
1933
1934   // C++ 5.5p2
1935   //   [...] to its first operand, which shall be of class T or of a class of
1936   //   which T is an unambiguous and accessible base class. [p3: a pointer to
1937   //   such a class]
1938   QualType LType = lex->getType();
1939   if (isIndirect) {
1940     if (const PointerType *Ptr = LType->getAs<PointerType>())
1941       LType = Ptr->getPointeeType().getNonReferenceType();
1942     else {
1943       Diag(Loc, diag::err_bad_memptr_lhs)
1944         << OpSpelling << 1 << LType
1945         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
1946       return QualType();
1947     }
1948   }
1949
1950   if (!Context.hasSameUnqualifiedType(Class, LType)) {
1951     // If we want to check the hierarchy, we need a complete type.
1952     if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1953         << OpSpelling << (int)isIndirect)) {
1954       return QualType();
1955     }
1956     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1957                        /*DetectVirtual=*/false);
1958     // FIXME: Would it be useful to print full ambiguity paths, or is that
1959     // overkill?
1960     if (!IsDerivedFrom(LType, Class, Paths) ||
1961         Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1962       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1963         << (int)isIndirect << lex->getType();
1964       return QualType();
1965     }
1966     // Cast LHS to type of use.
1967     QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1968     bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1969     
1970     CXXBaseSpecifierArray BasePath;
1971     BuildBasePathArray(Paths, BasePath);
1972     ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1973                       BasePath);
1974   }
1975
1976   if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
1977     // Diagnose use of pointer-to-member type which when used as
1978     // the functional cast in a pointer-to-member expression.
1979     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1980      return QualType();
1981   }
1982   // C++ 5.5p2
1983   //   The result is an object or a function of the type specified by the
1984   //   second operand.
1985   // The cv qualifiers are the union of those in the pointer and the left side,
1986   // in accordance with 5.5p5 and 5.2.5.
1987   // FIXME: This returns a dereferenced member function pointer as a normal
1988   // function type. However, the only operation valid on such functions is
1989   // calling them. There's also a GCC extension to get a function pointer to the
1990   // thing, which is another complication, because this type - unlike the type
1991   // that is the result of this expression - takes the class as the first
1992   // argument.
1993   // We probably need a "MemberFunctionClosureType" or something like that.
1994   QualType Result = MemPtr->getPointeeType();
1995   Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
1996   return Result;
1997 }
1998
1999 /// \brief Try to convert a type to another according to C++0x 5.16p3.
2000 ///
2001 /// This is part of the parameter validation for the ? operator. If either
2002 /// value operand is a class type, the two operands are attempted to be
2003 /// converted to each other. This function does the conversion in one direction.
2004 /// It returns true if the program is ill-formed and has already been diagnosed
2005 /// as such.
2006 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2007                                 SourceLocation QuestionLoc,
2008                                 bool &HaveConversion,
2009                                 QualType &ToType) {
2010   HaveConversion = false;
2011   ToType = To->getType();
2012   
2013   InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), 
2014                                                            SourceLocation());
2015   // C++0x 5.16p3
2016   //   The process for determining whether an operand expression E1 of type T1
2017   //   can be converted to match an operand expression E2 of type T2 is defined
2018   //   as follows:
2019   //   -- If E2 is an lvalue:
2020   bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
2021   if (ToIsLvalue) {
2022     //   E1 can be converted to match E2 if E1 can be implicitly converted to
2023     //   type "lvalue reference to T2", subject to the constraint that in the
2024     //   conversion the reference must bind directly to E1.
2025     QualType T = Self.Context.getLValueReferenceType(ToType);
2026     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2027     
2028     InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2029     if (InitSeq.isDirectReferenceBinding()) {
2030       ToType = T;
2031       HaveConversion = true;
2032       return false;
2033     }
2034     
2035     if (InitSeq.isAmbiguous())
2036       return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2037   }
2038
2039   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
2040   //      -- if E1 and E2 have class type, and the underlying class types are
2041   //         the same or one is a base class of the other:
2042   QualType FTy = From->getType();
2043   QualType TTy = To->getType();
2044   const RecordType *FRec = FTy->getAs<RecordType>();
2045   const RecordType *TRec = TTy->getAs<RecordType>();
2046   bool FDerivedFromT = FRec && TRec && FRec != TRec && 
2047                        Self.IsDerivedFrom(FTy, TTy);
2048   if (FRec && TRec && 
2049       (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
2050     //         E1 can be converted to match E2 if the class of T2 is the
2051     //         same type as, or a base class of, the class of T1, and
2052     //         [cv2 > cv1].
2053     if (FRec == TRec || FDerivedFromT) {
2054       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
2055         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2056         InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2057         if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2058           HaveConversion = true;
2059           return false;
2060         }
2061         
2062         if (InitSeq.isAmbiguous())
2063           return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2064       } 
2065     }
2066     
2067     return false;
2068   }
2069   
2070   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
2071   //        implicitly converted to the type that expression E2 would have
2072   //        if E2 were converted to an rvalue (or the type it has, if E2 is 
2073   //        an rvalue).
2074   //
2075   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2076   // to the array-to-pointer or function-to-pointer conversions.
2077   if (!TTy->getAs<TagType>())
2078     TTy = TTy.getUnqualifiedType();
2079   
2080   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2081   InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2082   HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;  
2083   ToType = TTy;
2084   if (InitSeq.isAmbiguous())
2085     return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2086
2087   return false;
2088 }
2089
2090 /// \brief Try to find a common type for two according to C++0x 5.16p5.
2091 ///
2092 /// This is part of the parameter validation for the ? operator. If either
2093 /// value operand is a class type, overload resolution is used to find a
2094 /// conversion to a common type.
2095 static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2096                                     SourceLocation Loc) {
2097   Expr *Args[2] = { LHS, RHS };
2098   OverloadCandidateSet CandidateSet(Loc);
2099   Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
2100
2101   OverloadCandidateSet::iterator Best;
2102   switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
2103     case OR_Success:
2104       // We found a match. Perform the conversions on the arguments and move on.
2105       if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
2106                                          Best->Conversions[0], Sema::AA_Converting) ||
2107           Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
2108                                          Best->Conversions[1], Sema::AA_Converting))
2109         break;
2110       return false;
2111
2112     case OR_No_Viable_Function:
2113       Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2114         << LHS->getType() << RHS->getType()
2115         << LHS->getSourceRange() << RHS->getSourceRange();
2116       return true;
2117
2118     case OR_Ambiguous:
2119       Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2120         << LHS->getType() << RHS->getType()
2121         << LHS->getSourceRange() << RHS->getSourceRange();
2122       // FIXME: Print the possible common types by printing the return types of
2123       // the viable candidates.
2124       break;
2125
2126     case OR_Deleted:
2127       assert(false && "Conditional operator has only built-in overloads");
2128       break;
2129   }
2130   return true;
2131 }
2132
2133 /// \brief Perform an "extended" implicit conversion as returned by
2134 /// TryClassUnification.
2135 static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2136   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2137   InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2138                                                            SourceLocation());
2139   InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2140   Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind, 
2141                                     Sema::MultiExprArg(Self, (void **)&E, 1));
2142   if (Result.isInvalid())
2143     return true;
2144   
2145   E = Result.takeAs<Expr>();
2146   return false;
2147 }
2148
2149 /// \brief Check the operands of ?: under C++ semantics.
2150 ///
2151 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2152 /// extension. In this case, LHS == Cond. (But they're not aliases.)
2153 QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2154                                            SourceLocation QuestionLoc) {
2155   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2156   // interface pointers.
2157
2158   // C++0x 5.16p1
2159   //   The first expression is contextually converted to bool.
2160   if (!Cond->isTypeDependent()) {
2161     if (CheckCXXBooleanCondition(Cond))
2162       return QualType();
2163   }
2164
2165   // Either of the arguments dependent?
2166   if (LHS->isTypeDependent() || RHS->isTypeDependent())
2167     return Context.DependentTy;
2168
2169   // C++0x 5.16p2
2170   //   If either the second or the third operand has type (cv) void, ...
2171   QualType LTy = LHS->getType();
2172   QualType RTy = RHS->getType();
2173   bool LVoid = LTy->isVoidType();
2174   bool RVoid = RTy->isVoidType();
2175   if (LVoid || RVoid) {
2176     //   ... then the [l2r] conversions are performed on the second and third
2177     //   operands ...
2178     DefaultFunctionArrayLvalueConversion(LHS);
2179     DefaultFunctionArrayLvalueConversion(RHS);
2180     LTy = LHS->getType();
2181     RTy = RHS->getType();
2182
2183     //   ... and one of the following shall hold:
2184     //   -- The second or the third operand (but not both) is a throw-
2185     //      expression; the result is of the type of the other and is an rvalue.
2186     bool LThrow = isa<CXXThrowExpr>(LHS);
2187     bool RThrow = isa<CXXThrowExpr>(RHS);
2188     if (LThrow && !RThrow)
2189       return RTy;
2190     if (RThrow && !LThrow)
2191       return LTy;
2192
2193     //   -- Both the second and third operands have type void; the result is of
2194     //      type void and is an rvalue.
2195     if (LVoid && RVoid)
2196       return Context.VoidTy;
2197
2198     // Neither holds, error.
2199     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2200       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2201       << LHS->getSourceRange() << RHS->getSourceRange();
2202     return QualType();
2203   }
2204
2205   // Neither is void.
2206
2207   // C++0x 5.16p3
2208   //   Otherwise, if the second and third operand have different types, and
2209   //   either has (cv) class type, and attempt is made to convert each of those
2210   //   operands to the other.
2211   if (!Context.hasSameType(LTy, RTy) && 
2212       (LTy->isRecordType() || RTy->isRecordType())) {
2213     ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2214     // These return true if a single direction is already ambiguous.
2215     QualType L2RType, R2LType;
2216     bool HaveL2R, HaveR2L;
2217     if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
2218       return QualType();
2219     if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
2220       return QualType();
2221     
2222     //   If both can be converted, [...] the program is ill-formed.
2223     if (HaveL2R && HaveR2L) {
2224       Diag(QuestionLoc, diag::err_conditional_ambiguous)
2225         << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2226       return QualType();
2227     }
2228
2229     //   If exactly one conversion is possible, that conversion is applied to
2230     //   the chosen operand and the converted operands are used in place of the
2231     //   original operands for the remainder of this section.
2232     if (HaveL2R) {
2233       if (ConvertForConditional(*this, LHS, L2RType))
2234         return QualType();
2235       LTy = LHS->getType();
2236     } else if (HaveR2L) {
2237       if (ConvertForConditional(*this, RHS, R2LType))
2238         return QualType();
2239       RTy = RHS->getType();
2240     }
2241   }
2242
2243   // C++0x 5.16p4
2244   //   If the second and third operands are lvalues and have the same type,
2245   //   the result is of that type [...]
2246   bool Same = Context.hasSameType(LTy, RTy);
2247   if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2248       RHS->isLvalue(Context) == Expr::LV_Valid)
2249     return LTy;
2250
2251   // C++0x 5.16p5
2252   //   Otherwise, the result is an rvalue. If the second and third operands
2253   //   do not have the same type, and either has (cv) class type, ...
2254   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2255     //   ... overload resolution is used to determine the conversions (if any)
2256     //   to be applied to the operands. If the overload resolution fails, the
2257     //   program is ill-formed.
2258     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2259       return QualType();
2260   }
2261
2262   // C++0x 5.16p6
2263   //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2264   //   conversions are performed on the second and third operands.
2265   DefaultFunctionArrayLvalueConversion(LHS);
2266   DefaultFunctionArrayLvalueConversion(RHS);
2267   LTy = LHS->getType();
2268   RTy = RHS->getType();
2269
2270   //   After those conversions, one of the following shall hold:
2271   //   -- The second and third operands have the same type; the result
2272   //      is of that type. If the operands have class type, the result
2273   //      is a prvalue temporary of the result type, which is
2274   //      copy-initialized from either the second operand or the third
2275   //      operand depending on the value of the first operand.
2276   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
2277     if (LTy->isRecordType()) {
2278       // The operands have class type. Make a temporary copy.
2279       InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
2280       OwningExprResult LHSCopy = PerformCopyInitialization(Entity, 
2281                                                            SourceLocation(), 
2282                                                            Owned(LHS));
2283       if (LHSCopy.isInvalid())
2284         return QualType();
2285         
2286       OwningExprResult RHSCopy = PerformCopyInitialization(Entity, 
2287                                                            SourceLocation(), 
2288                                                            Owned(RHS));
2289       if (RHSCopy.isInvalid())
2290         return QualType();
2291       
2292       LHS = LHSCopy.takeAs<Expr>();
2293       RHS = RHSCopy.takeAs<Expr>();
2294     }
2295
2296     return LTy;
2297   }
2298
2299   // Extension: conditional operator involving vector types.
2300   if (LTy->isVectorType() || RTy->isVectorType()) 
2301     return CheckVectorOperands(QuestionLoc, LHS, RHS);
2302
2303   //   -- The second and third operands have arithmetic or enumeration type;
2304   //      the usual arithmetic conversions are performed to bring them to a
2305   //      common type, and the result is of that type.
2306   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2307     UsualArithmeticConversions(LHS, RHS);
2308     return LHS->getType();
2309   }
2310
2311   //   -- The second and third operands have pointer type, or one has pointer
2312   //      type and the other is a null pointer constant; pointer conversions
2313   //      and qualification conversions are performed to bring them to their
2314   //      composite pointer type. The result is of the composite pointer type.
2315   //   -- The second and third operands have pointer to member type, or one has
2316   //      pointer to member type and the other is a null pointer constant;
2317   //      pointer to member conversions and qualification conversions are
2318   //      performed to bring them to a common type, whose cv-qualification
2319   //      shall match the cv-qualification of either the second or the third
2320   //      operand. The result is of the common type.
2321   bool NonStandardCompositeType = false;
2322   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
2323                               isSFINAEContext()? 0 : &NonStandardCompositeType);
2324   if (!Composite.isNull()) {
2325     if (NonStandardCompositeType)
2326       Diag(QuestionLoc, 
2327            diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2328         << LTy << RTy << Composite
2329         << LHS->getSourceRange() << RHS->getSourceRange();
2330       
2331     return Composite;
2332   }
2333   
2334   // Similarly, attempt to find composite type of two objective-c pointers.
2335   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2336   if (!Composite.isNull())
2337     return Composite;
2338
2339   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2340     << LHS->getType() << RHS->getType()
2341     << LHS->getSourceRange() << RHS->getSourceRange();
2342   return QualType();
2343 }
2344
2345 /// \brief Find a merged pointer type and convert the two expressions to it.
2346 ///
2347 /// This finds the composite pointer type (or member pointer type) for @p E1
2348 /// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2349 /// type and returns it.
2350 /// It does not emit diagnostics.
2351 ///
2352 /// \param Loc The location of the operator requiring these two expressions to
2353 /// be converted to the composite pointer type.
2354 ///
2355 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2356 /// a non-standard (but still sane) composite type to which both expressions
2357 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2358 /// will be set true.
2359 QualType Sema::FindCompositePointerType(SourceLocation Loc, 
2360                                         Expr *&E1, Expr *&E2,
2361                                         bool *NonStandardCompositeType) {
2362   if (NonStandardCompositeType)
2363     *NonStandardCompositeType = false;
2364   
2365   assert(getLangOptions().CPlusPlus && "This function assumes C++");
2366   QualType T1 = E1->getType(), T2 = E2->getType();
2367
2368   if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2369       !T2->isAnyPointerType() && !T2->isMemberPointerType())
2370    return QualType();
2371
2372   // C++0x 5.9p2
2373   //   Pointer conversions and qualification conversions are performed on
2374   //   pointer operands to bring them to their composite pointer type. If
2375   //   one operand is a null pointer constant, the composite pointer type is
2376   //   the type of the other operand.
2377   if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2378     if (T2->isMemberPointerType())
2379       ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2380     else
2381       ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
2382     return T2;
2383   }
2384   if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2385     if (T1->isMemberPointerType())
2386       ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2387     else
2388       ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
2389     return T1;
2390   }
2391
2392   // Now both have to be pointers or member pointers.
2393   if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2394       (!T2->isPointerType() && !T2->isMemberPointerType()))
2395     return QualType();
2396
2397   //   Otherwise, of one of the operands has type "pointer to cv1 void," then
2398   //   the other has type "pointer to cv2 T" and the composite pointer type is
2399   //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2400   //   Otherwise, the composite pointer type is a pointer type similar to the
2401   //   type of one of the operands, with a cv-qualification signature that is
2402   //   the union of the cv-qualification signatures of the operand types.
2403   // In practice, the first part here is redundant; it's subsumed by the second.
2404   // What we do here is, we build the two possible composite types, and try the
2405   // conversions in both directions. If only one works, or if the two composite
2406   // types are the same, we have succeeded.
2407   // FIXME: extended qualifiers?
2408   typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2409   QualifierVector QualifierUnion;
2410   typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2411       ContainingClassVector;
2412   ContainingClassVector MemberOfClass;
2413   QualType Composite1 = Context.getCanonicalType(T1),
2414            Composite2 = Context.getCanonicalType(T2);
2415   unsigned NeedConstBefore = 0;  
2416   do {
2417     const PointerType *Ptr1, *Ptr2;
2418     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2419         (Ptr2 = Composite2->getAs<PointerType>())) {
2420       Composite1 = Ptr1->getPointeeType();
2421       Composite2 = Ptr2->getPointeeType();
2422       
2423       // If we're allowed to create a non-standard composite type, keep track
2424       // of where we need to fill in additional 'const' qualifiers. 
2425       if (NonStandardCompositeType &&
2426           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2427         NeedConstBefore = QualifierUnion.size();
2428       
2429       QualifierUnion.push_back(
2430                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2431       MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2432       continue;
2433     }
2434
2435     const MemberPointerType *MemPtr1, *MemPtr2;
2436     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2437         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2438       Composite1 = MemPtr1->getPointeeType();
2439       Composite2 = MemPtr2->getPointeeType();
2440       
2441       // If we're allowed to create a non-standard composite type, keep track
2442       // of where we need to fill in additional 'const' qualifiers. 
2443       if (NonStandardCompositeType &&
2444           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2445         NeedConstBefore = QualifierUnion.size();
2446       
2447       QualifierUnion.push_back(
2448                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2449       MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2450                                              MemPtr2->getClass()));
2451       continue;
2452     }
2453
2454     // FIXME: block pointer types?
2455
2456     // Cannot unwrap any more types.
2457     break;
2458   } while (true);
2459
2460   if (NeedConstBefore && NonStandardCompositeType) {
2461     // Extension: Add 'const' to qualifiers that come before the first qualifier
2462     // mismatch, so that our (non-standard!) composite type meets the 
2463     // requirements of C++ [conv.qual]p4 bullet 3.
2464     for (unsigned I = 0; I != NeedConstBefore; ++I) {
2465       if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2466         QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2467         *NonStandardCompositeType = true;
2468       }
2469     }
2470   }
2471   
2472   // Rewrap the composites as pointers or member pointers with the union CVRs.
2473   ContainingClassVector::reverse_iterator MOC
2474     = MemberOfClass.rbegin();
2475   for (QualifierVector::reverse_iterator
2476          I = QualifierUnion.rbegin(),
2477          E = QualifierUnion.rend();
2478        I != E; (void)++I, ++MOC) {
2479     Qualifiers Quals = Qualifiers::fromCVRMask(*I);
2480     if (MOC->first && MOC->second) {
2481       // Rebuild member pointer type
2482       Composite1 = Context.getMemberPointerType(
2483                                     Context.getQualifiedType(Composite1, Quals),
2484                                     MOC->first);
2485       Composite2 = Context.getMemberPointerType(
2486                                     Context.getQualifiedType(Composite2, Quals),
2487                                     MOC->second);
2488     } else {
2489       // Rebuild pointer type
2490       Composite1
2491         = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2492       Composite2
2493         = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
2494     }
2495   }
2496
2497   // Try to convert to the first composite pointer type.
2498   InitializedEntity Entity1
2499     = InitializedEntity::InitializeTemporary(Composite1);
2500   InitializationKind Kind
2501     = InitializationKind::CreateCopy(Loc, SourceLocation());
2502   InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2503   InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
2504
2505   if (E1ToC1 && E2ToC1) {
2506     // Conversion to Composite1 is viable.
2507     if (!Context.hasSameType(Composite1, Composite2)) {
2508       // Composite2 is a different type from Composite1. Check whether
2509       // Composite2 is also viable.
2510       InitializedEntity Entity2
2511         = InitializedEntity::InitializeTemporary(Composite2);
2512       InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2513       InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2514       if (E1ToC2 && E2ToC2) {
2515         // Both Composite1 and Composite2 are viable and are different;
2516         // this is an ambiguity.
2517         return QualType();
2518       }
2519     }
2520
2521     // Convert E1 to Composite1
2522     OwningExprResult E1Result
2523       = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2524     if (E1Result.isInvalid())
2525       return QualType();
2526     E1 = E1Result.takeAs<Expr>();
2527
2528     // Convert E2 to Composite1
2529     OwningExprResult E2Result
2530       = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2531     if (E2Result.isInvalid())
2532       return QualType();
2533     E2 = E2Result.takeAs<Expr>();
2534     
2535     return Composite1;
2536   }
2537
2538   // Check whether Composite2 is viable.
2539   InitializedEntity Entity2
2540     = InitializedEntity::InitializeTemporary(Composite2);
2541   InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2542   InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2543   if (!E1ToC2 || !E2ToC2)
2544     return QualType();
2545   
2546   // Convert E1 to Composite2
2547   OwningExprResult E1Result
2548     = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2549   if (E1Result.isInvalid())
2550     return QualType();
2551   E1 = E1Result.takeAs<Expr>();
2552   
2553   // Convert E2 to Composite2
2554   OwningExprResult E2Result
2555     = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2556   if (E2Result.isInvalid())
2557     return QualType();
2558   E2 = E2Result.takeAs<Expr>();
2559   
2560   return Composite2;
2561 }
2562
2563 Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
2564   if (!Context.getLangOptions().CPlusPlus)
2565     return Owned(E);
2566
2567   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2568
2569   const RecordType *RT = E->getType()->getAs<RecordType>();
2570   if (!RT)
2571     return Owned(E);
2572
2573   // If this is the result of a call expression, our source might
2574   // actually be a reference, in which case we shouldn't bind.
2575   if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2576     QualType Ty = CE->getCallee()->getType();
2577     if (const PointerType *PT = Ty->getAs<PointerType>())
2578       Ty = PT->getPointeeType();
2579     else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2580       Ty = BPT->getPointeeType();
2581
2582     const FunctionType *FTy = Ty->getAs<FunctionType>();
2583     if (FTy->getResultType()->isReferenceType())
2584       return Owned(E);
2585   }
2586
2587   // That should be enough to guarantee that this type is complete.
2588   // If it has a trivial destructor, we can avoid the extra copy.
2589   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2590   if (RD->hasTrivialDestructor())
2591     return Owned(E);
2592
2593   CXXTemporary *Temp = CXXTemporary::Create(Context,
2594                                             RD->getDestructor(Context));
2595   ExprTemporaries.push_back(Temp);
2596   if (CXXDestructorDecl *Destructor =
2597         const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
2598     MarkDeclarationReferenced(E->getExprLoc(), Destructor);
2599     CheckDestructorAccess(E->getExprLoc(), Destructor,
2600                           PDiag(diag::err_access_dtor_temp)
2601                             << E->getType());
2602   }
2603   // FIXME: Add the temporary to the temporaries vector.
2604   return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2605 }
2606
2607 Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
2608   assert(SubExpr && "sub expression can't be null!");
2609
2610   // Check any implicit conversions within the expression.
2611   CheckImplicitConversions(SubExpr);
2612
2613   unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2614   assert(ExprTemporaries.size() >= FirstTemporary);
2615   if (ExprTemporaries.size() == FirstTemporary)
2616     return SubExpr;
2617
2618   Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
2619                                            &ExprTemporaries[FirstTemporary],
2620                                        ExprTemporaries.size() - FirstTemporary);
2621   ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2622                         ExprTemporaries.end());
2623
2624   return E;
2625 }
2626
2627 Sema::OwningExprResult 
2628 Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2629   if (SubExpr.isInvalid())
2630     return ExprError();
2631   
2632   return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2633 }
2634
2635 FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2636   unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2637   assert(ExprTemporaries.size() >= FirstTemporary);
2638   
2639   unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2640   CXXTemporary **Temporaries = 
2641     NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2642   
2643   FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2644
2645   ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2646                         ExprTemporaries.end());
2647
2648   return E;
2649 }
2650
2651 Sema::OwningExprResult
2652 Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2653                                    tok::TokenKind OpKind, TypeTy *&ObjectType,
2654                                    bool &MayBePseudoDestructor) {
2655   // Since this might be a postfix expression, get rid of ParenListExprs.
2656   Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2657
2658   Expr *BaseExpr = (Expr*)Base.get();
2659   assert(BaseExpr && "no record expansion");
2660
2661   QualType BaseType = BaseExpr->getType();
2662   MayBePseudoDestructor = false;
2663   if (BaseType->isDependentType()) {
2664     // If we have a pointer to a dependent type and are using the -> operator,
2665     // the object type is the type that the pointer points to. We might still
2666     // have enough information about that type to do something useful.
2667     if (OpKind == tok::arrow)
2668       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2669         BaseType = Ptr->getPointeeType();
2670     
2671     ObjectType = BaseType.getAsOpaquePtr();
2672     MayBePseudoDestructor = true;
2673     return move(Base);
2674   }
2675
2676   // C++ [over.match.oper]p8:
2677   //   [...] When operator->returns, the operator-> is applied  to the value
2678   //   returned, with the original second operand.
2679   if (OpKind == tok::arrow) {
2680     // The set of types we've considered so far.
2681     llvm::SmallPtrSet<CanQualType,8> CTypes;
2682     llvm::SmallVector<SourceLocation, 8> Locations;
2683     CTypes.insert(Context.getCanonicalType(BaseType));
2684     
2685     while (BaseType->isRecordType()) {
2686       Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
2687       BaseExpr = (Expr*)Base.get();
2688       if (BaseExpr == NULL)
2689         return ExprError();
2690       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
2691         Locations.push_back(OpCall->getDirectCallee()->getLocation());
2692       BaseType = BaseExpr->getType();
2693       CanQualType CBaseType = Context.getCanonicalType(BaseType);
2694       if (!CTypes.insert(CBaseType)) {
2695         Diag(OpLoc, diag::err_operator_arrow_circular);
2696         for (unsigned i = 0; i < Locations.size(); i++)
2697           Diag(Locations[i], diag::note_declared_at);
2698         return ExprError();
2699       }
2700     }
2701
2702     if (BaseType->isPointerType())
2703       BaseType = BaseType->getPointeeType();
2704   }
2705
2706   // We could end up with various non-record types here, such as extended
2707   // vector types or Objective-C interfaces. Just return early and let
2708   // ActOnMemberReferenceExpr do the work.
2709   if (!BaseType->isRecordType()) {
2710     // C++ [basic.lookup.classref]p2:
2711     //   [...] If the type of the object expression is of pointer to scalar
2712     //   type, the unqualified-id is looked up in the context of the complete
2713     //   postfix-expression.
2714     //
2715     // This also indicates that we should be parsing a
2716     // pseudo-destructor-name.
2717     ObjectType = 0;
2718     MayBePseudoDestructor = true;
2719     return move(Base);
2720   }
2721
2722   // The object type must be complete (or dependent).
2723   if (!BaseType->isDependentType() &&
2724       RequireCompleteType(OpLoc, BaseType, 
2725                           PDiag(diag::err_incomplete_member_access)))
2726     return ExprError();
2727   
2728   // C++ [basic.lookup.classref]p2:
2729   //   If the id-expression in a class member access (5.2.5) is an
2730   //   unqualified-id, and the type of the object expression is of a class
2731   //   type C (or of pointer to a class type C), the unqualified-id is looked
2732   //   up in the scope of class C. [...]
2733   ObjectType = BaseType.getAsOpaquePtr();
2734   return move(Base);
2735 }
2736
2737 Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2738                                                    ExprArg MemExpr) {
2739   Expr *E = (Expr *) MemExpr.get();
2740   SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2741   Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2742     << isa<CXXPseudoDestructorExpr>(E)
2743     << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
2744   
2745   return ActOnCallExpr(/*Scope*/ 0,
2746                        move(MemExpr),
2747                        /*LPLoc*/ ExpectedLParenLoc,
2748                        Sema::MultiExprArg(*this, 0, 0),
2749                        /*CommaLocs*/ 0,
2750                        /*RPLoc*/ ExpectedLParenLoc);
2751 }
2752
2753 Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2754                                                        SourceLocation OpLoc,
2755                                                        tok::TokenKind OpKind,
2756                                                        const CXXScopeSpec &SS,
2757                                                  TypeSourceInfo *ScopeTypeInfo,
2758                                                        SourceLocation CCLoc,
2759                                                        SourceLocation TildeLoc,
2760                                          PseudoDestructorTypeStorage Destructed,
2761                                                        bool HasTrailingLParen) {
2762   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
2763   
2764   // C++ [expr.pseudo]p2:
2765   //   The left-hand side of the dot operator shall be of scalar type. The 
2766   //   left-hand side of the arrow operator shall be of pointer to scalar type.
2767   //   This scalar type is the object type. 
2768   Expr *BaseE = (Expr *)Base.get();
2769   QualType ObjectType = BaseE->getType();
2770   if (OpKind == tok::arrow) {
2771     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2772       ObjectType = Ptr->getPointeeType();
2773     } else if (!BaseE->isTypeDependent()) {
2774       // The user wrote "p->" when she probably meant "p."; fix it.
2775       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2776         << ObjectType << true
2777         << FixItHint::CreateReplacement(OpLoc, ".");
2778       if (isSFINAEContext())
2779         return ExprError();
2780       
2781       OpKind = tok::period;
2782     }
2783   }
2784   
2785   if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2786     Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2787       << ObjectType << BaseE->getSourceRange();
2788     return ExprError();
2789   }
2790
2791   // C++ [expr.pseudo]p2:
2792   //   [...] The cv-unqualified versions of the object type and of the type 
2793   //   designated by the pseudo-destructor-name shall be the same type.
2794   if (DestructedTypeInfo) {
2795     QualType DestructedType = DestructedTypeInfo->getType();
2796     SourceLocation DestructedTypeStart
2797       = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
2798     if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2799         !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2800       Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2801         << ObjectType << DestructedType << BaseE->getSourceRange()
2802         << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
2803       
2804       // Recover by setting the destructed type to the object type.
2805       DestructedType = ObjectType;
2806       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2807                                                            DestructedTypeStart);
2808       Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2809     }
2810   }
2811   
2812   // C++ [expr.pseudo]p2:
2813   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2814   //   form
2815   //
2816   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 
2817   //
2818   //   shall designate the same scalar type.
2819   if (ScopeTypeInfo) {
2820     QualType ScopeType = ScopeTypeInfo->getType();
2821     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2822         !Context.hasSameType(ScopeType, ObjectType)) {
2823       
2824       Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
2825            diag::err_pseudo_dtor_type_mismatch)
2826         << ObjectType << ScopeType << BaseE->getSourceRange()
2827         << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
2828   
2829       ScopeType = QualType();
2830       ScopeTypeInfo = 0;
2831     }
2832   }
2833   
2834   OwningExprResult Result
2835     = Owned(new (Context) CXXPseudoDestructorExpr(Context, 
2836                                                   Base.takeAs<Expr>(),
2837                                                   OpKind == tok::arrow,
2838                                                   OpLoc,
2839                                        (NestedNameSpecifier *) SS.getScopeRep(),
2840                                                   SS.getRange(),
2841                                                   ScopeTypeInfo,
2842                                                   CCLoc,
2843                                                   TildeLoc,
2844                                                   Destructed));
2845             
2846   if (HasTrailingLParen)
2847     return move(Result);
2848   
2849   return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
2850 }
2851
2852 Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2853                                                        SourceLocation OpLoc,
2854                                                        tok::TokenKind OpKind,
2855                                                        CXXScopeSpec &SS,
2856                                                   UnqualifiedId &FirstTypeName,
2857                                                        SourceLocation CCLoc,
2858                                                        SourceLocation TildeLoc,
2859                                                  UnqualifiedId &SecondTypeName,
2860                                                        bool HasTrailingLParen) {
2861   assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2862           FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2863          "Invalid first type name in pseudo-destructor");
2864   assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2865           SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2866          "Invalid second type name in pseudo-destructor");
2867
2868   Expr *BaseE = (Expr *)Base.get();
2869   
2870   // C++ [expr.pseudo]p2:
2871   //   The left-hand side of the dot operator shall be of scalar type. The 
2872   //   left-hand side of the arrow operator shall be of pointer to scalar type.
2873   //   This scalar type is the object type. 
2874   QualType ObjectType = BaseE->getType();
2875   if (OpKind == tok::arrow) {
2876     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2877       ObjectType = Ptr->getPointeeType();
2878     } else if (!ObjectType->isDependentType()) {
2879       // The user wrote "p->" when she probably meant "p."; fix it.
2880       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2881         << ObjectType << true
2882         << FixItHint::CreateReplacement(OpLoc, ".");
2883       if (isSFINAEContext())
2884         return ExprError();
2885       
2886       OpKind = tok::period;
2887     }
2888   }
2889
2890   // Compute the object type that we should use for name lookup purposes. Only
2891   // record types and dependent types matter.
2892   void *ObjectTypePtrForLookup = 0;
2893   if (!SS.isSet()) {
2894     ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2895     if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2896       ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2897   }
2898   
2899   // Convert the name of the type being destructed (following the ~) into a 
2900   // type (with source-location information).
2901   QualType DestructedType;
2902   TypeSourceInfo *DestructedTypeInfo = 0;
2903   PseudoDestructorTypeStorage Destructed;
2904   if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2905     TypeTy *T = getTypeName(*SecondTypeName.Identifier, 
2906                             SecondTypeName.StartLocation,
2907                             S, &SS, true, ObjectTypePtrForLookup);
2908     if (!T && 
2909         ((SS.isSet() && !computeDeclContext(SS, false)) ||
2910          (!SS.isSet() && ObjectType->isDependentType()))) {
2911       // The name of the type being destroyed is a dependent name, and we 
2912       // couldn't find anything useful in scope. Just store the identifier and
2913       // it's location, and we'll perform (qualified) name lookup again at
2914       // template instantiation time.
2915       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2916                                                SecondTypeName.StartLocation);
2917     } else if (!T) {
2918       Diag(SecondTypeName.StartLocation, 
2919            diag::err_pseudo_dtor_destructor_non_type)
2920         << SecondTypeName.Identifier << ObjectType;
2921       if (isSFINAEContext())
2922         return ExprError();
2923       
2924       // Recover by assuming we had the right type all along.
2925       DestructedType = ObjectType;
2926     } else
2927       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
2928   } else {
2929     // Resolve the template-id to a type.
2930     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
2931     ASTTemplateArgsPtr TemplateArgsPtr(*this,
2932                                        TemplateId->getTemplateArgs(),
2933                                        TemplateId->NumArgs);
2934     TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2935                                        TemplateId->TemplateNameLoc,
2936                                        TemplateId->LAngleLoc,
2937                                        TemplateArgsPtr,
2938                                        TemplateId->RAngleLoc);
2939     if (T.isInvalid() || !T.get()) {
2940       // Recover by assuming we had the right type all along.
2941       DestructedType = ObjectType;
2942     } else
2943       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
2944   }
2945   
2946   // If we've performed some kind of recovery, (re-)build the type source 
2947   // information.
2948   if (!DestructedType.isNull()) {
2949     if (!DestructedTypeInfo)
2950       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
2951                                                   SecondTypeName.StartLocation);
2952     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2953   }
2954   
2955   // Convert the name of the scope type (the type prior to '::') into a type.
2956   TypeSourceInfo *ScopeTypeInfo = 0;
2957   QualType ScopeType;
2958   if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 
2959       FirstTypeName.Identifier) {
2960     if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2961       TypeTy *T = getTypeName(*FirstTypeName.Identifier, 
2962                               FirstTypeName.StartLocation,
2963                               S, &SS, false, ObjectTypePtrForLookup);
2964       if (!T) {
2965         Diag(FirstTypeName.StartLocation, 
2966              diag::err_pseudo_dtor_destructor_non_type)
2967           << FirstTypeName.Identifier << ObjectType;
2968         
2969         if (isSFINAEContext())
2970           return ExprError();
2971         
2972         // Just drop this type. It's unnecessary anyway.
2973         ScopeType = QualType();
2974       } else
2975         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
2976     } else {
2977       // Resolve the template-id to a type.
2978       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
2979       ASTTemplateArgsPtr TemplateArgsPtr(*this,
2980                                          TemplateId->getTemplateArgs(),
2981                                          TemplateId->NumArgs);
2982       TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2983                                          TemplateId->TemplateNameLoc,
2984                                          TemplateId->LAngleLoc,
2985                                          TemplateArgsPtr,
2986                                          TemplateId->RAngleLoc);
2987       if (T.isInvalid() || !T.get()) {
2988         // Recover by dropping this type.
2989         ScopeType = QualType();
2990       } else
2991         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);      
2992     }
2993   }
2994       
2995   if (!ScopeType.isNull() && !ScopeTypeInfo)
2996     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2997                                                   FirstTypeName.StartLocation);
2998
2999     
3000   return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
3001                                    ScopeTypeInfo, CCLoc, TildeLoc,
3002                                    Destructed, HasTrailingLParen);
3003 }
3004
3005 CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, 
3006                                                 NamedDecl *FoundDecl,
3007                                                 CXXMethodDecl *Method) {
3008   if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3009                                           FoundDecl, Method))
3010     assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
3011
3012   MemberExpr *ME = 
3013       new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, 
3014                                SourceLocation(), Method->getType());
3015   QualType ResultType = Method->getResultType().getNonReferenceType();
3016   MarkDeclarationReferenced(Exp->getLocStart(), Method);
3017   CXXMemberCallExpr *CE =
3018     new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
3019                                     Exp->getLocEnd());
3020   return CE;
3021 }
3022
3023 Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
3024   Expr *FullExpr = Arg.takeAs<Expr>();
3025   if (FullExpr)
3026     FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
3027   else
3028     return ExprError();
3029   
3030   return Owned(FullExpr);
3031 }