blob: e01df8d07429f4c31620b7ec2d7e30bb3addb6cc [file] [log] [blame]
Anders Carlssond2a889b2009-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 Stumpfc5e6de2009-03-20 21:53:12 +000016#include "clang/AST/DeclObjC.h"
Anders Carlssond2a889b2009-02-12 00:39:25 +000017#include "llvm/Module.h"
Anders Carlsson1f1cd392009-02-12 17:55:02 +000018#include "llvm/Target/TargetData.h"
Anders Carlssond2a889b2009-02-12 00:39:25 +000019
20#include <algorithm>
21
22using namespace clang;
23using namespace CodeGen;
24
Mike Stumpb3a6fac2009-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 Stumpb3a6fac2009-03-04 13:17:22 +000028
Mike Stump9d8c1262009-03-06 18:42:23 +000029llvm::Constant *CodeGenFunction::
Mike Stump68bb7a22009-03-25 17:58:24 +000030BuildDescriptorBlockDecl(bool BlockHasCopyDispose, uint64_t Size,
31 const llvm::StructType* Ty,
Mike Stump1fa52fe2009-03-07 02:35:30 +000032 std::vector<HelperInfo> *NoteForHelper) {
Mike Stumpff8f0872009-02-13 16:55:51 +000033 const llvm::Type *UnsignedLongTy
34 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb95bc002009-02-13 16:19:19 +000035 llvm::Constant *C;
36 std::vector<llvm::Constant*> Elts;
37
38 // reserved
Mike Stumpff8f0872009-02-13 16:55:51 +000039 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpb95bc002009-02-13 16:19:19 +000040 Elts.push_back(C);
41
42 // Size
Mike Stump139c3962009-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 Stumpfca5da02009-02-21 20:00:35 +000046 C = llvm::ConstantInt::get(UnsignedLongTy, Size);
Mike Stumpb95bc002009-02-13 16:19:19 +000047 Elts.push_back(C);
48
49 if (BlockHasCopyDispose) {
50 // copy_func_helper_decl
Mike Stump1fa52fe2009-03-07 02:35:30 +000051 Elts.push_back(BuildCopyHelper(Ty, *NoteForHelper));
Mike Stumpb95bc002009-02-13 16:19:19 +000052
53 // destroy_func_decl
Mike Stump1fa52fe2009-03-07 02:35:30 +000054 Elts.push_back(BuildDestroyHelper(Ty, *NoteForHelper));
Mike Stumpb95bc002009-02-13 16:19:19 +000055 }
56
57 C = llvm::ConstantStruct::get(Elts);
58
Mike Stumpb95bc002009-02-13 16:19:19 +000059 C = new llvm::GlobalVariable(C->getType(), true,
60 llvm::GlobalValue::InternalLinkage,
Mike Stump92ea8882009-02-13 20:17:16 +000061 C, "__block_descriptor_tmp", &CGM.getModule());
Mike Stumpb95bc002009-02-13 16:19:19 +000062 return C;
63}
64
Mike Stump1f010b52009-03-04 18:17:45 +000065llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Mike Stump5f87e9d2009-02-13 17:23:42 +000066 if (NSConcreteGlobalBlock)
67 return NSConcreteGlobalBlock;
68
Mike Stump56447902009-02-13 19:38:12 +000069 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stumpf13eac12009-03-04 22:48:06 +000070 // same thing as CreateRuntimeFunction if there's already a variable with the
71 // same name.
Mike Stump5f87e9d2009-02-13 17:23:42 +000072 NSConcreteGlobalBlock
Mike Stump1bdbf632009-03-05 08:32:30 +000073 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stump5f87e9d2009-02-13 17:23:42 +000074 llvm::GlobalValue::ExternalLinkage,
75 0, "_NSConcreteGlobalBlock",
76 &getModule());
77
78 return NSConcreteGlobalBlock;
79}
80
Mike Stump1f010b52009-03-04 18:17:45 +000081llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Mike Stumpeb3a5ca2009-02-13 19:29:27 +000082 if (NSConcreteStackBlock)
83 return NSConcreteStackBlock;
84
Mike Stump56447902009-02-13 19:38:12 +000085 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stumpf13eac12009-03-04 22:48:06 +000086 // same thing as CreateRuntimeFunction if there's already a variable with the
87 // same name.
Mike Stumpeb3a5ca2009-02-13 19:29:27 +000088 NSConcreteStackBlock
Mike Stump1bdbf632009-03-05 08:32:30 +000089 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stumpeb3a5ca2009-02-13 19:29:27 +000090 llvm::GlobalValue::ExternalLinkage,
91 0, "_NSConcreteStackBlock",
92 &getModule());
93
94 return NSConcreteStackBlock;
95}
96
Mike Stump1bdbf632009-03-05 08:32:30 +000097static void CollectBlockDeclRefInfo(const Stmt *S,
Anders Carlsson6cf64be2009-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 Dunbar56941d32009-03-02 07:00:57 +0000101 if (*I)
102 CollectBlockDeclRefInfo(*I, Info);
Mike Stump1bdbf632009-03-05 08:32:30 +0000103
Anders Carlsson6cf64be2009-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 Stump1bdbf632009-03-05 08:32:30 +0000108
Anders Carlsson6cf64be2009-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 Stumpf13eac12009-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 Carlsson6cf64be2009-03-01 01:09:12 +0000118static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
119{
120 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
121}
122
Mike Stumpf13eac12009-03-04 22:48:06 +0000123// FIXME: Push most into CGM, passing down a few bits, like current function
124// name.
Mike Stumpf1711822009-02-25 23:33:13 +0000125llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Mike Stumpb95bc002009-02-13 16:19:19 +0000126
Anders Carlsson6cf64be2009-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 Stumpf13eac12009-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 Stumpad9605d2009-03-04 03:23:46 +0000135 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson6cf64be2009-03-01 01:09:12 +0000136 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump1bdbf632009-03-05 08:32:30 +0000137
138 std::vector<llvm::Constant*> Elts(5);
Mike Stumpb95bc002009-02-13 16:19:19 +0000139 llvm::Constant *C;
Mike Stumpf1711822009-02-25 23:33:13 +0000140 llvm::Value *V;
Mike Stumpb95bc002009-02-13 16:19:19 +0000141
Mike Stumpb95bc002009-02-13 16:19:19 +0000142 {
143 // C = BuildBlockStructInitlist();
144 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
145
Mike Stump1bdbf632009-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 Stump68bb7a22009-03-25 17:58:24 +0000151 bool subBlockHasCopyDispose = false;
Mike Stump1bdbf632009-03-05 08:32:30 +0000152 llvm::Function *Fn
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000153 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl, LocalDeclMap,
Mike Stumpa20c59e2009-03-13 23:34:28 +0000154 subBlockSize,
Mike Stump1bdbf632009-03-05 08:32:30 +0000155 subBlockAlign,
156 subBlockDeclRefDecls,
Mike Stump68bb7a22009-03-25 17:58:24 +0000157 subBlockHasCopyDispose);
158 BlockHasCopyDispose |= subBlockHasCopyDispose;
Mike Stump1bdbf632009-03-05 08:32:30 +0000159 Elts[3] = Fn;
160
Mike Stump68bb7a22009-03-25 17:58:24 +0000161 if (subBlockHasCopyDispose)
Mike Stumpb95bc002009-02-13 16:19:19 +0000162 flags |= BLOCK_HAS_COPY_DISPOSE;
163
Mike Stump92ea8882009-02-13 20:17:16 +0000164 // __isa
Mike Stumpeb3a5ca2009-02-13 19:29:27 +0000165 C = CGM.getNSConcreteStackBlock();
Mike Stumpb95bc002009-02-13 16:19:19 +0000166 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump1bdbf632009-03-05 08:32:30 +0000167 Elts[0] = C;
Mike Stumpb95bc002009-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 Stump1bdbf632009-03-05 08:32:30 +0000173 Elts[1] = C;
Mike Stumpb95bc002009-02-13 16:19:19 +0000174
175 // __reserved
176 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump1bdbf632009-03-05 08:32:30 +0000177 Elts[2] = C;
Mike Stumpb95bc002009-02-13 16:19:19 +0000178
Mike Stumpf1711822009-02-25 23:33:13 +0000179 if (subBlockDeclRefDecls.size() == 0) {
Mike Stump9d8c1262009-03-06 18:42:23 +0000180 // __descriptor
Mike Stump68bb7a22009-03-25 17:58:24 +0000181 assert(subBlockHasCopyDispose == false);
182 Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize, 0, 0);
Mike Stump9d8c1262009-03-06 18:42:23 +0000183
Mike Stumpa7db9be2009-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 Stumpf1711822009-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 Stump1bdbf632009-03-05 08:32:30 +0000199
Mike Stumpf1711822009-02-25 23:33:13 +0000200 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
Mike Stump1fa52fe2009-03-07 02:35:30 +0000201 for (int i=0; i<4; ++i)
Mike Stumpf1711822009-02-25 23:33:13 +0000202 Types[i] = Elts[i]->getType();
Mike Stump1fa52fe2009-03-07 02:35:30 +0000203 Types[4] = PtrToInt8Ty;
Mike Stumpf1711822009-02-25 23:33:13 +0000204
Mike Stump2b6933f2009-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 Stumpad9605d2009-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 Stump2b6933f2009-02-28 09:07:16 +0000214 }
Mike Stumpf1711822009-02-25 23:33:13 +0000215
Mike Stump1fa52fe2009-03-07 02:35:30 +0000216 llvm::StructType *Ty = llvm::StructType::get(Types, true);
Mike Stumpf1711822009-02-25 23:33:13 +0000217
218 llvm::AllocaInst *A = CreateTempAlloca(Ty);
219 A->setAlignment(subBlockAlign);
220 V = A;
221
Mike Stump1fa52fe2009-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 Stumpf1711822009-02-25 23:33:13 +0000226 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump1bdbf632009-03-05 08:32:30 +0000227
Mike Stumpf1711822009-02-25 23:33:13 +0000228 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
229 {
Mike Stump2b6933f2009-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 Stumpf1711822009-02-25 23:33:13 +0000234
Mike Stump2b6933f2009-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 Stumpad9605d2009-03-04 03:23:46 +0000242 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stump1fa52fe2009-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 Stump2b6933f2009-02-28 09:07:16 +0000248 if (LocalDeclMap[VD]) {
Mike Stumpad9605d2009-03-04 03:23:46 +0000249 if (BDRE->isByRef()) {
Mike Stump1fa52fe2009-03-07 02:35:30 +0000250 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
Mike Stump0a33ed32009-03-07 06:04:31 +0000251 // FIXME: Someone double check this.
252 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
Mike Stumpad9605d2009-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 Stump1fa52fe2009-03-07 02:35:30 +0000259 ++helpersize;
Mike Stumpad9605d2009-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 Stump2b6933f2009-02-28 09:07:16 +0000265 }
Mike Stumpad9605d2009-03-04 03:23:46 +0000266 if (BDRE->isByRef()) {
Mike Stump29782de2009-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 Stump2b6933f2009-02-28 09:07:16 +0000270 E = new (getContext())
271 UnaryOperator(E, UnaryOperator::AddrOf,
272 getContext().getPointerType(E->getType()),
273 SourceLocation());
Mike Stumpad9605d2009-03-04 03:23:46 +0000274 }
Mike Stump1fa52fe2009-03-07 02:35:30 +0000275 ++helpersize;
Mike Stump2b6933f2009-02-28 09:07:16 +0000276
Mike Stump2b6933f2009-02-28 09:07:16 +0000277 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpad9605d2009-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 Stumpf13eac12009-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 Stump1bdbf632009-03-05 08:32:30 +0000288
Mike Stumpf13eac12009-03-04 22:48:06 +0000289 llvm::Value *BlockLiteral = LoadBlockStruct();
Mike Stump1bdbf632009-03-05 08:32:30 +0000290
Mike Stumpf13eac12009-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 Stumpad9605d2009-03-04 03:23:46 +0000296 Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpf13eac12009-03-04 22:48:06 +0000297 Loc = Builder.CreateLoad(Loc, false);
298 // Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpad9605d2009-03-04 03:23:46 +0000299 }
300 Builder.CreateStore(Loc, Addr);
301 } else if (r.isComplex())
Mike Stumpf1711822009-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 Stump1fa52fe2009-03-07 02:35:30 +0000311 NoteForHelper.resize(helpersize);
Mike Stump9d8c1262009-03-06 18:42:23 +0000312
313 // __descriptor
Mike Stump68bb7a22009-03-25 17:58:24 +0000314 llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
315 subBlockSize, Ty,
Mike Stump1fa52fe2009-03-07 02:35:30 +0000316 &NoteForHelper);
317 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
318 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
Mike Stumpb95bc002009-02-13 16:19:19 +0000319 }
Mike Stump1bdbf632009-03-05 08:32:30 +0000320
Mike Stumpd55240e2009-02-19 01:01:04 +0000321 QualType BPT = BE->getType();
Mike Stumpf1711822009-02-25 23:33:13 +0000322 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stumpb95bc002009-02-13 16:19:19 +0000323}
324
325
Mike Stump1f010b52009-03-04 18:17:45 +0000326const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stump95e54802009-02-13 15:16:56 +0000327 if (BlockDescriptorType)
328 return BlockDescriptorType;
329
Mike Stumpc4ae9632009-02-13 15:32:32 +0000330 const llvm::Type *UnsignedLongTy =
Mike Stump95e54802009-02-13 15:16:56 +0000331 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000332
Mike Stump95e54802009-02-13 15:16:56 +0000333 // struct __block_descriptor {
334 // unsigned long reserved;
335 // unsigned long block_size;
336 // };
Mike Stumpc4ae9632009-02-13 15:32:32 +0000337 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
338 UnsignedLongTy,
Mike Stump95e54802009-02-13 15:16:56 +0000339 NULL);
340
341 getModule().addTypeName("struct.__block_descriptor",
342 BlockDescriptorType);
343
344 return BlockDescriptorType;
Anders Carlssond2a889b2009-02-12 00:39:25 +0000345}
346
Mike Stump1f010b52009-03-04 18:17:45 +0000347const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump0dffa462009-02-13 15:25:34 +0000348 if (GenericBlockLiteralType)
349 return GenericBlockLiteralType;
350
Mike Stumpc4ae9632009-02-13 15:32:32 +0000351 const llvm::Type *BlockDescPtrTy =
Mike Stump0dffa462009-02-13 15:25:34 +0000352 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000353
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000354 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
355 getTypes().ConvertType(getContext().IntTy));
356
Mike Stump0dffa462009-02-13 15:25:34 +0000357 // struct __block_literal_generic {
Mike Stumpd55240e2009-02-19 01:01:04 +0000358 // void *__isa;
359 // int __flags;
360 // int __reserved;
361 // void (*__invoke)(void *);
362 // struct __block_descriptor *__descriptor;
Mike Stump0dffa462009-02-13 15:25:34 +0000363 // };
Mike Stump60294662009-03-05 01:23:13 +0000364 GenericBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000365 IntTy,
366 IntTy,
Mike Stump60294662009-03-05 01:23:13 +0000367 PtrToInt8Ty,
Mike Stump0dffa462009-02-13 15:25:34 +0000368 BlockDescPtrTy,
369 NULL);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000370
Mike Stump0dffa462009-02-13 15:25:34 +0000371 getModule().addTypeName("struct.__block_literal_generic",
372 GenericBlockLiteralType);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000373
Mike Stump0dffa462009-02-13 15:25:34 +0000374 return GenericBlockLiteralType;
Anders Carlssond2a889b2009-02-12 00:39:25 +0000375}
376
Mike Stump1f010b52009-03-04 18:17:45 +0000377const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
Mike Stumpd55240e2009-02-19 01:01:04 +0000378 if (GenericExtendedBlockLiteralType)
379 return GenericExtendedBlockLiteralType;
380
Mike Stumpd55240e2009-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 Stump60294662009-03-05 01:23:13 +0000396 GenericExtendedBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stumpd55240e2009-02-19 01:01:04 +0000397 IntTy,
398 IntTy,
Mike Stump60294662009-03-05 01:23:13 +0000399 PtrToInt8Ty,
Mike Stumpd55240e2009-02-19 01:01:04 +0000400 BlockDescPtrTy,
Mike Stump60294662009-03-05 01:23:13 +0000401 PtrToInt8Ty,
402 PtrToInt8Ty,
Mike Stumpd55240e2009-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 Carlsson1f1cd392009-02-12 17:55:02 +0000411RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpc4ae9632009-02-13 15:32:32 +0000412 const BlockPointerType *BPT =
Anders Carlssond2a889b2009-02-12 00:39:25 +0000413 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpc4ae9632009-02-13 15:32:32 +0000414
Anders Carlsson3f03b812009-04-07 00:20:24 +0000415 const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(BPT);
416 bool IsVariadic =
417 BPT->getPointeeType()->getAsFunctionProtoType()->isVariadic();
418
Anders Carlssond2a889b2009-02-12 00:39:25 +0000419 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
420
421 // Get a pointer to the generic block literal.
422 const llvm::Type *BlockLiteralTy =
Mike Stump0dffa462009-02-13 15:25:34 +0000423 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssond2a889b2009-02-12 00:39:25 +0000424
425 // Bitcast the callee to a block literal.
Mike Stumpc4ae9632009-02-13 15:32:32 +0000426 llvm::Value *BlockLiteral =
Anders Carlssond2a889b2009-02-12 00:39:25 +0000427 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
428
429 // Get the function pointer from the literal.
430 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Mike Stump39bcc612009-02-22 13:27:11 +0000431 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
Anders Carlssond2a889b2009-02-12 00:39:25 +0000432
433 // Cast the function pointer to the right type.
Anders Carlsson3f03b812009-04-07 00:20:24 +0000434 const llvm::Type *BlockFTy =
435 CGM.getTypes().GetFunctionType(FnInfo, IsVariadic);
436
Anders Carlssond2a889b2009-02-12 00:39:25 +0000437 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
438 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
439
Mike Stumpc4ae9632009-02-13 15:32:32 +0000440 BlockLiteral =
441 Builder.CreateBitCast(BlockLiteral,
Anders Carlssond2a889b2009-02-12 00:39:25 +0000442 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
443 "tmp");
Mike Stumpc4ae9632009-02-13 15:32:32 +0000444
Anders Carlssond2a889b2009-02-12 00:39:25 +0000445 // Add the block literal.
446 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
447 CallArgList Args;
448 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000449
Anders Carlssond2a889b2009-02-12 00:39:25 +0000450 // And the rest of the arguments.
Mike Stumpc4ae9632009-02-13 15:32:32 +0000451 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
Anders Carlssond2a889b2009-02-12 00:39:25 +0000452 i != e; ++i)
Mike Stumpc4ae9632009-02-13 15:32:32 +0000453 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
Anders Carlssond2a889b2009-02-12 00:39:25 +0000454 i->getType()));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000455
Anders Carlssond2a889b2009-02-12 00:39:25 +0000456 // And call the block.
Anders Carlsson3f03b812009-04-07 00:20:24 +0000457 return EmitCall(FnInfo, Func, Args);
Anders Carlssond2a889b2009-02-12 00:39:25 +0000458}
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000459
Mike Stumpad9605d2009-03-04 03:23:46 +0000460llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
461 uint64_t &offset = BlockDecls[E->getDecl()];
462
463 const llvm::Type *Ty;
464 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
465
Mike Stumpad9605d2009-03-04 03:23:46 +0000466 // See if we have already allocated an offset for this variable.
467 if (offset == 0) {
Mike Stump1bdbf632009-03-05 08:32:30 +0000468 // Don't run the expensive check, unless we have to.
469 if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
470 BlockHasCopyDispose = true;
Mike Stumpad9605d2009-03-04 03:23:46 +0000471 // if not, allocate one now.
472 offset = getBlockOffset(E);
473 }
474
475 llvm::Value *BlockLiteral = LoadBlockStruct();
476 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
477 llvm::ConstantInt::get(llvm::Type::Int64Ty,
478 offset),
Mike Stumpf13eac12009-03-04 22:48:06 +0000479 "block.literal");
Mike Stumpad9605d2009-03-04 03:23:46 +0000480 if (E->isByRef()) {
481 bool needsCopyDispose = BlockRequiresCopying(E->getType());
482 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
483 const llvm::Type *PtrStructTy
484 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
Mike Stump29782de2009-03-21 21:00:35 +0000485 // The block literal will need a copy/destroy helper.
486 BlockHasCopyDispose = true;
Mike Stumpad9605d2009-03-04 03:23:46 +0000487 Ty = PtrStructTy;
488 Ty = llvm::PointerType::get(Ty, 0);
489 V = Builder.CreateBitCast(V, Ty);
490 V = Builder.CreateLoad(V, false);
491 V = Builder.CreateStructGEP(V, 1, "forwarding");
492 V = Builder.CreateLoad(V, false);
493 V = Builder.CreateBitCast(V, PtrStructTy);
494 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
495 } else {
496 Ty = llvm::PointerType::get(Ty, 0);
497 V = Builder.CreateBitCast(V, Ty);
498 }
499 return V;
500}
501
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000502void CodeGenFunction::BlockForwardSelf() {
503 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
504 ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
505 llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
506 if (DMEntry)
507 return;
508 // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
509 BlockDeclRefExpr *BDRE = new (getContext())
510 BlockDeclRefExpr(SelfDecl,
511 SelfDecl->getType(), SourceLocation(), false);
512 DMEntry = GetAddrOfBlockDecl(BDRE);
513}
514
Mike Stump084ba462009-02-14 22:16:35 +0000515llvm::Constant *
Mike Stumpd6d0ebe2009-03-04 18:47:42 +0000516BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000517 // Generate the block descriptor.
518 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000519 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
520 getTypes().ConvertType(getContext().IntTy));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000521
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000522 llvm::Constant *DescriptorFields[2];
Mike Stumpc4ae9632009-02-13 15:32:32 +0000523
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000524 // Reserved
525 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000526
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000527 // Block literal size. For global blocks we just use the size of the generic
528 // block literal struct.
Mike Stumpc4ae9632009-02-13 15:32:32 +0000529 uint64_t BlockLiteralSize =
Mike Stump0dffa462009-02-13 15:25:34 +0000530 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000531 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000532
533 llvm::Constant *DescriptorStruct =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000534 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000535
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000536 llvm::GlobalVariable *Descriptor =
537 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpc4ae9632009-02-13 15:32:32 +0000538 llvm::GlobalVariable::InternalLinkage,
539 DescriptorStruct, "__block_descriptor_global",
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000540 &getModule());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000541
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000542 // Generate the constants for the block literal.
543 llvm::Constant *LiteralFields[5];
Mike Stumpc4ae9632009-02-13 15:32:32 +0000544
Mike Stump084ba462009-02-14 22:16:35 +0000545 CodeGenFunction::BlockInfo Info(0, n);
Mike Stumpf1711822009-02-25 23:33:13 +0000546 uint64_t subBlockSize, subBlockAlign;
Mike Stump2b6933f2009-02-28 09:07:16 +0000547 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Daniel Dunbaradaf35f2009-03-12 03:07:24 +0000548 bool subBlockHasCopyDispose = false;
Mike Stumpa20c59e2009-03-13 23:34:28 +0000549 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stumpfca5da02009-02-21 20:00:35 +0000550 llvm::Function *Fn
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000551 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
Mike Stumpa20c59e2009-03-13 23:34:28 +0000552 subBlockSize,
Mike Stumpd6d0ebe2009-03-04 18:47:42 +0000553 subBlockAlign,
Mike Stump1bdbf632009-03-05 08:32:30 +0000554 subBlockDeclRefDecls,
555 subBlockHasCopyDispose);
Mike Stumpfca5da02009-02-21 20:00:35 +0000556 assert(subBlockSize == BlockLiteralSize
557 && "no imports allowed for global block");
Daniel Dunbaradaf35f2009-03-12 03:07:24 +0000558 assert(!subBlockHasCopyDispose && "no imports allowed for global block");
Mike Stumpc4ae9632009-02-13 15:32:32 +0000559
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000560 // isa
Mike Stump5f87e9d2009-02-13 17:23:42 +0000561 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpc4ae9632009-02-13 15:32:32 +0000562
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000563 // Flags
Mike Stump1bdbf632009-03-05 08:32:30 +0000564 LiteralFields[1] =
Anders Carlsson63810c62009-03-01 21:09:29 +0000565 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000566
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000567 // Reserved
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000568 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000569
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000570 // Function
571 LiteralFields[3] = Fn;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000572
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000573 // Descriptor
574 LiteralFields[4] = Descriptor;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000575
576 llvm::Constant *BlockLiteralStruct =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000577 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000578
579 llvm::GlobalVariable *BlockLiteral =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000580 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpc4ae9632009-02-13 15:32:32 +0000581 llvm::GlobalVariable::InternalLinkage,
582 BlockLiteralStruct, "__block_literal_global",
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000583 &getModule());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000584
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000585 return BlockLiteral;
586}
587
Mike Stumpfca5da02009-02-21 20:00:35 +0000588llvm::Value *CodeGenFunction::LoadBlockStruct() {
589 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
590}
591
Mike Stump1bdbf632009-03-05 08:32:30 +0000592llvm::Function *
593CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
594 const BlockInfo& Info,
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000595 const Decl *OuterFuncDecl,
Mike Stumpa20c59e2009-03-13 23:34:28 +0000596 llvm::DenseMap<const Decl*, llvm::Value*> ldm,
Mike Stump1bdbf632009-03-05 08:32:30 +0000597 uint64_t &Size,
598 uint64_t &Align,
599 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
600 bool &subBlockHasCopyDispose) {
Mike Stumpa20c59e2009-03-13 23:34:28 +0000601 // Arrange for local static and local extern declarations to appear
602 // to be local to this function as well, as they are directly referenced
603 // in a block.
604 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
605 i != ldm.end();
606 ++i) {
607 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
608
609 if (VD->getStorageClass() == VarDecl::Static
610 || VD->getStorageClass() == VarDecl::Extern)
611 LocalDeclMap[VD] = i->second;
612 }
613
Eli Friedman584abaf2009-03-28 03:24:54 +0000614 // FIXME: We need to rearrange the code for copy/dispose so we have this
615 // sooner, so we can calculate offsets correctly.
616 if (!BlockHasCopyDispose)
617 BlockOffset = CGM.getTargetData()
618 .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
619 else
620 BlockOffset = CGM.getTargetData()
621 .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
622 BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
623
Douglas Gregor4fa58902009-02-26 23:50:07 +0000624 const FunctionProtoType *FTy =
Chris Lattner8130e7f2009-02-28 19:01:03 +0000625 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000626
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000627 FunctionArgList Args;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000628
Chris Lattner8130e7f2009-02-28 19:01:03 +0000629 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000630
631 // FIXME: This leaks
Mike Stumpc4ae9632009-02-13 15:32:32 +0000632 ImplicitParamDecl *SelfDecl =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000633 ImplicitParamDecl::Create(getContext(), 0,
634 SourceLocation(), 0,
635 getContext().getPointerType(getContext().VoidTy));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000636
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000637 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stumpfca5da02009-02-21 20:00:35 +0000638 BlockStructDecl = SelfDecl;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000639
Steve Naroff494cb0f2009-03-13 16:56:44 +0000640 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000641 e = BD->param_end(); i != e; ++i)
Mike Stump459207f2009-02-17 23:25:52 +0000642 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000643
644 const CGFunctionInfo &FI =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000645 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
646
Mike Stump084ba462009-02-14 22:16:35 +0000647 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000648 CodeGenTypes &Types = CGM.getTypes();
649 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000650
651 llvm::Function *Fn =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000652 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
653 Name,
654 &CGM.getModule());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000655
656 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner8130e7f2009-02-28 19:01:03 +0000657 BExpr->getBody()->getLocEnd());
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000658 CurFuncDecl = OuterFuncDecl;
Chris Lattner8130e7f2009-02-28 19:01:03 +0000659 EmitStmt(BExpr->getBody());
660 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000661
Mike Stumpf1711822009-02-25 23:33:13 +0000662 // The runtime needs a minimum alignment of a void *.
663 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
664 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
665
Mike Stumpfca5da02009-02-21 20:00:35 +0000666 Size = BlockOffset;
Mike Stumpf1711822009-02-25 23:33:13 +0000667 Align = BlockAlign;
668 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump1bdbf632009-03-05 08:32:30 +0000669 subBlockHasCopyDispose |= BlockHasCopyDispose;
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000670 return Fn;
671}
Mike Stump2b6933f2009-02-28 09:07:16 +0000672
Mike Stump1fa52fe2009-03-07 02:35:30 +0000673uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
Mike Stump2b6933f2009-02-28 09:07:16 +0000674 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
675
676 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
677 uint64_t Align = getContext().getDeclAlignInBytes(D);
678
679 if (BDRE->isByRef()) {
680 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
681 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
682 }
683
684 assert ((Align > 0) && "alignment must be 1 byte or more");
685
686 uint64_t OldOffset = BlockOffset;
687
688 // Ensure proper alignment, even if it means we have to have a gap
689 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
690 BlockAlign = std::max(Align, BlockAlign);
Mike Stump1bdbf632009-03-05 08:32:30 +0000691
Mike Stump2b6933f2009-02-28 09:07:16 +0000692 uint64_t Pad = BlockOffset - OldOffset;
693 if (Pad) {
694 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
695 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
696 llvm::APInt(32, Pad),
697 ArrayType::Normal, 0);
698 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
699 0, QualType(PadTy), VarDecl::None,
700 SourceLocation());
701 Expr *E;
702 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
703 SourceLocation(), false, false);
704 BlockDeclRefDecls.push_back(E);
705 }
706 BlockDeclRefDecls.push_back(BDRE);
707
708 BlockOffset += Size;
709 return BlockOffset-Size;
710}
Mike Stumpad9605d2009-03-04 03:23:46 +0000711
Mike Stump1fa52fe2009-03-07 02:35:30 +0000712llvm::Constant *BlockFunction::
713GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
714 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpecd79422009-03-06 01:33:24 +0000715 QualType R = getContext().VoidTy;
716
717 FunctionArgList Args;
718 // FIXME: This leaks
Mike Stump1fa52fe2009-03-07 02:35:30 +0000719 ImplicitParamDecl *Dst =
720 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
721 getContext().getPointerType(getContext().VoidTy));
722 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpecd79422009-03-06 01:33:24 +0000723 ImplicitParamDecl *Src =
724 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
725 getContext().getPointerType(getContext().VoidTy));
Mike Stumpecd79422009-03-06 01:33:24 +0000726 Args.push_back(std::make_pair(Src, Src->getType()));
727
728 const CGFunctionInfo &FI =
729 CGM.getTypes().getFunctionInfo(R, Args);
730
731 std::string Name = std::string("__copy_helper_block_");
732 CodeGenTypes &Types = CGM.getTypes();
733 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
734
735 llvm::Function *Fn =
736 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
737 Name,
738 &CGM.getModule());
739
740 IdentifierInfo *II
741 = &CGM.getContext().Idents.get("__copy_helper_block_");
742
743 FunctionDecl *FD = FunctionDecl::Create(getContext(),
744 getContext().getTranslationUnitDecl(),
745 SourceLocation(), II, R,
746 FunctionDecl::Static, false,
747 true);
748 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1fa52fe2009-03-07 02:35:30 +0000749
750 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
751 llvm::Type *PtrPtrT;
752 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
753 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
754 SrcObj = Builder.CreateLoad(SrcObj);
755
756 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
757 DstObj = Builder.CreateBitCast(DstObj, llvm::PointerType::get(T, 0));
758
759 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
760 int flag = NoteForHelper[i].flag;
761 int index = NoteForHelper[i].index;
762
763 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
764 || NoteForHelper[i].RequiresCopying) {
765 llvm::Value *Srcv = SrcObj;
766 Srcv = Builder.CreateStructGEP(Srcv, index);
767 Srcv = Builder.CreateBitCast(Srcv,
768 llvm::PointerType::get(PtrToInt8Ty, 0));
769 Srcv = Builder.CreateLoad(Srcv);
770
771 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
772 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
773
774 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
775 llvm::Value *F = getBlockObjectAssign();
776 Builder.CreateCall3(F, Dstv, Srcv, N);
777 }
778 }
779
Mike Stumpecd79422009-03-06 01:33:24 +0000780 CGF.FinishFunction();
781
782 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpad9605d2009-03-04 03:23:46 +0000783}
784
Mike Stump9d8c1262009-03-06 18:42:23 +0000785llvm::Constant *BlockFunction::
Mike Stump1fa52fe2009-03-07 02:35:30 +0000786GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
787 const llvm::StructType* T,
788 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpecd79422009-03-06 01:33:24 +0000789 QualType R = getContext().VoidTy;
790
791 FunctionArgList Args;
792 // FIXME: This leaks
793 ImplicitParamDecl *Src =
794 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
795 getContext().getPointerType(getContext().VoidTy));
796
797 Args.push_back(std::make_pair(Src, Src->getType()));
798
799 const CGFunctionInfo &FI =
800 CGM.getTypes().getFunctionInfo(R, Args);
801
802 std::string Name = std::string("__destroy_helper_block_");
803 CodeGenTypes &Types = CGM.getTypes();
804 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
805
806 llvm::Function *Fn =
807 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
808 Name,
809 &CGM.getModule());
810
811 IdentifierInfo *II
812 = &CGM.getContext().Idents.get("__destroy_helper_block_");
813
814 FunctionDecl *FD = FunctionDecl::Create(getContext(),
815 getContext().getTranslationUnitDecl(),
816 SourceLocation(), II, R,
817 FunctionDecl::Static, false,
818 true);
819 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump05a6d4e2009-03-07 02:53:18 +0000820
821 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
822 llvm::Type *PtrPtrT;
823 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
824 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
825 SrcObj = Builder.CreateLoad(SrcObj);
826
827 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
828 int flag = NoteForHelper[i].flag;
829 int index = NoteForHelper[i].index;
830
831 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
832 || NoteForHelper[i].RequiresCopying) {
833 llvm::Value *Srcv = SrcObj;
834 Srcv = Builder.CreateStructGEP(Srcv, index);
835 Srcv = Builder.CreateBitCast(Srcv,
836 llvm::PointerType::get(PtrToInt8Ty, 0));
837 Srcv = Builder.CreateLoad(Srcv);
838
839 BuildBlockRelease(Srcv, flag);
840 }
841 }
842
Mike Stumpecd79422009-03-06 01:33:24 +0000843 CGF.FinishFunction();
844
845 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
846}
847
Mike Stump1fa52fe2009-03-07 02:35:30 +0000848llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
849 std::vector<HelperInfo> &NoteForHelper) {
850 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
851 T, NoteForHelper);
Mike Stumpecd79422009-03-06 01:33:24 +0000852}
853
Mike Stump1fa52fe2009-03-07 02:35:30 +0000854llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
855 std::vector<HelperInfo> &NoteForHelper) {
856 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
857 T, NoteForHelper);
Mike Stumpad9605d2009-03-04 03:23:46 +0000858}
Mike Stump60294662009-03-05 01:23:13 +0000859
Mike Stump11973b62009-03-06 06:12:24 +0000860llvm::Constant *BlockFunction::
861GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stumpf4b62342009-03-06 02:29:21 +0000862 QualType R = getContext().VoidTy;
863
864 FunctionArgList Args;
865 // FIXME: This leaks
Mike Stump11973b62009-03-06 06:12:24 +0000866 ImplicitParamDecl *Dst =
867 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
868 getContext().getPointerType(getContext().VoidTy));
869 Args.push_back(std::make_pair(Dst, Dst->getType()));
870
871 // FIXME: This leaks
Mike Stumpf4b62342009-03-06 02:29:21 +0000872 ImplicitParamDecl *Src =
873 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
874 getContext().getPointerType(getContext().VoidTy));
Mike Stumpf4b62342009-03-06 02:29:21 +0000875 Args.push_back(std::make_pair(Src, Src->getType()));
876
877 const CGFunctionInfo &FI =
878 CGM.getTypes().getFunctionInfo(R, Args);
879
880 std::string Name = std::string("__Block_byref_id_object_copy_");
881 CodeGenTypes &Types = CGM.getTypes();
882 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
883
884 llvm::Function *Fn =
885 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
886 Name,
887 &CGM.getModule());
888
889 IdentifierInfo *II
890 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
891
892 FunctionDecl *FD = FunctionDecl::Create(getContext(),
893 getContext().getTranslationUnitDecl(),
894 SourceLocation(), II, R,
895 FunctionDecl::Static, false,
896 true);
897 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump11973b62009-03-06 06:12:24 +0000898
899 // dst->x
900 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
901 V = Builder.CreateBitCast(V, T);
902 V = Builder.CreateStructGEP(V, 6, "x");
903 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
904
905 // src->x
906 V = CGF.GetAddrOfLocalVar(Src);
907 V = Builder.CreateLoad(V);
908 V = Builder.CreateBitCast(V, T);
909 V = Builder.CreateStructGEP(V, 6, "x");
910 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
911 llvm::Value *SrcObj = Builder.CreateLoad(V);
912
913 flag |= BLOCK_BYREF_CALLER;
914
915 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
916 llvm::Value *F = getBlockObjectAssign();
917 Builder.CreateCall3(F, DstObj, SrcObj, N);
918
Mike Stumpf4b62342009-03-06 02:29:21 +0000919 CGF.FinishFunction();
920
921 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
922}
923
Mike Stump4a0e5132009-03-06 04:53:30 +0000924llvm::Constant *
925BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
926 int flag) {
Mike Stumpf4b62342009-03-06 02:29:21 +0000927 QualType R = getContext().VoidTy;
928
929 FunctionArgList Args;
930 // FIXME: This leaks
931 ImplicitParamDecl *Src =
932 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
933 getContext().getPointerType(getContext().VoidTy));
934
935 Args.push_back(std::make_pair(Src, Src->getType()));
936
937 const CGFunctionInfo &FI =
938 CGM.getTypes().getFunctionInfo(R, Args);
939
940 std::string Name = std::string("__Block_byref_id_object_dispose_");
941 CodeGenTypes &Types = CGM.getTypes();
942 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
943
944 llvm::Function *Fn =
945 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
946 Name,
947 &CGM.getModule());
948
949 IdentifierInfo *II
950 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
951
952 FunctionDecl *FD = FunctionDecl::Create(getContext(),
953 getContext().getTranslationUnitDecl(),
954 SourceLocation(), II, R,
955 FunctionDecl::Static, false,
956 true);
957 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump4a0e5132009-03-06 04:53:30 +0000958
959 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
960 V = Builder.CreateBitCast(V, T);
961 V = Builder.CreateStructGEP(V, 6, "x");
962 V = Builder.CreateBitCast(V, PtrToInt8Ty);
963
Mike Stump4a0e5132009-03-06 04:53:30 +0000964 flag |= BLOCK_BYREF_CALLER;
965 BuildBlockRelease(V, flag);
Mike Stumpf4b62342009-03-06 02:29:21 +0000966 CGF.FinishFunction();
967
968 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
969}
970
Mike Stump11973b62009-03-06 06:12:24 +0000971llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
972 int flag) {
973 return CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
Mike Stumpf4b62342009-03-06 02:29:21 +0000974}
975
Mike Stump4a0e5132009-03-06 04:53:30 +0000976llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
977 int flag) {
978 return CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
Mike Stumpf4b62342009-03-06 02:29:21 +0000979}
980
Mike Stump60294662009-03-05 01:23:13 +0000981llvm::Value *BlockFunction::getBlockObjectDispose() {
982 if (CGM.BlockObjectDispose == 0) {
983 const llvm::FunctionType *FTy;
984 std::vector<const llvm::Type*> ArgTys;
985 const llvm::Type *ResultType = llvm::Type::VoidTy;
986 ArgTys.push_back(PtrToInt8Ty);
987 ArgTys.push_back(llvm::Type::Int32Ty);
988 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump1bdbf632009-03-05 08:32:30 +0000989 CGM.BlockObjectDispose
Mike Stump60294662009-03-05 01:23:13 +0000990 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
991 }
992 return CGM.BlockObjectDispose;
993}
994
Mike Stump11973b62009-03-06 06:12:24 +0000995llvm::Value *BlockFunction::getBlockObjectAssign() {
996 if (CGM.BlockObjectAssign == 0) {
997 const llvm::FunctionType *FTy;
998 std::vector<const llvm::Type*> ArgTys;
999 const llvm::Type *ResultType = llvm::Type::VoidTy;
1000 ArgTys.push_back(PtrToInt8Ty);
1001 ArgTys.push_back(PtrToInt8Ty);
1002 ArgTys.push_back(llvm::Type::Int32Ty);
1003 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1004 CGM.BlockObjectAssign
1005 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1006 }
1007 return CGM.BlockObjectAssign;
1008}
1009
Mike Stump4a0e5132009-03-06 04:53:30 +00001010void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Mike Stump60294662009-03-05 01:23:13 +00001011 llvm::Value *F = getBlockObjectDispose();
Mike Stump4a0e5132009-03-06 04:53:30 +00001012 llvm::Value *N;
Mike Stump60294662009-03-05 01:23:13 +00001013 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump4a0e5132009-03-06 04:53:30 +00001014 N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
Mike Stump60294662009-03-05 01:23:13 +00001015 Builder.CreateCall2(F, V, N);
1016}
Mike Stump1bdbf632009-03-05 08:32:30 +00001017
1018ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump1fa52fe2009-03-07 02:35:30 +00001019
1020BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1021 CGBuilderTy &B)
1022 : CGM(cgm), CGF(cgf), Builder(B) {
1023 PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1024
1025 BlockHasCopyDispose = false;
1026}