blob: f38c04bcc43031eb660dcbee8ceeed33017ed9f6 [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
John McCallee504292010-05-21 04:11:14 +0000114static void CollectBlockDeclRefInfo(const Stmt *S, CGBlockInfo &Info) {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000115 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
116 I != E; ++I)
Daniel Dunbar82573ee2009-03-02 07:00:57 +0000117 if (*I)
John McCallee504292010-05-21 04:11:14 +0000118 CollectBlockDeclRefInfo(*I, Info);
Mike Stump00470a12009-03-05 08:32:30 +0000119
Mike Stumpea26cb52009-10-21 03:49:08 +0000120 // We want to ensure we walk down into block literals so we can find
121 // all nested BlockDeclRefExprs.
Mike Stump38e16272009-10-21 22:01:24 +0000122 if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallee504292010-05-21 04:11:14 +0000123 Info.InnerBlocks.insert(BE->getBlockDecl());
124 CollectBlockDeclRefInfo(BE->getBody(), Info);
Mike Stump38e16272009-10-21 22:01:24 +0000125 }
Mike Stumpea26cb52009-10-21 03:49:08 +0000126
John McCallee504292010-05-21 04:11:14 +0000127 else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
128 const ValueDecl *D = BDRE->getDecl();
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000129 // FIXME: Handle enums.
John McCallee504292010-05-21 04:11:14 +0000130 if (isa<FunctionDecl>(D))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000131 return;
Mike Stump00470a12009-03-05 08:32:30 +0000132
John McCallee504292010-05-21 04:11:14 +0000133 if (isa<ImplicitParamDecl>(D) &&
134 isa<ObjCMethodDecl>(D->getDeclContext()) &&
135 cast<ObjCMethodDecl>(D->getDeclContext())->getSelfDecl() == D) {
136 Info.NeedsObjCSelf = true;
137 return;
138 }
139
Mike Stump38e16272009-10-21 22:01:24 +0000140 // Only Decls that escape are added.
John McCallee504292010-05-21 04:11:14 +0000141 if (!Info.InnerBlocks.count(D->getDeclContext()))
Mike Stump38e16272009-10-21 22:01:24 +0000142 Info.DeclRefs.push_back(BDRE);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000143 }
John McCallea1471e2010-05-20 01:18:31 +0000144
John McCallee504292010-05-21 04:11:14 +0000145 // Make sure to capture implicit 'self' references due to super calls.
Chandler Carruthf54b80f2010-05-21 10:29:28 +0000146 else if (const ObjCMessageExpr *E = dyn_cast<ObjCMessageExpr>(S)) {
John McCallee504292010-05-21 04:11:14 +0000147 if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
148 E->getReceiverKind() == ObjCMessageExpr::SuperInstance)
149 Info.NeedsObjCSelf = true;
Chandler Carruthf54b80f2010-05-21 10:29:28 +0000150 }
John McCallee504292010-05-21 04:11:14 +0000151
152 // Getter/setter uses may also cause implicit super references,
153 // which we can check for with:
154 else if (isa<ObjCSuperExpr>(S))
155 Info.NeedsObjCSelf = true;
156
157 else if (isa<CXXThisExpr>(S))
John McCallea1471e2010-05-20 01:18:31 +0000158 Info.CXXThisRef = cast<CXXThisExpr>(S);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000159}
160
John McCallee504292010-05-21 04:11:14 +0000161/// CanBlockBeGlobal - Given a CGBlockInfo struct, determines if a block can be
Mike Stump58a85142009-03-04 22:48:06 +0000162/// declared as a global variable instead of on the stack.
John McCallee504292010-05-21 04:11:14 +0000163static bool CanBlockBeGlobal(const CGBlockInfo &Info) {
Mike Stumpea26cb52009-10-21 03:49:08 +0000164 return Info.DeclRefs.empty();
165}
166
167/// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
168/// ensure we can generate the debug information for the parameter for the block
169/// invoke function.
John McCallee504292010-05-21 04:11:14 +0000170static void AllocateAllBlockDeclRefs(CodeGenFunction &CGF, CGBlockInfo &Info) {
John McCallea1471e2010-05-20 01:18:31 +0000171 if (Info.CXXThisRef)
John McCallee504292010-05-21 04:11:14 +0000172 CGF.AllocateBlockCXXThisPointer(Info.CXXThisRef);
Mike Stumpea26cb52009-10-21 03:49:08 +0000173
174 for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
John McCallee504292010-05-21 04:11:14 +0000175 CGF.AllocateBlockDecl(Info.DeclRefs[i]);
176
177 if (Info.NeedsObjCSelf) {
178 ValueDecl *Self = cast<ObjCMethodDecl>(CGF.CurFuncDecl)->getSelfDecl();
179 BlockDeclRefExpr *BDRE =
180 new (CGF.getContext()) BlockDeclRefExpr(Self, Self->getType(),
181 SourceLocation(), false);
182 Info.DeclRefs.push_back(BDRE);
183 CGF.AllocateBlockDecl(BDRE);
184 }
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000185}
186
Mike Stump58a85142009-03-04 22:48:06 +0000187// FIXME: Push most into CGM, passing down a few bits, like current function
188// name.
Mike Stump8a2b4b12009-02-25 23:33:13 +0000189llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000190 std::string Name = CurFn->getName();
John McCallee504292010-05-21 04:11:14 +0000191 CGBlockInfo Info(Name.c_str());
192 Info.InnerBlocks.insert(BE->getBlockDecl());
193 CollectBlockDeclRefInfo(BE->getBody(), Info);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000194
195 // Check if the block can be global.
Mike Stump58a85142009-03-04 22:48:06 +0000196 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
197 // to just have one code path. We should move this function into CGM and pass
198 // CGF, then we can just check to see if CGF is 0.
Mike Stumpdab514f2009-03-04 03:23:46 +0000199 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000200 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump00470a12009-03-05 08:32:30 +0000201
David Chisnall5e530af2009-11-17 19:33:30 +0000202 size_t BlockFields = 5;
203
David Chisnall5e530af2009-11-17 19:33:30 +0000204 std::vector<llvm::Constant*> Elts(BlockFields);
205
Mike Stumpe5fee252009-02-13 16:19:19 +0000206 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000207 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000208
Mike Stumpe5fee252009-02-13 16:19:19 +0000209 {
210 // C = BuildBlockStructInitlist();
Blaine Garsta36e2232010-03-05 01:29:59 +0000211 unsigned int flags = BLOCK_HAS_SIGNATURE;
David Chisnall5e530af2009-11-17 19:33:30 +0000212
Mike Stump00470a12009-03-05 08:32:30 +0000213 // We run this first so that we set BlockHasCopyDispose from the entire
214 // block literal.
215 // __invoke
Mike Stump00470a12009-03-05 08:32:30 +0000216 llvm::Function *Fn
Fariborz Jahanian564360b2010-06-24 00:08:06 +0000217 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, BE, Info, CurFuncDecl,
John McCallee504292010-05-21 04:11:14 +0000218 LocalDeclMap);
219 BlockHasCopyDispose |= Info.BlockHasCopyDispose;
Mike Stump00470a12009-03-05 08:32:30 +0000220 Elts[3] = Fn;
221
Mike Stumpf5408fe2009-05-16 07:57:57 +0000222 // FIXME: Don't use BlockHasCopyDispose, it is set more often then
223 // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
John McCallee504292010-05-21 04:11:14 +0000224 if (Info.BlockHasCopyDispose)
Mike Stumpe5fee252009-02-13 16:19:19 +0000225 flags |= BLOCK_HAS_COPY_DISPOSE;
226
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000227 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000228 C = CGM.getNSConcreteStackBlock();
Owen Anderson3c4972d2009-07-29 18:54:39 +0000229 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump00470a12009-03-05 08:32:30 +0000230 Elts[0] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000231
232 // __flags
Blaine Garsta36e2232010-03-05 01:29:59 +0000233 {
234 QualType BPT = BE->getType();
235 const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
236 QualType ResultType = ftype->getResultType();
237
238 CallArgList Args;
239 CodeGenTypes &Types = CGM.getTypes();
240 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000241 FunctionType::ExtInfo());
Daniel Dunbardacf9dd2010-07-14 23:39:36 +0000242 if (CGM.ReturnTypeUsesSRet(FnInfo))
Blaine Garsta36e2232010-03-05 01:29:59 +0000243 flags |= BLOCK_USE_STRET;
244 }
Mike Stumpe5fee252009-02-13 16:19:19 +0000245 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
246 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000247 C = llvm::ConstantInt::get(IntTy, flags);
Mike Stump00470a12009-03-05 08:32:30 +0000248 Elts[1] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000249
250 // __reserved
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000251 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump00470a12009-03-05 08:32:30 +0000252 Elts[2] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000253
John McCallee504292010-05-21 04:11:14 +0000254 if (Info.BlockLayout.empty()) {
Mike Stumpcf62d392009-03-06 18:42:23 +0000255 // __descriptor
John McCallee504292010-05-21 04:11:14 +0000256 Elts[4] = BuildDescriptorBlockDecl(BE, Info.BlockHasCopyDispose,
257 Info.BlockSize, 0, 0);
Mike Stumpcf62d392009-03-06 18:42:23 +0000258
Mike Stump5570cfe2009-03-01 20:07:53 +0000259 // Optimize to being a global block.
260 Elts[0] = CGM.getNSConcreteGlobalBlock();
Blaine Garsta36e2232010-03-05 01:29:59 +0000261
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000262 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
Mike Stump5570cfe2009-03-01 20:07:53 +0000263
Nick Lewycky0d36dd22009-09-19 20:00:52 +0000264 C = llvm::ConstantStruct::get(VMContext, Elts, false);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000265
Owen Anderson1c431b32009-07-08 19:05:04 +0000266 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +0000267 llvm::GlobalValue::InternalLinkage, C,
268 "__block_holder_tmp_" +
269 llvm::Twine(CGM.getGlobalUniqueCount()));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000270 QualType BPT = BE->getType();
Owen Anderson3c4972d2009-07-29 18:54:39 +0000271 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000272 return C;
273 }
Mike Stump00470a12009-03-05 08:32:30 +0000274
John McCallee504292010-05-21 04:11:14 +0000275 std::vector<const llvm::Type *> Types(BlockFields+Info.BlockLayout.size());
Mike Stump08920992009-03-07 02:35:30 +0000276 for (int i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000277 Types[i] = Elts[i]->getType();
Mike Stump08920992009-03-07 02:35:30 +0000278 Types[4] = PtrToInt8Ty;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000279
John McCallee504292010-05-21 04:11:14 +0000280 for (unsigned i = 0, n = Info.BlockLayout.size(); i != n; ++i) {
281 const Expr *E = Info.BlockLayout[i];
Mike Stumpa99038c2009-02-28 09:07:16 +0000282 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
283 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000284 if (BDRE && BDRE->isByRef()) {
Fariborz Jahanian79651722010-06-02 21:35:17 +0000285 Types[i+BlockFields] =
286 llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
287 } else if (BDRE && BDRE->getDecl()->getType()->isReferenceType()) {
288 Types[i+BlockFields] = llvm::PointerType::get(ConvertType(Ty), 0);
289 } else
David Chisnall5e530af2009-11-17 19:33:30 +0000290 Types[i+BlockFields] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000291 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000292
Owen Anderson47a434f2009-08-05 23:18:46 +0000293 llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000294
295 llvm::AllocaInst *A = CreateTempAlloca(Ty);
John McCallee504292010-05-21 04:11:14 +0000296 A->setAlignment(Info.BlockAlign.getQuantity());
Mike Stump8a2b4b12009-02-25 23:33:13 +0000297 V = A;
298
John McCallea1471e2010-05-20 01:18:31 +0000299 // Build layout / cleanup information for all the data entries in the
300 // layout, and write the enclosing fields into the type.
John McCallee504292010-05-21 04:11:14 +0000301 std::vector<HelperInfo> NoteForHelper(Info.BlockLayout.size());
John McCallea1471e2010-05-20 01:18:31 +0000302 unsigned NumHelpers = 0;
Mike Stump08920992009-03-07 02:35:30 +0000303
304 for (unsigned i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000305 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump00470a12009-03-05 08:32:30 +0000306
John McCallee504292010-05-21 04:11:14 +0000307 for (unsigned i=0; i < Info.BlockLayout.size(); ++i) {
308 const Expr *E = Info.BlockLayout[i];
Mike Stump8a2b4b12009-02-25 23:33:13 +0000309
John McCallea1471e2010-05-20 01:18:31 +0000310 // Skip padding.
311 if (isa<DeclRefExpr>(E)) continue;
Mike Stumpa99038c2009-02-28 09:07:16 +0000312
John McCallea1471e2010-05-20 01:18:31 +0000313 llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
314 HelperInfo &Note = NoteForHelper[NumHelpers++];
Mike Stumpa99038c2009-02-28 09:07:16 +0000315
John McCallea1471e2010-05-20 01:18:31 +0000316 Note.index = i+5;
Mike Stump08920992009-03-07 02:35:30 +0000317
John McCallea1471e2010-05-20 01:18:31 +0000318 if (isa<CXXThisExpr>(E)) {
319 Note.RequiresCopying = false;
320 Note.flag = BLOCK_FIELD_IS_OBJECT;
Mike Stumpa99038c2009-02-28 09:07:16 +0000321
John McCallea1471e2010-05-20 01:18:31 +0000322 Builder.CreateStore(LoadCXXThis(), Addr);
323 continue;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000324 }
John McCallea1471e2010-05-20 01:18:31 +0000325
326 const BlockDeclRefExpr *BDRE = cast<BlockDeclRefExpr>(E);
327 const ValueDecl *VD = BDRE->getDecl();
328 QualType T = VD->getType();
329
330 Note.RequiresCopying = BlockRequiresCopying(T);
331
332 if (BDRE->isByRef()) {
333 Note.flag = BLOCK_FIELD_IS_BYREF;
334 if (T.isObjCGCWeak())
335 Note.flag |= BLOCK_FIELD_IS_WEAK;
336 } else if (T->isBlockPointerType()) {
337 Note.flag = BLOCK_FIELD_IS_BLOCK;
338 } else {
339 Note.flag = BLOCK_FIELD_IS_OBJECT;
340 }
341
342 if (LocalDeclMap[VD]) {
343 if (BDRE->isByRef()) {
344 llvm::Value *Loc = LocalDeclMap[VD];
345 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
346 Loc = Builder.CreateLoad(Loc);
347 Builder.CreateStore(Loc, Addr);
348 continue;
349 } else {
Fariborz Jahanianac7362d2010-06-08 20:57:22 +0000350 if (BDRE->getCopyConstructorExpr()) {
351 E = BDRE->getCopyConstructorExpr();
John McCallf1549f62010-07-06 01:34:17 +0000352 PushDestructorCleanup(E->getType(), Addr);
Fariborz Jahanianac7362d2010-06-08 20:57:22 +0000353 }
Fariborz Jahanian59da45a2010-06-04 21:35:44 +0000354 else {
355 E = new (getContext()) DeclRefExpr(const_cast<ValueDecl*>(VD),
Fariborz Jahanian79651722010-06-02 21:35:17 +0000356 VD->getType().getNonReferenceType(),
357 SourceLocation());
Fariborz Jahanian59da45a2010-06-04 21:35:44 +0000358 if (VD->getType()->isReferenceType()) {
359 E = new (getContext())
360 UnaryOperator(const_cast<Expr*>(E), UnaryOperator::AddrOf,
361 getContext().getPointerType(E->getType()),
362 SourceLocation());
363 }
Fariborz Jahaniandf8b8ea2010-06-04 16:10:00 +0000364 }
365 }
John McCallea1471e2010-05-20 01:18:31 +0000366 }
John McCallea1471e2010-05-20 01:18:31 +0000367
368 if (BDRE->isByRef()) {
369 E = new (getContext())
370 UnaryOperator(const_cast<Expr*>(E), UnaryOperator::AddrOf,
371 getContext().getPointerType(E->getType()),
372 SourceLocation());
373 }
374
375 RValue r = EmitAnyExpr(E, Addr, false);
376 if (r.isScalar()) {
377 llvm::Value *Loc = r.getScalarVal();
378 const llvm::Type *Ty = Types[i+BlockFields];
379 if (BDRE->isByRef()) {
380 // E is now the address of the value field, instead, we want the
381 // address of the actual ByRef struct. We optimize this slightly
382 // compared to gcc by not grabbing the forwarding slot as this must
383 // be done during Block_copy for us, and we can postpone the work
384 // until then.
385 CharUnits offset = BlockDecls[BDRE->getDecl()];
386
387 llvm::Value *BlockLiteral = LoadBlockStruct();
388
389 Loc = Builder.CreateGEP(BlockLiteral,
Chris Lattner77b89b82010-06-27 07:15:29 +0000390 llvm::ConstantInt::get(Int64Ty, offset.getQuantity()),
John McCallea1471e2010-05-20 01:18:31 +0000391 "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) {
Fariborz Jahaniandf8b8ea2010-06-04 16:10:00 +0000602
John McCallea1471e2010-05-20 01:18:31 +0000603 CharUnits offset = BlockDecls[VD];
604 assert(!offset.isZero() && "getting address of unallocated decl");
Mike Stumpdab514f2009-03-04 03:23:46 +0000605
606 llvm::Value *BlockLiteral = LoadBlockStruct();
607 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
Chris Lattner77b89b82010-06-27 07:15:29 +0000608 llvm::ConstantInt::get(Int64Ty, 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());
Owen Anderson96e0fc72009-07-29 22:16:19 +0000629 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000630 V = Builder.CreateBitCast(V, Ty);
Fariborz Jahanian79651722010-06-02 21:35:17 +0000631 if (VD->getType()->isReferenceType())
Fariborz Jahaniandf8b8ea2010-06-04 16:10:00 +0000632 V = Builder.CreateLoad(V, "ref.tmp");
Mike Stumpdab514f2009-03-04 03:23:46 +0000633 }
634 return V;
635}
636
Mike Stump67a64482009-02-14 22:16:35 +0000637llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000638BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000639 // Generate the block descriptor.
640 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000641 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
642 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000643
Blaine Garst2a7eb282010-02-23 21:51:17 +0000644 llvm::Constant *DescriptorFields[4];
Mike Stumpa5448542009-02-13 15:32:32 +0000645
Anders Carlssond5cab542009-02-12 17:55:02 +0000646 // Reserved
Owen Andersonc9c88b42009-07-31 20:28:54 +0000647 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000648
Anders Carlssond5cab542009-02-12 17:55:02 +0000649 // Block literal size. For global blocks we just use the size of the generic
650 // block literal struct.
Ken Dyck687cc4a2010-01-26 13:48:07 +0000651 CharUnits BlockLiteralSize =
652 CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
Owen Andersona1cf15f2009-07-14 23:10:40 +0000653 DescriptorFields[1] =
Ken Dyck199c3d62010-01-11 17:06:35 +0000654 llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
Blaine Garst2a7eb282010-02-23 21:51:17 +0000655
656 // signature. non-optional ObjC-style method descriptor @encode sequence
657 std::string BlockTypeEncoding;
658 CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
Mike Stumpa5448542009-02-13 15:32:32 +0000659
Blaine Garst2a7eb282010-02-23 21:51:17 +0000660 DescriptorFields[2] = llvm::ConstantExpr::getBitCast(
661 CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
662
663 // layout
664 DescriptorFields[3] =
665 llvm::ConstantInt::get(UnsignedLongTy,0);
666
667 // build the structure from the 4 elements
Mike Stumpa5448542009-02-13 15:32:32 +0000668 llvm::Constant *DescriptorStruct =
Blaine Garst2a7eb282010-02-23 21:51:17 +0000669 llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false);
Mike Stumpa5448542009-02-13 15:32:32 +0000670
Anders Carlssond5cab542009-02-12 17:55:02 +0000671 llvm::GlobalVariable *Descriptor =
Owen Anderson1c431b32009-07-08 19:05:04 +0000672 new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000673 llvm::GlobalVariable::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000674 DescriptorStruct, "__block_descriptor_global");
Mike Stumpa5448542009-02-13 15:32:32 +0000675
David Chisnall5e530af2009-11-17 19:33:30 +0000676 int FieldCount = 5;
Anders Carlssond5cab542009-02-12 17:55:02 +0000677 // Generate the constants for the block literal.
David Chisnall5e530af2009-11-17 19:33:30 +0000678
679 std::vector<llvm::Constant*> LiteralFields(FieldCount);
Mike Stumpa5448542009-02-13 15:32:32 +0000680
John McCallee504292010-05-21 04:11:14 +0000681 CGBlockInfo Info(n);
Mike Stump7f28a9c2009-03-13 23:34:28 +0000682 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000683 llvm::Function *Fn
Fariborz Jahanian564360b2010-06-24 00:08:06 +0000684 = CodeGenFunction(CGM).GenerateBlockFunction(GlobalDecl(), BE, Info, 0, LocalDeclMap);
John McCallee504292010-05-21 04:11:14 +0000685 assert(Info.BlockSize == BlockLiteralSize
Mike Stump4e7a1f72009-02-21 20:00:35 +0000686 && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000687
Anders Carlssond5cab542009-02-12 17:55:02 +0000688 // isa
Daniel Dunbar673431a2010-07-16 00:00:15 +0000689 LiteralFields[0] = CGM.getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000690
Anders Carlssond5cab542009-02-12 17:55:02 +0000691 // Flags
Blaine Garst2a7eb282010-02-23 21:51:17 +0000692 LiteralFields[1] =
Blaine Garsta36e2232010-03-05 01:29:59 +0000693 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
Mike Stumpa5448542009-02-13 15:32:32 +0000694
Anders Carlssond5cab542009-02-12 17:55:02 +0000695 // Reserved
Owen Andersonc9c88b42009-07-31 20:28:54 +0000696 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000697
Anders Carlssond5cab542009-02-12 17:55:02 +0000698 // Function
699 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000700
Anders Carlssond5cab542009-02-12 17:55:02 +0000701 // Descriptor
702 LiteralFields[4] = Descriptor;
David Chisnall5e530af2009-11-17 19:33:30 +0000703
Mike Stumpa5448542009-02-13 15:32:32 +0000704 llvm::Constant *BlockLiteralStruct =
David Chisnall5e530af2009-11-17 19:33:30 +0000705 llvm::ConstantStruct::get(VMContext, LiteralFields, false);
Mike Stumpa5448542009-02-13 15:32:32 +0000706
707 llvm::GlobalVariable *BlockLiteral =
Owen Anderson1c431b32009-07-08 19:05:04 +0000708 new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000709 llvm::GlobalVariable::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000710 BlockLiteralStruct, "__block_literal_global");
Mike Stumpa5448542009-02-13 15:32:32 +0000711
Anders Carlssond5cab542009-02-12 17:55:02 +0000712 return BlockLiteral;
713}
714
Mike Stump4e7a1f72009-02-21 20:00:35 +0000715llvm::Value *CodeGenFunction::LoadBlockStruct() {
Mike Stumpbf1914b2009-10-20 20:30:01 +0000716 llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
717 "self");
718 // For now, we codegen based upon byte offsets.
719 return Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000720}
721
Mike Stump00470a12009-03-05 08:32:30 +0000722llvm::Function *
Fariborz Jahanian564360b2010-06-24 00:08:06 +0000723CodeGenFunction::GenerateBlockFunction(GlobalDecl GD, const BlockExpr *BExpr,
John McCallee504292010-05-21 04:11:14 +0000724 CGBlockInfo &Info,
Mike Stump6cc88f72009-03-20 21:53:12 +0000725 const Decl *OuterFuncDecl,
John McCallee504292010-05-21 04:11:14 +0000726 llvm::DenseMap<const Decl*, llvm::Value*> ldm) {
Devang Patel963dfbd2009-04-15 21:51:44 +0000727
728 // Check if we should generate debug info for this block.
729 if (CGM.getDebugInfo())
730 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Mike Stump7f28a9c2009-03-13 23:34:28 +0000732 // Arrange for local static and local extern declarations to appear
733 // to be local to this function as well, as they are directly referenced
734 // in a block.
735 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
736 i != ldm.end();
737 ++i) {
738 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000740 if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
Mike Stump7f28a9c2009-03-13 23:34:28 +0000741 LocalDeclMap[VD] = i->second;
742 }
743
Ken Dyck687cc4a2010-01-26 13:48:07 +0000744 BlockOffset =
745 CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
Ken Dyck30a8a272010-01-26 19:13:33 +0000746 BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
Eli Friedman48f91222009-03-28 03:24:54 +0000747
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000748 const FunctionType *BlockFunctionType = BExpr->getFunctionType();
749 QualType ResultType;
Rafael Espindola264ba482010-03-30 20:24:48 +0000750 FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType);
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000751 bool IsVariadic;
Mike Stump1eb44332009-09-09 15:08:12 +0000752 if (const FunctionProtoType *FTy =
Fariborz Jahanianda0895d2009-04-11 18:54:57 +0000753 dyn_cast<FunctionProtoType>(BlockFunctionType)) {
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000754 ResultType = FTy->getResultType();
755 IsVariadic = FTy->isVariadic();
Mike Stumpb3589f42009-07-30 22:28:39 +0000756 } else {
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000757 // K&R style block.
758 ResultType = BlockFunctionType->getResultType();
759 IsVariadic = false;
760 }
Mike Stumpa5448542009-02-13 15:32:32 +0000761
Anders Carlssond5cab542009-02-12 17:55:02 +0000762 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000763
Mike Stumpea26cb52009-10-21 03:49:08 +0000764 CurFuncDecl = OuterFuncDecl;
765
Chris Lattner161d36d2009-02-28 19:01:03 +0000766 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000767
Mike Stumpea26cb52009-10-21 03:49:08 +0000768 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000769
John McCallea1471e2010-05-20 01:18:31 +0000770 // Build the block struct now.
John McCallee504292010-05-21 04:11:14 +0000771 AllocateAllBlockDeclRefs(*this, Info);
Mike Stumpea26cb52009-10-21 03:49:08 +0000772
Mike Stump083c25e2009-10-22 00:49:09 +0000773 QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +0000774 BlockLayout);
775
Anders Carlssond5cab542009-02-12 17:55:02 +0000776 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000777 ImplicitParamDecl *SelfDecl =
John McCall2888b652010-04-30 21:35:41 +0000778 ImplicitParamDecl::Create(getContext(), const_cast<BlockDecl*>(BD),
Mike Stumpadaaad32009-10-20 02:12:22 +0000779 SourceLocation(), II,
780 ParmTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000781
Anders Carlssond5cab542009-02-12 17:55:02 +0000782 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000783 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000784
Steve Naroffe78b8092009-03-13 16:56:44 +0000785 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000786 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000787 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000788
789 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +0000790 CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo);
Anders Carlssond5cab542009-02-12 17:55:02 +0000791
Anders Carlssond5cab542009-02-12 17:55:02 +0000792 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000793 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
Mike Stumpa5448542009-02-13 15:32:32 +0000794
Douglas Gregor35415f52010-05-25 17:04:15 +0000795 MangleBuffer Name;
Fariborz Jahanian564360b2010-06-24 00:08:06 +0000796 CGM.getMangledName(GD, Name, BD);
Mike Stumpa5448542009-02-13 15:32:32 +0000797 llvm::Function *Fn =
Douglas Gregor6e5d9b02010-05-25 17:12:30 +0000798 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
799 Name.getString(), &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000800
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000801 CGM.SetInternalFunctionAttributes(BD, Fn, FI);
802
Fariborz Jahanian16ac5ce2010-06-28 18:58:34 +0000803 QualType FnType(BlockFunctionType, 0);
Fariborz Jahanianef160b42010-06-28 19:42:10 +0000804 bool HasPrototype = isa<FunctionProtoType>(BlockFunctionType);
Fariborz Jahanian16ac5ce2010-06-28 18:58:34 +0000805
806 IdentifierInfo *ID = &getContext().Idents.get(Name.getString());
807 CurCodeDecl = FunctionDecl::Create(getContext(),
808 getContext().getTranslationUnitDecl(),
809 SourceLocation(), ID, FnType,
810 0,
811 FunctionDecl::Static,
812 FunctionDecl::None,
813 false, HasPrototype);
814
Chris Lattner4863db42009-04-23 07:18:56 +0000815 StartFunction(BD, ResultType, Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000816 BExpr->getBody()->getLocEnd());
Mike Stumpb1a6e682009-09-30 02:43:10 +0000817
Chris Lattner4863db42009-04-23 07:18:56 +0000818 CurFuncDecl = OuterFuncDecl;
Mike Stumpb289b3f2009-10-01 22:29:41 +0000819
John McCallea1471e2010-05-20 01:18:31 +0000820 // If we have a C++ 'this' reference, go ahead and force it into
821 // existence now.
822 if (Info.CXXThisRef) {
823 assert(!BlockCXXThisOffset.isZero() &&
824 "haven't yet allocated 'this' reference");
825
826 // TODO: I have a dream that one day this will be typed.
827 llvm::Value *BlockLiteral = LoadBlockStruct();
828 llvm::Value *ThisPtrRaw =
829 Builder.CreateConstInBoundsGEP1_64(BlockLiteral,
830 BlockCXXThisOffset.getQuantity(),
831 "this.ptr.raw");
832
833 const llvm::Type *Ty =
834 CGM.getTypes().ConvertType(Info.CXXThisRef->getType());
835 Ty = llvm::PointerType::get(Ty, 0);
836 llvm::Value *ThisPtr = Builder.CreateBitCast(ThisPtrRaw, Ty, "this.ptr");
837
838 CXXThisValue = Builder.CreateLoad(ThisPtr, "this");
839 }
840
John McCallee504292010-05-21 04:11:14 +0000841 // If we have an Objective C 'self' reference, go ahead and force it
842 // into existence now.
843 if (Info.NeedsObjCSelf) {
844 ValueDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
845 LocalDeclMap[Self] = GetAddrOfBlockDecl(Self, false);
846 }
847
Mike Stumpb289b3f2009-10-01 22:29:41 +0000848 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
849 llvm::BasicBlock *entry = Builder.GetInsertBlock();
850 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
851 --entry_ptr;
852
Chris Lattner161d36d2009-02-28 19:01:03 +0000853 EmitStmt(BExpr->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000854
Mike Stumpde8c5c72009-10-01 00:27:30 +0000855 // Remember where we were...
856 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000857
Mike Stumpde8c5c72009-10-01 00:27:30 +0000858 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000859 ++entry_ptr;
860 Builder.SetInsertPoint(entry, entry_ptr);
861
Mike Stumpb1a6e682009-09-30 02:43:10 +0000862 if (CGDebugInfo *DI = getDebugInfo()) {
Mike Stumpb1a6e682009-09-30 02:43:10 +0000863 // Emit debug information for all the BlockDeclRefDecls.
John McCallea1471e2010-05-20 01:18:31 +0000864 // FIXME: also for 'this'
865 for (unsigned i = 0, e = BlockLayout.size(); i != e; ++i) {
866 if (const BlockDeclRefExpr *BDRE =
867 dyn_cast<BlockDeclRefExpr>(BlockLayout[i])) {
Mike Stumpb1a6e682009-09-30 02:43:10 +0000868 const ValueDecl *D = BDRE->getDecl();
869 DI->setLocation(D->getLocation());
870 DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
871 LocalDeclMap[getBlockStructDecl()],
872 Builder, this);
873 }
874 }
Mike Stumpb1a6e682009-09-30 02:43:10 +0000875 }
Mike Stumpde8c5c72009-10-01 00:27:30 +0000876 // And resume where we left off.
877 if (resume == 0)
878 Builder.ClearInsertionPoint();
879 else
880 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +0000881
Chris Lattner161d36d2009-02-28 19:01:03 +0000882 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000883
Mike Stump8a2b4b12009-02-25 23:33:13 +0000884 // The runtime needs a minimum alignment of a void *.
Ken Dyck30a8a272010-01-26 19:13:33 +0000885 CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
Ken Dyck199c3d62010-01-11 17:06:35 +0000886 BlockOffset = CharUnits::fromQuantity(
Ken Dyck30a8a272010-01-26 19:13:33 +0000887 llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
888 MinAlign.getQuantity()));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000889
John McCallee504292010-05-21 04:11:14 +0000890 Info.BlockSize = BlockOffset;
891 Info.BlockAlign = BlockAlign;
892 Info.BlockLayout = BlockLayout;
893 Info.BlockHasCopyDispose = BlockHasCopyDispose;
Anders Carlssond5cab542009-02-12 17:55:02 +0000894 return Fn;
895}
Mike Stumpa99038c2009-02-28 09:07:16 +0000896
John McCallea1471e2010-05-20 01:18:31 +0000897CharUnits BlockFunction::getBlockOffset(CharUnits Size, CharUnits Align) {
898 assert((Align.isPositive()) && "alignment must be 1 byte or more");
Mike Stumpa99038c2009-02-28 09:07:16 +0000899
Ken Dyck199c3d62010-01-11 17:06:35 +0000900 CharUnits OldOffset = BlockOffset;
Mike Stumpa99038c2009-02-28 09:07:16 +0000901
902 // Ensure proper alignment, even if it means we have to have a gap
Ken Dyck199c3d62010-01-11 17:06:35 +0000903 BlockOffset = CharUnits::fromQuantity(
Ken Dyck30a8a272010-01-26 19:13:33 +0000904 llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
Mike Stumpa99038c2009-02-28 09:07:16 +0000905 BlockAlign = std::max(Align, BlockAlign);
Mike Stump00470a12009-03-05 08:32:30 +0000906
Ken Dyck199c3d62010-01-11 17:06:35 +0000907 CharUnits Pad = BlockOffset - OldOffset;
908 if (Pad.isPositive()) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000909 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000910 llvm::APInt(32,
911 Pad.getQuantity()),
Mike Stumpa99038c2009-02-28 09:07:16 +0000912 ArrayType::Normal, 0);
Douglas Gregorba55ec22010-05-11 18:17:16 +0000913 ValueDecl *PadDecl = VarDecl::Create(getContext(),
914 getContext().getTranslationUnitDecl(),
915 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +0000916 0, QualType(PadTy), 0,
917 VarDecl::None, VarDecl::None);
John McCallea1471e2010-05-20 01:18:31 +0000918 Expr *E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
919 SourceLocation());
920 BlockLayout.push_back(E);
Mike Stumpa99038c2009-02-28 09:07:16 +0000921 }
Mike Stumpa99038c2009-02-28 09:07:16 +0000922
923 BlockOffset += Size;
John McCallea1471e2010-05-20 01:18:31 +0000924 return BlockOffset - Size;
Mike Stumpa99038c2009-02-28 09:07:16 +0000925}
Mike Stumpdab514f2009-03-04 03:23:46 +0000926
Mike Stump08920992009-03-07 02:35:30 +0000927llvm::Constant *BlockFunction::
928GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +0000929 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000930 QualType R = getContext().VoidTy;
931
932 FunctionArgList Args;
933 // FIXME: This leaks
Mike Stump08920992009-03-07 02:35:30 +0000934 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +0000935 ImplicitParamDecl::Create(getContext(), 0,
936 SourceLocation(), 0,
Mike Stump08920992009-03-07 02:35:30 +0000937 getContext().getPointerType(getContext().VoidTy));
938 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000939 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +0000940 ImplicitParamDecl::Create(getContext(), 0,
941 SourceLocation(), 0,
Mike Stumpa4f668f2009-03-06 01:33:24 +0000942 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000943 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Mike Stumpa4f668f2009-03-06 01:33:24 +0000945 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +0000946 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +0000947
Mike Stump3899a7f2009-06-05 23:26:36 +0000948 // FIXME: We'd like to put these into a mergable by content, with
949 // internal linkage.
Mike Stumpa4f668f2009-03-06 01:33:24 +0000950 CodeGenTypes &Types = CGM.getTypes();
951 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
952
953 llvm::Function *Fn =
954 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +0000955 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +0000956
957 IdentifierInfo *II
958 = &CGM.getContext().Idents.get("__copy_helper_block_");
959
960 FunctionDecl *FD = FunctionDecl::Create(getContext(),
961 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000962 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000963 FunctionDecl::Static,
964 FunctionDecl::None,
965 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +0000966 true);
967 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +0000968
969 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
970 llvm::Type *PtrPtrT;
Mike Stump08920992009-03-07 02:35:30 +0000971
Mike Stumpb7477cf2009-04-10 18:52:28 +0000972 if (NoteForHelperp) {
973 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
Mike Stump08920992009-03-07 02:35:30 +0000974
Owen Anderson96e0fc72009-07-29 22:16:19 +0000975 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpb7477cf2009-04-10 18:52:28 +0000976 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
977 SrcObj = Builder.CreateLoad(SrcObj);
Mike Stump08920992009-03-07 02:35:30 +0000978
Mike Stumpb7477cf2009-04-10 18:52:28 +0000979 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
Mike Stumpc2f4c342009-04-15 22:11:36 +0000980 llvm::Type *PtrPtrT;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000981 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpc2f4c342009-04-15 22:11:36 +0000982 DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
983 DstObj = Builder.CreateLoad(DstObj);
Mike Stump08920992009-03-07 02:35:30 +0000984
Mike Stumpb7477cf2009-04-10 18:52:28 +0000985 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
986 int flag = NoteForHelper[i].flag;
987 int index = NoteForHelper[i].index;
Mike Stump08920992009-03-07 02:35:30 +0000988
Mike Stumpb7477cf2009-04-10 18:52:28 +0000989 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
990 || NoteForHelper[i].RequiresCopying) {
991 llvm::Value *Srcv = SrcObj;
992 Srcv = Builder.CreateStructGEP(Srcv, index);
993 Srcv = Builder.CreateBitCast(Srcv,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000994 llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpb7477cf2009-04-10 18:52:28 +0000995 Srcv = Builder.CreateLoad(Srcv);
996
997 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
998 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
999
Chris Lattner77b89b82010-06-27 07:15:29 +00001000 llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
Daniel Dunbar673431a2010-07-16 00:00:15 +00001001 llvm::Value *F = CGM.getBlockObjectAssign();
Mike Stumpb7477cf2009-04-10 18:52:28 +00001002 Builder.CreateCall3(F, Dstv, Srcv, N);
1003 }
Mike Stump08920992009-03-07 02:35:30 +00001004 }
1005 }
1006
Mike Stumpa4f668f2009-03-06 01:33:24 +00001007 CGF.FinishFunction();
1008
Owen Anderson3c4972d2009-07-29 18:54:39 +00001009 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +00001010}
1011
Mike Stumpcf62d392009-03-06 18:42:23 +00001012llvm::Constant *BlockFunction::
Mike Stump08920992009-03-07 02:35:30 +00001013GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
1014 const llvm::StructType* T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001015 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stumpa4f668f2009-03-06 01:33:24 +00001016 QualType R = getContext().VoidTy;
1017
1018 FunctionArgList Args;
1019 // FIXME: This leaks
1020 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001021 ImplicitParamDecl::Create(getContext(), 0,
1022 SourceLocation(), 0,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001023 getContext().getPointerType(getContext().VoidTy));
1024
1025 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Mike Stumpa4f668f2009-03-06 01:33:24 +00001027 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001028 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001029
Mike Stump3899a7f2009-06-05 23:26:36 +00001030 // FIXME: We'd like to put these into a mergable by content, with
1031 // internal linkage.
Mike Stumpa4f668f2009-03-06 01:33:24 +00001032 CodeGenTypes &Types = CGM.getTypes();
1033 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1034
1035 llvm::Function *Fn =
1036 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001037 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001038
1039 IdentifierInfo *II
1040 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1041
1042 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1043 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001044 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001045 FunctionDecl::Static,
1046 FunctionDecl::None,
1047 false, true);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001048 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001049
Mike Stumpb7477cf2009-04-10 18:52:28 +00001050 if (NoteForHelperp) {
1051 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
Mike Stump1edf6b62009-03-07 02:53:18 +00001052
Mike Stumpb7477cf2009-04-10 18:52:28 +00001053 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
1054 llvm::Type *PtrPtrT;
Owen Anderson96e0fc72009-07-29 22:16:19 +00001055 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpb7477cf2009-04-10 18:52:28 +00001056 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
1057 SrcObj = Builder.CreateLoad(SrcObj);
Mike Stump1edf6b62009-03-07 02:53:18 +00001058
Mike Stumpb7477cf2009-04-10 18:52:28 +00001059 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
1060 int flag = NoteForHelper[i].flag;
1061 int index = NoteForHelper[i].index;
Mike Stump1edf6b62009-03-07 02:53:18 +00001062
Mike Stumpb7477cf2009-04-10 18:52:28 +00001063 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
1064 || NoteForHelper[i].RequiresCopying) {
1065 llvm::Value *Srcv = SrcObj;
1066 Srcv = Builder.CreateStructGEP(Srcv, index);
1067 Srcv = Builder.CreateBitCast(Srcv,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001068 llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpb7477cf2009-04-10 18:52:28 +00001069 Srcv = Builder.CreateLoad(Srcv);
1070
1071 BuildBlockRelease(Srcv, flag);
1072 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001073 }
1074 }
1075
Mike Stumpa4f668f2009-03-06 01:33:24 +00001076 CGF.FinishFunction();
1077
Owen Anderson3c4972d2009-07-29 18:54:39 +00001078 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001079}
1080
Mike Stump08920992009-03-07 02:35:30 +00001081llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001082 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump08920992009-03-07 02:35:30 +00001083 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1084 T, NoteForHelper);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001085}
1086
Mike Stump08920992009-03-07 02:35:30 +00001087llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001088 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stump08920992009-03-07 02:35:30 +00001089 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001090 T, NoteForHelperp);
Mike Stumpdab514f2009-03-04 03:23:46 +00001091}
Mike Stump797b6322009-03-05 01:23:13 +00001092
Mike Stumpee094222009-03-06 06:12:24 +00001093llvm::Constant *BlockFunction::
1094GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stump45031c02009-03-06 02:29:21 +00001095 QualType R = getContext().VoidTy;
1096
1097 FunctionArgList Args;
1098 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001099 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001100 ImplicitParamDecl::Create(getContext(), 0,
1101 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001102 getContext().getPointerType(getContext().VoidTy));
1103 Args.push_back(std::make_pair(Dst, Dst->getType()));
1104
1105 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001106 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001107 ImplicitParamDecl::Create(getContext(), 0,
1108 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001109 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001110 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Mike Stump45031c02009-03-06 02:29:21 +00001112 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001113 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001114
Mike Stump45031c02009-03-06 02:29:21 +00001115 CodeGenTypes &Types = CGM.getTypes();
1116 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1117
Mike Stump3899a7f2009-06-05 23:26:36 +00001118 // FIXME: We'd like to put these into a mergable by content, with
1119 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001120 llvm::Function *Fn =
1121 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001122 "__Block_byref_id_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001123
1124 IdentifierInfo *II
1125 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1126
1127 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1128 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001129 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001130 FunctionDecl::Static,
1131 FunctionDecl::None,
1132 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001133 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001134
1135 // dst->x
1136 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001137 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001138 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001139 V = Builder.CreateStructGEP(V, 6, "x");
1140 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1141
1142 // src->x
1143 V = CGF.GetAddrOfLocalVar(Src);
1144 V = Builder.CreateLoad(V);
1145 V = Builder.CreateBitCast(V, T);
1146 V = Builder.CreateStructGEP(V, 6, "x");
Owen Anderson96e0fc72009-07-29 22:16:19 +00001147 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpee094222009-03-06 06:12:24 +00001148 llvm::Value *SrcObj = Builder.CreateLoad(V);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Mike Stumpee094222009-03-06 06:12:24 +00001150 flag |= BLOCK_BYREF_CALLER;
1151
Chris Lattner77b89b82010-06-27 07:15:29 +00001152 llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
Daniel Dunbar673431a2010-07-16 00:00:15 +00001153 llvm::Value *F = CGM.getBlockObjectAssign();
Mike Stumpee094222009-03-06 06:12:24 +00001154 Builder.CreateCall3(F, DstObj, SrcObj, N);
1155
Mike Stump45031c02009-03-06 02:29:21 +00001156 CGF.FinishFunction();
1157
Owen Anderson3c4972d2009-07-29 18:54:39 +00001158 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001159}
1160
Mike Stump1851b682009-03-06 04:53:30 +00001161llvm::Constant *
1162BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1163 int flag) {
Mike Stump45031c02009-03-06 02:29:21 +00001164 QualType R = getContext().VoidTy;
1165
1166 FunctionArgList Args;
1167 // FIXME: This leaks
1168 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001169 ImplicitParamDecl::Create(getContext(), 0,
1170 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001171 getContext().getPointerType(getContext().VoidTy));
1172
1173 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Mike Stump45031c02009-03-06 02:29:21 +00001175 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001176 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001177
Mike Stump45031c02009-03-06 02:29:21 +00001178 CodeGenTypes &Types = CGM.getTypes();
1179 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1180
Mike Stump3899a7f2009-06-05 23:26:36 +00001181 // FIXME: We'd like to put these into a mergable by content, with
1182 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001183 llvm::Function *Fn =
1184 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001185 "__Block_byref_id_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001186 &CGM.getModule());
1187
1188 IdentifierInfo *II
1189 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1190
1191 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1192 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001193 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001194 FunctionDecl::Static,
1195 FunctionDecl::None,
1196 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001197 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001198
1199 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001200 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001201 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001202 V = Builder.CreateStructGEP(V, 6, "x");
Owen Anderson96e0fc72009-07-29 22:16:19 +00001203 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001204 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001205
Mike Stump1851b682009-03-06 04:53:30 +00001206 flag |= BLOCK_BYREF_CALLER;
1207 BuildBlockRelease(V, flag);
Mike Stump45031c02009-03-06 02:29:21 +00001208 CGF.FinishFunction();
1209
Owen Anderson3c4972d2009-07-29 18:54:39 +00001210 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001211}
1212
Mike Stumpee094222009-03-06 06:12:24 +00001213llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
Chris Lattner10976d92009-12-05 08:21:30 +00001214 int Flag, unsigned Align) {
1215 // All alignments below that of pointer alignment collapse down to just
Mike Stump3899a7f2009-06-05 23:26:36 +00001216 // pointer alignment, as we always have at least that much alignment to begin
1217 // with.
1218 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001219
Mike Stump3899a7f2009-06-05 23:26:36 +00001220 // As an optimization, we only generate a single function of each kind we
1221 // might need. We need a different one for each alignment and for each
1222 // setting of flags. We mix Align and flag to get the kind.
Chris Lattner10976d92009-12-05 08:21:30 +00001223 uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1224 llvm::Constant *&Entry = CGM.AssignCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001225 if (Entry)
1226 return Entry;
Chris Lattner10976d92009-12-05 08:21:30 +00001227 return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
Mike Stump45031c02009-03-06 02:29:21 +00001228}
1229
Mike Stump1851b682009-03-06 04:53:30 +00001230llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
Chris Lattner10976d92009-12-05 08:21:30 +00001231 int Flag,
Mike Stump3899a7f2009-06-05 23:26:36 +00001232 unsigned Align) {
1233 // All alignments below that of pointer alignment collpase down to just
1234 // pointer alignment, as we always have at least that much alignment to begin
1235 // with.
1236 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001237
Mike Stump3899a7f2009-06-05 23:26:36 +00001238 // As an optimization, we only generate a single function of each kind we
1239 // might need. We need a different one for each alignment and for each
1240 // setting of flags. We mix Align and flag to get the kind.
Chris Lattner10976d92009-12-05 08:21:30 +00001241 uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1242 llvm::Constant *&Entry = CGM.DestroyCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001243 if (Entry)
1244 return Entry;
Chris Lattner10976d92009-12-05 08:21:30 +00001245 return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
Mike Stump45031c02009-03-06 02:29:21 +00001246}
1247
Mike Stump1851b682009-03-06 04:53:30 +00001248void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001249 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001250 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001251 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Chris Lattner77b89b82010-06-27 07:15:29 +00001252 N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
Mike Stump797b6322009-03-05 01:23:13 +00001253 Builder.CreateCall2(F, V, N);
1254}
Mike Stump00470a12009-03-05 08:32:30 +00001255
1256ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001257
1258BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1259 CGBuilderTy &B)
Chris Lattner77b89b82010-06-27 07:15:29 +00001260 : CGM(cgm), VMContext(cgm.getLLVMContext()), CGF(cgf), Builder(B) {
Owen Anderson0032b272009-08-13 21:57:51 +00001261 PtrToInt8Ty = llvm::PointerType::getUnqual(
1262 llvm::Type::getInt8Ty(VMContext));
Mike Stump08920992009-03-07 02:35:30 +00001263
1264 BlockHasCopyDispose = false;
1265}