blob: 344ac60d98add342ff461598fa7181ed1ef44f9d [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"
16#include "llvm/Module.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000017#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000018
19#include <algorithm>
20
21using namespace clang;
22using namespace CodeGen;
23
Mike Stump58919e12009-03-04 13:17:22 +000024// Temporary code to enable testing of __block variables
25// #include "clang/Frontend/CompileOptions.h"
26#include "llvm/Support/CommandLine.h"
27static llvm::cl::opt<bool>
28Enable__block("f__block",
29 // See all the FIXMEs for the various work that needs to be done
30 llvm::cl::desc("temporary option to turn on __block precessing "
31 "even though the code isn't done yet"),
32 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
Mike Stump00470a12009-03-05 08:32:30 +000033 llvm::cl::ZeroOrMore,
34 llvm::cl::init(false));
Mike Stump58919e12009-03-04 13:17:22 +000035
Mike Stumpcf62d392009-03-06 18:42:23 +000036llvm::Constant *CodeGenFunction::
Mike Stump08920992009-03-07 02:35:30 +000037BuildDescriptorBlockDecl(uint64_t Size, const llvm::StructType* Ty,
38 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump56129b12009-02-13 16:55:51 +000039 const llvm::Type *UnsignedLongTy
40 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpe5fee252009-02-13 16:19:19 +000041 llvm::Constant *C;
42 std::vector<llvm::Constant*> Elts;
43
44 // reserved
Mike Stump56129b12009-02-13 16:55:51 +000045 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000046 Elts.push_back(C);
47
48 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000049 // FIXME: What is the right way to say this doesn't fit? We should give
50 // a user diagnostic in that case. Better fix would be to change the
51 // API to size_t.
Mike Stump4e7a1f72009-02-21 20:00:35 +000052 C = llvm::ConstantInt::get(UnsignedLongTy, Size);
Mike Stumpe5fee252009-02-13 16:19:19 +000053 Elts.push_back(C);
54
55 if (BlockHasCopyDispose) {
56 // copy_func_helper_decl
Mike Stump08920992009-03-07 02:35:30 +000057 Elts.push_back(BuildCopyHelper(Ty, *NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000058
59 // destroy_func_decl
Mike Stump08920992009-03-07 02:35:30 +000060 Elts.push_back(BuildDestroyHelper(Ty, *NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000061 }
62
63 C = llvm::ConstantStruct::get(Elts);
64
Mike Stumpe5fee252009-02-13 16:19:19 +000065 C = new llvm::GlobalVariable(C->getType(), true,
66 llvm::GlobalValue::InternalLinkage,
Mike Stump7d6dc4f2009-02-13 20:17:16 +000067 C, "__block_descriptor_tmp", &CGM.getModule());
Mike Stumpe5fee252009-02-13 16:19:19 +000068 return C;
69}
70
Mike Stump2a998142009-03-04 18:17:45 +000071llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Mike Stumpf99f1d02009-02-13 17:23:42 +000072 if (NSConcreteGlobalBlock)
73 return NSConcreteGlobalBlock;
74
Mike Stumpf7448952009-02-13 19:38:12 +000075 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000076 // same thing as CreateRuntimeFunction if there's already a variable with the
77 // same name.
Mike Stumpf99f1d02009-02-13 17:23:42 +000078 NSConcreteGlobalBlock
Mike Stump00470a12009-03-05 08:32:30 +000079 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stumpf99f1d02009-02-13 17:23:42 +000080 llvm::GlobalValue::ExternalLinkage,
81 0, "_NSConcreteGlobalBlock",
82 &getModule());
83
84 return NSConcreteGlobalBlock;
85}
86
Mike Stump2a998142009-03-04 18:17:45 +000087llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Mike Stump59c5b112009-02-13 19:29:27 +000088 if (NSConcreteStackBlock)
89 return NSConcreteStackBlock;
90
Mike Stumpf7448952009-02-13 19:38:12 +000091 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000092 // same thing as CreateRuntimeFunction if there's already a variable with the
93 // same name.
Mike Stump59c5b112009-02-13 19:29:27 +000094 NSConcreteStackBlock
Mike Stump00470a12009-03-05 08:32:30 +000095 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stump59c5b112009-02-13 19:29:27 +000096 llvm::GlobalValue::ExternalLinkage,
97 0, "_NSConcreteStackBlock",
98 &getModule());
99
100 return NSConcreteStackBlock;
101}
102
Mike Stump00470a12009-03-05 08:32:30 +0000103static void CollectBlockDeclRefInfo(const Stmt *S,
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000104 CodeGenFunction::BlockInfo &Info) {
105 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
106 I != E; ++I)
Daniel Dunbar82573ee2009-03-02 07:00:57 +0000107 if (*I)
108 CollectBlockDeclRefInfo(*I, Info);
Mike Stump00470a12009-03-05 08:32:30 +0000109
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000110 if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
111 // FIXME: Handle enums.
112 if (isa<FunctionDecl>(DE->getDecl()))
113 return;
Mike Stump00470a12009-03-05 08:32:30 +0000114
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000115 if (DE->isByRef())
116 Info.ByRefDeclRefs.push_back(DE);
117 else
118 Info.ByCopyDeclRefs.push_back(DE);
119 }
120}
121
Mike Stump58a85142009-03-04 22:48:06 +0000122/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
123/// declared as a global variable instead of on the stack.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000124static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
125{
126 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
127}
128
Mike Stump58a85142009-03-04 22:48:06 +0000129// FIXME: Push most into CGM, passing down a few bits, like current function
130// name.
Mike Stump8a2b4b12009-02-25 23:33:13 +0000131llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Mike Stumpe5fee252009-02-13 16:19:19 +0000132
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000133 std::string Name = CurFn->getName();
134 CodeGenFunction::BlockInfo Info(0, Name.c_str());
135 CollectBlockDeclRefInfo(BE->getBody(), Info);
136
137 // Check if the block can be global.
Mike Stump58a85142009-03-04 22:48:06 +0000138 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
139 // to just have one code path. We should move this function into CGM and pass
140 // CGF, then we can just check to see if CGF is 0.
Mike Stumpdab514f2009-03-04 03:23:46 +0000141 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000142 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump00470a12009-03-05 08:32:30 +0000143
144 std::vector<llvm::Constant*> Elts(5);
Mike Stumpe5fee252009-02-13 16:19:19 +0000145 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000146 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000147
Mike Stumpe5fee252009-02-13 16:19:19 +0000148 {
149 // C = BuildBlockStructInitlist();
150 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
151
Mike Stump00470a12009-03-05 08:32:30 +0000152 // We run this first so that we set BlockHasCopyDispose from the entire
153 // block literal.
154 // __invoke
155 uint64_t subBlockSize, subBlockAlign;
156 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
157 llvm::Function *Fn
158 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
159 subBlockAlign,
160 subBlockDeclRefDecls,
161 BlockHasCopyDispose);
162 Elts[3] = Fn;
163
164 if (!Enable__block && BlockHasCopyDispose)
165 ErrorUnsupported(BE, "block literal that requires copy/dispose");
166
Mike Stumpe5fee252009-02-13 16:19:19 +0000167 if (BlockHasCopyDispose)
168 flags |= BLOCK_HAS_COPY_DISPOSE;
169
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000170 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000171 C = CGM.getNSConcreteStackBlock();
Mike Stumpe5fee252009-02-13 16:19:19 +0000172 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump00470a12009-03-05 08:32:30 +0000173 Elts[0] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000174
175 // __flags
176 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
177 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
178 C = llvm::ConstantInt::get(IntTy, flags);
Mike Stump00470a12009-03-05 08:32:30 +0000179 Elts[1] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000180
181 // __reserved
182 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump00470a12009-03-05 08:32:30 +0000183 Elts[2] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000184
Mike Stump8a2b4b12009-02-25 23:33:13 +0000185 if (subBlockDeclRefDecls.size() == 0) {
Mike Stumpcf62d392009-03-06 18:42:23 +0000186 // __descriptor
Mike Stump08920992009-03-07 02:35:30 +0000187 Elts[4] = BuildDescriptorBlockDecl(subBlockSize, 0, 0);
Mike Stumpcf62d392009-03-06 18:42:23 +0000188
Mike Stump5570cfe2009-03-01 20:07:53 +0000189 // Optimize to being a global block.
190 Elts[0] = CGM.getNSConcreteGlobalBlock();
191 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
192
Mike Stump8a2b4b12009-02-25 23:33:13 +0000193 C = llvm::ConstantStruct::get(Elts);
194
195 char Name[32];
196 sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
197 C = new llvm::GlobalVariable(C->getType(), true,
198 llvm::GlobalValue::InternalLinkage,
199 C, Name, &CGM.getModule());
200 QualType BPT = BE->getType();
201 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
202 return C;
203 }
Mike Stump00470a12009-03-05 08:32:30 +0000204
Mike Stump8a2b4b12009-02-25 23:33:13 +0000205 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
Mike Stump08920992009-03-07 02:35:30 +0000206 for (int i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000207 Types[i] = Elts[i]->getType();
Mike Stump08920992009-03-07 02:35:30 +0000208 Types[4] = PtrToInt8Ty;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000209
Mike Stumpa99038c2009-02-28 09:07:16 +0000210 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
211 const Expr *E = subBlockDeclRefDecls[i];
212 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
213 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000214 if (BDRE && BDRE->isByRef()) {
215 uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
216 Types[i+5] = llvm::PointerType::get(BuildByRefType(Ty, Align), 0);
217 } else
218 Types[i+5] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000219 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000220
Mike Stump08920992009-03-07 02:35:30 +0000221 llvm::StructType *Ty = llvm::StructType::get(Types, true);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000222
223 llvm::AllocaInst *A = CreateTempAlloca(Ty);
224 A->setAlignment(subBlockAlign);
225 V = A;
226
Mike Stump08920992009-03-07 02:35:30 +0000227 std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
228 int helpersize = 0;
229
230 for (unsigned i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000231 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump00470a12009-03-05 08:32:30 +0000232
Mike Stump8a2b4b12009-02-25 23:33:13 +0000233 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
234 {
Mike Stumpa99038c2009-02-28 09:07:16 +0000235 // FIXME: Push const down.
236 Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
237 DeclRefExpr *DR;
238 ValueDecl *VD;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000239
Mike Stumpa99038c2009-02-28 09:07:16 +0000240 DR = dyn_cast<DeclRefExpr>(E);
241 // Skip padding.
242 if (DR) continue;
243
244 BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
245 VD = BDRE->getDecl();
246
Mike Stumpdab514f2009-03-04 03:23:46 +0000247 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stump08920992009-03-07 02:35:30 +0000248 NoteForHelper[helpersize].index = i+5;
249 NoteForHelper[helpersize].RequiresCopying = BlockRequiresCopying(VD->getType());
250 NoteForHelper[helpersize].flag
251 = VD->getType()->isBlockPointerType() ? BLOCK_FIELD_IS_BLOCK : BLOCK_FIELD_IS_OBJECT;
252
Mike Stumpa99038c2009-02-28 09:07:16 +0000253 if (LocalDeclMap[VD]) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000254 if (BDRE->isByRef()) {
Mike Stump08920992009-03-07 02:35:30 +0000255 // FIXME: For only local, or all byrefs?
256 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
257 (0?BLOCK_FIELD_IS_WEAK : 0);
258 // FIXME: Add weak support
Mike Stumpdab514f2009-03-04 03:23:46 +0000259 const llvm::Type *Ty = Types[i+5];
260 llvm::Value *Loc = LocalDeclMap[VD];
261 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
262 Loc = Builder.CreateLoad(Loc, false);
263 Loc = Builder.CreateBitCast(Loc, Ty);
264 Builder.CreateStore(Loc, Addr);
Mike Stump08920992009-03-07 02:35:30 +0000265 ++helpersize;
Mike Stumpdab514f2009-03-04 03:23:46 +0000266 continue;
267 } else
268 E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
269 VD->getType(), SourceLocation(),
270 false, false);
Mike Stumpa99038c2009-02-28 09:07:16 +0000271 }
Mike Stumpdab514f2009-03-04 03:23:46 +0000272 if (BDRE->isByRef()) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000273 E = new (getContext())
274 UnaryOperator(E, UnaryOperator::AddrOf,
275 getContext().getPointerType(E->getType()),
276 SourceLocation());
Mike Stumpdab514f2009-03-04 03:23:46 +0000277 }
Mike Stump08920992009-03-07 02:35:30 +0000278 ++helpersize;
Mike Stumpa99038c2009-02-28 09:07:16 +0000279
Mike Stumpa99038c2009-02-28 09:07:16 +0000280 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpdab514f2009-03-04 03:23:46 +0000281 if (r.isScalar()) {
282 llvm::Value *Loc = r.getScalarVal();
283 const llvm::Type *Ty = Types[i+5];
284 if (BDRE->isByRef()) {
Mike Stump58a85142009-03-04 22:48:06 +0000285 // E is now the address of the value field, instead, we want the
286 // address of the actual ByRef struct. We optimize this slightly
287 // compared to gcc by not grabbing the forwarding slot as this must
288 // be done during Block_copy for us, and we can postpone the work
289 // until then.
290 uint64_t offset = BlockDecls[BDRE->getDecl()];
Mike Stump00470a12009-03-05 08:32:30 +0000291
Mike Stump58a85142009-03-04 22:48:06 +0000292 llvm::Value *BlockLiteral = LoadBlockStruct();
Mike Stump00470a12009-03-05 08:32:30 +0000293
Mike Stump58a85142009-03-04 22:48:06 +0000294 Loc = Builder.CreateGEP(BlockLiteral,
295 llvm::ConstantInt::get(llvm::Type::Int64Ty,
296 offset),
297 "block.literal");
298 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000299 Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stump58a85142009-03-04 22:48:06 +0000300 Loc = Builder.CreateLoad(Loc, false);
301 // Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000302 }
303 Builder.CreateStore(Loc, Addr);
304 } else if (r.isComplex())
Mike Stump8a2b4b12009-02-25 23:33:13 +0000305 // FIXME: implement
306 ErrorUnsupported(BE, "complex in block literal");
307 else if (r.isAggregate())
308 ; // Already created into the destination
309 else
310 assert (0 && "bad block variable");
311 // FIXME: Ensure that the offset created by the backend for
312 // the struct matches the previously computed offset in BlockDecls.
313 }
Mike Stump08920992009-03-07 02:35:30 +0000314 NoteForHelper.resize(helpersize);
Mike Stumpcf62d392009-03-06 18:42:23 +0000315
316 // __descriptor
Mike Stump08920992009-03-07 02:35:30 +0000317 llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockSize, Ty,
318 &NoteForHelper);
319 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
320 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
Mike Stumpe5fee252009-02-13 16:19:19 +0000321 }
Mike Stump00470a12009-03-05 08:32:30 +0000322
Mike Stumpbd65cac2009-02-19 01:01:04 +0000323 QualType BPT = BE->getType();
Mike Stump8a2b4b12009-02-25 23:33:13 +0000324 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stumpe5fee252009-02-13 16:19:19 +0000325}
326
327
Mike Stump2a998142009-03-04 18:17:45 +0000328const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000329 if (BlockDescriptorType)
330 return BlockDescriptorType;
331
Mike Stumpa5448542009-02-13 15:32:32 +0000332 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000333 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000334
Mike Stumpab695142009-02-13 15:16:56 +0000335 // struct __block_descriptor {
336 // unsigned long reserved;
337 // unsigned long block_size;
338 // };
Mike Stumpa5448542009-02-13 15:32:32 +0000339 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
340 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000341 NULL);
342
343 getModule().addTypeName("struct.__block_descriptor",
344 BlockDescriptorType);
345
346 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000347}
348
Mike Stump2a998142009-03-04 18:17:45 +0000349const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000350 if (GenericBlockLiteralType)
351 return GenericBlockLiteralType;
352
Mike Stumpa5448542009-02-13 15:32:32 +0000353 const llvm::Type *BlockDescPtrTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000354 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpa5448542009-02-13 15:32:32 +0000355
Mike Stump7cbb3602009-02-13 16:01:35 +0000356 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
357 getTypes().ConvertType(getContext().IntTy));
358
Mike Stump9b8a7972009-02-13 15:25:34 +0000359 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000360 // void *__isa;
361 // int __flags;
362 // int __reserved;
363 // void (*__invoke)(void *);
364 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000365 // };
Mike Stump797b6322009-03-05 01:23:13 +0000366 GenericBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000367 IntTy,
368 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000369 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000370 BlockDescPtrTy,
371 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000372
Mike Stump9b8a7972009-02-13 15:25:34 +0000373 getModule().addTypeName("struct.__block_literal_generic",
374 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000375
Mike Stump9b8a7972009-02-13 15:25:34 +0000376 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000377}
378
Mike Stump2a998142009-03-04 18:17:45 +0000379const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000380 if (GenericExtendedBlockLiteralType)
381 return GenericExtendedBlockLiteralType;
382
Mike Stumpbd65cac2009-02-19 01:01:04 +0000383 const llvm::Type *BlockDescPtrTy =
384 llvm::PointerType::getUnqual(getBlockDescriptorType());
385
386 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
387 getTypes().ConvertType(getContext().IntTy));
388
389 // struct __block_literal_generic {
390 // void *__isa;
391 // int __flags;
392 // int __reserved;
393 // void (*__invoke)(void *);
394 // struct __block_descriptor *__descriptor;
395 // void *__copy_func_helper_decl;
396 // void *__destroy_func_decl;
397 // };
Mike Stump797b6322009-03-05 01:23:13 +0000398 GenericExtendedBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000399 IntTy,
400 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000401 PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000402 BlockDescPtrTy,
Mike Stump797b6322009-03-05 01:23:13 +0000403 PtrToInt8Ty,
404 PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000405 NULL);
406
407 getModule().addTypeName("struct.__block_literal_extended_generic",
408 GenericExtendedBlockLiteralType);
409
410 return GenericExtendedBlockLiteralType;
411}
412
Mike Stumpa5448542009-02-13 15:32:32 +0000413/// getBlockFunctionType - Given a BlockPointerType, will return the
Anders Carlssonacfde802009-02-12 00:39:25 +0000414/// function type for the block, including the first block literal argument.
415static QualType getBlockFunctionType(ASTContext &Ctx,
Anders Carlssond5cab542009-02-12 17:55:02 +0000416 const BlockPointerType *BPT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000417 const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
Mike Stumpa5448542009-02-13 15:32:32 +0000418
Anders Carlssonacfde802009-02-12 00:39:25 +0000419 llvm::SmallVector<QualType, 8> Types;
420 Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000421
Douglas Gregor72564e72009-02-26 23:50:07 +0000422 for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000423 e = FTy->arg_type_end(); i != e; ++i)
424 Types.push_back(*i);
Mike Stumpa5448542009-02-13 15:32:32 +0000425
Anders Carlssonacfde802009-02-12 00:39:25 +0000426 return Ctx.getFunctionType(FTy->getResultType(),
Mike Stumpa5448542009-02-13 15:32:32 +0000427 &Types[0], Types.size(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000428 FTy->isVariadic(), 0);
429}
430
Anders Carlssond5cab542009-02-12 17:55:02 +0000431RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpa5448542009-02-13 15:32:32 +0000432 const BlockPointerType *BPT =
Anders Carlssonacfde802009-02-12 00:39:25 +0000433 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpa5448542009-02-13 15:32:32 +0000434
Anders Carlssonacfde802009-02-12 00:39:25 +0000435 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
436
437 // Get a pointer to the generic block literal.
438 const llvm::Type *BlockLiteralTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000439 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000440
441 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000442 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000443 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
444
445 // Get the function pointer from the literal.
446 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Mike Stump20733cd2009-02-22 13:27:11 +0000447 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000448
449 // Cast the function pointer to the right type.
Mike Stumpa5448542009-02-13 15:32:32 +0000450 const llvm::Type *BlockFTy =
Anders Carlssonacfde802009-02-12 00:39:25 +0000451 ConvertType(getBlockFunctionType(getContext(), BPT));
452 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
453 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
454
Mike Stumpa5448542009-02-13 15:32:32 +0000455 BlockLiteral =
456 Builder.CreateBitCast(BlockLiteral,
Anders Carlssonacfde802009-02-12 00:39:25 +0000457 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
458 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000459
Anders Carlssonacfde802009-02-12 00:39:25 +0000460 // Add the block literal.
461 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
462 CallArgList Args;
463 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000464
Anders Carlssonacfde802009-02-12 00:39:25 +0000465 // And the rest of the arguments.
Mike Stumpa5448542009-02-13 15:32:32 +0000466 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
Anders Carlssonacfde802009-02-12 00:39:25 +0000467 i != e; ++i)
Mike Stumpa5448542009-02-13 15:32:32 +0000468 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
Anders Carlssonacfde802009-02-12 00:39:25 +0000469 i->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000470
Anders Carlssonacfde802009-02-12 00:39:25 +0000471 // And call the block.
Mike Stumpa5448542009-02-13 15:32:32 +0000472 return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
Anders Carlssonacfde802009-02-12 00:39:25 +0000473 Func, Args);
474}
Anders Carlssond5cab542009-02-12 17:55:02 +0000475
Mike Stumpdab514f2009-03-04 03:23:46 +0000476llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
477 uint64_t &offset = BlockDecls[E->getDecl()];
478
479 const llvm::Type *Ty;
480 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
481
482 // FIXME: add support for copy/dispose helpers.
Mike Stump58919e12009-03-04 13:17:22 +0000483 if (!Enable__block && E->isByRef())
Mike Stumpdab514f2009-03-04 03:23:46 +0000484 ErrorUnsupported(E, "__block variable in block literal");
Mike Stumpa4f668f2009-03-06 01:33:24 +0000485 else if (!Enable__block && E->getType()->isBlockPointerType())
Mike Stumpdab514f2009-03-04 03:23:46 +0000486 ErrorUnsupported(E, "block pointer in block literal");
Mike Stump00470a12009-03-05 08:32:30 +0000487 else if (E->getDecl()->getAttr<ObjCNSObjectAttr>() ||
Mike Stumpdab514f2009-03-04 03:23:46 +0000488 getContext().isObjCNSObjectType(E->getType()))
489 ErrorUnsupported(E, "__attribute__((NSObject)) variable in block "
490 "literal");
Mike Stumpa4f668f2009-03-06 01:33:24 +0000491 else if (!Enable__block && getContext().isObjCObjectPointerType(E->getType()))
Mike Stumpdab514f2009-03-04 03:23:46 +0000492 ErrorUnsupported(E, "Objective-C variable in block literal");
493
494 // See if we have already allocated an offset for this variable.
495 if (offset == 0) {
Mike Stump00470a12009-03-05 08:32:30 +0000496 // Don't run the expensive check, unless we have to.
497 if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
498 BlockHasCopyDispose = true;
Mike Stumpdab514f2009-03-04 03:23:46 +0000499 // if not, allocate one now.
500 offset = getBlockOffset(E);
501 }
502
503 llvm::Value *BlockLiteral = LoadBlockStruct();
504 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
505 llvm::ConstantInt::get(llvm::Type::Int64Ty,
506 offset),
Mike Stump58a85142009-03-04 22:48:06 +0000507 "block.literal");
Mike Stumpdab514f2009-03-04 03:23:46 +0000508 if (E->isByRef()) {
509 bool needsCopyDispose = BlockRequiresCopying(E->getType());
510 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
511 const llvm::Type *PtrStructTy
512 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
513 Ty = PtrStructTy;
514 Ty = llvm::PointerType::get(Ty, 0);
515 V = Builder.CreateBitCast(V, Ty);
516 V = Builder.CreateLoad(V, false);
517 V = Builder.CreateStructGEP(V, 1, "forwarding");
518 V = Builder.CreateLoad(V, false);
519 V = Builder.CreateBitCast(V, PtrStructTy);
520 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
521 } else {
522 Ty = llvm::PointerType::get(Ty, 0);
523 V = Builder.CreateBitCast(V, Ty);
524 }
525 return V;
526}
527
Mike Stump67a64482009-02-14 22:16:35 +0000528llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000529BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000530 // Generate the block descriptor.
531 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000532 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
533 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000534
Anders Carlssond5cab542009-02-12 17:55:02 +0000535 llvm::Constant *DescriptorFields[2];
Mike Stumpa5448542009-02-13 15:32:32 +0000536
Anders Carlssond5cab542009-02-12 17:55:02 +0000537 // Reserved
538 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000539
Anders Carlssond5cab542009-02-12 17:55:02 +0000540 // Block literal size. For global blocks we just use the size of the generic
541 // block literal struct.
Mike Stumpa5448542009-02-13 15:32:32 +0000542 uint64_t BlockLiteralSize =
Mike Stump9b8a7972009-02-13 15:25:34 +0000543 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlssond5cab542009-02-12 17:55:02 +0000544 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpa5448542009-02-13 15:32:32 +0000545
546 llvm::Constant *DescriptorStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000547 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpa5448542009-02-13 15:32:32 +0000548
Anders Carlssond5cab542009-02-12 17:55:02 +0000549 llvm::GlobalVariable *Descriptor =
550 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000551 llvm::GlobalVariable::InternalLinkage,
552 DescriptorStruct, "__block_descriptor_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000553 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000554
Anders Carlssond5cab542009-02-12 17:55:02 +0000555 // Generate the constants for the block literal.
556 llvm::Constant *LiteralFields[5];
Mike Stumpa5448542009-02-13 15:32:32 +0000557
Mike Stump67a64482009-02-14 22:16:35 +0000558 CodeGenFunction::BlockInfo Info(0, n);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000559 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000560 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stump00470a12009-03-05 08:32:30 +0000561 bool subBlockHasCopyDispose;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000562 llvm::Function *Fn
Mike Stump90a90432009-03-04 18:47:42 +0000563 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
564 subBlockAlign,
Mike Stump00470a12009-03-05 08:32:30 +0000565 subBlockDeclRefDecls,
566 subBlockHasCopyDispose);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000567 assert(subBlockSize == BlockLiteralSize
568 && "no imports allowed for global block");
Mike Stump00470a12009-03-05 08:32:30 +0000569 assert(!subBlockHasCopyDispose && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000570
Anders Carlssond5cab542009-02-12 17:55:02 +0000571 // isa
Mike Stumpf99f1d02009-02-13 17:23:42 +0000572 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000573
Anders Carlssond5cab542009-02-12 17:55:02 +0000574 // Flags
Mike Stump00470a12009-03-05 08:32:30 +0000575 LiteralFields[1] =
Anders Carlsson8045ee02009-03-01 21:09:29 +0000576 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpa5448542009-02-13 15:32:32 +0000577
Anders Carlssond5cab542009-02-12 17:55:02 +0000578 // Reserved
Mike Stump7cbb3602009-02-13 16:01:35 +0000579 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000580
Anders Carlssond5cab542009-02-12 17:55:02 +0000581 // Function
582 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000583
Anders Carlssond5cab542009-02-12 17:55:02 +0000584 // Descriptor
585 LiteralFields[4] = Descriptor;
Mike Stumpa5448542009-02-13 15:32:32 +0000586
587 llvm::Constant *BlockLiteralStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000588 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpa5448542009-02-13 15:32:32 +0000589
590 llvm::GlobalVariable *BlockLiteral =
Anders Carlssond5cab542009-02-12 17:55:02 +0000591 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000592 llvm::GlobalVariable::InternalLinkage,
593 BlockLiteralStruct, "__block_literal_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000594 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000595
Anders Carlssond5cab542009-02-12 17:55:02 +0000596 return BlockLiteral;
597}
598
Mike Stump4e7a1f72009-02-21 20:00:35 +0000599llvm::Value *CodeGenFunction::LoadBlockStruct() {
600 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
601}
602
Mike Stump00470a12009-03-05 08:32:30 +0000603llvm::Function *
604CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
605 const BlockInfo& Info,
606 uint64_t &Size,
607 uint64_t &Align,
608 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
609 bool &subBlockHasCopyDispose) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000610 const FunctionProtoType *FTy =
Chris Lattner161d36d2009-02-28 19:01:03 +0000611 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpa5448542009-02-13 15:32:32 +0000612
Anders Carlssond5cab542009-02-12 17:55:02 +0000613 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000614
Chris Lattner161d36d2009-02-28 19:01:03 +0000615 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000616
617 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000618 ImplicitParamDecl *SelfDecl =
Anders Carlssond5cab542009-02-12 17:55:02 +0000619 ImplicitParamDecl::Create(getContext(), 0,
620 SourceLocation(), 0,
621 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000622
Anders Carlssond5cab542009-02-12 17:55:02 +0000623 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000624 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000625
626 for (BlockDecl::param_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000627 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000628 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000629
630 const CGFunctionInfo &FI =
Anders Carlssond5cab542009-02-12 17:55:02 +0000631 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
632
Mike Stump67a64482009-02-14 22:16:35 +0000633 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlssond5cab542009-02-12 17:55:02 +0000634 CodeGenTypes &Types = CGM.getTypes();
635 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000636
637 llvm::Function *Fn =
Anders Carlssond5cab542009-02-12 17:55:02 +0000638 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
639 Name,
640 &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000641
642 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000643 BExpr->getBody()->getLocEnd());
644 EmitStmt(BExpr->getBody());
645 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000646
Mike Stump8a2b4b12009-02-25 23:33:13 +0000647 // The runtime needs a minimum alignment of a void *.
648 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
649 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
650
Mike Stump4e7a1f72009-02-21 20:00:35 +0000651 Size = BlockOffset;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000652 Align = BlockAlign;
653 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump00470a12009-03-05 08:32:30 +0000654 subBlockHasCopyDispose |= BlockHasCopyDispose;
Anders Carlssond5cab542009-02-12 17:55:02 +0000655 return Fn;
656}
Mike Stumpa99038c2009-02-28 09:07:16 +0000657
Mike Stump08920992009-03-07 02:35:30 +0000658uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000659 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
660
661 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
662 uint64_t Align = getContext().getDeclAlignInBytes(D);
663
664 if (BDRE->isByRef()) {
665 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
666 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
667 }
668
669 assert ((Align > 0) && "alignment must be 1 byte or more");
670
671 uint64_t OldOffset = BlockOffset;
672
673 // Ensure proper alignment, even if it means we have to have a gap
674 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
675 BlockAlign = std::max(Align, BlockAlign);
Mike Stump00470a12009-03-05 08:32:30 +0000676
Mike Stumpa99038c2009-02-28 09:07:16 +0000677 uint64_t Pad = BlockOffset - OldOffset;
678 if (Pad) {
679 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
680 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
681 llvm::APInt(32, Pad),
682 ArrayType::Normal, 0);
683 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
684 0, QualType(PadTy), VarDecl::None,
685 SourceLocation());
686 Expr *E;
687 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
688 SourceLocation(), false, false);
689 BlockDeclRefDecls.push_back(E);
690 }
691 BlockDeclRefDecls.push_back(BDRE);
692
693 BlockOffset += Size;
694 return BlockOffset-Size;
695}
Mike Stumpdab514f2009-03-04 03:23:46 +0000696
Mike Stump08920992009-03-07 02:35:30 +0000697llvm::Constant *BlockFunction::
698GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
699 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000700 QualType R = getContext().VoidTy;
701
702 FunctionArgList Args;
703 // FIXME: This leaks
Mike Stump08920992009-03-07 02:35:30 +0000704 ImplicitParamDecl *Dst =
705 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
706 getContext().getPointerType(getContext().VoidTy));
707 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000708 ImplicitParamDecl *Src =
709 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
710 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000711 Args.push_back(std::make_pair(Src, Src->getType()));
712
713 const CGFunctionInfo &FI =
714 CGM.getTypes().getFunctionInfo(R, Args);
715
716 std::string Name = std::string("__copy_helper_block_");
717 CodeGenTypes &Types = CGM.getTypes();
718 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
719
720 llvm::Function *Fn =
721 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
722 Name,
723 &CGM.getModule());
724
725 IdentifierInfo *II
726 = &CGM.getContext().Idents.get("__copy_helper_block_");
727
728 FunctionDecl *FD = FunctionDecl::Create(getContext(),
729 getContext().getTranslationUnitDecl(),
730 SourceLocation(), II, R,
731 FunctionDecl::Static, false,
732 true);
733 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +0000734
735 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
736 llvm::Type *PtrPtrT;
737 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
738 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
739 SrcObj = Builder.CreateLoad(SrcObj);
740
741 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
742 DstObj = Builder.CreateBitCast(DstObj, llvm::PointerType::get(T, 0));
743
744 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
745 int flag = NoteForHelper[i].flag;
746 int index = NoteForHelper[i].index;
747
748 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
749 || NoteForHelper[i].RequiresCopying) {
750 llvm::Value *Srcv = SrcObj;
751 Srcv = Builder.CreateStructGEP(Srcv, index);
752 Srcv = Builder.CreateBitCast(Srcv,
753 llvm::PointerType::get(PtrToInt8Ty, 0));
754 Srcv = Builder.CreateLoad(Srcv);
755
756 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
757 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
758
759 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
760 llvm::Value *F = getBlockObjectAssign();
761 Builder.CreateCall3(F, Dstv, Srcv, N);
762 }
763 }
764
Mike Stumpa4f668f2009-03-06 01:33:24 +0000765 CGF.FinishFunction();
766
767 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000768}
769
Mike Stumpcf62d392009-03-06 18:42:23 +0000770llvm::Constant *BlockFunction::
Mike Stump08920992009-03-07 02:35:30 +0000771GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
772 const llvm::StructType* T,
773 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000774 QualType R = getContext().VoidTy;
775
776 FunctionArgList Args;
777 // FIXME: This leaks
778 ImplicitParamDecl *Src =
779 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
780 getContext().getPointerType(getContext().VoidTy));
781
782 Args.push_back(std::make_pair(Src, Src->getType()));
783
784 const CGFunctionInfo &FI =
785 CGM.getTypes().getFunctionInfo(R, Args);
786
787 std::string Name = std::string("__destroy_helper_block_");
788 CodeGenTypes &Types = CGM.getTypes();
789 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
790
791 llvm::Function *Fn =
792 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
793 Name,
794 &CGM.getModule());
795
796 IdentifierInfo *II
797 = &CGM.getContext().Idents.get("__destroy_helper_block_");
798
799 FunctionDecl *FD = FunctionDecl::Create(getContext(),
800 getContext().getTranslationUnitDecl(),
801 SourceLocation(), II, R,
802 FunctionDecl::Static, false,
803 true);
804 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +0000805
806 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
807 llvm::Type *PtrPtrT;
808 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
809 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
810 SrcObj = Builder.CreateLoad(SrcObj);
811
812 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
813 int flag = NoteForHelper[i].flag;
814 int index = NoteForHelper[i].index;
815
816 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
817 || NoteForHelper[i].RequiresCopying) {
818 llvm::Value *Srcv = SrcObj;
819 Srcv = Builder.CreateStructGEP(Srcv, index);
820 Srcv = Builder.CreateBitCast(Srcv,
821 llvm::PointerType::get(PtrToInt8Ty, 0));
822 Srcv = Builder.CreateLoad(Srcv);
823
824 BuildBlockRelease(Srcv, flag);
825 }
826 }
827
Mike Stumpa4f668f2009-03-06 01:33:24 +0000828 CGF.FinishFunction();
829
830 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
831}
832
Mike Stump08920992009-03-07 02:35:30 +0000833llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
834 std::vector<HelperInfo> &NoteForHelper) {
835 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
836 T, NoteForHelper);
Mike Stumpa4f668f2009-03-06 01:33:24 +0000837}
838
Mike Stump08920992009-03-07 02:35:30 +0000839llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
840 std::vector<HelperInfo> &NoteForHelper) {
841 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
842 T, NoteForHelper);
Mike Stumpdab514f2009-03-04 03:23:46 +0000843}
Mike Stump797b6322009-03-05 01:23:13 +0000844
Mike Stumpee094222009-03-06 06:12:24 +0000845llvm::Constant *BlockFunction::
846GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stump45031c02009-03-06 02:29:21 +0000847 QualType R = getContext().VoidTy;
848
849 FunctionArgList Args;
850 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +0000851 ImplicitParamDecl *Dst =
852 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
853 getContext().getPointerType(getContext().VoidTy));
854 Args.push_back(std::make_pair(Dst, Dst->getType()));
855
856 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +0000857 ImplicitParamDecl *Src =
858 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
859 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +0000860 Args.push_back(std::make_pair(Src, Src->getType()));
861
862 const CGFunctionInfo &FI =
863 CGM.getTypes().getFunctionInfo(R, Args);
864
865 std::string Name = std::string("__Block_byref_id_object_copy_");
866 CodeGenTypes &Types = CGM.getTypes();
867 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
868
869 llvm::Function *Fn =
870 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
871 Name,
872 &CGM.getModule());
873
874 IdentifierInfo *II
875 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
876
877 FunctionDecl *FD = FunctionDecl::Create(getContext(),
878 getContext().getTranslationUnitDecl(),
879 SourceLocation(), II, R,
880 FunctionDecl::Static, false,
881 true);
882 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +0000883
884 // dst->x
885 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
886 V = Builder.CreateBitCast(V, T);
887 V = Builder.CreateStructGEP(V, 6, "x");
888 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
889
890 // src->x
891 V = CGF.GetAddrOfLocalVar(Src);
892 V = Builder.CreateLoad(V);
893 V = Builder.CreateBitCast(V, T);
894 V = Builder.CreateStructGEP(V, 6, "x");
895 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
896 llvm::Value *SrcObj = Builder.CreateLoad(V);
897
898 flag |= BLOCK_BYREF_CALLER;
899
900 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
901 llvm::Value *F = getBlockObjectAssign();
902 Builder.CreateCall3(F, DstObj, SrcObj, N);
903
Mike Stump45031c02009-03-06 02:29:21 +0000904 CGF.FinishFunction();
905
906 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
907}
908
Mike Stump1851b682009-03-06 04:53:30 +0000909llvm::Constant *
910BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
911 int flag) {
Mike Stump45031c02009-03-06 02:29:21 +0000912 QualType R = getContext().VoidTy;
913
914 FunctionArgList Args;
915 // FIXME: This leaks
916 ImplicitParamDecl *Src =
917 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
918 getContext().getPointerType(getContext().VoidTy));
919
920 Args.push_back(std::make_pair(Src, Src->getType()));
921
922 const CGFunctionInfo &FI =
923 CGM.getTypes().getFunctionInfo(R, Args);
924
925 std::string Name = std::string("__Block_byref_id_object_dispose_");
926 CodeGenTypes &Types = CGM.getTypes();
927 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
928
929 llvm::Function *Fn =
930 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
931 Name,
932 &CGM.getModule());
933
934 IdentifierInfo *II
935 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
936
937 FunctionDecl *FD = FunctionDecl::Create(getContext(),
938 getContext().getTranslationUnitDecl(),
939 SourceLocation(), II, R,
940 FunctionDecl::Static, false,
941 true);
942 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +0000943
944 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
945 V = Builder.CreateBitCast(V, T);
946 V = Builder.CreateStructGEP(V, 6, "x");
947 V = Builder.CreateBitCast(V, PtrToInt8Ty);
948
949 // FIXME: Move to other one.
950 // int flag = BLOCK_FIELD_IS_BYREF;
951 // FIXME: Add weak support
952 if (0)
953 flag |= BLOCK_FIELD_IS_WEAK;
954 flag |= BLOCK_BYREF_CALLER;
955 BuildBlockRelease(V, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000956 CGF.FinishFunction();
957
958 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
959}
960
Mike Stumpee094222009-03-06 06:12:24 +0000961llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
962 int flag) {
963 return CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000964}
965
Mike Stump1851b682009-03-06 04:53:30 +0000966llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
967 int flag) {
968 return CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000969}
970
Mike Stump797b6322009-03-05 01:23:13 +0000971llvm::Value *BlockFunction::getBlockObjectDispose() {
972 if (CGM.BlockObjectDispose == 0) {
973 const llvm::FunctionType *FTy;
974 std::vector<const llvm::Type*> ArgTys;
975 const llvm::Type *ResultType = llvm::Type::VoidTy;
976 ArgTys.push_back(PtrToInt8Ty);
977 ArgTys.push_back(llvm::Type::Int32Ty);
978 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump00470a12009-03-05 08:32:30 +0000979 CGM.BlockObjectDispose
Mike Stump797b6322009-03-05 01:23:13 +0000980 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
981 }
982 return CGM.BlockObjectDispose;
983}
984
Mike Stumpee094222009-03-06 06:12:24 +0000985llvm::Value *BlockFunction::getBlockObjectAssign() {
986 if (CGM.BlockObjectAssign == 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(PtrToInt8Ty);
992 ArgTys.push_back(llvm::Type::Int32Ty);
993 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
994 CGM.BlockObjectAssign
995 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
996 }
997 return CGM.BlockObjectAssign;
998}
999
Mike Stump1851b682009-03-06 04:53:30 +00001000void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Mike Stump797b6322009-03-05 01:23:13 +00001001 llvm::Value *F = getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001002 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001003 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump1851b682009-03-06 04:53:30 +00001004 N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
Mike Stump797b6322009-03-05 01:23:13 +00001005 Builder.CreateCall2(F, V, N);
1006}
Mike Stump00470a12009-03-05 08:32:30 +00001007
1008ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001009
1010BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1011 CGBuilderTy &B)
1012 : CGM(cgm), CGF(cgf), Builder(B) {
1013 PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1014
1015 BlockHasCopyDispose = false;
1016}