159486a2dSAnders Carlsson //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
259486a2dSAnders Carlsson //
359486a2dSAnders Carlsson //                     The LLVM Compiler Infrastructure
459486a2dSAnders Carlsson //
559486a2dSAnders Carlsson // This file is distributed under the University of Illinois Open Source
659486a2dSAnders Carlsson // License. See LICENSE.TXT for details.
759486a2dSAnders Carlsson //
859486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
959486a2dSAnders Carlsson //
1059486a2dSAnders Carlsson // This contains code dealing with code generation of C++ expressions
1159486a2dSAnders Carlsson //
1259486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
1359486a2dSAnders Carlsson 
1491bbb554SDevang Patel #include "clang/Frontend/CodeGenOptions.h"
1559486a2dSAnders Carlsson #include "CodeGenFunction.h"
165d865c32SJohn McCall #include "CGCXXABI.h"
1760d215b6SFariborz Jahanian #include "CGObjCRuntime.h"
1891bbb554SDevang Patel #include "CGDebugInfo.h"
1926008e07SChris Lattner #include "llvm/Intrinsics.h"
20bbe277c4SAnders Carlsson #include "llvm/Support/CallSite.h"
21bbe277c4SAnders Carlsson 
2259486a2dSAnders Carlsson using namespace clang;
2359486a2dSAnders Carlsson using namespace CodeGen;
2459486a2dSAnders Carlsson 
2527da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
2627da15baSAnders Carlsson                                           llvm::Value *Callee,
2727da15baSAnders Carlsson                                           ReturnValueSlot ReturnValue,
2827da15baSAnders Carlsson                                           llvm::Value *This,
29e36a6b3eSAnders Carlsson                                           llvm::Value *VTT,
3027da15baSAnders Carlsson                                           CallExpr::const_arg_iterator ArgBeg,
3127da15baSAnders Carlsson                                           CallExpr::const_arg_iterator ArgEnd) {
3227da15baSAnders Carlsson   assert(MD->isInstance() &&
3327da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
3427da15baSAnders Carlsson 
3527da15baSAnders Carlsson   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
3627da15baSAnders Carlsson 
3727da15baSAnders Carlsson   CallArgList Args;
3827da15baSAnders Carlsson 
3927da15baSAnders Carlsson   // Push the this ptr.
4043dca6a8SEli Friedman   Args.add(RValue::get(This), MD->getThisType(getContext()));
4127da15baSAnders Carlsson 
42e36a6b3eSAnders Carlsson   // If there is a VTT parameter, emit it.
43e36a6b3eSAnders Carlsson   if (VTT) {
44e36a6b3eSAnders Carlsson     QualType T = getContext().getPointerType(getContext().VoidPtrTy);
4543dca6a8SEli Friedman     Args.add(RValue::get(VTT), T);
46e36a6b3eSAnders Carlsson   }
47e36a6b3eSAnders Carlsson 
4827da15baSAnders Carlsson   // And the rest of the call args
4927da15baSAnders Carlsson   EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
5027da15baSAnders Carlsson 
51ab26cfa5SJohn McCall   QualType ResultType = FPT->getResultType();
5299cc30c3STilmann Scheller   return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
5399cc30c3STilmann Scheller                                                  FPT->getExtInfo()),
54c50c27ccSRafael Espindola                   Callee, ReturnValue, Args, MD);
5527da15baSAnders Carlsson }
5627da15baSAnders Carlsson 
571ae64c5aSAnders Carlsson static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
586b3afd7dSAnders Carlsson   const Expr *E = Base;
596b3afd7dSAnders Carlsson 
606b3afd7dSAnders Carlsson   while (true) {
616b3afd7dSAnders Carlsson     E = E->IgnoreParens();
626b3afd7dSAnders Carlsson     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
636b3afd7dSAnders Carlsson       if (CE->getCastKind() == CK_DerivedToBase ||
646b3afd7dSAnders Carlsson           CE->getCastKind() == CK_UncheckedDerivedToBase ||
656b3afd7dSAnders Carlsson           CE->getCastKind() == CK_NoOp) {
666b3afd7dSAnders Carlsson         E = CE->getSubExpr();
676b3afd7dSAnders Carlsson         continue;
686b3afd7dSAnders Carlsson       }
696b3afd7dSAnders Carlsson     }
706b3afd7dSAnders Carlsson 
716b3afd7dSAnders Carlsson     break;
726b3afd7dSAnders Carlsson   }
736b3afd7dSAnders Carlsson 
746b3afd7dSAnders Carlsson   QualType DerivedType = E->getType();
751ae64c5aSAnders Carlsson   if (const PointerType *PTy = DerivedType->getAs<PointerType>())
761ae64c5aSAnders Carlsson     DerivedType = PTy->getPointeeType();
771ae64c5aSAnders Carlsson 
781ae64c5aSAnders Carlsson   return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
791ae64c5aSAnders Carlsson }
801ae64c5aSAnders Carlsson 
81c53d9e83SAnders Carlsson // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
82c53d9e83SAnders Carlsson // quite what we want.
83c53d9e83SAnders Carlsson static const Expr *skipNoOpCastsAndParens(const Expr *E) {
84c53d9e83SAnders Carlsson   while (true) {
85c53d9e83SAnders Carlsson     if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
86c53d9e83SAnders Carlsson       E = PE->getSubExpr();
87c53d9e83SAnders Carlsson       continue;
88c53d9e83SAnders Carlsson     }
89c53d9e83SAnders Carlsson 
90c53d9e83SAnders Carlsson     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
91c53d9e83SAnders Carlsson       if (CE->getCastKind() == CK_NoOp) {
92c53d9e83SAnders Carlsson         E = CE->getSubExpr();
93c53d9e83SAnders Carlsson         continue;
94c53d9e83SAnders Carlsson       }
95c53d9e83SAnders Carlsson     }
96c53d9e83SAnders Carlsson     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
97c53d9e83SAnders Carlsson       if (UO->getOpcode() == UO_Extension) {
98c53d9e83SAnders Carlsson         E = UO->getSubExpr();
99c53d9e83SAnders Carlsson         continue;
100c53d9e83SAnders Carlsson       }
101c53d9e83SAnders Carlsson     }
102c53d9e83SAnders Carlsson     return E;
103c53d9e83SAnders Carlsson   }
104c53d9e83SAnders Carlsson }
105c53d9e83SAnders Carlsson 
10627da15baSAnders Carlsson /// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
10727da15baSAnders Carlsson /// expr can be devirtualized.
108252a47f6SFariborz Jahanian static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
109252a47f6SFariborz Jahanian                                                const Expr *Base,
110a7911fa3SAnders Carlsson                                                const CXXMethodDecl *MD) {
111a7911fa3SAnders Carlsson 
1121ae64c5aSAnders Carlsson   // When building with -fapple-kext, all calls must go through the vtable since
1131ae64c5aSAnders Carlsson   // the kernel linker can do runtime patching of vtables.
114252a47f6SFariborz Jahanian   if (Context.getLangOptions().AppleKext)
115252a47f6SFariborz Jahanian     return false;
116252a47f6SFariborz Jahanian 
1171ae64c5aSAnders Carlsson   // If the most derived class is marked final, we know that no subclass can
1181ae64c5aSAnders Carlsson   // override this member function and so we can devirtualize it. For example:
1191ae64c5aSAnders Carlsson   //
1201ae64c5aSAnders Carlsson   // struct A { virtual void f(); }
1211ae64c5aSAnders Carlsson   // struct B final : A { };
1221ae64c5aSAnders Carlsson   //
1231ae64c5aSAnders Carlsson   // void f(B *b) {
1241ae64c5aSAnders Carlsson   //   b->f();
1251ae64c5aSAnders Carlsson   // }
1261ae64c5aSAnders Carlsson   //
1271ae64c5aSAnders Carlsson   const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1281ae64c5aSAnders Carlsson   if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1291ae64c5aSAnders Carlsson     return true;
1301ae64c5aSAnders Carlsson 
13119588aa4SAnders Carlsson   // If the member function is marked 'final', we know that it can't be
132b00c2144SAnders Carlsson   // overridden and can therefore devirtualize it.
1331eb95961SAnders Carlsson   if (MD->hasAttr<FinalAttr>())
134a7911fa3SAnders Carlsson     return true;
135a7911fa3SAnders Carlsson 
13619588aa4SAnders Carlsson   // Similarly, if the class itself is marked 'final' it can't be overridden
13719588aa4SAnders Carlsson   // and we can therefore devirtualize the member function call.
1381eb95961SAnders Carlsson   if (MD->getParent()->hasAttr<FinalAttr>())
139b00c2144SAnders Carlsson     return true;
140b00c2144SAnders Carlsson 
141c53d9e83SAnders Carlsson   Base = skipNoOpCastsAndParens(Base);
14227da15baSAnders Carlsson   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
14327da15baSAnders Carlsson     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
14427da15baSAnders Carlsson       // This is a record decl. We know the type and can devirtualize it.
14527da15baSAnders Carlsson       return VD->getType()->isRecordType();
14627da15baSAnders Carlsson     }
14727da15baSAnders Carlsson 
14827da15baSAnders Carlsson     return false;
14927da15baSAnders Carlsson   }
15027da15baSAnders Carlsson 
15127da15baSAnders Carlsson   // We can always devirtualize calls on temporary object expressions.
152a682427eSEli Friedman   if (isa<CXXConstructExpr>(Base))
15327da15baSAnders Carlsson     return true;
15427da15baSAnders Carlsson 
15527da15baSAnders Carlsson   // And calls on bound temporaries.
15627da15baSAnders Carlsson   if (isa<CXXBindTemporaryExpr>(Base))
15727da15baSAnders Carlsson     return true;
15827da15baSAnders Carlsson 
15927da15baSAnders Carlsson   // Check if this is a call expr that returns a record type.
16027da15baSAnders Carlsson   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
16127da15baSAnders Carlsson     return CE->getCallReturnType()->isRecordType();
16227da15baSAnders Carlsson 
16327da15baSAnders Carlsson   // We can't devirtualize the call.
16427da15baSAnders Carlsson   return false;
16527da15baSAnders Carlsson }
16627da15baSAnders Carlsson 
16764225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC
16864225794SFrancois Pichet // extensions allowing explicit constructor function call.
16927da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
17027da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
1712d2e8707SJohn McCall   const Expr *callee = CE->getCallee()->IgnoreParens();
1722d2e8707SJohn McCall 
1732d2e8707SJohn McCall   if (isa<BinaryOperator>(callee))
17427da15baSAnders Carlsson     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
17527da15baSAnders Carlsson 
1762d2e8707SJohn McCall   const MemberExpr *ME = cast<MemberExpr>(callee);
17727da15baSAnders Carlsson   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
17827da15baSAnders Carlsson 
17991bbb554SDevang Patel   CGDebugInfo *DI = getDebugInfo();
180401c916cSDevang Patel   if (DI && CGM.getCodeGenOpts().LimitDebugInfo
181401c916cSDevang Patel       && !isa<CallExpr>(ME->getBase())) {
18291bbb554SDevang Patel     QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
18391bbb554SDevang Patel     if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
18491bbb554SDevang Patel       DI->getOrCreateRecordType(PTy->getPointeeType(),
18591bbb554SDevang Patel                                 MD->getParent()->getLocation());
18691bbb554SDevang Patel     }
18791bbb554SDevang Patel   }
18891bbb554SDevang Patel 
18927da15baSAnders Carlsson   if (MD->isStatic()) {
19027da15baSAnders Carlsson     // The method is static, emit it as we would a regular call.
19127da15baSAnders Carlsson     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
19227da15baSAnders Carlsson     return EmitCall(getContext().getPointerType(MD->getType()), Callee,
19327da15baSAnders Carlsson                     ReturnValue, CE->arg_begin(), CE->arg_end());
19427da15baSAnders Carlsson   }
19527da15baSAnders Carlsson 
1960d635f53SJohn McCall   // Compute the object pointer.
19727da15baSAnders Carlsson   llvm::Value *This;
19827da15baSAnders Carlsson   if (ME->isArrow())
19927da15baSAnders Carlsson     This = EmitScalarExpr(ME->getBase());
200f93ac894SFariborz Jahanian   else
201e26a872bSJohn McCall     This = EmitLValue(ME->getBase()).getAddress();
20227da15baSAnders Carlsson 
2030d635f53SJohn McCall   if (MD->isTrivial()) {
2040d635f53SJohn McCall     if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
20564225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
20664225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
20764225794SFrancois Pichet       return RValue::get(0);
2080d635f53SJohn McCall 
20964225794SFrancois Pichet     if (MD->isCopyAssignmentOperator()) {
21027da15baSAnders Carlsson       // We don't like to generate the trivial copy assignment operator when
21127da15baSAnders Carlsson       // it isn't necessary; just produce the proper effect here.
21227da15baSAnders Carlsson       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
21327da15baSAnders Carlsson       EmitAggregateCopy(This, RHS, CE->getType());
21427da15baSAnders Carlsson       return RValue::get(This);
21527da15baSAnders Carlsson     }
21627da15baSAnders Carlsson 
21764225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
21864225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
21964225794SFrancois Pichet       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
22064225794SFrancois Pichet       EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
22164225794SFrancois Pichet                                      CE->arg_begin(), CE->arg_end());
22264225794SFrancois Pichet       return RValue::get(This);
22364225794SFrancois Pichet     }
22464225794SFrancois Pichet     llvm_unreachable("unknown trivial member function");
22564225794SFrancois Pichet   }
22664225794SFrancois Pichet 
2270d635f53SJohn McCall   // Compute the function type we're calling.
22864225794SFrancois Pichet   const CGFunctionInfo *FInfo = 0;
22964225794SFrancois Pichet   if (isa<CXXDestructorDecl>(MD))
23064225794SFrancois Pichet     FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
23164225794SFrancois Pichet                                            Dtor_Complete);
23264225794SFrancois Pichet   else if (isa<CXXConstructorDecl>(MD))
23364225794SFrancois Pichet     FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
23464225794SFrancois Pichet                                             Ctor_Complete);
23564225794SFrancois Pichet   else
23664225794SFrancois Pichet     FInfo = &CGM.getTypes().getFunctionInfo(MD);
2370d635f53SJohn McCall 
2380d635f53SJohn McCall   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
2390d635f53SJohn McCall   const llvm::Type *Ty
24064225794SFrancois Pichet     = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
2410d635f53SJohn McCall 
24227da15baSAnders Carlsson   // C++ [class.virtual]p12:
24327da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
24427da15baSAnders Carlsson   //   virtual call mechanism.
24527da15baSAnders Carlsson   //
24627da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
24727da15baSAnders Carlsson   // because then we know what the type is.
24847609b08SFariborz Jahanian   bool UseVirtualCall;
24947609b08SFariborz Jahanian   UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
250252a47f6SFariborz Jahanian                    && !canDevirtualizeMemberFunctionCalls(getContext(),
251252a47f6SFariborz Jahanian                                                           ME->getBase(), MD);
25227da15baSAnders Carlsson   llvm::Value *Callee;
2530d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
2540d635f53SJohn McCall     if (UseVirtualCall) {
2550d635f53SJohn McCall       Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
25627da15baSAnders Carlsson     } else {
257265c325eSFariborz Jahanian       if (getContext().getLangOptions().AppleKext &&
258265c325eSFariborz Jahanian           MD->isVirtual() &&
259265c325eSFariborz Jahanian           ME->hasQualifier())
2607f6f81baSFariborz Jahanian         Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
261265c325eSFariborz Jahanian       else
2620d635f53SJohn McCall         Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
26327da15baSAnders Carlsson     }
26464225794SFrancois Pichet   } else if (const CXXConstructorDecl *Ctor =
26564225794SFrancois Pichet                dyn_cast<CXXConstructorDecl>(MD)) {
26664225794SFrancois Pichet     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
2670d635f53SJohn McCall   } else if (UseVirtualCall) {
26827da15baSAnders Carlsson       Callee = BuildVirtualCall(MD, This, Ty);
26927da15baSAnders Carlsson   } else {
270252a47f6SFariborz Jahanian     if (getContext().getLangOptions().AppleKext &&
2719f9438b3SFariborz Jahanian         MD->isVirtual() &&
272252a47f6SFariborz Jahanian         ME->hasQualifier())
2737f6f81baSFariborz Jahanian       Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
274252a47f6SFariborz Jahanian     else
27527da15baSAnders Carlsson       Callee = CGM.GetAddrOfFunction(MD, Ty);
27627da15baSAnders Carlsson   }
27727da15baSAnders Carlsson 
278e36a6b3eSAnders Carlsson   return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
27927da15baSAnders Carlsson                            CE->arg_begin(), CE->arg_end());
28027da15baSAnders Carlsson }
28127da15baSAnders Carlsson 
28227da15baSAnders Carlsson RValue
28327da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
28427da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
28527da15baSAnders Carlsson   const BinaryOperator *BO =
28627da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
28727da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
28827da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
28927da15baSAnders Carlsson 
29027da15baSAnders Carlsson   const MemberPointerType *MPT =
2910009fcc3SJohn McCall     MemFnExpr->getType()->castAs<MemberPointerType>();
292475999dcSJohn McCall 
29327da15baSAnders Carlsson   const FunctionProtoType *FPT =
2940009fcc3SJohn McCall     MPT->getPointeeType()->castAs<FunctionProtoType>();
29527da15baSAnders Carlsson   const CXXRecordDecl *RD =
29627da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
29727da15baSAnders Carlsson 
29827da15baSAnders Carlsson   // Get the member function pointer.
299a1dee530SJohn McCall   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
30027da15baSAnders Carlsson 
30127da15baSAnders Carlsson   // Emit the 'this' pointer.
30227da15baSAnders Carlsson   llvm::Value *This;
30327da15baSAnders Carlsson 
304e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
30527da15baSAnders Carlsson     This = EmitScalarExpr(BaseExpr);
30627da15baSAnders Carlsson   else
30727da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
30827da15baSAnders Carlsson 
309475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
310475999dcSJohn McCall   llvm::Value *Callee =
311ad7c5c16SJohn McCall     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
31227da15baSAnders Carlsson 
31327da15baSAnders Carlsson   CallArgList Args;
31427da15baSAnders Carlsson 
31527da15baSAnders Carlsson   QualType ThisType =
31627da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
31727da15baSAnders Carlsson 
31827da15baSAnders Carlsson   // Push the this ptr.
31943dca6a8SEli Friedman   Args.add(RValue::get(This), ThisType);
32027da15baSAnders Carlsson 
32127da15baSAnders Carlsson   // And the rest of the call args
32227da15baSAnders Carlsson   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
3230009fcc3SJohn McCall   return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
32499cc30c3STilmann Scheller                   ReturnValue, Args);
32527da15baSAnders Carlsson }
32627da15baSAnders Carlsson 
32727da15baSAnders Carlsson RValue
32827da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
32927da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
33027da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
33127da15baSAnders Carlsson   assert(MD->isInstance() &&
33227da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
333e26a872bSJohn McCall   LValue LV = EmitLValue(E->getArg(0));
334e26a872bSJohn McCall   llvm::Value *This = LV.getAddress();
335e26a872bSJohn McCall 
336ec3bec0cSDouglas Gregor   if (MD->isCopyAssignmentOperator()) {
33727da15baSAnders Carlsson     const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
33827da15baSAnders Carlsson     if (ClassDecl->hasTrivialCopyAssignment()) {
33927da15baSAnders Carlsson       assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
34027da15baSAnders Carlsson              "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
34127da15baSAnders Carlsson       llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
34227da15baSAnders Carlsson       QualType Ty = E->getType();
34327da15baSAnders Carlsson       EmitAggregateCopy(This, Src, Ty);
34427da15baSAnders Carlsson       return RValue::get(This);
34527da15baSAnders Carlsson     }
34627da15baSAnders Carlsson   }
34727da15baSAnders Carlsson 
34827da15baSAnders Carlsson   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
34927da15baSAnders Carlsson   const llvm::Type *Ty =
35027da15baSAnders Carlsson     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
35127da15baSAnders Carlsson                                    FPT->isVariadic());
35227da15baSAnders Carlsson   llvm::Value *Callee;
35347609b08SFariborz Jahanian   if (MD->isVirtual() &&
354252a47f6SFariborz Jahanian       !canDevirtualizeMemberFunctionCalls(getContext(),
355252a47f6SFariborz Jahanian                                            E->getArg(0), MD))
35627da15baSAnders Carlsson     Callee = BuildVirtualCall(MD, This, Ty);
35727da15baSAnders Carlsson   else
35827da15baSAnders Carlsson     Callee = CGM.GetAddrOfFunction(MD, Ty);
35927da15baSAnders Carlsson 
360e36a6b3eSAnders Carlsson   return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
36127da15baSAnders Carlsson                            E->arg_begin() + 1, E->arg_end());
36227da15baSAnders Carlsson }
36327da15baSAnders Carlsson 
36427da15baSAnders Carlsson void
3657a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
3667a626f63SJohn McCall                                       AggValueSlot Dest) {
3677a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
36827da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
369630c76efSDouglas Gregor 
370630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
371630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
37203535265SArgyrios Kyrtzidis   // constructor, emit the zero initialization now, unless destination is
37303535265SArgyrios Kyrtzidis   // already zeroed.
37403535265SArgyrios Kyrtzidis   if (E->requiresZeroInitialization() && !Dest.isZeroed())
3757a626f63SJohn McCall     EmitNullInitialization(Dest.getAddr(), E->getType());
376630c76efSDouglas Gregor 
377630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
378630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
37927da15baSAnders Carlsson     return;
380630c76efSDouglas Gregor 
3818ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
3828ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
3838ea46b66SJohn McCall   // returns.
38427da15baSAnders Carlsson   if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
3858ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
3868ea46b66SJohn McCall                                                E->getArg(0)->getType()));
3877a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
3887a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
38927da15baSAnders Carlsson       return;
39027da15baSAnders Carlsson     }
391222cf0efSDouglas Gregor   }
392630c76efSDouglas Gregor 
393630c76efSDouglas Gregor   const ConstantArrayType *Array
394630c76efSDouglas Gregor     = getContext().getAsConstantArrayType(E->getType());
39527da15baSAnders Carlsson   if (Array) {
39627da15baSAnders Carlsson     QualType BaseElementTy = getContext().getBaseElementType(Array);
39727da15baSAnders Carlsson     const llvm::Type *BasePtr = ConvertType(BaseElementTy);
39827da15baSAnders Carlsson     BasePtr = llvm::PointerType::getUnqual(BasePtr);
39927da15baSAnders Carlsson     llvm::Value *BaseAddrPtr =
4007a626f63SJohn McCall       Builder.CreateBitCast(Dest.getAddr(), BasePtr);
40127da15baSAnders Carlsson 
40227da15baSAnders Carlsson     EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
40327da15baSAnders Carlsson                                E->arg_begin(), E->arg_end());
40427da15baSAnders Carlsson   }
405e11f9ce9SAnders Carlsson   else {
406*bceca20aSCameron Esfahani     CXXCtorType Type = Ctor_Complete;
407271c3681SAlexis Hunt     bool ForVirtualBase = false;
408271c3681SAlexis Hunt 
409271c3681SAlexis Hunt     switch (E->getConstructionKind()) {
410271c3681SAlexis Hunt      case CXXConstructExpr::CK_Delegating:
41161bc1737SAlexis Hunt       // We should be emitting a constructor; GlobalDecl will assert this
41261bc1737SAlexis Hunt       Type = CurGD.getCtorType();
413271c3681SAlexis Hunt       break;
41461bc1737SAlexis Hunt 
415271c3681SAlexis Hunt      case CXXConstructExpr::CK_Complete:
416271c3681SAlexis Hunt       Type = Ctor_Complete;
417271c3681SAlexis Hunt       break;
418271c3681SAlexis Hunt 
419271c3681SAlexis Hunt      case CXXConstructExpr::CK_VirtualBase:
420271c3681SAlexis Hunt       ForVirtualBase = true;
421271c3681SAlexis Hunt       // fall-through
422271c3681SAlexis Hunt 
423271c3681SAlexis Hunt      case CXXConstructExpr::CK_NonVirtualBase:
424271c3681SAlexis Hunt       Type = Ctor_Base;
425271c3681SAlexis Hunt     }
426e11f9ce9SAnders Carlsson 
42727da15baSAnders Carlsson     // Call the constructor.
4287a626f63SJohn McCall     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
42927da15baSAnders Carlsson                            E->arg_begin(), E->arg_end());
43027da15baSAnders Carlsson   }
431e11f9ce9SAnders Carlsson }
43227da15baSAnders Carlsson 
433e988bdacSFariborz Jahanian void
434e988bdacSFariborz Jahanian CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
435e988bdacSFariborz Jahanian                                             llvm::Value *Src,
43650198098SFariborz Jahanian                                             const Expr *Exp) {
4375d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
438e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
439e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
440e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
441e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
442e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
443e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
444e988bdacSFariborz Jahanian 
445e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
446e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
447e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
448e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
449e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
450e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
451e988bdacSFariborz Jahanian 
45299da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
45399da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
454e988bdacSFariborz Jahanian   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
455e988bdacSFariborz Jahanian                                  E->arg_begin(), E->arg_end());
456e988bdacSFariborz Jahanian }
457e988bdacSFariborz Jahanian 
458aa4149a2SJohn McCall /// Check whether the given operator new[] is the global placement
459aa4149a2SJohn McCall /// operator new[].
460aa4149a2SJohn McCall static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
461aa4149a2SJohn McCall                                         const FunctionDecl *Fn) {
462aa4149a2SJohn McCall   // Must be in global scope.  Note that allocation functions can't be
463aa4149a2SJohn McCall   // declared in namespaces.
46450c68258SSebastian Redl   if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
465aa4149a2SJohn McCall     return false;
466aa4149a2SJohn McCall 
467aa4149a2SJohn McCall   // Signature must be void *operator new[](size_t, void*).
468aa4149a2SJohn McCall   // The size_t is common to all operator new[]s.
469aa4149a2SJohn McCall   if (Fn->getNumParams() != 2)
470aa4149a2SJohn McCall     return false;
471aa4149a2SJohn McCall 
472aa4149a2SJohn McCall   CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
473aa4149a2SJohn McCall   return (ParamType == Ctx.VoidPtrTy);
474aa4149a2SJohn McCall }
475aa4149a2SJohn McCall 
4768ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
4778ed55a54SJohn McCall                                         const CXXNewExpr *E) {
47821122cf6SAnders Carlsson   if (!E->isArray())
4793eb55cfeSKen Dyck     return CharUnits::Zero();
48021122cf6SAnders Carlsson 
481399f499fSAnders Carlsson   // No cookie is required if the new operator being used is
482399f499fSAnders Carlsson   // ::operator new[](size_t, void*).
483399f499fSAnders Carlsson   const FunctionDecl *OperatorNew = E->getOperatorNew();
4848ed55a54SJohn McCall   if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
4853eb55cfeSKen Dyck     return CharUnits::Zero();
486399f499fSAnders Carlsson 
487284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
48859486a2dSAnders Carlsson }
48959486a2dSAnders Carlsson 
49047b4629bSFariborz Jahanian static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
49147b4629bSFariborz Jahanian                                         CodeGenFunction &CGF,
49259486a2dSAnders Carlsson                                         const CXXNewExpr *E,
49305fc5be3SDouglas Gregor                                         llvm::Value *&NumElements,
49405fc5be3SDouglas Gregor                                         llvm::Value *&SizeWithoutCookie) {
4957648fb46SArgyrios Kyrtzidis   QualType ElemType = E->getAllocatedType();
49659486a2dSAnders Carlsson 
4978ed55a54SJohn McCall   const llvm::IntegerType *SizeTy =
4988ed55a54SJohn McCall     cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
4998ed55a54SJohn McCall 
5007648fb46SArgyrios Kyrtzidis   CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
5018ed55a54SJohn McCall 
5028ed55a54SJohn McCall   if (!E->isArray()) {
50305fc5be3SDouglas Gregor     SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
50405fc5be3SDouglas Gregor     return SizeWithoutCookie;
50505fc5be3SDouglas Gregor   }
50659486a2dSAnders Carlsson 
5078ed55a54SJohn McCall   // Figure out the cookie size.
5088ed55a54SJohn McCall   CharUnits CookieSize = CalculateCookiePadding(CGF, E);
5098ed55a54SJohn McCall 
51059486a2dSAnders Carlsson   // Emit the array size expression.
5117648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
5127648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
51359486a2dSAnders Carlsson   NumElements = CGF.EmitScalarExpr(E->getArraySize());
5148ed55a54SJohn McCall   assert(NumElements->getType() == SizeTy && "element count not a size_t");
5158ed55a54SJohn McCall 
5168ed55a54SJohn McCall   uint64_t ArraySizeMultiplier = 1;
5177648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
5187648fb46SArgyrios Kyrtzidis              = CGF.getContext().getAsConstantArrayType(ElemType)) {
5197648fb46SArgyrios Kyrtzidis     ElemType = CAT->getElementType();
5208ed55a54SJohn McCall     ArraySizeMultiplier *= CAT->getSize().getZExtValue();
5217648fb46SArgyrios Kyrtzidis   }
52259486a2dSAnders Carlsson 
5238ed55a54SJohn McCall   llvm::Value *Size;
52432ac583dSChris Lattner 
52532ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
52632ac583dSChris Lattner   // Don't bloat the -O0 code.
52732ac583dSChris Lattner   if (llvm::ConstantInt *NumElementsC =
52832ac583dSChris Lattner         dyn_cast<llvm::ConstantInt>(NumElements)) {
52932ac583dSChris Lattner     llvm::APInt NEC = NumElementsC->getValue();
5308ed55a54SJohn McCall     unsigned SizeWidth = NEC.getBitWidth();
53132ac583dSChris Lattner 
5328ed55a54SJohn McCall     // Determine if there is an overflow here by doing an extended multiply.
5336d4db0c8SJay Foad     NEC = NEC.zext(SizeWidth*2);
5348ed55a54SJohn McCall     llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
53532ac583dSChris Lattner     SC *= NEC;
53632ac583dSChris Lattner 
5378ed55a54SJohn McCall     if (!CookieSize.isZero()) {
5388ed55a54SJohn McCall       // Save the current size without a cookie.  We don't care if an
5398ed55a54SJohn McCall       // overflow's already happened because SizeWithoutCookie isn't
5408ed55a54SJohn McCall       // used if the allocator returns null or throws, as it should
5418ed55a54SJohn McCall       // always do on an overflow.
5426d4db0c8SJay Foad       llvm::APInt SWC = SC.trunc(SizeWidth);
5438ed55a54SJohn McCall       SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
5448ed55a54SJohn McCall 
5458ed55a54SJohn McCall       // Add the cookie size.
5468ed55a54SJohn McCall       SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
5478ed55a54SJohn McCall     }
5488ed55a54SJohn McCall 
5498ed55a54SJohn McCall     if (SC.countLeadingZeros() >= SizeWidth) {
5506d4db0c8SJay Foad       SC = SC.trunc(SizeWidth);
5518ed55a54SJohn McCall       Size = llvm::ConstantInt::get(SizeTy, SC);
55232ac583dSChris Lattner     } else {
55332ac583dSChris Lattner       // On overflow, produce a -1 so operator new throws.
5548ed55a54SJohn McCall       Size = llvm::Constant::getAllOnesValue(SizeTy);
55532ac583dSChris Lattner     }
55632ac583dSChris Lattner 
5578ed55a54SJohn McCall     // Scale NumElements while we're at it.
5588ed55a54SJohn McCall     uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
5598ed55a54SJohn McCall     NumElements = llvm::ConstantInt::get(SizeTy, N);
56047b4629bSFariborz Jahanian 
5618ed55a54SJohn McCall   // Otherwise, we don't need to do an overflow-checked multiplication if
5628ed55a54SJohn McCall   // we're multiplying by one.
5638ed55a54SJohn McCall   } else if (TypeSize.isOne()) {
5648ed55a54SJohn McCall     assert(ArraySizeMultiplier == 1);
565f2f38701SChris Lattner 
5668ed55a54SJohn McCall     Size = NumElements;
567f2f38701SChris Lattner 
5688ed55a54SJohn McCall     // If we need a cookie, add its size in with an overflow check.
5698ed55a54SJohn McCall     // This is maybe a little paranoid.
5708ed55a54SJohn McCall     if (!CookieSize.isZero()) {
57105fc5be3SDouglas Gregor       SizeWithoutCookie = Size;
572f2f38701SChris Lattner 
5738ed55a54SJohn McCall       llvm::Value *CookieSizeV
5748ed55a54SJohn McCall         = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
5758ed55a54SJohn McCall 
5768ed55a54SJohn McCall       const llvm::Type *Types[] = { SizeTy };
5778ed55a54SJohn McCall       llvm::Value *UAddF
5788ed55a54SJohn McCall         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
5798ed55a54SJohn McCall       llvm::Value *AddRes
5808ed55a54SJohn McCall         = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
5818ed55a54SJohn McCall 
5828ed55a54SJohn McCall       Size = CGF.Builder.CreateExtractValue(AddRes, 0);
5838ed55a54SJohn McCall       llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
5848ed55a54SJohn McCall       Size = CGF.Builder.CreateSelect(DidOverflow,
5858ed55a54SJohn McCall                                       llvm::ConstantInt::get(SizeTy, -1),
5868ed55a54SJohn McCall                                       Size);
5878ed55a54SJohn McCall     }
5888ed55a54SJohn McCall 
5898ed55a54SJohn McCall   // Otherwise use the int.umul.with.overflow intrinsic.
5908ed55a54SJohn McCall   } else {
5918ed55a54SJohn McCall     llvm::Value *OutermostElementSize
5928ed55a54SJohn McCall       = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
5938ed55a54SJohn McCall 
5948ed55a54SJohn McCall     llvm::Value *NumOutermostElements = NumElements;
5958ed55a54SJohn McCall 
5968ed55a54SJohn McCall     // Scale NumElements by the array size multiplier.  This might
5978ed55a54SJohn McCall     // overflow, but only if the multiplication below also overflows,
5988ed55a54SJohn McCall     // in which case this multiplication isn't used.
5998ed55a54SJohn McCall     if (ArraySizeMultiplier != 1)
6008ed55a54SJohn McCall       NumElements = CGF.Builder.CreateMul(NumElements,
6018ed55a54SJohn McCall                          llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
6028ed55a54SJohn McCall 
6038ed55a54SJohn McCall     // The requested size of the outermost array is non-constant.
6048ed55a54SJohn McCall     // Multiply that by the static size of the elements of that array;
6058ed55a54SJohn McCall     // on unsigned overflow, set the size to -1 to trigger an
6068ed55a54SJohn McCall     // exception from the allocation routine.  This is sufficient to
6078ed55a54SJohn McCall     // prevent buffer overruns from the allocator returning a
6088ed55a54SJohn McCall     // seemingly valid pointer to insufficient space.  This idea comes
6098ed55a54SJohn McCall     // originally from MSVC, and GCC has an open bug requesting
6108ed55a54SJohn McCall     // similar behavior:
6118ed55a54SJohn McCall     //   http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
6128ed55a54SJohn McCall     //
6138ed55a54SJohn McCall     // This will not be sufficient for C++0x, which requires a
6148ed55a54SJohn McCall     // specific exception class (std::bad_array_new_length).
6158ed55a54SJohn McCall     // That will require ABI support that has not yet been specified.
6168ed55a54SJohn McCall     const llvm::Type *Types[] = { SizeTy };
6178ed55a54SJohn McCall     llvm::Value *UMulF
6188ed55a54SJohn McCall       = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
6198ed55a54SJohn McCall     llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
6208ed55a54SJohn McCall                                                   OutermostElementSize);
6218ed55a54SJohn McCall 
6228ed55a54SJohn McCall     // The overflow bit.
6238ed55a54SJohn McCall     llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
6248ed55a54SJohn McCall 
6258ed55a54SJohn McCall     // The result of the multiplication.
6268ed55a54SJohn McCall     Size = CGF.Builder.CreateExtractValue(MulRes, 0);
6278ed55a54SJohn McCall 
6288ed55a54SJohn McCall     // If we have a cookie, we need to add that size in, too.
6298ed55a54SJohn McCall     if (!CookieSize.isZero()) {
6308ed55a54SJohn McCall       SizeWithoutCookie = Size;
6318ed55a54SJohn McCall 
6328ed55a54SJohn McCall       llvm::Value *CookieSizeV
6338ed55a54SJohn McCall         = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
6348ed55a54SJohn McCall       llvm::Value *UAddF
6358ed55a54SJohn McCall         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
6368ed55a54SJohn McCall       llvm::Value *AddRes
6378ed55a54SJohn McCall         = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
6388ed55a54SJohn McCall 
6398ed55a54SJohn McCall       Size = CGF.Builder.CreateExtractValue(AddRes, 0);
6408ed55a54SJohn McCall 
6418ed55a54SJohn McCall       llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
642db42a3e8SEli Friedman       DidOverflow = CGF.Builder.CreateOr(DidOverflow, AddDidOverflow);
6438ed55a54SJohn McCall     }
6448ed55a54SJohn McCall 
6458ed55a54SJohn McCall     Size = CGF.Builder.CreateSelect(DidOverflow,
6468ed55a54SJohn McCall                                     llvm::ConstantInt::get(SizeTy, -1),
6478ed55a54SJohn McCall                                     Size);
6488ed55a54SJohn McCall   }
6498ed55a54SJohn McCall 
6508ed55a54SJohn McCall   if (CookieSize.isZero())
6518ed55a54SJohn McCall     SizeWithoutCookie = Size;
6528ed55a54SJohn McCall   else
6538ed55a54SJohn McCall     assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
65459486a2dSAnders Carlsson 
65532ac583dSChris Lattner   return Size;
65659486a2dSAnders Carlsson }
65759486a2dSAnders Carlsson 
658d5202e09SFariborz Jahanian static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
659d5202e09SFariborz Jahanian                                     llvm::Value *NewPtr) {
660d5202e09SFariborz Jahanian 
661d5202e09SFariborz Jahanian   assert(E->getNumConstructorArgs() == 1 &&
662d5202e09SFariborz Jahanian          "Can only have one argument to initializer of POD type.");
663d5202e09SFariborz Jahanian 
664d5202e09SFariborz Jahanian   const Expr *Init = E->getConstructorArg(0);
665d5202e09SFariborz Jahanian   QualType AllocType = E->getAllocatedType();
666d5202e09SFariborz Jahanian 
6670381634aSDaniel Dunbar   unsigned Alignment =
6680381634aSDaniel Dunbar     CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
669d5202e09SFariborz Jahanian   if (!CGF.hasAggregateLLVMType(AllocType))
670d5202e09SFariborz Jahanian     CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
6710381634aSDaniel Dunbar                           AllocType.isVolatileQualified(), Alignment,
6720381634aSDaniel Dunbar                           AllocType);
673d5202e09SFariborz Jahanian   else if (AllocType->isAnyComplexType())
674d5202e09SFariborz Jahanian     CGF.EmitComplexExprIntoAddr(Init, NewPtr,
675d5202e09SFariborz Jahanian                                 AllocType.isVolatileQualified());
6767a626f63SJohn McCall   else {
6777a626f63SJohn McCall     AggValueSlot Slot
6787a626f63SJohn McCall       = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
6797a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
6807a626f63SJohn McCall   }
681d5202e09SFariborz Jahanian }
682d5202e09SFariborz Jahanian 
683d5202e09SFariborz Jahanian void
684d5202e09SFariborz Jahanian CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
685d5202e09SFariborz Jahanian                                          llvm::Value *NewPtr,
686d5202e09SFariborz Jahanian                                          llvm::Value *NumElements) {
687b66b08efSFariborz Jahanian   // We have a POD type.
688b66b08efSFariborz Jahanian   if (E->getNumConstructorArgs() == 0)
689b66b08efSFariborz Jahanian     return;
690b66b08efSFariborz Jahanian 
691d5202e09SFariborz Jahanian   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
692d5202e09SFariborz Jahanian 
693d5202e09SFariborz Jahanian   // Create a temporary for the loop index and initialize it with 0.
694d5202e09SFariborz Jahanian   llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
695d5202e09SFariborz Jahanian   llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
696d5202e09SFariborz Jahanian   Builder.CreateStore(Zero, IndexPtr);
697d5202e09SFariborz Jahanian 
698d5202e09SFariborz Jahanian   // Start the loop with a block that tests the condition.
699d5202e09SFariborz Jahanian   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
700d5202e09SFariborz Jahanian   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
701d5202e09SFariborz Jahanian 
702d5202e09SFariborz Jahanian   EmitBlock(CondBlock);
703d5202e09SFariborz Jahanian 
704d5202e09SFariborz Jahanian   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
705d5202e09SFariborz Jahanian 
706d5202e09SFariborz Jahanian   // Generate: if (loop-index < number-of-elements fall to the loop body,
707d5202e09SFariborz Jahanian   // otherwise, go to the block after the for-loop.
708d5202e09SFariborz Jahanian   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
709d5202e09SFariborz Jahanian   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
710d5202e09SFariborz Jahanian   // If the condition is true, execute the body.
711d5202e09SFariborz Jahanian   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
712d5202e09SFariborz Jahanian 
713d5202e09SFariborz Jahanian   EmitBlock(ForBody);
714d5202e09SFariborz Jahanian 
715d5202e09SFariborz Jahanian   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
716d5202e09SFariborz Jahanian   // Inside the loop body, emit the constructor call on the array element.
717d5202e09SFariborz Jahanian   Counter = Builder.CreateLoad(IndexPtr);
718d5202e09SFariborz Jahanian   llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
719d5202e09SFariborz Jahanian                                                    "arrayidx");
720d5202e09SFariborz Jahanian   StoreAnyExprIntoOneUnit(*this, E, Address);
721d5202e09SFariborz Jahanian 
722d5202e09SFariborz Jahanian   EmitBlock(ContinueBlock);
723d5202e09SFariborz Jahanian 
724d5202e09SFariborz Jahanian   // Emit the increment of the loop counter.
725d5202e09SFariborz Jahanian   llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
726d5202e09SFariborz Jahanian   Counter = Builder.CreateLoad(IndexPtr);
727d5202e09SFariborz Jahanian   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
728d5202e09SFariborz Jahanian   Builder.CreateStore(NextVal, IndexPtr);
729d5202e09SFariborz Jahanian 
730d5202e09SFariborz Jahanian   // Finally, branch back up to the condition for the next iteration.
731d5202e09SFariborz Jahanian   EmitBranch(CondBlock);
732d5202e09SFariborz Jahanian 
733d5202e09SFariborz Jahanian   // Emit the fall-through block.
734d5202e09SFariborz Jahanian   EmitBlock(AfterFor, true);
735d5202e09SFariborz Jahanian }
736d5202e09SFariborz Jahanian 
73705fc5be3SDouglas Gregor static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
73805fc5be3SDouglas Gregor                            llvm::Value *NewPtr, llvm::Value *Size) {
739ad7c5c16SJohn McCall   CGF.EmitCastToVoidPtr(NewPtr);
740705ba07eSKen Dyck   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
741acc6b4e2SBenjamin Kramer   CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
742705ba07eSKen Dyck                            Alignment.getQuantity(), false);
74305fc5be3SDouglas Gregor }
74405fc5be3SDouglas Gregor 
74559486a2dSAnders Carlsson static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
74659486a2dSAnders Carlsson                                llvm::Value *NewPtr,
74705fc5be3SDouglas Gregor                                llvm::Value *NumElements,
74805fc5be3SDouglas Gregor                                llvm::Value *AllocSizeWithoutCookie) {
7493a202f60SAnders Carlsson   if (E->isArray()) {
750d040e6b2SAnders Carlsson     if (CXXConstructorDecl *Ctor = E->getConstructor()) {
75105fc5be3SDouglas Gregor       bool RequiresZeroInitialization = false;
75205fc5be3SDouglas Gregor       if (Ctor->getParent()->hasTrivialConstructor()) {
75305fc5be3SDouglas Gregor         // If new expression did not specify value-initialization, then there
75405fc5be3SDouglas Gregor         // is no initialization.
75505fc5be3SDouglas Gregor         if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
75605fc5be3SDouglas Gregor           return;
75705fc5be3SDouglas Gregor 
758614dbdcdSJohn McCall         if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
75905fc5be3SDouglas Gregor           // Optimization: since zero initialization will just set the memory
76005fc5be3SDouglas Gregor           // to all zeroes, generate a single memset to do it in one shot.
76105fc5be3SDouglas Gregor           EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
76205fc5be3SDouglas Gregor                          AllocSizeWithoutCookie);
7633a202f60SAnders Carlsson           return;
7643a202f60SAnders Carlsson         }
76505fc5be3SDouglas Gregor 
76605fc5be3SDouglas Gregor         RequiresZeroInitialization = true;
76705fc5be3SDouglas Gregor       }
76805fc5be3SDouglas Gregor 
76905fc5be3SDouglas Gregor       CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
77005fc5be3SDouglas Gregor                                      E->constructor_arg_begin(),
77105fc5be3SDouglas Gregor                                      E->constructor_arg_end(),
77205fc5be3SDouglas Gregor                                      RequiresZeroInitialization);
77305fc5be3SDouglas Gregor       return;
77405fc5be3SDouglas Gregor     } else if (E->getNumConstructorArgs() == 1 &&
77505fc5be3SDouglas Gregor                isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
77605fc5be3SDouglas Gregor       // Optimization: since zero initialization will just set the memory
77705fc5be3SDouglas Gregor       // to all zeroes, generate a single memset to do it in one shot.
77805fc5be3SDouglas Gregor       EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
77905fc5be3SDouglas Gregor                      AllocSizeWithoutCookie);
78005fc5be3SDouglas Gregor       return;
78105fc5be3SDouglas Gregor     } else {
782d5202e09SFariborz Jahanian       CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
783d5202e09SFariborz Jahanian       return;
784d040e6b2SAnders Carlsson     }
785d5202e09SFariborz Jahanian   }
78659486a2dSAnders Carlsson 
78759486a2dSAnders Carlsson   if (CXXConstructorDecl *Ctor = E->getConstructor()) {
788747eb784SDouglas Gregor     // Per C++ [expr.new]p15, if we have an initializer, then we're performing
789747eb784SDouglas Gregor     // direct initialization. C++ [dcl.init]p5 requires that we
790747eb784SDouglas Gregor     // zero-initialize storage if there are no user-declared constructors.
791747eb784SDouglas Gregor     if (E->hasInitializer() &&
792747eb784SDouglas Gregor         !Ctor->getParent()->hasUserDeclaredConstructor() &&
793747eb784SDouglas Gregor         !Ctor->getParent()->isEmpty())
794747eb784SDouglas Gregor       CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
795747eb784SDouglas Gregor 
796e11f9ce9SAnders Carlsson     CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
797e11f9ce9SAnders Carlsson                                NewPtr, E->constructor_arg_begin(),
79859486a2dSAnders Carlsson                                E->constructor_arg_end());
79959486a2dSAnders Carlsson 
80059486a2dSAnders Carlsson     return;
80159486a2dSAnders Carlsson   }
802b66b08efSFariborz Jahanian   // We have a POD type.
803b66b08efSFariborz Jahanian   if (E->getNumConstructorArgs() == 0)
804b66b08efSFariborz Jahanian     return;
80559486a2dSAnders Carlsson 
806d5202e09SFariborz Jahanian   StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
80759486a2dSAnders Carlsson }
80859486a2dSAnders Carlsson 
809824c2f53SJohn McCall namespace {
810824c2f53SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
811824c2f53SJohn McCall   /// abnormal exit from a new expression.
812824c2f53SJohn McCall   class CallDeleteDuringNew : public EHScopeStack::Cleanup {
813824c2f53SJohn McCall     size_t NumPlacementArgs;
814824c2f53SJohn McCall     const FunctionDecl *OperatorDelete;
815824c2f53SJohn McCall     llvm::Value *Ptr;
816824c2f53SJohn McCall     llvm::Value *AllocSize;
817824c2f53SJohn McCall 
818824c2f53SJohn McCall     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
819824c2f53SJohn McCall 
820824c2f53SJohn McCall   public:
821824c2f53SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
822824c2f53SJohn McCall       return NumPlacementArgs * sizeof(RValue);
823824c2f53SJohn McCall     }
824824c2f53SJohn McCall 
825824c2f53SJohn McCall     CallDeleteDuringNew(size_t NumPlacementArgs,
826824c2f53SJohn McCall                         const FunctionDecl *OperatorDelete,
827824c2f53SJohn McCall                         llvm::Value *Ptr,
828824c2f53SJohn McCall                         llvm::Value *AllocSize)
829824c2f53SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
830824c2f53SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
831824c2f53SJohn McCall 
832824c2f53SJohn McCall     void setPlacementArg(unsigned I, RValue Arg) {
833824c2f53SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
834824c2f53SJohn McCall       getPlacementArgs()[I] = Arg;
835824c2f53SJohn McCall     }
836824c2f53SJohn McCall 
837824c2f53SJohn McCall     void Emit(CodeGenFunction &CGF, bool IsForEH) {
838824c2f53SJohn McCall       const FunctionProtoType *FPT
839824c2f53SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
840824c2f53SJohn McCall       assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
841d441b1e6SJohn McCall              (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
842824c2f53SJohn McCall 
843824c2f53SJohn McCall       CallArgList DeleteArgs;
844824c2f53SJohn McCall 
845824c2f53SJohn McCall       // The first argument is always a void*.
846824c2f53SJohn McCall       FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
84743dca6a8SEli Friedman       DeleteArgs.add(RValue::get(Ptr), *AI++);
848824c2f53SJohn McCall 
849824c2f53SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
850824c2f53SJohn McCall       if (FPT->getNumArgs() == NumPlacementArgs + 2)
85143dca6a8SEli Friedman         DeleteArgs.add(RValue::get(AllocSize), *AI++);
852824c2f53SJohn McCall 
853824c2f53SJohn McCall       // Pass the rest of the arguments, which must match exactly.
854824c2f53SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I)
85543dca6a8SEli Friedman         DeleteArgs.add(getPlacementArgs()[I], *AI++);
856824c2f53SJohn McCall 
857824c2f53SJohn McCall       // Call 'operator delete'.
85899cc30c3STilmann Scheller       CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
859824c2f53SJohn McCall                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
860824c2f53SJohn McCall                    ReturnValueSlot(), DeleteArgs, OperatorDelete);
861824c2f53SJohn McCall     }
862824c2f53SJohn McCall   };
8637f9c92a9SJohn McCall 
8647f9c92a9SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
8657f9c92a9SJohn McCall   /// abnormal exit from a new expression when the new expression is
8667f9c92a9SJohn McCall   /// conditional.
8677f9c92a9SJohn McCall   class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
8687f9c92a9SJohn McCall     size_t NumPlacementArgs;
8697f9c92a9SJohn McCall     const FunctionDecl *OperatorDelete;
870cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type Ptr;
871cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type AllocSize;
8727f9c92a9SJohn McCall 
873cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type *getPlacementArgs() {
874cb5f77f0SJohn McCall       return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
8757f9c92a9SJohn McCall     }
8767f9c92a9SJohn McCall 
8777f9c92a9SJohn McCall   public:
8787f9c92a9SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
879cb5f77f0SJohn McCall       return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
8807f9c92a9SJohn McCall     }
8817f9c92a9SJohn McCall 
8827f9c92a9SJohn McCall     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
8837f9c92a9SJohn McCall                                    const FunctionDecl *OperatorDelete,
884cb5f77f0SJohn McCall                                    DominatingValue<RValue>::saved_type Ptr,
885cb5f77f0SJohn McCall                               DominatingValue<RValue>::saved_type AllocSize)
8867f9c92a9SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
8877f9c92a9SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
8887f9c92a9SJohn McCall 
889cb5f77f0SJohn McCall     void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
8907f9c92a9SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
8917f9c92a9SJohn McCall       getPlacementArgs()[I] = Arg;
8927f9c92a9SJohn McCall     }
8937f9c92a9SJohn McCall 
8947f9c92a9SJohn McCall     void Emit(CodeGenFunction &CGF, bool IsForEH) {
8957f9c92a9SJohn McCall       const FunctionProtoType *FPT
8967f9c92a9SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
8977f9c92a9SJohn McCall       assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
8987f9c92a9SJohn McCall              (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
8997f9c92a9SJohn McCall 
9007f9c92a9SJohn McCall       CallArgList DeleteArgs;
9017f9c92a9SJohn McCall 
9027f9c92a9SJohn McCall       // The first argument is always a void*.
9037f9c92a9SJohn McCall       FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
90443dca6a8SEli Friedman       DeleteArgs.add(Ptr.restore(CGF), *AI++);
9057f9c92a9SJohn McCall 
9067f9c92a9SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
9077f9c92a9SJohn McCall       if (FPT->getNumArgs() == NumPlacementArgs + 2) {
908cb5f77f0SJohn McCall         RValue RV = AllocSize.restore(CGF);
90943dca6a8SEli Friedman         DeleteArgs.add(RV, *AI++);
9107f9c92a9SJohn McCall       }
9117f9c92a9SJohn McCall 
9127f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
9137f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
914cb5f77f0SJohn McCall         RValue RV = getPlacementArgs()[I].restore(CGF);
91543dca6a8SEli Friedman         DeleteArgs.add(RV, *AI++);
9167f9c92a9SJohn McCall       }
9177f9c92a9SJohn McCall 
9187f9c92a9SJohn McCall       // Call 'operator delete'.
91999cc30c3STilmann Scheller       CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
9207f9c92a9SJohn McCall                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
9217f9c92a9SJohn McCall                    ReturnValueSlot(), DeleteArgs, OperatorDelete);
9227f9c92a9SJohn McCall     }
9237f9c92a9SJohn McCall   };
9247f9c92a9SJohn McCall }
9257f9c92a9SJohn McCall 
9267f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
9277f9c92a9SJohn McCall /// new-expression throws.
9287f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
9297f9c92a9SJohn McCall                                   const CXXNewExpr *E,
9307f9c92a9SJohn McCall                                   llvm::Value *NewPtr,
9317f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
9327f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
9337f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
9347f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
9357f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
9367f9c92a9SJohn McCall     CallDeleteDuringNew *Cleanup = CGF.EHStack
9377f9c92a9SJohn McCall       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
9387f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
9397f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
9407f9c92a9SJohn McCall                                                  NewPtr, AllocSize);
9417f9c92a9SJohn McCall     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
942f4258eb4SEli Friedman       Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
9437f9c92a9SJohn McCall 
9447f9c92a9SJohn McCall     return;
9457f9c92a9SJohn McCall   }
9467f9c92a9SJohn McCall 
9477f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
948cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
949cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
950cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
951cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
9527f9c92a9SJohn McCall 
9537f9c92a9SJohn McCall   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
9547f9c92a9SJohn McCall     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
9557f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
9567f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
9577f9c92a9SJohn McCall                                                  SavedNewPtr,
9587f9c92a9SJohn McCall                                                  SavedAllocSize);
9597f9c92a9SJohn McCall   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
960cb5f77f0SJohn McCall     Cleanup->setPlacementArg(I,
961f4258eb4SEli Friedman                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
9627f9c92a9SJohn McCall 
9637f9c92a9SJohn McCall   CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
964824c2f53SJohn McCall }
965824c2f53SJohn McCall 
96659486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
96775f9498aSJohn McCall   // The element type being allocated.
96875f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
9698ed55a54SJohn McCall 
97075f9498aSJohn McCall   // 1. Build a call to the allocation function.
97175f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
97275f9498aSJohn McCall   const FunctionProtoType *allocatorType =
97375f9498aSJohn McCall     allocator->getType()->castAs<FunctionProtoType>();
97459486a2dSAnders Carlsson 
97575f9498aSJohn McCall   CallArgList allocatorArgs;
97659486a2dSAnders Carlsson 
97759486a2dSAnders Carlsson   // The allocation size is the first argument.
97875f9498aSJohn McCall   QualType sizeType = getContext().getSizeType();
97959486a2dSAnders Carlsson 
98075f9498aSJohn McCall   llvm::Value *numElements = 0;
98175f9498aSJohn McCall   llvm::Value *allocSizeWithoutCookie = 0;
98275f9498aSJohn McCall   llvm::Value *allocSize =
98375f9498aSJohn McCall     EmitCXXNewAllocSize(getContext(), *this, E, numElements,
98475f9498aSJohn McCall                         allocSizeWithoutCookie);
98559486a2dSAnders Carlsson 
98643dca6a8SEli Friedman   allocatorArgs.add(RValue::get(allocSize), sizeType);
98759486a2dSAnders Carlsson 
98859486a2dSAnders Carlsson   // Emit the rest of the arguments.
98959486a2dSAnders Carlsson   // FIXME: Ideally, this should just use EmitCallArgs.
99075f9498aSJohn McCall   CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
99159486a2dSAnders Carlsson 
99259486a2dSAnders Carlsson   // First, use the types from the function type.
99359486a2dSAnders Carlsson   // We start at 1 here because the first argument (the allocation size)
99459486a2dSAnders Carlsson   // has already been emitted.
99575f9498aSJohn McCall   for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
99675f9498aSJohn McCall        ++i, ++placementArg) {
99775f9498aSJohn McCall     QualType argType = allocatorType->getArgType(i);
99859486a2dSAnders Carlsson 
99975f9498aSJohn McCall     assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
100075f9498aSJohn McCall                                                placementArg->getType()) &&
100159486a2dSAnders Carlsson            "type mismatch in call argument!");
100259486a2dSAnders Carlsson 
100332ea9694SJohn McCall     EmitCallArg(allocatorArgs, *placementArg, argType);
100459486a2dSAnders Carlsson   }
100559486a2dSAnders Carlsson 
100659486a2dSAnders Carlsson   // Either we've emitted all the call args, or we have a call to a
100759486a2dSAnders Carlsson   // variadic function.
100875f9498aSJohn McCall   assert((placementArg == E->placement_arg_end() ||
100975f9498aSJohn McCall           allocatorType->isVariadic()) &&
101075f9498aSJohn McCall          "Extra arguments to non-variadic function!");
101159486a2dSAnders Carlsson 
101259486a2dSAnders Carlsson   // If we still have any arguments, emit them using the type of the argument.
101375f9498aSJohn McCall   for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
101475f9498aSJohn McCall        placementArg != placementArgsEnd; ++placementArg) {
101532ea9694SJohn McCall     EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
101659486a2dSAnders Carlsson   }
101759486a2dSAnders Carlsson 
101875f9498aSJohn McCall   // Emit the allocation call.
101959486a2dSAnders Carlsson   RValue RV =
102075f9498aSJohn McCall     EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
102175f9498aSJohn McCall              CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
102275f9498aSJohn McCall              allocatorArgs, allocator);
102359486a2dSAnders Carlsson 
102475f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
102575f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
102675f9498aSJohn McCall   // exception spec; for this part, we inline
102775f9498aSJohn McCall   // CXXNewExpr::shouldNullCheckAllocation()) and we have an
102875f9498aSJohn McCall   // interesting initializer.
102931ad754cSSebastian Redl   bool nullCheck = allocatorType->isNothrow(getContext()) &&
103075f9498aSJohn McCall     !(allocType->isPODType() && !E->hasInitializer());
103159486a2dSAnders Carlsson 
103275f9498aSJohn McCall   llvm::BasicBlock *nullCheckBB = 0;
103375f9498aSJohn McCall   llvm::BasicBlock *contBB = 0;
103459486a2dSAnders Carlsson 
103575f9498aSJohn McCall   llvm::Value *allocation = RV.getScalarVal();
103675f9498aSJohn McCall   unsigned AS =
103775f9498aSJohn McCall     cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
103859486a2dSAnders Carlsson 
1039f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
1040f7dcf320SJohn McCall   // evaluated.
1041f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
1042f7dcf320SJohn McCall 
104375f9498aSJohn McCall   if (nullCheck) {
1044f7dcf320SJohn McCall     conditional.begin(*this);
104575f9498aSJohn McCall 
104675f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
104775f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
104875f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
104975f9498aSJohn McCall 
105075f9498aSJohn McCall     llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
105175f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
105275f9498aSJohn McCall     EmitBlock(notNullBB);
105359486a2dSAnders Carlsson   }
105459486a2dSAnders Carlsson 
105575f9498aSJohn McCall   assert((allocSize == allocSizeWithoutCookie) ==
10568ed55a54SJohn McCall          CalculateCookiePadding(*this, E).isZero());
105775f9498aSJohn McCall   if (allocSize != allocSizeWithoutCookie) {
10588ed55a54SJohn McCall     assert(E->isArray());
105975f9498aSJohn McCall     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
106075f9498aSJohn McCall                                                        numElements,
106175f9498aSJohn McCall                                                        E, allocType);
106259486a2dSAnders Carlsson   }
106359486a2dSAnders Carlsson 
1064824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1065824c2f53SJohn McCall   // exception is thrown.
106675f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
1067824c2f53SJohn McCall   if (E->getOperatorDelete()) {
106875f9498aSJohn McCall     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
106975f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1070824c2f53SJohn McCall   }
1071824c2f53SJohn McCall 
107275f9498aSJohn McCall   const llvm::Type *elementPtrTy
107375f9498aSJohn McCall     = ConvertTypeForMem(allocType)->getPointerTo(AS);
107475f9498aSJohn McCall   llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
1075824c2f53SJohn McCall 
10768ed55a54SJohn McCall   if (E->isArray()) {
107775f9498aSJohn McCall     EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
10788ed55a54SJohn McCall 
10798ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
10808ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
10818ed55a54SJohn McCall     // array pointer type.
108275f9498aSJohn McCall     const llvm::Type *resultType = ConvertTypeForMem(E->getType());
108375f9498aSJohn McCall     if (result->getType() != resultType)
108475f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
10858ed55a54SJohn McCall   } else {
108675f9498aSJohn McCall     EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
108747b4629bSFariborz Jahanian   }
108859486a2dSAnders Carlsson 
1089824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1090824c2f53SJohn McCall   // initialization.
109175f9498aSJohn McCall   if (operatorDeleteCleanup.isValid())
109275f9498aSJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup);
1093824c2f53SJohn McCall 
109475f9498aSJohn McCall   if (nullCheck) {
1095f7dcf320SJohn McCall     conditional.end(*this);
1096f7dcf320SJohn McCall 
109775f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
109875f9498aSJohn McCall     EmitBlock(contBB);
109959486a2dSAnders Carlsson 
110020c0f02cSJay Foad     llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
110175f9498aSJohn McCall     PHI->addIncoming(result, notNullBB);
110275f9498aSJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
110375f9498aSJohn McCall                      nullCheckBB);
110459486a2dSAnders Carlsson 
110575f9498aSJohn McCall     result = PHI;
110659486a2dSAnders Carlsson   }
110759486a2dSAnders Carlsson 
110875f9498aSJohn McCall   return result;
110959486a2dSAnders Carlsson }
111059486a2dSAnders Carlsson 
111159486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
111259486a2dSAnders Carlsson                                      llvm::Value *Ptr,
111359486a2dSAnders Carlsson                                      QualType DeleteTy) {
11148ed55a54SJohn McCall   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
11158ed55a54SJohn McCall 
111659486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
111759486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
111859486a2dSAnders Carlsson 
111959486a2dSAnders Carlsson   CallArgList DeleteArgs;
112059486a2dSAnders Carlsson 
112121122cf6SAnders Carlsson   // Check if we need to pass the size to the delete operator.
112221122cf6SAnders Carlsson   llvm::Value *Size = 0;
112321122cf6SAnders Carlsson   QualType SizeTy;
112421122cf6SAnders Carlsson   if (DeleteFTy->getNumArgs() == 2) {
112521122cf6SAnders Carlsson     SizeTy = DeleteFTy->getArgType(1);
11267df3cbebSKen Dyck     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
11277df3cbebSKen Dyck     Size = llvm::ConstantInt::get(ConvertType(SizeTy),
11287df3cbebSKen Dyck                                   DeleteTypeSize.getQuantity());
112921122cf6SAnders Carlsson   }
113021122cf6SAnders Carlsson 
113159486a2dSAnders Carlsson   QualType ArgTy = DeleteFTy->getArgType(0);
113259486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
113343dca6a8SEli Friedman   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
113459486a2dSAnders Carlsson 
113521122cf6SAnders Carlsson   if (Size)
113643dca6a8SEli Friedman     DeleteArgs.add(RValue::get(Size), SizeTy);
113759486a2dSAnders Carlsson 
113859486a2dSAnders Carlsson   // Emit the call to delete.
113999cc30c3STilmann Scheller   EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
114061a401caSAnders Carlsson            CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
114159486a2dSAnders Carlsson            DeleteArgs, DeleteFD);
114259486a2dSAnders Carlsson }
114359486a2dSAnders Carlsson 
11448ed55a54SJohn McCall namespace {
11458ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
11468ed55a54SJohn McCall   struct CallObjectDelete : EHScopeStack::Cleanup {
11478ed55a54SJohn McCall     llvm::Value *Ptr;
11488ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
11498ed55a54SJohn McCall     QualType ElementType;
11508ed55a54SJohn McCall 
11518ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
11528ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
11538ed55a54SJohn McCall                      QualType ElementType)
11548ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
11558ed55a54SJohn McCall 
11568ed55a54SJohn McCall     void Emit(CodeGenFunction &CGF, bool IsForEH) {
11578ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
11588ed55a54SJohn McCall     }
11598ed55a54SJohn McCall   };
11608ed55a54SJohn McCall }
11618ed55a54SJohn McCall 
11628ed55a54SJohn McCall /// Emit the code for deleting a single object.
11638ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
11648ed55a54SJohn McCall                              const FunctionDecl *OperatorDelete,
11658ed55a54SJohn McCall                              llvm::Value *Ptr,
11668ed55a54SJohn McCall                              QualType ElementType) {
11678ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
11688ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
11698ed55a54SJohn McCall   const CXXDestructorDecl *Dtor = 0;
11708ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
11718ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
11728ed55a54SJohn McCall     if (!RD->hasTrivialDestructor()) {
11738ed55a54SJohn McCall       Dtor = RD->getDestructor();
11748ed55a54SJohn McCall 
11758ed55a54SJohn McCall       if (Dtor->isVirtual()) {
11768ed55a54SJohn McCall         const llvm::Type *Ty =
11770d635f53SJohn McCall           CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
11780d635f53SJohn McCall                                                                Dtor_Complete),
11798ed55a54SJohn McCall                                          /*isVariadic=*/false);
11808ed55a54SJohn McCall 
11818ed55a54SJohn McCall         llvm::Value *Callee
11828ed55a54SJohn McCall           = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
11838ed55a54SJohn McCall         CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
11848ed55a54SJohn McCall                               0, 0);
11858ed55a54SJohn McCall 
11868ed55a54SJohn McCall         // The dtor took care of deleting the object.
11878ed55a54SJohn McCall         return;
11888ed55a54SJohn McCall       }
11898ed55a54SJohn McCall     }
11908ed55a54SJohn McCall   }
11918ed55a54SJohn McCall 
11928ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1193e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1194e4df6c8dSJohn McCall   // to pop it off in a second.
11958ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
11968ed55a54SJohn McCall                                             Ptr, OperatorDelete, ElementType);
11978ed55a54SJohn McCall 
11988ed55a54SJohn McCall   if (Dtor)
11998ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
12008ed55a54SJohn McCall                               /*ForVirtualBase=*/false, Ptr);
12018ed55a54SJohn McCall 
12028ed55a54SJohn McCall   CGF.PopCleanupBlock();
12038ed55a54SJohn McCall }
12048ed55a54SJohn McCall 
12058ed55a54SJohn McCall namespace {
12068ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
12078ed55a54SJohn McCall   struct CallArrayDelete : EHScopeStack::Cleanup {
12088ed55a54SJohn McCall     llvm::Value *Ptr;
12098ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
12108ed55a54SJohn McCall     llvm::Value *NumElements;
12118ed55a54SJohn McCall     QualType ElementType;
12128ed55a54SJohn McCall     CharUnits CookieSize;
12138ed55a54SJohn McCall 
12148ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
12158ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
12168ed55a54SJohn McCall                     llvm::Value *NumElements,
12178ed55a54SJohn McCall                     QualType ElementType,
12188ed55a54SJohn McCall                     CharUnits CookieSize)
12198ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
12208ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
12218ed55a54SJohn McCall 
12228ed55a54SJohn McCall     void Emit(CodeGenFunction &CGF, bool IsForEH) {
12238ed55a54SJohn McCall       const FunctionProtoType *DeleteFTy =
12248ed55a54SJohn McCall         OperatorDelete->getType()->getAs<FunctionProtoType>();
12258ed55a54SJohn McCall       assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
12268ed55a54SJohn McCall 
12278ed55a54SJohn McCall       CallArgList Args;
12288ed55a54SJohn McCall 
12298ed55a54SJohn McCall       // Pass the pointer as the first argument.
12308ed55a54SJohn McCall       QualType VoidPtrTy = DeleteFTy->getArgType(0);
12318ed55a54SJohn McCall       llvm::Value *DeletePtr
12328ed55a54SJohn McCall         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
123343dca6a8SEli Friedman       Args.add(RValue::get(DeletePtr), VoidPtrTy);
12348ed55a54SJohn McCall 
12358ed55a54SJohn McCall       // Pass the original requested size as the second argument.
12368ed55a54SJohn McCall       if (DeleteFTy->getNumArgs() == 2) {
12378ed55a54SJohn McCall         QualType size_t = DeleteFTy->getArgType(1);
12388ed55a54SJohn McCall         const llvm::IntegerType *SizeTy
12398ed55a54SJohn McCall           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
12408ed55a54SJohn McCall 
12418ed55a54SJohn McCall         CharUnits ElementTypeSize =
12428ed55a54SJohn McCall           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
12438ed55a54SJohn McCall 
12448ed55a54SJohn McCall         // The size of an element, multiplied by the number of elements.
12458ed55a54SJohn McCall         llvm::Value *Size
12468ed55a54SJohn McCall           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
12478ed55a54SJohn McCall         Size = CGF.Builder.CreateMul(Size, NumElements);
12488ed55a54SJohn McCall 
12498ed55a54SJohn McCall         // Plus the size of the cookie if applicable.
12508ed55a54SJohn McCall         if (!CookieSize.isZero()) {
12518ed55a54SJohn McCall           llvm::Value *CookieSizeV
12528ed55a54SJohn McCall             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
12538ed55a54SJohn McCall           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
12548ed55a54SJohn McCall         }
12558ed55a54SJohn McCall 
125643dca6a8SEli Friedman         Args.add(RValue::get(Size), size_t);
12578ed55a54SJohn McCall       }
12588ed55a54SJohn McCall 
12598ed55a54SJohn McCall       // Emit the call to delete.
126099cc30c3STilmann Scheller       CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
12618ed55a54SJohn McCall                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
12628ed55a54SJohn McCall                    ReturnValueSlot(), Args, OperatorDelete);
12638ed55a54SJohn McCall     }
12648ed55a54SJohn McCall   };
12658ed55a54SJohn McCall }
12668ed55a54SJohn McCall 
12678ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
12688ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1269284c48ffSJohn McCall                             const CXXDeleteExpr *E,
12708ed55a54SJohn McCall                             llvm::Value *Ptr,
12718ed55a54SJohn McCall                             QualType ElementType) {
12728ed55a54SJohn McCall   llvm::Value *NumElements = 0;
12738ed55a54SJohn McCall   llvm::Value *AllocatedPtr = 0;
12748ed55a54SJohn McCall   CharUnits CookieSize;
1275284c48ffSJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
12768ed55a54SJohn McCall                                       NumElements, AllocatedPtr, CookieSize);
12778ed55a54SJohn McCall 
12788ed55a54SJohn McCall   assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
12798ed55a54SJohn McCall 
12808ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1281284c48ffSJohn McCall   const FunctionDecl *OperatorDelete = E->getOperatorDelete();
12828ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
12838ed55a54SJohn McCall                                            AllocatedPtr, OperatorDelete,
12848ed55a54SJohn McCall                                            NumElements, ElementType,
12858ed55a54SJohn McCall                                            CookieSize);
12868ed55a54SJohn McCall 
12878ed55a54SJohn McCall   if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
12888ed55a54SJohn McCall     if (!RD->hasTrivialDestructor()) {
12898ed55a54SJohn McCall       assert(NumElements && "ReadArrayCookie didn't find element count"
12908ed55a54SJohn McCall                             " for a class with destructor");
12918ed55a54SJohn McCall       CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
12928ed55a54SJohn McCall     }
12938ed55a54SJohn McCall   }
12948ed55a54SJohn McCall 
12958ed55a54SJohn McCall   CGF.PopCleanupBlock();
12968ed55a54SJohn McCall }
12978ed55a54SJohn McCall 
129859486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
129959486a2dSAnders Carlsson 
130059486a2dSAnders Carlsson   // Get at the argument before we performed the implicit conversion
130159486a2dSAnders Carlsson   // to void*.
130259486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
130359486a2dSAnders Carlsson   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
1304e302792bSJohn McCall     if (ICE->getCastKind() != CK_UserDefinedConversion &&
130559486a2dSAnders Carlsson         ICE->getType()->isVoidPointerType())
130659486a2dSAnders Carlsson       Arg = ICE->getSubExpr();
130759486a2dSAnders Carlsson     else
130859486a2dSAnders Carlsson       break;
130959486a2dSAnders Carlsson   }
131059486a2dSAnders Carlsson 
131159486a2dSAnders Carlsson   llvm::Value *Ptr = EmitScalarExpr(Arg);
131259486a2dSAnders Carlsson 
131359486a2dSAnders Carlsson   // Null check the pointer.
131459486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
131559486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
131659486a2dSAnders Carlsson 
131798981b10SAnders Carlsson   llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
131859486a2dSAnders Carlsson 
131959486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
132059486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
132159486a2dSAnders Carlsson 
13228ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
13238ed55a54SJohn McCall   // first non-array element.
13248ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
13258ed55a54SJohn McCall   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
13268ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
13278ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
13288ed55a54SJohn McCall     llvm::SmallVector<llvm::Value*,8> GEP;
132959486a2dSAnders Carlsson 
13308ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
13318ed55a54SJohn McCall 
13328ed55a54SJohn McCall     // For each layer of array type we're pointing at:
13338ed55a54SJohn McCall     while (const ConstantArrayType *Arr
13348ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
13358ed55a54SJohn McCall       // 1. Unpeel the array type.
13368ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
13378ed55a54SJohn McCall 
13388ed55a54SJohn McCall       // 2. GEP to the first element of the array.
13398ed55a54SJohn McCall       GEP.push_back(Zero);
13408ed55a54SJohn McCall     }
13418ed55a54SJohn McCall 
13428ed55a54SJohn McCall     Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
13438ed55a54SJohn McCall   }
13448ed55a54SJohn McCall 
134504f36218SDouglas Gregor   assert(ConvertTypeForMem(DeleteTy) ==
134604f36218SDouglas Gregor          cast<llvm::PointerType>(Ptr->getType())->getElementType());
13478ed55a54SJohn McCall 
134859486a2dSAnders Carlsson   if (E->isArrayForm()) {
1349284c48ffSJohn McCall     EmitArrayDelete(*this, E, Ptr, DeleteTy);
13508ed55a54SJohn McCall   } else {
13518ed55a54SJohn McCall     EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
135259486a2dSAnders Carlsson   }
135359486a2dSAnders Carlsson 
135459486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
135559486a2dSAnders Carlsson }
135659486a2dSAnders Carlsson 
13570c63350bSAnders Carlsson static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
13580c63350bSAnders Carlsson   // void __cxa_bad_typeid();
13590c63350bSAnders Carlsson 
13600c63350bSAnders Carlsson   const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
13610c63350bSAnders Carlsson   const llvm::FunctionType *FTy =
13620c63350bSAnders Carlsson   llvm::FunctionType::get(VoidTy, false);
13630c63350bSAnders Carlsson 
13640c63350bSAnders Carlsson   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
13650c63350bSAnders Carlsson }
13660c63350bSAnders Carlsson 
13670c63350bSAnders Carlsson static void EmitBadTypeidCall(CodeGenFunction &CGF) {
1368bbe277c4SAnders Carlsson   llvm::Value *Fn = getBadTypeidFn(CGF);
1369bbe277c4SAnders Carlsson   CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
13700c63350bSAnders Carlsson   CGF.Builder.CreateUnreachable();
13710c63350bSAnders Carlsson }
13720c63350bSAnders Carlsson 
1373940f02d2SAnders Carlsson static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1374940f02d2SAnders Carlsson                                          const Expr *E,
1375940f02d2SAnders Carlsson                                          const llvm::Type *StdTypeInfoPtrTy) {
1376940f02d2SAnders Carlsson   // Get the vtable pointer.
1377940f02d2SAnders Carlsson   llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1378940f02d2SAnders Carlsson 
1379940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1380940f02d2SAnders Carlsson   //   If the glvalue expression is obtained by applying the unary * operator to
1381940f02d2SAnders Carlsson   //   a pointer and the pointer is a null pointer value, the typeid expression
1382940f02d2SAnders Carlsson   //   throws the std::bad_typeid exception.
1383940f02d2SAnders Carlsson   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1384940f02d2SAnders Carlsson     if (UO->getOpcode() == UO_Deref) {
1385940f02d2SAnders Carlsson       llvm::BasicBlock *BadTypeidBlock =
1386940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.bad_typeid");
1387940f02d2SAnders Carlsson       llvm::BasicBlock *EndBlock =
1388940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.end");
1389940f02d2SAnders Carlsson 
1390940f02d2SAnders Carlsson       llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1391940f02d2SAnders Carlsson       CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1392940f02d2SAnders Carlsson 
1393940f02d2SAnders Carlsson       CGF.EmitBlock(BadTypeidBlock);
1394940f02d2SAnders Carlsson       EmitBadTypeidCall(CGF);
1395940f02d2SAnders Carlsson       CGF.EmitBlock(EndBlock);
1396940f02d2SAnders Carlsson     }
1397940f02d2SAnders Carlsson   }
1398940f02d2SAnders Carlsson 
1399940f02d2SAnders Carlsson   llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1400940f02d2SAnders Carlsson                                         StdTypeInfoPtrTy->getPointerTo());
1401940f02d2SAnders Carlsson 
1402940f02d2SAnders Carlsson   // Load the type info.
1403940f02d2SAnders Carlsson   Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1404940f02d2SAnders Carlsson   return CGF.Builder.CreateLoad(Value);
1405940f02d2SAnders Carlsson }
1406940f02d2SAnders Carlsson 
140759486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
1408940f02d2SAnders Carlsson   const llvm::Type *StdTypeInfoPtrTy =
1409940f02d2SAnders Carlsson     ConvertType(E->getType())->getPointerTo();
1410fd7dfeb7SAnders Carlsson 
14113f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
14123f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
14133f4336cbSAnders Carlsson       CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1414940f02d2SAnders Carlsson     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
14153f4336cbSAnders Carlsson   }
1416fd7dfeb7SAnders Carlsson 
1417940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1418940f02d2SAnders Carlsson   //   When typeid is applied to a glvalue expression whose type is a
1419940f02d2SAnders Carlsson   //   polymorphic class type, the result refers to a std::type_info object
1420940f02d2SAnders Carlsson   //   representing the type of the most derived object (that is, the dynamic
1421940f02d2SAnders Carlsson   //   type) to which the glvalue refers.
1422940f02d2SAnders Carlsson   if (E->getExprOperand()->isGLValue()) {
1423940f02d2SAnders Carlsson     if (const RecordType *RT =
1424940f02d2SAnders Carlsson           E->getExprOperand()->getType()->getAs<RecordType>()) {
142559486a2dSAnders Carlsson       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1426940f02d2SAnders Carlsson       if (RD->isPolymorphic())
1427940f02d2SAnders Carlsson         return EmitTypeidFromVTable(*this, E->getExprOperand(),
1428940f02d2SAnders Carlsson                                     StdTypeInfoPtrTy);
142959486a2dSAnders Carlsson     }
143059486a2dSAnders Carlsson   }
1431940f02d2SAnders Carlsson 
1432940f02d2SAnders Carlsson   QualType OperandTy = E->getExprOperand()->getType();
1433940f02d2SAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1434940f02d2SAnders Carlsson                                StdTypeInfoPtrTy);
143559486a2dSAnders Carlsson }
143659486a2dSAnders Carlsson 
1437882d790fSAnders Carlsson static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1438882d790fSAnders Carlsson   // void *__dynamic_cast(const void *sub,
1439882d790fSAnders Carlsson   //                      const abi::__class_type_info *src,
1440882d790fSAnders Carlsson   //                      const abi::__class_type_info *dst,
1441882d790fSAnders Carlsson   //                      std::ptrdiff_t src2dst_offset);
1442882d790fSAnders Carlsson 
1443882d790fSAnders Carlsson   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1444882d790fSAnders Carlsson   const llvm::Type *PtrDiffTy =
1445882d790fSAnders Carlsson     CGF.ConvertType(CGF.getContext().getPointerDiffType());
1446882d790fSAnders Carlsson 
1447882d790fSAnders Carlsson   const llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1448882d790fSAnders Carlsson 
1449882d790fSAnders Carlsson   const llvm::FunctionType *FTy =
1450882d790fSAnders Carlsson     llvm::FunctionType::get(Int8PtrTy, Args, false);
1451882d790fSAnders Carlsson 
1452882d790fSAnders Carlsson   return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1453882d790fSAnders Carlsson }
1454882d790fSAnders Carlsson 
1455882d790fSAnders Carlsson static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1456882d790fSAnders Carlsson   // void __cxa_bad_cast();
1457882d790fSAnders Carlsson 
1458882d790fSAnders Carlsson   const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1459882d790fSAnders Carlsson   const llvm::FunctionType *FTy =
1460882d790fSAnders Carlsson     llvm::FunctionType::get(VoidTy, false);
1461882d790fSAnders Carlsson 
1462882d790fSAnders Carlsson   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1463882d790fSAnders Carlsson }
1464882d790fSAnders Carlsson 
1465c1c9971cSAnders Carlsson static void EmitBadCastCall(CodeGenFunction &CGF) {
1466bbe277c4SAnders Carlsson   llvm::Value *Fn = getBadCastFn(CGF);
1467bbe277c4SAnders Carlsson   CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
1468c1c9971cSAnders Carlsson   CGF.Builder.CreateUnreachable();
1469c1c9971cSAnders Carlsson }
1470c1c9971cSAnders Carlsson 
1471882d790fSAnders Carlsson static llvm::Value *
1472882d790fSAnders Carlsson EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1473882d790fSAnders Carlsson                     QualType SrcTy, QualType DestTy,
1474882d790fSAnders Carlsson                     llvm::BasicBlock *CastEnd) {
1475882d790fSAnders Carlsson   const llvm::Type *PtrDiffLTy =
1476882d790fSAnders Carlsson     CGF.ConvertType(CGF.getContext().getPointerDiffType());
1477882d790fSAnders Carlsson   const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1478882d790fSAnders Carlsson 
1479882d790fSAnders Carlsson   if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1480882d790fSAnders Carlsson     if (PTy->getPointeeType()->isVoidType()) {
1481882d790fSAnders Carlsson       // C++ [expr.dynamic.cast]p7:
1482882d790fSAnders Carlsson       //   If T is "pointer to cv void," then the result is a pointer to the
1483882d790fSAnders Carlsson       //   most derived object pointed to by v.
1484882d790fSAnders Carlsson 
1485882d790fSAnders Carlsson       // Get the vtable pointer.
1486882d790fSAnders Carlsson       llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1487882d790fSAnders Carlsson 
1488882d790fSAnders Carlsson       // Get the offset-to-top from the vtable.
1489882d790fSAnders Carlsson       llvm::Value *OffsetToTop =
1490882d790fSAnders Carlsson         CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1491882d790fSAnders Carlsson       OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1492882d790fSAnders Carlsson 
1493882d790fSAnders Carlsson       // Finally, add the offset to the pointer.
1494882d790fSAnders Carlsson       Value = CGF.EmitCastToVoidPtr(Value);
1495882d790fSAnders Carlsson       Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1496882d790fSAnders Carlsson 
1497882d790fSAnders Carlsson       return CGF.Builder.CreateBitCast(Value, DestLTy);
1498882d790fSAnders Carlsson     }
1499882d790fSAnders Carlsson   }
1500882d790fSAnders Carlsson 
1501882d790fSAnders Carlsson   QualType SrcRecordTy;
1502882d790fSAnders Carlsson   QualType DestRecordTy;
1503882d790fSAnders Carlsson 
1504882d790fSAnders Carlsson   if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1505882d790fSAnders Carlsson     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1506882d790fSAnders Carlsson     DestRecordTy = DestPTy->getPointeeType();
1507882d790fSAnders Carlsson   } else {
1508882d790fSAnders Carlsson     SrcRecordTy = SrcTy;
1509882d790fSAnders Carlsson     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1510882d790fSAnders Carlsson   }
1511882d790fSAnders Carlsson 
1512882d790fSAnders Carlsson   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1513882d790fSAnders Carlsson   assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1514882d790fSAnders Carlsson 
1515882d790fSAnders Carlsson   llvm::Value *SrcRTTI =
1516882d790fSAnders Carlsson     CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1517882d790fSAnders Carlsson   llvm::Value *DestRTTI =
1518882d790fSAnders Carlsson     CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1519882d790fSAnders Carlsson 
1520882d790fSAnders Carlsson   // FIXME: Actually compute a hint here.
1521882d790fSAnders Carlsson   llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1522882d790fSAnders Carlsson 
1523882d790fSAnders Carlsson   // Emit the call to __dynamic_cast.
1524882d790fSAnders Carlsson   Value = CGF.EmitCastToVoidPtr(Value);
1525882d790fSAnders Carlsson   Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1526882d790fSAnders Carlsson                                   SrcRTTI, DestRTTI, OffsetHint);
1527882d790fSAnders Carlsson   Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1528882d790fSAnders Carlsson 
1529882d790fSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
1530882d790fSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
1531882d790fSAnders Carlsson   if (DestTy->isReferenceType()) {
1532882d790fSAnders Carlsson     llvm::BasicBlock *BadCastBlock =
1533882d790fSAnders Carlsson       CGF.createBasicBlock("dynamic_cast.bad_cast");
1534882d790fSAnders Carlsson 
1535882d790fSAnders Carlsson     llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1536882d790fSAnders Carlsson     CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1537882d790fSAnders Carlsson 
1538882d790fSAnders Carlsson     CGF.EmitBlock(BadCastBlock);
1539c1c9971cSAnders Carlsson     EmitBadCastCall(CGF);
1540882d790fSAnders Carlsson   }
1541882d790fSAnders Carlsson 
1542882d790fSAnders Carlsson   return Value;
1543882d790fSAnders Carlsson }
1544882d790fSAnders Carlsson 
1545c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1546c1c9971cSAnders Carlsson                                           QualType DestTy) {
1547c1c9971cSAnders Carlsson   const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1548c1c9971cSAnders Carlsson   if (DestTy->isPointerType())
1549c1c9971cSAnders Carlsson     return llvm::Constant::getNullValue(DestLTy);
1550c1c9971cSAnders Carlsson 
1551c1c9971cSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
1552c1c9971cSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
1553c1c9971cSAnders Carlsson   EmitBadCastCall(CGF);
1554c1c9971cSAnders Carlsson 
1555c1c9971cSAnders Carlsson   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1556c1c9971cSAnders Carlsson   return llvm::UndefValue::get(DestLTy);
1557c1c9971cSAnders Carlsson }
1558c1c9971cSAnders Carlsson 
1559882d790fSAnders Carlsson llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
156059486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
15613f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
15623f4336cbSAnders Carlsson 
1563c1c9971cSAnders Carlsson   if (DCE->isAlwaysNull())
1564c1c9971cSAnders Carlsson     return EmitDynamicCastToNull(*this, DestTy);
1565c1c9971cSAnders Carlsson 
1566c1c9971cSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
1567c1c9971cSAnders Carlsson 
1568882d790fSAnders Carlsson   // C++ [expr.dynamic.cast]p4:
1569882d790fSAnders Carlsson   //   If the value of v is a null pointer value in the pointer case, the result
1570882d790fSAnders Carlsson   //   is the null pointer value of type T.
1571882d790fSAnders Carlsson   bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
157259486a2dSAnders Carlsson 
1573882d790fSAnders Carlsson   llvm::BasicBlock *CastNull = 0;
1574882d790fSAnders Carlsson   llvm::BasicBlock *CastNotNull = 0;
1575882d790fSAnders Carlsson   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1576fa8b4955SDouglas Gregor 
1577882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1578882d790fSAnders Carlsson     CastNull = createBasicBlock("dynamic_cast.null");
1579882d790fSAnders Carlsson     CastNotNull = createBasicBlock("dynamic_cast.notnull");
1580882d790fSAnders Carlsson 
1581882d790fSAnders Carlsson     llvm::Value *IsNull = Builder.CreateIsNull(Value);
1582882d790fSAnders Carlsson     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1583882d790fSAnders Carlsson     EmitBlock(CastNotNull);
158459486a2dSAnders Carlsson   }
158559486a2dSAnders Carlsson 
1586882d790fSAnders Carlsson   Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
15873f4336cbSAnders Carlsson 
1588882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1589882d790fSAnders Carlsson     EmitBranch(CastEnd);
159059486a2dSAnders Carlsson 
1591882d790fSAnders Carlsson     EmitBlock(CastNull);
1592882d790fSAnders Carlsson     EmitBranch(CastEnd);
159359486a2dSAnders Carlsson   }
159459486a2dSAnders Carlsson 
1595882d790fSAnders Carlsson   EmitBlock(CastEnd);
159659486a2dSAnders Carlsson 
1597882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1598882d790fSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1599882d790fSAnders Carlsson     PHI->addIncoming(Value, CastNotNull);
1600882d790fSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
160159486a2dSAnders Carlsson 
1602882d790fSAnders Carlsson     Value = PHI;
160359486a2dSAnders Carlsson   }
160459486a2dSAnders Carlsson 
1605882d790fSAnders Carlsson   return Value;
160659486a2dSAnders Carlsson }
1607