clang API Documentation

SemaExprCXX.cpp

Go to the documentation of this file.
00001 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for C++ expressions.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "Sema.h"
00015 #include "SemaInit.h"
00016 #include "Lookup.h"
00017 #include "clang/AST/ASTContext.h"
00018 #include "clang/AST/CXXInheritance.h"
00019 #include "clang/AST/ExprCXX.h"
00020 #include "clang/AST/TypeLoc.h"
00021 #include "clang/Basic/PartialDiagnostic.h"
00022 #include "clang/Basic/TargetInfo.h"
00023 #include "clang/Lex/Preprocessor.h"
00024 #include "clang/Parse/DeclSpec.h"
00025 #include "clang/Parse/Template.h"
00026 #include "llvm/ADT/STLExtras.h"
00027 using namespace clang;
00028 
00029 Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
00030                                         IdentifierInfo &II, 
00031                                         SourceLocation NameLoc,
00032                                         Scope *S, CXXScopeSpec &SS,
00033                                         TypeTy *ObjectTypePtr,
00034                                         bool EnteringContext) {
00035   // Determine where to perform name lookup.
00036 
00037   // FIXME: This area of the standard is very messy, and the current
00038   // wording is rather unclear about which scopes we search for the
00039   // destructor name; see core issues 399 and 555. Issue 399 in
00040   // particular shows where the current description of destructor name
00041   // lookup is completely out of line with existing practice, e.g.,
00042   // this appears to be ill-formed:
00043   //
00044   //   namespace N {
00045   //     template <typename T> struct S {
00046   //       ~S();
00047   //     };
00048   //   }
00049   //
00050   //   void f(N::S<int>* s) {
00051   //     s->N::S<int>::~S();
00052   //   }
00053   //
00054   // See also PR6358 and PR6359.
00055   QualType SearchType;
00056   DeclContext *LookupCtx = 0;
00057   bool isDependent = false;
00058   bool LookInScope = false;
00059 
00060   // If we have an object type, it's because we are in a
00061   // pseudo-destructor-expression or a member access expression, and
00062   // we know what type we're looking for.
00063   if (ObjectTypePtr)
00064     SearchType = GetTypeFromParser(ObjectTypePtr);
00065 
00066   if (SS.isSet()) {
00067     NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
00068     
00069     bool AlreadySearched = false;
00070     bool LookAtPrefix = true;
00071     if (!getLangOptions().CPlusPlus0x) {
00072       // C++ [basic.lookup.qual]p6:
00073       //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 
00074       //   the type-names are looked up as types in the scope designated by the
00075       //   nested-name-specifier. In a qualified-id of the form:
00076       // 
00077       //     ::[opt] nested-name-specifier  ̃ class-name 
00078       //
00079       //   where the nested-name-specifier designates a namespace scope, and in
00080       //   a qualified-id of the form:
00081       //
00082       //     ::opt nested-name-specifier class-name ::  ̃ class-name 
00083       //
00084       //   the class-names are looked up as types in the scope designated by 
00085       //   the nested-name-specifier.
00086       //
00087       // Here, we check the first case (completely) and determine whether the
00088       // code below is permitted to look at the prefix of the 
00089       // nested-name-specifier (as we do in C++0x).
00090       DeclContext *DC = computeDeclContext(SS, EnteringContext);
00091       if (DC && DC->isFileContext()) {
00092         AlreadySearched = true;
00093         LookupCtx = DC;
00094         isDependent = false;
00095       } else if (DC && isa<CXXRecordDecl>(DC))
00096         LookAtPrefix = false;
00097     }
00098     
00099     // C++0x [basic.lookup.qual]p6:
00100     //   If a pseudo-destructor-name (5.2.4) contains a
00101     //   nested-name-specifier, the type-names are looked up as types
00102     //   in the scope designated by the nested-name-specifier. Similarly, in 
00103     //   a qualified-id of the form:
00104     //
00105     //     :: [opt] nested-name-specifier[opt] class-name :: ~class-name 
00106     //
00107     //   the second class-name is looked up in the same scope as the first.
00108     //
00109     // To implement this, we look at the prefix of the
00110     // nested-name-specifier we were given, and determine the lookup
00111     // context from that.
00112     //
00113     // We also fold in the second case from the C++03 rules quoted further 
00114     // above.
00115     NestedNameSpecifier *Prefix = 0;
00116     if (AlreadySearched) {
00117       // Nothing left to do.
00118     } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
00119       CXXScopeSpec PrefixSS;
00120       PrefixSS.setScopeRep(Prefix);
00121       LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
00122       isDependent = isDependentScopeSpecifier(PrefixSS);
00123     } else if (getLangOptions().CPlusPlus0x &&
00124                (LookupCtx = computeDeclContext(SS, EnteringContext))) {
00125       if (!LookupCtx->isTranslationUnit())
00126         LookupCtx = LookupCtx->getParent();
00127       isDependent = LookupCtx && LookupCtx->isDependentContext();
00128     } else if (ObjectTypePtr) {
00129       LookupCtx = computeDeclContext(SearchType);
00130       isDependent = SearchType->isDependentType();
00131     } else {
00132       LookupCtx = computeDeclContext(SS, EnteringContext);
00133       isDependent = LookupCtx && LookupCtx->isDependentContext();
00134     }
00135     
00136     LookInScope = false;
00137   } else if (ObjectTypePtr) {
00138     // C++ [basic.lookup.classref]p3:
00139     //   If the unqualified-id is ~type-name, the type-name is looked up
00140     //   in the context of the entire postfix-expression. If the type T
00141     //   of the object expression is of a class type C, the type-name is
00142     //   also looked up in the scope of class C. At least one of the
00143     //   lookups shall find a name that refers to (possibly
00144     //   cv-qualified) T.
00145     LookupCtx = computeDeclContext(SearchType);
00146     isDependent = SearchType->isDependentType();
00147     assert((isDependent || !SearchType->isIncompleteType()) && 
00148            "Caller should have completed object type");
00149 
00150     LookInScope = true;
00151   } else {
00152     // Perform lookup into the current scope (only).
00153     LookInScope = true;
00154   }
00155 
00156   LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
00157   for (unsigned Step = 0; Step != 2; ++Step) {
00158     // Look for the name first in the computed lookup context (if we
00159     // have one) and, if that fails to find a match, in the sope (if
00160     // we're allowed to look there).
00161     Found.clear();
00162     if (Step == 0 && LookupCtx)
00163       LookupQualifiedName(Found, LookupCtx);
00164     else if (Step == 1 && LookInScope && S)
00165       LookupName(Found, S);
00166     else
00167       continue;
00168 
00169     // FIXME: Should we be suppressing ambiguities here?
00170     if (Found.isAmbiguous())
00171       return 0;
00172 
00173     if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
00174       QualType T = Context.getTypeDeclType(Type);
00175 
00176       if (SearchType.isNull() || SearchType->isDependentType() ||
00177           Context.hasSameUnqualifiedType(T, SearchType)) {
00178         // We found our type!
00179 
00180         return T.getAsOpaquePtr();
00181       }
00182     }
00183 
00184     // If the name that we found is a class template name, and it is
00185     // the same name as the template name in the last part of the
00186     // nested-name-specifier (if present) or the object type, then
00187     // this is the destructor for that class.
00188     // FIXME: This is a workaround until we get real drafting for core
00189     // issue 399, for which there isn't even an obvious direction. 
00190     if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
00191       QualType MemberOfType;
00192       if (SS.isSet()) {
00193         if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
00194           // Figure out the type of the context, if it has one.
00195           if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
00196             MemberOfType = Context.getTypeDeclType(Record);
00197         }
00198       }
00199       if (MemberOfType.isNull())
00200         MemberOfType = SearchType;
00201       
00202       if (MemberOfType.isNull())
00203         continue;
00204 
00205       // We're referring into a class template specialization. If the
00206       // class template we found is the same as the template being
00207       // specialized, we found what we are looking for.
00208       if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
00209         if (ClassTemplateSpecializationDecl *Spec
00210               = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
00211           if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
00212                 Template->getCanonicalDecl())
00213             return MemberOfType.getAsOpaquePtr();
00214         }
00215 
00216         continue;
00217       }
00218       
00219       // We're referring to an unresolved class template
00220       // specialization. Determine whether we class template we found
00221       // is the same as the template being specialized or, if we don't
00222       // know which template is being specialized, that it at least
00223       // has the same name.
00224       if (const TemplateSpecializationType *SpecType
00225             = MemberOfType->getAs<TemplateSpecializationType>()) {
00226         TemplateName SpecName = SpecType->getTemplateName();
00227 
00228         // The class template we found is the same template being
00229         // specialized.
00230         if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
00231           if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
00232             return MemberOfType.getAsOpaquePtr();
00233 
00234           continue;
00235         }
00236 
00237         // The class template we found has the same name as the
00238         // (dependent) template name being specialized.
00239         if (DependentTemplateName *DepTemplate 
00240                                     = SpecName.getAsDependentTemplateName()) {
00241           if (DepTemplate->isIdentifier() &&
00242               DepTemplate->getIdentifier() == Template->getIdentifier())
00243             return MemberOfType.getAsOpaquePtr();
00244 
00245           continue;
00246         }
00247       }
00248     }
00249   }
00250 
00251   if (isDependent) {
00252     // We didn't find our type, but that's okay: it's dependent
00253     // anyway.
00254     NestedNameSpecifier *NNS = 0;
00255     SourceRange Range;
00256     if (SS.isSet()) {
00257       NNS = (NestedNameSpecifier *)SS.getScopeRep();
00258       Range = SourceRange(SS.getRange().getBegin(), NameLoc);
00259     } else {
00260       NNS = NestedNameSpecifier::Create(Context, &II);
00261       Range = SourceRange(NameLoc);
00262     }
00263 
00264     return CheckTypenameType(ETK_None, NNS, II, Range).getAsOpaquePtr();
00265   }
00266 
00267   if (ObjectTypePtr)
00268     Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
00269       << &II;        
00270   else
00271     Diag(NameLoc, diag::err_destructor_class_name);
00272 
00273   return 0;
00274 }
00275 
00276 /// \brief Build a C++ typeid expression with a type operand.
00277 Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
00278                                             SourceLocation TypeidLoc,
00279                                             TypeSourceInfo *Operand,
00280                                             SourceLocation RParenLoc) {
00281   // C++ [expr.typeid]p4:
00282   //   The top-level cv-qualifiers of the lvalue expression or the type-id 
00283   //   that is the operand of typeid are always ignored.
00284   //   If the type of the type-id is a class type or a reference to a class 
00285   //   type, the class shall be completely-defined.
00286   QualType T = Operand->getType().getNonReferenceType();
00287   if (T->getAs<RecordType>() &&
00288       RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
00289     return ExprError();
00290   
00291   return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
00292                                            Operand,
00293                                            SourceRange(TypeidLoc, RParenLoc)));
00294 }
00295 
00296 /// \brief Build a C++ typeid expression with an expression operand.
00297 Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
00298                                             SourceLocation TypeidLoc,
00299                                             ExprArg Operand,
00300                                             SourceLocation RParenLoc) {
00301   bool isUnevaluatedOperand = true;
00302   Expr *E = static_cast<Expr *>(Operand.get());
00303   if (E && !E->isTypeDependent()) {
00304     QualType T = E->getType();
00305     if (const RecordType *RecordT = T->getAs<RecordType>()) {
00306       CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
00307       // C++ [expr.typeid]p3:
00308       //   [...] If the type of the expression is a class type, the class
00309       //   shall be completely-defined.
00310       if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
00311         return ExprError();
00312       
00313       // C++ [expr.typeid]p3:
00314       //   When typeid is applied to an expression other than an lvalue of a
00315       //   polymorphic class type [...] [the] expression is an unevaluated
00316       //   operand. [...]
00317       if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
00318         isUnevaluatedOperand = false;
00319     }
00320     
00321     // C++ [expr.typeid]p4:
00322     //   [...] If the type of the type-id is a reference to a possibly
00323     //   cv-qualified type, the result of the typeid expression refers to a 
00324     //   std::type_info object representing the cv-unqualified referenced 
00325     //   type.
00326     if (T.hasQualifiers()) {
00327       ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
00328                         E->isLvalue(Context));
00329       Operand.release();
00330       Operand = Owned(E);
00331     }
00332   }
00333   
00334   // If this is an unevaluated operand, clear out the set of
00335   // declaration references we have been computing and eliminate any
00336   // temporaries introduced in its computation.
00337   if (isUnevaluatedOperand)
00338     ExprEvalContexts.back().Context = Unevaluated;
00339   
00340   return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
00341                                            Operand.takeAs<Expr>(),
00342                                            SourceRange(TypeidLoc, RParenLoc)));  
00343 }
00344 
00345 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
00346 Action::OwningExprResult
00347 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
00348                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
00349   // Find the std::type_info type.
00350   if (!StdNamespace)
00351     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
00352 
00353   IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
00354   LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
00355   LookupQualifiedName(R, StdNamespace);
00356   RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
00357   if (!TypeInfoRecordDecl)
00358     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
00359   
00360   QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
00361   
00362   if (isType) {
00363     // The operand is a type; handle it as such.
00364     TypeSourceInfo *TInfo = 0;
00365     QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
00366     if (T.isNull())
00367       return ExprError();
00368     
00369     if (!TInfo)
00370       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
00371 
00372     return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
00373   }
00374 
00375   // The operand is an expression.  
00376   return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
00377 }
00378 
00379 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
00380 Action::OwningExprResult
00381 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
00382   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
00383          "Unknown C++ Boolean value!");
00384   return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
00385                                                 Context.BoolTy, OpLoc));
00386 }
00387 
00388 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
00389 Action::OwningExprResult
00390 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
00391   return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
00392 }
00393 
00394 /// ActOnCXXThrow - Parse throw expressions.
00395 Action::OwningExprResult
00396 Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
00397   Expr *Ex = E.takeAs<Expr>();
00398   if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
00399     return ExprError();
00400   return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
00401 }
00402 
00403 /// CheckCXXThrowOperand - Validate the operand of a throw.
00404 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
00405   // C++ [except.throw]p3:
00406   //   A throw-expression initializes a temporary object, called the exception
00407   //   object, the type of which is determined by removing any top-level
00408   //   cv-qualifiers from the static type of the operand of throw and adjusting
00409   //   the type from "array of T" or "function returning T" to "pointer to T" 
00410   //   or "pointer to function returning T", [...]
00411   if (E->getType().hasQualifiers())
00412     ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
00413                       E->isLvalue(Context) == Expr::LV_Valid);
00414   
00415   DefaultFunctionArrayConversion(E);
00416 
00417   //   If the type of the exception would be an incomplete type or a pointer
00418   //   to an incomplete type other than (cv) void the program is ill-formed.
00419   QualType Ty = E->getType();
00420   bool isPointer = false;
00421   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
00422     Ty = Ptr->getPointeeType();
00423     isPointer = true;
00424   }
00425   if (!isPointer || !Ty->isVoidType()) {
00426     if (RequireCompleteType(ThrowLoc, Ty,
00427                             PDiag(isPointer ? diag::err_throw_incomplete_ptr
00428                                             : diag::err_throw_incomplete)
00429                               << E->getSourceRange()))
00430       return true;
00431 
00432     if (RequireNonAbstractType(ThrowLoc, E->getType(),
00433                                PDiag(diag::err_throw_abstract_type)
00434                                  << E->getSourceRange()))
00435       return true;
00436   }
00437 
00438   // Initialize the exception result.  This implicitly weeds out
00439   // abstract types or types with inaccessible copy constructors.
00440   InitializedEntity Entity =
00441     InitializedEntity::InitializeException(ThrowLoc, E->getType());
00442   OwningExprResult Res = PerformCopyInitialization(Entity,
00443                                                    SourceLocation(),
00444                                                    Owned(E));
00445   if (Res.isInvalid())
00446     return true;
00447   E = Res.takeAs<Expr>();
00448   return false;
00449 }
00450 
00451 Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
00452   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
00453   /// is a non-lvalue expression whose value is the address of the object for
00454   /// which the function is called.
00455 
00456   if (!isa<FunctionDecl>(CurContext))
00457     return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
00458 
00459   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
00460     if (MD->isInstance())
00461       return Owned(new (Context) CXXThisExpr(ThisLoc,
00462                                              MD->getThisType(Context),
00463                                              /*isImplicit=*/false));
00464 
00465   return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
00466 }
00467 
00468 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
00469 /// Can be interpreted either as function-style casting ("int(x)")
00470 /// or class type construction ("ClassType(x,y,z)")
00471 /// or creation of a value-initialized type ("int()").
00472 Action::OwningExprResult
00473 Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
00474                                 SourceLocation LParenLoc,
00475                                 MultiExprArg exprs,
00476                                 SourceLocation *CommaLocs,
00477                                 SourceLocation RParenLoc) {
00478   if (!TypeRep)
00479     return ExprError();
00480 
00481   TypeSourceInfo *TInfo;
00482   QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
00483   if (!TInfo)
00484     TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
00485   unsigned NumExprs = exprs.size();
00486   Expr **Exprs = (Expr**)exprs.get();
00487   SourceLocation TyBeginLoc = TypeRange.getBegin();
00488   SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
00489 
00490   if (Ty->isDependentType() ||
00491       CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
00492     exprs.release();
00493 
00494     return Owned(CXXUnresolvedConstructExpr::Create(Context,
00495                                                     TypeRange.getBegin(), Ty,
00496                                                     LParenLoc,
00497                                                     Exprs, NumExprs,
00498                                                     RParenLoc));
00499   }
00500 
00501   if (Ty->isArrayType())
00502     return ExprError(Diag(TyBeginLoc,
00503                           diag::err_value_init_for_array_type) << FullRange);
00504   if (!Ty->isVoidType() &&
00505       RequireCompleteType(TyBeginLoc, Ty,
00506                           PDiag(diag::err_invalid_incomplete_type_use)
00507                             << FullRange))
00508     return ExprError();
00509   
00510   if (RequireNonAbstractType(TyBeginLoc, Ty,
00511                              diag::err_allocation_of_abstract_type))
00512     return ExprError();
00513 
00514 
00515   // C++ [expr.type.conv]p1:
00516   // If the expression list is a single expression, the type conversion
00517   // expression is equivalent (in definedness, and if defined in meaning) to the
00518   // corresponding cast expression.
00519   //
00520   if (NumExprs == 1) {
00521     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
00522     CXXBaseSpecifierArray BasePath;
00523     if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
00524                        /*FunctionalStyle=*/true))
00525       return ExprError();
00526 
00527     exprs.release();
00528 
00529     return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
00530                                                      TInfo, TyBeginLoc, Kind,
00531                                                      Exprs[0], BasePath,
00532                                                      RParenLoc));
00533   }
00534 
00535   if (const RecordType *RT = Ty->getAs<RecordType>()) {
00536     CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
00537 
00538     if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
00539         !Record->hasTrivialDestructor()) {
00540       InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
00541       InitializationKind Kind
00542         = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(), 
00543                                                       LParenLoc, RParenLoc)
00544                    : InitializationKind::CreateValue(TypeRange.getBegin(), 
00545                                                      LParenLoc, RParenLoc);
00546       InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
00547       OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
00548                                                 move(exprs));
00549 
00550       // FIXME: Improve AST representation?
00551       return move(Result);
00552     }
00553 
00554     // Fall through to value-initialize an object of class type that
00555     // doesn't have a user-declared default constructor.
00556   }
00557 
00558   // C++ [expr.type.conv]p1:
00559   // If the expression list specifies more than a single value, the type shall
00560   // be a class with a suitably declared constructor.
00561   //
00562   if (NumExprs > 1)
00563     return ExprError(Diag(CommaLocs[0],
00564                           diag::err_builtin_func_cast_more_than_one_arg)
00565       << FullRange);
00566 
00567   assert(NumExprs == 0 && "Expected 0 expressions");
00568   // C++ [expr.type.conv]p2:
00569   // The expression T(), where T is a simple-type-specifier for a non-array
00570   // complete object type or the (possibly cv-qualified) void type, creates an
00571   // rvalue of the specified type, which is value-initialized.
00572   //
00573   exprs.release();
00574   return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
00575 }
00576 
00577 
00578 /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
00579 /// @code new (memory) int[size][4] @endcode
00580 /// or
00581 /// @code ::new Foo(23, "hello") @endcode
00582 /// For the interpretation of this heap of arguments, consult the base version.
00583 Action::OwningExprResult
00584 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
00585                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
00586                   SourceLocation PlacementRParen, bool ParenTypeId,
00587                   Declarator &D, SourceLocation ConstructorLParen,
00588                   MultiExprArg ConstructorArgs,
00589                   SourceLocation ConstructorRParen) {
00590   Expr *ArraySize = 0;
00591   // If the specified type is an array, unwrap it and save the expression.
00592   if (D.getNumTypeObjects() > 0 &&
00593       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
00594     DeclaratorChunk &Chunk = D.getTypeObject(0);
00595     if (Chunk.Arr.hasStatic)
00596       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
00597         << D.getSourceRange());
00598     if (!Chunk.Arr.NumElts)
00599       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
00600         << D.getSourceRange());
00601 
00602     if (ParenTypeId) {
00603       // Can't have dynamic array size when the type-id is in parentheses.
00604       Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
00605       if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
00606           !NumElts->isIntegerConstantExpr(Context)) {
00607         Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
00608           << NumElts->getSourceRange();
00609         return ExprError();
00610       }
00611     }
00612 
00613     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
00614     D.DropFirstTypeObject();
00615   }
00616 
00617   // Every dimension shall be of constant size.
00618   if (ArraySize) {
00619     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
00620       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
00621         break;
00622 
00623       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
00624       if (Expr *NumElts = (Expr *)Array.NumElts) {
00625         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
00626             !NumElts->isIntegerConstantExpr(Context)) {
00627           Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
00628             << NumElts->getSourceRange();
00629           return ExprError();
00630         }
00631       }
00632     }
00633   }
00634 
00635   //FIXME: Store TypeSourceInfo in CXXNew expression.
00636   TypeSourceInfo *TInfo = 0;
00637   QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
00638   if (D.isInvalidType())
00639     return ExprError();
00640     
00641   return BuildCXXNew(StartLoc, UseGlobal,
00642                      PlacementLParen,
00643                      move(PlacementArgs),
00644                      PlacementRParen,
00645                      ParenTypeId,
00646                      AllocType,
00647                      D.getSourceRange().getBegin(),
00648                      D.getSourceRange(),
00649                      Owned(ArraySize),
00650                      ConstructorLParen,
00651                      move(ConstructorArgs),
00652                      ConstructorRParen);
00653 }
00654 
00655 Sema::OwningExprResult
00656 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
00657                   SourceLocation PlacementLParen,
00658                   MultiExprArg PlacementArgs,
00659                   SourceLocation PlacementRParen,
00660                   bool ParenTypeId,
00661                   QualType AllocType,
00662                   SourceLocation TypeLoc,
00663                   SourceRange TypeRange,
00664                   ExprArg ArraySizeE,
00665                   SourceLocation ConstructorLParen,
00666                   MultiExprArg ConstructorArgs,
00667                   SourceLocation ConstructorRParen) {
00668   if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
00669     return ExprError();
00670 
00671   QualType ResultType = Context.getPointerType(AllocType);
00672 
00673   // That every array dimension except the first is constant was already
00674   // checked by the type check above.
00675 
00676   // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
00677   //   or enumeration type with a non-negative value."
00678   Expr *ArraySize = (Expr *)ArraySizeE.get();
00679   if (ArraySize && !ArraySize->isTypeDependent()) {
00680     QualType SizeType = ArraySize->getType();
00681     if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
00682       return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
00683                             diag::err_array_size_not_integral)
00684         << SizeType << ArraySize->getSourceRange());
00685     // Let's see if this is a constant < 0. If so, we reject it out of hand.
00686     // We don't care about special rules, so we tell the machinery it's not
00687     // evaluated - it gives us a result in more cases.
00688     if (!ArraySize->isValueDependent()) {
00689       llvm::APSInt Value;
00690       if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
00691         if (Value < llvm::APSInt(
00692                         llvm::APInt::getNullValue(Value.getBitWidth()), 
00693                                  Value.isUnsigned()))
00694           return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
00695                            diag::err_typecheck_negative_array_size)
00696             << ArraySize->getSourceRange());
00697       }
00698     }
00699     
00700     ImpCastExprToType(ArraySize, Context.getSizeType(),
00701                       CastExpr::CK_IntegralCast);
00702   }
00703 
00704   FunctionDecl *OperatorNew = 0;
00705   FunctionDecl *OperatorDelete = 0;
00706   Expr **PlaceArgs = (Expr**)PlacementArgs.get();
00707   unsigned NumPlaceArgs = PlacementArgs.size();
00708   
00709   if (!AllocType->isDependentType() &&
00710       !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
00711       FindAllocationFunctions(StartLoc,
00712                               SourceRange(PlacementLParen, PlacementRParen),
00713                               UseGlobal, AllocType, ArraySize, PlaceArgs,
00714                               NumPlaceArgs, OperatorNew, OperatorDelete))
00715     return ExprError();
00716   llvm::SmallVector<Expr *, 8> AllPlaceArgs;
00717   if (OperatorNew) {
00718     // Add default arguments, if any.
00719     const FunctionProtoType *Proto = 
00720       OperatorNew->getType()->getAs<FunctionProtoType>();
00721     VariadicCallType CallType = 
00722       Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
00723     
00724     if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
00725                                Proto, 1, PlaceArgs, NumPlaceArgs, 
00726                                AllPlaceArgs, CallType))
00727       return ExprError();
00728     
00729     NumPlaceArgs = AllPlaceArgs.size();
00730     if (NumPlaceArgs > 0)
00731       PlaceArgs = &AllPlaceArgs[0];
00732   }
00733   
00734   bool Init = ConstructorLParen.isValid();
00735   // --- Choosing a constructor ---
00736   CXXConstructorDecl *Constructor = 0;
00737   Expr **ConsArgs = (Expr**)ConstructorArgs.get();
00738   unsigned NumConsArgs = ConstructorArgs.size();
00739   ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
00740 
00741   // Array 'new' can't have any initializers.
00742   if (NumConsArgs && ArraySize) {
00743     SourceRange InitRange(ConsArgs[0]->getLocStart(),
00744                           ConsArgs[NumConsArgs - 1]->getLocEnd());
00745     
00746     Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
00747     return ExprError();
00748   }
00749 
00750   if (!AllocType->isDependentType() &&
00751       !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
00752     // C++0x [expr.new]p15:
00753     //   A new-expression that creates an object of type T initializes that
00754     //   object as follows:
00755     InitializationKind Kind
00756     //     - If the new-initializer is omitted, the object is default-
00757     //       initialized (8.5); if no initialization is performed,
00758     //       the object has indeterminate value
00759       = !Init? InitializationKind::CreateDefault(TypeLoc)
00760     //     - Otherwise, the new-initializer is interpreted according to the 
00761     //       initialization rules of 8.5 for direct-initialization.
00762              : InitializationKind::CreateDirect(TypeLoc,
00763                                                 ConstructorLParen, 
00764                                                 ConstructorRParen);
00765     
00766     InitializedEntity Entity
00767       = InitializedEntity::InitializeNew(StartLoc, AllocType);
00768     InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
00769     OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 
00770                                                 move(ConstructorArgs));
00771     if (FullInit.isInvalid())
00772       return ExprError();
00773     
00774     // FullInit is our initializer; walk through it to determine if it's a 
00775     // constructor call, which CXXNewExpr handles directly.
00776     if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
00777       if (CXXBindTemporaryExpr *Binder
00778             = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
00779         FullInitExpr = Binder->getSubExpr();
00780       if (CXXConstructExpr *Construct
00781                     = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
00782         Constructor = Construct->getConstructor();
00783         for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
00784                                          AEnd = Construct->arg_end();
00785              A != AEnd; ++A)
00786           ConvertedConstructorArgs.push_back(A->Retain());
00787       } else {
00788         // Take the converted initializer.
00789         ConvertedConstructorArgs.push_back(FullInit.release());
00790       }
00791     } else {
00792       // No initialization required.
00793     }
00794     
00795     // Take the converted arguments and use them for the new expression.
00796     NumConsArgs = ConvertedConstructorArgs.size();
00797     ConsArgs = (Expr **)ConvertedConstructorArgs.take();
00798   }
00799   
00800   // Mark the new and delete operators as referenced.
00801   if (OperatorNew)
00802     MarkDeclarationReferenced(StartLoc, OperatorNew);
00803   if (OperatorDelete)
00804     MarkDeclarationReferenced(StartLoc, OperatorDelete);
00805 
00806   // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
00807   
00808   PlacementArgs.release();
00809   ConstructorArgs.release();
00810   ArraySizeE.release();
00811   return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
00812                                         PlaceArgs, NumPlaceArgs, ParenTypeId,
00813                                         ArraySize, Constructor, Init,
00814                                         ConsArgs, NumConsArgs, OperatorDelete,
00815                                         ResultType, StartLoc,
00816                                         Init ? ConstructorRParen :
00817                                                SourceLocation()));
00818 }
00819 
00820 /// CheckAllocatedType - Checks that a type is suitable as the allocated type
00821 /// in a new-expression.
00822 /// dimension off and stores the size expression in ArraySize.
00823 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
00824                               SourceRange R) {
00825   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
00826   //   abstract class type or array thereof.
00827   if (AllocType->isFunctionType())
00828     return Diag(Loc, diag::err_bad_new_type)
00829       << AllocType << 0 << R;
00830   else if (AllocType->isReferenceType())
00831     return Diag(Loc, diag::err_bad_new_type)
00832       << AllocType << 1 << R;
00833   else if (!AllocType->isDependentType() &&
00834            RequireCompleteType(Loc, AllocType,
00835                                PDiag(diag::err_new_incomplete_type)
00836                                  << R))
00837     return true;
00838   else if (RequireNonAbstractType(Loc, AllocType,
00839                                   diag::err_allocation_of_abstract_type))
00840     return true;
00841 
00842   return false;
00843 }
00844 
00845 /// \brief Determine whether the given function is a non-placement
00846 /// deallocation function.
00847 static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
00848   if (FD->isInvalidDecl())
00849     return false;
00850 
00851   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
00852     return Method->isUsualDeallocationFunction();
00853 
00854   return ((FD->getOverloadedOperator() == OO_Delete ||
00855            FD->getOverloadedOperator() == OO_Array_Delete) &&
00856           FD->getNumParams() == 1);
00857 }
00858 
00859 /// FindAllocationFunctions - Finds the overloads of operator new and delete
00860 /// that are appropriate for the allocation.
00861 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
00862                                    bool UseGlobal, QualType AllocType,
00863                                    bool IsArray, Expr **PlaceArgs,
00864                                    unsigned NumPlaceArgs,
00865                                    FunctionDecl *&OperatorNew,
00866                                    FunctionDecl *&OperatorDelete) {
00867   // --- Choosing an allocation function ---
00868   // C++ 5.3.4p8 - 14 & 18
00869   // 1) If UseGlobal is true, only look in the global scope. Else, also look
00870   //   in the scope of the allocated class.
00871   // 2) If an array size is given, look for operator new[], else look for
00872   //   operator new.
00873   // 3) The first argument is always size_t. Append the arguments from the
00874   //   placement form.
00875 
00876   llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
00877   // We don't care about the actual value of this argument.
00878   // FIXME: Should the Sema create the expression and embed it in the syntax
00879   // tree? Or should the consumer just recalculate the value?
00880   IntegerLiteral Size(llvm::APInt::getNullValue(
00881                       Context.Target.getPointerWidth(0)),
00882                       Context.getSizeType(),
00883                       SourceLocation());
00884   AllocArgs[0] = &Size;
00885   std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
00886 
00887   // C++ [expr.new]p8:
00888   //   If the allocated type is a non-array type, the allocation
00889   //   function’s name is operator new and the deallocation function’s
00890   //   name is operator delete. If the allocated type is an array
00891   //   type, the allocation function’s name is operator new[] and the
00892   //   deallocation function’s name is operator delete[].
00893   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
00894                                         IsArray ? OO_Array_New : OO_New);
00895   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
00896                                         IsArray ? OO_Array_Delete : OO_Delete);
00897 
00898   if (AllocType->isRecordType() && !UseGlobal) {
00899     CXXRecordDecl *Record
00900       = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
00901     if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
00902                           AllocArgs.size(), Record, /*AllowMissing=*/true,
00903                           OperatorNew))
00904       return true;
00905   }
00906   if (!OperatorNew) {
00907     // Didn't find a member overload. Look for a global one.
00908     DeclareGlobalNewDelete();
00909     DeclContext *TUDecl = Context.getTranslationUnitDecl();
00910     if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
00911                           AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
00912                           OperatorNew))
00913       return true;
00914   }
00915 
00916   // We don't need an operator delete if we're running under
00917   // -fno-exceptions.
00918   if (!getLangOptions().Exceptions) {
00919     OperatorDelete = 0;
00920     return false;
00921   }
00922 
00923   // FindAllocationOverload can change the passed in arguments, so we need to
00924   // copy them back.
00925   if (NumPlaceArgs > 0)
00926     std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
00927 
00928   // C++ [expr.new]p19:
00929   //
00930   //   If the new-expression begins with a unary :: operator, the
00931   //   deallocation function’s name is looked up in the global
00932   //   scope. Otherwise, if the allocated type is a class type T or an
00933   //   array thereof, the deallocation function’s name is looked up in
00934   //   the scope of T. If this lookup fails to find the name, or if
00935   //   the allocated type is not a class type or array thereof, the
00936   //   deallocation function’s name is looked up in the global scope.
00937   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
00938   if (AllocType->isRecordType() && !UseGlobal) {
00939     CXXRecordDecl *RD
00940       = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
00941     LookupQualifiedName(FoundDelete, RD);
00942   }
00943   if (FoundDelete.isAmbiguous())
00944     return true; // FIXME: clean up expressions?
00945 
00946   if (FoundDelete.empty()) {
00947     DeclareGlobalNewDelete();
00948     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
00949   }
00950 
00951   FoundDelete.suppressDiagnostics();
00952 
00953   llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
00954 
00955   if (NumPlaceArgs > 0) {
00956     // C++ [expr.new]p20:
00957     //   A declaration of a placement deallocation function matches the
00958     //   declaration of a placement allocation function if it has the
00959     //   same number of parameters and, after parameter transformations
00960     //   (8.3.5), all parameter types except the first are
00961     //   identical. [...]
00962     // 
00963     // To perform this comparison, we compute the function type that
00964     // the deallocation function should have, and use that type both
00965     // for template argument deduction and for comparison purposes.
00966     QualType ExpectedFunctionType;
00967     {
00968       const FunctionProtoType *Proto
00969         = OperatorNew->getType()->getAs<FunctionProtoType>();
00970       llvm::SmallVector<QualType, 4> ArgTypes;
00971       ArgTypes.push_back(Context.VoidPtrTy); 
00972       for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
00973         ArgTypes.push_back(Proto->getArgType(I));
00974 
00975       ExpectedFunctionType
00976         = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
00977                                   ArgTypes.size(),
00978                                   Proto->isVariadic(),
00979                                   0, false, false, 0, 0,
00980                                   FunctionType::ExtInfo());
00981     }
00982 
00983     for (LookupResult::iterator D = FoundDelete.begin(), 
00984                              DEnd = FoundDelete.end();
00985          D != DEnd; ++D) {
00986       FunctionDecl *Fn = 0;
00987       if (FunctionTemplateDecl *FnTmpl 
00988             = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
00989         // Perform template argument deduction to try to match the
00990         // expected function type.
00991         TemplateDeductionInfo Info(Context, StartLoc);
00992         if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
00993           continue;
00994       } else
00995         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
00996 
00997       if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
00998         Matches.push_back(std::make_pair(D.getPair(), Fn));
00999     }
01000   } else {
01001     // C++ [expr.new]p20:
01002     //   [...] Any non-placement deallocation function matches a
01003     //   non-placement allocation function. [...]
01004     for (LookupResult::iterator D = FoundDelete.begin(), 
01005                              DEnd = FoundDelete.end();
01006          D != DEnd; ++D) {
01007       if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
01008         if (isNonPlacementDeallocationFunction(Fn))
01009           Matches.push_back(std::make_pair(D.getPair(), Fn));
01010     }
01011   }
01012 
01013   // C++ [expr.new]p20:
01014   //   [...] If the lookup finds a single matching deallocation
01015   //   function, that function will be called; otherwise, no
01016   //   deallocation function will be called.
01017   if (Matches.size() == 1) {
01018     OperatorDelete = Matches[0].second;
01019 
01020     // C++0x [expr.new]p20:
01021     //   If the lookup finds the two-parameter form of a usual
01022     //   deallocation function (3.7.4.2) and that function, considered
01023     //   as a placement deallocation function, would have been
01024     //   selected as a match for the allocation function, the program
01025     //   is ill-formed.
01026     if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
01027         isNonPlacementDeallocationFunction(OperatorDelete)) {
01028       Diag(StartLoc, diag::err_placement_new_non_placement_delete)
01029         << SourceRange(PlaceArgs[0]->getLocStart(), 
01030                        PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
01031       Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
01032         << DeleteName;
01033     } else {
01034       CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
01035                             Matches[0].first);
01036     }
01037   }
01038 
01039   return false;
01040 }
01041 
01042 /// FindAllocationOverload - Find an fitting overload for the allocation
01043 /// function in the specified scope.
01044 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
01045                                   DeclarationName Name, Expr** Args,
01046                                   unsigned NumArgs, DeclContext *Ctx,
01047                                   bool AllowMissing, FunctionDecl *&Operator) {
01048   LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
01049   LookupQualifiedName(R, Ctx);
01050   if (R.empty()) {
01051     if (AllowMissing)
01052       return false;
01053     return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
01054       << Name << Range;
01055   }
01056 
01057   if (R.isAmbiguous())
01058     return true;
01059 
01060   R.suppressDiagnostics();
01061 
01062   OverloadCandidateSet Candidates(StartLoc);
01063   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 
01064        Alloc != AllocEnd; ++Alloc) {
01065     // Even member operator new/delete are implicitly treated as
01066     // static, so don't use AddMemberCandidate.
01067     NamedDecl *D = (*Alloc)->getUnderlyingDecl();
01068 
01069     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
01070       AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
01071                                    /*ExplicitTemplateArgs=*/0, Args, NumArgs,
01072                                    Candidates,
01073                                    /*SuppressUserConversions=*/false);
01074       continue;
01075     }
01076 
01077     FunctionDecl *Fn = cast<FunctionDecl>(D);
01078     AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
01079                          /*SuppressUserConversions=*/false);
01080   }
01081 
01082   // Do the resolution.
01083   OverloadCandidateSet::iterator Best;
01084   switch(BestViableFunction(Candidates, StartLoc, Best)) {
01085   case OR_Success: {
01086     // Got one!
01087     FunctionDecl *FnDecl = Best->Function;
01088     // The first argument is size_t, and the first parameter must be size_t,
01089     // too. This is checked on declaration and can be assumed. (It can't be
01090     // asserted on, though, since invalid decls are left in there.)
01091     // Watch out for variadic allocator function.
01092     unsigned NumArgsInFnDecl = FnDecl->getNumParams();
01093     for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
01094       OwningExprResult Result
01095         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
01096                                                        FnDecl->getParamDecl(i)),
01097                                     SourceLocation(),
01098                                     Owned(Args[i]->Retain()));
01099       if (Result.isInvalid())
01100         return true;
01101       
01102       Args[i] = Result.takeAs<Expr>();
01103     }
01104     Operator = FnDecl;
01105     CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
01106     return false;
01107   }
01108 
01109   case OR_No_Viable_Function:
01110     Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
01111       << Name << Range;
01112     PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
01113     return true;
01114 
01115   case OR_Ambiguous:
01116     Diag(StartLoc, diag::err_ovl_ambiguous_call)
01117       << Name << Range;
01118     PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
01119     return true;
01120 
01121   case OR_Deleted:
01122     Diag(StartLoc, diag::err_ovl_deleted_call)
01123       << Best->Function->isDeleted()
01124       << Name << Range;
01125     PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
01126     return true;
01127   }
01128   assert(false && "Unreachable, bad result from BestViableFunction");
01129   return true;
01130 }
01131 
01132 
01133 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
01134 /// delete. These are:
01135 /// @code
01136 ///   void* operator new(std::size_t) throw(std::bad_alloc);
01137 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
01138 ///   void operator delete(void *) throw();
01139 ///   void operator delete[](void *) throw();
01140 /// @endcode
01141 /// Note that the placement and nothrow forms of new are *not* implicitly
01142 /// declared. Their use requires including <new>.
01143 void Sema::DeclareGlobalNewDelete() {
01144   if (GlobalNewDeleteDeclared)
01145     return;
01146   
01147   // C++ [basic.std.dynamic]p2:
01148   //   [...] The following allocation and deallocation functions (18.4) are 
01149   //   implicitly declared in global scope in each translation unit of a 
01150   //   program
01151   //   
01152   //     void* operator new(std::size_t) throw(std::bad_alloc);
01153   //     void* operator new[](std::size_t) throw(std::bad_alloc); 
01154   //     void  operator delete(void*) throw(); 
01155   //     void  operator delete[](void*) throw();
01156   //
01157   //   These implicit declarations introduce only the function names operator 
01158   //   new, operator new[], operator delete, operator delete[].
01159   //
01160   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
01161   // "std" or "bad_alloc" as necessary to form the exception specification.
01162   // However, we do not make these implicit declarations visible to name
01163   // lookup.
01164   if (!StdNamespace) {
01165     // The "std" namespace has not yet been defined, so build one implicitly.
01166     StdNamespace = NamespaceDecl::Create(Context, 
01167                                          Context.getTranslationUnitDecl(),
01168                                          SourceLocation(),
01169                                          &PP.getIdentifierTable().get("std"));
01170     StdNamespace->setImplicit(true);
01171   }
01172   
01173   if (!StdBadAlloc) {
01174     // The "std::bad_alloc" class has not yet been declared, so build it
01175     // implicitly.
01176     StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class, 
01177                                         StdNamespace, 
01178                                         SourceLocation(), 
01179                                       &PP.getIdentifierTable().get("bad_alloc"), 
01180                                         SourceLocation(), 0);
01181     StdBadAlloc->setImplicit(true);
01182   }
01183   
01184   GlobalNewDeleteDeclared = true;
01185 
01186   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
01187   QualType SizeT = Context.getSizeType();
01188   bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
01189 
01190   DeclareGlobalAllocationFunction(
01191       Context.DeclarationNames.getCXXOperatorName(OO_New),
01192       VoidPtr, SizeT, AssumeSaneOperatorNew);
01193   DeclareGlobalAllocationFunction(
01194       Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
01195       VoidPtr, SizeT, AssumeSaneOperatorNew);
01196   DeclareGlobalAllocationFunction(
01197       Context.DeclarationNames.getCXXOperatorName(OO_Delete),
01198       Context.VoidTy, VoidPtr);
01199   DeclareGlobalAllocationFunction(
01200       Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
01201       Context.VoidTy, VoidPtr);
01202 }
01203 
01204 /// DeclareGlobalAllocationFunction - Declares a single implicit global
01205 /// allocation function if it doesn't already exist.
01206 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
01207                                            QualType Return, QualType Argument,
01208                                            bool AddMallocAttr) {
01209   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
01210 
01211   // Check if this function is already declared.
01212   {
01213     DeclContext::lookup_iterator Alloc, AllocEnd;
01214     for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
01215          Alloc != AllocEnd; ++Alloc) {
01216       // Only look at non-template functions, as it is the predefined,
01217       // non-templated allocation function we are trying to declare here.
01218       if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
01219         QualType InitialParamType =
01220           Context.getCanonicalType(
01221             Func->getParamDecl(0)->getType().getUnqualifiedType());
01222         // FIXME: Do we need to check for default arguments here?
01223         if (Func->getNumParams() == 1 && InitialParamType == Argument)
01224           return;
01225       }
01226     }
01227   }
01228 
01229   QualType BadAllocType;
01230   bool HasBadAllocExceptionSpec 
01231     = (Name.getCXXOverloadedOperator() == OO_New ||
01232        Name.getCXXOverloadedOperator() == OO_Array_New);
01233   if (HasBadAllocExceptionSpec) {
01234     assert(StdBadAlloc && "Must have std::bad_alloc declared");
01235     BadAllocType = Context.getTypeDeclType(StdBadAlloc);
01236   }
01237   
01238   QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
01239                                             true, false,
01240                                             HasBadAllocExceptionSpec? 1 : 0,
01241                                             &BadAllocType,
01242                                             FunctionType::ExtInfo());
01243   FunctionDecl *Alloc =
01244     FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
01245                          FnType, /*TInfo=*/0, FunctionDecl::None,
01246                          FunctionDecl::None, false, true);
01247   Alloc->setImplicit();
01248   
01249   if (AddMallocAttr)
01250     Alloc->addAttr(::new (Context) MallocAttr());
01251   
01252   ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
01253                                            0, Argument, /*TInfo=*/0,
01254                                            VarDecl::None,
01255                                            VarDecl::None, 0);
01256   Alloc->setParams(&Param, 1);
01257 
01258   // FIXME: Also add this declaration to the IdentifierResolver, but
01259   // make sure it is at the end of the chain to coincide with the
01260   // global scope.
01261   ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
01262 }
01263 
01264 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
01265                                     DeclarationName Name,
01266                                     FunctionDecl* &Operator) {
01267   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
01268   // Try to find operator delete/operator delete[] in class scope.
01269   LookupQualifiedName(Found, RD);
01270   
01271   if (Found.isAmbiguous())
01272     return true;
01273 
01274   for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
01275        F != FEnd; ++F) {
01276     if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
01277       if (Delete->isUsualDeallocationFunction()) {
01278         Operator = Delete;
01279         return false;
01280       }
01281   }
01282 
01283   // We did find operator delete/operator delete[] declarations, but
01284   // none of them were suitable.
01285   if (!Found.empty()) {
01286     Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
01287       << Name << RD;
01288         
01289     for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
01290          F != FEnd; ++F) {
01291       Diag((*F)->getLocation(), diag::note_member_declared_here)
01292         << Name;
01293     }
01294 
01295     return true;
01296   }
01297 
01298   // Look for a global declaration.
01299   DeclareGlobalNewDelete();
01300   DeclContext *TUDecl = Context.getTranslationUnitDecl();
01301   
01302   CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
01303   Expr* DeallocArgs[1];
01304   DeallocArgs[0] = &Null;
01305   if (FindAllocationOverload(StartLoc, SourceRange(), Name,
01306                              DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
01307                              Operator))
01308     return true;
01309 
01310   assert(Operator && "Did not find a deallocation function!");
01311   return false;
01312 }
01313 
01314 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
01315 /// @code ::delete ptr; @endcode
01316 /// or
01317 /// @code delete [] ptr; @endcode
01318 Action::OwningExprResult
01319 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
01320                      bool ArrayForm, ExprArg Operand) {
01321   // C++ [expr.delete]p1:
01322   //   The operand shall have a pointer type, or a class type having a single
01323   //   conversion function to a pointer type. The result has type void.
01324   //
01325   // DR599 amends "pointer type" to "pointer to object type" in both cases.
01326 
01327   FunctionDecl *OperatorDelete = 0;
01328 
01329   Expr *Ex = (Expr *)Operand.get();
01330   if (!Ex->isTypeDependent()) {
01331     QualType Type = Ex->getType();
01332 
01333     if (const RecordType *Record = Type->getAs<RecordType>()) {
01334       llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
01335 
01336       CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
01337       const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();      
01338       for (UnresolvedSetImpl::iterator I = Conversions->begin(),
01339              E = Conversions->end(); I != E; ++I) {
01340         NamedDecl *D = I.getDecl();
01341         if (isa<UsingShadowDecl>(D))
01342           D = cast<UsingShadowDecl>(D)->getTargetDecl();
01343 
01344         // Skip over templated conversion functions; they aren't considered.
01345         if (isa<FunctionTemplateDecl>(D))
01346           continue;
01347         
01348         CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
01349         
01350         QualType ConvType = Conv->getConversionType().getNonReferenceType();
01351         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
01352           if (ConvPtrType->getPointeeType()->isObjectType())
01353             ObjectPtrConversions.push_back(Conv);
01354       }
01355       if (ObjectPtrConversions.size() == 1) {
01356         // We have a single conversion to a pointer-to-object type. Perform
01357         // that conversion.
01358         // TODO: don't redo the conversion calculation.
01359         Operand.release();
01360         if (!PerformImplicitConversion(Ex,
01361                             ObjectPtrConversions.front()->getConversionType(),
01362                                       AA_Converting)) {
01363           Operand = Owned(Ex);
01364           Type = Ex->getType();
01365         }
01366       }
01367       else if (ObjectPtrConversions.size() > 1) {
01368         Diag(StartLoc, diag::err_ambiguous_delete_operand)
01369               << Type << Ex->getSourceRange();
01370         for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
01371           NoteOverloadCandidate(ObjectPtrConversions[i]);
01372         return ExprError();
01373       }
01374     }
01375 
01376     if (!Type->isPointerType())
01377       return ExprError(Diag(StartLoc, diag::err_delete_operand)
01378         << Type << Ex->getSourceRange());
01379 
01380     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
01381     if (Pointee->isFunctionType() || Pointee->isVoidType())
01382       return ExprError(Diag(StartLoc, diag::err_delete_operand)
01383         << Type << Ex->getSourceRange());
01384     else if (!Pointee->isDependentType() &&
01385              RequireCompleteType(StartLoc, Pointee,
01386                                  PDiag(diag::warn_delete_incomplete)
01387                                    << Ex->getSourceRange()))
01388       return ExprError();
01389 
01390     // C++ [expr.delete]p2:
01391     //   [Note: a pointer to a const type can be the operand of a 
01392     //   delete-expression; it is not necessary to cast away the constness 
01393     //   (5.2.11) of the pointer expression before it is used as the operand 
01394     //   of the delete-expression. ]
01395     ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), 
01396                       CastExpr::CK_NoOp);
01397     
01398     // Update the operand.
01399     Operand.take();
01400     Operand = ExprArg(*this, Ex);
01401     
01402     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
01403                                       ArrayForm ? OO_Array_Delete : OO_Delete);
01404 
01405     if (const RecordType *RT = Pointee->getAs<RecordType>()) {
01406       CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
01407 
01408       if (!UseGlobal && 
01409           FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
01410         return ExprError();
01411       
01412       if (!RD->hasTrivialDestructor())
01413         if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
01414           MarkDeclarationReferenced(StartLoc,
01415                                     const_cast<CXXDestructorDecl*>(Dtor));
01416     }
01417     
01418     if (!OperatorDelete) {
01419       // Look for a global declaration.
01420       DeclareGlobalNewDelete();
01421       DeclContext *TUDecl = Context.getTranslationUnitDecl();
01422       if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
01423                                  &Ex, 1, TUDecl, /*AllowMissing=*/false,
01424                                  OperatorDelete))
01425         return ExprError();
01426     }
01427 
01428     MarkDeclarationReferenced(StartLoc, OperatorDelete);
01429 
01430     // FIXME: Check access and ambiguity of operator delete and destructor.
01431   }
01432 
01433   Operand.release();
01434   return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
01435                                            OperatorDelete, Ex, StartLoc));
01436 }
01437 
01438 /// \brief Check the use of the given variable as a C++ condition in an if,
01439 /// while, do-while, or switch statement.
01440 Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
01441   QualType T = ConditionVar->getType();
01442   
01443   // C++ [stmt.select]p2:
01444   //   The declarator shall not specify a function or an array.
01445   if (T->isFunctionType())
01446     return ExprError(Diag(ConditionVar->getLocation(), 
01447                           diag::err_invalid_use_of_function_type)
01448                        << ConditionVar->getSourceRange());
01449   else if (T->isArrayType())
01450     return ExprError(Diag(ConditionVar->getLocation(), 
01451                           diag::err_invalid_use_of_array_type)
01452                      << ConditionVar->getSourceRange());
01453 
01454   return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
01455                                    ConditionVar->getLocation(), 
01456                                 ConditionVar->getType().getNonReferenceType()));
01457 }
01458 
01459 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
01460 bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
01461   // C++ 6.4p4:
01462   // The value of a condition that is an initialized declaration in a statement
01463   // other than a switch statement is the value of the declared variable
01464   // implicitly converted to type bool. If that conversion is ill-formed, the
01465   // program is ill-formed.
01466   // The value of a condition that is an expression is the value of the
01467   // expression, implicitly converted to bool.
01468   //
01469   return PerformContextuallyConvertToBool(CondExpr);
01470 }
01471 
01472 /// Helper function to determine whether this is the (deprecated) C++
01473 /// conversion from a string literal to a pointer to non-const char or
01474 /// non-const wchar_t (for narrow and wide string literals,
01475 /// respectively).
01476 bool
01477 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
01478   // Look inside the implicit cast, if it exists.
01479   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
01480     From = Cast->getSubExpr();
01481 
01482   // A string literal (2.13.4) that is not a wide string literal can
01483   // be converted to an rvalue of type "pointer to char"; a wide
01484   // string literal can be converted to an rvalue of type "pointer
01485   // to wchar_t" (C++ 4.2p2).
01486   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
01487     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
01488       if (const BuiltinType *ToPointeeType
01489           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
01490         // This conversion is considered only when there is an
01491         // explicit appropriate pointer target type (C++ 4.2p2).
01492         if (!ToPtrType->getPointeeType().hasQualifiers() &&
01493             ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
01494              (!StrLit->isWide() &&
01495               (ToPointeeType->getKind() == BuiltinType::Char_U ||
01496                ToPointeeType->getKind() == BuiltinType::Char_S))))
01497           return true;
01498       }
01499 
01500   return false;
01501 }
01502 
01503 static Sema::OwningExprResult BuildCXXCastArgument(Sema &S, 
01504                                                    SourceLocation CastLoc,
01505                                                    QualType Ty,
01506                                                    CastExpr::CastKind Kind,
01507                                                    CXXMethodDecl *Method,
01508                                                    Sema::ExprArg Arg) {
01509   Expr *From = Arg.takeAs<Expr>();
01510   
01511   switch (Kind) {
01512   default: assert(0 && "Unhandled cast kind!");
01513   case CastExpr::CK_ConstructorConversion: {
01514     ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
01515     
01516     if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
01517                                   Sema::MultiExprArg(S, (void **)&From, 1),
01518                                   CastLoc, ConstructorArgs))
01519       return S.ExprError();
01520     
01521     Sema::OwningExprResult Result = 
01522     S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 
01523                             move_arg(ConstructorArgs));
01524     if (Result.isInvalid())
01525       return S.ExprError();
01526     
01527     return S.MaybeBindToTemporary(Result.takeAs<Expr>());
01528   }
01529     
01530   case CastExpr::CK_UserDefinedConversion: {
01531     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
01532     
01533     // Create an implicit call expr that calls it.
01534     // FIXME: pass the FoundDecl for the user-defined conversion here
01535     CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
01536     return S.MaybeBindToTemporary(CE);
01537   }
01538   }
01539 }    
01540 
01541 /// PerformImplicitConversion - Perform an implicit conversion of the
01542 /// expression From to the type ToType using the pre-computed implicit
01543 /// conversion sequence ICS. Returns true if there was an error, false
01544 /// otherwise. The expression From is replaced with the converted
01545 /// expression. Action is the kind of conversion we're performing,
01546 /// used in the error message.
01547 bool
01548 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
01549                                 const ImplicitConversionSequence &ICS,
01550                                 AssignmentAction Action, bool IgnoreBaseAccess) {
01551   switch (ICS.getKind()) {
01552   case ImplicitConversionSequence::StandardConversion:
01553     if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
01554                                   IgnoreBaseAccess))
01555       return true;
01556     break;
01557 
01558   case ImplicitConversionSequence::UserDefinedConversion: {
01559     
01560       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
01561       CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
01562       QualType BeforeToType;
01563       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
01564         CastKind = CastExpr::CK_UserDefinedConversion;
01565         
01566         // If the user-defined conversion is specified by a conversion function,
01567         // the initial standard conversion sequence converts the source type to
01568         // the implicit object parameter of the conversion function.
01569         BeforeToType = Context.getTagDeclType(Conv->getParent());
01570       } else if (const CXXConstructorDecl *Ctor = 
01571                   dyn_cast<CXXConstructorDecl>(FD)) {
01572         CastKind = CastExpr::CK_ConstructorConversion;
01573         // Do no conversion if dealing with ... for the first conversion.
01574         if (!ICS.UserDefined.EllipsisConversion) {
01575           // If the user-defined conversion is specified by a constructor, the 
01576           // initial standard conversion sequence converts the source type to the
01577           // type required by the argument of the constructor
01578           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
01579         }
01580       }    
01581       else
01582         assert(0 && "Unknown conversion function kind!");
01583       // Whatch out for elipsis conversion.
01584       if (!ICS.UserDefined.EllipsisConversion) {
01585         if (PerformImplicitConversion(From, BeforeToType, 
01586                                       ICS.UserDefined.Before, AA_Converting,
01587                                       IgnoreBaseAccess))
01588           return true;
01589       }
01590     
01591       OwningExprResult CastArg 
01592         = BuildCXXCastArgument(*this,
01593                                From->getLocStart(),
01594                                ToType.getNonReferenceType(),
01595                                CastKind, cast<CXXMethodDecl>(FD), 
01596                                Owned(From));
01597 
01598       if (CastArg.isInvalid())
01599         return true;
01600 
01601       From = CastArg.takeAs<Expr>();
01602 
01603       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
01604                                        AA_Converting, IgnoreBaseAccess);
01605   }
01606 
01607   case ImplicitConversionSequence::AmbiguousConversion:
01608     DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
01609                           PDiag(diag::err_typecheck_ambiguous_condition)
01610                             << From->getSourceRange());
01611      return true;
01612       
01613   case ImplicitConversionSequence::EllipsisConversion:
01614     assert(false && "Cannot perform an ellipsis conversion");
01615     return false;
01616 
01617   case ImplicitConversionSequence::BadConversion:
01618     return true;
01619   }
01620 
01621   // Everything went well.
01622   return false;
01623 }
01624 
01625 /// PerformImplicitConversion - Perform an implicit conversion of the
01626 /// expression From to the type ToType by following the standard
01627 /// conversion sequence SCS. Returns true if there was an error, false
01628 /// otherwise. The expression From is replaced with the converted
01629 /// expression. Flavor is the context in which we're performing this
01630 /// conversion, for use in error messages.
01631 bool
01632 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
01633                                 const StandardConversionSequence& SCS,
01634                                 AssignmentAction Action, bool IgnoreBaseAccess) {
01635   // Overall FIXME: we are recomputing too many types here and doing far too
01636   // much extra work. What this means is that we need to keep track of more
01637   // information that is computed when we try the implicit conversion initially,
01638   // so that we don't need to recompute anything here.
01639   QualType FromType = From->getType();
01640 
01641   if (SCS.CopyConstructor) {
01642     // FIXME: When can ToType be a reference type?
01643     assert(!ToType->isReferenceType());
01644     if (SCS.Second == ICK_Derived_To_Base) {
01645       ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
01646       if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
01647                                   MultiExprArg(*this, (void **)&From, 1),
01648                                   /*FIXME:ConstructLoc*/SourceLocation(), 
01649                                   ConstructorArgs))
01650         return true;
01651       OwningExprResult FromResult =
01652         BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
01653                               ToType, SCS.CopyConstructor,
01654                               move_arg(ConstructorArgs));
01655       if (FromResult.isInvalid())
01656         return true;
01657       From = FromResult.takeAs<Expr>();
01658       return false;
01659     }
01660     OwningExprResult FromResult =
01661       BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
01662                             ToType, SCS.CopyConstructor,
01663                             MultiExprArg(*this, (void**)&From, 1));
01664 
01665     if (FromResult.isInvalid())
01666       return true;
01667 
01668     From = FromResult.takeAs<Expr>();
01669     return false;
01670   }
01671 
01672   // Resolve overloaded function references.
01673   if (Context.hasSameType(FromType, Context.OverloadTy)) {
01674     DeclAccessPair Found;
01675     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
01676                                                           true, Found);
01677     if (!Fn)
01678       return true;
01679 
01680     if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
01681       return true;
01682 
01683     From = FixOverloadedFunctionReference(From, Found, Fn);
01684     FromType = From->getType();
01685   }
01686 
01687   // Perform the first implicit conversion.
01688   switch (SCS.First) {
01689   case ICK_Identity:
01690   case ICK_Lvalue_To_Rvalue:
01691     // Nothing to do.
01692     break;
01693 
01694   case ICK_Array_To_Pointer:
01695     FromType = Context.getArrayDecayedType(FromType);
01696     ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
01697     break;
01698 
01699   case ICK_Function_To_Pointer:
01700     FromType = Context.getPointerType(FromType);
01701     ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
01702     break;
01703 
01704   default:
01705     assert(false && "Improper first standard conversion");
01706     break;
01707   }
01708 
01709   // Perform the second implicit conversion
01710   switch (SCS.Second) {
01711   case ICK_Identity:
01712     // If both sides are functions (or pointers/references to them), there could
01713     // be incompatible exception declarations.
01714     if (CheckExceptionSpecCompatibility(From, ToType))
01715       return true;
01716     // Nothing else to do.
01717     break;
01718 
01719   case ICK_NoReturn_Adjustment:
01720     // If both sides are functions (or pointers/references to them), there could
01721     // be incompatible exception declarations.
01722     if (CheckExceptionSpecCompatibility(From, ToType))
01723       return true;      
01724       
01725     ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
01726                       CastExpr::CK_NoOp);
01727     break;
01728       
01729   case ICK_Integral_Promotion:
01730   case ICK_Integral_Conversion:
01731     ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
01732     break;
01733 
01734   case ICK_Floating_Promotion:
01735   case ICK_Floating_Conversion:
01736     ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
01737     break;
01738 
01739   case ICK_Complex_Promotion:
01740   case ICK_Complex_Conversion:
01741     ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
01742     break;
01743 
01744   case ICK_Floating_Integral:
01745     if (ToType->isFloatingType())
01746       ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
01747     else
01748       ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
01749     break;
01750 
01751   case ICK_Complex_Real:
01752     ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
01753     break;
01754 
01755   case ICK_Compatible_Conversion:
01756     ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
01757     break;
01758 
01759   case ICK_Pointer_Conversion: {
01760     if (SCS.IncompatibleObjC) {
01761       // Diagnose incompatible Objective-C conversions
01762       Diag(From->getSourceRange().getBegin(),
01763            diag::ext_typecheck_convert_incompatible_pointer)
01764         << From->getType() << ToType << Action
01765         << From->getSourceRange();
01766     }
01767 
01768     
01769     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
01770     CXXBaseSpecifierArray BasePath;
01771     if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
01772       return true;
01773     ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
01774     break;
01775   }
01776   
01777   case ICK_Pointer_Member: {
01778     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
01779     CXXBaseSpecifierArray BasePath;
01780     if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
01781                                      IgnoreBaseAccess))
01782       return true;
01783     if (CheckExceptionSpecCompatibility(From, ToType))
01784       return true;
01785     ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
01786     break;
01787   }
01788   case ICK_Boolean_Conversion: {
01789     CastExpr::CastKind Kind = CastExpr::CK_Unknown;
01790     if (FromType->isMemberPointerType())
01791       Kind = CastExpr::CK_MemberPointerToBoolean;
01792     
01793     ImpCastExprToType(From, Context.BoolTy, Kind);
01794     break;
01795   }
01796 
01797   case ICK_Derived_To_Base:
01798     if (CheckDerivedToBaseConversion(From->getType(), 
01799                                      ToType.getNonReferenceType(),
01800                                      From->getLocStart(),
01801                                      From->getSourceRange(), 0,
01802                                      IgnoreBaseAccess))
01803       return true;
01804     ImpCastExprToType(From, ToType.getNonReferenceType(), 
01805                       CastExpr::CK_DerivedToBase);
01806     break;
01807       
01808   default:
01809     assert(false && "Improper second standard conversion");
01810     break;
01811   }
01812 
01813   switch (SCS.Third) {
01814   case ICK_Identity:
01815     // Nothing to do.
01816     break;
01817 
01818   case ICK_Qualification:
01819     // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
01820     // references.
01821     ImpCastExprToType(From, ToType.getNonReferenceType(),
01822                       CastExpr::CK_NoOp, ToType->isLValueReferenceType());
01823 
01824     if (SCS.DeprecatedStringLiteralToCharPtr)
01825       Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
01826         << ToType.getNonReferenceType();
01827 
01828     break;
01829       
01830   default:
01831     assert(false && "Improper second standard conversion");
01832     break;
01833   }
01834 
01835   return false;
01836 }
01837 
01838 Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
01839                                                  SourceLocation KWLoc,
01840                                                  SourceLocation LParen,
01841                                                  TypeTy *Ty,
01842                                                  SourceLocation RParen) {
01843   QualType T = GetTypeFromParser(Ty);
01844 
01845   // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
01846   // all traits except __is_class, __is_enum and __is_union require a the type
01847   // to be complete.
01848   if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
01849     if (RequireCompleteType(KWLoc, T,
01850                             diag::err_incomplete_type_used_in_type_trait_expr))
01851       return ExprError();
01852   }
01853 
01854   // There is no point in eagerly computing the value. The traits are designed
01855   // to be used from type trait templates, so Ty will be a template parameter
01856   // 99% of the time.
01857   return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
01858                                                 RParen, Context.BoolTy));
01859 }
01860 
01861 QualType Sema::CheckPointerToMemberOperands(
01862   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
01863   const char *OpSpelling = isIndirect ? "->*" : ".*";
01864   // C++ 5.5p2
01865   //   The binary operator .* [p3: ->*] binds its second operand, which shall
01866   //   be of type "pointer to member of T" (where T is a completely-defined
01867   //   class type) [...]
01868   QualType RType = rex->getType();
01869   const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
01870   if (!MemPtr) {
01871     Diag(Loc, diag::err_bad_memptr_rhs)
01872       << OpSpelling << RType << rex->getSourceRange();
01873     return QualType();
01874   }
01875 
01876   QualType Class(MemPtr->getClass(), 0);
01877 
01878   if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
01879     return QualType();
01880 
01881   // C++ 5.5p2
01882   //   [...] to its first operand, which shall be of class T or of a class of
01883   //   which T is an unambiguous and accessible base class. [p3: a pointer to
01884   //   such a class]
01885   QualType LType = lex->getType();
01886   if (isIndirect) {
01887     if (const PointerType *Ptr = LType->getAs<PointerType>())
01888       LType = Ptr->getPointeeType().getNonReferenceType();
01889     else {
01890       Diag(Loc, diag::err_bad_memptr_lhs)
01891         << OpSpelling << 1 << LType
01892         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
01893       return QualType();
01894     }
01895   }
01896 
01897   if (!Context.hasSameUnqualifiedType(Class, LType)) {
01898     // If we want to check the hierarchy, we need a complete type.
01899     if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
01900         << OpSpelling << (int)isIndirect)) {
01901       return QualType();
01902     }
01903     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
01904                        /*DetectVirtual=*/false);
01905     // FIXME: Would it be useful to print full ambiguity paths, or is that
01906     // overkill?
01907     if (!IsDerivedFrom(LType, Class, Paths) ||
01908         Paths.isAmbiguous(Context.getCanonicalType(Class))) {
01909       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
01910         << (int)isIndirect << lex->getType();
01911       return QualType();
01912     }
01913     // Cast LHS to type of use.
01914     QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
01915     bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
01916     
01917     CXXBaseSpecifierArray BasePath;
01918     BuildBasePathArray(Paths, BasePath);
01919     ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
01920                       BasePath);
01921   }
01922 
01923   if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
01924     // Diagnose use of pointer-to-member type which when used as
01925     // the functional cast in a pointer-to-member expression.
01926     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
01927      return QualType();
01928   }
01929   // C++ 5.5p2
01930   //   The result is an object or a function of the type specified by the
01931   //   second operand.
01932   // The cv qualifiers are the union of those in the pointer and the left side,
01933   // in accordance with 5.5p5 and 5.2.5.
01934   // FIXME: This returns a dereferenced member function pointer as a normal
01935   // function type. However, the only operation valid on such functions is
01936   // calling them. There's also a GCC extension to get a function pointer to the
01937   // thing, which is another complication, because this type - unlike the type
01938   // that is the result of this expression - takes the class as the first
01939   // argument.
01940   // We probably need a "MemberFunctionClosureType" or something like that.
01941   QualType Result = MemPtr->getPointeeType();
01942   Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
01943   return Result;
01944 }
01945 
01946 /// \brief Try to convert a type to another according to C++0x 5.16p3.
01947 ///
01948 /// This is part of the parameter validation for the ? operator. If either
01949 /// value operand is a class type, the two operands are attempted to be
01950 /// converted to each other. This function does the conversion in one direction.
01951 /// It returns true if the program is ill-formed and has already been diagnosed
01952 /// as such.
01953 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
01954                                 SourceLocation QuestionLoc,
01955                                 bool &HaveConversion,
01956                                 QualType &ToType) {
01957   HaveConversion = false;
01958   ToType = To->getType();
01959   
01960   InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), 
01961                                                            SourceLocation());
01962   // C++0x 5.16p3
01963   //   The process for determining whether an operand expression E1 of type T1
01964   //   can be converted to match an operand expression E2 of type T2 is defined
01965   //   as follows:
01966   //   -- If E2 is an lvalue:
01967   bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
01968   if (ToIsLvalue) {
01969     //   E1 can be converted to match E2 if E1 can be implicitly converted to
01970     //   type "lvalue reference to T2", subject to the constraint that in the
01971     //   conversion the reference must bind directly to E1.
01972     QualType T = Self.Context.getLValueReferenceType(ToType);
01973     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
01974     
01975     InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
01976     if (InitSeq.isDirectReferenceBinding()) {
01977       ToType = T;
01978       HaveConversion = true;
01979       return false;
01980     }
01981     
01982     if (InitSeq.isAmbiguous())
01983       return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
01984   }
01985 
01986   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
01987   //      -- if E1 and E2 have class type, and the underlying class types are
01988   //         the same or one is a base class of the other:
01989   QualType FTy = From->getType();
01990   QualType TTy = To->getType();
01991   const RecordType *FRec = FTy->getAs<RecordType>();
01992   const RecordType *TRec = TTy->getAs<RecordType>();
01993   bool FDerivedFromT = FRec && TRec && FRec != TRec && 
01994                        Self.IsDerivedFrom(FTy, TTy);
01995   if (FRec && TRec && 
01996       (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
01997     //         E1 can be converted to match E2 if the class of T2 is the
01998     //         same type as, or a base class of, the class of T1, and
01999     //         [cv2 > cv1].
02000     if (FRec == TRec || FDerivedFromT) {
02001       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
02002         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
02003         InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
02004         if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
02005           HaveConversion = true;
02006           return false;
02007         }
02008         
02009         if (InitSeq.isAmbiguous())
02010           return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
02011       } 
02012     }
02013     
02014     return false;
02015   }
02016   
02017   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
02018   //        implicitly converted to the type that expression E2 would have
02019   //        if E2 were converted to an rvalue (or the type it has, if E2 is 
02020   //        an rvalue).
02021   //
02022   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
02023   // to the array-to-pointer or function-to-pointer conversions.
02024   if (!TTy->getAs<TagType>())
02025     TTy = TTy.getUnqualifiedType();
02026   
02027   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
02028   InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
02029   HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;  
02030   ToType = TTy;
02031   if (InitSeq.isAmbiguous())
02032     return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
02033 
02034   return false;
02035 }
02036 
02037 /// \brief Try to find a common type for two according to C++0x 5.16p5.
02038 ///
02039 /// This is part of the parameter validation for the ? operator. If either
02040 /// value operand is a class type, overload resolution is used to find a
02041 /// conversion to a common type.
02042 static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
02043                                     SourceLocation Loc) {
02044   Expr *Args[2] = { LHS, RHS };
02045   OverloadCandidateSet CandidateSet(Loc);
02046   Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
02047 
02048   OverloadCandidateSet::iterator Best;
02049   switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
02050     case OR_Success:
02051       // We found a match. Perform the conversions on the arguments and move on.
02052       if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
02053                                          Best->Conversions[0], Sema::AA_Converting) ||
02054           Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
02055                                          Best->Conversions[1], Sema::AA_Converting))
02056         break;
02057       return false;
02058 
02059     case OR_No_Viable_Function:
02060       Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
02061         << LHS->getType() << RHS->getType()
02062         << LHS->getSourceRange() << RHS->getSourceRange();
02063       return true;
02064 
02065     case OR_Ambiguous:
02066       Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
02067         << LHS->getType() << RHS->getType()
02068         << LHS->getSourceRange() << RHS->getSourceRange();
02069       // FIXME: Print the possible common types by printing the return types of
02070       // the viable candidates.
02071       break;
02072 
02073     case OR_Deleted:
02074       assert(false && "Conditional operator has only built-in overloads");
02075       break;
02076   }
02077   return true;
02078 }
02079 
02080 /// \brief Perform an "extended" implicit conversion as returned by
02081 /// TryClassUnification.
02082 static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
02083   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
02084   InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
02085                                                            SourceLocation());
02086   InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
02087   Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind, 
02088                                     Sema::MultiExprArg(Self, (void **)&E, 1));
02089   if (Result.isInvalid())
02090     return true;
02091   
02092   E = Result.takeAs<Expr>();
02093   return false;
02094 }
02095 
02096 /// \brief Check the operands of ?: under C++ semantics.
02097 ///
02098 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
02099 /// extension. In this case, LHS == Cond. (But they're not aliases.)
02100 QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
02101                                            SourceLocation QuestionLoc) {
02102   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
02103   // interface pointers.
02104 
02105   // C++0x 5.16p1
02106   //   The first expression is contextually converted to bool.
02107   if (!Cond->isTypeDependent()) {
02108     if (CheckCXXBooleanCondition(Cond))
02109       return QualType();
02110   }
02111 
02112   // Either of the arguments dependent?
02113   if (LHS->isTypeDependent() || RHS->isTypeDependent())
02114     return Context.DependentTy;
02115 
02116   CheckSignCompare(LHS, RHS, QuestionLoc);
02117 
02118   // C++0x 5.16p2
02119   //   If either the second or the third operand has type (cv) void, ...
02120   QualType LTy = LHS->getType();
02121   QualType RTy = RHS->getType();
02122   bool LVoid = LTy->isVoidType();
02123   bool RVoid = RTy->isVoidType();
02124   if (LVoid || RVoid) {
02125     //   ... then the [l2r] conversions are performed on the second and third
02126     //   operands ...
02127     DefaultFunctionArrayLvalueConversion(LHS);
02128     DefaultFunctionArrayLvalueConversion(RHS);
02129     LTy = LHS->getType();
02130     RTy = RHS->getType();
02131 
02132     //   ... and one of the following shall hold:
02133     //   -- The second or the third operand (but not both) is a throw-
02134     //      expression; the result is of the type of the other and is an rvalue.
02135     bool LThrow = isa<CXXThrowExpr>(LHS);
02136     bool RThrow = isa<CXXThrowExpr>(RHS);
02137     if (LThrow && !RThrow)
02138       return RTy;
02139     if (RThrow && !LThrow)
02140       return LTy;
02141 
02142     //   -- Both the second and third operands have type void; the result is of
02143     //      type void and is an rvalue.
02144     if (LVoid && RVoid)
02145       return Context.VoidTy;
02146 
02147     // Neither holds, error.
02148     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
02149       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
02150       << LHS->getSourceRange() << RHS->getSourceRange();
02151     return QualType();
02152   }
02153 
02154   // Neither is void.
02155 
02156   // C++0x 5.16p3
02157   //   Otherwise, if the second and third operand have different types, and
02158   //   either has (cv) class type, and attempt is made to convert each of those
02159   //   operands to the other.
02160   if (!Context.hasSameType(LTy, RTy) && 
02161       (LTy->isRecordType() || RTy->isRecordType())) {
02162     ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
02163     // These return true if a single direction is already ambiguous.
02164     QualType L2RType, R2LType;
02165     bool HaveL2R, HaveR2L;
02166     if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
02167       return QualType();
02168     if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
02169       return QualType();
02170     
02171     //   If both can be converted, [...] the program is ill-formed.
02172     if (HaveL2R && HaveR2L) {
02173       Diag(QuestionLoc, diag::err_conditional_ambiguous)
02174         << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
02175       return QualType();
02176     }
02177 
02178     //   If exactly one conversion is possible, that conversion is applied to
02179     //   the chosen operand and the converted operands are used in place of the
02180     //   original operands for the remainder of this section.
02181     if (HaveL2R) {
02182       if (ConvertForConditional(*this, LHS, L2RType))
02183         return QualType();
02184       LTy = LHS->getType();
02185     } else if (HaveR2L) {
02186       if (ConvertForConditional(*this, RHS, R2LType))
02187         return QualType();
02188       RTy = RHS->getType();
02189     }
02190   }
02191 
02192   // C++0x 5.16p4
02193   //   If the second and third operands are lvalues and have the same type,
02194   //   the result is of that type [...]
02195   bool Same = Context.hasSameType(LTy, RTy);
02196   if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
02197       RHS->isLvalue(Context) == Expr::LV_Valid)
02198     return LTy;
02199 
02200   // C++0x 5.16p5
02201   //   Otherwise, the result is an rvalue. If the second and third operands
02202   //   do not have the same type, and either has (cv) class type, ...
02203   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
02204     //   ... overload resolution is used to determine the conversions (if any)
02205     //   to be applied to the operands. If the overload resolution fails, the
02206     //   program is ill-formed.
02207     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
02208       return QualType();
02209   }
02210 
02211   // C++0x 5.16p6
02212   //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
02213   //   conversions are performed on the second and third operands.
02214   DefaultFunctionArrayLvalueConversion(LHS);
02215   DefaultFunctionArrayLvalueConversion(RHS);
02216   LTy = LHS->getType();
02217   RTy = RHS->getType();
02218 
02219   //   After those conversions, one of the following shall hold:
02220   //   -- The second and third operands have the same type; the result
02221   //      is of that type.
02222   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
02223     return LTy;
02224 
02225   //   -- The second and third operands have arithmetic or enumeration type;
02226   //      the usual arithmetic conversions are performed to bring them to a
02227   //      common type, and the result is of that type.
02228   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
02229     UsualArithmeticConversions(LHS, RHS);
02230     return LHS->getType();
02231   }
02232 
02233   //   -- The second and third operands have pointer type, or one has pointer
02234   //      type and the other is a null pointer constant; pointer conversions
02235   //      and qualification conversions are performed to bring them to their
02236   //      composite pointer type. The result is of the composite pointer type.
02237   //   -- The second and third operands have pointer to member type, or one has
02238   //      pointer to member type and the other is a null pointer constant;
02239   //      pointer to member conversions and qualification conversions are
02240   //      performed to bring them to a common type, whose cv-qualification
02241   //      shall match the cv-qualification of either the second or the third
02242   //      operand. The result is of the common type.
02243   bool NonStandardCompositeType = false;
02244   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
02245                               isSFINAEContext()? 0 : &NonStandardCompositeType);
02246   if (!Composite.isNull()) {
02247     if (NonStandardCompositeType)
02248       Diag(QuestionLoc, 
02249            diag::ext_typecheck_cond_incompatible_operands_nonstandard)
02250         << LTy << RTy << Composite
02251         << LHS->getSourceRange() << RHS->getSourceRange();
02252       
02253     return Composite;
02254   }
02255   
02256   // Similarly, attempt to find composite type of two objective-c pointers.
02257   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
02258   if (!Composite.isNull())
02259     return Composite;
02260 
02261   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
02262     << LHS->getType() << RHS->getType()
02263     << LHS->getSourceRange() << RHS->getSourceRange();
02264   return QualType();
02265 }
02266 
02267 /// \brief Find a merged pointer type and convert the two expressions to it.
02268 ///
02269 /// This finds the composite pointer type (or member pointer type) for @p E1
02270 /// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
02271 /// type and returns it.
02272 /// It does not emit diagnostics.
02273 ///
02274 /// \param Loc The location of the operator requiring these two expressions to
02275 /// be converted to the composite pointer type.
02276 ///
02277 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
02278 /// a non-standard (but still sane) composite type to which both expressions
02279 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
02280 /// will be set true.
02281 QualType Sema::FindCompositePointerType(SourceLocation Loc, 
02282                                         Expr *&E1, Expr *&E2,
02283                                         bool *NonStandardCompositeType) {
02284   if (NonStandardCompositeType)
02285     *NonStandardCompositeType = false;
02286   
02287   assert(getLangOptions().CPlusPlus && "This function assumes C++");
02288   QualType T1 = E1->getType(), T2 = E2->getType();
02289 
02290   if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
02291       !T2->isAnyPointerType() && !T2->isMemberPointerType())
02292    return QualType();
02293 
02294   // C++0x 5.9p2
02295   //   Pointer conversions and qualification conversions are performed on
02296   //   pointer operands to bring them to their composite pointer type. If
02297   //   one operand is a null pointer constant, the composite pointer type is
02298   //   the type of the other operand.
02299   if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
02300     if (T2->isMemberPointerType())
02301       ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
02302     else
02303       ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
02304     return T2;
02305   }
02306   if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
02307     if (T1->isMemberPointerType())
02308       ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
02309     else
02310       ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
02311     return T1;
02312   }
02313 
02314   // Now both have to be pointers or member pointers.
02315   if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
02316       (!T2->isPointerType() && !T2->isMemberPointerType()))
02317     return QualType();
02318 
02319   //   Otherwise, of one of the operands has type "pointer to cv1 void," then
02320   //   the other has type "pointer to cv2 T" and the composite pointer type is
02321   //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
02322   //   Otherwise, the composite pointer type is a pointer type similar to the
02323   //   type of one of the operands, with a cv-qualification signature that is
02324   //   the union of the cv-qualification signatures of the operand types.
02325   // In practice, the first part here is redundant; it's subsumed by the second.
02326   // What we do here is, we build the two possible composite types, and try the
02327   // conversions in both directions. If only one works, or if the two composite
02328   // types are the same, we have succeeded.
02329   // FIXME: extended qualifiers?
02330   typedef llvm::SmallVector<unsigned, 4> QualifierVector;
02331   QualifierVector QualifierUnion;
02332   typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
02333       ContainingClassVector;
02334   ContainingClassVector MemberOfClass;
02335   QualType Composite1 = Context.getCanonicalType(T1),
02336            Composite2 = Context.getCanonicalType(T2);
02337   unsigned NeedConstBefore = 0;  
02338   do {
02339     const PointerType *Ptr1, *Ptr2;
02340     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
02341         (Ptr2 = Composite2->getAs<PointerType>())) {
02342       Composite1 = Ptr1->getPointeeType();
02343       Composite2 = Ptr2->getPointeeType();
02344       
02345       // If we're allowed to create a non-standard composite type, keep track
02346       // of where we need to fill in additional 'const' qualifiers. 
02347       if (NonStandardCompositeType &&
02348           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
02349         NeedConstBefore = QualifierUnion.size();
02350       
02351       QualifierUnion.push_back(
02352                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
02353       MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
02354       continue;
02355     }
02356 
02357     const MemberPointerType *MemPtr1, *MemPtr2;
02358     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
02359         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
02360       Composite1 = MemPtr1->getPointeeType();
02361       Composite2 = MemPtr2->getPointeeType();
02362       
02363       // If we're allowed to create a non-standard composite type, keep track
02364       // of where we need to fill in additional 'const' qualifiers. 
02365       if (NonStandardCompositeType &&
02366           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
02367         NeedConstBefore = QualifierUnion.size();
02368       
02369       QualifierUnion.push_back(
02370                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
02371       MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
02372                                              MemPtr2->getClass()));
02373       continue;
02374     }
02375 
02376     // FIXME: block pointer types?
02377 
02378     // Cannot unwrap any more types.
02379     break;
02380   } while (true);
02381 
02382   if (NeedConstBefore && NonStandardCompositeType) {
02383     // Extension: Add 'const' to qualifiers that come before the first qualifier
02384     // mismatch, so that our (non-standard!) composite type meets the 
02385     // requirements of C++ [conv.qual]p4 bullet 3.
02386     for (unsigned I = 0; I != NeedConstBefore; ++I) {
02387       if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
02388         QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
02389         *NonStandardCompositeType = true;
02390       }
02391     }
02392   }
02393   
02394   // Rewrap the composites as pointers or member pointers with the union CVRs.
02395   ContainingClassVector::reverse_iterator MOC
02396     = MemberOfClass.rbegin();
02397   for (QualifierVector::reverse_iterator
02398          I = QualifierUnion.rbegin(),
02399          E = QualifierUnion.rend();
02400        I != E; (void)++I, ++MOC) {
02401     Qualifiers Quals = Qualifiers::fromCVRMask(*I);
02402     if (MOC->first && MOC->second) {
02403       // Rebuild member pointer type
02404       Composite1 = Context.getMemberPointerType(
02405                                     Context.getQualifiedType(Composite1, Quals),
02406                                     MOC->first);
02407       Composite2 = Context.getMemberPointerType(
02408                                     Context.getQualifiedType(Composite2, Quals),
02409                                     MOC->second);
02410     } else {
02411       // Rebuild pointer type
02412       Composite1
02413         = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
02414       Composite2
02415         = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
02416     }
02417   }
02418 
02419   // Try to convert to the first composite pointer type.
02420   InitializedEntity Entity1
02421     = InitializedEntity::InitializeTemporary(Composite1);
02422   InitializationKind Kind
02423     = InitializationKind::CreateCopy(Loc, SourceLocation());
02424   InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
02425   InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
02426 
02427   if (E1ToC1 && E2ToC1) {
02428     // Conversion to Composite1 is viable.
02429     if (!Context.hasSameType(Composite1, Composite2)) {
02430       // Composite2 is a different type from Composite1. Check whether
02431       // Composite2 is also viable.
02432       InitializedEntity Entity2
02433         = InitializedEntity::InitializeTemporary(Composite2);
02434       InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
02435       InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
02436       if (E1ToC2 && E2ToC2) {
02437         // Both Composite1 and Composite2 are viable and are different;
02438         // this is an ambiguity.
02439         return QualType();
02440       }
02441     }
02442 
02443     // Convert E1 to Composite1
02444     OwningExprResult E1Result
02445       = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
02446     if (E1Result.isInvalid())
02447       return QualType();
02448     E1 = E1Result.takeAs<Expr>();
02449 
02450     // Convert E2 to Composite1
02451     OwningExprResult E2Result
02452       = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
02453     if (E2Result.isInvalid())
02454       return QualType();
02455     E2 = E2Result.takeAs<Expr>();
02456     
02457     return Composite1;
02458   }
02459 
02460   // Check whether Composite2 is viable.
02461   InitializedEntity Entity2
02462     = InitializedEntity::InitializeTemporary(Composite2);
02463   InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
02464   InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
02465   if (!E1ToC2 || !E2ToC2)
02466     return QualType();
02467   
02468   // Convert E1 to Composite2
02469   OwningExprResult E1Result
02470     = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
02471   if (E1Result.isInvalid())
02472     return QualType();
02473   E1 = E1Result.takeAs<Expr>();
02474   
02475   // Convert E2 to Composite2
02476   OwningExprResult E2Result
02477     = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
02478   if (E2Result.isInvalid())
02479     return QualType();
02480   E2 = E2Result.takeAs<Expr>();
02481   
02482   return Composite2;
02483 }
02484 
02485 Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
02486   if (!Context.getLangOptions().CPlusPlus)
02487     return Owned(E);
02488 
02489   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
02490 
02491   const RecordType *RT = E->getType()->getAs<RecordType>();
02492   if (!RT)
02493     return Owned(E);
02494 
02495   // If this is the result of a call expression, our source might
02496   // actually be a reference, in which case we shouldn't bind.
02497   if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
02498     QualType Ty = CE->getCallee()->getType();
02499     if (const PointerType *PT = Ty->getAs<PointerType>())
02500       Ty = PT->getPointeeType();
02501     else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
02502       Ty = BPT->getPointeeType();
02503 
02504     const FunctionType *FTy = Ty->getAs<FunctionType>();
02505     if (FTy->getResultType()->isReferenceType())
02506       return Owned(E);
02507   }
02508 
02509   // That should be enough to guarantee that this type is complete.
02510   // If it has a trivial destructor, we can avoid the extra copy.
02511   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
02512   if (RD->hasTrivialDestructor())
02513     return Owned(E);
02514 
02515   CXXTemporary *Temp = CXXTemporary::Create(Context,
02516                                             RD->getDestructor(Context));
02517   ExprTemporaries.push_back(Temp);
02518   if (CXXDestructorDecl *Destructor =
02519         const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
02520     MarkDeclarationReferenced(E->getExprLoc(), Destructor);
02521     CheckDestructorAccess(E->getExprLoc(), Destructor,
02522                           PDiag(diag::err_access_dtor_temp)
02523                             << E->getType());
02524   }
02525   // FIXME: Add the temporary to the temporaries vector.
02526   return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
02527 }
02528 
02529 Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
02530   assert(SubExpr && "sub expression can't be null!");
02531 
02532   unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
02533   assert(ExprTemporaries.size() >= FirstTemporary);
02534   if (ExprTemporaries.size() == FirstTemporary)
02535     return SubExpr;
02536 
02537   Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
02538                                            &ExprTemporaries[FirstTemporary],
02539                                        ExprTemporaries.size() - FirstTemporary);
02540   ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
02541                         ExprTemporaries.end());
02542 
02543   return E;
02544 }
02545 
02546 Sema::OwningExprResult 
02547 Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
02548   if (SubExpr.isInvalid())
02549     return ExprError();
02550   
02551   return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
02552 }
02553 
02554 FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
02555   unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
02556   assert(ExprTemporaries.size() >= FirstTemporary);
02557   
02558   unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
02559   CXXTemporary **Temporaries = 
02560     NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
02561   
02562   FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
02563 
02564   ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
02565                         ExprTemporaries.end());
02566 
02567   return E;
02568 }
02569 
02570 Sema::OwningExprResult
02571 Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
02572                                    tok::TokenKind OpKind, TypeTy *&ObjectType,
02573                                    bool &MayBePseudoDestructor) {
02574   // Since this might be a postfix expression, get rid of ParenListExprs.
02575   Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
02576 
02577   Expr *BaseExpr = (Expr*)Base.get();
02578   assert(BaseExpr && "no record expansion");
02579 
02580   QualType BaseType = BaseExpr->getType();
02581   MayBePseudoDestructor = false;
02582   if (BaseType->isDependentType()) {
02583     // If we have a pointer to a dependent type and are using the -> operator,
02584     // the object type is the type that the pointer points to. We might still
02585     // have enough information about that type to do something useful.
02586     if (OpKind == tok::arrow)
02587       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
02588         BaseType = Ptr->getPointeeType();
02589     
02590     ObjectType = BaseType.getAsOpaquePtr();
02591     MayBePseudoDestructor = true;
02592     return move(Base);
02593   }
02594 
02595   // C++ [over.match.oper]p8:
02596   //   [...] When operator->returns, the operator-> is applied  to the value
02597   //   returned, with the original second operand.
02598   if (OpKind == tok::arrow) {
02599     // The set of types we've considered so far.
02600     llvm::SmallPtrSet<CanQualType,8> CTypes;
02601     llvm::SmallVector<SourceLocation, 8> Locations;
02602     CTypes.insert(Context.getCanonicalType(BaseType));
02603     
02604     while (BaseType->isRecordType()) {
02605       Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
02606       BaseExpr = (Expr*)Base.get();
02607       if (BaseExpr == NULL)
02608         return ExprError();
02609       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
02610         Locations.push_back(OpCall->getDirectCallee()->getLocation());
02611       BaseType = BaseExpr->getType();
02612       CanQualType CBaseType = Context.getCanonicalType(BaseType);
02613       if (!CTypes.insert(CBaseType)) {
02614         Diag(OpLoc, diag::err_operator_arrow_circular);
02615         for (unsigned i = 0; i < Locations.size(); i++)
02616           Diag(Locations[i], diag::note_declared_at);
02617         return ExprError();
02618       }
02619     }
02620 
02621     if (BaseType->isPointerType())
02622       BaseType = BaseType->getPointeeType();
02623   }
02624 
02625   // We could end up with various non-record types here, such as extended
02626   // vector types or Objective-C interfaces. Just return early and let
02627   // ActOnMemberReferenceExpr do the work.
02628   if (!BaseType->isRecordType()) {
02629     // C++ [basic.lookup.classref]p2:
02630     //   [...] If the type of the object expression is of pointer to scalar
02631     //   type, the unqualified-id is looked up in the context of the complete
02632     //   postfix-expression.
02633     //
02634     // This also indicates that we should be parsing a
02635     // pseudo-destructor-name.
02636     ObjectType = 0;
02637     MayBePseudoDestructor = true;
02638     return move(Base);
02639   }
02640 
02641   // The object type must be complete (or dependent).
02642   if (!BaseType->isDependentType() &&
02643       RequireCompleteType(OpLoc, BaseType, 
02644                           PDiag(diag::err_incomplete_member_access)))
02645     return ExprError();
02646   
02647   // C++ [basic.lookup.classref]p2:
02648   //   If the id-expression in a class member access (5.2.5) is an
02649   //   unqualified-id, and the type of the object expression is of a class
02650   //   type C (or of pointer to a class type C), the unqualified-id is looked
02651   //   up in the scope of class C. [...]
02652   ObjectType = BaseType.getAsOpaquePtr();
02653   return move(Base);
02654 }
02655 
02656 Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
02657                                                    ExprArg MemExpr) {
02658   Expr *E = (Expr *) MemExpr.get();
02659   SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
02660   Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
02661     << isa<CXXPseudoDestructorExpr>(E)
02662     << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
02663   
02664   return ActOnCallExpr(/*Scope*/ 0,
02665                        move(MemExpr),
02666                        /*LPLoc*/ ExpectedLParenLoc,
02667                        Sema::MultiExprArg(*this, 0, 0),
02668                        /*CommaLocs*/ 0,
02669                        /*RPLoc*/ ExpectedLParenLoc);
02670 }
02671 
02672 Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
02673                                                        SourceLocation OpLoc,
02674                                                        tok::TokenKind OpKind,
02675                                                        const CXXScopeSpec &SS,
02676                                                  TypeSourceInfo *ScopeTypeInfo,
02677                                                        SourceLocation CCLoc,
02678                                                        SourceLocation TildeLoc,
02679                                          PseudoDestructorTypeStorage Destructed,
02680                                                        bool HasTrailingLParen) {
02681   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
02682   
02683   // C++ [expr.pseudo]p2:
02684   //   The left-hand side of the dot operator shall be of scalar type. The 
02685   //   left-hand side of the arrow operator shall be of pointer to scalar type.
02686   //   This scalar type is the object type. 
02687   Expr *BaseE = (Expr *)Base.get();
02688   QualType ObjectType = BaseE->getType();
02689   if (OpKind == tok::arrow) {
02690     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
02691       ObjectType = Ptr->getPointeeType();
02692     } else if (!BaseE->isTypeDependent()) {
02693       // The user wrote "p->" when she probably meant "p."; fix it.
02694       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
02695         << ObjectType << true
02696         << FixItHint::CreateReplacement(OpLoc, ".");
02697       if (isSFINAEContext())
02698         return ExprError();
02699       
02700       OpKind = tok::period;
02701     }
02702   }
02703   
02704   if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
02705     Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
02706       << ObjectType << BaseE->getSourceRange();
02707     return ExprError();
02708   }
02709 
02710   // C++ [expr.pseudo]p2:
02711   //   [...] The cv-unqualified versions of the object type and of the type 
02712   //   designated by the pseudo-destructor-name shall be the same type.
02713   if (DestructedTypeInfo) {
02714     QualType DestructedType = DestructedTypeInfo->getType();
02715     SourceLocation DestructedTypeStart
02716       = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
02717     if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
02718         !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
02719       Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
02720         << ObjectType << DestructedType << BaseE->getSourceRange()
02721         << DestructedTypeInfo->getTypeLoc().getSourceRange();
02722       
02723       // Recover by setting the destructed type to the object type.
02724       DestructedType = ObjectType;
02725       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
02726                                                            DestructedTypeStart);
02727       Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
02728     }
02729   }
02730   
02731   // C++ [expr.pseudo]p2:
02732   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
02733   //   form
02734   //
02735   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 
02736   //
02737   //   shall designate the same scalar type.
02738   if (ScopeTypeInfo) {
02739     QualType ScopeType = ScopeTypeInfo->getType();
02740     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
02741         !Context.hasSameType(ScopeType, ObjectType)) {
02742       
02743       Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
02744            diag::err_pseudo_dtor_type_mismatch)
02745         << ObjectType << ScopeType << BaseE->getSourceRange()
02746         << ScopeTypeInfo->getTypeLoc().getSourceRange();
02747   
02748       ScopeType = QualType();
02749       ScopeTypeInfo = 0;
02750     }
02751   }
02752   
02753   OwningExprResult Result
02754     = Owned(new (Context) CXXPseudoDestructorExpr(Context, 
02755                                                   Base.takeAs<Expr>(),
02756                                                   OpKind == tok::arrow,
02757                                                   OpLoc,
02758                                        (NestedNameSpecifier *) SS.getScopeRep(),
02759                                                   SS.getRange(),
02760                                                   ScopeTypeInfo,
02761                                                   CCLoc,
02762                                                   TildeLoc,
02763                                                   Destructed));
02764             
02765   if (HasTrailingLParen)
02766     return move(Result);
02767   
02768   return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
02769 }
02770 
02771 Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
02772                                                        SourceLocation OpLoc,
02773                                                        tok::TokenKind OpKind,
02774                                                        CXXScopeSpec &SS,
02775                                                   UnqualifiedId &FirstTypeName,
02776                                                        SourceLocation CCLoc,
02777                                                        SourceLocation TildeLoc,
02778                                                  UnqualifiedId &SecondTypeName,
02779                                                        bool HasTrailingLParen) {
02780   assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
02781           FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
02782          "Invalid first type name in pseudo-destructor");
02783   assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
02784           SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
02785          "Invalid second type name in pseudo-destructor");
02786 
02787   Expr *BaseE = (Expr *)Base.get();
02788   
02789   // C++ [expr.pseudo]p2:
02790   //   The left-hand side of the dot operator shall be of scalar type. The 
02791   //   left-hand side of the arrow operator shall be of pointer to scalar type.
02792   //   This scalar type is the object type. 
02793   QualType ObjectType = BaseE->getType();
02794   if (OpKind == tok::arrow) {
02795     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
02796       ObjectType = Ptr->getPointeeType();
02797     } else if (!ObjectType->isDependentType()) {
02798       // The user wrote "p->" when she probably meant "p."; fix it.
02799       Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
02800         << ObjectType << true
02801         << FixItHint::CreateReplacement(OpLoc, ".");
02802       if (isSFINAEContext())
02803         return ExprError();
02804       
02805       OpKind = tok::period;
02806     }
02807   }
02808 
02809   // Compute the object type that we should use for name lookup purposes. Only
02810   // record types and dependent types matter.
02811   void *ObjectTypePtrForLookup = 0;
02812   if (!SS.isSet()) {
02813     ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
02814     if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
02815       ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
02816   }
02817   
02818   // Convert the name of the type being destructed (following the ~) into a 
02819   // type (with source-location information).
02820   QualType DestructedType;
02821   TypeSourceInfo *DestructedTypeInfo = 0;
02822   PseudoDestructorTypeStorage Destructed;
02823   if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
02824     TypeTy *T = getTypeName(*SecondTypeName.Identifier, 
02825                             SecondTypeName.StartLocation,
02826                             S, &SS, true, ObjectTypePtrForLookup);
02827     if (!T && 
02828         ((SS.isSet() && !computeDeclContext(SS, false)) ||
02829          (!SS.isSet() && ObjectType->isDependentType()))) {
02830       // The name of the type being destroyed is a dependent name, and we 
02831       // couldn't find anything useful in scope. Just store the identifier and
02832       // it's location, and we'll perform (qualified) name lookup again at
02833       // template instantiation time.
02834       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
02835                                                SecondTypeName.StartLocation);
02836     } else if (!T) {
02837       Diag(SecondTypeName.StartLocation, 
02838            diag::err_pseudo_dtor_destructor_non_type)
02839         << SecondTypeName.Identifier << ObjectType;
02840       if (isSFINAEContext())
02841         return ExprError();
02842       
02843       // Recover by assuming we had the right type all along.
02844       DestructedType = ObjectType;
02845     } else
02846       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
02847   } else {
02848     // Resolve the template-id to a type.
02849     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
02850     ASTTemplateArgsPtr TemplateArgsPtr(*this,
02851                                        TemplateId->getTemplateArgs(),
02852                                        TemplateId->NumArgs);
02853     TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
02854                                        TemplateId->TemplateNameLoc,
02855                                        TemplateId->LAngleLoc,
02856                                        TemplateArgsPtr,
02857                                        TemplateId->RAngleLoc);
02858     if (T.isInvalid() || !T.get()) {
02859       // Recover by assuming we had the right type all along.
02860       DestructedType = ObjectType;
02861     } else
02862       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
02863   }
02864   
02865   // If we've performed some kind of recovery, (re-)build the type source 
02866   // information.
02867   if (!DestructedType.isNull()) {
02868     if (!DestructedTypeInfo)
02869       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
02870                                                   SecondTypeName.StartLocation);
02871     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
02872   }
02873   
02874   // Convert the name of the scope type (the type prior to '::') into a type.
02875   TypeSourceInfo *ScopeTypeInfo = 0;
02876   QualType ScopeType;
02877   if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 
02878       FirstTypeName.Identifier) {
02879     if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
02880       TypeTy *T = getTypeName(*FirstTypeName.Identifier, 
02881                               FirstTypeName.StartLocation,
02882                               S, &SS, false, ObjectTypePtrForLookup);
02883       if (!T) {
02884         Diag(FirstTypeName.StartLocation, 
02885              diag::err_pseudo_dtor_destructor_non_type)
02886           << FirstTypeName.Identifier << ObjectType;
02887         
02888         if (isSFINAEContext())
02889           return ExprError();
02890         
02891         // Just drop this type. It's unnecessary anyway.
02892         ScopeType = QualType();
02893       } else
02894         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
02895     } else {
02896       // Resolve the template-id to a type.
02897       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
02898       ASTTemplateArgsPtr TemplateArgsPtr(*this,
02899                                          TemplateId->getTemplateArgs(),
02900                                          TemplateId->NumArgs);
02901       TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
02902                                          TemplateId->TemplateNameLoc,
02903                                          TemplateId->LAngleLoc,
02904                                          TemplateArgsPtr,
02905                                          TemplateId->RAngleLoc);
02906       if (T.isInvalid() || !T.get()) {
02907         // Recover by dropping this type.
02908         ScopeType = QualType();
02909       } else
02910         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);      
02911     }
02912   }
02913       
02914   if (!ScopeType.isNull() && !ScopeTypeInfo)
02915     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
02916                                                   FirstTypeName.StartLocation);
02917 
02918     
02919   return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
02920                                    ScopeTypeInfo, CCLoc, TildeLoc,
02921                                    Destructed, HasTrailingLParen);
02922 }
02923 
02924 CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, 
02925                                                 NamedDecl *FoundDecl,
02926                                                 CXXMethodDecl *Method) {
02927   if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
02928                                           FoundDecl, Method))
02929     assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
02930 
02931   MemberExpr *ME = 
02932       new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, 
02933                                SourceLocation(), Method->getType());
02934   QualType ResultType = Method->getResultType().getNonReferenceType();
02935   MarkDeclarationReferenced(Exp->getLocStart(), Method);
02936   CXXMemberCallExpr *CE =
02937     new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
02938                                     Exp->getLocEnd());
02939   return CE;
02940 }
02941 
02942 Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
02943   Expr *FullExpr = Arg.takeAs<Expr>();
02944   if (FullExpr)
02945     FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
02946 
02947   return Owned(FullExpr);
02948 }