blob: dcae95f3de19546022eeed86c2c208411ab407e0 [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
Mike Stumpb1a6e682009-09-30 02:43:10 +000014#include "CGDebugInfo.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000015#include "CodeGenFunction.h"
Fariborz Jahanian263c4de2010-02-10 23:34:57 +000016#include "CGObjCRuntime.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "CodeGenModule.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000018#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000019#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000020#include "llvm/ADT/SmallSet.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000021#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000022#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000023
Anders Carlssonacfde802009-02-12 00:39:25 +000024using namespace clang;
25using namespace CodeGen;
26
John McCallee504292010-05-21 04:11:14 +000027/// CGBlockInfo - Information to generate a block literal.
28class clang::CodeGen::CGBlockInfo {
29public:
30 /// Name - The name of the block, kindof.
31 const char *Name;
32
33 /// DeclRefs - Variables from parent scopes that have been
34 /// imported into this block.
35 llvm::SmallVector<const BlockDeclRefExpr *, 8> DeclRefs;
36
37 /// InnerBlocks - This block and the blocks it encloses.
38 llvm::SmallPtrSet<const DeclContext *, 4> InnerBlocks;
39
40 /// CXXThisRef - Non-null if 'this' was required somewhere, in
41 /// which case this is that expression.
42 const CXXThisExpr *CXXThisRef;
43
44 /// NeedsObjCSelf - True if something in this block has an implicit
45 /// reference to 'self'.
46 bool NeedsObjCSelf;
47
48 /// These are initialized by GenerateBlockFunction.
49 bool BlockHasCopyDispose;
50 CharUnits BlockSize;
51 CharUnits BlockAlign;
52 llvm::SmallVector<const Expr*, 8> BlockLayout;
53
54 CGBlockInfo(const char *Name);
55};
56
57CGBlockInfo::CGBlockInfo(const char *N)
58 : Name(N), CXXThisRef(0), NeedsObjCSelf(false) {
59
60 // Skip asm prefix, if any.
61 if (Name && Name[0] == '\01')
62 ++Name;
63}
64
65
Mike Stumpcf62d392009-03-06 18:42:23 +000066llvm::Constant *CodeGenFunction::
Blaine Garst2a7eb282010-02-23 21:51:17 +000067BuildDescriptorBlockDecl(const BlockExpr *BE, bool BlockHasCopyDispose, CharUnits Size,
Mike Stumpa803b0e2009-03-25 17:58:24 +000068 const llvm::StructType* Ty,
Mike Stump08920992009-03-07 02:35:30 +000069 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump56129b12009-02-13 16:55:51 +000070 const llvm::Type *UnsignedLongTy
71 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpe5fee252009-02-13 16:19:19 +000072 llvm::Constant *C;
73 std::vector<llvm::Constant*> Elts;
74
75 // reserved
Owen Anderson4a28d5d2009-07-24 23:12:58 +000076 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000077 Elts.push_back(C);
78
79 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000080 // FIXME: What is the right way to say this doesn't fit? We should give
81 // a user diagnostic in that case. Better fix would be to change the
82 // API to size_t.
Ken Dyck199c3d62010-01-11 17:06:35 +000083 C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
Mike Stumpe5fee252009-02-13 16:19:19 +000084 Elts.push_back(C);
85
Blaine Garst2a7eb282010-02-23 21:51:17 +000086 // optional copy/dispose helpers
Mike Stumpe5fee252009-02-13 16:19:19 +000087 if (BlockHasCopyDispose) {
88 // copy_func_helper_decl
Mike Stumpb7477cf2009-04-10 18:52:28 +000089 Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000090
91 // destroy_func_decl
Mike Stumpb7477cf2009-04-10 18:52:28 +000092 Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000093 }
94
Blaine Garst2a7eb282010-02-23 21:51:17 +000095 // Signature. non-optional ObjC-style method descriptor @encode sequence
96 std::string BlockTypeEncoding;
97 CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
98
99 Elts.push_back(llvm::ConstantExpr::getBitCast(
100 CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty));
101
102 // Layout.
103 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
104 Elts.push_back(C);
105
Nick Lewycky0d36dd22009-09-19 20:00:52 +0000106 C = llvm::ConstantStruct::get(VMContext, Elts, false);
Mike Stumpe5fee252009-02-13 16:19:19 +0000107
Owen Anderson1c431b32009-07-08 19:05:04 +0000108 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
Mike Stumpe5fee252009-02-13 16:19:19 +0000109 llvm::GlobalValue::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000110 C, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000111 return C;
112}
113
Mike Stump2a998142009-03-04 18:17:45 +0000114llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Chris Lattnere2f79b62009-05-13 02:50:56 +0000115 if (NSConcreteGlobalBlock == 0)
Mike Stump1eb44332009-09-09 15:08:12 +0000116 NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
Chris Lattnere2f79b62009-05-13 02:50:56 +0000117 "_NSConcreteGlobalBlock");
Mike Stumpf99f1d02009-02-13 17:23:42 +0000118 return NSConcreteGlobalBlock;
119}
120
Mike Stump2a998142009-03-04 18:17:45 +0000121llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Chris Lattnere2f79b62009-05-13 02:50:56 +0000122 if (NSConcreteStackBlock == 0)
Mike Stump1eb44332009-09-09 15:08:12 +0000123 NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
Chris Lattnere2f79b62009-05-13 02:50:56 +0000124 "_NSConcreteStackBlock");
Mike Stump59c5b112009-02-13 19:29:27 +0000125 return NSConcreteStackBlock;
126}
127
John McCallee504292010-05-21 04:11:14 +0000128static void CollectBlockDeclRefInfo(const Stmt *S, CGBlockInfo &Info) {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000129 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
130 I != E; ++I)
Daniel Dunbar82573ee2009-03-02 07:00:57 +0000131 if (*I)
John McCallee504292010-05-21 04:11:14 +0000132 CollectBlockDeclRefInfo(*I, Info);
Mike Stump00470a12009-03-05 08:32:30 +0000133
Mike Stumpea26cb52009-10-21 03:49:08 +0000134 // We want to ensure we walk down into block literals so we can find
135 // all nested BlockDeclRefExprs.
Mike Stump38e16272009-10-21 22:01:24 +0000136 if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallee504292010-05-21 04:11:14 +0000137 Info.InnerBlocks.insert(BE->getBlockDecl());
138 CollectBlockDeclRefInfo(BE->getBody(), Info);
Mike Stump38e16272009-10-21 22:01:24 +0000139 }
Mike Stumpea26cb52009-10-21 03:49:08 +0000140
John McCallee504292010-05-21 04:11:14 +0000141 else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
142 const ValueDecl *D = BDRE->getDecl();
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000143 // FIXME: Handle enums.
John McCallee504292010-05-21 04:11:14 +0000144 if (isa<FunctionDecl>(D))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000145 return;
Mike Stump00470a12009-03-05 08:32:30 +0000146
John McCallee504292010-05-21 04:11:14 +0000147 if (isa<ImplicitParamDecl>(D) &&
148 isa<ObjCMethodDecl>(D->getDeclContext()) &&
149 cast<ObjCMethodDecl>(D->getDeclContext())->getSelfDecl() == D) {
150 Info.NeedsObjCSelf = true;
151 return;
152 }
153
Mike Stump38e16272009-10-21 22:01:24 +0000154 // Only Decls that escape are added.
John McCallee504292010-05-21 04:11:14 +0000155 if (!Info.InnerBlocks.count(D->getDeclContext()))
Mike Stump38e16272009-10-21 22:01:24 +0000156 Info.DeclRefs.push_back(BDRE);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000157 }
John McCallea1471e2010-05-20 01:18:31 +0000158
John McCallee504292010-05-21 04:11:14 +0000159 // Make sure to capture implicit 'self' references due to super calls.
Chandler Carruthf54b80f2010-05-21 10:29:28 +0000160 else if (const ObjCMessageExpr *E = dyn_cast<ObjCMessageExpr>(S)) {
John McCallee504292010-05-21 04:11:14 +0000161 if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
162 E->getReceiverKind() == ObjCMessageExpr::SuperInstance)
163 Info.NeedsObjCSelf = true;
Chandler Carruthf54b80f2010-05-21 10:29:28 +0000164 }
John McCallee504292010-05-21 04:11:14 +0000165
166 // Getter/setter uses may also cause implicit super references,
167 // which we can check for with:
168 else if (isa<ObjCSuperExpr>(S))
169 Info.NeedsObjCSelf = true;
170
171 else if (isa<CXXThisExpr>(S))
John McCallea1471e2010-05-20 01:18:31 +0000172 Info.CXXThisRef = cast<CXXThisExpr>(S);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000173}
174
John McCallee504292010-05-21 04:11:14 +0000175/// CanBlockBeGlobal - Given a CGBlockInfo struct, determines if a block can be
Mike Stump58a85142009-03-04 22:48:06 +0000176/// declared as a global variable instead of on the stack.
John McCallee504292010-05-21 04:11:14 +0000177static bool CanBlockBeGlobal(const CGBlockInfo &Info) {
Mike Stumpea26cb52009-10-21 03:49:08 +0000178 return Info.DeclRefs.empty();
179}
180
181/// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
182/// ensure we can generate the debug information for the parameter for the block
183/// invoke function.
John McCallee504292010-05-21 04:11:14 +0000184static void AllocateAllBlockDeclRefs(CodeGenFunction &CGF, CGBlockInfo &Info) {
John McCallea1471e2010-05-20 01:18:31 +0000185 if (Info.CXXThisRef)
John McCallee504292010-05-21 04:11:14 +0000186 CGF.AllocateBlockCXXThisPointer(Info.CXXThisRef);
Mike Stumpea26cb52009-10-21 03:49:08 +0000187
188 for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
John McCallee504292010-05-21 04:11:14 +0000189 CGF.AllocateBlockDecl(Info.DeclRefs[i]);
190
191 if (Info.NeedsObjCSelf) {
192 ValueDecl *Self = cast<ObjCMethodDecl>(CGF.CurFuncDecl)->getSelfDecl();
193 BlockDeclRefExpr *BDRE =
194 new (CGF.getContext()) BlockDeclRefExpr(Self, Self->getType(),
195 SourceLocation(), false);
196 Info.DeclRefs.push_back(BDRE);
197 CGF.AllocateBlockDecl(BDRE);
198 }
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000199}
200
Mike Stump58a85142009-03-04 22:48:06 +0000201// FIXME: Push most into CGM, passing down a few bits, like current function
202// name.
Mike Stump8a2b4b12009-02-25 23:33:13 +0000203llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000204 std::string Name = CurFn->getName();
John McCallee504292010-05-21 04:11:14 +0000205 CGBlockInfo Info(Name.c_str());
206 Info.InnerBlocks.insert(BE->getBlockDecl());
207 CollectBlockDeclRefInfo(BE->getBody(), Info);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000208
209 // Check if the block can be global.
Mike Stump58a85142009-03-04 22:48:06 +0000210 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
211 // to just have one code path. We should move this function into CGM and pass
212 // CGF, then we can just check to see if CGF is 0.
Mike Stumpdab514f2009-03-04 03:23:46 +0000213 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000214 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump00470a12009-03-05 08:32:30 +0000215
David Chisnall5e530af2009-11-17 19:33:30 +0000216 size_t BlockFields = 5;
217
David Chisnall5e530af2009-11-17 19:33:30 +0000218 std::vector<llvm::Constant*> Elts(BlockFields);
219
Mike Stumpe5fee252009-02-13 16:19:19 +0000220 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000221 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000222
Mike Stumpe5fee252009-02-13 16:19:19 +0000223 {
224 // C = BuildBlockStructInitlist();
Blaine Garsta36e2232010-03-05 01:29:59 +0000225 unsigned int flags = BLOCK_HAS_SIGNATURE;
David Chisnall5e530af2009-11-17 19:33:30 +0000226
Mike Stump00470a12009-03-05 08:32:30 +0000227 // We run this first so that we set BlockHasCopyDispose from the entire
228 // block literal.
229 // __invoke
Mike Stump00470a12009-03-05 08:32:30 +0000230 llvm::Function *Fn
Mike Stumpbb304192009-09-24 22:31:14 +0000231 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
John McCallee504292010-05-21 04:11:14 +0000232 LocalDeclMap);
233 BlockHasCopyDispose |= Info.BlockHasCopyDispose;
Mike Stump00470a12009-03-05 08:32:30 +0000234 Elts[3] = Fn;
235
Mike Stumpf5408fe2009-05-16 07:57:57 +0000236 // FIXME: Don't use BlockHasCopyDispose, it is set more often then
237 // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
John McCallee504292010-05-21 04:11:14 +0000238 if (Info.BlockHasCopyDispose)
Mike Stumpe5fee252009-02-13 16:19:19 +0000239 flags |= BLOCK_HAS_COPY_DISPOSE;
240
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000241 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000242 C = CGM.getNSConcreteStackBlock();
Owen Anderson3c4972d2009-07-29 18:54:39 +0000243 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump00470a12009-03-05 08:32:30 +0000244 Elts[0] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000245
246 // __flags
Blaine Garsta36e2232010-03-05 01:29:59 +0000247 {
248 QualType BPT = BE->getType();
249 const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
250 QualType ResultType = ftype->getResultType();
251
252 CallArgList Args;
253 CodeGenTypes &Types = CGM.getTypes();
254 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000255 FunctionType::ExtInfo());
Blaine Garsta36e2232010-03-05 01:29:59 +0000256 if (CGM.ReturnTypeUsesSret(FnInfo))
257 flags |= BLOCK_USE_STRET;
258 }
Mike Stumpe5fee252009-02-13 16:19:19 +0000259 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
260 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000261 C = llvm::ConstantInt::get(IntTy, flags);
Mike Stump00470a12009-03-05 08:32:30 +0000262 Elts[1] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000263
264 // __reserved
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000265 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump00470a12009-03-05 08:32:30 +0000266 Elts[2] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000267
John McCallee504292010-05-21 04:11:14 +0000268 if (Info.BlockLayout.empty()) {
Mike Stumpcf62d392009-03-06 18:42:23 +0000269 // __descriptor
John McCallee504292010-05-21 04:11:14 +0000270 Elts[4] = BuildDescriptorBlockDecl(BE, Info.BlockHasCopyDispose,
271 Info.BlockSize, 0, 0);
Mike Stumpcf62d392009-03-06 18:42:23 +0000272
Mike Stump5570cfe2009-03-01 20:07:53 +0000273 // Optimize to being a global block.
274 Elts[0] = CGM.getNSConcreteGlobalBlock();
Blaine Garsta36e2232010-03-05 01:29:59 +0000275
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000276 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
Mike Stump5570cfe2009-03-01 20:07:53 +0000277
Nick Lewycky0d36dd22009-09-19 20:00:52 +0000278 C = llvm::ConstantStruct::get(VMContext, Elts, false);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000279
Owen Anderson1c431b32009-07-08 19:05:04 +0000280 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +0000281 llvm::GlobalValue::InternalLinkage, C,
282 "__block_holder_tmp_" +
283 llvm::Twine(CGM.getGlobalUniqueCount()));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000284 QualType BPT = BE->getType();
Owen Anderson3c4972d2009-07-29 18:54:39 +0000285 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000286 return C;
287 }
Mike Stump00470a12009-03-05 08:32:30 +0000288
John McCallee504292010-05-21 04:11:14 +0000289 std::vector<const llvm::Type *> Types(BlockFields+Info.BlockLayout.size());
Mike Stump08920992009-03-07 02:35:30 +0000290 for (int i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000291 Types[i] = Elts[i]->getType();
Mike Stump08920992009-03-07 02:35:30 +0000292 Types[4] = PtrToInt8Ty;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000293
John McCallee504292010-05-21 04:11:14 +0000294 for (unsigned i = 0, n = Info.BlockLayout.size(); i != n; ++i) {
295 const Expr *E = Info.BlockLayout[i];
Mike Stumpa99038c2009-02-28 09:07:16 +0000296 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
297 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000298 if (BDRE && BDRE->isByRef()) {
David Chisnall5e530af2009-11-17 19:33:30 +0000299 Types[i+BlockFields] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000300 } else
David Chisnall5e530af2009-11-17 19:33:30 +0000301 Types[i+BlockFields] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000302 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000303
Owen Anderson47a434f2009-08-05 23:18:46 +0000304 llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000305
306 llvm::AllocaInst *A = CreateTempAlloca(Ty);
John McCallee504292010-05-21 04:11:14 +0000307 A->setAlignment(Info.BlockAlign.getQuantity());
Mike Stump8a2b4b12009-02-25 23:33:13 +0000308 V = A;
309
John McCallea1471e2010-05-20 01:18:31 +0000310 // Build layout / cleanup information for all the data entries in the
311 // layout, and write the enclosing fields into the type.
John McCallee504292010-05-21 04:11:14 +0000312 std::vector<HelperInfo> NoteForHelper(Info.BlockLayout.size());
John McCallea1471e2010-05-20 01:18:31 +0000313 unsigned NumHelpers = 0;
Mike Stump08920992009-03-07 02:35:30 +0000314
315 for (unsigned i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000316 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump00470a12009-03-05 08:32:30 +0000317
John McCallee504292010-05-21 04:11:14 +0000318 for (unsigned i=0; i < Info.BlockLayout.size(); ++i) {
319 const Expr *E = Info.BlockLayout[i];
Mike Stump8a2b4b12009-02-25 23:33:13 +0000320
John McCallea1471e2010-05-20 01:18:31 +0000321 // Skip padding.
322 if (isa<DeclRefExpr>(E)) continue;
Mike Stumpa99038c2009-02-28 09:07:16 +0000323
John McCallea1471e2010-05-20 01:18:31 +0000324 llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
325 HelperInfo &Note = NoteForHelper[NumHelpers++];
Mike Stumpa99038c2009-02-28 09:07:16 +0000326
John McCallea1471e2010-05-20 01:18:31 +0000327 Note.index = i+5;
Mike Stump08920992009-03-07 02:35:30 +0000328
John McCallea1471e2010-05-20 01:18:31 +0000329 if (isa<CXXThisExpr>(E)) {
330 Note.RequiresCopying = false;
331 Note.flag = BLOCK_FIELD_IS_OBJECT;
Mike Stumpa99038c2009-02-28 09:07:16 +0000332
John McCallea1471e2010-05-20 01:18:31 +0000333 Builder.CreateStore(LoadCXXThis(), Addr);
334 continue;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000335 }
John McCallea1471e2010-05-20 01:18:31 +0000336
337 const BlockDeclRefExpr *BDRE = cast<BlockDeclRefExpr>(E);
338 const ValueDecl *VD = BDRE->getDecl();
339 QualType T = VD->getType();
340
341 Note.RequiresCopying = BlockRequiresCopying(T);
342
343 if (BDRE->isByRef()) {
344 Note.flag = BLOCK_FIELD_IS_BYREF;
345 if (T.isObjCGCWeak())
346 Note.flag |= BLOCK_FIELD_IS_WEAK;
347 } else if (T->isBlockPointerType()) {
348 Note.flag = BLOCK_FIELD_IS_BLOCK;
349 } else {
350 Note.flag = BLOCK_FIELD_IS_OBJECT;
351 }
352
353 if (LocalDeclMap[VD]) {
354 if (BDRE->isByRef()) {
355 llvm::Value *Loc = LocalDeclMap[VD];
356 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
357 Loc = Builder.CreateLoad(Loc);
358 Builder.CreateStore(Loc, Addr);
359 continue;
360 } else {
361 E = new (getContext()) DeclRefExpr(const_cast<ValueDecl*>(VD),
362 VD->getType(),
363 SourceLocation());
364 }
365 }
366
367 if (BDRE->isByRef()) {
368 E = new (getContext())
369 UnaryOperator(const_cast<Expr*>(E), UnaryOperator::AddrOf,
370 getContext().getPointerType(E->getType()),
371 SourceLocation());
372 }
373
374 RValue r = EmitAnyExpr(E, Addr, false);
375 if (r.isScalar()) {
376 llvm::Value *Loc = r.getScalarVal();
377 const llvm::Type *Ty = Types[i+BlockFields];
378 if (BDRE->isByRef()) {
379 // E is now the address of the value field, instead, we want the
380 // address of the actual ByRef struct. We optimize this slightly
381 // compared to gcc by not grabbing the forwarding slot as this must
382 // be done during Block_copy for us, and we can postpone the work
383 // until then.
384 CharUnits offset = BlockDecls[BDRE->getDecl()];
385
386 llvm::Value *BlockLiteral = LoadBlockStruct();
387
388 Loc = Builder.CreateGEP(BlockLiteral,
389 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
390 offset.getQuantity()),
391 "block.literal");
392 Ty = llvm::PointerType::get(Ty, 0);
393 Loc = Builder.CreateBitCast(Loc, Ty);
394 Loc = Builder.CreateLoad(Loc);
395 // Loc = Builder.CreateBitCast(Loc, Ty);
396 }
397 Builder.CreateStore(Loc, Addr);
398 } else if (r.isComplex())
399 // FIXME: implement
400 ErrorUnsupported(BE, "complex in block literal");
401 else if (r.isAggregate())
402 ; // Already created into the destination
403 else
404 assert (0 && "bad block variable");
405 // FIXME: Ensure that the offset created by the backend for
406 // the struct matches the previously computed offset in BlockDecls.
407 }
408 NoteForHelper.resize(NumHelpers);
Mike Stumpcf62d392009-03-06 18:42:23 +0000409
410 // __descriptor
Blaine Garst2a7eb282010-02-23 21:51:17 +0000411 llvm::Value *Descriptor = BuildDescriptorBlockDecl(BE,
John McCallee504292010-05-21 04:11:14 +0000412 Info.BlockHasCopyDispose,
413 Info.BlockSize, Ty,
Mike Stump08920992009-03-07 02:35:30 +0000414 &NoteForHelper);
415 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
416 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
Mike Stumpe5fee252009-02-13 16:19:19 +0000417 }
Mike Stump00470a12009-03-05 08:32:30 +0000418
Mike Stumpbd65cac2009-02-19 01:01:04 +0000419 QualType BPT = BE->getType();
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000420 V = Builder.CreateBitCast(V, ConvertType(BPT));
421 // See if this is a __weak block variable and the must call objc_read_weak
422 // on it.
423 const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
424 QualType RES = ftype->getResultType();
425 if (RES.isObjCGCWeak()) {
426 // Must cast argument to id*
427 const llvm::Type *ObjectPtrTy =
428 ConvertType(CGM.getContext().getObjCIdType());
429 const llvm::Type *PtrObjectPtrTy =
430 llvm::PointerType::getUnqual(ObjectPtrTy);
431 V = Builder.CreateBitCast(V, PtrObjectPtrTy);
432 V = CGM.getObjCRuntime().EmitObjCWeakRead(*this, V);
433 }
434 return V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000435}
436
437
Mike Stump2a998142009-03-04 18:17:45 +0000438const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000439 if (BlockDescriptorType)
440 return BlockDescriptorType;
441
Mike Stumpa5448542009-02-13 15:32:32 +0000442 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000443 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000444
Mike Stumpab695142009-02-13 15:16:56 +0000445 // struct __block_descriptor {
446 // unsigned long reserved;
447 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000448 //
449 // // later, the following will be added
450 //
451 // struct {
452 // void (*copyHelper)();
453 // void (*copyHelper)();
454 // } helpers; // !!! optional
455 //
456 // const char *signature; // the block signature
457 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000458 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000459 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
460 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000461 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000462 NULL);
463
464 getModule().addTypeName("struct.__block_descriptor",
465 BlockDescriptorType);
466
467 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000468}
469
Mike Stump2a998142009-03-04 18:17:45 +0000470const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000471 if (GenericBlockLiteralType)
472 return GenericBlockLiteralType;
473
Mike Stumpa5448542009-02-13 15:32:32 +0000474 const llvm::Type *BlockDescPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000475 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpa5448542009-02-13 15:32:32 +0000476
Mike Stump7cbb3602009-02-13 16:01:35 +0000477 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
478 getTypes().ConvertType(getContext().IntTy));
479
Mike Stump9b8a7972009-02-13 15:25:34 +0000480 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000481 // void *__isa;
482 // int __flags;
483 // int __reserved;
484 // void (*__invoke)(void *);
485 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000486 // };
Blaine Garst2a7eb282010-02-23 21:51:17 +0000487 GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
Owen Anderson47a434f2009-08-05 23:18:46 +0000488 PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000489 IntTy,
490 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000491 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000492 BlockDescPtrTy,
493 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000494
Mike Stump9b8a7972009-02-13 15:25:34 +0000495 getModule().addTypeName("struct.__block_literal_generic",
496 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000497
Mike Stump9b8a7972009-02-13 15:25:34 +0000498 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000499}
500
Mike Stumpbd65cac2009-02-19 01:01:04 +0000501
Anders Carlssona1736c02009-12-24 21:13:40 +0000502RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
503 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000504 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000505 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000506
Anders Carlssonacfde802009-02-12 00:39:25 +0000507 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
508
509 // Get a pointer to the generic block literal.
510 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000511 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000512
513 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000514 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000515 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
516
517 // Get the function pointer from the literal.
518 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000519
Mike Stumpa5448542009-02-13 15:32:32 +0000520 BlockLiteral =
521 Builder.CreateBitCast(BlockLiteral,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000522 llvm::Type::getInt8PtrTy(VMContext),
Anders Carlssonacfde802009-02-12 00:39:25 +0000523 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000524
Anders Carlssonacfde802009-02-12 00:39:25 +0000525 // Add the block literal.
526 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
527 CallArgList Args;
528 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000529
Anders Carlsson782f3972009-04-08 23:13:16 +0000530 QualType FnType = BPT->getPointeeType();
531
Anders Carlssonacfde802009-02-12 00:39:25 +0000532 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000533 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000534 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000535
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000536 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000537 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000538
John McCall04a67a62010-02-05 21:31:56 +0000539 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
540 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000541
Mike Stump1eb44332009-09-09 15:08:12 +0000542 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000543 CGM.getTypes().getFunctionInfo(ResultType, Args,
544 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000546 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000547 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000548 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Owen Anderson96e0fc72009-07-29 22:16:19 +0000550 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000551 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Anders Carlssonacfde802009-02-12 00:39:25 +0000553 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000554 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000555}
Anders Carlssond5cab542009-02-12 17:55:02 +0000556
John McCallea1471e2010-05-20 01:18:31 +0000557void CodeGenFunction::AllocateBlockCXXThisPointer(const CXXThisExpr *E) {
558 assert(BlockCXXThisOffset.isZero() && "already computed 'this' pointer");
559
560 // Figure out what the offset is.
561 QualType T = E->getType();
562 std::pair<CharUnits,CharUnits> TypeInfo = getContext().getTypeInfoInChars(T);
563 CharUnits Offset = getBlockOffset(TypeInfo.first, TypeInfo.second);
564
565 BlockCXXThisOffset = Offset;
566 BlockLayout.push_back(E);
567}
568
569void CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000570 const ValueDecl *VD = E->getDecl();
John McCallea1471e2010-05-20 01:18:31 +0000571 CharUnits &Offset = BlockDecls[VD];
Mike Stumpdab514f2009-03-04 03:23:46 +0000572
Mike Stumpdab514f2009-03-04 03:23:46 +0000573 // See if we have already allocated an offset for this variable.
John McCallea1471e2010-05-20 01:18:31 +0000574 if (!Offset.isZero())
575 return;
Mike Stumpea26cb52009-10-21 03:49:08 +0000576
577 // Don't run the expensive check, unless we have to.
Mike Stump083c25e2009-10-22 00:49:09 +0000578 if (!BlockHasCopyDispose)
579 if (E->isByRef()
580 || BlockRequiresCopying(E->getType()))
581 BlockHasCopyDispose = true;
Mike Stumpea26cb52009-10-21 03:49:08 +0000582
John McCallea1471e2010-05-20 01:18:31 +0000583 const ValueDecl *D = cast<ValueDecl>(E->getDecl());
Mike Stumpea26cb52009-10-21 03:49:08 +0000584
John McCallea1471e2010-05-20 01:18:31 +0000585 CharUnits Size;
586 CharUnits Align;
587
588 if (E->isByRef()) {
589 llvm::tie(Size,Align) =
590 getContext().getTypeInfoInChars(getContext().VoidPtrTy);
591 } else {
592 Size = getContext().getTypeSizeInChars(D->getType());
593 Align = getContext().getDeclAlign(D);
594 }
595
596 Offset = getBlockOffset(Size, Align);
597 BlockLayout.push_back(E);
Mike Stumpea26cb52009-10-21 03:49:08 +0000598}
599
John McCallee504292010-05-21 04:11:14 +0000600llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const ValueDecl *VD,
601 bool IsByRef) {
John McCallea1471e2010-05-20 01:18:31 +0000602 CharUnits offset = BlockDecls[VD];
603 assert(!offset.isZero() && "getting address of unallocated decl");
Mike Stumpdab514f2009-03-04 03:23:46 +0000604
605 llvm::Value *BlockLiteral = LoadBlockStruct();
606 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
Mike Stumpea26cb52009-10-21 03:49:08 +0000607 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Ken Dyck199c3d62010-01-11 17:06:35 +0000608 offset.getQuantity()),
Mike Stump58a85142009-03-04 22:48:06 +0000609 "block.literal");
John McCallee504292010-05-21 04:11:14 +0000610 if (IsByRef) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000611 const llvm::Type *PtrStructTy
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000612 = llvm::PointerType::get(BuildByRefType(VD), 0);
Mike Stumpa8b60c92009-03-21 21:00:35 +0000613 // The block literal will need a copy/destroy helper.
614 BlockHasCopyDispose = true;
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000615
616 const llvm::Type *Ty = PtrStructTy;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000617 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000618 V = Builder.CreateBitCast(V, Ty);
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000619 V = Builder.CreateLoad(V);
Mike Stumpdab514f2009-03-04 03:23:46 +0000620 V = Builder.CreateStructGEP(V, 1, "forwarding");
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000621 V = Builder.CreateLoad(V);
Mike Stumpdab514f2009-03-04 03:23:46 +0000622 V = Builder.CreateBitCast(V, PtrStructTy);
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000623 V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
624 VD->getNameAsString());
Fariborz Jahaniand33ded52010-05-04 17:59:32 +0000625 if (VD->getType()->isReferenceType())
626 V = Builder.CreateLoad(V);
Mike Stumpdab514f2009-03-04 03:23:46 +0000627 } else {
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000628 const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
629
Owen Anderson96e0fc72009-07-29 22:16:19 +0000630 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000631 V = Builder.CreateBitCast(V, Ty);
632 }
633 return V;
634}
635
Mike Stump67a64482009-02-14 22:16:35 +0000636llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000637BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000638 // Generate the block descriptor.
639 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000640 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
641 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000642
Blaine Garst2a7eb282010-02-23 21:51:17 +0000643 llvm::Constant *DescriptorFields[4];
Mike Stumpa5448542009-02-13 15:32:32 +0000644
Anders Carlssond5cab542009-02-12 17:55:02 +0000645 // Reserved
Owen Andersonc9c88b42009-07-31 20:28:54 +0000646 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000647
Anders Carlssond5cab542009-02-12 17:55:02 +0000648 // Block literal size. For global blocks we just use the size of the generic
649 // block literal struct.
Ken Dyck687cc4a2010-01-26 13:48:07 +0000650 CharUnits BlockLiteralSize =
651 CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
Owen Andersona1cf15f2009-07-14 23:10:40 +0000652 DescriptorFields[1] =
Ken Dyck199c3d62010-01-11 17:06:35 +0000653 llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
Blaine Garst2a7eb282010-02-23 21:51:17 +0000654
655 // signature. non-optional ObjC-style method descriptor @encode sequence
656 std::string BlockTypeEncoding;
657 CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
Mike Stumpa5448542009-02-13 15:32:32 +0000658
Blaine Garst2a7eb282010-02-23 21:51:17 +0000659 DescriptorFields[2] = llvm::ConstantExpr::getBitCast(
660 CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
661
662 // layout
663 DescriptorFields[3] =
664 llvm::ConstantInt::get(UnsignedLongTy,0);
665
666 // build the structure from the 4 elements
Mike Stumpa5448542009-02-13 15:32:32 +0000667 llvm::Constant *DescriptorStruct =
Blaine Garst2a7eb282010-02-23 21:51:17 +0000668 llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false);
Mike Stumpa5448542009-02-13 15:32:32 +0000669
Anders Carlssond5cab542009-02-12 17:55:02 +0000670 llvm::GlobalVariable *Descriptor =
Owen Anderson1c431b32009-07-08 19:05:04 +0000671 new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000672 llvm::GlobalVariable::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000673 DescriptorStruct, "__block_descriptor_global");
Mike Stumpa5448542009-02-13 15:32:32 +0000674
David Chisnall5e530af2009-11-17 19:33:30 +0000675 int FieldCount = 5;
Anders Carlssond5cab542009-02-12 17:55:02 +0000676 // Generate the constants for the block literal.
David Chisnall5e530af2009-11-17 19:33:30 +0000677
678 std::vector<llvm::Constant*> LiteralFields(FieldCount);
Mike Stumpa5448542009-02-13 15:32:32 +0000679
John McCallee504292010-05-21 04:11:14 +0000680 CGBlockInfo Info(n);
Mike Stump7f28a9c2009-03-13 23:34:28 +0000681 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000682 llvm::Function *Fn
John McCallee504292010-05-21 04:11:14 +0000683 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap);
684 assert(Info.BlockSize == BlockLiteralSize
Mike Stump4e7a1f72009-02-21 20:00:35 +0000685 && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000686
Anders Carlssond5cab542009-02-12 17:55:02 +0000687 // isa
Mike Stumpf99f1d02009-02-13 17:23:42 +0000688 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000689
Anders Carlssond5cab542009-02-12 17:55:02 +0000690 // Flags
Blaine Garst2a7eb282010-02-23 21:51:17 +0000691 LiteralFields[1] =
Blaine Garsta36e2232010-03-05 01:29:59 +0000692 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
Mike Stumpa5448542009-02-13 15:32:32 +0000693
Anders Carlssond5cab542009-02-12 17:55:02 +0000694 // Reserved
Owen Andersonc9c88b42009-07-31 20:28:54 +0000695 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000696
Anders Carlssond5cab542009-02-12 17:55:02 +0000697 // Function
698 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000699
Anders Carlssond5cab542009-02-12 17:55:02 +0000700 // Descriptor
701 LiteralFields[4] = Descriptor;
David Chisnall5e530af2009-11-17 19:33:30 +0000702
Mike Stumpa5448542009-02-13 15:32:32 +0000703 llvm::Constant *BlockLiteralStruct =
David Chisnall5e530af2009-11-17 19:33:30 +0000704 llvm::ConstantStruct::get(VMContext, LiteralFields, false);
Mike Stumpa5448542009-02-13 15:32:32 +0000705
706 llvm::GlobalVariable *BlockLiteral =
Owen Anderson1c431b32009-07-08 19:05:04 +0000707 new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000708 llvm::GlobalVariable::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000709 BlockLiteralStruct, "__block_literal_global");
Mike Stumpa5448542009-02-13 15:32:32 +0000710
Anders Carlssond5cab542009-02-12 17:55:02 +0000711 return BlockLiteral;
712}
713
Mike Stump4e7a1f72009-02-21 20:00:35 +0000714llvm::Value *CodeGenFunction::LoadBlockStruct() {
Mike Stumpbf1914b2009-10-20 20:30:01 +0000715 llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
716 "self");
717 // For now, we codegen based upon byte offsets.
718 return Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000719}
720
Mike Stump00470a12009-03-05 08:32:30 +0000721llvm::Function *
722CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
John McCallee504292010-05-21 04:11:14 +0000723 CGBlockInfo &Info,
Mike Stump6cc88f72009-03-20 21:53:12 +0000724 const Decl *OuterFuncDecl,
John McCallee504292010-05-21 04:11:14 +0000725 llvm::DenseMap<const Decl*, llvm::Value*> ldm) {
Devang Patel963dfbd2009-04-15 21:51:44 +0000726
727 // Check if we should generate debug info for this block.
728 if (CGM.getDebugInfo())
729 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Mike Stump7f28a9c2009-03-13 23:34:28 +0000731 // Arrange for local static and local extern declarations to appear
732 // to be local to this function as well, as they are directly referenced
733 // in a block.
734 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
735 i != ldm.end();
736 ++i) {
737 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000739 if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
Mike Stump7f28a9c2009-03-13 23:34:28 +0000740 LocalDeclMap[VD] = i->second;
741 }
742
Ken Dyck687cc4a2010-01-26 13:48:07 +0000743 BlockOffset =
744 CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
Ken Dyck30a8a272010-01-26 19:13:33 +0000745 BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
Eli Friedman48f91222009-03-28 03:24:54 +0000746
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000747 const FunctionType *BlockFunctionType = BExpr->getFunctionType();
748 QualType ResultType;
Rafael Espindola264ba482010-03-30 20:24:48 +0000749 FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType);
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000750 bool IsVariadic;
Mike Stump1eb44332009-09-09 15:08:12 +0000751 if (const FunctionProtoType *FTy =
Fariborz Jahanianda0895d2009-04-11 18:54:57 +0000752 dyn_cast<FunctionProtoType>(BlockFunctionType)) {
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000753 ResultType = FTy->getResultType();
754 IsVariadic = FTy->isVariadic();
Mike Stumpb3589f42009-07-30 22:28:39 +0000755 } else {
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000756 // K&R style block.
757 ResultType = BlockFunctionType->getResultType();
758 IsVariadic = false;
759 }
Mike Stumpa5448542009-02-13 15:32:32 +0000760
Anders Carlssond5cab542009-02-12 17:55:02 +0000761 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000762
Mike Stumpea26cb52009-10-21 03:49:08 +0000763 CurFuncDecl = OuterFuncDecl;
764
Chris Lattner161d36d2009-02-28 19:01:03 +0000765 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000766
Mike Stumpea26cb52009-10-21 03:49:08 +0000767 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000768
John McCallea1471e2010-05-20 01:18:31 +0000769 // Build the block struct now.
John McCallee504292010-05-21 04:11:14 +0000770 AllocateAllBlockDeclRefs(*this, Info);
Mike Stumpea26cb52009-10-21 03:49:08 +0000771
Mike Stump083c25e2009-10-22 00:49:09 +0000772 QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +0000773 BlockLayout);
774
Anders Carlssond5cab542009-02-12 17:55:02 +0000775 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000776 ImplicitParamDecl *SelfDecl =
John McCall2888b652010-04-30 21:35:41 +0000777 ImplicitParamDecl::Create(getContext(), const_cast<BlockDecl*>(BD),
Mike Stumpadaaad32009-10-20 02:12:22 +0000778 SourceLocation(), II,
779 ParmTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000780
Anders Carlssond5cab542009-02-12 17:55:02 +0000781 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000782 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000783
Steve Naroffe78b8092009-03-13 16:56:44 +0000784 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000785 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000786 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000787
788 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +0000789 CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo);
Anders Carlssond5cab542009-02-12 17:55:02 +0000790
Anders Carlssond5cab542009-02-12 17:55:02 +0000791 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000792 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
Mike Stumpa5448542009-02-13 15:32:32 +0000793
Douglas Gregor35415f52010-05-25 17:04:15 +0000794 MangleBuffer Name;
795 CGM.getMangledName(Name, BD);
Mike Stumpa5448542009-02-13 15:32:32 +0000796 llvm::Function *Fn =
Douglas Gregor35415f52010-05-25 17:04:15 +0000797 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, Name,
Anders Carlssond5cab542009-02-12 17:55:02 +0000798 &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000799
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000800 CGM.SetInternalFunctionAttributes(BD, Fn, FI);
801
Chris Lattner4863db42009-04-23 07:18:56 +0000802 StartFunction(BD, ResultType, Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000803 BExpr->getBody()->getLocEnd());
Mike Stumpb1a6e682009-09-30 02:43:10 +0000804
Chris Lattner4863db42009-04-23 07:18:56 +0000805 CurFuncDecl = OuterFuncDecl;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000806 CurCodeDecl = BD;
Mike Stumpb289b3f2009-10-01 22:29:41 +0000807
John McCallea1471e2010-05-20 01:18:31 +0000808 // If we have a C++ 'this' reference, go ahead and force it into
809 // existence now.
810 if (Info.CXXThisRef) {
811 assert(!BlockCXXThisOffset.isZero() &&
812 "haven't yet allocated 'this' reference");
813
814 // TODO: I have a dream that one day this will be typed.
815 llvm::Value *BlockLiteral = LoadBlockStruct();
816 llvm::Value *ThisPtrRaw =
817 Builder.CreateConstInBoundsGEP1_64(BlockLiteral,
818 BlockCXXThisOffset.getQuantity(),
819 "this.ptr.raw");
820
821 const llvm::Type *Ty =
822 CGM.getTypes().ConvertType(Info.CXXThisRef->getType());
823 Ty = llvm::PointerType::get(Ty, 0);
824 llvm::Value *ThisPtr = Builder.CreateBitCast(ThisPtrRaw, Ty, "this.ptr");
825
826 CXXThisValue = Builder.CreateLoad(ThisPtr, "this");
827 }
828
John McCallee504292010-05-21 04:11:14 +0000829 // If we have an Objective C 'self' reference, go ahead and force it
830 // into existence now.
831 if (Info.NeedsObjCSelf) {
832 ValueDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
833 LocalDeclMap[Self] = GetAddrOfBlockDecl(Self, false);
834 }
835
Mike Stumpb289b3f2009-10-01 22:29:41 +0000836 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
837 llvm::BasicBlock *entry = Builder.GetInsertBlock();
838 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
839 --entry_ptr;
840
Chris Lattner161d36d2009-02-28 19:01:03 +0000841 EmitStmt(BExpr->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000842
Mike Stumpde8c5c72009-10-01 00:27:30 +0000843 // Remember where we were...
844 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000845
Mike Stumpde8c5c72009-10-01 00:27:30 +0000846 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000847 ++entry_ptr;
848 Builder.SetInsertPoint(entry, entry_ptr);
849
Mike Stumpb1a6e682009-09-30 02:43:10 +0000850 if (CGDebugInfo *DI = getDebugInfo()) {
Mike Stumpb1a6e682009-09-30 02:43:10 +0000851 // Emit debug information for all the BlockDeclRefDecls.
John McCallea1471e2010-05-20 01:18:31 +0000852 // FIXME: also for 'this'
853 for (unsigned i = 0, e = BlockLayout.size(); i != e; ++i) {
854 if (const BlockDeclRefExpr *BDRE =
855 dyn_cast<BlockDeclRefExpr>(BlockLayout[i])) {
Mike Stumpb1a6e682009-09-30 02:43:10 +0000856 const ValueDecl *D = BDRE->getDecl();
857 DI->setLocation(D->getLocation());
858 DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
859 LocalDeclMap[getBlockStructDecl()],
860 Builder, this);
861 }
862 }
Mike Stumpb1a6e682009-09-30 02:43:10 +0000863 }
Mike Stumpde8c5c72009-10-01 00:27:30 +0000864 // And resume where we left off.
865 if (resume == 0)
866 Builder.ClearInsertionPoint();
867 else
868 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +0000869
Chris Lattner161d36d2009-02-28 19:01:03 +0000870 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000871
Mike Stump8a2b4b12009-02-25 23:33:13 +0000872 // The runtime needs a minimum alignment of a void *.
Ken Dyck30a8a272010-01-26 19:13:33 +0000873 CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
Ken Dyck199c3d62010-01-11 17:06:35 +0000874 BlockOffset = CharUnits::fromQuantity(
Ken Dyck30a8a272010-01-26 19:13:33 +0000875 llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
876 MinAlign.getQuantity()));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000877
John McCallee504292010-05-21 04:11:14 +0000878 Info.BlockSize = BlockOffset;
879 Info.BlockAlign = BlockAlign;
880 Info.BlockLayout = BlockLayout;
881 Info.BlockHasCopyDispose = BlockHasCopyDispose;
Anders Carlssond5cab542009-02-12 17:55:02 +0000882 return Fn;
883}
Mike Stumpa99038c2009-02-28 09:07:16 +0000884
John McCallea1471e2010-05-20 01:18:31 +0000885CharUnits BlockFunction::getBlockOffset(CharUnits Size, CharUnits Align) {
886 assert((Align.isPositive()) && "alignment must be 1 byte or more");
Mike Stumpa99038c2009-02-28 09:07:16 +0000887
Ken Dyck199c3d62010-01-11 17:06:35 +0000888 CharUnits OldOffset = BlockOffset;
Mike Stumpa99038c2009-02-28 09:07:16 +0000889
890 // Ensure proper alignment, even if it means we have to have a gap
Ken Dyck199c3d62010-01-11 17:06:35 +0000891 BlockOffset = CharUnits::fromQuantity(
Ken Dyck30a8a272010-01-26 19:13:33 +0000892 llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
Mike Stumpa99038c2009-02-28 09:07:16 +0000893 BlockAlign = std::max(Align, BlockAlign);
Mike Stump00470a12009-03-05 08:32:30 +0000894
Ken Dyck199c3d62010-01-11 17:06:35 +0000895 CharUnits Pad = BlockOffset - OldOffset;
896 if (Pad.isPositive()) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000897 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000898 llvm::APInt(32,
899 Pad.getQuantity()),
Mike Stumpa99038c2009-02-28 09:07:16 +0000900 ArrayType::Normal, 0);
Douglas Gregorba55ec22010-05-11 18:17:16 +0000901 ValueDecl *PadDecl = VarDecl::Create(getContext(),
902 getContext().getTranslationUnitDecl(),
903 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +0000904 0, QualType(PadTy), 0,
905 VarDecl::None, VarDecl::None);
John McCallea1471e2010-05-20 01:18:31 +0000906 Expr *E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
907 SourceLocation());
908 BlockLayout.push_back(E);
Mike Stumpa99038c2009-02-28 09:07:16 +0000909 }
Mike Stumpa99038c2009-02-28 09:07:16 +0000910
911 BlockOffset += Size;
John McCallea1471e2010-05-20 01:18:31 +0000912 return BlockOffset - Size;
Mike Stumpa99038c2009-02-28 09:07:16 +0000913}
Mike Stumpdab514f2009-03-04 03:23:46 +0000914
Mike Stump08920992009-03-07 02:35:30 +0000915llvm::Constant *BlockFunction::
916GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +0000917 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000918 QualType R = getContext().VoidTy;
919
920 FunctionArgList Args;
921 // FIXME: This leaks
Mike Stump08920992009-03-07 02:35:30 +0000922 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +0000923 ImplicitParamDecl::Create(getContext(), 0,
924 SourceLocation(), 0,
Mike Stump08920992009-03-07 02:35:30 +0000925 getContext().getPointerType(getContext().VoidTy));
926 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000927 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +0000928 ImplicitParamDecl::Create(getContext(), 0,
929 SourceLocation(), 0,
Mike Stumpa4f668f2009-03-06 01:33:24 +0000930 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000931 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Mike Stumpa4f668f2009-03-06 01:33:24 +0000933 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +0000934 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +0000935
Mike Stump3899a7f2009-06-05 23:26:36 +0000936 // FIXME: We'd like to put these into a mergable by content, with
937 // internal linkage.
Mike Stumpa4f668f2009-03-06 01:33:24 +0000938 CodeGenTypes &Types = CGM.getTypes();
939 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
940
941 llvm::Function *Fn =
942 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +0000943 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +0000944
945 IdentifierInfo *II
946 = &CGM.getContext().Idents.get("__copy_helper_block_");
947
948 FunctionDecl *FD = FunctionDecl::Create(getContext(),
949 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000950 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000951 FunctionDecl::Static,
952 FunctionDecl::None,
953 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +0000954 true);
955 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +0000956
957 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
958 llvm::Type *PtrPtrT;
Mike Stump08920992009-03-07 02:35:30 +0000959
Mike Stumpb7477cf2009-04-10 18:52:28 +0000960 if (NoteForHelperp) {
961 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
Mike Stump08920992009-03-07 02:35:30 +0000962
Owen Anderson96e0fc72009-07-29 22:16:19 +0000963 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpb7477cf2009-04-10 18:52:28 +0000964 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
965 SrcObj = Builder.CreateLoad(SrcObj);
Mike Stump08920992009-03-07 02:35:30 +0000966
Mike Stumpb7477cf2009-04-10 18:52:28 +0000967 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
Mike Stumpc2f4c342009-04-15 22:11:36 +0000968 llvm::Type *PtrPtrT;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000969 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpc2f4c342009-04-15 22:11:36 +0000970 DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
971 DstObj = Builder.CreateLoad(DstObj);
Mike Stump08920992009-03-07 02:35:30 +0000972
Mike Stumpb7477cf2009-04-10 18:52:28 +0000973 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
974 int flag = NoteForHelper[i].flag;
975 int index = NoteForHelper[i].index;
Mike Stump08920992009-03-07 02:35:30 +0000976
Mike Stumpb7477cf2009-04-10 18:52:28 +0000977 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
978 || NoteForHelper[i].RequiresCopying) {
979 llvm::Value *Srcv = SrcObj;
980 Srcv = Builder.CreateStructGEP(Srcv, index);
981 Srcv = Builder.CreateBitCast(Srcv,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000982 llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpb7477cf2009-04-10 18:52:28 +0000983 Srcv = Builder.CreateLoad(Srcv);
984
985 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
986 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
987
Owen Anderson0032b272009-08-13 21:57:51 +0000988 llvm::Value *N = llvm::ConstantInt::get(
989 llvm::Type::getInt32Ty(T->getContext()), flag);
Mike Stumpb7477cf2009-04-10 18:52:28 +0000990 llvm::Value *F = getBlockObjectAssign();
991 Builder.CreateCall3(F, Dstv, Srcv, N);
992 }
Mike Stump08920992009-03-07 02:35:30 +0000993 }
994 }
995
Mike Stumpa4f668f2009-03-06 01:33:24 +0000996 CGF.FinishFunction();
997
Owen Anderson3c4972d2009-07-29 18:54:39 +0000998 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000999}
1000
Mike Stumpcf62d392009-03-06 18:42:23 +00001001llvm::Constant *BlockFunction::
Mike Stump08920992009-03-07 02:35:30 +00001002GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
1003 const llvm::StructType* T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001004 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stumpa4f668f2009-03-06 01:33:24 +00001005 QualType R = getContext().VoidTy;
1006
1007 FunctionArgList Args;
1008 // FIXME: This leaks
1009 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001010 ImplicitParamDecl::Create(getContext(), 0,
1011 SourceLocation(), 0,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001012 getContext().getPointerType(getContext().VoidTy));
1013
1014 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Mike Stumpa4f668f2009-03-06 01:33:24 +00001016 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001017 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001018
Mike Stump3899a7f2009-06-05 23:26:36 +00001019 // FIXME: We'd like to put these into a mergable by content, with
1020 // internal linkage.
Mike Stumpa4f668f2009-03-06 01:33:24 +00001021 CodeGenTypes &Types = CGM.getTypes();
1022 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1023
1024 llvm::Function *Fn =
1025 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001026 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001027
1028 IdentifierInfo *II
1029 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1030
1031 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1032 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001033 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001034 FunctionDecl::Static,
1035 FunctionDecl::None,
1036 false, true);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001037 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001038
Mike Stumpb7477cf2009-04-10 18:52:28 +00001039 if (NoteForHelperp) {
1040 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
Mike Stump1edf6b62009-03-07 02:53:18 +00001041
Mike Stumpb7477cf2009-04-10 18:52:28 +00001042 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
1043 llvm::Type *PtrPtrT;
Owen Anderson96e0fc72009-07-29 22:16:19 +00001044 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpb7477cf2009-04-10 18:52:28 +00001045 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
1046 SrcObj = Builder.CreateLoad(SrcObj);
Mike Stump1edf6b62009-03-07 02:53:18 +00001047
Mike Stumpb7477cf2009-04-10 18:52:28 +00001048 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
1049 int flag = NoteForHelper[i].flag;
1050 int index = NoteForHelper[i].index;
Mike Stump1edf6b62009-03-07 02:53:18 +00001051
Mike Stumpb7477cf2009-04-10 18:52:28 +00001052 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
1053 || NoteForHelper[i].RequiresCopying) {
1054 llvm::Value *Srcv = SrcObj;
1055 Srcv = Builder.CreateStructGEP(Srcv, index);
1056 Srcv = Builder.CreateBitCast(Srcv,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001057 llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpb7477cf2009-04-10 18:52:28 +00001058 Srcv = Builder.CreateLoad(Srcv);
1059
1060 BuildBlockRelease(Srcv, flag);
1061 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001062 }
1063 }
1064
Mike Stumpa4f668f2009-03-06 01:33:24 +00001065 CGF.FinishFunction();
1066
Owen Anderson3c4972d2009-07-29 18:54:39 +00001067 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001068}
1069
Mike Stump08920992009-03-07 02:35:30 +00001070llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001071 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump08920992009-03-07 02:35:30 +00001072 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1073 T, NoteForHelper);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001074}
1075
Mike Stump08920992009-03-07 02:35:30 +00001076llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001077 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stump08920992009-03-07 02:35:30 +00001078 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001079 T, NoteForHelperp);
Mike Stumpdab514f2009-03-04 03:23:46 +00001080}
Mike Stump797b6322009-03-05 01:23:13 +00001081
Mike Stumpee094222009-03-06 06:12:24 +00001082llvm::Constant *BlockFunction::
1083GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stump45031c02009-03-06 02:29:21 +00001084 QualType R = getContext().VoidTy;
1085
1086 FunctionArgList Args;
1087 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001088 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001089 ImplicitParamDecl::Create(getContext(), 0,
1090 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001091 getContext().getPointerType(getContext().VoidTy));
1092 Args.push_back(std::make_pair(Dst, Dst->getType()));
1093
1094 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001095 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001096 ImplicitParamDecl::Create(getContext(), 0,
1097 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001098 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001099 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Mike Stump45031c02009-03-06 02:29:21 +00001101 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001102 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001103
Mike Stump45031c02009-03-06 02:29:21 +00001104 CodeGenTypes &Types = CGM.getTypes();
1105 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1106
Mike Stump3899a7f2009-06-05 23:26:36 +00001107 // FIXME: We'd like to put these into a mergable by content, with
1108 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001109 llvm::Function *Fn =
1110 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001111 "__Block_byref_id_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001112
1113 IdentifierInfo *II
1114 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1115
1116 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1117 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001118 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001119 FunctionDecl::Static,
1120 FunctionDecl::None,
1121 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001122 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001123
1124 // dst->x
1125 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001126 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001127 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001128 V = Builder.CreateStructGEP(V, 6, "x");
1129 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1130
1131 // src->x
1132 V = CGF.GetAddrOfLocalVar(Src);
1133 V = Builder.CreateLoad(V);
1134 V = Builder.CreateBitCast(V, T);
1135 V = Builder.CreateStructGEP(V, 6, "x");
Owen Anderson96e0fc72009-07-29 22:16:19 +00001136 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpee094222009-03-06 06:12:24 +00001137 llvm::Value *SrcObj = Builder.CreateLoad(V);
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Mike Stumpee094222009-03-06 06:12:24 +00001139 flag |= BLOCK_BYREF_CALLER;
1140
Owen Anderson0032b272009-08-13 21:57:51 +00001141 llvm::Value *N = llvm::ConstantInt::get(
1142 llvm::Type::getInt32Ty(T->getContext()), flag);
Mike Stumpee094222009-03-06 06:12:24 +00001143 llvm::Value *F = getBlockObjectAssign();
1144 Builder.CreateCall3(F, DstObj, SrcObj, N);
1145
Mike Stump45031c02009-03-06 02:29:21 +00001146 CGF.FinishFunction();
1147
Owen Anderson3c4972d2009-07-29 18:54:39 +00001148 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001149}
1150
Mike Stump1851b682009-03-06 04:53:30 +00001151llvm::Constant *
1152BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1153 int flag) {
Mike Stump45031c02009-03-06 02:29:21 +00001154 QualType R = getContext().VoidTy;
1155
1156 FunctionArgList Args;
1157 // FIXME: This leaks
1158 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001159 ImplicitParamDecl::Create(getContext(), 0,
1160 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001161 getContext().getPointerType(getContext().VoidTy));
1162
1163 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Mike Stump45031c02009-03-06 02:29:21 +00001165 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001166 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001167
Mike Stump45031c02009-03-06 02:29:21 +00001168 CodeGenTypes &Types = CGM.getTypes();
1169 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1170
Mike Stump3899a7f2009-06-05 23:26:36 +00001171 // FIXME: We'd like to put these into a mergable by content, with
1172 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001173 llvm::Function *Fn =
1174 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001175 "__Block_byref_id_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001176 &CGM.getModule());
1177
1178 IdentifierInfo *II
1179 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1180
1181 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1182 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001183 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001184 FunctionDecl::Static,
1185 FunctionDecl::None,
1186 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001187 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001188
1189 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001190 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001191 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001192 V = Builder.CreateStructGEP(V, 6, "x");
Owen Anderson96e0fc72009-07-29 22:16:19 +00001193 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001194 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001195
Mike Stump1851b682009-03-06 04:53:30 +00001196 flag |= BLOCK_BYREF_CALLER;
1197 BuildBlockRelease(V, flag);
Mike Stump45031c02009-03-06 02:29:21 +00001198 CGF.FinishFunction();
1199
Owen Anderson3c4972d2009-07-29 18:54:39 +00001200 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001201}
1202
Mike Stumpee094222009-03-06 06:12:24 +00001203llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
Chris Lattner10976d92009-12-05 08:21:30 +00001204 int Flag, unsigned Align) {
1205 // All alignments below that of pointer alignment collapse down to just
Mike Stump3899a7f2009-06-05 23:26:36 +00001206 // pointer alignment, as we always have at least that much alignment to begin
1207 // with.
1208 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001209
Mike Stump3899a7f2009-06-05 23:26:36 +00001210 // As an optimization, we only generate a single function of each kind we
1211 // might need. We need a different one for each alignment and for each
1212 // setting of flags. We mix Align and flag to get the kind.
Chris Lattner10976d92009-12-05 08:21:30 +00001213 uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1214 llvm::Constant *&Entry = CGM.AssignCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001215 if (Entry)
1216 return Entry;
Chris Lattner10976d92009-12-05 08:21:30 +00001217 return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
Mike Stump45031c02009-03-06 02:29:21 +00001218}
1219
Mike Stump1851b682009-03-06 04:53:30 +00001220llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
Chris Lattner10976d92009-12-05 08:21:30 +00001221 int Flag,
Mike Stump3899a7f2009-06-05 23:26:36 +00001222 unsigned Align) {
1223 // All alignments below that of pointer alignment collpase down to just
1224 // pointer alignment, as we always have at least that much alignment to begin
1225 // with.
1226 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001227
Mike Stump3899a7f2009-06-05 23:26:36 +00001228 // As an optimization, we only generate a single function of each kind we
1229 // might need. We need a different one for each alignment and for each
1230 // setting of flags. We mix Align and flag to get the kind.
Chris Lattner10976d92009-12-05 08:21:30 +00001231 uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1232 llvm::Constant *&Entry = CGM.DestroyCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001233 if (Entry)
1234 return Entry;
Chris Lattner10976d92009-12-05 08:21:30 +00001235 return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
Mike Stump45031c02009-03-06 02:29:21 +00001236}
1237
Mike Stump797b6322009-03-05 01:23:13 +00001238llvm::Value *BlockFunction::getBlockObjectDispose() {
1239 if (CGM.BlockObjectDispose == 0) {
1240 const llvm::FunctionType *FTy;
1241 std::vector<const llvm::Type*> ArgTys;
Owen Anderson0032b272009-08-13 21:57:51 +00001242 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
Mike Stump797b6322009-03-05 01:23:13 +00001243 ArgTys.push_back(PtrToInt8Ty);
Owen Anderson0032b272009-08-13 21:57:51 +00001244 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
Owen Anderson96e0fc72009-07-29 22:16:19 +00001245 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump00470a12009-03-05 08:32:30 +00001246 CGM.BlockObjectDispose
Mike Stump797b6322009-03-05 01:23:13 +00001247 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1248 }
1249 return CGM.BlockObjectDispose;
1250}
1251
Mike Stumpee094222009-03-06 06:12:24 +00001252llvm::Value *BlockFunction::getBlockObjectAssign() {
1253 if (CGM.BlockObjectAssign == 0) {
1254 const llvm::FunctionType *FTy;
1255 std::vector<const llvm::Type*> ArgTys;
Owen Anderson0032b272009-08-13 21:57:51 +00001256 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
Mike Stumpee094222009-03-06 06:12:24 +00001257 ArgTys.push_back(PtrToInt8Ty);
1258 ArgTys.push_back(PtrToInt8Ty);
Owen Anderson0032b272009-08-13 21:57:51 +00001259 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
Owen Anderson96e0fc72009-07-29 22:16:19 +00001260 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stumpee094222009-03-06 06:12:24 +00001261 CGM.BlockObjectAssign
1262 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1263 }
1264 return CGM.BlockObjectAssign;
1265}
1266
Mike Stump1851b682009-03-06 04:53:30 +00001267void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Mike Stump797b6322009-03-05 01:23:13 +00001268 llvm::Value *F = getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001269 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001270 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Owen Anderson0032b272009-08-13 21:57:51 +00001271 N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
Mike Stump797b6322009-03-05 01:23:13 +00001272 Builder.CreateCall2(F, V, N);
1273}
Mike Stump00470a12009-03-05 08:32:30 +00001274
1275ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001276
1277BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1278 CGBuilderTy &B)
Owen Andersona1cf15f2009-07-14 23:10:40 +00001279 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
Owen Anderson0032b272009-08-13 21:57:51 +00001280 PtrToInt8Ty = llvm::PointerType::getUnqual(
1281 llvm::Type::getInt8Ty(VMContext));
Mike Stump08920992009-03-07 02:35:30 +00001282
1283 BlockHasCopyDispose = false;
1284}