blob: cf5d9abe8d1cabb8588dffb3b7f52f52c1e0055b [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlsson16d81b82009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Fariborz Jahanian842ddd02010-05-20 21:38:57 +000015#include "CGObjCRuntime.h"
Anders Carlsson16d81b82009-09-22 22:53:17 +000016using namespace clang;
17using namespace CodeGen;
18
Anders Carlsson3b5ad222010-01-01 20:29:01 +000019RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
20 llvm::Value *Callee,
21 ReturnValueSlot ReturnValue,
22 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000023 llvm::Value *VTT,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000024 CallExpr::const_arg_iterator ArgBeg,
25 CallExpr::const_arg_iterator ArgEnd) {
26 assert(MD->isInstance() &&
27 "Trying to emit a member call expr on a static method!");
28
29 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
30
31 CallArgList Args;
32
33 // Push the this ptr.
34 Args.push_back(std::make_pair(RValue::get(This),
35 MD->getThisType(getContext())));
36
Anders Carlssonc997d422010-01-02 01:01:18 +000037 // If there is a VTT parameter, emit it.
38 if (VTT) {
39 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
40 Args.push_back(std::make_pair(RValue::get(VTT), T));
41 }
42
Anders Carlsson3b5ad222010-01-01 20:29:01 +000043 // And the rest of the call args
44 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
45
John McCall04a67a62010-02-05 21:31:56 +000046 QualType ResultType = FPT->getResultType();
47 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +000048 FPT->getExtInfo()),
49 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000050}
51
52/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
53/// expr can be devirtualized.
54static bool canDevirtualizeMemberFunctionCalls(const Expr *Base) {
55 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
56 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
57 // This is a record decl. We know the type and can devirtualize it.
58 return VD->getType()->isRecordType();
59 }
60
61 return false;
62 }
63
64 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +000065 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +000066 return true;
67
68 // And calls on bound temporaries.
69 if (isa<CXXBindTemporaryExpr>(Base))
70 return true;
71
72 // Check if this is a call expr that returns a record type.
73 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
74 return CE->getCallReturnType()->isRecordType();
75
76 // We can't devirtualize the call.
77 return false;
78}
79
80RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
81 ReturnValueSlot ReturnValue) {
82 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
83 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
84
85 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
86 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
87
88 if (MD->isStatic()) {
89 // The method is static, emit it as we would a regular call.
90 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
91 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
92 ReturnValue, CE->arg_begin(), CE->arg_end());
93 }
94
95 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
96
97 const llvm::Type *Ty =
98 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
99 FPT->isVariadic());
100 llvm::Value *This;
101
102 if (ME->isArrow())
103 This = EmitScalarExpr(ME->getBase());
104 else {
105 LValue BaseLV = EmitLValue(ME->getBase());
106 This = BaseLV.getAddress();
107 }
108
109 if (MD->isCopyAssignment() && MD->isTrivial()) {
110 // We don't like to generate the trivial copy assignment operator when
111 // it isn't necessary; just produce the proper effect here.
112 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
113 EmitAggregateCopy(This, RHS, CE->getType());
114 return RValue::get(This);
115 }
116
117 // C++ [class.virtual]p12:
118 // Explicit qualification with the scope operator (5.1) suppresses the
119 // virtual call mechanism.
120 //
121 // We also don't emit a virtual call if the base expression has a record type
122 // because then we know what the type is.
123 llvm::Value *Callee;
124 if (const CXXDestructorDecl *Destructor
125 = dyn_cast<CXXDestructorDecl>(MD)) {
126 if (Destructor->isTrivial())
127 return RValue::get(0);
128 if (MD->isVirtual() && !ME->hasQualifier() &&
129 !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
130 Callee = BuildVirtualCall(Destructor, Dtor_Complete, This, Ty);
131 } else {
132 Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty);
133 }
134 } else if (MD->isVirtual() && !ME->hasQualifier() &&
135 !canDevirtualizeMemberFunctionCalls(ME->getBase())) {
136 Callee = BuildVirtualCall(MD, This, Ty);
137 } else {
138 Callee = CGM.GetAddrOfFunction(MD, Ty);
139 }
140
Anders Carlssonc997d422010-01-02 01:01:18 +0000141 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000142 CE->arg_begin(), CE->arg_end());
143}
144
145RValue
146CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
147 ReturnValueSlot ReturnValue) {
148 const BinaryOperator *BO =
149 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
150 const Expr *BaseExpr = BO->getLHS();
151 const Expr *MemFnExpr = BO->getRHS();
152
153 const MemberPointerType *MPT =
154 MemFnExpr->getType()->getAs<MemberPointerType>();
155 const FunctionProtoType *FPT =
156 MPT->getPointeeType()->getAs<FunctionProtoType>();
157 const CXXRecordDecl *RD =
158 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
159
160 const llvm::FunctionType *FTy =
161 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
162 FPT->isVariadic());
163
Anders Carlsson51591be2010-02-04 17:08:48 +0000164 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000165
166 // Get the member function pointer.
Daniel Dunbar195337d2010-02-09 02:48:28 +0000167 llvm::Value *MemFnPtr = CreateMemTemp(MemFnExpr->getType(), "mem.fn");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000168 EmitAggExpr(MemFnExpr, MemFnPtr, /*VolatileDest=*/false);
169
170 // Emit the 'this' pointer.
171 llvm::Value *This;
172
173 if (BO->getOpcode() == BinaryOperator::PtrMemI)
174 This = EmitScalarExpr(BaseExpr);
175 else
176 This = EmitLValue(BaseExpr).getAddress();
177
178 // Adjust it.
179 llvm::Value *Adj = Builder.CreateStructGEP(MemFnPtr, 1);
180 Adj = Builder.CreateLoad(Adj, "mem.fn.adj");
181
182 llvm::Value *Ptr = Builder.CreateBitCast(This, Int8PtrTy, "ptr");
183 Ptr = Builder.CreateGEP(Ptr, Adj, "adj");
184
185 This = Builder.CreateBitCast(Ptr, This->getType(), "this");
186
187 llvm::Value *FnPtr = Builder.CreateStructGEP(MemFnPtr, 0, "mem.fn.ptr");
188
189 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
190
191 llvm::Value *FnAsInt = Builder.CreateLoad(FnPtr, "fn");
192
193 // If the LSB in the function pointer is 1, the function pointer points to
194 // a virtual function.
195 llvm::Value *IsVirtual
196 = Builder.CreateAnd(FnAsInt, llvm::ConstantInt::get(PtrDiffTy, 1),
197 "and");
198
199 IsVirtual = Builder.CreateTrunc(IsVirtual,
200 llvm::Type::getInt1Ty(VMContext));
201
202 llvm::BasicBlock *FnVirtual = createBasicBlock("fn.virtual");
203 llvm::BasicBlock *FnNonVirtual = createBasicBlock("fn.nonvirtual");
204 llvm::BasicBlock *FnEnd = createBasicBlock("fn.end");
205
206 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
207 EmitBlock(FnVirtual);
208
Anders Carlsson046c2942010-04-17 20:15:18 +0000209 const llvm::Type *VTableTy =
Anders Carlsson51591be2010-02-04 17:08:48 +0000210 FTy->getPointerTo()->getPointerTo();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000211
Anders Carlsson046c2942010-04-17 20:15:18 +0000212 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
213 VTable = Builder.CreateLoad(VTable);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000214
Anders Carlsson046c2942010-04-17 20:15:18 +0000215 VTable = Builder.CreateBitCast(VTable, Int8PtrTy);
216 llvm::Value *VTableOffset =
Anders Carlsson51591be2010-02-04 17:08:48 +0000217 Builder.CreateSub(FnAsInt, llvm::ConstantInt::get(PtrDiffTy, 1));
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000218
Anders Carlsson046c2942010-04-17 20:15:18 +0000219 VTable = Builder.CreateGEP(VTable, VTableOffset, "fn");
220 VTable = Builder.CreateBitCast(VTable, VTableTy);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000221
Anders Carlsson046c2942010-04-17 20:15:18 +0000222 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "virtualfn");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000223
224 EmitBranch(FnEnd);
225 EmitBlock(FnNonVirtual);
226
227 // If the function is not virtual, just load the pointer.
228 llvm::Value *NonVirtualFn = Builder.CreateLoad(FnPtr, "fn");
229 NonVirtualFn = Builder.CreateIntToPtr(NonVirtualFn, FTy->getPointerTo());
230
231 EmitBlock(FnEnd);
232
233 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo());
234 Callee->reserveOperandSpace(2);
235 Callee->addIncoming(VirtualFn, FnVirtual);
236 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
237
238 CallArgList Args;
239
240 QualType ThisType =
241 getContext().getPointerType(getContext().getTagDeclType(RD));
242
243 // Push the this ptr.
244 Args.push_back(std::make_pair(RValue::get(This), ThisType));
245
246 // And the rest of the call args
247 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall04a67a62010-02-05 21:31:56 +0000248 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
249 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000250 ReturnValue, Args);
251}
252
253RValue
254CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
255 const CXXMethodDecl *MD,
256 ReturnValueSlot ReturnValue) {
257 assert(MD->isInstance() &&
258 "Trying to emit a member call expr on a static method!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000259 if (MD->isCopyAssignment()) {
260 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
261 if (ClassDecl->hasTrivialCopyAssignment()) {
262 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
263 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Fariborz Jahanianb3ebe942010-05-10 22:57:35 +0000264 LValue LV = EmitLValue(E->getArg(0));
265 llvm::Value *This;
266 if (LV.isPropertyRef()) {
Fariborz Jahanianc9a8fa42010-05-16 00:10:46 +0000267 llvm::Value *AggLoc = CreateMemTemp(E->getArg(1)->getType());
Fariborz Jahanian0ca0b1f2010-05-15 23:05:52 +0000268 EmitAggExpr(E->getArg(1), AggLoc, false /*VolatileDest*/);
269 EmitObjCPropertySet(LV.getPropertyRefExpr(),
270 RValue::getAggregate(AggLoc, false /*VolatileDest*/));
271 return RValue::getAggregate(0, false);
Fariborz Jahanianb3ebe942010-05-10 22:57:35 +0000272 }
273 else
274 This = LV.getAddress();
275
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000276 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
277 QualType Ty = E->getType();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000278 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000279 return RValue::get(This);
280 }
281 }
282
283 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
284 const llvm::Type *Ty =
285 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
286 FPT->isVariadic());
Fariborz Jahanianbbb52242010-05-07 18:56:13 +0000287 LValue LV = EmitLValue(E->getArg(0));
288 llvm::Value *This;
289 if (LV.isPropertyRef()) {
Fariborz Jahanian1d49f212010-05-20 16:46:55 +0000290 RValue RV = EmitLoadOfPropertyRefLValue(LV, E->getArg(0)->getType());
291 assert (!RV.isScalar() && "EmitCXXOperatorMemberCallExpr");
292 This = RV.getAggregateAddr();
Fariborz Jahanianbbb52242010-05-07 18:56:13 +0000293 }
294 else
295 This = LV.getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000296
297 llvm::Value *Callee;
298 if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0)))
299 Callee = BuildVirtualCall(MD, This, Ty);
300 else
301 Callee = CGM.GetAddrOfFunction(MD, Ty);
302
Anders Carlssonc997d422010-01-02 01:01:18 +0000303 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000304 E->arg_begin() + 1, E->arg_end());
305}
306
307void
308CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
309 const CXXConstructExpr *E) {
310 assert(Dest && "Must have a destination!");
311 const CXXConstructorDecl *CD = E->getConstructor();
312 const ConstantArrayType *Array =
313 getContext().getAsConstantArrayType(E->getType());
314 // For a copy constructor, even if it is trivial, must fall thru so
315 // its argument is code-gen'ed.
316 if (!CD->isCopyConstructor()) {
317 QualType InitType = E->getType();
318 if (Array)
319 InitType = getContext().getBaseElementType(Array);
320 const CXXRecordDecl *RD =
321 cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl());
322 if (RD->hasTrivialConstructor())
323 return;
324 }
325 // Code gen optimization to eliminate copy constructor and return
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000326 // its first argument instead, if in fact that argument is a temporary
327 // object.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000328 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000329 if (const Expr *Arg = E->getArg(0)->getTemporaryObject()) {
330 EmitAggExpr(Arg, Dest, false);
331 return;
332 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000333 }
334 if (Array) {
335 QualType BaseElementTy = getContext().getBaseElementType(Array);
336 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
337 BasePtr = llvm::PointerType::getUnqual(BasePtr);
338 llvm::Value *BaseAddrPtr =
Anders Carlsson43db20e2010-05-01 17:02:18 +0000339 Builder.CreateBitCast(Dest, BasePtr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000340
341 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
342 E->arg_begin(), E->arg_end());
343 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000344 else {
345 CXXCtorType Type =
346 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
347 ? Ctor_Complete : Ctor_Base;
348 bool ForVirtualBase =
349 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
350
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000351 // Call the constructor.
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000352 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000353 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000354 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000355}
356
Ken Dyckcaf647c2010-01-26 19:44:24 +0000357static CharUnits CalculateCookiePadding(ASTContext &Ctx, QualType ElementType) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000358 const RecordType *RT = ElementType->getAs<RecordType>();
Anders Carlssona4d4c012009-09-23 16:07:23 +0000359 if (!RT)
Ken Dyckcaf647c2010-01-26 19:44:24 +0000360 return CharUnits::Zero();
Anders Carlssona4d4c012009-09-23 16:07:23 +0000361
362 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
363 if (!RD)
Ken Dyckcaf647c2010-01-26 19:44:24 +0000364 return CharUnits::Zero();
Anders Carlssona4d4c012009-09-23 16:07:23 +0000365
366 // Check if the class has a trivial destructor.
367 if (RD->hasTrivialDestructor()) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000368 // Check if the usual deallocation function takes two arguments.
Anders Carlsson710f7052009-12-13 20:10:12 +0000369 const CXXMethodDecl *UsualDeallocationFunction = 0;
370
Anders Carlsson871d0782009-12-13 20:04:38 +0000371 DeclarationName OpName =
372 Ctx.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
Anders Carlsson871d0782009-12-13 20:04:38 +0000373 DeclContext::lookup_const_iterator Op, OpEnd;
374 for (llvm::tie(Op, OpEnd) = RD->lookup(OpName);
375 Op != OpEnd; ++Op) {
Anders Carlsson710f7052009-12-13 20:10:12 +0000376 const CXXMethodDecl *Delete = cast<CXXMethodDecl>(*Op);
Anders Carlsson871d0782009-12-13 20:04:38 +0000377
378 if (Delete->isUsualDeallocationFunction()) {
Anders Carlsson710f7052009-12-13 20:10:12 +0000379 UsualDeallocationFunction = Delete;
Anders Carlsson871d0782009-12-13 20:04:38 +0000380 break;
381 }
382 }
Anders Carlsson710f7052009-12-13 20:10:12 +0000383
384 // No usual deallocation function, we don't need a cookie.
385 if (!UsualDeallocationFunction)
Ken Dyckcaf647c2010-01-26 19:44:24 +0000386 return CharUnits::Zero();
Anders Carlsson710f7052009-12-13 20:10:12 +0000387
388 // The usual deallocation function doesn't take a size_t argument, so we
389 // don't need a cookie.
390 if (UsualDeallocationFunction->getNumParams() == 1)
Ken Dyckcaf647c2010-01-26 19:44:24 +0000391 return CharUnits::Zero();
Anders Carlsson710f7052009-12-13 20:10:12 +0000392
393 assert(UsualDeallocationFunction->getNumParams() == 2 &&
394 "Unexpected deallocation function type!");
395 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000396
Anders Carlsson871d0782009-12-13 20:04:38 +0000397 // Padding is the maximum of sizeof(size_t) and alignof(ElementType)
Ken Dyckcaf647c2010-01-26 19:44:24 +0000398 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
399 Ctx.getTypeAlignInChars(ElementType));
Anders Carlsson871d0782009-12-13 20:04:38 +0000400}
401
Ken Dyckcaf647c2010-01-26 19:44:24 +0000402static CharUnits CalculateCookiePadding(ASTContext &Ctx, const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000403 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000404 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000405
Anders Carlssondd937552009-12-13 20:34:34 +0000406 // No cookie is required if the new operator being used is
407 // ::operator new[](size_t, void*).
408 const FunctionDecl *OperatorNew = E->getOperatorNew();
409 if (OperatorNew->getDeclContext()->getLookupContext()->isFileContext()) {
410 if (OperatorNew->getNumParams() == 2) {
411 CanQualType ParamType =
412 Ctx.getCanonicalType(OperatorNew->getParamDecl(1)->getType());
413
414 if (ParamType == Ctx.VoidPtrTy)
Ken Dyckcaf647c2010-01-26 19:44:24 +0000415 return CharUnits::Zero();
Anders Carlssondd937552009-12-13 20:34:34 +0000416 }
417 }
418
Anders Carlsson871d0782009-12-13 20:04:38 +0000419 return CalculateCookiePadding(Ctx, E->getAllocatedType());
Anders Carlssona4d4c012009-09-23 16:07:23 +0000420}
421
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000422static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
423 CodeGenFunction &CGF,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000424 const CXXNewExpr *E,
425 llvm::Value *& NumElements) {
426 QualType Type = E->getAllocatedType();
Ken Dyckcaf647c2010-01-26 19:44:24 +0000427 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(Type);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000428 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
429
430 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000431 return llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
Anders Carlssona4d4c012009-09-23 16:07:23 +0000432
Ken Dyckcaf647c2010-01-26 19:44:24 +0000433 CharUnits CookiePadding = CalculateCookiePadding(CGF.getContext(), E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000434
435 Expr::EvalResult Result;
436 if (E->getArraySize()->Evaluate(Result, CGF.getContext()) &&
437 !Result.HasSideEffects && Result.Val.isInt()) {
438
Ken Dyckcaf647c2010-01-26 19:44:24 +0000439 CharUnits AllocSize =
440 Result.Val.getInt().getZExtValue() * TypeSize + CookiePadding;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000441
442 NumElements =
443 llvm::ConstantInt::get(SizeTy, Result.Val.getInt().getZExtValue());
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000444 while (const ArrayType *AType = Context.getAsArrayType(Type)) {
445 const llvm::ArrayType *llvmAType =
446 cast<llvm::ArrayType>(CGF.ConvertType(Type));
447 NumElements =
448 CGF.Builder.CreateMul(NumElements,
449 llvm::ConstantInt::get(
450 SizeTy, llvmAType->getNumElements()));
451 Type = AType->getElementType();
452 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000453
Ken Dyckcaf647c2010-01-26 19:44:24 +0000454 return llvm::ConstantInt::get(SizeTy, AllocSize.getQuantity());
Anders Carlssona4d4c012009-09-23 16:07:23 +0000455 }
456
457 // Emit the array size expression.
458 NumElements = CGF.EmitScalarExpr(E->getArraySize());
459
460 // Multiply with the type size.
461 llvm::Value *V =
462 CGF.Builder.CreateMul(NumElements,
Ken Dyckcaf647c2010-01-26 19:44:24 +0000463 llvm::ConstantInt::get(SizeTy,
464 TypeSize.getQuantity()));
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000465
466 while (const ArrayType *AType = Context.getAsArrayType(Type)) {
467 const llvm::ArrayType *llvmAType =
468 cast<llvm::ArrayType>(CGF.ConvertType(Type));
469 NumElements =
470 CGF.Builder.CreateMul(NumElements,
471 llvm::ConstantInt::get(
472 SizeTy, llvmAType->getNumElements()));
473 Type = AType->getElementType();
474 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000475
476 // And add the cookie padding if necessary.
Ken Dyckcaf647c2010-01-26 19:44:24 +0000477 if (!CookiePadding.isZero())
478 V = CGF.Builder.CreateAdd(V,
479 llvm::ConstantInt::get(SizeTy, CookiePadding.getQuantity()));
Anders Carlssona4d4c012009-09-23 16:07:23 +0000480
481 return V;
482}
483
484static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
485 llvm::Value *NewPtr,
486 llvm::Value *NumElements) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000487 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000488 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
489 if (!Ctor->getParent()->hasTrivialConstructor())
490 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
491 E->constructor_arg_begin(),
492 E->constructor_arg_end());
493 return;
494 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000495 }
496
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000497 QualType AllocType = E->getAllocatedType();
498
499 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000500 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
501 NewPtr, E->constructor_arg_begin(),
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000502 E->constructor_arg_end());
503
504 return;
505 }
506
507 // We have a POD type.
508 if (E->getNumConstructorArgs() == 0)
509 return;
510
511 assert(E->getNumConstructorArgs() == 1 &&
512 "Can only have one argument to initializer of POD type.");
513
514 const Expr *Init = E->getConstructorArg(0);
515
516 if (!CGF.hasAggregateLLVMType(AllocType))
517 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
518 AllocType.isVolatileQualified(), AllocType);
519 else if (AllocType->isAnyComplexType())
520 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
521 AllocType.isVolatileQualified());
522 else
523 CGF.EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssona4d4c012009-09-23 16:07:23 +0000524}
525
Anders Carlsson16d81b82009-09-22 22:53:17 +0000526llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlsson16d81b82009-09-22 22:53:17 +0000527 QualType AllocType = E->getAllocatedType();
528 FunctionDecl *NewFD = E->getOperatorNew();
529 const FunctionProtoType *NewFTy = NewFD->getType()->getAs<FunctionProtoType>();
530
531 CallArgList NewArgs;
532
533 // The allocation size is the first argument.
534 QualType SizeTy = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000535
Anders Carlssona4d4c012009-09-23 16:07:23 +0000536 llvm::Value *NumElements = 0;
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000537 llvm::Value *AllocSize = EmitCXXNewAllocSize(getContext(),
538 *this, E, NumElements);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000539
Anders Carlsson16d81b82009-09-22 22:53:17 +0000540 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
541
542 // Emit the rest of the arguments.
543 // FIXME: Ideally, this should just use EmitCallArgs.
544 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
545
546 // First, use the types from the function type.
547 // We start at 1 here because the first argument (the allocation size)
548 // has already been emitted.
549 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
550 QualType ArgType = NewFTy->getArgType(i);
551
552 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
553 getTypePtr() ==
554 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
555 "type mismatch in call argument!");
556
557 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
558 ArgType));
559
560 }
561
562 // Either we've emitted all the call args, or we have a call to a
563 // variadic function.
564 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
565 "Extra arguments in non-variadic function!");
566
567 // If we still have any arguments, emit them using the type of the argument.
568 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
569 NewArg != NewArgEnd; ++NewArg) {
570 QualType ArgType = NewArg->getType();
571 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
572 ArgType));
573 }
574
575 // Emit the call to new.
576 RValue RV =
John McCall04a67a62010-02-05 21:31:56 +0000577 EmitCall(CGM.getTypes().getFunctionInfo(NewArgs, NewFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000578 CGM.GetAddrOfFunction(NewFD), ReturnValueSlot(), NewArgs, NewFD);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000579
580 // If an allocation function is declared with an empty exception specification
581 // it returns null to indicate failure to allocate storage. [expr.new]p13.
582 // (We don't need to check for null when there's no new initializer and
583 // we're allocating a POD type).
584 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
585 !(AllocType->isPODType() && !E->hasInitializer());
586
587 llvm::BasicBlock *NewNull = 0;
588 llvm::BasicBlock *NewNotNull = 0;
589 llvm::BasicBlock *NewEnd = 0;
590
591 llvm::Value *NewPtr = RV.getScalarVal();
592
593 if (NullCheckResult) {
594 NewNull = createBasicBlock("new.null");
595 NewNotNull = createBasicBlock("new.notnull");
596 NewEnd = createBasicBlock("new.end");
597
598 llvm::Value *IsNull =
599 Builder.CreateICmpEQ(NewPtr,
600 llvm::Constant::getNullValue(NewPtr->getType()),
601 "isnull");
602
603 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
604 EmitBlock(NewNotNull);
605 }
Ken Dyckcaf647c2010-01-26 19:44:24 +0000606
607 CharUnits CookiePadding = CalculateCookiePadding(getContext(), E);
608 if (!CookiePadding.isZero()) {
609 CharUnits CookieOffset =
610 CookiePadding - getContext().getTypeSizeInChars(SizeTy);
Anders Carlsson6ac5fc42009-09-23 18:59:48 +0000611
612 llvm::Value *NumElementsPtr =
Ken Dyckcaf647c2010-01-26 19:44:24 +0000613 Builder.CreateConstInBoundsGEP1_64(NewPtr, CookieOffset.getQuantity());
Anders Carlsson6ac5fc42009-09-23 18:59:48 +0000614
615 NumElementsPtr = Builder.CreateBitCast(NumElementsPtr,
616 ConvertType(SizeTy)->getPointerTo());
617 Builder.CreateStore(NumElements, NumElementsPtr);
618
619 // Now add the padding to the new ptr.
Ken Dyckcaf647c2010-01-26 19:44:24 +0000620 NewPtr = Builder.CreateConstInBoundsGEP1_64(NewPtr,
621 CookiePadding.getQuantity());
Anders Carlsson6ac5fc42009-09-23 18:59:48 +0000622 }
623
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000624 if (AllocType->isArrayType()) {
625 while (const ArrayType *AType = getContext().getAsArrayType(AllocType))
626 AllocType = AType->getElementType();
627 NewPtr =
628 Builder.CreateBitCast(NewPtr,
629 ConvertType(getContext().getPointerType(AllocType)));
630 EmitNewInitializer(*this, E, NewPtr, NumElements);
631 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
632 }
633 else {
634 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
635 EmitNewInitializer(*this, E, NewPtr, NumElements);
636 }
637
Anders Carlsson16d81b82009-09-22 22:53:17 +0000638 if (NullCheckResult) {
639 Builder.CreateBr(NewEnd);
Eli Friedman7f1de452009-11-10 22:39:09 +0000640 NewNotNull = Builder.GetInsertBlock();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000641 EmitBlock(NewNull);
642 Builder.CreateBr(NewEnd);
643 EmitBlock(NewEnd);
644
645 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
646 PHI->reserveOperandSpace(2);
647 PHI->addIncoming(NewPtr, NewNotNull);
648 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
649
650 NewPtr = PHI;
651 }
652
653 return NewPtr;
654}
655
Anders Carlsson871d0782009-12-13 20:04:38 +0000656static std::pair<llvm::Value *, llvm::Value *>
657GetAllocatedObjectPtrAndNumElements(CodeGenFunction &CGF,
658 llvm::Value *Ptr, QualType DeleteTy) {
659 QualType SizeTy = CGF.getContext().getSizeType();
660 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy);
661
Ken Dyckcaf647c2010-01-26 19:44:24 +0000662 CharUnits DeleteTypeAlign = CGF.getContext().getTypeAlignInChars(DeleteTy);
663 CharUnits CookiePadding =
664 std::max(CGF.getContext().getTypeSizeInChars(SizeTy),
665 DeleteTypeAlign);
666 assert(!CookiePadding.isZero() && "CookiePadding should not be 0.");
Anders Carlsson871d0782009-12-13 20:04:38 +0000667
668 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Ken Dyckcaf647c2010-01-26 19:44:24 +0000669 CharUnits CookieOffset =
670 CookiePadding - CGF.getContext().getTypeSizeInChars(SizeTy);
Anders Carlsson871d0782009-12-13 20:04:38 +0000671
672 llvm::Value *AllocatedObjectPtr = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
673 AllocatedObjectPtr =
674 CGF.Builder.CreateConstInBoundsGEP1_64(AllocatedObjectPtr,
Ken Dyckcaf647c2010-01-26 19:44:24 +0000675 -CookiePadding.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +0000676
677 llvm::Value *NumElementsPtr =
678 CGF.Builder.CreateConstInBoundsGEP1_64(AllocatedObjectPtr,
Ken Dyckcaf647c2010-01-26 19:44:24 +0000679 CookieOffset.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +0000680 NumElementsPtr =
681 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo());
682
683 llvm::Value *NumElements = CGF.Builder.CreateLoad(NumElementsPtr);
684 NumElements =
685 CGF.Builder.CreateIntCast(NumElements, SizeLTy, /*isSigned=*/false);
686
687 return std::make_pair(AllocatedObjectPtr, NumElements);
688}
689
Eli Friedman5fe05982009-11-18 00:50:08 +0000690void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
691 llvm::Value *Ptr,
692 QualType DeleteTy) {
693 const FunctionProtoType *DeleteFTy =
694 DeleteFD->getType()->getAs<FunctionProtoType>();
695
696 CallArgList DeleteArgs;
697
Anders Carlsson871d0782009-12-13 20:04:38 +0000698 // Check if we need to pass the size to the delete operator.
699 llvm::Value *Size = 0;
700 QualType SizeTy;
701 if (DeleteFTy->getNumArgs() == 2) {
702 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +0000703 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
704 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
705 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +0000706 }
707
708 if (DeleteFD->getOverloadedOperator() == OO_Array_Delete &&
Ken Dyckcaf647c2010-01-26 19:44:24 +0000709 !CalculateCookiePadding(getContext(), DeleteTy).isZero()) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000710 // We need to get the number of elements in the array from the cookie.
711 llvm::Value *AllocatedObjectPtr;
712 llvm::Value *NumElements;
713 llvm::tie(AllocatedObjectPtr, NumElements) =
714 GetAllocatedObjectPtrAndNumElements(*this, Ptr, DeleteTy);
715
716 // Multiply the size with the number of elements.
717 if (Size)
718 Size = Builder.CreateMul(NumElements, Size);
719
720 Ptr = AllocatedObjectPtr;
721 }
722
Eli Friedman5fe05982009-11-18 00:50:08 +0000723 QualType ArgTy = DeleteFTy->getArgType(0);
724 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
725 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
726
Anders Carlsson871d0782009-12-13 20:04:38 +0000727 if (Size)
Eli Friedman5fe05982009-11-18 00:50:08 +0000728 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedman5fe05982009-11-18 00:50:08 +0000729
730 // Emit the call to delete.
John McCall04a67a62010-02-05 21:31:56 +0000731 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000732 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +0000733 DeleteArgs, DeleteFD);
734}
735
Anders Carlsson16d81b82009-09-22 22:53:17 +0000736void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +0000737
Douglas Gregor90916562009-09-29 18:16:17 +0000738 // Get at the argument before we performed the implicit conversion
739 // to void*.
740 const Expr *Arg = E->getArgument();
741 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
742 if (ICE->getCastKind() != CastExpr::CK_UserDefinedConversion &&
743 ICE->getType()->isVoidPointerType())
744 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +0000745 else
746 break;
Douglas Gregor90916562009-09-29 18:16:17 +0000747 }
748
749 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000750
Douglas Gregor90916562009-09-29 18:16:17 +0000751 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000752
753 // Null check the pointer.
754 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
755 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
756
757 llvm::Value *IsNull =
758 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
759 "isnull");
760
761 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
762 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +0000763
764 bool ShouldCallDelete = true;
765
Anders Carlsson16d81b82009-09-22 22:53:17 +0000766 // Call the destructor if necessary.
767 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
768 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
769 if (!RD->hasTrivialDestructor()) {
770 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
Fariborz Jahanian72c21532009-11-13 19:27:47 +0000771 if (E->isArrayForm()) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000772 llvm::Value *AllocatedObjectPtr;
773 llvm::Value *NumElements;
774 llvm::tie(AllocatedObjectPtr, NumElements) =
775 GetAllocatedObjectPtrAndNumElements(*this, Ptr, DeleteTy);
776
Anders Carlsson61537102009-12-13 18:48:07 +0000777 EmitCXXAggrDestructorCall(Dtor, NumElements, Ptr);
Anders Carlsson61537102009-12-13 18:48:07 +0000778 } else if (Dtor->isVirtual()) {
Anders Carlsson16d81b82009-09-22 22:53:17 +0000779 const llvm::Type *Ty =
780 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(Dtor),
781 /*isVariadic=*/false);
782
Anders Carlsson566abee2009-11-13 04:45:41 +0000783 llvm::Value *Callee = BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
Anders Carlssonc997d422010-01-02 01:01:18 +0000784 EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
785 0, 0);
Anders Carlsson566abee2009-11-13 04:45:41 +0000786
787 // The dtor took care of deleting the object.
788 ShouldCallDelete = false;
Anders Carlsson16d81b82009-09-22 22:53:17 +0000789 } else
Anders Carlsson8e6404c2010-05-02 23:29:11 +0000790 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
791 Ptr);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000792 }
793 }
794 }
795
Eli Friedman5fe05982009-11-18 00:50:08 +0000796 if (ShouldCallDelete)
797 EmitDeleteCall(E->getOperatorDelete(), Ptr, DeleteTy);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000798
Anders Carlsson16d81b82009-09-22 22:53:17 +0000799 EmitBlock(DeleteEnd);
800}
Mike Stumpc2e84ae2009-11-15 08:09:41 +0000801
802llvm::Value * CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
803 QualType Ty = E->getType();
804 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +0000805
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000806 if (E->isTypeOperand()) {
807 llvm::Constant *TypeInfo =
808 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
809 return Builder.CreateBitCast(TypeInfo, LTy);
810 }
811
Mike Stumpc2e84ae2009-11-15 08:09:41 +0000812 Expr *subE = E->getExprOperand();
Mike Stump5fae8562009-11-17 22:33:00 +0000813 Ty = subE->getType();
814 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
815 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc2e84ae2009-11-15 08:09:41 +0000816 if (const RecordType *RT = Ty->getAs<RecordType>()) {
817 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
818 if (RD->isPolymorphic()) {
819 // FIXME: if subE is an lvalue do
820 LValue Obj = EmitLValue(subE);
821 llvm::Value *This = Obj.getAddress();
Mike Stumpf549e892009-11-15 16:52:53 +0000822 LTy = LTy->getPointerTo()->getPointerTo();
823 llvm::Value *V = Builder.CreateBitCast(This, LTy);
824 // We need to do a zero check for *p, unless it has NonNullAttr.
825 // FIXME: PointerType->hasAttr<NonNullAttr>()
826 bool CanBeZero = false;
Mike Stumpdb519a42009-11-17 00:45:21 +0000827 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
Mike Stumpf549e892009-11-15 16:52:53 +0000828 if (UO->getOpcode() == UnaryOperator::Deref)
829 CanBeZero = true;
830 if (CanBeZero) {
831 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
832 llvm::BasicBlock *ZeroBlock = createBasicBlock();
833
834 llvm::Value *Zero = llvm::Constant::getNullValue(LTy);
835 Builder.CreateCondBr(Builder.CreateICmpNE(V, Zero),
836 NonZeroBlock, ZeroBlock);
837 EmitBlock(ZeroBlock);
838 /// Call __cxa_bad_typeid
839 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
840 const llvm::FunctionType *FTy;
841 FTy = llvm::FunctionType::get(ResultType, false);
842 llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
Mike Stumpc849c052009-11-16 06:50:58 +0000843 Builder.CreateCall(F)->setDoesNotReturn();
Mike Stumpf549e892009-11-15 16:52:53 +0000844 Builder.CreateUnreachable();
845 EmitBlock(NonZeroBlock);
846 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +0000847 V = Builder.CreateLoad(V, "vtable");
848 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
849 V = Builder.CreateLoad(V);
850 return V;
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000851 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +0000852 }
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000853 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +0000854}
Mike Stumpc849c052009-11-16 06:50:58 +0000855
856llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
857 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000858 QualType SrcTy = DCE->getSubExpr()->getType();
859 QualType DestTy = DCE->getTypeAsWritten();
860 QualType InnerType = DestTy->getPointeeType();
861
Mike Stumpc849c052009-11-16 06:50:58 +0000862 const llvm::Type *LTy = ConvertType(DCE->getType());
Mike Stump2b35baf2009-11-16 22:52:20 +0000863
Mike Stumpc849c052009-11-16 06:50:58 +0000864 bool CanBeZero = false;
Mike Stumpc849c052009-11-16 06:50:58 +0000865 bool ToVoid = false;
Mike Stump2b35baf2009-11-16 22:52:20 +0000866 bool ThrowOnBad = false;
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000867 if (DestTy->isPointerType()) {
Mike Stumpc849c052009-11-16 06:50:58 +0000868 // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
869 CanBeZero = true;
870 if (InnerType->isVoidType())
871 ToVoid = true;
872 } else {
873 LTy = LTy->getPointerTo();
Douglas Gregor485ee322010-05-14 21:14:41 +0000874
875 // FIXME: What if exceptions are disabled?
Mike Stumpc849c052009-11-16 06:50:58 +0000876 ThrowOnBad = true;
877 }
878
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000879 if (SrcTy->isPointerType() || SrcTy->isReferenceType())
880 SrcTy = SrcTy->getPointeeType();
881 SrcTy = SrcTy.getUnqualifiedType();
882
Anders Carlsson6f0e4852009-12-18 14:55:04 +0000883 if (DestTy->isPointerType() || DestTy->isReferenceType())
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000884 DestTy = DestTy->getPointeeType();
885 DestTy = DestTy.getUnqualifiedType();
Mike Stumpc849c052009-11-16 06:50:58 +0000886
Mike Stumpc849c052009-11-16 06:50:58 +0000887 llvm::BasicBlock *ContBlock = createBasicBlock();
888 llvm::BasicBlock *NullBlock = 0;
889 llvm::BasicBlock *NonZeroBlock = 0;
890 if (CanBeZero) {
891 NonZeroBlock = createBasicBlock();
892 NullBlock = createBasicBlock();
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000893 Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
Mike Stumpc849c052009-11-16 06:50:58 +0000894 EmitBlock(NonZeroBlock);
895 }
896
Mike Stumpc849c052009-11-16 06:50:58 +0000897 llvm::BasicBlock *BadCastBlock = 0;
Mike Stumpc849c052009-11-16 06:50:58 +0000898
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000899 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
Mike Stump2b35baf2009-11-16 22:52:20 +0000900
901 // See if this is a dynamic_cast(void*)
902 if (ToVoid) {
903 llvm::Value *This = V;
904 V = Builder.CreateBitCast(This, PtrDiffTy->getPointerTo()->getPointerTo());
905 V = Builder.CreateLoad(V, "vtable");
906 V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
907 V = Builder.CreateLoad(V, "offset to top");
908 This = Builder.CreateBitCast(This, llvm::Type::getInt8PtrTy(VMContext));
909 V = Builder.CreateInBoundsGEP(This, V);
910 V = Builder.CreateBitCast(V, LTy);
911 } else {
912 /// Call __dynamic_cast
913 const llvm::Type *ResultType = llvm::Type::getInt8PtrTy(VMContext);
914 const llvm::FunctionType *FTy;
915 std::vector<const llvm::Type*> ArgTys;
916 const llvm::Type *PtrToInt8Ty
917 = llvm::Type::getInt8Ty(VMContext)->getPointerTo();
918 ArgTys.push_back(PtrToInt8Ty);
919 ArgTys.push_back(PtrToInt8Ty);
920 ArgTys.push_back(PtrToInt8Ty);
921 ArgTys.push_back(PtrDiffTy);
922 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump2b35baf2009-11-16 22:52:20 +0000923
924 // FIXME: Calculate better hint.
925 llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000926
927 assert(SrcTy->isRecordType() && "Src type must be record type!");
928 assert(DestTy->isRecordType() && "Dest type must be record type!");
929
Douglas Gregor154fe982009-12-23 22:04:40 +0000930 llvm::Value *SrcArg
931 = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
932 llvm::Value *DestArg
933 = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000934
Mike Stump2b35baf2009-11-16 22:52:20 +0000935 V = Builder.CreateBitCast(V, PtrToInt8Ty);
936 V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000937 V, SrcArg, DestArg, hint);
Mike Stump2b35baf2009-11-16 22:52:20 +0000938 V = Builder.CreateBitCast(V, LTy);
939
940 if (ThrowOnBad) {
941 BadCastBlock = createBasicBlock();
Anders Carlsson1d7088d2009-12-17 07:09:17 +0000942 Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
Mike Stump2b35baf2009-11-16 22:52:20 +0000943 EmitBlock(BadCastBlock);
Douglas Gregor485ee322010-05-14 21:14:41 +0000944 /// Invoke __cxa_bad_cast
Mike Stump2b35baf2009-11-16 22:52:20 +0000945 ResultType = llvm::Type::getVoidTy(VMContext);
946 const llvm::FunctionType *FBadTy;
Mike Stumpfde17be2009-11-17 03:01:03 +0000947 FBadTy = llvm::FunctionType::get(ResultType, false);
Mike Stump2b35baf2009-11-16 22:52:20 +0000948 llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
Douglas Gregor485ee322010-05-14 21:14:41 +0000949 if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
950 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
951 Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
952 EmitBlock(Cont);
953 } else {
954 // FIXME: Does this ever make sense?
955 Builder.CreateCall(F)->setDoesNotReturn();
956 }
Mike Stump8b152b82009-11-17 00:08:50 +0000957 Builder.CreateUnreachable();
Mike Stump2b35baf2009-11-16 22:52:20 +0000958 }
Mike Stumpc849c052009-11-16 06:50:58 +0000959 }
960
961 if (CanBeZero) {
962 Builder.CreateBr(ContBlock);
963 EmitBlock(NullBlock);
964 Builder.CreateBr(ContBlock);
965 }
966 EmitBlock(ContBlock);
967 if (CanBeZero) {
968 llvm::PHINode *PHI = Builder.CreatePHI(LTy);
Mike Stump14431c12009-11-17 00:10:05 +0000969 PHI->reserveOperandSpace(2);
Mike Stumpc849c052009-11-16 06:50:58 +0000970 PHI->addIncoming(V, NonZeroBlock);
971 PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
Mike Stumpc849c052009-11-16 06:50:58 +0000972 V = PHI;
973 }
974
975 return V;
976}