blob: 5780fc2958f1ccc00ffac26b394de6f566e8a5bc [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"
28static llvm::cl::opt<bool>
29Enable__block("f__block",
30 // See all the FIXMEs for the various work that needs to be done
31 llvm::cl::desc("temporary option to turn on __block precessing "
32 "even though the code isn't done yet"),
33 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
Mike Stump1bdbf632009-03-05 08:32:30 +000034 llvm::cl::ZeroOrMore,
Mike Stumpb0fa8b52009-03-07 06:16:52 +000035 llvm::cl::init(true));
Mike Stumpb3a6fac2009-03-04 13:17:22 +000036
Mike Stump9d8c1262009-03-06 18:42:23 +000037llvm::Constant *CodeGenFunction::
Mike Stump1fa52fe2009-03-07 02:35:30 +000038BuildDescriptorBlockDecl(uint64_t Size, const llvm::StructType* Ty,
39 std::vector<HelperInfo> *NoteForHelper) {
Mike Stumpff8f0872009-02-13 16:55:51 +000040 const llvm::Type *UnsignedLongTy
41 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb95bc002009-02-13 16:19:19 +000042 llvm::Constant *C;
43 std::vector<llvm::Constant*> Elts;
44
45 // reserved
Mike Stumpff8f0872009-02-13 16:55:51 +000046 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpb95bc002009-02-13 16:19:19 +000047 Elts.push_back(C);
48
49 // Size
Mike Stump139c3962009-02-21 20:07:44 +000050 // FIXME: What is the right way to say this doesn't fit? We should give
51 // a user diagnostic in that case. Better fix would be to change the
52 // API to size_t.
Mike Stumpfca5da02009-02-21 20:00:35 +000053 C = llvm::ConstantInt::get(UnsignedLongTy, Size);
Mike Stumpb95bc002009-02-13 16:19:19 +000054 Elts.push_back(C);
55
56 if (BlockHasCopyDispose) {
57 // copy_func_helper_decl
Mike Stump1fa52fe2009-03-07 02:35:30 +000058 Elts.push_back(BuildCopyHelper(Ty, *NoteForHelper));
Mike Stumpb95bc002009-02-13 16:19:19 +000059
60 // destroy_func_decl
Mike Stump1fa52fe2009-03-07 02:35:30 +000061 Elts.push_back(BuildDestroyHelper(Ty, *NoteForHelper));
Mike Stumpb95bc002009-02-13 16:19:19 +000062 }
63
64 C = llvm::ConstantStruct::get(Elts);
65
Mike Stumpb95bc002009-02-13 16:19:19 +000066 C = new llvm::GlobalVariable(C->getType(), true,
67 llvm::GlobalValue::InternalLinkage,
Mike Stump92ea8882009-02-13 20:17:16 +000068 C, "__block_descriptor_tmp", &CGM.getModule());
Mike Stumpb95bc002009-02-13 16:19:19 +000069 return C;
70}
71
Mike Stump1f010b52009-03-04 18:17:45 +000072llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Mike Stump5f87e9d2009-02-13 17:23:42 +000073 if (NSConcreteGlobalBlock)
74 return NSConcreteGlobalBlock;
75
Mike Stump56447902009-02-13 19:38:12 +000076 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stumpf13eac12009-03-04 22:48:06 +000077 // same thing as CreateRuntimeFunction if there's already a variable with the
78 // same name.
Mike Stump5f87e9d2009-02-13 17:23:42 +000079 NSConcreteGlobalBlock
Mike Stump1bdbf632009-03-05 08:32:30 +000080 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stump5f87e9d2009-02-13 17:23:42 +000081 llvm::GlobalValue::ExternalLinkage,
82 0, "_NSConcreteGlobalBlock",
83 &getModule());
84
85 return NSConcreteGlobalBlock;
86}
87
Mike Stump1f010b52009-03-04 18:17:45 +000088llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Mike Stumpeb3a5ca2009-02-13 19:29:27 +000089 if (NSConcreteStackBlock)
90 return NSConcreteStackBlock;
91
Mike Stump56447902009-02-13 19:38:12 +000092 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stumpf13eac12009-03-04 22:48:06 +000093 // same thing as CreateRuntimeFunction if there's already a variable with the
94 // same name.
Mike Stumpeb3a5ca2009-02-13 19:29:27 +000095 NSConcreteStackBlock
Mike Stump1bdbf632009-03-05 08:32:30 +000096 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stumpeb3a5ca2009-02-13 19:29:27 +000097 llvm::GlobalValue::ExternalLinkage,
98 0, "_NSConcreteStackBlock",
99 &getModule());
100
101 return NSConcreteStackBlock;
102}
103
Mike Stump1bdbf632009-03-05 08:32:30 +0000104static void CollectBlockDeclRefInfo(const Stmt *S,
Anders Carlsson6cf64be2009-03-01 01:09:12 +0000105 CodeGenFunction::BlockInfo &Info) {
106 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
107 I != E; ++I)
Daniel Dunbar56941d32009-03-02 07:00:57 +0000108 if (*I)
109 CollectBlockDeclRefInfo(*I, Info);
Mike Stump1bdbf632009-03-05 08:32:30 +0000110
Anders Carlsson6cf64be2009-03-01 01:09:12 +0000111 if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
112 // FIXME: Handle enums.
113 if (isa<FunctionDecl>(DE->getDecl()))
114 return;
Mike Stump1bdbf632009-03-05 08:32:30 +0000115
Anders Carlsson6cf64be2009-03-01 01:09:12 +0000116 if (DE->isByRef())
117 Info.ByRefDeclRefs.push_back(DE);
118 else
119 Info.ByCopyDeclRefs.push_back(DE);
120 }
121}
122
Mike Stumpf13eac12009-03-04 22:48:06 +0000123/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
124/// declared as a global variable instead of on the stack.
Anders Carlsson6cf64be2009-03-01 01:09:12 +0000125static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
126{
127 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
128}
129
Mike Stumpf13eac12009-03-04 22:48:06 +0000130// FIXME: Push most into CGM, passing down a few bits, like current function
131// name.
Mike Stumpf1711822009-02-25 23:33:13 +0000132llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Mike Stumpb95bc002009-02-13 16:19:19 +0000133
Anders Carlsson6cf64be2009-03-01 01:09:12 +0000134 std::string Name = CurFn->getName();
135 CodeGenFunction::BlockInfo Info(0, Name.c_str());
136 CollectBlockDeclRefInfo(BE->getBody(), Info);
137
138 // Check if the block can be global.
Mike Stumpf13eac12009-03-04 22:48:06 +0000139 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
140 // to just have one code path. We should move this function into CGM and pass
141 // CGF, then we can just check to see if CGF is 0.
Mike Stumpad9605d2009-03-04 03:23:46 +0000142 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson6cf64be2009-03-01 01:09:12 +0000143 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump1bdbf632009-03-05 08:32:30 +0000144
145 std::vector<llvm::Constant*> Elts(5);
Mike Stumpb95bc002009-02-13 16:19:19 +0000146 llvm::Constant *C;
Mike Stumpf1711822009-02-25 23:33:13 +0000147 llvm::Value *V;
Mike Stumpb95bc002009-02-13 16:19:19 +0000148
Mike Stumpb95bc002009-02-13 16:19:19 +0000149 {
150 // C = BuildBlockStructInitlist();
151 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
152
Mike Stump1bdbf632009-03-05 08:32:30 +0000153 // We run this first so that we set BlockHasCopyDispose from the entire
154 // block literal.
155 // __invoke
156 uint64_t subBlockSize, subBlockAlign;
157 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
158 llvm::Function *Fn
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000159 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl, LocalDeclMap,
Mike Stumpa20c59e2009-03-13 23:34:28 +0000160 subBlockSize,
Mike Stump1bdbf632009-03-05 08:32:30 +0000161 subBlockAlign,
162 subBlockDeclRefDecls,
163 BlockHasCopyDispose);
164 Elts[3] = Fn;
165
166 if (!Enable__block && BlockHasCopyDispose)
167 ErrorUnsupported(BE, "block literal that requires copy/dispose");
168
Mike Stumpb95bc002009-02-13 16:19:19 +0000169 if (BlockHasCopyDispose)
170 flags |= BLOCK_HAS_COPY_DISPOSE;
171
Mike Stump92ea8882009-02-13 20:17:16 +0000172 // __isa
Mike Stumpeb3a5ca2009-02-13 19:29:27 +0000173 C = CGM.getNSConcreteStackBlock();
Mike Stumpb95bc002009-02-13 16:19:19 +0000174 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump1bdbf632009-03-05 08:32:30 +0000175 Elts[0] = C;
Mike Stumpb95bc002009-02-13 16:19:19 +0000176
177 // __flags
178 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
179 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
180 C = llvm::ConstantInt::get(IntTy, flags);
Mike Stump1bdbf632009-03-05 08:32:30 +0000181 Elts[1] = C;
Mike Stumpb95bc002009-02-13 16:19:19 +0000182
183 // __reserved
184 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump1bdbf632009-03-05 08:32:30 +0000185 Elts[2] = C;
Mike Stumpb95bc002009-02-13 16:19:19 +0000186
Mike Stumpf1711822009-02-25 23:33:13 +0000187 if (subBlockDeclRefDecls.size() == 0) {
Mike Stump9d8c1262009-03-06 18:42:23 +0000188 // __descriptor
Mike Stump1fa52fe2009-03-07 02:35:30 +0000189 Elts[4] = BuildDescriptorBlockDecl(subBlockSize, 0, 0);
Mike Stump9d8c1262009-03-06 18:42:23 +0000190
Mike Stumpa7db9be2009-03-01 20:07:53 +0000191 // Optimize to being a global block.
192 Elts[0] = CGM.getNSConcreteGlobalBlock();
193 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
194
Mike Stumpf1711822009-02-25 23:33:13 +0000195 C = llvm::ConstantStruct::get(Elts);
196
197 char Name[32];
198 sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
199 C = new llvm::GlobalVariable(C->getType(), true,
200 llvm::GlobalValue::InternalLinkage,
201 C, Name, &CGM.getModule());
202 QualType BPT = BE->getType();
203 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
204 return C;
205 }
Mike Stump1bdbf632009-03-05 08:32:30 +0000206
Mike Stumpf1711822009-02-25 23:33:13 +0000207 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
Mike Stump1fa52fe2009-03-07 02:35:30 +0000208 for (int i=0; i<4; ++i)
Mike Stumpf1711822009-02-25 23:33:13 +0000209 Types[i] = Elts[i]->getType();
Mike Stump1fa52fe2009-03-07 02:35:30 +0000210 Types[4] = PtrToInt8Ty;
Mike Stumpf1711822009-02-25 23:33:13 +0000211
Mike Stump2b6933f2009-02-28 09:07:16 +0000212 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
213 const Expr *E = subBlockDeclRefDecls[i];
214 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
215 QualType Ty = E->getType();
Mike Stumpad9605d2009-03-04 03:23:46 +0000216 if (BDRE && BDRE->isByRef()) {
217 uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
218 Types[i+5] = llvm::PointerType::get(BuildByRefType(Ty, Align), 0);
219 } else
220 Types[i+5] = ConvertType(Ty);
Mike Stump2b6933f2009-02-28 09:07:16 +0000221 }
Mike Stumpf1711822009-02-25 23:33:13 +0000222
Mike Stump1fa52fe2009-03-07 02:35:30 +0000223 llvm::StructType *Ty = llvm::StructType::get(Types, true);
Mike Stumpf1711822009-02-25 23:33:13 +0000224
225 llvm::AllocaInst *A = CreateTempAlloca(Ty);
226 A->setAlignment(subBlockAlign);
227 V = A;
228
Mike Stump1fa52fe2009-03-07 02:35:30 +0000229 std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
230 int helpersize = 0;
231
232 for (unsigned i=0; i<4; ++i)
Mike Stumpf1711822009-02-25 23:33:13 +0000233 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump1bdbf632009-03-05 08:32:30 +0000234
Mike Stumpf1711822009-02-25 23:33:13 +0000235 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
236 {
Mike Stump2b6933f2009-02-28 09:07:16 +0000237 // FIXME: Push const down.
238 Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
239 DeclRefExpr *DR;
240 ValueDecl *VD;
Mike Stumpf1711822009-02-25 23:33:13 +0000241
Mike Stump2b6933f2009-02-28 09:07:16 +0000242 DR = dyn_cast<DeclRefExpr>(E);
243 // Skip padding.
244 if (DR) continue;
245
246 BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
247 VD = BDRE->getDecl();
248
Mike Stumpad9605d2009-03-04 03:23:46 +0000249 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stump1fa52fe2009-03-07 02:35:30 +0000250 NoteForHelper[helpersize].index = i+5;
251 NoteForHelper[helpersize].RequiresCopying = BlockRequiresCopying(VD->getType());
252 NoteForHelper[helpersize].flag
253 = VD->getType()->isBlockPointerType() ? BLOCK_FIELD_IS_BLOCK : BLOCK_FIELD_IS_OBJECT;
254
Mike Stump2b6933f2009-02-28 09:07:16 +0000255 if (LocalDeclMap[VD]) {
Mike Stumpad9605d2009-03-04 03:23:46 +0000256 if (BDRE->isByRef()) {
Mike Stump1fa52fe2009-03-07 02:35:30 +0000257 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
Mike Stump0a33ed32009-03-07 06:04:31 +0000258 // FIXME: Someone double check this.
259 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
Mike Stumpad9605d2009-03-04 03:23:46 +0000260 const llvm::Type *Ty = Types[i+5];
261 llvm::Value *Loc = LocalDeclMap[VD];
262 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
263 Loc = Builder.CreateLoad(Loc, false);
264 Loc = Builder.CreateBitCast(Loc, Ty);
265 Builder.CreateStore(Loc, Addr);
Mike Stump1fa52fe2009-03-07 02:35:30 +0000266 ++helpersize;
Mike Stumpad9605d2009-03-04 03:23:46 +0000267 continue;
268 } else
269 E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
270 VD->getType(), SourceLocation(),
271 false, false);
Mike Stump2b6933f2009-02-28 09:07:16 +0000272 }
Mike Stumpad9605d2009-03-04 03:23:46 +0000273 if (BDRE->isByRef()) {
Mike Stump29782de2009-03-21 21:00:35 +0000274 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
275 // FIXME: Someone double check this.
276 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
Mike Stump2b6933f2009-02-28 09:07:16 +0000277 E = new (getContext())
278 UnaryOperator(E, UnaryOperator::AddrOf,
279 getContext().getPointerType(E->getType()),
280 SourceLocation());
Mike Stumpad9605d2009-03-04 03:23:46 +0000281 }
Mike Stump1fa52fe2009-03-07 02:35:30 +0000282 ++helpersize;
Mike Stump2b6933f2009-02-28 09:07:16 +0000283
Mike Stump2b6933f2009-02-28 09:07:16 +0000284 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpad9605d2009-03-04 03:23:46 +0000285 if (r.isScalar()) {
286 llvm::Value *Loc = r.getScalarVal();
287 const llvm::Type *Ty = Types[i+5];
288 if (BDRE->isByRef()) {
Mike Stumpf13eac12009-03-04 22:48:06 +0000289 // E is now the address of the value field, instead, we want the
290 // address of the actual ByRef struct. We optimize this slightly
291 // compared to gcc by not grabbing the forwarding slot as this must
292 // be done during Block_copy for us, and we can postpone the work
293 // until then.
294 uint64_t offset = BlockDecls[BDRE->getDecl()];
Mike Stump1bdbf632009-03-05 08:32:30 +0000295
Mike Stumpf13eac12009-03-04 22:48:06 +0000296 llvm::Value *BlockLiteral = LoadBlockStruct();
Mike Stump1bdbf632009-03-05 08:32:30 +0000297
Mike Stumpf13eac12009-03-04 22:48:06 +0000298 Loc = Builder.CreateGEP(BlockLiteral,
299 llvm::ConstantInt::get(llvm::Type::Int64Ty,
300 offset),
301 "block.literal");
302 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpad9605d2009-03-04 03:23:46 +0000303 Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpf13eac12009-03-04 22:48:06 +0000304 Loc = Builder.CreateLoad(Loc, false);
305 // Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpad9605d2009-03-04 03:23:46 +0000306 }
307 Builder.CreateStore(Loc, Addr);
308 } else if (r.isComplex())
Mike Stumpf1711822009-02-25 23:33:13 +0000309 // FIXME: implement
310 ErrorUnsupported(BE, "complex in block literal");
311 else if (r.isAggregate())
312 ; // Already created into the destination
313 else
314 assert (0 && "bad block variable");
315 // FIXME: Ensure that the offset created by the backend for
316 // the struct matches the previously computed offset in BlockDecls.
317 }
Mike Stump1fa52fe2009-03-07 02:35:30 +0000318 NoteForHelper.resize(helpersize);
Mike Stump9d8c1262009-03-06 18:42:23 +0000319
320 // __descriptor
Mike Stump1fa52fe2009-03-07 02:35:30 +0000321 llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockSize, Ty,
322 &NoteForHelper);
323 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
324 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
Mike Stumpb95bc002009-02-13 16:19:19 +0000325 }
Mike Stump1bdbf632009-03-05 08:32:30 +0000326
Mike Stumpd55240e2009-02-19 01:01:04 +0000327 QualType BPT = BE->getType();
Mike Stumpf1711822009-02-25 23:33:13 +0000328 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stumpb95bc002009-02-13 16:19:19 +0000329}
330
331
Mike Stump1f010b52009-03-04 18:17:45 +0000332const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stump95e54802009-02-13 15:16:56 +0000333 if (BlockDescriptorType)
334 return BlockDescriptorType;
335
Mike Stumpc4ae9632009-02-13 15:32:32 +0000336 const llvm::Type *UnsignedLongTy =
Mike Stump95e54802009-02-13 15:16:56 +0000337 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000338
Mike Stump95e54802009-02-13 15:16:56 +0000339 // struct __block_descriptor {
340 // unsigned long reserved;
341 // unsigned long block_size;
342 // };
Mike Stumpc4ae9632009-02-13 15:32:32 +0000343 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
344 UnsignedLongTy,
Mike Stump95e54802009-02-13 15:16:56 +0000345 NULL);
346
347 getModule().addTypeName("struct.__block_descriptor",
348 BlockDescriptorType);
349
350 return BlockDescriptorType;
Anders Carlssond2a889b2009-02-12 00:39:25 +0000351}
352
Mike Stump1f010b52009-03-04 18:17:45 +0000353const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump0dffa462009-02-13 15:25:34 +0000354 if (GenericBlockLiteralType)
355 return GenericBlockLiteralType;
356
Mike Stumpc4ae9632009-02-13 15:32:32 +0000357 const llvm::Type *BlockDescPtrTy =
Mike Stump0dffa462009-02-13 15:25:34 +0000358 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000359
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000360 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
361 getTypes().ConvertType(getContext().IntTy));
362
Mike Stump0dffa462009-02-13 15:25:34 +0000363 // struct __block_literal_generic {
Mike Stumpd55240e2009-02-19 01:01:04 +0000364 // void *__isa;
365 // int __flags;
366 // int __reserved;
367 // void (*__invoke)(void *);
368 // struct __block_descriptor *__descriptor;
Mike Stump0dffa462009-02-13 15:25:34 +0000369 // };
Mike Stump60294662009-03-05 01:23:13 +0000370 GenericBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000371 IntTy,
372 IntTy,
Mike Stump60294662009-03-05 01:23:13 +0000373 PtrToInt8Ty,
Mike Stump0dffa462009-02-13 15:25:34 +0000374 BlockDescPtrTy,
375 NULL);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000376
Mike Stump0dffa462009-02-13 15:25:34 +0000377 getModule().addTypeName("struct.__block_literal_generic",
378 GenericBlockLiteralType);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000379
Mike Stump0dffa462009-02-13 15:25:34 +0000380 return GenericBlockLiteralType;
Anders Carlssond2a889b2009-02-12 00:39:25 +0000381}
382
Mike Stump1f010b52009-03-04 18:17:45 +0000383const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
Mike Stumpd55240e2009-02-19 01:01:04 +0000384 if (GenericExtendedBlockLiteralType)
385 return GenericExtendedBlockLiteralType;
386
Mike Stumpd55240e2009-02-19 01:01:04 +0000387 const llvm::Type *BlockDescPtrTy =
388 llvm::PointerType::getUnqual(getBlockDescriptorType());
389
390 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
391 getTypes().ConvertType(getContext().IntTy));
392
393 // struct __block_literal_generic {
394 // void *__isa;
395 // int __flags;
396 // int __reserved;
397 // void (*__invoke)(void *);
398 // struct __block_descriptor *__descriptor;
399 // void *__copy_func_helper_decl;
400 // void *__destroy_func_decl;
401 // };
Mike Stump60294662009-03-05 01:23:13 +0000402 GenericExtendedBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stumpd55240e2009-02-19 01:01:04 +0000403 IntTy,
404 IntTy,
Mike Stump60294662009-03-05 01:23:13 +0000405 PtrToInt8Ty,
Mike Stumpd55240e2009-02-19 01:01:04 +0000406 BlockDescPtrTy,
Mike Stump60294662009-03-05 01:23:13 +0000407 PtrToInt8Ty,
408 PtrToInt8Ty,
Mike Stumpd55240e2009-02-19 01:01:04 +0000409 NULL);
410
411 getModule().addTypeName("struct.__block_literal_extended_generic",
412 GenericExtendedBlockLiteralType);
413
414 return GenericExtendedBlockLiteralType;
415}
416
Mike Stumpc4ae9632009-02-13 15:32:32 +0000417/// getBlockFunctionType - Given a BlockPointerType, will return the
Anders Carlssond2a889b2009-02-12 00:39:25 +0000418/// function type for the block, including the first block literal argument.
419static QualType getBlockFunctionType(ASTContext &Ctx,
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000420 const BlockPointerType *BPT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000421 const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000422
Anders Carlssond2a889b2009-02-12 00:39:25 +0000423 llvm::SmallVector<QualType, 8> Types;
424 Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000425
Douglas Gregor4fa58902009-02-26 23:50:07 +0000426 for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
Anders Carlssond2a889b2009-02-12 00:39:25 +0000427 e = FTy->arg_type_end(); i != e; ++i)
428 Types.push_back(*i);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000429
Anders Carlssond2a889b2009-02-12 00:39:25 +0000430 return Ctx.getFunctionType(FTy->getResultType(),
Mike Stumpc4ae9632009-02-13 15:32:32 +0000431 &Types[0], Types.size(),
Anders Carlssond2a889b2009-02-12 00:39:25 +0000432 FTy->isVariadic(), 0);
433}
434
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000435RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpc4ae9632009-02-13 15:32:32 +0000436 const BlockPointerType *BPT =
Anders Carlssond2a889b2009-02-12 00:39:25 +0000437 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpc4ae9632009-02-13 15:32:32 +0000438
Anders Carlssond2a889b2009-02-12 00:39:25 +0000439 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
440
441 // Get a pointer to the generic block literal.
442 const llvm::Type *BlockLiteralTy =
Mike Stump0dffa462009-02-13 15:25:34 +0000443 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssond2a889b2009-02-12 00:39:25 +0000444
445 // Bitcast the callee to a block literal.
Mike Stumpc4ae9632009-02-13 15:32:32 +0000446 llvm::Value *BlockLiteral =
Anders Carlssond2a889b2009-02-12 00:39:25 +0000447 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
448
449 // Get the function pointer from the literal.
450 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Mike Stump39bcc612009-02-22 13:27:11 +0000451 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
Anders Carlssond2a889b2009-02-12 00:39:25 +0000452
453 // Cast the function pointer to the right type.
Mike Stumpc4ae9632009-02-13 15:32:32 +0000454 const llvm::Type *BlockFTy =
Anders Carlssond2a889b2009-02-12 00:39:25 +0000455 ConvertType(getBlockFunctionType(getContext(), BPT));
456 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
457 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
458
Mike Stumpc4ae9632009-02-13 15:32:32 +0000459 BlockLiteral =
460 Builder.CreateBitCast(BlockLiteral,
Anders Carlssond2a889b2009-02-12 00:39:25 +0000461 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
462 "tmp");
Mike Stumpc4ae9632009-02-13 15:32:32 +0000463
Anders Carlssond2a889b2009-02-12 00:39:25 +0000464 // Add the block literal.
465 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
466 CallArgList Args;
467 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000468
Anders Carlssond2a889b2009-02-12 00:39:25 +0000469 // And the rest of the arguments.
Mike Stumpc4ae9632009-02-13 15:32:32 +0000470 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
Anders Carlssond2a889b2009-02-12 00:39:25 +0000471 i != e; ++i)
Mike Stumpc4ae9632009-02-13 15:32:32 +0000472 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
Anders Carlssond2a889b2009-02-12 00:39:25 +0000473 i->getType()));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000474
Anders Carlssond2a889b2009-02-12 00:39:25 +0000475 // And call the block.
Mike Stumpc4ae9632009-02-13 15:32:32 +0000476 return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
Anders Carlssond2a889b2009-02-12 00:39:25 +0000477 Func, Args);
478}
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000479
Mike Stumpad9605d2009-03-04 03:23:46 +0000480llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
481 uint64_t &offset = BlockDecls[E->getDecl()];
482
483 const llvm::Type *Ty;
484 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
485
Mike Stumpb3a6fac2009-03-04 13:17:22 +0000486 if (!Enable__block && E->isByRef())
Mike Stumpad9605d2009-03-04 03:23:46 +0000487 ErrorUnsupported(E, "__block variable in block literal");
Mike Stumpecd79422009-03-06 01:33:24 +0000488 else if (!Enable__block && E->getType()->isBlockPointerType())
Mike Stumpad9605d2009-03-04 03:23:46 +0000489 ErrorUnsupported(E, "block pointer in block literal");
Mike Stumpe43c54a2009-03-07 14:53:10 +0000490 else if (!Enable__block && (E->getDecl()->getAttr<ObjCNSObjectAttr>() ||
491 getContext().isObjCNSObjectType(E->getType())))
Mike Stumpad9605d2009-03-04 03:23:46 +0000492 ErrorUnsupported(E, "__attribute__((NSObject)) variable in block "
493 "literal");
Mike Stumpecd79422009-03-06 01:33:24 +0000494 else if (!Enable__block && getContext().isObjCObjectPointerType(E->getType()))
Mike Stumpad9605d2009-03-04 03:23:46 +0000495 ErrorUnsupported(E, "Objective-C variable in block literal");
496
497 // See if we have already allocated an offset for this variable.
498 if (offset == 0) {
Mike Stump1bdbf632009-03-05 08:32:30 +0000499 // Don't run the expensive check, unless we have to.
500 if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
501 BlockHasCopyDispose = true;
Mike Stumpad9605d2009-03-04 03:23:46 +0000502 // if not, allocate one now.
503 offset = getBlockOffset(E);
504 }
505
506 llvm::Value *BlockLiteral = LoadBlockStruct();
507 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
508 llvm::ConstantInt::get(llvm::Type::Int64Ty,
509 offset),
Mike Stumpf13eac12009-03-04 22:48:06 +0000510 "block.literal");
Mike Stumpad9605d2009-03-04 03:23:46 +0000511 if (E->isByRef()) {
512 bool needsCopyDispose = BlockRequiresCopying(E->getType());
513 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
514 const llvm::Type *PtrStructTy
515 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
Mike Stump29782de2009-03-21 21:00:35 +0000516 // The block literal will need a copy/destroy helper.
517 BlockHasCopyDispose = true;
Mike Stumpad9605d2009-03-04 03:23:46 +0000518 Ty = PtrStructTy;
519 Ty = llvm::PointerType::get(Ty, 0);
520 V = Builder.CreateBitCast(V, Ty);
521 V = Builder.CreateLoad(V, false);
522 V = Builder.CreateStructGEP(V, 1, "forwarding");
523 V = Builder.CreateLoad(V, false);
524 V = Builder.CreateBitCast(V, PtrStructTy);
525 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
526 } else {
527 Ty = llvm::PointerType::get(Ty, 0);
528 V = Builder.CreateBitCast(V, Ty);
529 }
530 return V;
531}
532
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000533void CodeGenFunction::BlockForwardSelf() {
534 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
535 ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
536 llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
537 if (DMEntry)
538 return;
539 // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
540 BlockDeclRefExpr *BDRE = new (getContext())
541 BlockDeclRefExpr(SelfDecl,
542 SelfDecl->getType(), SourceLocation(), false);
543 DMEntry = GetAddrOfBlockDecl(BDRE);
544}
545
Mike Stump084ba462009-02-14 22:16:35 +0000546llvm::Constant *
Mike Stumpd6d0ebe2009-03-04 18:47:42 +0000547BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000548 // Generate the block descriptor.
549 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000550 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
551 getTypes().ConvertType(getContext().IntTy));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000552
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000553 llvm::Constant *DescriptorFields[2];
Mike Stumpc4ae9632009-02-13 15:32:32 +0000554
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000555 // Reserved
556 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000557
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000558 // Block literal size. For global blocks we just use the size of the generic
559 // block literal struct.
Mike Stumpc4ae9632009-02-13 15:32:32 +0000560 uint64_t BlockLiteralSize =
Mike Stump0dffa462009-02-13 15:25:34 +0000561 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000562 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000563
564 llvm::Constant *DescriptorStruct =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000565 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000566
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000567 llvm::GlobalVariable *Descriptor =
568 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpc4ae9632009-02-13 15:32:32 +0000569 llvm::GlobalVariable::InternalLinkage,
570 DescriptorStruct, "__block_descriptor_global",
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000571 &getModule());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000572
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000573 // Generate the constants for the block literal.
574 llvm::Constant *LiteralFields[5];
Mike Stumpc4ae9632009-02-13 15:32:32 +0000575
Mike Stump084ba462009-02-14 22:16:35 +0000576 CodeGenFunction::BlockInfo Info(0, n);
Mike Stumpf1711822009-02-25 23:33:13 +0000577 uint64_t subBlockSize, subBlockAlign;
Mike Stump2b6933f2009-02-28 09:07:16 +0000578 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Daniel Dunbaradaf35f2009-03-12 03:07:24 +0000579 bool subBlockHasCopyDispose = false;
Mike Stumpa20c59e2009-03-13 23:34:28 +0000580 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stumpfca5da02009-02-21 20:00:35 +0000581 llvm::Function *Fn
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000582 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
Mike Stumpa20c59e2009-03-13 23:34:28 +0000583 subBlockSize,
Mike Stumpd6d0ebe2009-03-04 18:47:42 +0000584 subBlockAlign,
Mike Stump1bdbf632009-03-05 08:32:30 +0000585 subBlockDeclRefDecls,
586 subBlockHasCopyDispose);
Mike Stumpfca5da02009-02-21 20:00:35 +0000587 assert(subBlockSize == BlockLiteralSize
588 && "no imports allowed for global block");
Daniel Dunbaradaf35f2009-03-12 03:07:24 +0000589 assert(!subBlockHasCopyDispose && "no imports allowed for global block");
Mike Stumpc4ae9632009-02-13 15:32:32 +0000590
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000591 // isa
Mike Stump5f87e9d2009-02-13 17:23:42 +0000592 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpc4ae9632009-02-13 15:32:32 +0000593
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000594 // Flags
Mike Stump1bdbf632009-03-05 08:32:30 +0000595 LiteralFields[1] =
Anders Carlsson63810c62009-03-01 21:09:29 +0000596 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000597
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000598 // Reserved
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000599 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000600
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000601 // Function
602 LiteralFields[3] = Fn;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000603
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000604 // Descriptor
605 LiteralFields[4] = Descriptor;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000606
607 llvm::Constant *BlockLiteralStruct =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000608 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000609
610 llvm::GlobalVariable *BlockLiteral =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000611 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpc4ae9632009-02-13 15:32:32 +0000612 llvm::GlobalVariable::InternalLinkage,
613 BlockLiteralStruct, "__block_literal_global",
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000614 &getModule());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000615
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000616 return BlockLiteral;
617}
618
Mike Stumpfca5da02009-02-21 20:00:35 +0000619llvm::Value *CodeGenFunction::LoadBlockStruct() {
620 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
621}
622
Mike Stump1bdbf632009-03-05 08:32:30 +0000623llvm::Function *
624CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
625 const BlockInfo& Info,
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000626 const Decl *OuterFuncDecl,
Mike Stumpa20c59e2009-03-13 23:34:28 +0000627 llvm::DenseMap<const Decl*, llvm::Value*> ldm,
Mike Stump1bdbf632009-03-05 08:32:30 +0000628 uint64_t &Size,
629 uint64_t &Align,
630 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
631 bool &subBlockHasCopyDispose) {
Mike Stumpa20c59e2009-03-13 23:34:28 +0000632 // Arrange for local static and local extern declarations to appear
633 // to be local to this function as well, as they are directly referenced
634 // in a block.
635 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
636 i != ldm.end();
637 ++i) {
638 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
639
640 if (VD->getStorageClass() == VarDecl::Static
641 || VD->getStorageClass() == VarDecl::Extern)
642 LocalDeclMap[VD] = i->second;
643 }
644
Douglas Gregor4fa58902009-02-26 23:50:07 +0000645 const FunctionProtoType *FTy =
Chris Lattner8130e7f2009-02-28 19:01:03 +0000646 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000647
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000648 FunctionArgList Args;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000649
Chris Lattner8130e7f2009-02-28 19:01:03 +0000650 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000651
652 // FIXME: This leaks
Mike Stumpc4ae9632009-02-13 15:32:32 +0000653 ImplicitParamDecl *SelfDecl =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000654 ImplicitParamDecl::Create(getContext(), 0,
655 SourceLocation(), 0,
656 getContext().getPointerType(getContext().VoidTy));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000657
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000658 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stumpfca5da02009-02-21 20:00:35 +0000659 BlockStructDecl = SelfDecl;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000660
Steve Naroff494cb0f2009-03-13 16:56:44 +0000661 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000662 e = BD->param_end(); i != e; ++i)
Mike Stump459207f2009-02-17 23:25:52 +0000663 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000664
665 const CGFunctionInfo &FI =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000666 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
667
Mike Stump084ba462009-02-14 22:16:35 +0000668 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000669 CodeGenTypes &Types = CGM.getTypes();
670 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000671
672 llvm::Function *Fn =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000673 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
674 Name,
675 &CGM.getModule());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000676
677 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner8130e7f2009-02-28 19:01:03 +0000678 BExpr->getBody()->getLocEnd());
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000679 CurFuncDecl = OuterFuncDecl;
Chris Lattner8130e7f2009-02-28 19:01:03 +0000680 EmitStmt(BExpr->getBody());
681 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000682
Mike Stumpf1711822009-02-25 23:33:13 +0000683 // The runtime needs a minimum alignment of a void *.
684 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
685 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
686
Mike Stumpfca5da02009-02-21 20:00:35 +0000687 Size = BlockOffset;
Mike Stumpf1711822009-02-25 23:33:13 +0000688 Align = BlockAlign;
689 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump1bdbf632009-03-05 08:32:30 +0000690 subBlockHasCopyDispose |= BlockHasCopyDispose;
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000691 return Fn;
692}
Mike Stump2b6933f2009-02-28 09:07:16 +0000693
Mike Stump1fa52fe2009-03-07 02:35:30 +0000694uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
Mike Stump2b6933f2009-02-28 09:07:16 +0000695 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
696
697 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
698 uint64_t Align = getContext().getDeclAlignInBytes(D);
699
700 if (BDRE->isByRef()) {
701 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
702 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
703 }
704
705 assert ((Align > 0) && "alignment must be 1 byte or more");
706
707 uint64_t OldOffset = BlockOffset;
708
709 // Ensure proper alignment, even if it means we have to have a gap
710 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
711 BlockAlign = std::max(Align, BlockAlign);
Mike Stump1bdbf632009-03-05 08:32:30 +0000712
Mike Stump2b6933f2009-02-28 09:07:16 +0000713 uint64_t Pad = BlockOffset - OldOffset;
714 if (Pad) {
715 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
716 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
717 llvm::APInt(32, Pad),
718 ArrayType::Normal, 0);
719 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
720 0, QualType(PadTy), VarDecl::None,
721 SourceLocation());
722 Expr *E;
723 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
724 SourceLocation(), false, false);
725 BlockDeclRefDecls.push_back(E);
726 }
727 BlockDeclRefDecls.push_back(BDRE);
728
729 BlockOffset += Size;
730 return BlockOffset-Size;
731}
Mike Stumpad9605d2009-03-04 03:23:46 +0000732
Mike Stump1fa52fe2009-03-07 02:35:30 +0000733llvm::Constant *BlockFunction::
734GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
735 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpecd79422009-03-06 01:33:24 +0000736 QualType R = getContext().VoidTy;
737
738 FunctionArgList Args;
739 // FIXME: This leaks
Mike Stump1fa52fe2009-03-07 02:35:30 +0000740 ImplicitParamDecl *Dst =
741 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
742 getContext().getPointerType(getContext().VoidTy));
743 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpecd79422009-03-06 01:33:24 +0000744 ImplicitParamDecl *Src =
745 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
746 getContext().getPointerType(getContext().VoidTy));
Mike Stumpecd79422009-03-06 01:33:24 +0000747 Args.push_back(std::make_pair(Src, Src->getType()));
748
749 const CGFunctionInfo &FI =
750 CGM.getTypes().getFunctionInfo(R, Args);
751
752 std::string Name = std::string("__copy_helper_block_");
753 CodeGenTypes &Types = CGM.getTypes();
754 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
755
756 llvm::Function *Fn =
757 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
758 Name,
759 &CGM.getModule());
760
761 IdentifierInfo *II
762 = &CGM.getContext().Idents.get("__copy_helper_block_");
763
764 FunctionDecl *FD = FunctionDecl::Create(getContext(),
765 getContext().getTranslationUnitDecl(),
766 SourceLocation(), II, R,
767 FunctionDecl::Static, false,
768 true);
769 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1fa52fe2009-03-07 02:35:30 +0000770
771 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
772 llvm::Type *PtrPtrT;
773 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
774 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
775 SrcObj = Builder.CreateLoad(SrcObj);
776
777 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
778 DstObj = Builder.CreateBitCast(DstObj, llvm::PointerType::get(T, 0));
779
780 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
781 int flag = NoteForHelper[i].flag;
782 int index = NoteForHelper[i].index;
783
784 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
785 || NoteForHelper[i].RequiresCopying) {
786 llvm::Value *Srcv = SrcObj;
787 Srcv = Builder.CreateStructGEP(Srcv, index);
788 Srcv = Builder.CreateBitCast(Srcv,
789 llvm::PointerType::get(PtrToInt8Ty, 0));
790 Srcv = Builder.CreateLoad(Srcv);
791
792 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
793 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
794
795 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
796 llvm::Value *F = getBlockObjectAssign();
797 Builder.CreateCall3(F, Dstv, Srcv, N);
798 }
799 }
800
Mike Stumpecd79422009-03-06 01:33:24 +0000801 CGF.FinishFunction();
802
803 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpad9605d2009-03-04 03:23:46 +0000804}
805
Mike Stump9d8c1262009-03-06 18:42:23 +0000806llvm::Constant *BlockFunction::
Mike Stump1fa52fe2009-03-07 02:35:30 +0000807GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
808 const llvm::StructType* T,
809 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpecd79422009-03-06 01:33:24 +0000810 QualType R = getContext().VoidTy;
811
812 FunctionArgList Args;
813 // FIXME: This leaks
814 ImplicitParamDecl *Src =
815 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
816 getContext().getPointerType(getContext().VoidTy));
817
818 Args.push_back(std::make_pair(Src, Src->getType()));
819
820 const CGFunctionInfo &FI =
821 CGM.getTypes().getFunctionInfo(R, Args);
822
823 std::string Name = std::string("__destroy_helper_block_");
824 CodeGenTypes &Types = CGM.getTypes();
825 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
826
827 llvm::Function *Fn =
828 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
829 Name,
830 &CGM.getModule());
831
832 IdentifierInfo *II
833 = &CGM.getContext().Idents.get("__destroy_helper_block_");
834
835 FunctionDecl *FD = FunctionDecl::Create(getContext(),
836 getContext().getTranslationUnitDecl(),
837 SourceLocation(), II, R,
838 FunctionDecl::Static, false,
839 true);
840 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump05a6d4e2009-03-07 02:53:18 +0000841
842 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
843 llvm::Type *PtrPtrT;
844 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
845 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
846 SrcObj = Builder.CreateLoad(SrcObj);
847
848 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
849 int flag = NoteForHelper[i].flag;
850 int index = NoteForHelper[i].index;
851
852 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
853 || NoteForHelper[i].RequiresCopying) {
854 llvm::Value *Srcv = SrcObj;
855 Srcv = Builder.CreateStructGEP(Srcv, index);
856 Srcv = Builder.CreateBitCast(Srcv,
857 llvm::PointerType::get(PtrToInt8Ty, 0));
858 Srcv = Builder.CreateLoad(Srcv);
859
860 BuildBlockRelease(Srcv, flag);
861 }
862 }
863
Mike Stumpecd79422009-03-06 01:33:24 +0000864 CGF.FinishFunction();
865
866 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
867}
868
Mike Stump1fa52fe2009-03-07 02:35:30 +0000869llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
870 std::vector<HelperInfo> &NoteForHelper) {
871 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
872 T, NoteForHelper);
Mike Stumpecd79422009-03-06 01:33:24 +0000873}
874
Mike Stump1fa52fe2009-03-07 02:35:30 +0000875llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
876 std::vector<HelperInfo> &NoteForHelper) {
877 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
878 T, NoteForHelper);
Mike Stumpad9605d2009-03-04 03:23:46 +0000879}
Mike Stump60294662009-03-05 01:23:13 +0000880
Mike Stump11973b62009-03-06 06:12:24 +0000881llvm::Constant *BlockFunction::
882GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stumpf4b62342009-03-06 02:29:21 +0000883 QualType R = getContext().VoidTy;
884
885 FunctionArgList Args;
886 // FIXME: This leaks
Mike Stump11973b62009-03-06 06:12:24 +0000887 ImplicitParamDecl *Dst =
888 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
889 getContext().getPointerType(getContext().VoidTy));
890 Args.push_back(std::make_pair(Dst, Dst->getType()));
891
892 // FIXME: This leaks
Mike Stumpf4b62342009-03-06 02:29:21 +0000893 ImplicitParamDecl *Src =
894 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
895 getContext().getPointerType(getContext().VoidTy));
Mike Stumpf4b62342009-03-06 02:29:21 +0000896 Args.push_back(std::make_pair(Src, Src->getType()));
897
898 const CGFunctionInfo &FI =
899 CGM.getTypes().getFunctionInfo(R, Args);
900
901 std::string Name = std::string("__Block_byref_id_object_copy_");
902 CodeGenTypes &Types = CGM.getTypes();
903 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
904
905 llvm::Function *Fn =
906 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
907 Name,
908 &CGM.getModule());
909
910 IdentifierInfo *II
911 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
912
913 FunctionDecl *FD = FunctionDecl::Create(getContext(),
914 getContext().getTranslationUnitDecl(),
915 SourceLocation(), II, R,
916 FunctionDecl::Static, false,
917 true);
918 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump11973b62009-03-06 06:12:24 +0000919
920 // dst->x
921 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
922 V = Builder.CreateBitCast(V, T);
923 V = Builder.CreateStructGEP(V, 6, "x");
924 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
925
926 // src->x
927 V = CGF.GetAddrOfLocalVar(Src);
928 V = Builder.CreateLoad(V);
929 V = Builder.CreateBitCast(V, T);
930 V = Builder.CreateStructGEP(V, 6, "x");
931 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
932 llvm::Value *SrcObj = Builder.CreateLoad(V);
933
934 flag |= BLOCK_BYREF_CALLER;
935
936 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
937 llvm::Value *F = getBlockObjectAssign();
938 Builder.CreateCall3(F, DstObj, SrcObj, N);
939
Mike Stumpf4b62342009-03-06 02:29:21 +0000940 CGF.FinishFunction();
941
942 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
943}
944
Mike Stump4a0e5132009-03-06 04:53:30 +0000945llvm::Constant *
946BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
947 int flag) {
Mike Stumpf4b62342009-03-06 02:29:21 +0000948 QualType R = getContext().VoidTy;
949
950 FunctionArgList Args;
951 // FIXME: This leaks
952 ImplicitParamDecl *Src =
953 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
954 getContext().getPointerType(getContext().VoidTy));
955
956 Args.push_back(std::make_pair(Src, Src->getType()));
957
958 const CGFunctionInfo &FI =
959 CGM.getTypes().getFunctionInfo(R, Args);
960
961 std::string Name = std::string("__Block_byref_id_object_dispose_");
962 CodeGenTypes &Types = CGM.getTypes();
963 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
964
965 llvm::Function *Fn =
966 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
967 Name,
968 &CGM.getModule());
969
970 IdentifierInfo *II
971 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
972
973 FunctionDecl *FD = FunctionDecl::Create(getContext(),
974 getContext().getTranslationUnitDecl(),
975 SourceLocation(), II, R,
976 FunctionDecl::Static, false,
977 true);
978 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump4a0e5132009-03-06 04:53:30 +0000979
980 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
981 V = Builder.CreateBitCast(V, T);
982 V = Builder.CreateStructGEP(V, 6, "x");
983 V = Builder.CreateBitCast(V, PtrToInt8Ty);
984
Mike Stump4a0e5132009-03-06 04:53:30 +0000985 flag |= BLOCK_BYREF_CALLER;
986 BuildBlockRelease(V, flag);
Mike Stumpf4b62342009-03-06 02:29:21 +0000987 CGF.FinishFunction();
988
989 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
990}
991
Mike Stump11973b62009-03-06 06:12:24 +0000992llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
993 int flag) {
994 return CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
Mike Stumpf4b62342009-03-06 02:29:21 +0000995}
996
Mike Stump4a0e5132009-03-06 04:53:30 +0000997llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
998 int flag) {
999 return CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
Mike Stumpf4b62342009-03-06 02:29:21 +00001000}
1001
Mike Stump60294662009-03-05 01:23:13 +00001002llvm::Value *BlockFunction::getBlockObjectDispose() {
1003 if (CGM.BlockObjectDispose == 0) {
1004 const llvm::FunctionType *FTy;
1005 std::vector<const llvm::Type*> ArgTys;
1006 const llvm::Type *ResultType = llvm::Type::VoidTy;
1007 ArgTys.push_back(PtrToInt8Ty);
1008 ArgTys.push_back(llvm::Type::Int32Ty);
1009 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump1bdbf632009-03-05 08:32:30 +00001010 CGM.BlockObjectDispose
Mike Stump60294662009-03-05 01:23:13 +00001011 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1012 }
1013 return CGM.BlockObjectDispose;
1014}
1015
Mike Stump11973b62009-03-06 06:12:24 +00001016llvm::Value *BlockFunction::getBlockObjectAssign() {
1017 if (CGM.BlockObjectAssign == 0) {
1018 const llvm::FunctionType *FTy;
1019 std::vector<const llvm::Type*> ArgTys;
1020 const llvm::Type *ResultType = llvm::Type::VoidTy;
1021 ArgTys.push_back(PtrToInt8Ty);
1022 ArgTys.push_back(PtrToInt8Ty);
1023 ArgTys.push_back(llvm::Type::Int32Ty);
1024 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1025 CGM.BlockObjectAssign
1026 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1027 }
1028 return CGM.BlockObjectAssign;
1029}
1030
Mike Stump4a0e5132009-03-06 04:53:30 +00001031void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Mike Stump60294662009-03-05 01:23:13 +00001032 llvm::Value *F = getBlockObjectDispose();
Mike Stump4a0e5132009-03-06 04:53:30 +00001033 llvm::Value *N;
Mike Stump60294662009-03-05 01:23:13 +00001034 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump4a0e5132009-03-06 04:53:30 +00001035 N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
Mike Stump60294662009-03-05 01:23:13 +00001036 Builder.CreateCall2(F, V, N);
1037}
Mike Stump1bdbf632009-03-05 08:32:30 +00001038
1039ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump1fa52fe2009-03-07 02:35:30 +00001040
1041BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1042 CGBuilderTy &B)
1043 : CGM(cgm), CGF(cgf), Builder(B) {
1044 PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1045
1046 BlockHasCopyDispose = false;
1047}