blob: c8d9655951d6aec4009d22d7baa756e47c712799 [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
447 const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(BPT);
448 bool IsVariadic =
449 BPT->getPointeeType()->getAsFunctionProtoType()->isVariadic();
450
451 // Cast the function pointer to the right type.
452 const llvm::Type *BlockFTy =
453 CGM.getTypes().GetFunctionType(FnInfo, IsVariadic);
454
455 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
456 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
457
Anders Carlssonacfde802009-02-12 00:39:25 +0000458 // And call the block.
Anders Carlssonf8544a42009-04-07 00:20:24 +0000459 return EmitCall(FnInfo, Func, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000460}
Anders Carlssond5cab542009-02-12 17:55:02 +0000461
Mike Stumpdab514f2009-03-04 03:23:46 +0000462llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
463 uint64_t &offset = BlockDecls[E->getDecl()];
464
465 const llvm::Type *Ty;
466 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
467
Mike Stumpdab514f2009-03-04 03:23:46 +0000468 // See if we have already allocated an offset for this variable.
469 if (offset == 0) {
Mike Stump00470a12009-03-05 08:32:30 +0000470 // Don't run the expensive check, unless we have to.
471 if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
472 BlockHasCopyDispose = true;
Mike Stumpdab514f2009-03-04 03:23:46 +0000473 // if not, allocate one now.
474 offset = getBlockOffset(E);
475 }
476
477 llvm::Value *BlockLiteral = LoadBlockStruct();
478 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
479 llvm::ConstantInt::get(llvm::Type::Int64Ty,
480 offset),
Mike Stump58a85142009-03-04 22:48:06 +0000481 "block.literal");
Mike Stumpdab514f2009-03-04 03:23:46 +0000482 if (E->isByRef()) {
483 bool needsCopyDispose = BlockRequiresCopying(E->getType());
484 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
485 const llvm::Type *PtrStructTy
486 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
Mike Stumpa8b60c92009-03-21 21:00:35 +0000487 // The block literal will need a copy/destroy helper.
488 BlockHasCopyDispose = true;
Mike Stumpdab514f2009-03-04 03:23:46 +0000489 Ty = PtrStructTy;
490 Ty = llvm::PointerType::get(Ty, 0);
491 V = Builder.CreateBitCast(V, Ty);
492 V = Builder.CreateLoad(V, false);
493 V = Builder.CreateStructGEP(V, 1, "forwarding");
494 V = Builder.CreateLoad(V, false);
495 V = Builder.CreateBitCast(V, PtrStructTy);
496 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
497 } else {
498 Ty = llvm::PointerType::get(Ty, 0);
499 V = Builder.CreateBitCast(V, Ty);
500 }
501 return V;
502}
503
Mike Stump6cc88f72009-03-20 21:53:12 +0000504void CodeGenFunction::BlockForwardSelf() {
505 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
506 ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
507 llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
508 if (DMEntry)
509 return;
510 // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
511 BlockDeclRefExpr *BDRE = new (getContext())
512 BlockDeclRefExpr(SelfDecl,
513 SelfDecl->getType(), SourceLocation(), false);
514 DMEntry = GetAddrOfBlockDecl(BDRE);
515}
516
Mike Stump67a64482009-02-14 22:16:35 +0000517llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000518BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000519 // Generate the block descriptor.
520 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000521 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
522 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000523
Anders Carlssond5cab542009-02-12 17:55:02 +0000524 llvm::Constant *DescriptorFields[2];
Mike Stumpa5448542009-02-13 15:32:32 +0000525
Anders Carlssond5cab542009-02-12 17:55:02 +0000526 // Reserved
527 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000528
Anders Carlssond5cab542009-02-12 17:55:02 +0000529 // Block literal size. For global blocks we just use the size of the generic
530 // block literal struct.
Mike Stumpa5448542009-02-13 15:32:32 +0000531 uint64_t BlockLiteralSize =
Mike Stump9b8a7972009-02-13 15:25:34 +0000532 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlssond5cab542009-02-12 17:55:02 +0000533 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpa5448542009-02-13 15:32:32 +0000534
535 llvm::Constant *DescriptorStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000536 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpa5448542009-02-13 15:32:32 +0000537
Anders Carlssond5cab542009-02-12 17:55:02 +0000538 llvm::GlobalVariable *Descriptor =
539 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000540 llvm::GlobalVariable::InternalLinkage,
541 DescriptorStruct, "__block_descriptor_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000542 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000543
Anders Carlssond5cab542009-02-12 17:55:02 +0000544 // Generate the constants for the block literal.
545 llvm::Constant *LiteralFields[5];
Mike Stumpa5448542009-02-13 15:32:32 +0000546
Mike Stump67a64482009-02-14 22:16:35 +0000547 CodeGenFunction::BlockInfo Info(0, n);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000548 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000549 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Daniel Dunbard67b09a2009-03-12 03:07:24 +0000550 bool subBlockHasCopyDispose = false;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000551 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000552 llvm::Function *Fn
Mike Stump6cc88f72009-03-20 21:53:12 +0000553 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000554 subBlockSize,
Mike Stump90a90432009-03-04 18:47:42 +0000555 subBlockAlign,
Mike Stump00470a12009-03-05 08:32:30 +0000556 subBlockDeclRefDecls,
557 subBlockHasCopyDispose);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000558 assert(subBlockSize == BlockLiteralSize
559 && "no imports allowed for global block");
Daniel Dunbard67b09a2009-03-12 03:07:24 +0000560 assert(!subBlockHasCopyDispose && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000561
Anders Carlssond5cab542009-02-12 17:55:02 +0000562 // isa
Mike Stumpf99f1d02009-02-13 17:23:42 +0000563 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000564
Anders Carlssond5cab542009-02-12 17:55:02 +0000565 // Flags
Mike Stump00470a12009-03-05 08:32:30 +0000566 LiteralFields[1] =
Anders Carlsson8045ee02009-03-01 21:09:29 +0000567 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpa5448542009-02-13 15:32:32 +0000568
Anders Carlssond5cab542009-02-12 17:55:02 +0000569 // Reserved
Mike Stump7cbb3602009-02-13 16:01:35 +0000570 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000571
Anders Carlssond5cab542009-02-12 17:55:02 +0000572 // Function
573 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000574
Anders Carlssond5cab542009-02-12 17:55:02 +0000575 // Descriptor
576 LiteralFields[4] = Descriptor;
Mike Stumpa5448542009-02-13 15:32:32 +0000577
578 llvm::Constant *BlockLiteralStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000579 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpa5448542009-02-13 15:32:32 +0000580
581 llvm::GlobalVariable *BlockLiteral =
Anders Carlssond5cab542009-02-12 17:55:02 +0000582 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000583 llvm::GlobalVariable::InternalLinkage,
584 BlockLiteralStruct, "__block_literal_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000585 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000586
Anders Carlssond5cab542009-02-12 17:55:02 +0000587 return BlockLiteral;
588}
589
Mike Stump4e7a1f72009-02-21 20:00:35 +0000590llvm::Value *CodeGenFunction::LoadBlockStruct() {
591 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
592}
593
Mike Stump00470a12009-03-05 08:32:30 +0000594llvm::Function *
595CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
596 const BlockInfo& Info,
Mike Stump6cc88f72009-03-20 21:53:12 +0000597 const Decl *OuterFuncDecl,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000598 llvm::DenseMap<const Decl*, llvm::Value*> ldm,
Mike Stump00470a12009-03-05 08:32:30 +0000599 uint64_t &Size,
600 uint64_t &Align,
601 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
602 bool &subBlockHasCopyDispose) {
Mike Stump7f28a9c2009-03-13 23:34:28 +0000603 // Arrange for local static and local extern declarations to appear
604 // to be local to this function as well, as they are directly referenced
605 // in a block.
606 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
607 i != ldm.end();
608 ++i) {
609 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
610
611 if (VD->getStorageClass() == VarDecl::Static
612 || VD->getStorageClass() == VarDecl::Extern)
613 LocalDeclMap[VD] = i->second;
614 }
615
Eli Friedman48f91222009-03-28 03:24:54 +0000616 // FIXME: We need to rearrange the code for copy/dispose so we have this
617 // sooner, so we can calculate offsets correctly.
618 if (!BlockHasCopyDispose)
619 BlockOffset = CGM.getTargetData()
620 .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
621 else
622 BlockOffset = CGM.getTargetData()
623 .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
624 BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
625
Douglas Gregor72564e72009-02-26 23:50:07 +0000626 const FunctionProtoType *FTy =
Chris Lattner161d36d2009-02-28 19:01:03 +0000627 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpa5448542009-02-13 15:32:32 +0000628
Anders Carlssond5cab542009-02-12 17:55:02 +0000629 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000630
Chris Lattner161d36d2009-02-28 19:01:03 +0000631 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000632
633 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000634 ImplicitParamDecl *SelfDecl =
Anders Carlssond5cab542009-02-12 17:55:02 +0000635 ImplicitParamDecl::Create(getContext(), 0,
636 SourceLocation(), 0,
637 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000638
Anders Carlssond5cab542009-02-12 17:55:02 +0000639 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000640 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000641
Steve Naroffe78b8092009-03-13 16:56:44 +0000642 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000643 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000644 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000645
646 const CGFunctionInfo &FI =
Anders Carlssond5cab542009-02-12 17:55:02 +0000647 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
648
Mike Stump67a64482009-02-14 22:16:35 +0000649 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlssond5cab542009-02-12 17:55:02 +0000650 CodeGenTypes &Types = CGM.getTypes();
651 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000652
653 llvm::Function *Fn =
Anders Carlssond5cab542009-02-12 17:55:02 +0000654 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
655 Name,
656 &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000657
658 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000659 BExpr->getBody()->getLocEnd());
Mike Stump6cc88f72009-03-20 21:53:12 +0000660 CurFuncDecl = OuterFuncDecl;
Chris Lattner161d36d2009-02-28 19:01:03 +0000661 EmitStmt(BExpr->getBody());
662 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000663
Mike Stump8a2b4b12009-02-25 23:33:13 +0000664 // The runtime needs a minimum alignment of a void *.
665 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
666 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
667
Mike Stump4e7a1f72009-02-21 20:00:35 +0000668 Size = BlockOffset;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000669 Align = BlockAlign;
670 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump00470a12009-03-05 08:32:30 +0000671 subBlockHasCopyDispose |= BlockHasCopyDispose;
Anders Carlssond5cab542009-02-12 17:55:02 +0000672 return Fn;
673}
Mike Stumpa99038c2009-02-28 09:07:16 +0000674
Mike Stump08920992009-03-07 02:35:30 +0000675uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000676 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
677
678 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
679 uint64_t Align = getContext().getDeclAlignInBytes(D);
680
681 if (BDRE->isByRef()) {
682 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
683 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
684 }
685
686 assert ((Align > 0) && "alignment must be 1 byte or more");
687
688 uint64_t OldOffset = BlockOffset;
689
690 // Ensure proper alignment, even if it means we have to have a gap
691 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
692 BlockAlign = std::max(Align, BlockAlign);
Mike Stump00470a12009-03-05 08:32:30 +0000693
Mike Stumpa99038c2009-02-28 09:07:16 +0000694 uint64_t Pad = BlockOffset - OldOffset;
695 if (Pad) {
696 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
697 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
698 llvm::APInt(32, Pad),
699 ArrayType::Normal, 0);
700 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
701 0, QualType(PadTy), VarDecl::None,
702 SourceLocation());
703 Expr *E;
704 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
705 SourceLocation(), false, false);
706 BlockDeclRefDecls.push_back(E);
707 }
708 BlockDeclRefDecls.push_back(BDRE);
709
710 BlockOffset += Size;
711 return BlockOffset-Size;
712}
Mike Stumpdab514f2009-03-04 03:23:46 +0000713
Mike Stump08920992009-03-07 02:35:30 +0000714llvm::Constant *BlockFunction::
715GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
716 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000717 QualType R = getContext().VoidTy;
718
719 FunctionArgList Args;
720 // FIXME: This leaks
Mike Stump08920992009-03-07 02:35:30 +0000721 ImplicitParamDecl *Dst =
722 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
723 getContext().getPointerType(getContext().VoidTy));
724 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000725 ImplicitParamDecl *Src =
726 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
727 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000728 Args.push_back(std::make_pair(Src, Src->getType()));
729
730 const CGFunctionInfo &FI =
731 CGM.getTypes().getFunctionInfo(R, Args);
732
733 std::string Name = std::string("__copy_helper_block_");
734 CodeGenTypes &Types = CGM.getTypes();
735 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
736
737 llvm::Function *Fn =
738 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
739 Name,
740 &CGM.getModule());
741
742 IdentifierInfo *II
743 = &CGM.getContext().Idents.get("__copy_helper_block_");
744
745 FunctionDecl *FD = FunctionDecl::Create(getContext(),
746 getContext().getTranslationUnitDecl(),
747 SourceLocation(), II, R,
748 FunctionDecl::Static, false,
749 true);
750 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +0000751
752 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
753 llvm::Type *PtrPtrT;
754 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
755 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
756 SrcObj = Builder.CreateLoad(SrcObj);
757
758 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
759 DstObj = Builder.CreateBitCast(DstObj, llvm::PointerType::get(T, 0));
760
761 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
762 int flag = NoteForHelper[i].flag;
763 int index = NoteForHelper[i].index;
764
765 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
766 || NoteForHelper[i].RequiresCopying) {
767 llvm::Value *Srcv = SrcObj;
768 Srcv = Builder.CreateStructGEP(Srcv, index);
769 Srcv = Builder.CreateBitCast(Srcv,
770 llvm::PointerType::get(PtrToInt8Ty, 0));
771 Srcv = Builder.CreateLoad(Srcv);
772
773 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
774 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
775
776 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
777 llvm::Value *F = getBlockObjectAssign();
778 Builder.CreateCall3(F, Dstv, Srcv, N);
779 }
780 }
781
Mike Stumpa4f668f2009-03-06 01:33:24 +0000782 CGF.FinishFunction();
783
784 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000785}
786
Mike Stumpcf62d392009-03-06 18:42:23 +0000787llvm::Constant *BlockFunction::
Mike Stump08920992009-03-07 02:35:30 +0000788GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
789 const llvm::StructType* T,
790 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000791 QualType R = getContext().VoidTy;
792
793 FunctionArgList Args;
794 // FIXME: This leaks
795 ImplicitParamDecl *Src =
796 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
797 getContext().getPointerType(getContext().VoidTy));
798
799 Args.push_back(std::make_pair(Src, Src->getType()));
800
801 const CGFunctionInfo &FI =
802 CGM.getTypes().getFunctionInfo(R, Args);
803
804 std::string Name = std::string("__destroy_helper_block_");
805 CodeGenTypes &Types = CGM.getTypes();
806 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
807
808 llvm::Function *Fn =
809 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
810 Name,
811 &CGM.getModule());
812
813 IdentifierInfo *II
814 = &CGM.getContext().Idents.get("__destroy_helper_block_");
815
816 FunctionDecl *FD = FunctionDecl::Create(getContext(),
817 getContext().getTranslationUnitDecl(),
818 SourceLocation(), II, R,
819 FunctionDecl::Static, false,
820 true);
821 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +0000822
823 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
824 llvm::Type *PtrPtrT;
825 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
826 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
827 SrcObj = Builder.CreateLoad(SrcObj);
828
829 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
830 int flag = NoteForHelper[i].flag;
831 int index = NoteForHelper[i].index;
832
833 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
834 || NoteForHelper[i].RequiresCopying) {
835 llvm::Value *Srcv = SrcObj;
836 Srcv = Builder.CreateStructGEP(Srcv, index);
837 Srcv = Builder.CreateBitCast(Srcv,
838 llvm::PointerType::get(PtrToInt8Ty, 0));
839 Srcv = Builder.CreateLoad(Srcv);
840
841 BuildBlockRelease(Srcv, flag);
842 }
843 }
844
Mike Stumpa4f668f2009-03-06 01:33:24 +0000845 CGF.FinishFunction();
846
847 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
848}
849
Mike Stump08920992009-03-07 02:35:30 +0000850llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
851 std::vector<HelperInfo> &NoteForHelper) {
852 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
853 T, NoteForHelper);
Mike Stumpa4f668f2009-03-06 01:33:24 +0000854}
855
Mike Stump08920992009-03-07 02:35:30 +0000856llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
857 std::vector<HelperInfo> &NoteForHelper) {
858 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
859 T, NoteForHelper);
Mike Stumpdab514f2009-03-04 03:23:46 +0000860}
Mike Stump797b6322009-03-05 01:23:13 +0000861
Mike Stumpee094222009-03-06 06:12:24 +0000862llvm::Constant *BlockFunction::
863GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stump45031c02009-03-06 02:29:21 +0000864 QualType R = getContext().VoidTy;
865
866 FunctionArgList Args;
867 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +0000868 ImplicitParamDecl *Dst =
869 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
870 getContext().getPointerType(getContext().VoidTy));
871 Args.push_back(std::make_pair(Dst, Dst->getType()));
872
873 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +0000874 ImplicitParamDecl *Src =
875 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
876 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +0000877 Args.push_back(std::make_pair(Src, Src->getType()));
878
879 const CGFunctionInfo &FI =
880 CGM.getTypes().getFunctionInfo(R, Args);
881
882 std::string Name = std::string("__Block_byref_id_object_copy_");
883 CodeGenTypes &Types = CGM.getTypes();
884 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
885
886 llvm::Function *Fn =
887 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
888 Name,
889 &CGM.getModule());
890
891 IdentifierInfo *II
892 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
893
894 FunctionDecl *FD = FunctionDecl::Create(getContext(),
895 getContext().getTranslationUnitDecl(),
896 SourceLocation(), II, R,
897 FunctionDecl::Static, false,
898 true);
899 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +0000900
901 // dst->x
902 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
903 V = Builder.CreateBitCast(V, T);
904 V = Builder.CreateStructGEP(V, 6, "x");
905 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
906
907 // src->x
908 V = CGF.GetAddrOfLocalVar(Src);
909 V = Builder.CreateLoad(V);
910 V = Builder.CreateBitCast(V, T);
911 V = Builder.CreateStructGEP(V, 6, "x");
912 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
913 llvm::Value *SrcObj = Builder.CreateLoad(V);
914
915 flag |= BLOCK_BYREF_CALLER;
916
917 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
918 llvm::Value *F = getBlockObjectAssign();
919 Builder.CreateCall3(F, DstObj, SrcObj, N);
920
Mike Stump45031c02009-03-06 02:29:21 +0000921 CGF.FinishFunction();
922
923 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
924}
925
Mike Stump1851b682009-03-06 04:53:30 +0000926llvm::Constant *
927BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
928 int flag) {
Mike Stump45031c02009-03-06 02:29:21 +0000929 QualType R = getContext().VoidTy;
930
931 FunctionArgList Args;
932 // FIXME: This leaks
933 ImplicitParamDecl *Src =
934 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
935 getContext().getPointerType(getContext().VoidTy));
936
937 Args.push_back(std::make_pair(Src, Src->getType()));
938
939 const CGFunctionInfo &FI =
940 CGM.getTypes().getFunctionInfo(R, Args);
941
942 std::string Name = std::string("__Block_byref_id_object_dispose_");
943 CodeGenTypes &Types = CGM.getTypes();
944 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
945
946 llvm::Function *Fn =
947 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
948 Name,
949 &CGM.getModule());
950
951 IdentifierInfo *II
952 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
953
954 FunctionDecl *FD = FunctionDecl::Create(getContext(),
955 getContext().getTranslationUnitDecl(),
956 SourceLocation(), II, R,
957 FunctionDecl::Static, false,
958 true);
959 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +0000960
961 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
962 V = Builder.CreateBitCast(V, T);
963 V = Builder.CreateStructGEP(V, 6, "x");
964 V = Builder.CreateBitCast(V, PtrToInt8Ty);
965
Mike Stump1851b682009-03-06 04:53:30 +0000966 flag |= BLOCK_BYREF_CALLER;
967 BuildBlockRelease(V, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000968 CGF.FinishFunction();
969
970 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
971}
972
Mike Stumpee094222009-03-06 06:12:24 +0000973llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
974 int flag) {
975 return CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000976}
977
Mike Stump1851b682009-03-06 04:53:30 +0000978llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
979 int flag) {
980 return CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000981}
982
Mike Stump797b6322009-03-05 01:23:13 +0000983llvm::Value *BlockFunction::getBlockObjectDispose() {
984 if (CGM.BlockObjectDispose == 0) {
985 const llvm::FunctionType *FTy;
986 std::vector<const llvm::Type*> ArgTys;
987 const llvm::Type *ResultType = llvm::Type::VoidTy;
988 ArgTys.push_back(PtrToInt8Ty);
989 ArgTys.push_back(llvm::Type::Int32Ty);
990 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump00470a12009-03-05 08:32:30 +0000991 CGM.BlockObjectDispose
Mike Stump797b6322009-03-05 01:23:13 +0000992 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
993 }
994 return CGM.BlockObjectDispose;
995}
996
Mike Stumpee094222009-03-06 06:12:24 +0000997llvm::Value *BlockFunction::getBlockObjectAssign() {
998 if (CGM.BlockObjectAssign == 0) {
999 const llvm::FunctionType *FTy;
1000 std::vector<const llvm::Type*> ArgTys;
1001 const llvm::Type *ResultType = llvm::Type::VoidTy;
1002 ArgTys.push_back(PtrToInt8Ty);
1003 ArgTys.push_back(PtrToInt8Ty);
1004 ArgTys.push_back(llvm::Type::Int32Ty);
1005 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1006 CGM.BlockObjectAssign
1007 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1008 }
1009 return CGM.BlockObjectAssign;
1010}
1011
Mike Stump1851b682009-03-06 04:53:30 +00001012void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Mike Stump797b6322009-03-05 01:23:13 +00001013 llvm::Value *F = getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001014 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001015 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump1851b682009-03-06 04:53:30 +00001016 N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
Mike Stump797b6322009-03-05 01:23:13 +00001017 Builder.CreateCall2(F, V, N);
1018}
Mike Stump00470a12009-03-05 08:32:30 +00001019
1020ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001021
1022BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1023 CGBuilderTy &B)
1024 : CGM(cgm), CGF(cgf), Builder(B) {
1025 PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1026
1027 BlockHasCopyDispose = false;
1028}