blob: 379da11033d417cb3e4910ffea4e096d1449dae0 [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"
John McCalld16c2cf2011-02-08 08:22:06 +000018#include "CGBlocks.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000020#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000022#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000023#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000024
Anders Carlssonacfde802009-02-12 00:39:25 +000025using namespace clang;
26using namespace CodeGen;
27
John McCall1a343eb2011-11-10 08:15:53 +000028CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
29 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
John McCall6f103ba2011-11-10 10:43:54 +000030 HasCXXObject(false), UsesStret(false), StructureType(0), Block(block),
31 DominatingIP(0) {
John McCallee504292010-05-21 04:11:14 +000032
John McCall1a343eb2011-11-10 08:15:53 +000033 // Skip asm prefix, if any. 'name' is usually taken directly from
34 // the mangled name of the enclosing function.
35 if (!name.empty() && name[0] == '\01')
36 name = name.substr(1);
John McCallee504292010-05-21 04:11:14 +000037}
38
John McCallf0c11f72011-03-31 08:03:29 +000039// Anchor the vtable to this translation unit.
40CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
41
John McCall6b5a61b2011-02-07 10:33:21 +000042/// Build the given block as a global block.
43static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
44 const CGBlockInfo &blockInfo,
45 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000046
John McCall6b5a61b2011-02-07 10:33:21 +000047/// Build the helper function to copy a block.
48static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
49 const CGBlockInfo &blockInfo) {
50 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
51}
52
53/// Build the helper function to dipose of a block.
54static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
55 const CGBlockInfo &blockInfo) {
56 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
57}
58
59/// Build the block descriptor constant for a block.
60static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
61 const CGBlockInfo &blockInfo) {
62 ASTContext &C = CGM.getContext();
63
Chris Lattner2acc6e32011-07-18 04:24:23 +000064 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
65 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000066
Chris Lattner5f9e2722011-07-23 10:55:15 +000067 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000068
69 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000070 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000071
72 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000073 // FIXME: What is the right way to say this doesn't fit? We should give
74 // a user diagnostic in that case. Better fix would be to change the
75 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000076 elements.push_back(llvm::ConstantInt::get(ulong,
77 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000078
John McCall6b5a61b2011-02-07 10:33:21 +000079 // Optional copy/dispose helpers.
80 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000081 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000082 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000083
84 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000085 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000086 }
87
John McCall6b5a61b2011-02-07 10:33:21 +000088 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
89 std::string typeAtEncoding =
90 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
91 elements.push_back(llvm::ConstantExpr::getBitCast(
92 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000093
John McCall6b5a61b2011-02-07 10:33:21 +000094 // GC layout.
David Blaikie4e4d0842012-03-11 07:00:24 +000095 if (C.getLangOpts().ObjC1)
John McCall6b5a61b2011-02-07 10:33:21 +000096 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
97 else
98 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000099
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000100 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000101
John McCall6b5a61b2011-02-07 10:33:21 +0000102 llvm::GlobalVariable *global =
103 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
104 llvm::GlobalValue::InternalLinkage,
105 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000106
John McCall6b5a61b2011-02-07 10:33:21 +0000107 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000108}
109
John McCall6b5a61b2011-02-07 10:33:21 +0000110/*
111 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000112
John McCall6b5a61b2011-02-07 10:33:21 +0000113 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
114 struct Block_literal {
115 /// Initialized to one of:
116 /// extern void *_NSConcreteStackBlock[];
117 /// extern void *_NSConcreteGlobalBlock[];
118 ///
119 /// In theory, we could start one off malloc'ed by setting
120 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
121 /// this isa:
122 /// extern void *_NSConcreteMallocBlock[];
123 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000124
John McCall6b5a61b2011-02-07 10:33:21 +0000125 /// These are the flags (with corresponding bit number) that the
126 /// compiler is actually supposed to know about.
127 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
128 /// descriptor provides copy and dispose helper functions
129 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
130 /// object with a nontrivial destructor or copy constructor
131 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
132 /// as global memory
133 /// 29. BLOCK_USE_STRET - indicates that the block function
134 /// uses stret, which objc_msgSend needs to know about
135 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
136 /// @encoded signature string
137 /// And we're not supposed to manipulate these:
138 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
139 /// to malloc'ed memory
140 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
141 /// to GC-allocated memory
142 /// Additionally, the bottom 16 bits are a reference count which
143 /// should be zero on the stack.
144 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000145
John McCall6b5a61b2011-02-07 10:33:21 +0000146 /// Reserved; should be zero-initialized.
147 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000148
John McCall6b5a61b2011-02-07 10:33:21 +0000149 /// Function pointer generated from block literal.
150 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000151
John McCall6b5a61b2011-02-07 10:33:21 +0000152 /// Block description metadata generated from block literal.
153 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000154
John McCall6b5a61b2011-02-07 10:33:21 +0000155 /// Captured values follow.
156 _CapturesTypes captures...;
157 };
158 */
David Chisnall5e530af2009-11-17 19:33:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160/// The number of fields in a block header.
161const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163namespace {
164 /// A chunk of data that we actually have to capture in the block.
165 struct BlockLayoutChunk {
166 CharUnits Alignment;
167 CharUnits Size;
168 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000169 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000170
John McCall6b5a61b2011-02-07 10:33:21 +0000171 BlockLayoutChunk(CharUnits align, CharUnits size,
172 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000173 llvm::Type *type)
John McCall6b5a61b2011-02-07 10:33:21 +0000174 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000175
John McCall6b5a61b2011-02-07 10:33:21 +0000176 /// Tell the block info that this chunk has the given field index.
177 void setIndex(CGBlockInfo &info, unsigned index) {
178 if (!Capture)
179 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000180 else
John McCall6b5a61b2011-02-07 10:33:21 +0000181 info.Captures[Capture->getVariable()]
182 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000183 }
John McCall6b5a61b2011-02-07 10:33:21 +0000184 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000185
John McCall6b5a61b2011-02-07 10:33:21 +0000186 /// Order by descending alignment.
187 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
188 return left.Alignment > right.Alignment;
189 }
190}
191
John McCall461c9c12011-02-08 03:07:00 +0000192/// Determines if the given type is safe for constant capture in C++.
193static bool isSafeForCXXConstantCapture(QualType type) {
194 const RecordType *recordType =
195 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
196
197 // Only records can be unsafe.
198 if (!recordType) return true;
199
200 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
201
202 // Maintain semantics for classes with non-trivial dtors or copy ctors.
203 if (!record->hasTrivialDestructor()) return false;
204 if (!record->hasTrivialCopyConstructor()) return false;
205
206 // Otherwise, we just have to make sure there aren't any mutable
207 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000208 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000209}
210
John McCall6b5a61b2011-02-07 10:33:21 +0000211/// It is illegal to modify a const object after initialization.
212/// Therefore, if a const object has a constant initializer, we don't
213/// actually need to keep storage for it in the block; we'll just
214/// rematerialize it at the start of the block function. This is
215/// acceptable because we make no promises about address stability of
216/// captured variables.
217static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000218 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000219 const VarDecl *var) {
220 QualType type = var->getType();
221
222 // We can only do this if the variable is const.
223 if (!type.isConstQualified()) return 0;
224
John McCall461c9c12011-02-08 03:07:00 +0000225 // Furthermore, in C++ we have to worry about mutable fields:
226 // C++ [dcl.type.cv]p4:
227 // Except that any class member declared mutable can be
228 // modified, any attempt to modify a const object during its
229 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000230 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000231 return 0;
232
233 // If the variable doesn't have any initializer (shouldn't this be
234 // invalid?), it's not clear what we should do. Maybe capture as
235 // zero?
236 const Expr *init = var->getInit();
237 if (!init) return 0;
238
Richard Smith2d6a5672012-01-14 04:30:29 +0000239 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000240}
241
242/// Get the low bit of a nonzero character count. This is the
243/// alignment of the nth byte if the 0th byte is universally aligned.
244static CharUnits getLowBit(CharUnits v) {
245 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
246}
247
248static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000249 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000250 ASTContext &C = CGM.getContext();
251
252 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
253 CharUnits ptrSize, ptrAlign, intSize, intAlign;
254 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
255 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
256
257 // Are there crazy embedded platforms where this isn't true?
258 assert(intSize <= ptrSize && "layout assumptions horribly violated");
259
260 CharUnits headerSize = ptrSize;
261 if (2 * intSize < ptrAlign) headerSize += ptrSize;
262 else headerSize += 2 * intSize;
263 headerSize += 2 * ptrSize;
264
265 info.BlockAlign = ptrAlign;
266 info.BlockSize = headerSize;
267
268 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000269 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
270 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000271 elementTypes.push_back(i8p);
272 elementTypes.push_back(intTy);
273 elementTypes.push_back(intTy);
274 elementTypes.push_back(i8p);
275 elementTypes.push_back(CGM.getBlockDescriptorType());
276
277 assert(elementTypes.size() == BlockHeaderSize);
278}
279
280/// Compute the layout of the given block. Attempts to lay the block
281/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000282static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
283 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000284 ASTContext &C = CGM.getContext();
285 const BlockDecl *block = info.getBlockDecl();
286
Chris Lattner5f9e2722011-07-23 10:55:15 +0000287 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000288 initializeForBlockHeader(CGM, info, elementTypes);
289
290 if (!block->hasCaptures()) {
291 info.StructureType =
292 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
293 info.CanBeGlobal = true;
294 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000295 }
Mike Stump00470a12009-03-05 08:32:30 +0000296
John McCall6b5a61b2011-02-07 10:33:21 +0000297 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000298 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000299 layout.reserve(block->capturesCXXThis() +
300 (block->capture_end() - block->capture_begin()));
301
302 CharUnits maxFieldAlign;
303
304 // First, 'this'.
305 if (block->capturesCXXThis()) {
306 const DeclContext *DC = block->getDeclContext();
307 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
308 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000309 QualType thisType;
310 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
311 thisType = C.getPointerType(C.getRecordType(RD));
312 else
313 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000314
Jay Foadef6de3d2011-07-11 09:56:20 +0000315 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000316 std::pair<CharUnits,CharUnits> tinfo
317 = CGM.getContext().getTypeInfoInChars(thisType);
318 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
319
320 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
321 }
322
323 // Next, all the block captures.
324 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
325 ce = block->capture_end(); ci != ce; ++ci) {
326 const VarDecl *variable = ci->getVariable();
327
328 if (ci->isByRef()) {
329 // We have to copy/dispose of the __block reference.
330 info.NeedsCopyDispose = true;
331
John McCall6b5a61b2011-02-07 10:33:21 +0000332 // Just use void* instead of a pointer to the byref type.
333 QualType byRefPtrTy = C.VoidPtrTy;
334
Jay Foadef6de3d2011-07-11 09:56:20 +0000335 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000336 std::pair<CharUnits,CharUnits> tinfo
337 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
338 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
339
340 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
341 &*ci, llvmType));
342 continue;
343 }
344
345 // Otherwise, build a layout chunk with the size and alignment of
346 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000347 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000348 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
349 continue;
350 }
351
John McCallf85e1932011-06-15 23:02:42 +0000352 // If we have a lifetime qualifier, honor it for capture purposes.
353 // That includes *not* copying it if it's __unsafe_unretained.
354 if (Qualifiers::ObjCLifetime lifetime
355 = variable->getType().getObjCLifetime()) {
356 switch (lifetime) {
357 case Qualifiers::OCL_None: llvm_unreachable("impossible");
358 case Qualifiers::OCL_ExplicitNone:
359 case Qualifiers::OCL_Autoreleasing:
360 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000361
John McCallf85e1932011-06-15 23:02:42 +0000362 case Qualifiers::OCL_Strong:
363 case Qualifiers::OCL_Weak:
364 info.NeedsCopyDispose = true;
365 }
366
367 // Block pointers require copy/dispose. So do Objective-C pointers.
368 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000369 info.NeedsCopyDispose = true;
370
371 // So do types that require non-trivial copy construction.
372 } else if (ci->hasCopyExpr()) {
373 info.NeedsCopyDispose = true;
374 info.HasCXXObject = true;
375
376 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000377 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000378 if (const CXXRecordDecl *record =
379 variable->getType()->getAsCXXRecordDecl()) {
380 if (!record->hasTrivialDestructor()) {
381 info.HasCXXObject = true;
382 info.NeedsCopyDispose = true;
383 }
384 }
385 }
386
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000387 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000388 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000389 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000390
John McCall6b5a61b2011-02-07 10:33:21 +0000391 maxFieldAlign = std::max(maxFieldAlign, align);
392
Jay Foadef6de3d2011-07-11 09:56:20 +0000393 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000394 CGM.getTypes().ConvertTypeForMem(VT);
395
John McCall6b5a61b2011-02-07 10:33:21 +0000396 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
397 }
398
399 // If that was everything, we're done here.
400 if (layout.empty()) {
401 info.StructureType =
402 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
403 info.CanBeGlobal = true;
404 return;
405 }
406
407 // Sort the layout by alignment. We have to use a stable sort here
408 // to get reproducible results. There should probably be an
409 // llvm::array_pod_stable_sort.
410 std::stable_sort(layout.begin(), layout.end());
411
412 CharUnits &blockSize = info.BlockSize;
413 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
414
415 // Assuming that the first byte in the header is maximally aligned,
416 // get the alignment of the first byte following the header.
417 CharUnits endAlign = getLowBit(blockSize);
418
419 // If the end of the header isn't satisfactorily aligned for the
420 // maximum thing, look for things that are okay with the header-end
421 // alignment, and keep appending them until we get something that's
422 // aligned right. This algorithm is only guaranteed optimal if
423 // that condition is satisfied at some point; otherwise we can get
424 // things like:
425 // header // next byte has alignment 4
426 // something_with_size_5; // next byte has alignment 1
427 // something_with_alignment_8;
428 // which has 7 bytes of padding, as opposed to the naive solution
429 // which might have less (?).
430 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000431 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000432 li = layout.begin() + 1, le = layout.end();
433
434 // Look for something that the header end is already
435 // satisfactorily aligned for.
436 for (; li != le && endAlign < li->Alignment; ++li)
437 ;
438
439 // If we found something that's naturally aligned for the end of
440 // the header, keep adding things...
441 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000442 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000443 for (; li != le; ++li) {
444 assert(endAlign >= li->Alignment);
445
446 li->setIndex(info, elementTypes.size());
447 elementTypes.push_back(li->Type);
448 blockSize += li->Size;
449 endAlign = getLowBit(blockSize);
450
451 // ...until we get to the alignment of the maximum field.
452 if (endAlign >= maxFieldAlign)
453 break;
454 }
455
456 // Don't re-append everything we just appended.
457 layout.erase(first, li);
458 }
459 }
460
John McCall6ea48412012-04-26 21:14:42 +0000461 assert(endAlign == getLowBit(blockSize));
462
John McCall6b5a61b2011-02-07 10:33:21 +0000463 // At this point, we just have to add padding if the end align still
464 // isn't aligned right.
465 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000466 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
467 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000468
John McCall5936e332011-02-15 09:22:45 +0000469 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
470 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000471 blockSize = newBlockSize;
472 endAlign = maxFieldAlign;
John McCall6b5a61b2011-02-07 10:33:21 +0000473 }
474
John McCall6ea48412012-04-26 21:14:42 +0000475 assert(endAlign == getLowBit(blockSize));
476
John McCall6b5a61b2011-02-07 10:33:21 +0000477 // Slam everything else on now. This works because they have
478 // strictly decreasing alignment and we expect that size is always a
479 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000480 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000481 li = layout.begin(), le = layout.end(); li != le; ++li) {
482 assert(endAlign >= li->Alignment);
483 li->setIndex(info, elementTypes.size());
484 elementTypes.push_back(li->Type);
485 blockSize += li->Size;
486 endAlign = getLowBit(blockSize);
487 }
488
489 info.StructureType =
490 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
491}
492
John McCall1a343eb2011-11-10 08:15:53 +0000493/// Enter the scope of a block. This should be run at the entrance to
494/// a full-expression so that the block's cleanups are pushed at the
495/// right place in the stack.
496static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000497 assert(CGF.HaveInsertPoint());
498
John McCall1a343eb2011-11-10 08:15:53 +0000499 // Allocate the block info and place it at the head of the list.
500 CGBlockInfo &blockInfo =
501 *new CGBlockInfo(block, CGF.CurFn->getName());
502 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
503 CGF.FirstBlockInfo = &blockInfo;
504
505 // Compute information about the layout, etc., of this block,
506 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000507 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000508
509 // Nothing else to do if it can be global.
510 if (blockInfo.CanBeGlobal) return;
511
512 // Make the allocation for the block.
513 blockInfo.Address =
514 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
515 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
516
517 // If there are cleanups to emit, enter them (but inactive).
518 if (!blockInfo.NeedsCopyDispose) return;
519
520 // Walk through the captures (in order) and find the ones not
521 // captured by constant.
522 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
523 ce = block->capture_end(); ci != ce; ++ci) {
524 // Ignore __block captures; there's nothing special in the
525 // on-stack block that we need to do for them.
526 if (ci->isByRef()) continue;
527
528 // Ignore variables that are constant-captured.
529 const VarDecl *variable = ci->getVariable();
530 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
531 if (capture.isConstant()) continue;
532
533 // Ignore objects that aren't destructed.
534 QualType::DestructionKind dtorKind =
535 variable->getType().isDestructedType();
536 if (dtorKind == QualType::DK_none) continue;
537
538 CodeGenFunction::Destroyer *destroyer;
539
540 // Block captures count as local values and have imprecise semantics.
541 // They also can't be arrays, so need to worry about that.
542 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000543 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000544 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000545 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000546 }
547
548 // GEP down to the address.
549 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
550 capture.getIndex());
551
John McCall6f103ba2011-11-10 10:43:54 +0000552 // We can use that GEP as the dominating IP.
553 if (!blockInfo.DominatingIP)
554 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
555
John McCall1a343eb2011-11-10 08:15:53 +0000556 CleanupKind cleanupKind = InactiveNormalCleanup;
557 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
558 if (useArrayEHCleanup)
559 cleanupKind = InactiveNormalAndEHCleanup;
560
561 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000562 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000563
564 // Remember where that cleanup was.
565 capture.setCleanup(CGF.EHStack.stable_begin());
566 }
567}
568
569/// Enter a full-expression with a non-trivial number of objects to
570/// clean up. This is in this file because, at the moment, the only
571/// kind of cleanup object is a BlockDecl*.
572void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
573 assert(E->getNumObjects() != 0);
574 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
575 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
576 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
577 enterBlockScope(*this, *i);
578 }
579}
580
581/// Find the layout for the given block in a linked list and remove it.
582static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
583 const BlockDecl *block) {
584 while (true) {
585 assert(head && *head);
586 CGBlockInfo *cur = *head;
587
588 // If this is the block we're looking for, splice it out of the list.
589 if (cur->getBlockDecl() == block) {
590 *head = cur->NextBlockInfo;
591 return cur;
592 }
593
594 head = &cur->NextBlockInfo;
595 }
596}
597
598/// Destroy a chain of block layouts.
599void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
600 assert(head && "destroying an empty chain");
601 do {
602 CGBlockInfo *cur = head;
603 head = cur->NextBlockInfo;
604 delete cur;
605 } while (head != 0);
606}
607
John McCall6b5a61b2011-02-07 10:33:21 +0000608/// Emit a block literal expression in the current function.
609llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000610 // If the block has no captures, we won't have a pre-computed
611 // layout for it.
612 if (!blockExpr->getBlockDecl()->hasCaptures()) {
613 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000614 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000615 blockInfo.BlockExpression = blockExpr;
616 return EmitBlockLiteral(blockInfo);
617 }
John McCall6b5a61b2011-02-07 10:33:21 +0000618
John McCall1a343eb2011-11-10 08:15:53 +0000619 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000620 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000621 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
622 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000623
John McCall1a343eb2011-11-10 08:15:53 +0000624 blockInfo->BlockExpression = blockExpr;
625 return EmitBlockLiteral(*blockInfo);
626}
627
628llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
629 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000630 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000631 llvm::Constant *blockFn
632 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000633 CurFuncDecl, LocalDeclMap,
Eli Friedman23f02672012-03-01 04:01:32 +0000634 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000635 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000636
637 // If there is nothing to capture, we can emit this as a global block.
638 if (blockInfo.CanBeGlobal)
639 return buildGlobalBlock(CGM, blockInfo, blockFn);
640
641 // Otherwise, we have to emit this as a local block.
642
643 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000644 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000645
646 // Build the block descriptor.
647 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
648
John McCall1a343eb2011-11-10 08:15:53 +0000649 llvm::AllocaInst *blockAddr = blockInfo.Address;
650 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000651
652 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000653 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000654 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
655 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000656 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000657
658 // Initialize the block literal.
659 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000660 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000661 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000662 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000663 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
664 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
665 "block.invoke"));
666 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
667 "block.descriptor"));
668
669 // Finally, capture all the values into the block.
670 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
671
672 // First, 'this'.
673 if (blockDecl->capturesCXXThis()) {
674 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
675 blockInfo.CXXThisIndex,
676 "block.captured-this.addr");
677 Builder.CreateStore(LoadCXXThis(), addr);
678 }
679
680 // Next, captured variables.
681 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
682 ce = blockDecl->capture_end(); ci != ce; ++ci) {
683 const VarDecl *variable = ci->getVariable();
684 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
685
686 // Ignore constant captures.
687 if (capture.isConstant()) continue;
688
689 QualType type = variable->getType();
690
691 // This will be a [[type]]*, except that a byref entry will just be
692 // an i8**.
693 llvm::Value *blockField =
694 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
695 "block.captured");
696
697 // Compute the address of the thing we're going to move into the
698 // block literal.
699 llvm::Value *src;
700 if (ci->isNested()) {
701 // We need to use the capture from the enclosing block.
702 const CGBlockInfo::Capture &enclosingCapture =
703 BlockInfo->getCapture(variable);
704
705 // This is a [[type]]*, except that a byref entry wil just be an i8**.
706 src = Builder.CreateStructGEP(LoadBlockStruct(),
707 enclosingCapture.getIndex(),
708 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000709 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000710 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000711 // special; we'll simply emit it directly.
712 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000713 } else {
714 // This is a [[type]]*.
715 src = LocalDeclMap[variable];
716 }
717
718 // For byrefs, we just write the pointer to the byref struct into
719 // the block field. There's no need to chase the forwarding
720 // pointer at this point, since we're building something that will
721 // live a shorter life than the stack byref anyway.
722 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000723 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000724 if (ci->isNested())
725 src = Builder.CreateLoad(src, "byref.capture");
726 else
John McCall5936e332011-02-15 09:22:45 +0000727 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000728
John McCall5936e332011-02-15 09:22:45 +0000729 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000730 Builder.CreateStore(src, blockField);
731
732 // If we have a copy constructor, evaluate that into the block field.
733 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000734 if (blockDecl->isConversionFromLambda()) {
735 // If we have a lambda conversion, emit the expression
736 // directly into the block instead.
737 CharUnits Align = getContext().getTypeAlignInChars(type);
738 AggValueSlot Slot =
739 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
740 AggValueSlot::IsDestructed,
741 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000742 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000743 EmitAggExpr(copyExpr, Slot);
744 } else {
745 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
746 }
John McCall6b5a61b2011-02-07 10:33:21 +0000747
748 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000749 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000750 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
751
752 // Otherwise, fake up a POD copy into the block field.
753 } else {
John McCallf85e1932011-06-15 23:02:42 +0000754 // Fake up a new variable so that EmitScalarInit doesn't think
755 // we're referring to the variable in its own initializer.
756 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000757 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000758
John McCallbb699b02011-02-07 18:37:40 +0000759 // We use one of these or the other depending on whether the
760 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000761 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
762 /*refersToEnclosing*/ ci->isNested(), type,
763 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000764
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000765 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000766 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000767 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000768 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000769 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000770 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000771 }
772
John McCall1a343eb2011-11-10 08:15:53 +0000773 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000774 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000775 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
776 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000777 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000778 }
John McCall6b5a61b2011-02-07 10:33:21 +0000779 }
780
781 // Cast to the converted block-pointer type, which happens (somewhat
782 // unfortunately) to be a pointer to function type.
783 llvm::Value *result =
784 Builder.CreateBitCast(blockAddr,
785 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000786
John McCall6b5a61b2011-02-07 10:33:21 +0000787 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000788}
789
790
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000791llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000792 if (BlockDescriptorType)
793 return BlockDescriptorType;
794
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000795 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000796 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000797
Mike Stumpab695142009-02-13 15:16:56 +0000798 // struct __block_descriptor {
799 // unsigned long reserved;
800 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000801 //
802 // // later, the following will be added
803 //
804 // struct {
805 // void (*copyHelper)();
806 // void (*copyHelper)();
807 // } helpers; // !!! optional
808 //
809 // const char *signature; // the block signature
810 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000811 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000812 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000813 llvm::StructType::create("struct.__block_descriptor",
814 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000815
John McCall6b5a61b2011-02-07 10:33:21 +0000816 // Now form a pointer to that.
817 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000818 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000819}
820
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000821llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000822 if (GenericBlockLiteralType)
823 return GenericBlockLiteralType;
824
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000825 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000826
Mike Stump9b8a7972009-02-13 15:25:34 +0000827 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000828 // void *__isa;
829 // int __flags;
830 // int __reserved;
831 // void (*__invoke)(void *);
832 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000833 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000834 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000835 llvm::StructType::create("struct.__block_literal_generic",
836 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
837 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000838
Mike Stump9b8a7972009-02-13 15:25:34 +0000839 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000840}
841
Mike Stumpbd65cac2009-02-19 01:01:04 +0000842
Anders Carlssona1736c02009-12-24 21:13:40 +0000843RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
844 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000845 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000846 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000847
Anders Carlssonacfde802009-02-12 00:39:25 +0000848 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
849
850 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000851 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000852 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000853
854 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000855 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000856 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
857
858 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000859 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000860
Benjamin Kramer578faa82011-09-27 21:06:10 +0000861 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000862
Anders Carlssonacfde802009-02-12 00:39:25 +0000863 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000864 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000865 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000866
Anders Carlsson782f3972009-04-08 23:13:16 +0000867 QualType FnType = BPT->getPointeeType();
868
Anders Carlssonacfde802009-02-12 00:39:25 +0000869 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000870 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000871 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000872
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000873 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000874 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000875
John McCall64cd2322011-03-09 08:39:33 +0000876 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000877 const CGFunctionInfo &FnInfo =
878 CGM.getTypes().arrangeFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000880 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000881 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Chris Lattner2acc6e32011-07-18 04:24:23 +0000883 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000884 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Anders Carlssonacfde802009-02-12 00:39:25 +0000886 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000887 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000888}
Anders Carlssond5cab542009-02-12 17:55:02 +0000889
John McCall6b5a61b2011-02-07 10:33:21 +0000890llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
891 bool isByRef) {
892 assert(BlockInfo && "evaluating block ref without block information?");
893 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000894
John McCall6b5a61b2011-02-07 10:33:21 +0000895 // Handle constant captures.
896 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000897
John McCall6b5a61b2011-02-07 10:33:21 +0000898 llvm::Value *addr =
899 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
900 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000901
John McCall6b5a61b2011-02-07 10:33:21 +0000902 if (isByRef) {
903 // addr should be a void** right now. Load, then cast the result
904 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000905
John McCall6b5a61b2011-02-07 10:33:21 +0000906 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000907 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000908 = llvm::PointerType::get(BuildByRefType(variable), 0);
909 addr = Builder.CreateBitCast(addr, byrefPointerType,
910 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000911
John McCall6b5a61b2011-02-07 10:33:21 +0000912 // Follow the forwarding pointer.
913 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
914 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000915
John McCall6b5a61b2011-02-07 10:33:21 +0000916 // Cast back to byref* and GEP over to the actual object.
917 addr = Builder.CreateBitCast(addr, byrefPointerType);
918 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
919 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000920 }
921
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000922 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000923 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000924
John McCall6b5a61b2011-02-07 10:33:21 +0000925 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000926}
927
Mike Stump67a64482009-02-14 22:16:35 +0000928llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000929CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000930 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000931 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
932 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000933
John McCall6b5a61b2011-02-07 10:33:21 +0000934 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +0000935 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000936
John McCall6b5a61b2011-02-07 10:33:21 +0000937 // Using that metadata, generate the actual block function.
938 llvm::Constant *blockFn;
939 {
940 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000941 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
942 blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000943 0, LocalDeclMap,
944 false);
John McCall6b5a61b2011-02-07 10:33:21 +0000945 }
John McCall5936e332011-02-15 09:22:45 +0000946 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000947
John McCalld16c2cf2011-02-08 08:22:06 +0000948 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000949}
950
John McCall6b5a61b2011-02-07 10:33:21 +0000951static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
952 const CGBlockInfo &blockInfo,
953 llvm::Constant *blockFn) {
954 assert(blockInfo.CanBeGlobal);
955
956 // Generate the constants for the block literal initializer.
957 llvm::Constant *fields[BlockHeaderSize];
958
959 // isa
960 fields[0] = CGM.getNSConcreteGlobalBlock();
961
962 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000963 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
964 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
965
John McCall5936e332011-02-15 09:22:45 +0000966 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000967
968 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000969 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000970
971 // Function
972 fields[3] = blockFn;
973
974 // Descriptor
975 fields[4] = buildBlockDescriptor(CGM, blockInfo);
976
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000977 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000978
979 llvm::GlobalVariable *literal =
980 new llvm::GlobalVariable(CGM.getModule(),
981 init->getType(),
982 /*constant*/ true,
983 llvm::GlobalVariable::InternalLinkage,
984 init,
985 "__block_literal_global");
986 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
987
988 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000989 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +0000990 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
991 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000992}
993
Mike Stump00470a12009-03-05 08:32:30 +0000994llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000995CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
996 const CGBlockInfo &blockInfo,
997 const Decl *outerFnDecl,
Eli Friedman64bee652012-02-25 02:48:22 +0000998 const DeclMapTy &ldm,
999 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001000 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001001
Devang Patel6d1155b2011-03-07 21:53:18 +00001002 // Check if we should generate debug info for this block function.
1003 if (CGM.getModuleDebugInfo())
1004 DebugInfo = CGM.getModuleDebugInfo();
1005
John McCall6b5a61b2011-02-07 10:33:21 +00001006 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Mike Stump7f28a9c2009-03-13 23:34:28 +00001008 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001009 // to be local to this function as well, in case they're directly
1010 // referenced in a block.
1011 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1012 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1013 if (var && !var->hasLocalStorage())
1014 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001015 }
1016
John McCall6b5a61b2011-02-07 10:33:21 +00001017 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001018
John McCall6b5a61b2011-02-07 10:33:21 +00001019 // Build the argument list.
1020 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001021
John McCall6b5a61b2011-02-07 10:33:21 +00001022 // The first argument is the block pointer. Just take it as a void*
1023 // and cast it later.
1024 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001025 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001026
John McCall8178df32011-02-22 22:38:33 +00001027 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1028 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001029 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001030
John McCall6b5a61b2011-02-07 10:33:21 +00001031 // Now add the rest of the parameters.
1032 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1033 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001034 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001035
John McCall6b5a61b2011-02-07 10:33:21 +00001036 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001037 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001038 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001039 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1040 fnType->getExtInfo(),
1041 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001042 if (CGM.ReturnTypeUsesSRet(fnInfo))
1043 blockInfo.UsesStret = true;
1044
John McCallde5d3c72012-02-17 03:33:10 +00001045 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001046
John McCall6b5a61b2011-02-07 10:33:21 +00001047 MangleBuffer name;
1048 CGM.getBlockMangledName(GD, name, blockDecl);
1049 llvm::Function *fn =
1050 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1051 name.getString(), &CGM.getModule());
1052 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001053
John McCall6b5a61b2011-02-07 10:33:21 +00001054 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001055 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001056 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001057 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001058
John McCall8178df32011-02-22 22:38:33 +00001059 // Okay. Undo some of what StartFunction did.
1060
1061 // Pull the 'self' reference out of the local decl map.
1062 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1063 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001064 BlockPointer = Builder.CreateBitCast(blockAddr,
1065 blockInfo.StructureType->getPointerTo(),
1066 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001067
John McCallea1471e2010-05-20 01:18:31 +00001068 // If we have a C++ 'this' reference, go ahead and force it into
1069 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001070 if (blockDecl->capturesCXXThis()) {
1071 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1072 blockInfo.CXXThisIndex,
1073 "block.captured-this");
1074 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001075 }
1076
John McCall6b5a61b2011-02-07 10:33:21 +00001077 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1078 // appease it.
1079 if (const ObjCMethodDecl *method
1080 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1081 const VarDecl *self = method->getSelfDecl();
1082
1083 // There might not be a capture for 'self', but if there is...
1084 if (blockInfo.Captures.count(self)) {
1085 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1086 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1087 capture.getIndex(),
1088 "block.captured-self");
1089 LocalDeclMap[self] = selfAddr;
1090 }
1091 }
1092
1093 // Also force all the constant captures.
1094 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1095 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1096 const VarDecl *variable = ci->getVariable();
1097 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1098 if (!capture.isConstant()) continue;
1099
1100 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1101
1102 llvm::AllocaInst *alloca =
1103 CreateMemTemp(variable->getType(), "block.captured-const");
1104 alloca->setAlignment(align);
1105
1106 Builder.CreateStore(capture.getConstant(), alloca, align);
1107
1108 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001109 }
1110
John McCallf4b88a42012-03-10 09:33:50 +00001111 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001112 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1113 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1114 --entry_ptr;
1115
Eli Friedman64bee652012-02-25 02:48:22 +00001116 if (IsLambdaConversionToBlock)
1117 EmitLambdaBlockInvokeBody();
1118 else
1119 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001120
Mike Stumpde8c5c72009-10-01 00:27:30 +00001121 // Remember where we were...
1122 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001123
Mike Stumpde8c5c72009-10-01 00:27:30 +00001124 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001125 ++entry_ptr;
1126 Builder.SetInsertPoint(entry, entry_ptr);
1127
John McCallf4b88a42012-03-10 09:33:50 +00001128 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001129 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001130 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001131 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1132 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1133 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001134 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001135
1136 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1137 if (capture.isConstant()) {
1138 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1139 Builder);
1140 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001141 }
John McCall6b5a61b2011-02-07 10:33:21 +00001142
John McCall8178df32011-02-22 22:38:33 +00001143 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001144 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001145 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001146 }
John McCall6b5a61b2011-02-07 10:33:21 +00001147
Mike Stumpde8c5c72009-10-01 00:27:30 +00001148 // And resume where we left off.
1149 if (resume == 0)
1150 Builder.ClearInsertionPoint();
1151 else
1152 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001153
John McCall6b5a61b2011-02-07 10:33:21 +00001154 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001155
John McCall6b5a61b2011-02-07 10:33:21 +00001156 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001157}
Mike Stumpa99038c2009-02-28 09:07:16 +00001158
John McCall6b5a61b2011-02-07 10:33:21 +00001159/*
1160 notes.push_back(HelperInfo());
1161 HelperInfo &note = notes.back();
1162 note.index = capture.getIndex();
1163 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1164 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001165
John McCall6b5a61b2011-02-07 10:33:21 +00001166 if (ci->isByRef()) {
1167 note.flag = BLOCK_FIELD_IS_BYREF;
1168 if (type.isObjCGCWeak())
1169 note.flag |= BLOCK_FIELD_IS_WEAK;
1170 } else if (type->isBlockPointerType()) {
1171 note.flag = BLOCK_FIELD_IS_BLOCK;
1172 } else {
1173 note.flag = BLOCK_FIELD_IS_OBJECT;
1174 }
1175 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001176
Mike Stump00470a12009-03-05 08:32:30 +00001177
Mike Stumpa99038c2009-02-28 09:07:16 +00001178
John McCall6b5a61b2011-02-07 10:33:21 +00001179llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001180CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001181 ASTContext &C = getContext();
1182
1183 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001184 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1185 args.push_back(&dstDecl);
1186 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1187 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Mike Stumpa4f668f2009-03-06 01:33:24 +00001189 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001190 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1191 FunctionType::ExtInfo(),
1192 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001193
John McCall6b5a61b2011-02-07 10:33:21 +00001194 // FIXME: it would be nice if these were mergeable with things with
1195 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001196 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001197
1198 llvm::Function *Fn =
1199 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001200 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001201
1202 IdentifierInfo *II
1203 = &CGM.getContext().Idents.get("__copy_helper_block_");
1204
Devang Patel58dc5ca2011-05-02 20:37:08 +00001205 // Check if we should generate debug info for this block helper function.
1206 if (CGM.getModuleDebugInfo())
1207 DebugInfo = CGM.getModuleDebugInfo();
1208
John McCall6b5a61b2011-02-07 10:33:21 +00001209 FunctionDecl *FD = FunctionDecl::Create(C,
1210 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001211 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001212 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001213 SC_Static,
1214 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001215 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001216 false);
John McCalld26bc762011-03-09 04:27:21 +00001217 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001218
Chris Lattner2acc6e32011-07-18 04:24:23 +00001219 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001220
John McCalld26bc762011-03-09 04:27:21 +00001221 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001222 src = Builder.CreateLoad(src);
1223 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001224
John McCalld26bc762011-03-09 04:27:21 +00001225 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001226 dst = Builder.CreateLoad(dst);
1227 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001228
John McCall6b5a61b2011-02-07 10:33:21 +00001229 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001230
John McCall6b5a61b2011-02-07 10:33:21 +00001231 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1232 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1233 const VarDecl *variable = ci->getVariable();
1234 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001235
John McCall6b5a61b2011-02-07 10:33:21 +00001236 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1237 if (capture.isConstant()) continue;
1238
1239 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001240 BlockFieldFlags flags;
1241
1242 bool isARCWeakCapture = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001243
1244 if (copyExpr) {
1245 assert(!ci->isByRef());
1246 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001247
John McCall6b5a61b2011-02-07 10:33:21 +00001248 } else if (ci->isByRef()) {
1249 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001250 if (type.isObjCGCWeak())
1251 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001252
John McCallf85e1932011-06-15 23:02:42 +00001253 } else if (type->isObjCRetainableType()) {
1254 flags = BLOCK_FIELD_IS_OBJECT;
1255 if (type->isBlockPointerType())
1256 flags = BLOCK_FIELD_IS_BLOCK;
1257
1258 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001259 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001260 Qualifiers qs = type.getQualifiers();
1261
1262 // Don't generate special copy logic for a captured object
1263 // unless it's __strong or __weak.
1264 if (!qs.hasStrongOrWeakObjCLifetime())
1265 continue;
1266
1267 // Support __weak direct captures.
1268 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1269 isARCWeakCapture = true;
1270 }
1271 } else {
1272 continue;
1273 }
John McCall6b5a61b2011-02-07 10:33:21 +00001274
1275 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001276 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1277 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001278
1279 // If there's an explicit copy expression, we do that.
1280 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001281 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCallf85e1932011-06-15 23:02:42 +00001282 } else if (isARCWeakCapture) {
1283 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001284 } else {
1285 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001286 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1287 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001288 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCallf85e1932011-06-15 23:02:42 +00001289 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
Mike Stump08920992009-03-07 02:35:30 +00001290 }
1291 }
1292
John McCalld16c2cf2011-02-08 08:22:06 +00001293 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001294
John McCall5936e332011-02-15 09:22:45 +00001295 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001296}
1297
John McCall6b5a61b2011-02-07 10:33:21 +00001298llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001299CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001300 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001301
John McCall6b5a61b2011-02-07 10:33:21 +00001302 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001303 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1304 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Mike Stumpa4f668f2009-03-06 01:33:24 +00001306 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001307 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1308 FunctionType::ExtInfo(),
1309 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001310
Mike Stump3899a7f2009-06-05 23:26:36 +00001311 // FIXME: We'd like to put these into a mergable by content, with
1312 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001313 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001314
1315 llvm::Function *Fn =
1316 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001317 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001318
Devang Patel58dc5ca2011-05-02 20:37:08 +00001319 // Check if we should generate debug info for this block destroy function.
1320 if (CGM.getModuleDebugInfo())
1321 DebugInfo = CGM.getModuleDebugInfo();
1322
Mike Stumpa4f668f2009-03-06 01:33:24 +00001323 IdentifierInfo *II
1324 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1325
John McCall6b5a61b2011-02-07 10:33:21 +00001326 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001327 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001328 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001329 SC_Static,
1330 SC_None,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001331 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001332 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001333
Chris Lattner2acc6e32011-07-18 04:24:23 +00001334 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001335
John McCalld26bc762011-03-09 04:27:21 +00001336 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001337 src = Builder.CreateLoad(src);
1338 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001339
John McCall6b5a61b2011-02-07 10:33:21 +00001340 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1341
John McCalld16c2cf2011-02-08 08:22:06 +00001342 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001343
1344 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1345 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1346 const VarDecl *variable = ci->getVariable();
1347 QualType type = variable->getType();
1348
1349 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1350 if (capture.isConstant()) continue;
1351
John McCalld16c2cf2011-02-08 08:22:06 +00001352 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001353 const CXXDestructorDecl *dtor = 0;
1354
John McCallf85e1932011-06-15 23:02:42 +00001355 bool isARCWeakCapture = false;
1356
John McCall6b5a61b2011-02-07 10:33:21 +00001357 if (ci->isByRef()) {
1358 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001359 if (type.isObjCGCWeak())
1360 flags |= BLOCK_FIELD_IS_WEAK;
1361 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1362 if (record->hasTrivialDestructor())
1363 continue;
1364 dtor = record->getDestructor();
1365 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001366 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001367 if (type->isBlockPointerType())
1368 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001369
John McCallf85e1932011-06-15 23:02:42 +00001370 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001371 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001372 Qualifiers qs = type.getQualifiers();
1373
1374 // Don't generate special dispose logic for a captured object
1375 // unless it's __strong or __weak.
1376 if (!qs.hasStrongOrWeakObjCLifetime())
1377 continue;
1378
1379 // Support __weak direct captures.
1380 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1381 isARCWeakCapture = true;
1382 }
1383 } else {
1384 continue;
1385 }
John McCall6b5a61b2011-02-07 10:33:21 +00001386
1387 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001388 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001389
1390 // If there's an explicit copy expression, we do that.
1391 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001392 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001393
John McCallf85e1932011-06-15 23:02:42 +00001394 // If this is a __weak capture, emit the release directly.
1395 } else if (isARCWeakCapture) {
1396 EmitARCDestroyWeak(srcField);
1397
John McCall6b5a61b2011-02-07 10:33:21 +00001398 // Otherwise we call _Block_object_dispose. It wouldn't be too
1399 // hard to just emit this as a cleanup if we wanted to make sure
1400 // that things were done in reverse.
1401 } else {
1402 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001403 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001404 BuildBlockRelease(value, flags);
1405 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001406 }
1407
John McCall6b5a61b2011-02-07 10:33:21 +00001408 cleanups.ForceCleanup();
1409
John McCalld16c2cf2011-02-08 08:22:06 +00001410 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001411
John McCall5936e332011-02-15 09:22:45 +00001412 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001413}
1414
John McCallf0c11f72011-03-31 08:03:29 +00001415namespace {
1416
1417/// Emits the copy/dispose helper functions for a __block object of id type.
1418class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1419 BlockFieldFlags Flags;
1420
1421public:
1422 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1423 : ByrefHelpers(alignment), Flags(flags) {}
1424
John McCall36170192011-03-31 09:19:20 +00001425 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1426 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001427 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1428
1429 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1430 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1431
1432 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1433
1434 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1435 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1436 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1437 }
1438
1439 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1440 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1441 llvm::Value *value = CGF.Builder.CreateLoad(field);
1442
1443 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1444 }
1445
1446 void profileImpl(llvm::FoldingSetNodeID &id) const {
1447 id.AddInteger(Flags.getBitMask());
1448 }
1449};
1450
John McCallf85e1932011-06-15 23:02:42 +00001451/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1452class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1453public:
1454 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1455
1456 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1457 llvm::Value *srcField) {
1458 CGF.EmitARCMoveWeak(destField, srcField);
1459 }
1460
1461 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1462 CGF.EmitARCDestroyWeak(field);
1463 }
1464
1465 void profileImpl(llvm::FoldingSetNodeID &id) const {
1466 // 0 is distinguishable from all pointers and byref flags
1467 id.AddInteger(0);
1468 }
1469};
1470
1471/// Emits the copy/dispose helpers for an ARC __block __strong variable
1472/// that's not of block-pointer type.
1473class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1474public:
1475 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1476
1477 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1478 llvm::Value *srcField) {
1479 // Do a "move" by copying the value and then zeroing out the old
1480 // variable.
1481
John McCalla59e4b72011-11-09 03:17:26 +00001482 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1483 value->setAlignment(Alignment.getQuantity());
1484
John McCallf85e1932011-06-15 23:02:42 +00001485 llvm::Value *null =
1486 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001487
1488 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1489 store->setAlignment(Alignment.getQuantity());
1490
1491 store = CGF.Builder.CreateStore(null, srcField);
1492 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001493 }
1494
1495 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCalla59e4b72011-11-09 03:17:26 +00001496 llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1497 value->setAlignment(Alignment.getQuantity());
1498
John McCallf85e1932011-06-15 23:02:42 +00001499 CGF.EmitARCRelease(value, /*precise*/ false);
1500 }
1501
1502 void profileImpl(llvm::FoldingSetNodeID &id) const {
1503 // 1 is distinguishable from all pointers and byref flags
1504 id.AddInteger(1);
1505 }
1506};
1507
John McCalla59e4b72011-11-09 03:17:26 +00001508/// Emits the copy/dispose helpers for an ARC __block __strong
1509/// variable that's of block-pointer type.
1510class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1511public:
1512 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1513
1514 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1515 llvm::Value *srcField) {
1516 // Do the copy with objc_retainBlock; that's all that
1517 // _Block_object_assign would do anyway, and we'd have to pass the
1518 // right arguments to make sure it doesn't get no-op'ed.
1519 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1520 oldValue->setAlignment(Alignment.getQuantity());
1521
1522 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1523
1524 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1525 store->setAlignment(Alignment.getQuantity());
1526 }
1527
1528 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1529 llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1530 value->setAlignment(Alignment.getQuantity());
1531
1532 CGF.EmitARCRelease(value, /*precise*/ false);
1533 }
1534
1535 void profileImpl(llvm::FoldingSetNodeID &id) const {
1536 // 2 is distinguishable from all pointers and byref flags
1537 id.AddInteger(2);
1538 }
1539};
1540
John McCallf0c11f72011-03-31 08:03:29 +00001541/// Emits the copy/dispose helpers for a __block variable with a
1542/// nontrivial copy constructor or destructor.
1543class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1544 QualType VarType;
1545 const Expr *CopyExpr;
1546
1547public:
1548 CXXByrefHelpers(CharUnits alignment, QualType type,
1549 const Expr *copyExpr)
1550 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1551
1552 bool needsCopy() const { return CopyExpr != 0; }
1553 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1554 llvm::Value *srcField) {
1555 if (!CopyExpr) return;
1556 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1557 }
1558
1559 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1560 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1561 CGF.PushDestructorCleanup(VarType, field);
1562 CGF.PopCleanupBlocks(cleanupDepth);
1563 }
1564
1565 void profileImpl(llvm::FoldingSetNodeID &id) const {
1566 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1567 }
1568};
1569} // end anonymous namespace
1570
1571static llvm::Constant *
1572generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001573 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001574 CodeGenModule::ByrefHelpers &byrefInfo) {
1575 ASTContext &Context = CGF.getContext();
1576
1577 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001578
John McCalld26bc762011-03-09 04:27:21 +00001579 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001580 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001581 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001582
John McCallf0c11f72011-03-31 08:03:29 +00001583 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001584 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Mike Stump45031c02009-03-06 02:29:21 +00001586 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001587 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1588 FunctionType::ExtInfo(),
1589 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001590
John McCallf0c11f72011-03-31 08:03:29 +00001591 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001592 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001593
Mike Stump3899a7f2009-06-05 23:26:36 +00001594 // FIXME: We'd like to put these into a mergable by content, with
1595 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001596 llvm::Function *Fn =
1597 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001598 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001599
1600 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001601 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001602
John McCallf0c11f72011-03-31 08:03:29 +00001603 FunctionDecl *FD = FunctionDecl::Create(Context,
1604 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001605 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001606 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001607 SC_Static,
1608 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001609 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001610
John McCallf0c11f72011-03-31 08:03:29 +00001611 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001612
John McCallf0c11f72011-03-31 08:03:29 +00001613 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001614 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001615
John McCallf0c11f72011-03-31 08:03:29 +00001616 // dst->x
1617 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1618 destField = CGF.Builder.CreateLoad(destField);
1619 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1620 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001621
John McCallf0c11f72011-03-31 08:03:29 +00001622 // src->x
1623 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1624 srcField = CGF.Builder.CreateLoad(srcField);
1625 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1626 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1627
1628 byrefInfo.emitCopy(CGF, destField, srcField);
1629 }
1630
1631 CGF.FinishFunction();
1632
1633 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001634}
1635
John McCallf0c11f72011-03-31 08:03:29 +00001636/// Build the copy helper for a __block variable.
1637static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001638 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001639 CodeGenModule::ByrefHelpers &info) {
1640 CodeGenFunction CGF(CGM);
1641 return generateByrefCopyHelper(CGF, byrefType, info);
1642}
1643
1644/// Generate code for a __block variable's dispose helper.
1645static llvm::Constant *
1646generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001647 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001648 CodeGenModule::ByrefHelpers &byrefInfo) {
1649 ASTContext &Context = CGF.getContext();
1650 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001651
John McCalld26bc762011-03-09 04:27:21 +00001652 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001653 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001654 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Mike Stump45031c02009-03-06 02:29:21 +00001656 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001657 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1658 FunctionType::ExtInfo(),
1659 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001660
John McCallf0c11f72011-03-31 08:03:29 +00001661 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001662 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001663
Mike Stump3899a7f2009-06-05 23:26:36 +00001664 // FIXME: We'd like to put these into a mergable by content, with
1665 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001666 llvm::Function *Fn =
1667 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001668 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001669 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001670
1671 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001672 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001673
John McCallf0c11f72011-03-31 08:03:29 +00001674 FunctionDecl *FD = FunctionDecl::Create(Context,
1675 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001676 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001677 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001678 SC_Static,
1679 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001680 false, false);
John McCallf0c11f72011-03-31 08:03:29 +00001681 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001682
John McCallf0c11f72011-03-31 08:03:29 +00001683 if (byrefInfo.needsDispose()) {
1684 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1685 V = CGF.Builder.CreateLoad(V);
1686 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1687 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001688
John McCallf0c11f72011-03-31 08:03:29 +00001689 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001690 }
Mike Stump45031c02009-03-06 02:29:21 +00001691
John McCallf0c11f72011-03-31 08:03:29 +00001692 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001693
John McCallf0c11f72011-03-31 08:03:29 +00001694 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001695}
1696
John McCallf0c11f72011-03-31 08:03:29 +00001697/// Build the dispose helper for a __block variable.
1698static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001699 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001700 CodeGenModule::ByrefHelpers &info) {
1701 CodeGenFunction CGF(CGM);
1702 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001703}
1704
John McCallf0c11f72011-03-31 08:03:29 +00001705///
1706template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001707 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001708 T &byrefInfo) {
1709 // Increase the field's alignment to be at least pointer alignment,
1710 // since the layout of the byref struct will guarantee at least that.
1711 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1712 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1713
1714 llvm::FoldingSetNodeID id;
1715 byrefInfo.Profile(id);
1716
1717 void *insertPos;
1718 CodeGenModule::ByrefHelpers *node
1719 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1720 if (node) return static_cast<T*>(node);
1721
1722 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1723 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1724
1725 T *copy = new (CGM.getContext()) T(byrefInfo);
1726 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1727 return copy;
1728}
1729
1730CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001731CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001732 const AutoVarEmission &emission) {
1733 const VarDecl &var = *emission.Variable;
1734 QualType type = var.getType();
1735
1736 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1737 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1738 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1739
1740 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1741 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1742 }
1743
John McCallf85e1932011-06-15 23:02:42 +00001744 // Otherwise, if we don't have a retainable type, there's nothing to do.
1745 // that the runtime does extra copies.
1746 if (!type->isObjCRetainableType()) return 0;
1747
1748 Qualifiers qs = type.getQualifiers();
1749
1750 // If we have lifetime, that dominates.
1751 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001752 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001753
1754 switch (lifetime) {
1755 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1756
1757 // These are just bits as far as the runtime is concerned.
1758 case Qualifiers::OCL_ExplicitNone:
1759 case Qualifiers::OCL_Autoreleasing:
1760 return 0;
1761
1762 // Tell the runtime that this is ARC __weak, called by the
1763 // byref routines.
1764 case Qualifiers::OCL_Weak: {
1765 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1766 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1767 }
1768
1769 // ARC __strong __block variables need to be retained.
1770 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001771 // Block pointers need to be copied, and there's no direct
1772 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001773 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001774 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001775 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1776
1777 // Otherwise, we transfer ownership of the retain from the stack
1778 // to the heap.
1779 } else {
1780 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1781 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1782 }
1783 }
1784 llvm_unreachable("fell out of lifetime switch!");
1785 }
1786
John McCallf0c11f72011-03-31 08:03:29 +00001787 BlockFieldFlags flags;
1788 if (type->isBlockPointerType()) {
1789 flags |= BLOCK_FIELD_IS_BLOCK;
1790 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1791 type->isObjCObjectPointerType()) {
1792 flags |= BLOCK_FIELD_IS_OBJECT;
1793 } else {
1794 return 0;
1795 }
1796
1797 if (type.isObjCGCWeak())
1798 flags |= BLOCK_FIELD_IS_WEAK;
1799
1800 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1801 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001802}
1803
John McCall5af02db2011-03-31 01:59:53 +00001804unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1805 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1806
1807 return ByRefValueInfo.find(VD)->second.second;
1808}
1809
1810llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1811 const VarDecl *V) {
1812 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1813 Loc = Builder.CreateLoad(Loc);
1814 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1815 V->getNameAsString());
1816 return Loc;
1817}
1818
1819/// BuildByRefType - This routine changes a __block variable declared as T x
1820/// into:
1821///
1822/// struct {
1823/// void *__isa;
1824/// void *__forwarding;
1825/// int32_t __flags;
1826/// int32_t __size;
1827/// void *__copy_helper; // only if needed
1828/// void *__destroy_helper; // only if needed
1829/// char padding[X]; // only if needed
1830/// T x;
1831/// } x
1832///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001833llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1834 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001835 if (Info.first)
1836 return Info.first;
1837
1838 QualType Ty = D->getType();
1839
Chris Lattner5f9e2722011-07-23 10:55:15 +00001840 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001841
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001842 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001843 llvm::StructType::create(getLLVMContext(),
1844 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001845
1846 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001847 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001848
1849 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001850 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001851
1852 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001853 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001854
1855 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001856 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001857
David Chisnall9595dae2012-04-04 13:07:13 +00001858 bool HasCopyAndDispose =
1859 (Ty->isObjCRetainableType()) || getContext().getBlockVarCopyInits(D);
John McCall5af02db2011-03-31 01:59:53 +00001860 if (HasCopyAndDispose) {
1861 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001862 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001863
1864 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001865 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001866 }
1867
1868 bool Packed = false;
1869 CharUnits Align = getContext().getDeclAlign(D);
1870 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1871 // We have to insert padding.
1872
1873 // The struct above has 2 32-bit integers.
1874 unsigned CurrentOffsetInBytes = 4 * 2;
1875
1876 // And either 2 or 4 pointers.
1877 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1878 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1879
1880 // Align the offset.
1881 unsigned AlignedOffsetInBytes =
1882 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1883
1884 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1885 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00001886 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00001887 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001888 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001889 if (NumPaddingBytes > 1)
1890 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1891
John McCall0774cb82011-05-15 01:53:33 +00001892 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001893
1894 // We want a packed struct.
1895 Packed = true;
1896 }
1897 }
1898
1899 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001900 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001901
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001902 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001903
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001904 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001905
John McCall0774cb82011-05-15 01:53:33 +00001906 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001907
1908 return Info.first;
1909}
1910
1911/// Initialize the structural components of a __block variable, i.e.
1912/// everything but the actual object.
1913void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001914 // Find the address of the local.
1915 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001916
John McCallf0c11f72011-03-31 08:03:29 +00001917 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001918 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001919 cast<llvm::PointerType>(addr->getType())->getElementType());
1920
1921 // Build the byref helpers if necessary. This is null if we don't need any.
1922 CodeGenModule::ByrefHelpers *helpers =
1923 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001924
1925 const VarDecl &D = *emission.Variable;
1926 QualType type = D.getType();
1927
John McCallf0c11f72011-03-31 08:03:29 +00001928 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001929
1930 // Initialize the 'isa', which is just 0 or 1.
1931 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001932 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001933 isa = 1;
1934 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1935 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1936
1937 // Store the address of the variable into its own forwarding pointer.
1938 Builder.CreateStore(addr,
1939 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1940
1941 // Blocks ABI:
1942 // c) the flags field is set to either 0 if no helper functions are
1943 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1944 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001945 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001946 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1947 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1948
John McCallf0c11f72011-03-31 08:03:29 +00001949 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1950 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001951 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1952
John McCallf0c11f72011-03-31 08:03:29 +00001953 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001954 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001955 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001956
1957 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001958 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001959 }
1960}
1961
John McCalld16c2cf2011-02-08 08:22:06 +00001962void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001963 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001964 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001965 V = Builder.CreateBitCast(V, Int8PtrTy);
1966 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001967 Builder.CreateCall2(F, V, N);
1968}
John McCall5af02db2011-03-31 01:59:53 +00001969
1970namespace {
1971 struct CallBlockRelease : EHScopeStack::Cleanup {
1972 llvm::Value *Addr;
1973 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1974
John McCallad346f42011-07-12 20:27:29 +00001975 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001976 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00001977 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1978 }
1979 };
1980}
1981
1982/// Enter a cleanup to destroy a __block variable. Note that this
1983/// cleanup should be a no-op if the variable hasn't left the stack
1984/// yet; if a cleanup is required for the variable itself, that needs
1985/// to be done externally.
1986void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1987 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00001988 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00001989 return;
1990
1991 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1992}
John McCall13db5cf2011-09-09 20:41:01 +00001993
1994/// Adjust the declaration of something from the blocks API.
1995static void configureBlocksRuntimeObject(CodeGenModule &CGM,
1996 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001997 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00001998
1999 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2000 if (GV->isDeclaration() &&
2001 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2002 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2003}
2004
2005llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2006 if (BlockObjectDispose)
2007 return BlockObjectDispose;
2008
2009 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2010 llvm::FunctionType *fty
2011 = llvm::FunctionType::get(VoidTy, args, false);
2012 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2013 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2014 return BlockObjectDispose;
2015}
2016
2017llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2018 if (BlockObjectAssign)
2019 return BlockObjectAssign;
2020
2021 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2022 llvm::FunctionType *fty
2023 = llvm::FunctionType::get(VoidTy, args, false);
2024 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2025 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2026 return BlockObjectAssign;
2027}
2028
2029llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2030 if (NSConcreteGlobalBlock)
2031 return NSConcreteGlobalBlock;
2032
2033 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2034 Int8PtrTy->getPointerTo(), 0);
2035 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2036 return NSConcreteGlobalBlock;
2037}
2038
2039llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2040 if (NSConcreteStackBlock)
2041 return NSConcreteStackBlock;
2042
2043 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2044 Int8PtrTy->getPointerTo(), 0);
2045 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2046 return NSConcreteStackBlock;
2047}