blob: 04f1ef24b29715d3f00faede23e06c02b5c9b5a2 [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 +000027CGBlockInfo::CGBlockInfo(const char *N)
28 : Name(N), CXXThisRef(0), NeedsObjCSelf(false) {
29
30 // Skip asm prefix, if any.
31 if (Name && Name[0] == '\01')
32 ++Name;
33}
34
35
Mike Stumpcf62d392009-03-06 18:42:23 +000036llvm::Constant *CodeGenFunction::
Fariborz Jahanian89ecd412010-08-04 16:57:49 +000037BuildDescriptorBlockDecl(const BlockExpr *BE, const CGBlockInfo &Info,
Mike Stumpa803b0e2009-03-25 17:58:24 +000038 const llvm::StructType* Ty,
Fariborz Jahanian44034db2010-08-04 18:44:59 +000039 llvm::Constant *BlockVarLayout,
Mike Stump08920992009-03-07 02:35:30 +000040 std::vector<HelperInfo> *NoteForHelper) {
Fariborz Jahanian89ecd412010-08-04 16:57:49 +000041 bool BlockHasCopyDispose = Info.BlockHasCopyDispose;
42 CharUnits Size = Info.BlockSize;
Mike Stump56129b12009-02-13 16:55:51 +000043 const llvm::Type *UnsignedLongTy
44 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpe5fee252009-02-13 16:19:19 +000045 llvm::Constant *C;
46 std::vector<llvm::Constant*> Elts;
47
48 // reserved
Owen Anderson4a28d5d2009-07-24 23:12:58 +000049 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000050 Elts.push_back(C);
51
52 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000053 // FIXME: What is the right way to say this doesn't fit? We should give
54 // a user diagnostic in that case. Better fix would be to change the
55 // API to size_t.
Ken Dyck199c3d62010-01-11 17:06:35 +000056 C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
Mike Stumpe5fee252009-02-13 16:19:19 +000057 Elts.push_back(C);
58
Blaine Garst2a7eb282010-02-23 21:51:17 +000059 // optional copy/dispose helpers
Mike Stumpe5fee252009-02-13 16:19:19 +000060 if (BlockHasCopyDispose) {
61 // copy_func_helper_decl
Mike Stumpb7477cf2009-04-10 18:52:28 +000062 Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000063
64 // destroy_func_decl
Mike Stumpb7477cf2009-04-10 18:52:28 +000065 Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000066 }
67
Blaine Garst2a7eb282010-02-23 21:51:17 +000068 // Signature. non-optional ObjC-style method descriptor @encode sequence
69 std::string BlockTypeEncoding;
70 CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
71
72 Elts.push_back(llvm::ConstantExpr::getBitCast(
73 CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty));
74
75 // Layout.
Fariborz Jahanian44034db2010-08-04 18:44:59 +000076 C = BlockVarLayout;
77
Blaine Garst2a7eb282010-02-23 21:51:17 +000078 Elts.push_back(C);
79
Nick Lewycky0d36dd22009-09-19 20:00:52 +000080 C = llvm::ConstantStruct::get(VMContext, Elts, false);
Mike Stumpe5fee252009-02-13 16:19:19 +000081
Owen Anderson1c431b32009-07-08 19:05:04 +000082 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
Mike Stumpe5fee252009-02-13 16:19:19 +000083 llvm::GlobalValue::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +000084 C, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +000085 return C;
86}
87
John McCallee504292010-05-21 04:11:14 +000088static void CollectBlockDeclRefInfo(const Stmt *S, CGBlockInfo &Info) {
Anders Carlsson4de9fce2009-03-01 01:09:12 +000089 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
90 I != E; ++I)
Daniel Dunbar82573ee2009-03-02 07:00:57 +000091 if (*I)
John McCallee504292010-05-21 04:11:14 +000092 CollectBlockDeclRefInfo(*I, Info);
Mike Stump00470a12009-03-05 08:32:30 +000093
Mike Stumpea26cb52009-10-21 03:49:08 +000094 // We want to ensure we walk down into block literals so we can find
95 // all nested BlockDeclRefExprs.
Mike Stump38e16272009-10-21 22:01:24 +000096 if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallee504292010-05-21 04:11:14 +000097 Info.InnerBlocks.insert(BE->getBlockDecl());
98 CollectBlockDeclRefInfo(BE->getBody(), Info);
Mike Stump38e16272009-10-21 22:01:24 +000099 }
Mike Stumpea26cb52009-10-21 03:49:08 +0000100
John McCallee504292010-05-21 04:11:14 +0000101 else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
102 const ValueDecl *D = BDRE->getDecl();
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000103 // FIXME: Handle enums.
John McCallee504292010-05-21 04:11:14 +0000104 if (isa<FunctionDecl>(D))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000105 return;
Mike Stump00470a12009-03-05 08:32:30 +0000106
John McCallee504292010-05-21 04:11:14 +0000107 if (isa<ImplicitParamDecl>(D) &&
108 isa<ObjCMethodDecl>(D->getDeclContext()) &&
109 cast<ObjCMethodDecl>(D->getDeclContext())->getSelfDecl() == D) {
110 Info.NeedsObjCSelf = true;
111 return;
112 }
113
Mike Stump38e16272009-10-21 22:01:24 +0000114 // Only Decls that escape are added.
John McCallee504292010-05-21 04:11:14 +0000115 if (!Info.InnerBlocks.count(D->getDeclContext()))
Mike Stump38e16272009-10-21 22:01:24 +0000116 Info.DeclRefs.push_back(BDRE);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000117 }
John McCallea1471e2010-05-20 01:18:31 +0000118
John McCallee504292010-05-21 04:11:14 +0000119 // Make sure to capture implicit 'self' references due to super calls.
Chandler Carruthf54b80f2010-05-21 10:29:28 +0000120 else if (const ObjCMessageExpr *E = dyn_cast<ObjCMessageExpr>(S)) {
John McCallee504292010-05-21 04:11:14 +0000121 if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
122 E->getReceiverKind() == ObjCMessageExpr::SuperInstance)
123 Info.NeedsObjCSelf = true;
Chandler Carruthf54b80f2010-05-21 10:29:28 +0000124 }
John McCallee504292010-05-21 04:11:14 +0000125
126 // Getter/setter uses may also cause implicit super references,
127 // which we can check for with:
128 else if (isa<ObjCSuperExpr>(S))
129 Info.NeedsObjCSelf = true;
130
131 else if (isa<CXXThisExpr>(S))
John McCallea1471e2010-05-20 01:18:31 +0000132 Info.CXXThisRef = cast<CXXThisExpr>(S);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000133}
134
John McCallee504292010-05-21 04:11:14 +0000135/// CanBlockBeGlobal - Given a CGBlockInfo struct, determines if a block can be
Mike Stump58a85142009-03-04 22:48:06 +0000136/// declared as a global variable instead of on the stack.
John McCallee504292010-05-21 04:11:14 +0000137static bool CanBlockBeGlobal(const CGBlockInfo &Info) {
Mike Stumpea26cb52009-10-21 03:49:08 +0000138 return Info.DeclRefs.empty();
139}
140
141/// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
142/// ensure we can generate the debug information for the parameter for the block
143/// invoke function.
John McCallee504292010-05-21 04:11:14 +0000144static void AllocateAllBlockDeclRefs(CodeGenFunction &CGF, CGBlockInfo &Info) {
John McCallea1471e2010-05-20 01:18:31 +0000145 if (Info.CXXThisRef)
John McCallee504292010-05-21 04:11:14 +0000146 CGF.AllocateBlockCXXThisPointer(Info.CXXThisRef);
Mike Stumpea26cb52009-10-21 03:49:08 +0000147
148 for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
John McCallee504292010-05-21 04:11:14 +0000149 CGF.AllocateBlockDecl(Info.DeclRefs[i]);
150
151 if (Info.NeedsObjCSelf) {
152 ValueDecl *Self = cast<ObjCMethodDecl>(CGF.CurFuncDecl)->getSelfDecl();
153 BlockDeclRefExpr *BDRE =
154 new (CGF.getContext()) BlockDeclRefExpr(Self, Self->getType(),
155 SourceLocation(), false);
156 Info.DeclRefs.push_back(BDRE);
157 CGF.AllocateBlockDecl(BDRE);
158 }
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000159}
160
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000161static unsigned computeBlockFlag(CodeGenModule &CGM,
162 const BlockExpr *BE, unsigned flags) {
163 QualType BPT = BE->getType();
164 const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
165 QualType ResultType = ftype->getResultType();
166
167 CallArgList Args;
168 CodeGenTypes &Types = CGM.getTypes();
169 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
170 FunctionType::ExtInfo());
171 if (CGM.ReturnTypeUsesSRet(FnInfo))
172 flags |= CodeGenFunction::BLOCK_USE_STRET;
173 return flags;
174}
175
Mike Stump58a85142009-03-04 22:48:06 +0000176// FIXME: Push most into CGM, passing down a few bits, like current function
177// name.
Mike Stump8a2b4b12009-02-25 23:33:13 +0000178llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000179 std::string Name = CurFn->getName();
John McCallee504292010-05-21 04:11:14 +0000180 CGBlockInfo Info(Name.c_str());
181 Info.InnerBlocks.insert(BE->getBlockDecl());
182 CollectBlockDeclRefInfo(BE->getBody(), Info);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000183
184 // Check if the block can be global.
Mike Stump58a85142009-03-04 22:48:06 +0000185 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
186 // to just have one code path. We should move this function into CGM and pass
187 // CGF, then we can just check to see if CGF is 0.
Mike Stumpdab514f2009-03-04 03:23:46 +0000188 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000189 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump00470a12009-03-05 08:32:30 +0000190
David Chisnall5e530af2009-11-17 19:33:30 +0000191 size_t BlockFields = 5;
192
David Chisnall5e530af2009-11-17 19:33:30 +0000193 std::vector<llvm::Constant*> Elts(BlockFields);
194
Mike Stumpe5fee252009-02-13 16:19:19 +0000195 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000196 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000197
Mike Stumpe5fee252009-02-13 16:19:19 +0000198 {
Fariborz Jahanian44034db2010-08-04 18:44:59 +0000199 llvm::Constant *BlockVarLayout;
Mike Stumpe5fee252009-02-13 16:19:19 +0000200 // C = BuildBlockStructInitlist();
Blaine Garsta36e2232010-03-05 01:29:59 +0000201 unsigned int flags = BLOCK_HAS_SIGNATURE;
David Chisnall5e530af2009-11-17 19:33:30 +0000202
Mike Stump00470a12009-03-05 08:32:30 +0000203 // We run this first so that we set BlockHasCopyDispose from the entire
204 // block literal.
205 // __invoke
Mike Stump00470a12009-03-05 08:32:30 +0000206 llvm::Function *Fn
Fariborz Jahanian564360b2010-06-24 00:08:06 +0000207 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, BE, Info, CurFuncDecl,
Fariborz Jahanian44034db2010-08-04 18:44:59 +0000208 BlockVarLayout,
John McCallee504292010-05-21 04:11:14 +0000209 LocalDeclMap);
210 BlockHasCopyDispose |= Info.BlockHasCopyDispose;
Mike Stump00470a12009-03-05 08:32:30 +0000211 Elts[3] = Fn;
212
Mike Stumpf5408fe2009-05-16 07:57:57 +0000213 // FIXME: Don't use BlockHasCopyDispose, it is set more often then
214 // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
John McCallee504292010-05-21 04:11:14 +0000215 if (Info.BlockHasCopyDispose)
Mike Stumpe5fee252009-02-13 16:19:19 +0000216 flags |= BLOCK_HAS_COPY_DISPOSE;
217
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000218 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000219 C = CGM.getNSConcreteStackBlock();
Owen Anderson3c4972d2009-07-29 18:54:39 +0000220 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump00470a12009-03-05 08:32:30 +0000221 Elts[0] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000222
223 // __flags
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000224 flags = computeBlockFlag(CGM, BE, flags);
Mike Stumpe5fee252009-02-13 16:19:19 +0000225 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
226 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000227 C = llvm::ConstantInt::get(IntTy, flags);
Mike Stump00470a12009-03-05 08:32:30 +0000228 Elts[1] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000229
230 // __reserved
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000231 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump00470a12009-03-05 08:32:30 +0000232 Elts[2] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000233
John McCallee504292010-05-21 04:11:14 +0000234 if (Info.BlockLayout.empty()) {
Mike Stumpcf62d392009-03-06 18:42:23 +0000235 // __descriptor
Fariborz Jahanian44034db2010-08-04 18:44:59 +0000236 C = llvm::Constant::getNullValue(PtrToInt8Ty);
237 Elts[4] = BuildDescriptorBlockDecl(BE, Info, 0, C, 0);
Mike Stumpcf62d392009-03-06 18:42:23 +0000238
Mike Stump5570cfe2009-03-01 20:07:53 +0000239 // Optimize to being a global block.
240 Elts[0] = CGM.getNSConcreteGlobalBlock();
Blaine Garsta36e2232010-03-05 01:29:59 +0000241
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000242 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
Mike Stump5570cfe2009-03-01 20:07:53 +0000243
Nick Lewycky0d36dd22009-09-19 20:00:52 +0000244 C = llvm::ConstantStruct::get(VMContext, Elts, false);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000245
Owen Anderson1c431b32009-07-08 19:05:04 +0000246 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +0000247 llvm::GlobalValue::InternalLinkage, C,
248 "__block_holder_tmp_" +
249 llvm::Twine(CGM.getGlobalUniqueCount()));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000250 QualType BPT = BE->getType();
Owen Anderson3c4972d2009-07-29 18:54:39 +0000251 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000252 return C;
253 }
Mike Stump00470a12009-03-05 08:32:30 +0000254
John McCallee504292010-05-21 04:11:14 +0000255 std::vector<const llvm::Type *> Types(BlockFields+Info.BlockLayout.size());
Mike Stump08920992009-03-07 02:35:30 +0000256 for (int i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000257 Types[i] = Elts[i]->getType();
Mike Stump08920992009-03-07 02:35:30 +0000258 Types[4] = PtrToInt8Ty;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000259
John McCallee504292010-05-21 04:11:14 +0000260 for (unsigned i = 0, n = Info.BlockLayout.size(); i != n; ++i) {
261 const Expr *E = Info.BlockLayout[i];
Mike Stumpa99038c2009-02-28 09:07:16 +0000262 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
263 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000264 if (BDRE && BDRE->isByRef()) {
Fariborz Jahanian79651722010-06-02 21:35:17 +0000265 Types[i+BlockFields] =
266 llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
267 } else if (BDRE && BDRE->getDecl()->getType()->isReferenceType()) {
268 Types[i+BlockFields] = llvm::PointerType::get(ConvertType(Ty), 0);
269 } else
David Chisnall5e530af2009-11-17 19:33:30 +0000270 Types[i+BlockFields] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000271 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000272
Owen Anderson47a434f2009-08-05 23:18:46 +0000273 llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000274
275 llvm::AllocaInst *A = CreateTempAlloca(Ty);
John McCallee504292010-05-21 04:11:14 +0000276 A->setAlignment(Info.BlockAlign.getQuantity());
Mike Stump8a2b4b12009-02-25 23:33:13 +0000277 V = A;
278
John McCallea1471e2010-05-20 01:18:31 +0000279 // Build layout / cleanup information for all the data entries in the
280 // layout, and write the enclosing fields into the type.
John McCallee504292010-05-21 04:11:14 +0000281 std::vector<HelperInfo> NoteForHelper(Info.BlockLayout.size());
John McCallea1471e2010-05-20 01:18:31 +0000282 unsigned NumHelpers = 0;
Mike Stump08920992009-03-07 02:35:30 +0000283
284 for (unsigned i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000285 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump00470a12009-03-05 08:32:30 +0000286
John McCallee504292010-05-21 04:11:14 +0000287 for (unsigned i=0; i < Info.BlockLayout.size(); ++i) {
288 const Expr *E = Info.BlockLayout[i];
Mike Stump8a2b4b12009-02-25 23:33:13 +0000289
John McCallea1471e2010-05-20 01:18:31 +0000290 // Skip padding.
291 if (isa<DeclRefExpr>(E)) continue;
Mike Stumpa99038c2009-02-28 09:07:16 +0000292
John McCallea1471e2010-05-20 01:18:31 +0000293 llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
294 HelperInfo &Note = NoteForHelper[NumHelpers++];
Mike Stumpa99038c2009-02-28 09:07:16 +0000295
John McCallea1471e2010-05-20 01:18:31 +0000296 Note.index = i+5;
Mike Stump08920992009-03-07 02:35:30 +0000297
John McCallea1471e2010-05-20 01:18:31 +0000298 if (isa<CXXThisExpr>(E)) {
299 Note.RequiresCopying = false;
300 Note.flag = BLOCK_FIELD_IS_OBJECT;
Mike Stumpa99038c2009-02-28 09:07:16 +0000301
John McCallea1471e2010-05-20 01:18:31 +0000302 Builder.CreateStore(LoadCXXThis(), Addr);
303 continue;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000304 }
John McCallea1471e2010-05-20 01:18:31 +0000305
306 const BlockDeclRefExpr *BDRE = cast<BlockDeclRefExpr>(E);
307 const ValueDecl *VD = BDRE->getDecl();
308 QualType T = VD->getType();
309
310 Note.RequiresCopying = BlockRequiresCopying(T);
311
312 if (BDRE->isByRef()) {
313 Note.flag = BLOCK_FIELD_IS_BYREF;
314 if (T.isObjCGCWeak())
315 Note.flag |= BLOCK_FIELD_IS_WEAK;
316 } else if (T->isBlockPointerType()) {
317 Note.flag = BLOCK_FIELD_IS_BLOCK;
318 } else {
319 Note.flag = BLOCK_FIELD_IS_OBJECT;
320 }
321
322 if (LocalDeclMap[VD]) {
323 if (BDRE->isByRef()) {
324 llvm::Value *Loc = LocalDeclMap[VD];
325 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
326 Loc = Builder.CreateLoad(Loc);
327 Builder.CreateStore(Loc, Addr);
328 continue;
329 } else {
Fariborz Jahanianac7362d2010-06-08 20:57:22 +0000330 if (BDRE->getCopyConstructorExpr()) {
331 E = BDRE->getCopyConstructorExpr();
John McCallf1549f62010-07-06 01:34:17 +0000332 PushDestructorCleanup(E->getType(), Addr);
Fariborz Jahanianac7362d2010-06-08 20:57:22 +0000333 }
Fariborz Jahanian59da45a2010-06-04 21:35:44 +0000334 else {
335 E = new (getContext()) DeclRefExpr(const_cast<ValueDecl*>(VD),
Fariborz Jahanian79651722010-06-02 21:35:17 +0000336 VD->getType().getNonReferenceType(),
337 SourceLocation());
Fariborz Jahanian59da45a2010-06-04 21:35:44 +0000338 if (VD->getType()->isReferenceType()) {
339 E = new (getContext())
John McCall2de56d12010-08-25 11:45:40 +0000340 UnaryOperator(const_cast<Expr*>(E), UO_AddrOf,
Fariborz Jahanian59da45a2010-06-04 21:35:44 +0000341 getContext().getPointerType(E->getType()),
342 SourceLocation());
343 }
Fariborz Jahaniandf8b8ea2010-06-04 16:10:00 +0000344 }
345 }
John McCallea1471e2010-05-20 01:18:31 +0000346 }
John McCallea1471e2010-05-20 01:18:31 +0000347
348 if (BDRE->isByRef()) {
349 E = new (getContext())
John McCall2de56d12010-08-25 11:45:40 +0000350 UnaryOperator(const_cast<Expr*>(E), UO_AddrOf,
John McCallea1471e2010-05-20 01:18:31 +0000351 getContext().getPointerType(E->getType()),
352 SourceLocation());
353 }
354
355 RValue r = EmitAnyExpr(E, Addr, false);
356 if (r.isScalar()) {
357 llvm::Value *Loc = r.getScalarVal();
358 const llvm::Type *Ty = Types[i+BlockFields];
359 if (BDRE->isByRef()) {
360 // E is now the address of the value field, instead, we want the
361 // address of the actual ByRef struct. We optimize this slightly
362 // compared to gcc by not grabbing the forwarding slot as this must
363 // be done during Block_copy for us, and we can postpone the work
364 // until then.
365 CharUnits offset = BlockDecls[BDRE->getDecl()];
366
367 llvm::Value *BlockLiteral = LoadBlockStruct();
368
369 Loc = Builder.CreateGEP(BlockLiteral,
Chris Lattner77b89b82010-06-27 07:15:29 +0000370 llvm::ConstantInt::get(Int64Ty, offset.getQuantity()),
John McCallea1471e2010-05-20 01:18:31 +0000371 "block.literal");
372 Ty = llvm::PointerType::get(Ty, 0);
373 Loc = Builder.CreateBitCast(Loc, Ty);
374 Loc = Builder.CreateLoad(Loc);
375 // Loc = Builder.CreateBitCast(Loc, Ty);
376 }
377 Builder.CreateStore(Loc, Addr);
378 } else if (r.isComplex())
379 // FIXME: implement
380 ErrorUnsupported(BE, "complex in block literal");
381 else if (r.isAggregate())
382 ; // Already created into the destination
383 else
384 assert (0 && "bad block variable");
385 // FIXME: Ensure that the offset created by the backend for
386 // the struct matches the previously computed offset in BlockDecls.
387 }
388 NoteForHelper.resize(NumHelpers);
Mike Stumpcf62d392009-03-06 18:42:23 +0000389
390 // __descriptor
Fariborz Jahanian89ecd412010-08-04 16:57:49 +0000391 llvm::Value *Descriptor = BuildDescriptorBlockDecl(BE, Info, Ty,
Fariborz Jahanian44034db2010-08-04 18:44:59 +0000392 BlockVarLayout,
Mike Stump08920992009-03-07 02:35:30 +0000393 &NoteForHelper);
394 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
395 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
Mike Stumpe5fee252009-02-13 16:19:19 +0000396 }
Mike Stump00470a12009-03-05 08:32:30 +0000397
Mike Stumpbd65cac2009-02-19 01:01:04 +0000398 QualType BPT = BE->getType();
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000399 V = Builder.CreateBitCast(V, ConvertType(BPT));
400 // See if this is a __weak block variable and the must call objc_read_weak
401 // on it.
402 const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
403 QualType RES = ftype->getResultType();
404 if (RES.isObjCGCWeak()) {
405 // Must cast argument to id*
406 const llvm::Type *ObjectPtrTy =
407 ConvertType(CGM.getContext().getObjCIdType());
408 const llvm::Type *PtrObjectPtrTy =
409 llvm::PointerType::getUnqual(ObjectPtrTy);
410 V = Builder.CreateBitCast(V, PtrObjectPtrTy);
411 V = CGM.getObjCRuntime().EmitObjCWeakRead(*this, V);
412 }
413 return V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000414}
415
416
Mike Stump2a998142009-03-04 18:17:45 +0000417const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000418 if (BlockDescriptorType)
419 return BlockDescriptorType;
420
Mike Stumpa5448542009-02-13 15:32:32 +0000421 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000422 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000423
Mike Stumpab695142009-02-13 15:16:56 +0000424 // struct __block_descriptor {
425 // unsigned long reserved;
426 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000427 //
428 // // later, the following will be added
429 //
430 // struct {
431 // void (*copyHelper)();
432 // void (*copyHelper)();
433 // } helpers; // !!! optional
434 //
435 // const char *signature; // the block signature
436 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000437 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000438 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
439 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000440 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000441 NULL);
442
443 getModule().addTypeName("struct.__block_descriptor",
444 BlockDescriptorType);
445
446 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000447}
448
Mike Stump2a998142009-03-04 18:17:45 +0000449const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000450 if (GenericBlockLiteralType)
451 return GenericBlockLiteralType;
452
Mike Stumpa5448542009-02-13 15:32:32 +0000453 const llvm::Type *BlockDescPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000454 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpa5448542009-02-13 15:32:32 +0000455
Mike Stump7cbb3602009-02-13 16:01:35 +0000456 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
457 getTypes().ConvertType(getContext().IntTy));
458
Mike Stump9b8a7972009-02-13 15:25:34 +0000459 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000460 // void *__isa;
461 // int __flags;
462 // int __reserved;
463 // void (*__invoke)(void *);
464 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000465 // };
Blaine Garst2a7eb282010-02-23 21:51:17 +0000466 GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
Owen Anderson47a434f2009-08-05 23:18:46 +0000467 PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000468 IntTy,
469 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000470 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000471 BlockDescPtrTy,
472 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000473
Mike Stump9b8a7972009-02-13 15:25:34 +0000474 getModule().addTypeName("struct.__block_literal_generic",
475 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000476
Mike Stump9b8a7972009-02-13 15:25:34 +0000477 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000478}
479
Mike Stumpbd65cac2009-02-19 01:01:04 +0000480
Anders Carlssona1736c02009-12-24 21:13:40 +0000481RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
482 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000483 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000484 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000485
Anders Carlssonacfde802009-02-12 00:39:25 +0000486 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
487
488 // Get a pointer to the generic block literal.
489 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000490 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000491
492 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000493 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000494 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
495
496 // Get the function pointer from the literal.
497 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000498
Mike Stumpa5448542009-02-13 15:32:32 +0000499 BlockLiteral =
500 Builder.CreateBitCast(BlockLiteral,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000501 llvm::Type::getInt8PtrTy(VMContext),
Anders Carlssonacfde802009-02-12 00:39:25 +0000502 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000503
Anders Carlssonacfde802009-02-12 00:39:25 +0000504 // Add the block literal.
505 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
506 CallArgList Args;
507 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000508
Anders Carlsson782f3972009-04-08 23:13:16 +0000509 QualType FnType = BPT->getPointeeType();
510
Anders Carlssonacfde802009-02-12 00:39:25 +0000511 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000512 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000513 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000514
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000515 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000516 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000517
John McCall04a67a62010-02-05 21:31:56 +0000518 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
519 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000520
Mike Stump1eb44332009-09-09 15:08:12 +0000521 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000522 CGM.getTypes().getFunctionInfo(ResultType, Args,
523 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000525 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000526 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000527 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Owen Anderson96e0fc72009-07-29 22:16:19 +0000529 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000530 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Anders Carlssonacfde802009-02-12 00:39:25 +0000532 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000533 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000534}
Anders Carlssond5cab542009-02-12 17:55:02 +0000535
John McCallea1471e2010-05-20 01:18:31 +0000536void CodeGenFunction::AllocateBlockCXXThisPointer(const CXXThisExpr *E) {
537 assert(BlockCXXThisOffset.isZero() && "already computed 'this' pointer");
538
539 // Figure out what the offset is.
540 QualType T = E->getType();
541 std::pair<CharUnits,CharUnits> TypeInfo = getContext().getTypeInfoInChars(T);
542 CharUnits Offset = getBlockOffset(TypeInfo.first, TypeInfo.second);
543
544 BlockCXXThisOffset = Offset;
545 BlockLayout.push_back(E);
546}
547
548void CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000549 const ValueDecl *VD = E->getDecl();
John McCallea1471e2010-05-20 01:18:31 +0000550 CharUnits &Offset = BlockDecls[VD];
Mike Stumpdab514f2009-03-04 03:23:46 +0000551
Mike Stumpdab514f2009-03-04 03:23:46 +0000552 // See if we have already allocated an offset for this variable.
John McCallea1471e2010-05-20 01:18:31 +0000553 if (!Offset.isZero())
554 return;
Mike Stumpea26cb52009-10-21 03:49:08 +0000555
556 // Don't run the expensive check, unless we have to.
Mike Stump083c25e2009-10-22 00:49:09 +0000557 if (!BlockHasCopyDispose)
558 if (E->isByRef()
559 || BlockRequiresCopying(E->getType()))
560 BlockHasCopyDispose = true;
Mike Stumpea26cb52009-10-21 03:49:08 +0000561
John McCallea1471e2010-05-20 01:18:31 +0000562 const ValueDecl *D = cast<ValueDecl>(E->getDecl());
Mike Stumpea26cb52009-10-21 03:49:08 +0000563
John McCallea1471e2010-05-20 01:18:31 +0000564 CharUnits Size;
565 CharUnits Align;
566
567 if (E->isByRef()) {
568 llvm::tie(Size,Align) =
569 getContext().getTypeInfoInChars(getContext().VoidPtrTy);
570 } else {
571 Size = getContext().getTypeSizeInChars(D->getType());
572 Align = getContext().getDeclAlign(D);
573 }
574
575 Offset = getBlockOffset(Size, Align);
576 BlockLayout.push_back(E);
Mike Stumpea26cb52009-10-21 03:49:08 +0000577}
578
John McCallee504292010-05-21 04:11:14 +0000579llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const ValueDecl *VD,
580 bool IsByRef) {
Fariborz Jahaniandf8b8ea2010-06-04 16:10:00 +0000581
John McCallea1471e2010-05-20 01:18:31 +0000582 CharUnits offset = BlockDecls[VD];
583 assert(!offset.isZero() && "getting address of unallocated decl");
Mike Stumpdab514f2009-03-04 03:23:46 +0000584
585 llvm::Value *BlockLiteral = LoadBlockStruct();
586 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
Chris Lattner77b89b82010-06-27 07:15:29 +0000587 llvm::ConstantInt::get(Int64Ty, offset.getQuantity()),
Mike Stump58a85142009-03-04 22:48:06 +0000588 "block.literal");
John McCallee504292010-05-21 04:11:14 +0000589 if (IsByRef) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000590 const llvm::Type *PtrStructTy
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000591 = llvm::PointerType::get(BuildByRefType(VD), 0);
Mike Stumpa8b60c92009-03-21 21:00:35 +0000592 // The block literal will need a copy/destroy helper.
593 BlockHasCopyDispose = true;
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000594
595 const llvm::Type *Ty = PtrStructTy;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000596 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000597 V = Builder.CreateBitCast(V, Ty);
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000598 V = Builder.CreateLoad(V);
Mike Stumpdab514f2009-03-04 03:23:46 +0000599 V = Builder.CreateStructGEP(V, 1, "forwarding");
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000600 V = Builder.CreateLoad(V);
Mike Stumpdab514f2009-03-04 03:23:46 +0000601 V = Builder.CreateBitCast(V, PtrStructTy);
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000602 V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
603 VD->getNameAsString());
Fariborz Jahaniand33ded52010-05-04 17:59:32 +0000604 if (VD->getType()->isReferenceType())
605 V = Builder.CreateLoad(V);
Mike Stumpdab514f2009-03-04 03:23:46 +0000606 } else {
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000607 const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
Owen Anderson96e0fc72009-07-29 22:16:19 +0000608 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000609 V = Builder.CreateBitCast(V, Ty);
Fariborz Jahanian79651722010-06-02 21:35:17 +0000610 if (VD->getType()->isReferenceType())
Fariborz Jahaniandf8b8ea2010-06-04 16:10:00 +0000611 V = Builder.CreateLoad(V, "ref.tmp");
Mike Stumpdab514f2009-03-04 03:23:46 +0000612 }
613 return V;
614}
615
Mike Stump67a64482009-02-14 22:16:35 +0000616llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000617BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000618 // Generate the block descriptor.
619 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000620 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
621 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000622
Blaine Garst2a7eb282010-02-23 21:51:17 +0000623 llvm::Constant *DescriptorFields[4];
Mike Stumpa5448542009-02-13 15:32:32 +0000624
Anders Carlssond5cab542009-02-12 17:55:02 +0000625 // Reserved
Owen Andersonc9c88b42009-07-31 20:28:54 +0000626 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000627
Anders Carlssond5cab542009-02-12 17:55:02 +0000628 // Block literal size. For global blocks we just use the size of the generic
629 // block literal struct.
Ken Dyck687cc4a2010-01-26 13:48:07 +0000630 CharUnits BlockLiteralSize =
631 CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
Owen Andersona1cf15f2009-07-14 23:10:40 +0000632 DescriptorFields[1] =
Ken Dyck199c3d62010-01-11 17:06:35 +0000633 llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
Blaine Garst2a7eb282010-02-23 21:51:17 +0000634
635 // signature. non-optional ObjC-style method descriptor @encode sequence
636 std::string BlockTypeEncoding;
637 CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
Mike Stumpa5448542009-02-13 15:32:32 +0000638
Blaine Garst2a7eb282010-02-23 21:51:17 +0000639 DescriptorFields[2] = llvm::ConstantExpr::getBitCast(
640 CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
641
642 // layout
643 DescriptorFields[3] =
644 llvm::ConstantInt::get(UnsignedLongTy,0);
645
646 // build the structure from the 4 elements
Mike Stumpa5448542009-02-13 15:32:32 +0000647 llvm::Constant *DescriptorStruct =
Blaine Garst2a7eb282010-02-23 21:51:17 +0000648 llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false);
Mike Stumpa5448542009-02-13 15:32:32 +0000649
Anders Carlssond5cab542009-02-12 17:55:02 +0000650 llvm::GlobalVariable *Descriptor =
Owen Anderson1c431b32009-07-08 19:05:04 +0000651 new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000652 llvm::GlobalVariable::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000653 DescriptorStruct, "__block_descriptor_global");
Mike Stumpa5448542009-02-13 15:32:32 +0000654
David Chisnall5e530af2009-11-17 19:33:30 +0000655 int FieldCount = 5;
Anders Carlssond5cab542009-02-12 17:55:02 +0000656 // Generate the constants for the block literal.
David Chisnall5e530af2009-11-17 19:33:30 +0000657
658 std::vector<llvm::Constant*> LiteralFields(FieldCount);
Mike Stumpa5448542009-02-13 15:32:32 +0000659
John McCallee504292010-05-21 04:11:14 +0000660 CGBlockInfo Info(n);
Fariborz Jahanian44034db2010-08-04 18:44:59 +0000661 llvm::Constant *BlockVarLayout;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000662 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000663 llvm::Function *Fn
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000664 = CodeGenFunction(CGM).GenerateBlockFunction(GlobalDecl(), BE,
Fariborz Jahanian44034db2010-08-04 18:44:59 +0000665 Info, 0, BlockVarLayout,
666 LocalDeclMap);
John McCallee504292010-05-21 04:11:14 +0000667 assert(Info.BlockSize == BlockLiteralSize
Mike Stump4e7a1f72009-02-21 20:00:35 +0000668 && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000669
Anders Carlssond5cab542009-02-12 17:55:02 +0000670 // isa
Daniel Dunbar673431a2010-07-16 00:00:15 +0000671 LiteralFields[0] = CGM.getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000672
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000673 // __flags
674 unsigned flags = computeBlockFlag(CGM, BE,
675 (BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000676 LiteralFields[1] =
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000677 llvm::ConstantInt::get(IntTy, flags);
Mike Stumpa5448542009-02-13 15:32:32 +0000678
Anders Carlssond5cab542009-02-12 17:55:02 +0000679 // Reserved
Owen Andersonc9c88b42009-07-31 20:28:54 +0000680 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000681
Anders Carlssond5cab542009-02-12 17:55:02 +0000682 // Function
683 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000684
Anders Carlssond5cab542009-02-12 17:55:02 +0000685 // Descriptor
686 LiteralFields[4] = Descriptor;
David Chisnall5e530af2009-11-17 19:33:30 +0000687
Mike Stumpa5448542009-02-13 15:32:32 +0000688 llvm::Constant *BlockLiteralStruct =
David Chisnall5e530af2009-11-17 19:33:30 +0000689 llvm::ConstantStruct::get(VMContext, LiteralFields, false);
Mike Stumpa5448542009-02-13 15:32:32 +0000690
691 llvm::GlobalVariable *BlockLiteral =
Owen Anderson1c431b32009-07-08 19:05:04 +0000692 new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000693 llvm::GlobalVariable::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000694 BlockLiteralStruct, "__block_literal_global");
Mike Stumpa5448542009-02-13 15:32:32 +0000695
Anders Carlssond5cab542009-02-12 17:55:02 +0000696 return BlockLiteral;
697}
698
Mike Stump4e7a1f72009-02-21 20:00:35 +0000699llvm::Value *CodeGenFunction::LoadBlockStruct() {
Mike Stumpbf1914b2009-10-20 20:30:01 +0000700 llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
701 "self");
702 // For now, we codegen based upon byte offsets.
703 return Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000704}
705
Mike Stump00470a12009-03-05 08:32:30 +0000706llvm::Function *
Fariborz Jahanian564360b2010-06-24 00:08:06 +0000707CodeGenFunction::GenerateBlockFunction(GlobalDecl GD, const BlockExpr *BExpr,
John McCallee504292010-05-21 04:11:14 +0000708 CGBlockInfo &Info,
Mike Stump6cc88f72009-03-20 21:53:12 +0000709 const Decl *OuterFuncDecl,
Fariborz Jahanian44034db2010-08-04 18:44:59 +0000710 llvm::Constant *& BlockVarLayout,
John McCallee504292010-05-21 04:11:14 +0000711 llvm::DenseMap<const Decl*, llvm::Value*> ldm) {
Devang Patel963dfbd2009-04-15 21:51:44 +0000712
713 // Check if we should generate debug info for this block.
714 if (CGM.getDebugInfo())
715 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Mike Stump7f28a9c2009-03-13 23:34:28 +0000717 // Arrange for local static and local extern declarations to appear
718 // to be local to this function as well, as they are directly referenced
719 // in a block.
720 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
721 i != ldm.end();
722 ++i) {
723 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
Mike Stump1eb44332009-09-09 15:08:12 +0000724
John McCalld931b082010-08-26 03:08:43 +0000725 if (VD->getStorageClass() == SC_Static || VD->hasExternalStorage())
Mike Stump7f28a9c2009-03-13 23:34:28 +0000726 LocalDeclMap[VD] = i->second;
727 }
728
Ken Dyck687cc4a2010-01-26 13:48:07 +0000729 BlockOffset =
730 CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
Ken Dyck30a8a272010-01-26 19:13:33 +0000731 BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
Eli Friedman48f91222009-03-28 03:24:54 +0000732
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000733 const FunctionType *BlockFunctionType = BExpr->getFunctionType();
734 QualType ResultType;
Rafael Espindola264ba482010-03-30 20:24:48 +0000735 FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType);
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000736 bool IsVariadic;
Mike Stump1eb44332009-09-09 15:08:12 +0000737 if (const FunctionProtoType *FTy =
Fariborz Jahanianda0895d2009-04-11 18:54:57 +0000738 dyn_cast<FunctionProtoType>(BlockFunctionType)) {
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000739 ResultType = FTy->getResultType();
740 IsVariadic = FTy->isVariadic();
Mike Stumpb3589f42009-07-30 22:28:39 +0000741 } else {
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000742 // K&R style block.
743 ResultType = BlockFunctionType->getResultType();
744 IsVariadic = false;
745 }
Mike Stumpa5448542009-02-13 15:32:32 +0000746
Anders Carlssond5cab542009-02-12 17:55:02 +0000747 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000748
Mike Stumpea26cb52009-10-21 03:49:08 +0000749 CurFuncDecl = OuterFuncDecl;
750
Chris Lattner161d36d2009-02-28 19:01:03 +0000751 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000752
Mike Stumpea26cb52009-10-21 03:49:08 +0000753 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000754
John McCallea1471e2010-05-20 01:18:31 +0000755 // Build the block struct now.
John McCallee504292010-05-21 04:11:14 +0000756 AllocateAllBlockDeclRefs(*this, Info);
Mike Stumpea26cb52009-10-21 03:49:08 +0000757
Fariborz Jahanian44034db2010-08-04 18:44:59 +0000758 // Capture block layout info. here.
759 if (CGM.getContext().getLangOptions().ObjC1)
760 BlockVarLayout = CGM.getObjCRuntime().GCBlockLayout(*this, Info.DeclRefs);
761 else
762 BlockVarLayout = llvm::Constant::getNullValue(PtrToInt8Ty);
763
Mike Stump083c25e2009-10-22 00:49:09 +0000764 QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +0000765 BlockLayout);
766
Anders Carlssond5cab542009-02-12 17:55:02 +0000767 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000768 ImplicitParamDecl *SelfDecl =
John McCall2888b652010-04-30 21:35:41 +0000769 ImplicitParamDecl::Create(getContext(), const_cast<BlockDecl*>(BD),
Mike Stumpadaaad32009-10-20 02:12:22 +0000770 SourceLocation(), II,
771 ParmTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000772
Anders Carlssond5cab542009-02-12 17:55:02 +0000773 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000774 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000775
Steve Naroffe78b8092009-03-13 16:56:44 +0000776 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000777 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000778 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000779
780 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +0000781 CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo);
Anders Carlssond5cab542009-02-12 17:55:02 +0000782
Anders Carlssond5cab542009-02-12 17:55:02 +0000783 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000784 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
Mike Stumpa5448542009-02-13 15:32:32 +0000785
Douglas Gregor35415f52010-05-25 17:04:15 +0000786 MangleBuffer Name;
Fariborz Jahanian564360b2010-06-24 00:08:06 +0000787 CGM.getMangledName(GD, Name, BD);
Mike Stumpa5448542009-02-13 15:32:32 +0000788 llvm::Function *Fn =
Douglas Gregor6e5d9b02010-05-25 17:12:30 +0000789 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
790 Name.getString(), &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000791
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000792 CGM.SetInternalFunctionAttributes(BD, Fn, FI);
Fariborz Jahanian8404f672010-08-13 00:19:55 +0000793 StartFunction(BD, ResultType, Fn, Args,
794 BExpr->getBody()->getLocEnd());
795
796 CurFuncDecl = OuterFuncDecl;
797
Fariborz Jahanian16ac5ce2010-06-28 18:58:34 +0000798 QualType FnType(BlockFunctionType, 0);
Fariborz Jahanianef160b42010-06-28 19:42:10 +0000799 bool HasPrototype = isa<FunctionProtoType>(BlockFunctionType);
Fariborz Jahanian16ac5ce2010-06-28 18:58:34 +0000800
801 IdentifierInfo *ID = &getContext().Idents.get(Name.getString());
802 CurCodeDecl = FunctionDecl::Create(getContext(),
803 getContext().getTranslationUnitDecl(),
804 SourceLocation(), ID, FnType,
805 0,
John McCalld931b082010-08-26 03:08:43 +0000806 SC_Static,
807 SC_None,
Fariborz Jahanian16ac5ce2010-06-28 18:58:34 +0000808 false, HasPrototype);
Fariborz Jahanian8404f672010-08-13 00:19:55 +0000809 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FnType)) {
810 const FunctionDecl *CFD = dyn_cast<FunctionDecl>(CurCodeDecl);
811 FunctionDecl *FD = const_cast<FunctionDecl *>(CFD);
812 llvm::SmallVector<ParmVarDecl*, 16> Params;
813 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
814 Params.push_back(ParmVarDecl::Create(getContext(), FD,
815 SourceLocation(), 0,
816 FT->getArgType(i), /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +0000817 SC_None, SC_None, 0));
Fariborz Jahanian8404f672010-08-13 00:19:55 +0000818 FD->setParams(Params.data(), Params.size());
819 }
Fariborz Jahanian16ac5ce2010-06-28 18:58:34 +0000820
Fariborz Jahanian8404f672010-08-13 00:19:55 +0000821
John McCallea1471e2010-05-20 01:18:31 +0000822 // If we have a C++ 'this' reference, go ahead and force it into
823 // existence now.
824 if (Info.CXXThisRef) {
825 assert(!BlockCXXThisOffset.isZero() &&
826 "haven't yet allocated 'this' reference");
827
828 // TODO: I have a dream that one day this will be typed.
829 llvm::Value *BlockLiteral = LoadBlockStruct();
830 llvm::Value *ThisPtrRaw =
831 Builder.CreateConstInBoundsGEP1_64(BlockLiteral,
832 BlockCXXThisOffset.getQuantity(),
833 "this.ptr.raw");
834
835 const llvm::Type *Ty =
836 CGM.getTypes().ConvertType(Info.CXXThisRef->getType());
837 Ty = llvm::PointerType::get(Ty, 0);
838 llvm::Value *ThisPtr = Builder.CreateBitCast(ThisPtrRaw, Ty, "this.ptr");
839
840 CXXThisValue = Builder.CreateLoad(ThisPtr, "this");
841 }
842
John McCallee504292010-05-21 04:11:14 +0000843 // If we have an Objective C 'self' reference, go ahead and force it
844 // into existence now.
845 if (Info.NeedsObjCSelf) {
846 ValueDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
847 LocalDeclMap[Self] = GetAddrOfBlockDecl(Self, false);
848 }
849
Mike Stumpb289b3f2009-10-01 22:29:41 +0000850 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
851 llvm::BasicBlock *entry = Builder.GetInsertBlock();
852 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
853 --entry_ptr;
854
Chris Lattner161d36d2009-02-28 19:01:03 +0000855 EmitStmt(BExpr->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000856
Mike Stumpde8c5c72009-10-01 00:27:30 +0000857 // Remember where we were...
858 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000859
Mike Stumpde8c5c72009-10-01 00:27:30 +0000860 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000861 ++entry_ptr;
862 Builder.SetInsertPoint(entry, entry_ptr);
863
Mike Stumpb1a6e682009-09-30 02:43:10 +0000864 if (CGDebugInfo *DI = getDebugInfo()) {
Mike Stumpb1a6e682009-09-30 02:43:10 +0000865 // Emit debug information for all the BlockDeclRefDecls.
John McCallea1471e2010-05-20 01:18:31 +0000866 // FIXME: also for 'this'
867 for (unsigned i = 0, e = BlockLayout.size(); i != e; ++i) {
868 if (const BlockDeclRefExpr *BDRE =
869 dyn_cast<BlockDeclRefExpr>(BlockLayout[i])) {
Mike Stumpb1a6e682009-09-30 02:43:10 +0000870 const ValueDecl *D = BDRE->getDecl();
871 DI->setLocation(D->getLocation());
872 DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
873 LocalDeclMap[getBlockStructDecl()],
874 Builder, this);
875 }
876 }
Mike Stumpb1a6e682009-09-30 02:43:10 +0000877 }
Mike Stumpde8c5c72009-10-01 00:27:30 +0000878 // And resume where we left off.
879 if (resume == 0)
880 Builder.ClearInsertionPoint();
881 else
882 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +0000883
Chris Lattner161d36d2009-02-28 19:01:03 +0000884 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000885
Mike Stump8a2b4b12009-02-25 23:33:13 +0000886 // The runtime needs a minimum alignment of a void *.
Ken Dyck30a8a272010-01-26 19:13:33 +0000887 CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
Ken Dyck199c3d62010-01-11 17:06:35 +0000888 BlockOffset = CharUnits::fromQuantity(
Ken Dyck30a8a272010-01-26 19:13:33 +0000889 llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
890 MinAlign.getQuantity()));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000891
John McCallee504292010-05-21 04:11:14 +0000892 Info.BlockSize = BlockOffset;
893 Info.BlockAlign = BlockAlign;
894 Info.BlockLayout = BlockLayout;
895 Info.BlockHasCopyDispose = BlockHasCopyDispose;
Anders Carlssond5cab542009-02-12 17:55:02 +0000896 return Fn;
897}
Mike Stumpa99038c2009-02-28 09:07:16 +0000898
John McCallea1471e2010-05-20 01:18:31 +0000899CharUnits BlockFunction::getBlockOffset(CharUnits Size, CharUnits Align) {
900 assert((Align.isPositive()) && "alignment must be 1 byte or more");
Mike Stumpa99038c2009-02-28 09:07:16 +0000901
Ken Dyck199c3d62010-01-11 17:06:35 +0000902 CharUnits OldOffset = BlockOffset;
Mike Stumpa99038c2009-02-28 09:07:16 +0000903
904 // Ensure proper alignment, even if it means we have to have a gap
Ken Dyck199c3d62010-01-11 17:06:35 +0000905 BlockOffset = CharUnits::fromQuantity(
Ken Dyck30a8a272010-01-26 19:13:33 +0000906 llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
Mike Stumpa99038c2009-02-28 09:07:16 +0000907 BlockAlign = std::max(Align, BlockAlign);
Mike Stump00470a12009-03-05 08:32:30 +0000908
Ken Dyck199c3d62010-01-11 17:06:35 +0000909 CharUnits Pad = BlockOffset - OldOffset;
910 if (Pad.isPositive()) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000911 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000912 llvm::APInt(32,
913 Pad.getQuantity()),
Mike Stumpa99038c2009-02-28 09:07:16 +0000914 ArrayType::Normal, 0);
Douglas Gregorba55ec22010-05-11 18:17:16 +0000915 ValueDecl *PadDecl = VarDecl::Create(getContext(),
916 getContext().getTranslationUnitDecl(),
917 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +0000918 0, QualType(PadTy), 0,
John McCalld931b082010-08-26 03:08:43 +0000919 SC_None, SC_None);
John McCallea1471e2010-05-20 01:18:31 +0000920 Expr *E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
921 SourceLocation());
922 BlockLayout.push_back(E);
Mike Stumpa99038c2009-02-28 09:07:16 +0000923 }
Mike Stumpa99038c2009-02-28 09:07:16 +0000924
925 BlockOffset += Size;
John McCallea1471e2010-05-20 01:18:31 +0000926 return BlockOffset - Size;
Mike Stumpa99038c2009-02-28 09:07:16 +0000927}
Mike Stumpdab514f2009-03-04 03:23:46 +0000928
Mike Stump08920992009-03-07 02:35:30 +0000929llvm::Constant *BlockFunction::
930GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +0000931 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000932 QualType R = getContext().VoidTy;
933
934 FunctionArgList Args;
935 // FIXME: This leaks
Mike Stump08920992009-03-07 02:35:30 +0000936 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +0000937 ImplicitParamDecl::Create(getContext(), 0,
938 SourceLocation(), 0,
Mike Stump08920992009-03-07 02:35:30 +0000939 getContext().getPointerType(getContext().VoidTy));
940 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000941 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +0000942 ImplicitParamDecl::Create(getContext(), 0,
943 SourceLocation(), 0,
Mike Stumpa4f668f2009-03-06 01:33:24 +0000944 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000945 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Mike Stumpa4f668f2009-03-06 01:33:24 +0000947 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +0000948 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +0000949
Mike Stump3899a7f2009-06-05 23:26:36 +0000950 // FIXME: We'd like to put these into a mergable by content, with
951 // internal linkage.
Mike Stumpa4f668f2009-03-06 01:33:24 +0000952 CodeGenTypes &Types = CGM.getTypes();
953 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
954
955 llvm::Function *Fn =
956 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +0000957 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +0000958
959 IdentifierInfo *II
960 = &CGM.getContext().Idents.get("__copy_helper_block_");
961
962 FunctionDecl *FD = FunctionDecl::Create(getContext(),
963 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000964 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +0000965 SC_Static,
966 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000967 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +0000968 true);
969 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +0000970
971 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
972 llvm::Type *PtrPtrT;
Mike Stump08920992009-03-07 02:35:30 +0000973
Mike Stumpb7477cf2009-04-10 18:52:28 +0000974 if (NoteForHelperp) {
975 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
Mike Stump08920992009-03-07 02:35:30 +0000976
Owen Anderson96e0fc72009-07-29 22:16:19 +0000977 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpb7477cf2009-04-10 18:52:28 +0000978 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
979 SrcObj = Builder.CreateLoad(SrcObj);
Mike Stump08920992009-03-07 02:35:30 +0000980
Mike Stumpb7477cf2009-04-10 18:52:28 +0000981 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
Mike Stumpc2f4c342009-04-15 22:11:36 +0000982 llvm::Type *PtrPtrT;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000983 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpc2f4c342009-04-15 22:11:36 +0000984 DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
985 DstObj = Builder.CreateLoad(DstObj);
Mike Stump08920992009-03-07 02:35:30 +0000986
Mike Stumpb7477cf2009-04-10 18:52:28 +0000987 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
988 int flag = NoteForHelper[i].flag;
989 int index = NoteForHelper[i].index;
Mike Stump08920992009-03-07 02:35:30 +0000990
Mike Stumpb7477cf2009-04-10 18:52:28 +0000991 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
992 || NoteForHelper[i].RequiresCopying) {
993 llvm::Value *Srcv = SrcObj;
994 Srcv = Builder.CreateStructGEP(Srcv, index);
995 Srcv = Builder.CreateBitCast(Srcv,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000996 llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpb7477cf2009-04-10 18:52:28 +0000997 Srcv = Builder.CreateLoad(Srcv);
998
999 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
1000 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
1001
Chris Lattner77b89b82010-06-27 07:15:29 +00001002 llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
Daniel Dunbar673431a2010-07-16 00:00:15 +00001003 llvm::Value *F = CGM.getBlockObjectAssign();
Mike Stumpb7477cf2009-04-10 18:52:28 +00001004 Builder.CreateCall3(F, Dstv, Srcv, N);
1005 }
Mike Stump08920992009-03-07 02:35:30 +00001006 }
1007 }
1008
Mike Stumpa4f668f2009-03-06 01:33:24 +00001009 CGF.FinishFunction();
1010
Owen Anderson3c4972d2009-07-29 18:54:39 +00001011 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +00001012}
1013
Mike Stumpcf62d392009-03-06 18:42:23 +00001014llvm::Constant *BlockFunction::
Mike Stump08920992009-03-07 02:35:30 +00001015GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
1016 const llvm::StructType* T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001017 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stumpa4f668f2009-03-06 01:33:24 +00001018 QualType R = getContext().VoidTy;
1019
1020 FunctionArgList Args;
1021 // FIXME: This leaks
1022 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001023 ImplicitParamDecl::Create(getContext(), 0,
1024 SourceLocation(), 0,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001025 getContext().getPointerType(getContext().VoidTy));
1026
1027 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Mike Stumpa4f668f2009-03-06 01:33:24 +00001029 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001030 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001031
Mike Stump3899a7f2009-06-05 23:26:36 +00001032 // FIXME: We'd like to put these into a mergable by content, with
1033 // internal linkage.
Mike Stumpa4f668f2009-03-06 01:33:24 +00001034 CodeGenTypes &Types = CGM.getTypes();
1035 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1036
1037 llvm::Function *Fn =
1038 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001039 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001040
1041 IdentifierInfo *II
1042 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1043
1044 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1045 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001046 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001047 SC_Static,
1048 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001049 false, true);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001050 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001051
Mike Stumpb7477cf2009-04-10 18:52:28 +00001052 if (NoteForHelperp) {
1053 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
Mike Stump1edf6b62009-03-07 02:53:18 +00001054
Mike Stumpb7477cf2009-04-10 18:52:28 +00001055 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
1056 llvm::Type *PtrPtrT;
Owen Anderson96e0fc72009-07-29 22:16:19 +00001057 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpb7477cf2009-04-10 18:52:28 +00001058 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
1059 SrcObj = Builder.CreateLoad(SrcObj);
Mike Stump1edf6b62009-03-07 02:53:18 +00001060
Mike Stumpb7477cf2009-04-10 18:52:28 +00001061 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
1062 int flag = NoteForHelper[i].flag;
1063 int index = NoteForHelper[i].index;
Mike Stump1edf6b62009-03-07 02:53:18 +00001064
Mike Stumpb7477cf2009-04-10 18:52:28 +00001065 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
1066 || NoteForHelper[i].RequiresCopying) {
1067 llvm::Value *Srcv = SrcObj;
1068 Srcv = Builder.CreateStructGEP(Srcv, index);
1069 Srcv = Builder.CreateBitCast(Srcv,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001070 llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpb7477cf2009-04-10 18:52:28 +00001071 Srcv = Builder.CreateLoad(Srcv);
1072
1073 BuildBlockRelease(Srcv, flag);
1074 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001075 }
1076 }
1077
Mike Stumpa4f668f2009-03-06 01:33:24 +00001078 CGF.FinishFunction();
1079
Owen Anderson3c4972d2009-07-29 18:54:39 +00001080 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001081}
1082
Mike Stump08920992009-03-07 02:35:30 +00001083llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001084 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump08920992009-03-07 02:35:30 +00001085 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1086 T, NoteForHelper);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001087}
1088
Mike Stump08920992009-03-07 02:35:30 +00001089llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001090 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stump08920992009-03-07 02:35:30 +00001091 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001092 T, NoteForHelperp);
Mike Stumpdab514f2009-03-04 03:23:46 +00001093}
Mike Stump797b6322009-03-05 01:23:13 +00001094
Mike Stumpee094222009-03-06 06:12:24 +00001095llvm::Constant *BlockFunction::
1096GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stump45031c02009-03-06 02:29:21 +00001097 QualType R = getContext().VoidTy;
1098
1099 FunctionArgList Args;
1100 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001101 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001102 ImplicitParamDecl::Create(getContext(), 0,
1103 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001104 getContext().getPointerType(getContext().VoidTy));
1105 Args.push_back(std::make_pair(Dst, Dst->getType()));
1106
1107 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001108 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001109 ImplicitParamDecl::Create(getContext(), 0,
1110 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001111 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001112 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Mike Stump45031c02009-03-06 02:29:21 +00001114 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001115 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001116
Mike Stump45031c02009-03-06 02:29:21 +00001117 CodeGenTypes &Types = CGM.getTypes();
1118 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1119
Mike Stump3899a7f2009-06-05 23:26:36 +00001120 // FIXME: We'd like to put these into a mergable by content, with
1121 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001122 llvm::Function *Fn =
1123 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001124 "__Block_byref_id_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001125
1126 IdentifierInfo *II
1127 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1128
1129 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1130 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001131 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001132 SC_Static,
1133 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001134 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001135 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001136
1137 // dst->x
1138 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001139 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001140 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001141 V = Builder.CreateStructGEP(V, 6, "x");
1142 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1143
1144 // src->x
1145 V = CGF.GetAddrOfLocalVar(Src);
1146 V = Builder.CreateLoad(V);
1147 V = Builder.CreateBitCast(V, T);
1148 V = Builder.CreateStructGEP(V, 6, "x");
Owen Anderson96e0fc72009-07-29 22:16:19 +00001149 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpee094222009-03-06 06:12:24 +00001150 llvm::Value *SrcObj = Builder.CreateLoad(V);
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Mike Stumpee094222009-03-06 06:12:24 +00001152 flag |= BLOCK_BYREF_CALLER;
1153
Chris Lattner77b89b82010-06-27 07:15:29 +00001154 llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
Daniel Dunbar673431a2010-07-16 00:00:15 +00001155 llvm::Value *F = CGM.getBlockObjectAssign();
Mike Stumpee094222009-03-06 06:12:24 +00001156 Builder.CreateCall3(F, DstObj, SrcObj, N);
1157
Mike Stump45031c02009-03-06 02:29:21 +00001158 CGF.FinishFunction();
1159
Owen Anderson3c4972d2009-07-29 18:54:39 +00001160 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001161}
1162
Mike Stump1851b682009-03-06 04:53:30 +00001163llvm::Constant *
1164BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1165 int flag) {
Mike Stump45031c02009-03-06 02:29:21 +00001166 QualType R = getContext().VoidTy;
1167
1168 FunctionArgList Args;
1169 // FIXME: This leaks
1170 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001171 ImplicitParamDecl::Create(getContext(), 0,
1172 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001173 getContext().getPointerType(getContext().VoidTy));
1174
1175 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Mike Stump45031c02009-03-06 02:29:21 +00001177 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001178 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001179
Mike Stump45031c02009-03-06 02:29:21 +00001180 CodeGenTypes &Types = CGM.getTypes();
1181 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1182
Mike Stump3899a7f2009-06-05 23:26:36 +00001183 // FIXME: We'd like to put these into a mergable by content, with
1184 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001185 llvm::Function *Fn =
1186 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001187 "__Block_byref_id_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001188 &CGM.getModule());
1189
1190 IdentifierInfo *II
1191 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1192
1193 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1194 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001195 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001196 SC_Static,
1197 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001198 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001199 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001200
1201 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001202 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001203 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001204 V = Builder.CreateStructGEP(V, 6, "x");
Owen Anderson96e0fc72009-07-29 22:16:19 +00001205 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001206 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001207
Mike Stump1851b682009-03-06 04:53:30 +00001208 flag |= BLOCK_BYREF_CALLER;
1209 BuildBlockRelease(V, flag);
Mike Stump45031c02009-03-06 02:29:21 +00001210 CGF.FinishFunction();
1211
Owen Anderson3c4972d2009-07-29 18:54:39 +00001212 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001213}
1214
Mike Stumpee094222009-03-06 06:12:24 +00001215llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
Chris Lattner10976d92009-12-05 08:21:30 +00001216 int Flag, unsigned Align) {
1217 // All alignments below that of pointer alignment collapse down to just
Mike Stump3899a7f2009-06-05 23:26:36 +00001218 // pointer alignment, as we always have at least that much alignment to begin
1219 // with.
1220 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001221
Mike Stump3899a7f2009-06-05 23:26:36 +00001222 // As an optimization, we only generate a single function of each kind we
1223 // might need. We need a different one for each alignment and for each
1224 // setting of flags. We mix Align and flag to get the kind.
Chris Lattner10976d92009-12-05 08:21:30 +00001225 uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1226 llvm::Constant *&Entry = CGM.AssignCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001227 if (Entry)
1228 return Entry;
Chris Lattner10976d92009-12-05 08:21:30 +00001229 return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
Mike Stump45031c02009-03-06 02:29:21 +00001230}
1231
Mike Stump1851b682009-03-06 04:53:30 +00001232llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
Chris Lattner10976d92009-12-05 08:21:30 +00001233 int Flag,
Mike Stump3899a7f2009-06-05 23:26:36 +00001234 unsigned Align) {
1235 // All alignments below that of pointer alignment collpase down to just
1236 // pointer alignment, as we always have at least that much alignment to begin
1237 // with.
1238 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001239
Mike Stump3899a7f2009-06-05 23:26:36 +00001240 // As an optimization, we only generate a single function of each kind we
1241 // might need. We need a different one for each alignment and for each
1242 // setting of flags. We mix Align and flag to get the kind.
Chris Lattner10976d92009-12-05 08:21:30 +00001243 uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1244 llvm::Constant *&Entry = CGM.DestroyCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001245 if (Entry)
1246 return Entry;
Chris Lattner10976d92009-12-05 08:21:30 +00001247 return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
Mike Stump45031c02009-03-06 02:29:21 +00001248}
1249
Mike Stump1851b682009-03-06 04:53:30 +00001250void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001251 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001252 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001253 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Chris Lattner77b89b82010-06-27 07:15:29 +00001254 N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
Mike Stump797b6322009-03-05 01:23:13 +00001255 Builder.CreateCall2(F, V, N);
1256}
Mike Stump00470a12009-03-05 08:32:30 +00001257
1258ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001259
1260BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1261 CGBuilderTy &B)
Chris Lattner77b89b82010-06-27 07:15:29 +00001262 : CGM(cgm), VMContext(cgm.getLLVMContext()), CGF(cgf), Builder(B) {
Owen Anderson0032b272009-08-13 21:57:51 +00001263 PtrToInt8Ty = llvm::PointerType::getUnqual(
1264 llvm::Type::getInt8Ty(VMContext));
Mike Stump08920992009-03-07 02:35:30 +00001265
1266 BlockHasCopyDispose = false;
1267}