blob: 74b6af1425e471c3b739747dce216d713c1096c9 [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000016#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "llvm/Module.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000018#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000019
20#include <algorithm>
21
22using namespace clang;
23using namespace CodeGen;
24
Mike Stump58919e12009-03-04 13:17:22 +000025// Temporary code to enable testing of __block variables
26// #include "clang/Frontend/CompileOptions.h"
27#include "llvm/Support/CommandLine.h"
Mike Stump58919e12009-03-04 13:17:22 +000028
Mike Stumpcf62d392009-03-06 18:42:23 +000029llvm::Constant *CodeGenFunction::
Mike Stumpa803b0e2009-03-25 17:58:24 +000030BuildDescriptorBlockDecl(bool BlockHasCopyDispose, uint64_t Size,
31 const llvm::StructType* Ty,
Mike Stump08920992009-03-07 02:35:30 +000032 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump56129b12009-02-13 16:55:51 +000033 const llvm::Type *UnsignedLongTy
34 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpe5fee252009-02-13 16:19:19 +000035 llvm::Constant *C;
36 std::vector<llvm::Constant*> Elts;
37
38 // reserved
Mike Stump56129b12009-02-13 16:55:51 +000039 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000040 Elts.push_back(C);
41
42 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000043 // FIXME: What is the right way to say this doesn't fit? We should give
44 // a user diagnostic in that case. Better fix would be to change the
45 // API to size_t.
Mike Stump4e7a1f72009-02-21 20:00:35 +000046 C = llvm::ConstantInt::get(UnsignedLongTy, Size);
Mike Stumpe5fee252009-02-13 16:19:19 +000047 Elts.push_back(C);
48
49 if (BlockHasCopyDispose) {
50 // copy_func_helper_decl
Mike Stump08920992009-03-07 02:35:30 +000051 Elts.push_back(BuildCopyHelper(Ty, *NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000052
53 // destroy_func_decl
Mike Stump08920992009-03-07 02:35:30 +000054 Elts.push_back(BuildDestroyHelper(Ty, *NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000055 }
56
57 C = llvm::ConstantStruct::get(Elts);
58
Mike Stumpe5fee252009-02-13 16:19:19 +000059 C = new llvm::GlobalVariable(C->getType(), true,
60 llvm::GlobalValue::InternalLinkage,
Mike Stump7d6dc4f2009-02-13 20:17:16 +000061 C, "__block_descriptor_tmp", &CGM.getModule());
Mike Stumpe5fee252009-02-13 16:19:19 +000062 return C;
63}
64
Mike Stump2a998142009-03-04 18:17:45 +000065llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Mike Stumpf99f1d02009-02-13 17:23:42 +000066 if (NSConcreteGlobalBlock)
67 return NSConcreteGlobalBlock;
68
Mike Stumpf7448952009-02-13 19:38:12 +000069 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000070 // same thing as CreateRuntimeFunction if there's already a variable with the
71 // same name.
Mike Stumpf99f1d02009-02-13 17:23:42 +000072 NSConcreteGlobalBlock
Mike Stump00470a12009-03-05 08:32:30 +000073 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stumpf99f1d02009-02-13 17:23:42 +000074 llvm::GlobalValue::ExternalLinkage,
75 0, "_NSConcreteGlobalBlock",
76 &getModule());
77
78 return NSConcreteGlobalBlock;
79}
80
Mike Stump2a998142009-03-04 18:17:45 +000081llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Mike Stump59c5b112009-02-13 19:29:27 +000082 if (NSConcreteStackBlock)
83 return NSConcreteStackBlock;
84
Mike Stumpf7448952009-02-13 19:38:12 +000085 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000086 // same thing as CreateRuntimeFunction if there's already a variable with the
87 // same name.
Mike Stump59c5b112009-02-13 19:29:27 +000088 NSConcreteStackBlock
Mike Stump00470a12009-03-05 08:32:30 +000089 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stump59c5b112009-02-13 19:29:27 +000090 llvm::GlobalValue::ExternalLinkage,
91 0, "_NSConcreteStackBlock",
92 &getModule());
93
94 return NSConcreteStackBlock;
95}
96
Mike Stump00470a12009-03-05 08:32:30 +000097static void CollectBlockDeclRefInfo(const Stmt *S,
Anders Carlsson4de9fce2009-03-01 01:09:12 +000098 CodeGenFunction::BlockInfo &Info) {
99 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
100 I != E; ++I)
Daniel Dunbar82573ee2009-03-02 07:00:57 +0000101 if (*I)
102 CollectBlockDeclRefInfo(*I, Info);
Mike Stump00470a12009-03-05 08:32:30 +0000103
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000104 if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
105 // FIXME: Handle enums.
106 if (isa<FunctionDecl>(DE->getDecl()))
107 return;
Mike Stump00470a12009-03-05 08:32:30 +0000108
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000109 if (DE->isByRef())
110 Info.ByRefDeclRefs.push_back(DE);
111 else
112 Info.ByCopyDeclRefs.push_back(DE);
113 }
114}
115
Mike Stump58a85142009-03-04 22:48:06 +0000116/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
117/// declared as a global variable instead of on the stack.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000118static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
119{
120 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
121}
122
Mike Stump58a85142009-03-04 22:48:06 +0000123// FIXME: Push most into CGM, passing down a few bits, like current function
124// name.
Mike Stump8a2b4b12009-02-25 23:33:13 +0000125llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Mike Stumpe5fee252009-02-13 16:19:19 +0000126
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000127 std::string Name = CurFn->getName();
128 CodeGenFunction::BlockInfo Info(0, Name.c_str());
129 CollectBlockDeclRefInfo(BE->getBody(), Info);
130
131 // Check if the block can be global.
Mike Stump58a85142009-03-04 22:48:06 +0000132 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
133 // to just have one code path. We should move this function into CGM and pass
134 // CGF, then we can just check to see if CGF is 0.
Mike Stumpdab514f2009-03-04 03:23:46 +0000135 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000136 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump00470a12009-03-05 08:32:30 +0000137
138 std::vector<llvm::Constant*> Elts(5);
Mike Stumpe5fee252009-02-13 16:19:19 +0000139 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000140 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000141
Mike Stumpe5fee252009-02-13 16:19:19 +0000142 {
143 // C = BuildBlockStructInitlist();
144 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
145
Mike Stump00470a12009-03-05 08:32:30 +0000146 // We run this first so that we set BlockHasCopyDispose from the entire
147 // block literal.
148 // __invoke
149 uint64_t subBlockSize, subBlockAlign;
150 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stumpa803b0e2009-03-25 17:58:24 +0000151 bool subBlockHasCopyDispose = false;
Mike Stump00470a12009-03-05 08:32:30 +0000152 llvm::Function *Fn
Mike Stump6cc88f72009-03-20 21:53:12 +0000153 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl, LocalDeclMap,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000154 subBlockSize,
Mike Stump00470a12009-03-05 08:32:30 +0000155 subBlockAlign,
156 subBlockDeclRefDecls,
Mike Stumpa803b0e2009-03-25 17:58:24 +0000157 subBlockHasCopyDispose);
158 BlockHasCopyDispose |= subBlockHasCopyDispose;
Mike Stump00470a12009-03-05 08:32:30 +0000159 Elts[3] = Fn;
160
Mike Stumpa803b0e2009-03-25 17:58:24 +0000161 if (subBlockHasCopyDispose)
Mike Stumpe5fee252009-02-13 16:19:19 +0000162 flags |= BLOCK_HAS_COPY_DISPOSE;
163
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000164 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000165 C = CGM.getNSConcreteStackBlock();
Mike Stumpe5fee252009-02-13 16:19:19 +0000166 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump00470a12009-03-05 08:32:30 +0000167 Elts[0] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000168
169 // __flags
170 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
171 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
172 C = llvm::ConstantInt::get(IntTy, flags);
Mike Stump00470a12009-03-05 08:32:30 +0000173 Elts[1] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000174
175 // __reserved
176 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump00470a12009-03-05 08:32:30 +0000177 Elts[2] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000178
Mike Stump8a2b4b12009-02-25 23:33:13 +0000179 if (subBlockDeclRefDecls.size() == 0) {
Mike Stumpcf62d392009-03-06 18:42:23 +0000180 // __descriptor
Mike Stumpa803b0e2009-03-25 17:58:24 +0000181 assert(subBlockHasCopyDispose == false);
182 Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize, 0, 0);
Mike Stumpcf62d392009-03-06 18:42:23 +0000183
Mike Stump5570cfe2009-03-01 20:07:53 +0000184 // Optimize to being a global block.
185 Elts[0] = CGM.getNSConcreteGlobalBlock();
186 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
187
Mike Stump8a2b4b12009-02-25 23:33:13 +0000188 C = llvm::ConstantStruct::get(Elts);
189
190 char Name[32];
191 sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
192 C = new llvm::GlobalVariable(C->getType(), true,
193 llvm::GlobalValue::InternalLinkage,
194 C, Name, &CGM.getModule());
195 QualType BPT = BE->getType();
196 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
197 return C;
198 }
Mike Stump00470a12009-03-05 08:32:30 +0000199
Mike Stump8a2b4b12009-02-25 23:33:13 +0000200 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
Mike Stump08920992009-03-07 02:35:30 +0000201 for (int i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000202 Types[i] = Elts[i]->getType();
Mike Stump08920992009-03-07 02:35:30 +0000203 Types[4] = PtrToInt8Ty;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000204
Mike Stumpa99038c2009-02-28 09:07:16 +0000205 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
206 const Expr *E = subBlockDeclRefDecls[i];
207 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
208 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000209 if (BDRE && BDRE->isByRef()) {
210 uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
211 Types[i+5] = llvm::PointerType::get(BuildByRefType(Ty, Align), 0);
212 } else
213 Types[i+5] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000214 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000215
Mike Stump08920992009-03-07 02:35:30 +0000216 llvm::StructType *Ty = llvm::StructType::get(Types, true);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000217
218 llvm::AllocaInst *A = CreateTempAlloca(Ty);
219 A->setAlignment(subBlockAlign);
220 V = A;
221
Mike Stump08920992009-03-07 02:35:30 +0000222 std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
223 int helpersize = 0;
224
225 for (unsigned i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000226 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump00470a12009-03-05 08:32:30 +0000227
Mike Stump8a2b4b12009-02-25 23:33:13 +0000228 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
229 {
Mike Stumpa99038c2009-02-28 09:07:16 +0000230 // FIXME: Push const down.
231 Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
232 DeclRefExpr *DR;
233 ValueDecl *VD;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000234
Mike Stumpa99038c2009-02-28 09:07:16 +0000235 DR = dyn_cast<DeclRefExpr>(E);
236 // Skip padding.
237 if (DR) continue;
238
239 BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
240 VD = BDRE->getDecl();
241
Mike Stumpdab514f2009-03-04 03:23:46 +0000242 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stump08920992009-03-07 02:35:30 +0000243 NoteForHelper[helpersize].index = i+5;
244 NoteForHelper[helpersize].RequiresCopying = BlockRequiresCopying(VD->getType());
245 NoteForHelper[helpersize].flag
246 = VD->getType()->isBlockPointerType() ? BLOCK_FIELD_IS_BLOCK : BLOCK_FIELD_IS_OBJECT;
247
Mike Stumpa99038c2009-02-28 09:07:16 +0000248 if (LocalDeclMap[VD]) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000249 if (BDRE->isByRef()) {
Mike Stump08920992009-03-07 02:35:30 +0000250 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
Mike Stumpf4bc3122009-03-07 06:04:31 +0000251 // FIXME: Someone double check this.
252 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000253 const llvm::Type *Ty = Types[i+5];
254 llvm::Value *Loc = LocalDeclMap[VD];
255 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
256 Loc = Builder.CreateLoad(Loc, false);
257 Loc = Builder.CreateBitCast(Loc, Ty);
258 Builder.CreateStore(Loc, Addr);
Mike Stump08920992009-03-07 02:35:30 +0000259 ++helpersize;
Mike Stumpdab514f2009-03-04 03:23:46 +0000260 continue;
261 } else
262 E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
263 VD->getType(), SourceLocation(),
264 false, false);
Mike Stumpa99038c2009-02-28 09:07:16 +0000265 }
Mike Stumpdab514f2009-03-04 03:23:46 +0000266 if (BDRE->isByRef()) {
Mike Stumpa8b60c92009-03-21 21:00:35 +0000267 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
268 // FIXME: Someone double check this.
269 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
Mike Stumpa99038c2009-02-28 09:07:16 +0000270 E = new (getContext())
271 UnaryOperator(E, UnaryOperator::AddrOf,
272 getContext().getPointerType(E->getType()),
273 SourceLocation());
Mike Stumpdab514f2009-03-04 03:23:46 +0000274 }
Mike Stump08920992009-03-07 02:35:30 +0000275 ++helpersize;
Mike Stumpa99038c2009-02-28 09:07:16 +0000276
Mike Stumpa99038c2009-02-28 09:07:16 +0000277 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpdab514f2009-03-04 03:23:46 +0000278 if (r.isScalar()) {
279 llvm::Value *Loc = r.getScalarVal();
280 const llvm::Type *Ty = Types[i+5];
281 if (BDRE->isByRef()) {
Mike Stump58a85142009-03-04 22:48:06 +0000282 // E is now the address of the value field, instead, we want the
283 // address of the actual ByRef struct. We optimize this slightly
284 // compared to gcc by not grabbing the forwarding slot as this must
285 // be done during Block_copy for us, and we can postpone the work
286 // until then.
287 uint64_t offset = BlockDecls[BDRE->getDecl()];
Mike Stump00470a12009-03-05 08:32:30 +0000288
Mike Stump58a85142009-03-04 22:48:06 +0000289 llvm::Value *BlockLiteral = LoadBlockStruct();
Mike Stump00470a12009-03-05 08:32:30 +0000290
Mike Stump58a85142009-03-04 22:48:06 +0000291 Loc = Builder.CreateGEP(BlockLiteral,
292 llvm::ConstantInt::get(llvm::Type::Int64Ty,
293 offset),
294 "block.literal");
295 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000296 Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stump58a85142009-03-04 22:48:06 +0000297 Loc = Builder.CreateLoad(Loc, false);
298 // Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000299 }
300 Builder.CreateStore(Loc, Addr);
301 } else if (r.isComplex())
Mike Stump8a2b4b12009-02-25 23:33:13 +0000302 // FIXME: implement
303 ErrorUnsupported(BE, "complex in block literal");
304 else if (r.isAggregate())
305 ; // Already created into the destination
306 else
307 assert (0 && "bad block variable");
308 // FIXME: Ensure that the offset created by the backend for
309 // the struct matches the previously computed offset in BlockDecls.
310 }
Mike Stump08920992009-03-07 02:35:30 +0000311 NoteForHelper.resize(helpersize);
Mike Stumpcf62d392009-03-06 18:42:23 +0000312
313 // __descriptor
Mike Stumpa803b0e2009-03-25 17:58:24 +0000314 llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
315 subBlockSize, Ty,
Mike Stump08920992009-03-07 02:35:30 +0000316 &NoteForHelper);
317 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
318 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
Mike Stumpe5fee252009-02-13 16:19:19 +0000319 }
Mike Stump00470a12009-03-05 08:32:30 +0000320
Mike Stumpbd65cac2009-02-19 01:01:04 +0000321 QualType BPT = BE->getType();
Mike Stump8a2b4b12009-02-25 23:33:13 +0000322 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stumpe5fee252009-02-13 16:19:19 +0000323}
324
325
Mike Stump2a998142009-03-04 18:17:45 +0000326const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000327 if (BlockDescriptorType)
328 return BlockDescriptorType;
329
Mike Stumpa5448542009-02-13 15:32:32 +0000330 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000331 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000332
Mike Stumpab695142009-02-13 15:16:56 +0000333 // struct __block_descriptor {
334 // unsigned long reserved;
335 // unsigned long block_size;
336 // };
Mike Stumpa5448542009-02-13 15:32:32 +0000337 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
338 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000339 NULL);
340
341 getModule().addTypeName("struct.__block_descriptor",
342 BlockDescriptorType);
343
344 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000345}
346
Mike Stump2a998142009-03-04 18:17:45 +0000347const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000348 if (GenericBlockLiteralType)
349 return GenericBlockLiteralType;
350
Mike Stumpa5448542009-02-13 15:32:32 +0000351 const llvm::Type *BlockDescPtrTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000352 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpa5448542009-02-13 15:32:32 +0000353
Mike Stump7cbb3602009-02-13 16:01:35 +0000354 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
355 getTypes().ConvertType(getContext().IntTy));
356
Mike Stump9b8a7972009-02-13 15:25:34 +0000357 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000358 // void *__isa;
359 // int __flags;
360 // int __reserved;
361 // void (*__invoke)(void *);
362 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000363 // };
Mike Stump797b6322009-03-05 01:23:13 +0000364 GenericBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000365 IntTy,
366 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000367 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000368 BlockDescPtrTy,
369 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000370
Mike Stump9b8a7972009-02-13 15:25:34 +0000371 getModule().addTypeName("struct.__block_literal_generic",
372 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000373
Mike Stump9b8a7972009-02-13 15:25:34 +0000374 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000375}
376
Mike Stump2a998142009-03-04 18:17:45 +0000377const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000378 if (GenericExtendedBlockLiteralType)
379 return GenericExtendedBlockLiteralType;
380
Mike Stumpbd65cac2009-02-19 01:01:04 +0000381 const llvm::Type *BlockDescPtrTy =
382 llvm::PointerType::getUnqual(getBlockDescriptorType());
383
384 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
385 getTypes().ConvertType(getContext().IntTy));
386
387 // struct __block_literal_generic {
388 // void *__isa;
389 // int __flags;
390 // int __reserved;
391 // void (*__invoke)(void *);
392 // struct __block_descriptor *__descriptor;
393 // void *__copy_func_helper_decl;
394 // void *__destroy_func_decl;
395 // };
Mike Stump797b6322009-03-05 01:23:13 +0000396 GenericExtendedBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000397 IntTy,
398 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000399 PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000400 BlockDescPtrTy,
Mike Stump797b6322009-03-05 01:23:13 +0000401 PtrToInt8Ty,
402 PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000403 NULL);
404
405 getModule().addTypeName("struct.__block_literal_extended_generic",
406 GenericExtendedBlockLiteralType);
407
408 return GenericExtendedBlockLiteralType;
409}
410
Anders Carlssond5cab542009-02-12 17:55:02 +0000411RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpa5448542009-02-13 15:32:32 +0000412 const BlockPointerType *BPT =
Anders Carlssonacfde802009-02-12 00:39:25 +0000413 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpa5448542009-02-13 15:32:32 +0000414
Anders Carlssonacfde802009-02-12 00:39:25 +0000415 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
416
417 // Get a pointer to the generic block literal.
418 const llvm::Type *BlockLiteralTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000419 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000420
421 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000422 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000423 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
424
425 // Get the function pointer from the literal.
426 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000427
Mike Stumpa5448542009-02-13 15:32:32 +0000428 BlockLiteral =
429 Builder.CreateBitCast(BlockLiteral,
Anders Carlssonacfde802009-02-12 00:39:25 +0000430 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
431 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000432
Anders Carlssonacfde802009-02-12 00:39:25 +0000433 // Add the block literal.
434 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
435 CallArgList Args;
436 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000437
Anders Carlssonacfde802009-02-12 00:39:25 +0000438 // And the rest of the arguments.
Mike Stumpa5448542009-02-13 15:32:32 +0000439 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
Anders Carlssonacfde802009-02-12 00:39:25 +0000440 i != e; ++i)
Mike Stumpa5448542009-02-13 15:32:32 +0000441 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
Anders Carlssonacfde802009-02-12 00:39:25 +0000442 i->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000443
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000444 // Load the function.
445 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
446
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000447 QualType FnType = BPT->getPointeeType();
448 QualType ResultType = FnType->getAsFunctionType()->getResultType();
449
450 const CGFunctionInfo &FnInfo =
451 CGM.getTypes().getFunctionInfo(ResultType, Args);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000452
453 // Cast the function pointer to the right type.
454 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000455 CGM.getTypes().GetFunctionType(FnInfo, false);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000456
457 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
458 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
459
Anders Carlssonacfde802009-02-12 00:39:25 +0000460 // And call the block.
Anders Carlssonf8544a42009-04-07 00:20:24 +0000461 return EmitCall(FnInfo, Func, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000462}
Anders Carlssond5cab542009-02-12 17:55:02 +0000463
Mike Stumpdab514f2009-03-04 03:23:46 +0000464llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
465 uint64_t &offset = BlockDecls[E->getDecl()];
466
467 const llvm::Type *Ty;
468 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
469
Mike Stumpdab514f2009-03-04 03:23:46 +0000470 // See if we have already allocated an offset for this variable.
471 if (offset == 0) {
Mike Stump00470a12009-03-05 08:32:30 +0000472 // Don't run the expensive check, unless we have to.
473 if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
474 BlockHasCopyDispose = true;
Mike Stumpdab514f2009-03-04 03:23:46 +0000475 // if not, allocate one now.
476 offset = getBlockOffset(E);
477 }
478
479 llvm::Value *BlockLiteral = LoadBlockStruct();
480 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
481 llvm::ConstantInt::get(llvm::Type::Int64Ty,
482 offset),
Mike Stump58a85142009-03-04 22:48:06 +0000483 "block.literal");
Mike Stumpdab514f2009-03-04 03:23:46 +0000484 if (E->isByRef()) {
485 bool needsCopyDispose = BlockRequiresCopying(E->getType());
486 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
487 const llvm::Type *PtrStructTy
488 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
Mike Stumpa8b60c92009-03-21 21:00:35 +0000489 // The block literal will need a copy/destroy helper.
490 BlockHasCopyDispose = true;
Mike Stumpdab514f2009-03-04 03:23:46 +0000491 Ty = PtrStructTy;
492 Ty = llvm::PointerType::get(Ty, 0);
493 V = Builder.CreateBitCast(V, Ty);
494 V = Builder.CreateLoad(V, false);
495 V = Builder.CreateStructGEP(V, 1, "forwarding");
496 V = Builder.CreateLoad(V, false);
497 V = Builder.CreateBitCast(V, PtrStructTy);
498 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
499 } else {
500 Ty = llvm::PointerType::get(Ty, 0);
501 V = Builder.CreateBitCast(V, Ty);
502 }
503 return V;
504}
505
Mike Stump6cc88f72009-03-20 21:53:12 +0000506void CodeGenFunction::BlockForwardSelf() {
507 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
508 ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
509 llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
510 if (DMEntry)
511 return;
512 // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
513 BlockDeclRefExpr *BDRE = new (getContext())
514 BlockDeclRefExpr(SelfDecl,
515 SelfDecl->getType(), SourceLocation(), false);
516 DMEntry = GetAddrOfBlockDecl(BDRE);
517}
518
Mike Stump67a64482009-02-14 22:16:35 +0000519llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000520BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000521 // Generate the block descriptor.
522 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000523 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
524 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000525
Anders Carlssond5cab542009-02-12 17:55:02 +0000526 llvm::Constant *DescriptorFields[2];
Mike Stumpa5448542009-02-13 15:32:32 +0000527
Anders Carlssond5cab542009-02-12 17:55:02 +0000528 // Reserved
529 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000530
Anders Carlssond5cab542009-02-12 17:55:02 +0000531 // Block literal size. For global blocks we just use the size of the generic
532 // block literal struct.
Mike Stumpa5448542009-02-13 15:32:32 +0000533 uint64_t BlockLiteralSize =
Mike Stump9b8a7972009-02-13 15:25:34 +0000534 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlssond5cab542009-02-12 17:55:02 +0000535 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpa5448542009-02-13 15:32:32 +0000536
537 llvm::Constant *DescriptorStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000538 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpa5448542009-02-13 15:32:32 +0000539
Anders Carlssond5cab542009-02-12 17:55:02 +0000540 llvm::GlobalVariable *Descriptor =
541 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000542 llvm::GlobalVariable::InternalLinkage,
543 DescriptorStruct, "__block_descriptor_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000544 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000545
Anders Carlssond5cab542009-02-12 17:55:02 +0000546 // Generate the constants for the block literal.
547 llvm::Constant *LiteralFields[5];
Mike Stumpa5448542009-02-13 15:32:32 +0000548
Mike Stump67a64482009-02-14 22:16:35 +0000549 CodeGenFunction::BlockInfo Info(0, n);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000550 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000551 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Daniel Dunbard67b09a2009-03-12 03:07:24 +0000552 bool subBlockHasCopyDispose = false;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000553 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000554 llvm::Function *Fn
Mike Stump6cc88f72009-03-20 21:53:12 +0000555 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000556 subBlockSize,
Mike Stump90a90432009-03-04 18:47:42 +0000557 subBlockAlign,
Mike Stump00470a12009-03-05 08:32:30 +0000558 subBlockDeclRefDecls,
559 subBlockHasCopyDispose);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000560 assert(subBlockSize == BlockLiteralSize
561 && "no imports allowed for global block");
Daniel Dunbard67b09a2009-03-12 03:07:24 +0000562 assert(!subBlockHasCopyDispose && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000563
Anders Carlssond5cab542009-02-12 17:55:02 +0000564 // isa
Mike Stumpf99f1d02009-02-13 17:23:42 +0000565 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000566
Anders Carlssond5cab542009-02-12 17:55:02 +0000567 // Flags
Mike Stump00470a12009-03-05 08:32:30 +0000568 LiteralFields[1] =
Anders Carlsson8045ee02009-03-01 21:09:29 +0000569 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpa5448542009-02-13 15:32:32 +0000570
Anders Carlssond5cab542009-02-12 17:55:02 +0000571 // Reserved
Mike Stump7cbb3602009-02-13 16:01:35 +0000572 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000573
Anders Carlssond5cab542009-02-12 17:55:02 +0000574 // Function
575 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000576
Anders Carlssond5cab542009-02-12 17:55:02 +0000577 // Descriptor
578 LiteralFields[4] = Descriptor;
Mike Stumpa5448542009-02-13 15:32:32 +0000579
580 llvm::Constant *BlockLiteralStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000581 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpa5448542009-02-13 15:32:32 +0000582
583 llvm::GlobalVariable *BlockLiteral =
Anders Carlssond5cab542009-02-12 17:55:02 +0000584 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000585 llvm::GlobalVariable::InternalLinkage,
586 BlockLiteralStruct, "__block_literal_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000587 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000588
Anders Carlssond5cab542009-02-12 17:55:02 +0000589 return BlockLiteral;
590}
591
Mike Stump4e7a1f72009-02-21 20:00:35 +0000592llvm::Value *CodeGenFunction::LoadBlockStruct() {
593 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
594}
595
Mike Stump00470a12009-03-05 08:32:30 +0000596llvm::Function *
597CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
598 const BlockInfo& Info,
Mike Stump6cc88f72009-03-20 21:53:12 +0000599 const Decl *OuterFuncDecl,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000600 llvm::DenseMap<const Decl*, llvm::Value*> ldm,
Mike Stump00470a12009-03-05 08:32:30 +0000601 uint64_t &Size,
602 uint64_t &Align,
603 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
604 bool &subBlockHasCopyDispose) {
Mike Stump7f28a9c2009-03-13 23:34:28 +0000605 // Arrange for local static and local extern declarations to appear
606 // to be local to this function as well, as they are directly referenced
607 // in a block.
608 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
609 i != ldm.end();
610 ++i) {
611 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
612
613 if (VD->getStorageClass() == VarDecl::Static
614 || VD->getStorageClass() == VarDecl::Extern)
615 LocalDeclMap[VD] = i->second;
616 }
617
Eli Friedman48f91222009-03-28 03:24:54 +0000618 // FIXME: We need to rearrange the code for copy/dispose so we have this
619 // sooner, so we can calculate offsets correctly.
620 if (!BlockHasCopyDispose)
621 BlockOffset = CGM.getTargetData()
622 .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
623 else
624 BlockOffset = CGM.getTargetData()
625 .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
626 BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
627
Douglas Gregor72564e72009-02-26 23:50:07 +0000628 const FunctionProtoType *FTy =
Chris Lattner161d36d2009-02-28 19:01:03 +0000629 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpa5448542009-02-13 15:32:32 +0000630
Anders Carlssond5cab542009-02-12 17:55:02 +0000631 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000632
Chris Lattner161d36d2009-02-28 19:01:03 +0000633 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000634
635 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000636 ImplicitParamDecl *SelfDecl =
Anders Carlssond5cab542009-02-12 17:55:02 +0000637 ImplicitParamDecl::Create(getContext(), 0,
638 SourceLocation(), 0,
639 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000640
Anders Carlssond5cab542009-02-12 17:55:02 +0000641 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000642 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000643
Steve Naroffe78b8092009-03-13 16:56:44 +0000644 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000645 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000646 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000647
648 const CGFunctionInfo &FI =
Anders Carlssond5cab542009-02-12 17:55:02 +0000649 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
650
Mike Stump67a64482009-02-14 22:16:35 +0000651 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlssond5cab542009-02-12 17:55:02 +0000652 CodeGenTypes &Types = CGM.getTypes();
653 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000654
655 llvm::Function *Fn =
Anders Carlssond5cab542009-02-12 17:55:02 +0000656 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
657 Name,
658 &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000659
660 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000661 BExpr->getBody()->getLocEnd());
Mike Stump6cc88f72009-03-20 21:53:12 +0000662 CurFuncDecl = OuterFuncDecl;
Chris Lattner161d36d2009-02-28 19:01:03 +0000663 EmitStmt(BExpr->getBody());
664 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000665
Mike Stump8a2b4b12009-02-25 23:33:13 +0000666 // The runtime needs a minimum alignment of a void *.
667 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
668 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
669
Mike Stump4e7a1f72009-02-21 20:00:35 +0000670 Size = BlockOffset;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000671 Align = BlockAlign;
672 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump00470a12009-03-05 08:32:30 +0000673 subBlockHasCopyDispose |= BlockHasCopyDispose;
Anders Carlssond5cab542009-02-12 17:55:02 +0000674 return Fn;
675}
Mike Stumpa99038c2009-02-28 09:07:16 +0000676
Mike Stump08920992009-03-07 02:35:30 +0000677uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000678 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
679
680 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
681 uint64_t Align = getContext().getDeclAlignInBytes(D);
682
683 if (BDRE->isByRef()) {
684 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
685 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
686 }
687
688 assert ((Align > 0) && "alignment must be 1 byte or more");
689
690 uint64_t OldOffset = BlockOffset;
691
692 // Ensure proper alignment, even if it means we have to have a gap
693 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
694 BlockAlign = std::max(Align, BlockAlign);
Mike Stump00470a12009-03-05 08:32:30 +0000695
Mike Stumpa99038c2009-02-28 09:07:16 +0000696 uint64_t Pad = BlockOffset - OldOffset;
697 if (Pad) {
698 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
699 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
700 llvm::APInt(32, Pad),
701 ArrayType::Normal, 0);
702 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
703 0, QualType(PadTy), VarDecl::None,
704 SourceLocation());
705 Expr *E;
706 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
707 SourceLocation(), false, false);
708 BlockDeclRefDecls.push_back(E);
709 }
710 BlockDeclRefDecls.push_back(BDRE);
711
712 BlockOffset += Size;
713 return BlockOffset-Size;
714}
Mike Stumpdab514f2009-03-04 03:23:46 +0000715
Mike Stump08920992009-03-07 02:35:30 +0000716llvm::Constant *BlockFunction::
717GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
718 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000719 QualType R = getContext().VoidTy;
720
721 FunctionArgList Args;
722 // FIXME: This leaks
Mike Stump08920992009-03-07 02:35:30 +0000723 ImplicitParamDecl *Dst =
724 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
725 getContext().getPointerType(getContext().VoidTy));
726 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000727 ImplicitParamDecl *Src =
728 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
729 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000730 Args.push_back(std::make_pair(Src, Src->getType()));
731
732 const CGFunctionInfo &FI =
733 CGM.getTypes().getFunctionInfo(R, Args);
734
735 std::string Name = std::string("__copy_helper_block_");
736 CodeGenTypes &Types = CGM.getTypes();
737 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
738
739 llvm::Function *Fn =
740 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
741 Name,
742 &CGM.getModule());
743
744 IdentifierInfo *II
745 = &CGM.getContext().Idents.get("__copy_helper_block_");
746
747 FunctionDecl *FD = FunctionDecl::Create(getContext(),
748 getContext().getTranslationUnitDecl(),
749 SourceLocation(), II, R,
750 FunctionDecl::Static, false,
751 true);
752 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +0000753
754 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
755 llvm::Type *PtrPtrT;
756 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
757 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
758 SrcObj = Builder.CreateLoad(SrcObj);
759
760 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
761 DstObj = Builder.CreateBitCast(DstObj, llvm::PointerType::get(T, 0));
762
763 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
764 int flag = NoteForHelper[i].flag;
765 int index = NoteForHelper[i].index;
766
767 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
768 || NoteForHelper[i].RequiresCopying) {
769 llvm::Value *Srcv = SrcObj;
770 Srcv = Builder.CreateStructGEP(Srcv, index);
771 Srcv = Builder.CreateBitCast(Srcv,
772 llvm::PointerType::get(PtrToInt8Ty, 0));
773 Srcv = Builder.CreateLoad(Srcv);
774
775 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
776 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
777
778 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
779 llvm::Value *F = getBlockObjectAssign();
780 Builder.CreateCall3(F, Dstv, Srcv, N);
781 }
782 }
783
Mike Stumpa4f668f2009-03-06 01:33:24 +0000784 CGF.FinishFunction();
785
786 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000787}
788
Mike Stumpcf62d392009-03-06 18:42:23 +0000789llvm::Constant *BlockFunction::
Mike Stump08920992009-03-07 02:35:30 +0000790GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
791 const llvm::StructType* T,
792 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000793 QualType R = getContext().VoidTy;
794
795 FunctionArgList Args;
796 // FIXME: This leaks
797 ImplicitParamDecl *Src =
798 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
799 getContext().getPointerType(getContext().VoidTy));
800
801 Args.push_back(std::make_pair(Src, Src->getType()));
802
803 const CGFunctionInfo &FI =
804 CGM.getTypes().getFunctionInfo(R, Args);
805
806 std::string Name = std::string("__destroy_helper_block_");
807 CodeGenTypes &Types = CGM.getTypes();
808 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
809
810 llvm::Function *Fn =
811 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
812 Name,
813 &CGM.getModule());
814
815 IdentifierInfo *II
816 = &CGM.getContext().Idents.get("__destroy_helper_block_");
817
818 FunctionDecl *FD = FunctionDecl::Create(getContext(),
819 getContext().getTranslationUnitDecl(),
820 SourceLocation(), II, R,
821 FunctionDecl::Static, false,
822 true);
823 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +0000824
825 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
826 llvm::Type *PtrPtrT;
827 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
828 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
829 SrcObj = Builder.CreateLoad(SrcObj);
830
831 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
832 int flag = NoteForHelper[i].flag;
833 int index = NoteForHelper[i].index;
834
835 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
836 || NoteForHelper[i].RequiresCopying) {
837 llvm::Value *Srcv = SrcObj;
838 Srcv = Builder.CreateStructGEP(Srcv, index);
839 Srcv = Builder.CreateBitCast(Srcv,
840 llvm::PointerType::get(PtrToInt8Ty, 0));
841 Srcv = Builder.CreateLoad(Srcv);
842
843 BuildBlockRelease(Srcv, flag);
844 }
845 }
846
Mike Stumpa4f668f2009-03-06 01:33:24 +0000847 CGF.FinishFunction();
848
849 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
850}
851
Mike Stump08920992009-03-07 02:35:30 +0000852llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
853 std::vector<HelperInfo> &NoteForHelper) {
854 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
855 T, NoteForHelper);
Mike Stumpa4f668f2009-03-06 01:33:24 +0000856}
857
Mike Stump08920992009-03-07 02:35:30 +0000858llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
859 std::vector<HelperInfo> &NoteForHelper) {
860 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
861 T, NoteForHelper);
Mike Stumpdab514f2009-03-04 03:23:46 +0000862}
Mike Stump797b6322009-03-05 01:23:13 +0000863
Mike Stumpee094222009-03-06 06:12:24 +0000864llvm::Constant *BlockFunction::
865GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stump45031c02009-03-06 02:29:21 +0000866 QualType R = getContext().VoidTy;
867
868 FunctionArgList Args;
869 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +0000870 ImplicitParamDecl *Dst =
871 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
872 getContext().getPointerType(getContext().VoidTy));
873 Args.push_back(std::make_pair(Dst, Dst->getType()));
874
875 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +0000876 ImplicitParamDecl *Src =
877 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
878 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +0000879 Args.push_back(std::make_pair(Src, Src->getType()));
880
881 const CGFunctionInfo &FI =
882 CGM.getTypes().getFunctionInfo(R, Args);
883
884 std::string Name = std::string("__Block_byref_id_object_copy_");
885 CodeGenTypes &Types = CGM.getTypes();
886 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
887
888 llvm::Function *Fn =
889 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
890 Name,
891 &CGM.getModule());
892
893 IdentifierInfo *II
894 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
895
896 FunctionDecl *FD = FunctionDecl::Create(getContext(),
897 getContext().getTranslationUnitDecl(),
898 SourceLocation(), II, R,
899 FunctionDecl::Static, false,
900 true);
901 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +0000902
903 // dst->x
904 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
905 V = Builder.CreateBitCast(V, T);
906 V = Builder.CreateStructGEP(V, 6, "x");
907 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
908
909 // src->x
910 V = CGF.GetAddrOfLocalVar(Src);
911 V = Builder.CreateLoad(V);
912 V = Builder.CreateBitCast(V, T);
913 V = Builder.CreateStructGEP(V, 6, "x");
914 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
915 llvm::Value *SrcObj = Builder.CreateLoad(V);
916
917 flag |= BLOCK_BYREF_CALLER;
918
919 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
920 llvm::Value *F = getBlockObjectAssign();
921 Builder.CreateCall3(F, DstObj, SrcObj, N);
922
Mike Stump45031c02009-03-06 02:29:21 +0000923 CGF.FinishFunction();
924
925 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
926}
927
Mike Stump1851b682009-03-06 04:53:30 +0000928llvm::Constant *
929BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
930 int flag) {
Mike Stump45031c02009-03-06 02:29:21 +0000931 QualType R = getContext().VoidTy;
932
933 FunctionArgList Args;
934 // FIXME: This leaks
935 ImplicitParamDecl *Src =
936 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
937 getContext().getPointerType(getContext().VoidTy));
938
939 Args.push_back(std::make_pair(Src, Src->getType()));
940
941 const CGFunctionInfo &FI =
942 CGM.getTypes().getFunctionInfo(R, Args);
943
944 std::string Name = std::string("__Block_byref_id_object_dispose_");
945 CodeGenTypes &Types = CGM.getTypes();
946 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
947
948 llvm::Function *Fn =
949 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
950 Name,
951 &CGM.getModule());
952
953 IdentifierInfo *II
954 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
955
956 FunctionDecl *FD = FunctionDecl::Create(getContext(),
957 getContext().getTranslationUnitDecl(),
958 SourceLocation(), II, R,
959 FunctionDecl::Static, false,
960 true);
961 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +0000962
963 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
964 V = Builder.CreateBitCast(V, T);
965 V = Builder.CreateStructGEP(V, 6, "x");
966 V = Builder.CreateBitCast(V, PtrToInt8Ty);
967
Mike Stump1851b682009-03-06 04:53:30 +0000968 flag |= BLOCK_BYREF_CALLER;
969 BuildBlockRelease(V, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000970 CGF.FinishFunction();
971
972 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
973}
974
Mike Stumpee094222009-03-06 06:12:24 +0000975llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
976 int flag) {
977 return CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000978}
979
Mike Stump1851b682009-03-06 04:53:30 +0000980llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
981 int flag) {
982 return CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000983}
984
Mike Stump797b6322009-03-05 01:23:13 +0000985llvm::Value *BlockFunction::getBlockObjectDispose() {
986 if (CGM.BlockObjectDispose == 0) {
987 const llvm::FunctionType *FTy;
988 std::vector<const llvm::Type*> ArgTys;
989 const llvm::Type *ResultType = llvm::Type::VoidTy;
990 ArgTys.push_back(PtrToInt8Ty);
991 ArgTys.push_back(llvm::Type::Int32Ty);
992 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump00470a12009-03-05 08:32:30 +0000993 CGM.BlockObjectDispose
Mike Stump797b6322009-03-05 01:23:13 +0000994 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
995 }
996 return CGM.BlockObjectDispose;
997}
998
Mike Stumpee094222009-03-06 06:12:24 +0000999llvm::Value *BlockFunction::getBlockObjectAssign() {
1000 if (CGM.BlockObjectAssign == 0) {
1001 const llvm::FunctionType *FTy;
1002 std::vector<const llvm::Type*> ArgTys;
1003 const llvm::Type *ResultType = llvm::Type::VoidTy;
1004 ArgTys.push_back(PtrToInt8Ty);
1005 ArgTys.push_back(PtrToInt8Ty);
1006 ArgTys.push_back(llvm::Type::Int32Ty);
1007 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1008 CGM.BlockObjectAssign
1009 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1010 }
1011 return CGM.BlockObjectAssign;
1012}
1013
Mike Stump1851b682009-03-06 04:53:30 +00001014void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Mike Stump797b6322009-03-05 01:23:13 +00001015 llvm::Value *F = getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001016 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001017 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump1851b682009-03-06 04:53:30 +00001018 N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
Mike Stump797b6322009-03-05 01:23:13 +00001019 Builder.CreateCall2(F, V, N);
1020}
Mike Stump00470a12009-03-05 08:32:30 +00001021
1022ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001023
1024BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1025 CGBuilderTy &B)
1026 : CGM(cgm), CGF(cgf), Builder(B) {
1027 PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1028
1029 BlockHasCopyDispose = false;
1030}