blob: 8aabada259c37dda0d613af9134a32662b04690e [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 Stumpf99f1d02009-02-13 17:23:42 +000084 // same thing as CreateRuntimeFunction if there's already a variable with
85 // the same name.
86 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 Stump59c5b112009-02-13 19:29:27 +0000102 // same thing as CreateRuntimeFunction if there's already a variable with
103 // the same name.
104 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
132/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block
133/// can be declared as a global variable instead of on the stack.
134static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
135{
136 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
137}
138
Mike Stumpbd65cac2009-02-19 01:01:04 +0000139// FIXME: Push most into CGM, passing down a few bits, like current
140// function 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 Stumpdab514f2009-03-04 03:23:46 +0000148 // FIXME: This test doesn't work for nested blocks yet. Longer
149 // term, I'd like to just have one code path. We should move
150 // this function into CGM and pass CGF, then we can just check to
151 // see if CGF is 0.
152 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000153 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
154
Mike Stumpe5fee252009-02-13 16:19:19 +0000155 std::vector<llvm::Constant*> Elts;
156 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000157 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000158
Mike Stumpe5fee252009-02-13 16:19:19 +0000159 {
160 // C = BuildBlockStructInitlist();
161 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
162
163 if (BlockHasCopyDispose)
164 flags |= BLOCK_HAS_COPY_DISPOSE;
165
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000166 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000167 C = CGM.getNSConcreteStackBlock();
Mike Stump59c5b112009-02-13 19:29:27 +0000168 const llvm::PointerType *PtrToInt8Ty
169 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stumpe5fee252009-02-13 16:19:19 +0000170 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
171 Elts.push_back(C);
172
173 // __flags
174 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
175 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
176 C = llvm::ConstantInt::get(IntTy, flags);
177 Elts.push_back(C);
178
179 // __reserved
180 C = llvm::ConstantInt::get(IntTy, 0);
181 Elts.push_back(C);
182
Mike Stumpbd65cac2009-02-19 01:01:04 +0000183 // __invoke
Mike Stump8a2b4b12009-02-25 23:33:13 +0000184 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000185 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000186 llvm::Function *Fn
Mike Stump8a2b4b12009-02-25 23:33:13 +0000187 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
188 subBlockAlign, subBlockDeclRefDecls);
Mike Stump67a64482009-02-14 22:16:35 +0000189 Elts.push_back(Fn);
Mike Stumpe5fee252009-02-13 16:19:19 +0000190
191 // __descriptor
Mike Stump4e7a1f72009-02-21 20:00:35 +0000192 Elts.push_back(BuildDescriptorBlockDecl(subBlockSize));
Mike Stumpe5fee252009-02-13 16:19:19 +0000193
Mike Stump8a2b4b12009-02-25 23:33:13 +0000194 if (subBlockDeclRefDecls.size() == 0) {
Mike Stump5570cfe2009-03-01 20:07:53 +0000195 // Optimize to being a global block.
196 Elts[0] = CGM.getNSConcreteGlobalBlock();
197 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
198
Mike Stump8a2b4b12009-02-25 23:33:13 +0000199 C = llvm::ConstantStruct::get(Elts);
200
201 char Name[32];
202 sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
203 C = new llvm::GlobalVariable(C->getType(), true,
204 llvm::GlobalValue::InternalLinkage,
205 C, Name, &CGM.getModule());
206 QualType BPT = BE->getType();
207 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
208 return C;
209 }
210
211 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
212 for (int i=0; i<5; ++i)
213 Types[i] = Elts[i]->getType();
214
Mike Stumpa99038c2009-02-28 09:07:16 +0000215 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
216 const Expr *E = subBlockDeclRefDecls[i];
217 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
218 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000219 if (BDRE && BDRE->isByRef()) {
220 uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
221 Types[i+5] = llvm::PointerType::get(BuildByRefType(Ty, Align), 0);
222 } else
223 Types[i+5] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000224 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000225
226 llvm::Type *Ty = llvm::StructType::get(Types, true);
227
228 llvm::AllocaInst *A = CreateTempAlloca(Ty);
229 A->setAlignment(subBlockAlign);
230 V = A;
231
232 for (unsigned i=0; i<5; ++i)
233 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
234
235 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
236 {
Mike Stumpa99038c2009-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 Stump8a2b4b12009-02-25 23:33:13 +0000241
Mike Stumpa99038c2009-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 Stumpdab514f2009-03-04 03:23:46 +0000249 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stumpa99038c2009-02-28 09:07:16 +0000250 // FIXME: I want a better way to do this.
251 if (LocalDeclMap[VD]) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000252 if (BDRE->isByRef()) {
253 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);
259 continue;
260 } else
261 E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
262 VD->getType(), SourceLocation(),
263 false, false);
Mike Stumpa99038c2009-02-28 09:07:16 +0000264 }
Mike Stumpdab514f2009-03-04 03:23:46 +0000265 if (BDRE->isByRef()) {
266 // FIXME: __block in nested literals
Mike Stumpa99038c2009-02-28 09:07:16 +0000267 E = new (getContext())
268 UnaryOperator(E, UnaryOperator::AddrOf,
269 getContext().getPointerType(E->getType()),
270 SourceLocation());
Mike Stumpdab514f2009-03-04 03:23:46 +0000271 }
Mike Stumpa99038c2009-02-28 09:07:16 +0000272
Mike Stumpa99038c2009-02-28 09:07:16 +0000273 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpdab514f2009-03-04 03:23:46 +0000274 if (r.isScalar()) {
275 llvm::Value *Loc = r.getScalarVal();
276 const llvm::Type *Ty = Types[i+5];
277 if (BDRE->isByRef()) {
278 Loc = Builder.CreateBitCast(Loc, Ty);
279 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
280 Loc = Builder.CreateBitCast(Loc, Ty);
281 }
282 Builder.CreateStore(Loc, Addr);
283 } else if (r.isComplex())
Mike Stump8a2b4b12009-02-25 23:33:13 +0000284 // FIXME: implement
285 ErrorUnsupported(BE, "complex in block literal");
286 else if (r.isAggregate())
287 ; // Already created into the destination
288 else
289 assert (0 && "bad block variable");
290 // FIXME: Ensure that the offset created by the backend for
291 // the struct matches the previously computed offset in BlockDecls.
292 }
Mike Stumpe5fee252009-02-13 16:19:19 +0000293 }
294
Mike Stumpbd65cac2009-02-19 01:01:04 +0000295 QualType BPT = BE->getType();
Mike Stump8a2b4b12009-02-25 23:33:13 +0000296 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stumpe5fee252009-02-13 16:19:19 +0000297}
298
299
Mike Stump2a998142009-03-04 18:17:45 +0000300const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000301 if (BlockDescriptorType)
302 return BlockDescriptorType;
303
Mike Stumpa5448542009-02-13 15:32:32 +0000304 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000305 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000306
Mike Stumpab695142009-02-13 15:16:56 +0000307 // struct __block_descriptor {
308 // unsigned long reserved;
309 // unsigned long block_size;
310 // };
Mike Stumpa5448542009-02-13 15:32:32 +0000311 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
312 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000313 NULL);
314
315 getModule().addTypeName("struct.__block_descriptor",
316 BlockDescriptorType);
317
318 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000319}
320
Mike Stump2a998142009-03-04 18:17:45 +0000321const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000322 if (GenericBlockLiteralType)
323 return GenericBlockLiteralType;
324
Mike Stumpa5448542009-02-13 15:32:32 +0000325 const llvm::Type *Int8PtrTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000326 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stumpa5448542009-02-13 15:32:32 +0000327
328 const llvm::Type *BlockDescPtrTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000329 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpa5448542009-02-13 15:32:32 +0000330
Mike Stump7cbb3602009-02-13 16:01:35 +0000331 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
332 getTypes().ConvertType(getContext().IntTy));
333
Mike Stump9b8a7972009-02-13 15:25:34 +0000334 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000335 // void *__isa;
336 // int __flags;
337 // int __reserved;
338 // void (*__invoke)(void *);
339 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000340 // };
341 GenericBlockLiteralType = llvm::StructType::get(Int8PtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000342 IntTy,
343 IntTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000344 Int8PtrTy,
345 BlockDescPtrTy,
346 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000347
Mike Stump9b8a7972009-02-13 15:25:34 +0000348 getModule().addTypeName("struct.__block_literal_generic",
349 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000350
Mike Stump9b8a7972009-02-13 15:25:34 +0000351 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000352}
353
Mike Stump2a998142009-03-04 18:17:45 +0000354const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000355 if (GenericExtendedBlockLiteralType)
356 return GenericExtendedBlockLiteralType;
357
358 const llvm::Type *Int8PtrTy =
359 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
360
361 const llvm::Type *BlockDescPtrTy =
362 llvm::PointerType::getUnqual(getBlockDescriptorType());
363
364 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
365 getTypes().ConvertType(getContext().IntTy));
366
367 // struct __block_literal_generic {
368 // void *__isa;
369 // int __flags;
370 // int __reserved;
371 // void (*__invoke)(void *);
372 // struct __block_descriptor *__descriptor;
373 // void *__copy_func_helper_decl;
374 // void *__destroy_func_decl;
375 // };
376 GenericExtendedBlockLiteralType = llvm::StructType::get(Int8PtrTy,
377 IntTy,
378 IntTy,
379 Int8PtrTy,
380 BlockDescPtrTy,
381 Int8PtrTy,
382 Int8PtrTy,
383 NULL);
384
385 getModule().addTypeName("struct.__block_literal_extended_generic",
386 GenericExtendedBlockLiteralType);
387
388 return GenericExtendedBlockLiteralType;
389}
390
Mike Stumpa5448542009-02-13 15:32:32 +0000391/// getBlockFunctionType - Given a BlockPointerType, will return the
Anders Carlssonacfde802009-02-12 00:39:25 +0000392/// function type for the block, including the first block literal argument.
393static QualType getBlockFunctionType(ASTContext &Ctx,
Anders Carlssond5cab542009-02-12 17:55:02 +0000394 const BlockPointerType *BPT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000395 const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
Mike Stumpa5448542009-02-13 15:32:32 +0000396
Anders Carlssonacfde802009-02-12 00:39:25 +0000397 llvm::SmallVector<QualType, 8> Types;
398 Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000399
Douglas Gregor72564e72009-02-26 23:50:07 +0000400 for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000401 e = FTy->arg_type_end(); i != e; ++i)
402 Types.push_back(*i);
Mike Stumpa5448542009-02-13 15:32:32 +0000403
Anders Carlssonacfde802009-02-12 00:39:25 +0000404 return Ctx.getFunctionType(FTy->getResultType(),
Mike Stumpa5448542009-02-13 15:32:32 +0000405 &Types[0], Types.size(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000406 FTy->isVariadic(), 0);
407}
408
Anders Carlssond5cab542009-02-12 17:55:02 +0000409RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpa5448542009-02-13 15:32:32 +0000410 const BlockPointerType *BPT =
Anders Carlssonacfde802009-02-12 00:39:25 +0000411 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpa5448542009-02-13 15:32:32 +0000412
Anders Carlssonacfde802009-02-12 00:39:25 +0000413 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
414
415 // Get a pointer to the generic block literal.
416 const llvm::Type *BlockLiteralTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000417 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000418
419 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000420 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000421 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
422
423 // Get the function pointer from the literal.
424 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Mike Stump20733cd2009-02-22 13:27:11 +0000425 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000426
427 // Cast the function pointer to the right type.
Mike Stumpa5448542009-02-13 15:32:32 +0000428 const llvm::Type *BlockFTy =
Anders Carlssonacfde802009-02-12 00:39:25 +0000429 ConvertType(getBlockFunctionType(getContext(), BPT));
430 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
431 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
432
Mike Stumpa5448542009-02-13 15:32:32 +0000433 BlockLiteral =
434 Builder.CreateBitCast(BlockLiteral,
Anders Carlssonacfde802009-02-12 00:39:25 +0000435 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
436 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000437
Anders Carlssonacfde802009-02-12 00:39:25 +0000438 // Add the block literal.
439 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
440 CallArgList Args;
441 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000442
Anders Carlssonacfde802009-02-12 00:39:25 +0000443 // And the rest of the arguments.
Mike Stumpa5448542009-02-13 15:32:32 +0000444 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
Anders Carlssonacfde802009-02-12 00:39:25 +0000445 i != e; ++i)
Mike Stumpa5448542009-02-13 15:32:32 +0000446 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
Anders Carlssonacfde802009-02-12 00:39:25 +0000447 i->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000448
Anders Carlssonacfde802009-02-12 00:39:25 +0000449 // And call the block.
Mike Stumpa5448542009-02-13 15:32:32 +0000450 return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
Anders Carlssonacfde802009-02-12 00:39:25 +0000451 Func, Args);
452}
Anders Carlssond5cab542009-02-12 17:55:02 +0000453
Mike Stumpdab514f2009-03-04 03:23:46 +0000454llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
455 uint64_t &offset = BlockDecls[E->getDecl()];
456
457 const llvm::Type *Ty;
458 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
459
460 // FIXME: add support for copy/dispose helpers.
Mike Stump58919e12009-03-04 13:17:22 +0000461 if (!Enable__block && E->isByRef())
Mike Stumpdab514f2009-03-04 03:23:46 +0000462 ErrorUnsupported(E, "__block variable in block literal");
463 else if (E->getType()->isBlockPointerType())
464 ErrorUnsupported(E, "block pointer in block literal");
465 else if (E->getDecl()->getAttr<ObjCNSObjectAttr>() ||
466 getContext().isObjCNSObjectType(E->getType()))
467 ErrorUnsupported(E, "__attribute__((NSObject)) variable in block "
468 "literal");
469 else if (getContext().isObjCObjectPointerType(E->getType()))
470 ErrorUnsupported(E, "Objective-C variable in block literal");
471
472 // See if we have already allocated an offset for this variable.
473 if (offset == 0) {
474 // if not, allocate one now.
475 offset = getBlockOffset(E);
476 }
477
478 llvm::Value *BlockLiteral = LoadBlockStruct();
479 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
480 llvm::ConstantInt::get(llvm::Type::Int64Ty,
481 offset),
482 "tmp");
483 if (E->isByRef()) {
484 bool needsCopyDispose = BlockRequiresCopying(E->getType());
485 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
486 const llvm::Type *PtrStructTy
487 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
488 Ty = PtrStructTy;
489 Ty = llvm::PointerType::get(Ty, 0);
490 V = Builder.CreateBitCast(V, Ty);
491 V = Builder.CreateLoad(V, false);
492 V = Builder.CreateStructGEP(V, 1, "forwarding");
493 V = Builder.CreateLoad(V, false);
494 V = Builder.CreateBitCast(V, PtrStructTy);
495 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
496 } else {
497 Ty = llvm::PointerType::get(Ty, 0);
498 V = Builder.CreateBitCast(V, Ty);
499 }
500 return V;
501}
502
Mike Stump67a64482009-02-14 22:16:35 +0000503llvm::Constant *
Mike Stump30395dd2009-02-14 22:49:33 +0000504CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000505 // Generate the block descriptor.
506 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000507 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
508 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000509
Anders Carlssond5cab542009-02-12 17:55:02 +0000510 llvm::Constant *DescriptorFields[2];
Mike Stumpa5448542009-02-13 15:32:32 +0000511
Anders Carlssond5cab542009-02-12 17:55:02 +0000512 // Reserved
513 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000514
Anders Carlssond5cab542009-02-12 17:55:02 +0000515 // Block literal size. For global blocks we just use the size of the generic
516 // block literal struct.
Mike Stumpa5448542009-02-13 15:32:32 +0000517 uint64_t BlockLiteralSize =
Mike Stump9b8a7972009-02-13 15:25:34 +0000518 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlssond5cab542009-02-12 17:55:02 +0000519 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpa5448542009-02-13 15:32:32 +0000520
521 llvm::Constant *DescriptorStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000522 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpa5448542009-02-13 15:32:32 +0000523
Anders Carlssond5cab542009-02-12 17:55:02 +0000524 llvm::GlobalVariable *Descriptor =
525 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000526 llvm::GlobalVariable::InternalLinkage,
527 DescriptorStruct, "__block_descriptor_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000528 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000529
Anders Carlssond5cab542009-02-12 17:55:02 +0000530 // Generate the constants for the block literal.
531 llvm::Constant *LiteralFields[5];
Mike Stumpa5448542009-02-13 15:32:32 +0000532
Mike Stump67a64482009-02-14 22:16:35 +0000533 CodeGenFunction::BlockInfo Info(0, n);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000534 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000535 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000536 llvm::Function *Fn
Mike Stump8a2b4b12009-02-25 23:33:13 +0000537 = CodeGenFunction(*this).GenerateBlockFunction(BE, Info, subBlockSize,
538 subBlockAlign,
539 subBlockDeclRefDecls);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000540 assert(subBlockSize == BlockLiteralSize
541 && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000542
Anders Carlssond5cab542009-02-12 17:55:02 +0000543 // isa
Mike Stumpf99f1d02009-02-13 17:23:42 +0000544 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000545
Anders Carlssond5cab542009-02-12 17:55:02 +0000546 // Flags
Anders Carlsson8045ee02009-03-01 21:09:29 +0000547 LiteralFields[1] =
548 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpa5448542009-02-13 15:32:32 +0000549
Anders Carlssond5cab542009-02-12 17:55:02 +0000550 // Reserved
Mike Stump7cbb3602009-02-13 16:01:35 +0000551 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000552
Anders Carlssond5cab542009-02-12 17:55:02 +0000553 // Function
554 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000555
Anders Carlssond5cab542009-02-12 17:55:02 +0000556 // Descriptor
557 LiteralFields[4] = Descriptor;
Mike Stumpa5448542009-02-13 15:32:32 +0000558
559 llvm::Constant *BlockLiteralStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000560 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpa5448542009-02-13 15:32:32 +0000561
562 llvm::GlobalVariable *BlockLiteral =
Anders Carlssond5cab542009-02-12 17:55:02 +0000563 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000564 llvm::GlobalVariable::InternalLinkage,
565 BlockLiteralStruct, "__block_literal_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000566 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000567
Anders Carlssond5cab542009-02-12 17:55:02 +0000568 return BlockLiteral;
569}
570
Mike Stump4e7a1f72009-02-21 20:00:35 +0000571llvm::Value *CodeGenFunction::LoadBlockStruct() {
572 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
573}
574
Chris Lattner161d36d2009-02-28 19:01:03 +0000575llvm::Function *CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
Mike Stump4e7a1f72009-02-21 20:00:35 +0000576 const BlockInfo& Info,
Mike Stump8a2b4b12009-02-25 23:33:13 +0000577 uint64_t &Size,
578 uint64_t &Align,
Mike Stumpa99038c2009-02-28 09:07:16 +0000579 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000580 const FunctionProtoType *FTy =
Chris Lattner161d36d2009-02-28 19:01:03 +0000581 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpa5448542009-02-13 15:32:32 +0000582
Anders Carlssond5cab542009-02-12 17:55:02 +0000583 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000584
Chris Lattner161d36d2009-02-28 19:01:03 +0000585 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000586
587 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000588 ImplicitParamDecl *SelfDecl =
Anders Carlssond5cab542009-02-12 17:55:02 +0000589 ImplicitParamDecl::Create(getContext(), 0,
590 SourceLocation(), 0,
591 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000592
Anders Carlssond5cab542009-02-12 17:55:02 +0000593 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000594 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000595
596 for (BlockDecl::param_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000597 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000598 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000599
600 const CGFunctionInfo &FI =
Anders Carlssond5cab542009-02-12 17:55:02 +0000601 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
602
Mike Stump67a64482009-02-14 22:16:35 +0000603 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlssond5cab542009-02-12 17:55:02 +0000604 CodeGenTypes &Types = CGM.getTypes();
605 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000606
607 llvm::Function *Fn =
Anders Carlssond5cab542009-02-12 17:55:02 +0000608 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
609 Name,
610 &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000611
612 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000613 BExpr->getBody()->getLocEnd());
614 EmitStmt(BExpr->getBody());
615 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000616
Mike Stump8a2b4b12009-02-25 23:33:13 +0000617 // The runtime needs a minimum alignment of a void *.
618 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
619 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
620
Mike Stump4e7a1f72009-02-21 20:00:35 +0000621 Size = BlockOffset;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000622 Align = BlockAlign;
623 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000624
Anders Carlssond5cab542009-02-12 17:55:02 +0000625 return Fn;
626}
Mike Stumpa99038c2009-02-28 09:07:16 +0000627
628uint64_t CodeGenFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
629 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
630
631 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
632 uint64_t Align = getContext().getDeclAlignInBytes(D);
633
634 if (BDRE->isByRef()) {
635 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
636 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
637 }
638
639 assert ((Align > 0) && "alignment must be 1 byte or more");
640
641 uint64_t OldOffset = BlockOffset;
642
643 // Ensure proper alignment, even if it means we have to have a gap
644 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
645 BlockAlign = std::max(Align, BlockAlign);
646
647 uint64_t Pad = BlockOffset - OldOffset;
648 if (Pad) {
649 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
650 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
651 llvm::APInt(32, Pad),
652 ArrayType::Normal, 0);
653 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
654 0, QualType(PadTy), VarDecl::None,
655 SourceLocation());
656 Expr *E;
657 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
658 SourceLocation(), false, false);
659 BlockDeclRefDecls.push_back(E);
660 }
661 BlockDeclRefDecls.push_back(BDRE);
662
663 BlockOffset += Size;
664 return BlockOffset-Size;
665}
Mike Stumpdab514f2009-03-04 03:23:46 +0000666
667llvm::Value *CodeGenFunction::BuildCopyHelper(int flag) {
668 const llvm::PointerType *PtrToInt8Ty
669 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
670 // FIXME: implement
671 llvm::Value *V = llvm::ConstantInt::get(llvm::Type::Int32Ty, 43);
672 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "tmp");
673 V = Builder.CreateBitCast(V, PtrToInt8Ty, "tmp");
674 return V;
675}
676
677llvm::Value *CodeGenFunction::BuildDestroyHelper(int flag) {
678 const llvm::PointerType *PtrToInt8Ty
679 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
680 // FIXME: implement
681 llvm::Value *V = llvm::ConstantInt::get(llvm::Type::Int32Ty, 44);
682 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "tmp");
683 V = Builder.CreateBitCast(V, PtrToInt8Ty, "tmp");
684 return V;
685}