blob: 00bda4689c4c8dc46d94c344dbce175a3b47fc8f [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "llvm/Module.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000017#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000018
19#include <algorithm>
20
21using namespace clang;
22using namespace CodeGen;
23
Mike Stump58919e12009-03-04 13:17:22 +000024// Temporary code to enable testing of __block variables
25// #include "clang/Frontend/CompileOptions.h"
26#include "llvm/Support/CommandLine.h"
27static llvm::cl::opt<bool>
28Enable__block("f__block",
29 // See all the FIXMEs for the various work that needs to be done
30 llvm::cl::desc("temporary option to turn on __block precessing "
31 "even though the code isn't done yet"),
32 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
33 llvm::cl::ZeroOrMore);
34
35
Mike Stump4e7a1f72009-02-21 20:00:35 +000036llvm::Constant *CodeGenFunction::BuildDescriptorBlockDecl(uint64_t Size) {
Mike Stumpe5fee252009-02-13 16:19:19 +000037 const llvm::PointerType *PtrToInt8Ty
38 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stump56129b12009-02-13 16:55:51 +000039 const llvm::Type *UnsignedLongTy
40 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpe5fee252009-02-13 16:19:19 +000041 llvm::Constant *C;
42 std::vector<llvm::Constant*> Elts;
43
44 // reserved
Mike Stump56129b12009-02-13 16:55:51 +000045 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000046 Elts.push_back(C);
47
48 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000049 // FIXME: What is the right way to say this doesn't fit? We should give
50 // a user diagnostic in that case. Better fix would be to change the
51 // API to size_t.
Mike Stump4e7a1f72009-02-21 20:00:35 +000052 C = llvm::ConstantInt::get(UnsignedLongTy, Size);
Mike Stumpe5fee252009-02-13 16:19:19 +000053 Elts.push_back(C);
54
55 if (BlockHasCopyDispose) {
56 // copy_func_helper_decl
Mike Stump4e7a1f72009-02-21 20:00:35 +000057 // FIXME: implement
Mike Stump56129b12009-02-13 16:55:51 +000058 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000059 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
60 Elts.push_back(C);
61
62 // destroy_func_decl
Mike Stump4e7a1f72009-02-21 20:00:35 +000063 // FIXME: implement
Mike Stump56129b12009-02-13 16:55:51 +000064 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000065 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
66 Elts.push_back(C);
67 }
68
69 C = llvm::ConstantStruct::get(Elts);
70
Mike Stumpe5fee252009-02-13 16:19:19 +000071 C = new llvm::GlobalVariable(C->getType(), true,
72 llvm::GlobalValue::InternalLinkage,
Mike Stump7d6dc4f2009-02-13 20:17:16 +000073 C, "__block_descriptor_tmp", &CGM.getModule());
Mike Stumpe5fee252009-02-13 16:19:19 +000074 return C;
75}
76
Mike Stump2a998142009-03-04 18:17:45 +000077llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Mike Stumpf99f1d02009-02-13 17:23:42 +000078 if (NSConcreteGlobalBlock)
79 return NSConcreteGlobalBlock;
80
81 const llvm::PointerType *PtrToInt8Ty
82 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stumpf7448952009-02-13 19:38:12 +000083 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000084 // same thing as CreateRuntimeFunction if there's already a variable with the
85 // same name.
Mike Stumpf99f1d02009-02-13 17:23:42 +000086 NSConcreteGlobalBlock
87 = new llvm::GlobalVariable(PtrToInt8Ty, false,
88 llvm::GlobalValue::ExternalLinkage,
89 0, "_NSConcreteGlobalBlock",
90 &getModule());
91
92 return NSConcreteGlobalBlock;
93}
94
Mike Stump2a998142009-03-04 18:17:45 +000095llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Mike Stump59c5b112009-02-13 19:29:27 +000096 if (NSConcreteStackBlock)
97 return NSConcreteStackBlock;
98
99 const llvm::PointerType *PtrToInt8Ty
100 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stumpf7448952009-02-13 19:38:12 +0000101 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +0000102 // same thing as CreateRuntimeFunction if there's already a variable with the
103 // same name.
Mike Stump59c5b112009-02-13 19:29:27 +0000104 NSConcreteStackBlock
105 = new llvm::GlobalVariable(PtrToInt8Ty, false,
106 llvm::GlobalValue::ExternalLinkage,
107 0, "_NSConcreteStackBlock",
108 &getModule());
109
110 return NSConcreteStackBlock;
111}
112
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000113static void CollectBlockDeclRefInfo(const Stmt *S,
114 CodeGenFunction::BlockInfo &Info) {
115 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
116 I != E; ++I)
Daniel Dunbar82573ee2009-03-02 07:00:57 +0000117 if (*I)
118 CollectBlockDeclRefInfo(*I, Info);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000119
120 if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
121 // FIXME: Handle enums.
122 if (isa<FunctionDecl>(DE->getDecl()))
123 return;
124
125 if (DE->isByRef())
126 Info.ByRefDeclRefs.push_back(DE);
127 else
128 Info.ByCopyDeclRefs.push_back(DE);
129 }
130}
131
Mike Stump58a85142009-03-04 22:48:06 +0000132/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
133/// declared as a global variable instead of on the stack.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000134static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
135{
136 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
137}
138
Mike Stump58a85142009-03-04 22:48:06 +0000139// FIXME: Push most into CGM, passing down a few bits, like current function
140// name.
Mike Stump8a2b4b12009-02-25 23:33:13 +0000141llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Mike Stumpe5fee252009-02-13 16:19:19 +0000142
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000143 std::string Name = CurFn->getName();
144 CodeGenFunction::BlockInfo Info(0, Name.c_str());
145 CollectBlockDeclRefInfo(BE->getBody(), Info);
146
147 // Check if the block can be global.
Mike Stump58a85142009-03-04 22:48:06 +0000148 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
149 // to just have one code path. We should move this function into CGM and pass
150 // CGF, then we can just check to see if CGF is 0.
Mike Stumpdab514f2009-03-04 03:23:46 +0000151 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000152 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
153
Mike Stumpe5fee252009-02-13 16:19:19 +0000154 std::vector<llvm::Constant*> Elts;
155 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000156 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000157
Mike Stumpe5fee252009-02-13 16:19:19 +0000158 {
159 // C = BuildBlockStructInitlist();
160 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
161
162 if (BlockHasCopyDispose)
163 flags |= BLOCK_HAS_COPY_DISPOSE;
164
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000165 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000166 C = CGM.getNSConcreteStackBlock();
Mike Stump59c5b112009-02-13 19:29:27 +0000167 const llvm::PointerType *PtrToInt8Ty
168 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stumpe5fee252009-02-13 16:19:19 +0000169 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
170 Elts.push_back(C);
171
172 // __flags
173 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
174 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
175 C = llvm::ConstantInt::get(IntTy, flags);
176 Elts.push_back(C);
177
178 // __reserved
179 C = llvm::ConstantInt::get(IntTy, 0);
180 Elts.push_back(C);
181
Mike Stumpbd65cac2009-02-19 01:01:04 +0000182 // __invoke
Mike Stump8a2b4b12009-02-25 23:33:13 +0000183 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000184 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000185 llvm::Function *Fn
Mike Stump8a2b4b12009-02-25 23:33:13 +0000186 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
187 subBlockAlign, subBlockDeclRefDecls);
Mike Stump67a64482009-02-14 22:16:35 +0000188 Elts.push_back(Fn);
Mike Stumpe5fee252009-02-13 16:19:19 +0000189
190 // __descriptor
Mike Stump4e7a1f72009-02-21 20:00:35 +0000191 Elts.push_back(BuildDescriptorBlockDecl(subBlockSize));
Mike Stumpe5fee252009-02-13 16:19:19 +0000192
Mike Stump8a2b4b12009-02-25 23:33:13 +0000193 if (subBlockDeclRefDecls.size() == 0) {
Mike Stump5570cfe2009-03-01 20:07:53 +0000194 // Optimize to being a global block.
195 Elts[0] = CGM.getNSConcreteGlobalBlock();
196 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
197
Mike Stump8a2b4b12009-02-25 23:33:13 +0000198 C = llvm::ConstantStruct::get(Elts);
199
200 char Name[32];
201 sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
202 C = new llvm::GlobalVariable(C->getType(), true,
203 llvm::GlobalValue::InternalLinkage,
204 C, Name, &CGM.getModule());
205 QualType BPT = BE->getType();
206 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
207 return C;
208 }
209
210 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
211 for (int i=0; i<5; ++i)
212 Types[i] = Elts[i]->getType();
213
Mike Stumpa99038c2009-02-28 09:07:16 +0000214 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
215 const Expr *E = subBlockDeclRefDecls[i];
216 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
217 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000218 if (BDRE && BDRE->isByRef()) {
219 uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
220 Types[i+5] = llvm::PointerType::get(BuildByRefType(Ty, Align), 0);
221 } else
222 Types[i+5] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000223 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000224
225 llvm::Type *Ty = llvm::StructType::get(Types, true);
226
227 llvm::AllocaInst *A = CreateTempAlloca(Ty);
228 A->setAlignment(subBlockAlign);
229 V = A;
230
231 for (unsigned i=0; i<5; ++i)
232 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
233
234 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
235 {
Mike Stumpa99038c2009-02-28 09:07:16 +0000236 // FIXME: Push const down.
237 Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
238 DeclRefExpr *DR;
239 ValueDecl *VD;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000240
Mike Stumpa99038c2009-02-28 09:07:16 +0000241 DR = dyn_cast<DeclRefExpr>(E);
242 // Skip padding.
243 if (DR) continue;
244
245 BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
246 VD = BDRE->getDecl();
247
Mike Stumpdab514f2009-03-04 03:23:46 +0000248 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stumpa99038c2009-02-28 09:07:16 +0000249 // FIXME: I want a better way to do this.
250 if (LocalDeclMap[VD]) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000251 if (BDRE->isByRef()) {
252 const llvm::Type *Ty = Types[i+5];
253 llvm::Value *Loc = LocalDeclMap[VD];
254 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
255 Loc = Builder.CreateLoad(Loc, false);
256 Loc = Builder.CreateBitCast(Loc, Ty);
257 Builder.CreateStore(Loc, Addr);
258 continue;
259 } else
260 E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
261 VD->getType(), SourceLocation(),
262 false, false);
Mike Stumpa99038c2009-02-28 09:07:16 +0000263 }
Mike Stumpdab514f2009-03-04 03:23:46 +0000264 if (BDRE->isByRef()) {
265 // FIXME: __block in nested literals
Mike Stumpa99038c2009-02-28 09:07:16 +0000266 E = new (getContext())
267 UnaryOperator(E, UnaryOperator::AddrOf,
268 getContext().getPointerType(E->getType()),
269 SourceLocation());
Mike Stumpdab514f2009-03-04 03:23:46 +0000270 }
Mike Stumpa99038c2009-02-28 09:07:16 +0000271
Mike Stumpa99038c2009-02-28 09:07:16 +0000272 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpdab514f2009-03-04 03:23:46 +0000273 if (r.isScalar()) {
274 llvm::Value *Loc = r.getScalarVal();
275 const llvm::Type *Ty = Types[i+5];
276 if (BDRE->isByRef()) {
Mike Stump58a85142009-03-04 22:48:06 +0000277 // E is now the address of the value field, instead, we want the
278 // address of the actual ByRef struct. We optimize this slightly
279 // compared to gcc by not grabbing the forwarding slot as this must
280 // be done during Block_copy for us, and we can postpone the work
281 // until then.
282 uint64_t offset = BlockDecls[BDRE->getDecl()];
283
284 llvm::Value *BlockLiteral = LoadBlockStruct();
285
286 Loc = Builder.CreateGEP(BlockLiteral,
287 llvm::ConstantInt::get(llvm::Type::Int64Ty,
288 offset),
289 "block.literal");
290 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000291 Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stump58a85142009-03-04 22:48:06 +0000292 Loc = Builder.CreateLoad(Loc, false);
293 // Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000294 }
295 Builder.CreateStore(Loc, Addr);
296 } else if (r.isComplex())
Mike Stump8a2b4b12009-02-25 23:33:13 +0000297 // FIXME: implement
298 ErrorUnsupported(BE, "complex in block literal");
299 else if (r.isAggregate())
300 ; // Already created into the destination
301 else
302 assert (0 && "bad block variable");
303 // FIXME: Ensure that the offset created by the backend for
304 // the struct matches the previously computed offset in BlockDecls.
305 }
Mike Stumpe5fee252009-02-13 16:19:19 +0000306 }
307
Mike Stumpbd65cac2009-02-19 01:01:04 +0000308 QualType BPT = BE->getType();
Mike Stump8a2b4b12009-02-25 23:33:13 +0000309 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stumpe5fee252009-02-13 16:19:19 +0000310}
311
312
Mike Stump2a998142009-03-04 18:17:45 +0000313const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000314 if (BlockDescriptorType)
315 return BlockDescriptorType;
316
Mike Stumpa5448542009-02-13 15:32:32 +0000317 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000318 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000319
Mike Stumpab695142009-02-13 15:16:56 +0000320 // struct __block_descriptor {
321 // unsigned long reserved;
322 // unsigned long block_size;
323 // };
Mike Stumpa5448542009-02-13 15:32:32 +0000324 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
325 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000326 NULL);
327
328 getModule().addTypeName("struct.__block_descriptor",
329 BlockDescriptorType);
330
331 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000332}
333
Mike Stump2a998142009-03-04 18:17:45 +0000334const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000335 if (GenericBlockLiteralType)
336 return GenericBlockLiteralType;
337
Mike Stumpa5448542009-02-13 15:32:32 +0000338 const llvm::Type *Int8PtrTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000339 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stumpa5448542009-02-13 15:32:32 +0000340
341 const llvm::Type *BlockDescPtrTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000342 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpa5448542009-02-13 15:32:32 +0000343
Mike Stump7cbb3602009-02-13 16:01:35 +0000344 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
345 getTypes().ConvertType(getContext().IntTy));
346
Mike Stump9b8a7972009-02-13 15:25:34 +0000347 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000348 // void *__isa;
349 // int __flags;
350 // int __reserved;
351 // void (*__invoke)(void *);
352 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000353 // };
354 GenericBlockLiteralType = llvm::StructType::get(Int8PtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000355 IntTy,
356 IntTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000357 Int8PtrTy,
358 BlockDescPtrTy,
359 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000360
Mike Stump9b8a7972009-02-13 15:25:34 +0000361 getModule().addTypeName("struct.__block_literal_generic",
362 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000363
Mike Stump9b8a7972009-02-13 15:25:34 +0000364 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000365}
366
Mike Stump2a998142009-03-04 18:17:45 +0000367const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000368 if (GenericExtendedBlockLiteralType)
369 return GenericExtendedBlockLiteralType;
370
371 const llvm::Type *Int8PtrTy =
372 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
373
374 const llvm::Type *BlockDescPtrTy =
375 llvm::PointerType::getUnqual(getBlockDescriptorType());
376
377 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
378 getTypes().ConvertType(getContext().IntTy));
379
380 // struct __block_literal_generic {
381 // void *__isa;
382 // int __flags;
383 // int __reserved;
384 // void (*__invoke)(void *);
385 // struct __block_descriptor *__descriptor;
386 // void *__copy_func_helper_decl;
387 // void *__destroy_func_decl;
388 // };
389 GenericExtendedBlockLiteralType = llvm::StructType::get(Int8PtrTy,
390 IntTy,
391 IntTy,
392 Int8PtrTy,
393 BlockDescPtrTy,
394 Int8PtrTy,
395 Int8PtrTy,
396 NULL);
397
398 getModule().addTypeName("struct.__block_literal_extended_generic",
399 GenericExtendedBlockLiteralType);
400
401 return GenericExtendedBlockLiteralType;
402}
403
Mike Stumpa5448542009-02-13 15:32:32 +0000404/// getBlockFunctionType - Given a BlockPointerType, will return the
Anders Carlssonacfde802009-02-12 00:39:25 +0000405/// function type for the block, including the first block literal argument.
406static QualType getBlockFunctionType(ASTContext &Ctx,
Anders Carlssond5cab542009-02-12 17:55:02 +0000407 const BlockPointerType *BPT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000408 const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
Mike Stumpa5448542009-02-13 15:32:32 +0000409
Anders Carlssonacfde802009-02-12 00:39:25 +0000410 llvm::SmallVector<QualType, 8> Types;
411 Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000412
Douglas Gregor72564e72009-02-26 23:50:07 +0000413 for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000414 e = FTy->arg_type_end(); i != e; ++i)
415 Types.push_back(*i);
Mike Stumpa5448542009-02-13 15:32:32 +0000416
Anders Carlssonacfde802009-02-12 00:39:25 +0000417 return Ctx.getFunctionType(FTy->getResultType(),
Mike Stumpa5448542009-02-13 15:32:32 +0000418 &Types[0], Types.size(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000419 FTy->isVariadic(), 0);
420}
421
Anders Carlssond5cab542009-02-12 17:55:02 +0000422RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpa5448542009-02-13 15:32:32 +0000423 const BlockPointerType *BPT =
Anders Carlssonacfde802009-02-12 00:39:25 +0000424 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpa5448542009-02-13 15:32:32 +0000425
Anders Carlssonacfde802009-02-12 00:39:25 +0000426 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
427
428 // Get a pointer to the generic block literal.
429 const llvm::Type *BlockLiteralTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000430 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000431
432 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000433 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000434 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
435
436 // Get the function pointer from the literal.
437 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Mike Stump20733cd2009-02-22 13:27:11 +0000438 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000439
440 // Cast the function pointer to the right type.
Mike Stumpa5448542009-02-13 15:32:32 +0000441 const llvm::Type *BlockFTy =
Anders Carlssonacfde802009-02-12 00:39:25 +0000442 ConvertType(getBlockFunctionType(getContext(), BPT));
443 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
444 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
445
Mike Stumpa5448542009-02-13 15:32:32 +0000446 BlockLiteral =
447 Builder.CreateBitCast(BlockLiteral,
Anders Carlssonacfde802009-02-12 00:39:25 +0000448 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
449 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000450
Anders Carlssonacfde802009-02-12 00:39:25 +0000451 // Add the block literal.
452 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
453 CallArgList Args;
454 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000455
Anders Carlssonacfde802009-02-12 00:39:25 +0000456 // And the rest of the arguments.
Mike Stumpa5448542009-02-13 15:32:32 +0000457 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
Anders Carlssonacfde802009-02-12 00:39:25 +0000458 i != e; ++i)
Mike Stumpa5448542009-02-13 15:32:32 +0000459 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
Anders Carlssonacfde802009-02-12 00:39:25 +0000460 i->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000461
Anders Carlssonacfde802009-02-12 00:39:25 +0000462 // And call the block.
Mike Stumpa5448542009-02-13 15:32:32 +0000463 return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
Anders Carlssonacfde802009-02-12 00:39:25 +0000464 Func, Args);
465}
Anders Carlssond5cab542009-02-12 17:55:02 +0000466
Mike Stumpdab514f2009-03-04 03:23:46 +0000467llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
468 uint64_t &offset = BlockDecls[E->getDecl()];
469
470 const llvm::Type *Ty;
471 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
472
473 // FIXME: add support for copy/dispose helpers.
Mike Stump58919e12009-03-04 13:17:22 +0000474 if (!Enable__block && E->isByRef())
Mike Stumpdab514f2009-03-04 03:23:46 +0000475 ErrorUnsupported(E, "__block variable in block literal");
476 else if (E->getType()->isBlockPointerType())
477 ErrorUnsupported(E, "block pointer in block literal");
478 else if (E->getDecl()->getAttr<ObjCNSObjectAttr>() ||
479 getContext().isObjCNSObjectType(E->getType()))
480 ErrorUnsupported(E, "__attribute__((NSObject)) variable in block "
481 "literal");
482 else if (getContext().isObjCObjectPointerType(E->getType()))
483 ErrorUnsupported(E, "Objective-C variable in block literal");
484
485 // See if we have already allocated an offset for this variable.
486 if (offset == 0) {
487 // if not, allocate one now.
488 offset = getBlockOffset(E);
489 }
490
491 llvm::Value *BlockLiteral = LoadBlockStruct();
492 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
493 llvm::ConstantInt::get(llvm::Type::Int64Ty,
494 offset),
Mike Stump58a85142009-03-04 22:48:06 +0000495 "block.literal");
Mike Stumpdab514f2009-03-04 03:23:46 +0000496 if (E->isByRef()) {
497 bool needsCopyDispose = BlockRequiresCopying(E->getType());
498 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
499 const llvm::Type *PtrStructTy
500 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
501 Ty = PtrStructTy;
502 Ty = llvm::PointerType::get(Ty, 0);
503 V = Builder.CreateBitCast(V, Ty);
504 V = Builder.CreateLoad(V, false);
505 V = Builder.CreateStructGEP(V, 1, "forwarding");
506 V = Builder.CreateLoad(V, false);
507 V = Builder.CreateBitCast(V, PtrStructTy);
508 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
509 } else {
510 Ty = llvm::PointerType::get(Ty, 0);
511 V = Builder.CreateBitCast(V, Ty);
512 }
513 return V;
514}
515
Mike Stump67a64482009-02-14 22:16:35 +0000516llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000517BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000518 // Generate the block descriptor.
519 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000520 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
521 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000522
Anders Carlssond5cab542009-02-12 17:55:02 +0000523 llvm::Constant *DescriptorFields[2];
Mike Stumpa5448542009-02-13 15:32:32 +0000524
Anders Carlssond5cab542009-02-12 17:55:02 +0000525 // Reserved
526 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000527
Anders Carlssond5cab542009-02-12 17:55:02 +0000528 // Block literal size. For global blocks we just use the size of the generic
529 // block literal struct.
Mike Stumpa5448542009-02-13 15:32:32 +0000530 uint64_t BlockLiteralSize =
Mike Stump9b8a7972009-02-13 15:25:34 +0000531 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlssond5cab542009-02-12 17:55:02 +0000532 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpa5448542009-02-13 15:32:32 +0000533
534 llvm::Constant *DescriptorStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000535 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpa5448542009-02-13 15:32:32 +0000536
Anders Carlssond5cab542009-02-12 17:55:02 +0000537 llvm::GlobalVariable *Descriptor =
538 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000539 llvm::GlobalVariable::InternalLinkage,
540 DescriptorStruct, "__block_descriptor_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000541 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000542
Anders Carlssond5cab542009-02-12 17:55:02 +0000543 // Generate the constants for the block literal.
544 llvm::Constant *LiteralFields[5];
Mike Stumpa5448542009-02-13 15:32:32 +0000545
Mike Stump67a64482009-02-14 22:16:35 +0000546 CodeGenFunction::BlockInfo Info(0, n);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000547 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000548 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000549 llvm::Function *Fn
Mike Stump90a90432009-03-04 18:47:42 +0000550 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
551 subBlockAlign,
552 subBlockDeclRefDecls);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000553 assert(subBlockSize == BlockLiteralSize
554 && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000555
Anders Carlssond5cab542009-02-12 17:55:02 +0000556 // isa
Mike Stumpf99f1d02009-02-13 17:23:42 +0000557 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000558
Anders Carlssond5cab542009-02-12 17:55:02 +0000559 // Flags
Anders Carlsson8045ee02009-03-01 21:09:29 +0000560 LiteralFields[1] =
561 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpa5448542009-02-13 15:32:32 +0000562
Anders Carlssond5cab542009-02-12 17:55:02 +0000563 // Reserved
Mike Stump7cbb3602009-02-13 16:01:35 +0000564 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000565
Anders Carlssond5cab542009-02-12 17:55:02 +0000566 // Function
567 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000568
Anders Carlssond5cab542009-02-12 17:55:02 +0000569 // Descriptor
570 LiteralFields[4] = Descriptor;
Mike Stumpa5448542009-02-13 15:32:32 +0000571
572 llvm::Constant *BlockLiteralStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000573 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpa5448542009-02-13 15:32:32 +0000574
575 llvm::GlobalVariable *BlockLiteral =
Anders Carlssond5cab542009-02-12 17:55:02 +0000576 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000577 llvm::GlobalVariable::InternalLinkage,
578 BlockLiteralStruct, "__block_literal_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000579 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000580
Anders Carlssond5cab542009-02-12 17:55:02 +0000581 return BlockLiteral;
582}
583
Mike Stump4e7a1f72009-02-21 20:00:35 +0000584llvm::Value *CodeGenFunction::LoadBlockStruct() {
585 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
586}
587
Chris Lattner161d36d2009-02-28 19:01:03 +0000588llvm::Function *CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
Mike Stump4e7a1f72009-02-21 20:00:35 +0000589 const BlockInfo& Info,
Mike Stump8a2b4b12009-02-25 23:33:13 +0000590 uint64_t &Size,
591 uint64_t &Align,
Mike Stumpa99038c2009-02-28 09:07:16 +0000592 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000593 const FunctionProtoType *FTy =
Chris Lattner161d36d2009-02-28 19:01:03 +0000594 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpa5448542009-02-13 15:32:32 +0000595
Anders Carlssond5cab542009-02-12 17:55:02 +0000596 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000597
Chris Lattner161d36d2009-02-28 19:01:03 +0000598 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000599
600 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000601 ImplicitParamDecl *SelfDecl =
Anders Carlssond5cab542009-02-12 17:55:02 +0000602 ImplicitParamDecl::Create(getContext(), 0,
603 SourceLocation(), 0,
604 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000605
Anders Carlssond5cab542009-02-12 17:55:02 +0000606 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000607 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000608
609 for (BlockDecl::param_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000610 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000611 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000612
613 const CGFunctionInfo &FI =
Anders Carlssond5cab542009-02-12 17:55:02 +0000614 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
615
Mike Stump67a64482009-02-14 22:16:35 +0000616 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlssond5cab542009-02-12 17:55:02 +0000617 CodeGenTypes &Types = CGM.getTypes();
618 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000619
620 llvm::Function *Fn =
Anders Carlssond5cab542009-02-12 17:55:02 +0000621 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
622 Name,
623 &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000624
625 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000626 BExpr->getBody()->getLocEnd());
627 EmitStmt(BExpr->getBody());
628 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000629
Mike Stump8a2b4b12009-02-25 23:33:13 +0000630 // The runtime needs a minimum alignment of a void *.
631 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
632 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
633
Mike Stump4e7a1f72009-02-21 20:00:35 +0000634 Size = BlockOffset;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000635 Align = BlockAlign;
636 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000637
Anders Carlssond5cab542009-02-12 17:55:02 +0000638 return Fn;
639}
Mike Stumpa99038c2009-02-28 09:07:16 +0000640
641uint64_t CodeGenFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
642 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
643
644 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
645 uint64_t Align = getContext().getDeclAlignInBytes(D);
646
647 if (BDRE->isByRef()) {
648 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
649 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
650 }
651
652 assert ((Align > 0) && "alignment must be 1 byte or more");
653
654 uint64_t OldOffset = BlockOffset;
655
656 // Ensure proper alignment, even if it means we have to have a gap
657 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
658 BlockAlign = std::max(Align, BlockAlign);
659
660 uint64_t Pad = BlockOffset - OldOffset;
661 if (Pad) {
662 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
663 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
664 llvm::APInt(32, Pad),
665 ArrayType::Normal, 0);
666 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
667 0, QualType(PadTy), VarDecl::None,
668 SourceLocation());
669 Expr *E;
670 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
671 SourceLocation(), false, false);
672 BlockDeclRefDecls.push_back(E);
673 }
674 BlockDeclRefDecls.push_back(BDRE);
675
676 BlockOffset += Size;
677 return BlockOffset-Size;
678}
Mike Stumpdab514f2009-03-04 03:23:46 +0000679
Mike Stump3947de52009-03-04 18:57:26 +0000680llvm::Value *BlockFunction::BuildCopyHelper(int flag) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000681 const llvm::PointerType *PtrToInt8Ty
682 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
683 // FIXME: implement
684 llvm::Value *V = llvm::ConstantInt::get(llvm::Type::Int32Ty, 43);
685 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "tmp");
686 V = Builder.CreateBitCast(V, PtrToInt8Ty, "tmp");
687 return V;
688}
689
Mike Stump3947de52009-03-04 18:57:26 +0000690llvm::Value *BlockFunction::BuildDestroyHelper(int flag) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000691 const llvm::PointerType *PtrToInt8Ty
692 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
693 // FIXME: implement
694 llvm::Value *V = llvm::ConstantInt::get(llvm::Type::Int32Ty, 44);
695 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "tmp");
696 V = Builder.CreateBitCast(V, PtrToInt8Ty, "tmp");
697 return V;
698}