blob: 8fc43442018cd41a58b4433cd7630ac5437bcb8f [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.
95 if (C.getLangOptions().ObjC1)
96 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,
218 const VarDecl *var) {
219 QualType type = var->getType();
220
221 // We can only do this if the variable is const.
222 if (!type.isConstQualified()) return 0;
223
John McCall461c9c12011-02-08 03:07:00 +0000224 // Furthermore, in C++ we have to worry about mutable fields:
225 // C++ [dcl.type.cv]p4:
226 // Except that any class member declared mutable can be
227 // modified, any attempt to modify a const object during its
228 // lifetime results in undefined behavior.
229 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000230 return 0;
231
232 // If the variable doesn't have any initializer (shouldn't this be
233 // invalid?), it's not clear what we should do. Maybe capture as
234 // zero?
235 const Expr *init = var->getInit();
236 if (!init) return 0;
237
238 return CGM.EmitConstantExpr(init, var->getType());
239}
240
241/// Get the low bit of a nonzero character count. This is the
242/// alignment of the nth byte if the 0th byte is universally aligned.
243static CharUnits getLowBit(CharUnits v) {
244 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
245}
246
247static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000249 ASTContext &C = CGM.getContext();
250
251 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
252 CharUnits ptrSize, ptrAlign, intSize, intAlign;
253 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
254 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
255
256 // Are there crazy embedded platforms where this isn't true?
257 assert(intSize <= ptrSize && "layout assumptions horribly violated");
258
259 CharUnits headerSize = ptrSize;
260 if (2 * intSize < ptrAlign) headerSize += ptrSize;
261 else headerSize += 2 * intSize;
262 headerSize += 2 * ptrSize;
263
264 info.BlockAlign = ptrAlign;
265 info.BlockSize = headerSize;
266
267 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000268 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
269 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000270 elementTypes.push_back(i8p);
271 elementTypes.push_back(intTy);
272 elementTypes.push_back(intTy);
273 elementTypes.push_back(i8p);
274 elementTypes.push_back(CGM.getBlockDescriptorType());
275
276 assert(elementTypes.size() == BlockHeaderSize);
277}
278
279/// Compute the layout of the given block. Attempts to lay the block
280/// out with minimal space requirements.
281static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
282 ASTContext &C = CGM.getContext();
283 const BlockDecl *block = info.getBlockDecl();
284
Chris Lattner5f9e2722011-07-23 10:55:15 +0000285 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000286 initializeForBlockHeader(CGM, info, elementTypes);
287
288 if (!block->hasCaptures()) {
289 info.StructureType =
290 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
291 info.CanBeGlobal = true;
292 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000293 }
Mike Stump00470a12009-03-05 08:32:30 +0000294
John McCall6b5a61b2011-02-07 10:33:21 +0000295 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000296 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000297 layout.reserve(block->capturesCXXThis() +
298 (block->capture_end() - block->capture_begin()));
299
300 CharUnits maxFieldAlign;
301
302 // First, 'this'.
303 if (block->capturesCXXThis()) {
304 const DeclContext *DC = block->getDeclContext();
305 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
306 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000307 QualType thisType;
308 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
309 thisType = C.getPointerType(C.getRecordType(RD));
310 else
311 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000312
Jay Foadef6de3d2011-07-11 09:56:20 +0000313 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000314 std::pair<CharUnits,CharUnits> tinfo
315 = CGM.getContext().getTypeInfoInChars(thisType);
316 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
317
318 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
319 }
320
321 // Next, all the block captures.
322 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
323 ce = block->capture_end(); ci != ce; ++ci) {
324 const VarDecl *variable = ci->getVariable();
325
326 if (ci->isByRef()) {
327 // We have to copy/dispose of the __block reference.
328 info.NeedsCopyDispose = true;
329
John McCall6b5a61b2011-02-07 10:33:21 +0000330 // Just use void* instead of a pointer to the byref type.
331 QualType byRefPtrTy = C.VoidPtrTy;
332
Jay Foadef6de3d2011-07-11 09:56:20 +0000333 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000334 std::pair<CharUnits,CharUnits> tinfo
335 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
336 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
337
338 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
339 &*ci, llvmType));
340 continue;
341 }
342
343 // Otherwise, build a layout chunk with the size and alignment of
344 // the declaration.
345 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
346 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
347 continue;
348 }
349
John McCallf85e1932011-06-15 23:02:42 +0000350 // If we have a lifetime qualifier, honor it for capture purposes.
351 // That includes *not* copying it if it's __unsafe_unretained.
352 if (Qualifiers::ObjCLifetime lifetime
353 = variable->getType().getObjCLifetime()) {
354 switch (lifetime) {
355 case Qualifiers::OCL_None: llvm_unreachable("impossible");
356 case Qualifiers::OCL_ExplicitNone:
357 case Qualifiers::OCL_Autoreleasing:
358 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000359
John McCallf85e1932011-06-15 23:02:42 +0000360 case Qualifiers::OCL_Strong:
361 case Qualifiers::OCL_Weak:
362 info.NeedsCopyDispose = true;
363 }
364
365 // Block pointers require copy/dispose. So do Objective-C pointers.
366 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000367 info.NeedsCopyDispose = true;
368
369 // So do types that require non-trivial copy construction.
370 } else if (ci->hasCopyExpr()) {
371 info.NeedsCopyDispose = true;
372 info.HasCXXObject = true;
373
374 // And so do types with destructors.
375 } else if (CGM.getLangOptions().CPlusPlus) {
376 if (const CXXRecordDecl *record =
377 variable->getType()->getAsCXXRecordDecl()) {
378 if (!record->hasTrivialDestructor()) {
379 info.HasCXXObject = true;
380 info.NeedsCopyDispose = true;
381 }
382 }
383 }
384
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000385 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000386 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000387 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000388
John McCall6b5a61b2011-02-07 10:33:21 +0000389 maxFieldAlign = std::max(maxFieldAlign, align);
390
Jay Foadef6de3d2011-07-11 09:56:20 +0000391 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000392 CGM.getTypes().ConvertTypeForMem(VT);
393
John McCall6b5a61b2011-02-07 10:33:21 +0000394 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
395 }
396
397 // If that was everything, we're done here.
398 if (layout.empty()) {
399 info.StructureType =
400 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
401 info.CanBeGlobal = true;
402 return;
403 }
404
405 // Sort the layout by alignment. We have to use a stable sort here
406 // to get reproducible results. There should probably be an
407 // llvm::array_pod_stable_sort.
408 std::stable_sort(layout.begin(), layout.end());
409
410 CharUnits &blockSize = info.BlockSize;
411 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
412
413 // Assuming that the first byte in the header is maximally aligned,
414 // get the alignment of the first byte following the header.
415 CharUnits endAlign = getLowBit(blockSize);
416
417 // If the end of the header isn't satisfactorily aligned for the
418 // maximum thing, look for things that are okay with the header-end
419 // alignment, and keep appending them until we get something that's
420 // aligned right. This algorithm is only guaranteed optimal if
421 // that condition is satisfied at some point; otherwise we can get
422 // things like:
423 // header // next byte has alignment 4
424 // something_with_size_5; // next byte has alignment 1
425 // something_with_alignment_8;
426 // which has 7 bytes of padding, as opposed to the naive solution
427 // which might have less (?).
428 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000429 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000430 li = layout.begin() + 1, le = layout.end();
431
432 // Look for something that the header end is already
433 // satisfactorily aligned for.
434 for (; li != le && endAlign < li->Alignment; ++li)
435 ;
436
437 // If we found something that's naturally aligned for the end of
438 // the header, keep adding things...
439 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000440 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000441 for (; li != le; ++li) {
442 assert(endAlign >= li->Alignment);
443
444 li->setIndex(info, elementTypes.size());
445 elementTypes.push_back(li->Type);
446 blockSize += li->Size;
447 endAlign = getLowBit(blockSize);
448
449 // ...until we get to the alignment of the maximum field.
450 if (endAlign >= maxFieldAlign)
451 break;
452 }
453
454 // Don't re-append everything we just appended.
455 layout.erase(first, li);
456 }
457 }
458
459 // At this point, we just have to add padding if the end align still
460 // isn't aligned right.
461 if (endAlign < maxFieldAlign) {
462 CharUnits padding = maxFieldAlign - endAlign;
463
John McCall5936e332011-02-15 09:22:45 +0000464 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
465 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000466 blockSize += padding;
467
468 endAlign = getLowBit(blockSize);
469 assert(endAlign >= maxFieldAlign);
470 }
471
472 // Slam everything else on now. This works because they have
473 // strictly decreasing alignment and we expect that size is always a
474 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000475 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000476 li = layout.begin(), le = layout.end(); li != le; ++li) {
477 assert(endAlign >= li->Alignment);
478 li->setIndex(info, elementTypes.size());
479 elementTypes.push_back(li->Type);
480 blockSize += li->Size;
481 endAlign = getLowBit(blockSize);
482 }
483
484 info.StructureType =
485 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
486}
487
John McCall1a343eb2011-11-10 08:15:53 +0000488/// Enter the scope of a block. This should be run at the entrance to
489/// a full-expression so that the block's cleanups are pushed at the
490/// right place in the stack.
491static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
492 // Allocate the block info and place it at the head of the list.
493 CGBlockInfo &blockInfo =
494 *new CGBlockInfo(block, CGF.CurFn->getName());
495 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
496 CGF.FirstBlockInfo = &blockInfo;
497
498 // Compute information about the layout, etc., of this block,
499 // pushing cleanups as necessary.
500 computeBlockInfo(CGF.CGM, blockInfo);
501
502 // Nothing else to do if it can be global.
503 if (blockInfo.CanBeGlobal) return;
504
505 // Make the allocation for the block.
506 blockInfo.Address =
507 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
508 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
509
510 // If there are cleanups to emit, enter them (but inactive).
511 if (!blockInfo.NeedsCopyDispose) return;
512
513 // Walk through the captures (in order) and find the ones not
514 // captured by constant.
515 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
516 ce = block->capture_end(); ci != ce; ++ci) {
517 // Ignore __block captures; there's nothing special in the
518 // on-stack block that we need to do for them.
519 if (ci->isByRef()) continue;
520
521 // Ignore variables that are constant-captured.
522 const VarDecl *variable = ci->getVariable();
523 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
524 if (capture.isConstant()) continue;
525
526 // Ignore objects that aren't destructed.
527 QualType::DestructionKind dtorKind =
528 variable->getType().isDestructedType();
529 if (dtorKind == QualType::DK_none) continue;
530
531 CodeGenFunction::Destroyer *destroyer;
532
533 // Block captures count as local values and have imprecise semantics.
534 // They also can't be arrays, so need to worry about that.
535 if (dtorKind == QualType::DK_objc_strong_lifetime) {
536 destroyer = &CodeGenFunction::destroyARCStrongImprecise;
537 } else {
538 destroyer = &CGF.getDestroyer(dtorKind);
539 }
540
541 // GEP down to the address.
542 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
543 capture.getIndex());
544
John McCall6f103ba2011-11-10 10:43:54 +0000545 // We can use that GEP as the dominating IP.
546 if (!blockInfo.DominatingIP)
547 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
548
John McCall1a343eb2011-11-10 08:15:53 +0000549 CleanupKind cleanupKind = InactiveNormalCleanup;
550 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
551 if (useArrayEHCleanup)
552 cleanupKind = InactiveNormalAndEHCleanup;
553
554 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
555 *destroyer, useArrayEHCleanup);
556
557 // Remember where that cleanup was.
558 capture.setCleanup(CGF.EHStack.stable_begin());
559 }
560}
561
562/// Enter a full-expression with a non-trivial number of objects to
563/// clean up. This is in this file because, at the moment, the only
564/// kind of cleanup object is a BlockDecl*.
565void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
566 assert(E->getNumObjects() != 0);
567 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
568 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
569 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
570 enterBlockScope(*this, *i);
571 }
572}
573
574/// Find the layout for the given block in a linked list and remove it.
575static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
576 const BlockDecl *block) {
577 while (true) {
578 assert(head && *head);
579 CGBlockInfo *cur = *head;
580
581 // If this is the block we're looking for, splice it out of the list.
582 if (cur->getBlockDecl() == block) {
583 *head = cur->NextBlockInfo;
584 return cur;
585 }
586
587 head = &cur->NextBlockInfo;
588 }
589}
590
591/// Destroy a chain of block layouts.
592void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
593 assert(head && "destroying an empty chain");
594 do {
595 CGBlockInfo *cur = head;
596 head = cur->NextBlockInfo;
597 delete cur;
598 } while (head != 0);
599}
600
John McCall6b5a61b2011-02-07 10:33:21 +0000601/// Emit a block literal expression in the current function.
602llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000603 // If the block has no captures, we won't have a pre-computed
604 // layout for it.
605 if (!blockExpr->getBlockDecl()->hasCaptures()) {
606 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
607 computeBlockInfo(CGM, blockInfo);
608 blockInfo.BlockExpression = blockExpr;
609 return EmitBlockLiteral(blockInfo);
610 }
John McCall6b5a61b2011-02-07 10:33:21 +0000611
John McCall1a343eb2011-11-10 08:15:53 +0000612 // Find the block info for this block and take ownership of it.
613 llvm::OwningPtr<CGBlockInfo> blockInfo;
614 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
615 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000616
John McCall1a343eb2011-11-10 08:15:53 +0000617 blockInfo->BlockExpression = blockExpr;
618 return EmitBlockLiteral(*blockInfo);
619}
620
621llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
622 // Using the computed layout, generate the actual block function.
John McCall6b5a61b2011-02-07 10:33:21 +0000623 llvm::Constant *blockFn
624 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
625 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000626 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000627
628 // If there is nothing to capture, we can emit this as a global block.
629 if (blockInfo.CanBeGlobal)
630 return buildGlobalBlock(CGM, blockInfo, blockFn);
631
632 // Otherwise, we have to emit this as a local block.
633
634 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000635 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000636
637 // Build the block descriptor.
638 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
639
John McCall1a343eb2011-11-10 08:15:53 +0000640 llvm::AllocaInst *blockAddr = blockInfo.Address;
641 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000642
643 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000644 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000645 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
646 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000647 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000648
649 // Initialize the block literal.
650 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000651 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000652 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000653 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000654 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
655 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
656 "block.invoke"));
657 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
658 "block.descriptor"));
659
660 // Finally, capture all the values into the block.
661 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
662
663 // First, 'this'.
664 if (blockDecl->capturesCXXThis()) {
665 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
666 blockInfo.CXXThisIndex,
667 "block.captured-this.addr");
668 Builder.CreateStore(LoadCXXThis(), addr);
669 }
670
671 // Next, captured variables.
672 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
673 ce = blockDecl->capture_end(); ci != ce; ++ci) {
674 const VarDecl *variable = ci->getVariable();
675 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
676
677 // Ignore constant captures.
678 if (capture.isConstant()) continue;
679
680 QualType type = variable->getType();
681
682 // This will be a [[type]]*, except that a byref entry will just be
683 // an i8**.
684 llvm::Value *blockField =
685 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
686 "block.captured");
687
688 // Compute the address of the thing we're going to move into the
689 // block literal.
690 llvm::Value *src;
691 if (ci->isNested()) {
692 // We need to use the capture from the enclosing block.
693 const CGBlockInfo::Capture &enclosingCapture =
694 BlockInfo->getCapture(variable);
695
696 // This is a [[type]]*, except that a byref entry wil just be an i8**.
697 src = Builder.CreateStructGEP(LoadBlockStruct(),
698 enclosingCapture.getIndex(),
699 "block.capture.addr");
700 } else {
701 // This is a [[type]]*.
702 src = LocalDeclMap[variable];
703 }
704
705 // For byrefs, we just write the pointer to the byref struct into
706 // the block field. There's no need to chase the forwarding
707 // pointer at this point, since we're building something that will
708 // live a shorter life than the stack byref anyway.
709 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000710 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000711 if (ci->isNested())
712 src = Builder.CreateLoad(src, "byref.capture");
713 else
John McCall5936e332011-02-15 09:22:45 +0000714 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000715
John McCall5936e332011-02-15 09:22:45 +0000716 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000717 Builder.CreateStore(src, blockField);
718
719 // If we have a copy constructor, evaluate that into the block field.
720 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
721 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
722
723 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000724 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000725 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
726
727 // Otherwise, fake up a POD copy into the block field.
728 } else {
John McCallf85e1932011-06-15 23:02:42 +0000729 // Fake up a new variable so that EmitScalarInit doesn't think
730 // we're referring to the variable in its own initializer.
731 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000732 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000733
John McCallbb699b02011-02-07 18:37:40 +0000734 // We use one of these or the other depending on whether the
735 // reference is nested.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000736 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
John McCallbb699b02011-02-07 18:37:40 +0000737 SourceLocation());
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000738 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
John McCallbb699b02011-02-07 18:37:40 +0000739 VK_LValue, SourceLocation(), /*byref*/ false);
740
741 Expr *declRef =
742 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
743
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000744 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000745 declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000746 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000747 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000748 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000749 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000750 }
751
John McCall1a343eb2011-11-10 08:15:53 +0000752 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000753 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000754 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
755 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000756 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000757 }
John McCall6b5a61b2011-02-07 10:33:21 +0000758 }
759
760 // Cast to the converted block-pointer type, which happens (somewhat
761 // unfortunately) to be a pointer to function type.
762 llvm::Value *result =
763 Builder.CreateBitCast(blockAddr,
764 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000765
John McCall6b5a61b2011-02-07 10:33:21 +0000766 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000767}
768
769
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000770llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000771 if (BlockDescriptorType)
772 return BlockDescriptorType;
773
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000774 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000775 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000776
Mike Stumpab695142009-02-13 15:16:56 +0000777 // struct __block_descriptor {
778 // unsigned long reserved;
779 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000780 //
781 // // later, the following will be added
782 //
783 // struct {
784 // void (*copyHelper)();
785 // void (*copyHelper)();
786 // } helpers; // !!! optional
787 //
788 // const char *signature; // the block signature
789 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000790 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000791 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000792 llvm::StructType::create("struct.__block_descriptor",
793 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000794
John McCall6b5a61b2011-02-07 10:33:21 +0000795 // Now form a pointer to that.
796 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000797 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000798}
799
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000800llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000801 if (GenericBlockLiteralType)
802 return GenericBlockLiteralType;
803
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000804 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000805
Mike Stump9b8a7972009-02-13 15:25:34 +0000806 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000807 // void *__isa;
808 // int __flags;
809 // int __reserved;
810 // void (*__invoke)(void *);
811 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000812 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000813 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000814 llvm::StructType::create("struct.__block_literal_generic",
815 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
816 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000817
Mike Stump9b8a7972009-02-13 15:25:34 +0000818 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000819}
820
Mike Stumpbd65cac2009-02-19 01:01:04 +0000821
Anders Carlssona1736c02009-12-24 21:13:40 +0000822RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
823 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000824 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000825 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000826
Anders Carlssonacfde802009-02-12 00:39:25 +0000827 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
828
829 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000830 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000831 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000832
833 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000834 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000835 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
836
837 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000838 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000839
Benjamin Kramer578faa82011-09-27 21:06:10 +0000840 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000841
Anders Carlssonacfde802009-02-12 00:39:25 +0000842 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000843 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000844 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000845
Anders Carlsson782f3972009-04-08 23:13:16 +0000846 QualType FnType = BPT->getPointeeType();
847
Anders Carlssonacfde802009-02-12 00:39:25 +0000848 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000849 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000850 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000851
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000852 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000853 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000854
John McCall64cd2322011-03-09 08:39:33 +0000855 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
Eli Friedmanc55db3b2011-08-09 17:38:12 +0000856 const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000858 // Cast the function pointer to the right type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000859 llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000860 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000861
Chris Lattner2acc6e32011-07-18 04:24:23 +0000862 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000863 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Anders Carlssonacfde802009-02-12 00:39:25 +0000865 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000866 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000867}
Anders Carlssond5cab542009-02-12 17:55:02 +0000868
John McCall6b5a61b2011-02-07 10:33:21 +0000869llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
870 bool isByRef) {
871 assert(BlockInfo && "evaluating block ref without block information?");
872 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000873
John McCall6b5a61b2011-02-07 10:33:21 +0000874 // Handle constant captures.
875 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000876
John McCall6b5a61b2011-02-07 10:33:21 +0000877 llvm::Value *addr =
878 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
879 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000880
John McCall6b5a61b2011-02-07 10:33:21 +0000881 if (isByRef) {
882 // addr should be a void** right now. Load, then cast the result
883 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000884
John McCall6b5a61b2011-02-07 10:33:21 +0000885 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000886 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000887 = llvm::PointerType::get(BuildByRefType(variable), 0);
888 addr = Builder.CreateBitCast(addr, byrefPointerType,
889 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000890
John McCall6b5a61b2011-02-07 10:33:21 +0000891 // Follow the forwarding pointer.
892 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
893 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000894
John McCall6b5a61b2011-02-07 10:33:21 +0000895 // Cast back to byref* and GEP over to the actual object.
896 addr = Builder.CreateBitCast(addr, byrefPointerType);
897 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
898 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000899 }
900
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000901 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000902 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000903
John McCall6b5a61b2011-02-07 10:33:21 +0000904 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000905}
906
Mike Stump67a64482009-02-14 22:16:35 +0000907llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000908CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000909 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000910 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
911 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000912
John McCall6b5a61b2011-02-07 10:33:21 +0000913 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000914 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000915
John McCall6b5a61b2011-02-07 10:33:21 +0000916 // Using that metadata, generate the actual block function.
917 llvm::Constant *blockFn;
918 {
919 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000920 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
921 blockInfo,
922 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000923 }
John McCall5936e332011-02-15 09:22:45 +0000924 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000925
John McCalld16c2cf2011-02-08 08:22:06 +0000926 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000927}
928
John McCall6b5a61b2011-02-07 10:33:21 +0000929static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
930 const CGBlockInfo &blockInfo,
931 llvm::Constant *blockFn) {
932 assert(blockInfo.CanBeGlobal);
933
934 // Generate the constants for the block literal initializer.
935 llvm::Constant *fields[BlockHeaderSize];
936
937 // isa
938 fields[0] = CGM.getNSConcreteGlobalBlock();
939
940 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000941 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
942 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
943
John McCall5936e332011-02-15 09:22:45 +0000944 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000945
946 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000947 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000948
949 // Function
950 fields[3] = blockFn;
951
952 // Descriptor
953 fields[4] = buildBlockDescriptor(CGM, blockInfo);
954
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000955 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000956
957 llvm::GlobalVariable *literal =
958 new llvm::GlobalVariable(CGM.getModule(),
959 init->getType(),
960 /*constant*/ true,
961 llvm::GlobalVariable::InternalLinkage,
962 init,
963 "__block_literal_global");
964 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
965
966 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000967 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +0000968 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
969 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000970}
971
Mike Stump00470a12009-03-05 08:32:30 +0000972llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000973CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
974 const CGBlockInfo &blockInfo,
975 const Decl *outerFnDecl,
976 const DeclMapTy &ldm) {
977 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000978
Devang Patel6d1155b2011-03-07 21:53:18 +0000979 // Check if we should generate debug info for this block function.
980 if (CGM.getModuleDebugInfo())
981 DebugInfo = CGM.getModuleDebugInfo();
982
John McCall6b5a61b2011-02-07 10:33:21 +0000983 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Mike Stump7f28a9c2009-03-13 23:34:28 +0000985 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000986 // to be local to this function as well, in case they're directly
987 // referenced in a block.
988 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
989 const VarDecl *var = dyn_cast<VarDecl>(i->first);
990 if (var && !var->hasLocalStorage())
991 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000992 }
993
John McCall6b5a61b2011-02-07 10:33:21 +0000994 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000995
John McCall6b5a61b2011-02-07 10:33:21 +0000996 // Build the argument list.
997 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000998
John McCall6b5a61b2011-02-07 10:33:21 +0000999 // The first argument is the block pointer. Just take it as a void*
1000 // and cast it later.
1001 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001002 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001003
John McCall8178df32011-02-22 22:38:33 +00001004 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1005 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001006 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001007
John McCall6b5a61b2011-02-07 10:33:21 +00001008 // Now add the rest of the parameters.
1009 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1010 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001011 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001012
John McCall6b5a61b2011-02-07 10:33:21 +00001013 // Create the function declaration.
1014 const FunctionProtoType *fnType =
1015 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
1016 const CGFunctionInfo &fnInfo =
1017 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
1018 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +00001019 if (CGM.ReturnTypeUsesSRet(fnInfo))
1020 blockInfo.UsesStret = true;
1021
Chris Lattner2acc6e32011-07-18 04:24:23 +00001022 llvm::FunctionType *fnLLVMType =
John McCall6b5a61b2011-02-07 10:33:21 +00001023 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +00001024
John McCall6b5a61b2011-02-07 10:33:21 +00001025 MangleBuffer name;
1026 CGM.getBlockMangledName(GD, name, blockDecl);
1027 llvm::Function *fn =
1028 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1029 name.getString(), &CGM.getModule());
1030 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001031
John McCall6b5a61b2011-02-07 10:33:21 +00001032 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001033 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001034 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001035 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001036
John McCall8178df32011-02-22 22:38:33 +00001037 // Okay. Undo some of what StartFunction did.
1038
1039 // Pull the 'self' reference out of the local decl map.
1040 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1041 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001042 BlockPointer = Builder.CreateBitCast(blockAddr,
1043 blockInfo.StructureType->getPointerTo(),
1044 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001045
John McCallea1471e2010-05-20 01:18:31 +00001046 // If we have a C++ 'this' reference, go ahead and force it into
1047 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001048 if (blockDecl->capturesCXXThis()) {
1049 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1050 blockInfo.CXXThisIndex,
1051 "block.captured-this");
1052 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001053 }
1054
John McCall6b5a61b2011-02-07 10:33:21 +00001055 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1056 // appease it.
1057 if (const ObjCMethodDecl *method
1058 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1059 const VarDecl *self = method->getSelfDecl();
1060
1061 // There might not be a capture for 'self', but if there is...
1062 if (blockInfo.Captures.count(self)) {
1063 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1064 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1065 capture.getIndex(),
1066 "block.captured-self");
1067 LocalDeclMap[self] = selfAddr;
1068 }
1069 }
1070
1071 // Also force all the constant captures.
1072 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1073 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1074 const VarDecl *variable = ci->getVariable();
1075 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1076 if (!capture.isConstant()) continue;
1077
1078 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1079
1080 llvm::AllocaInst *alloca =
1081 CreateMemTemp(variable->getType(), "block.captured-const");
1082 alloca->setAlignment(align);
1083
1084 Builder.CreateStore(capture.getConstant(), alloca, align);
1085
1086 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001087 }
1088
Mike Stumpb289b3f2009-10-01 22:29:41 +00001089 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
1090 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1091 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1092 --entry_ptr;
1093
John McCall6b5a61b2011-02-07 10:33:21 +00001094 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001095
Mike Stumpde8c5c72009-10-01 00:27:30 +00001096 // Remember where we were...
1097 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001098
Mike Stumpde8c5c72009-10-01 00:27:30 +00001099 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001100 ++entry_ptr;
1101 Builder.SetInsertPoint(entry, entry_ptr);
1102
John McCall6b5a61b2011-02-07 10:33:21 +00001103 // Emit debug information for all the BlockDeclRefDecls.
1104 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001105 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001106 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1107 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1108 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001109 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001110
1111 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1112 if (capture.isConstant()) {
1113 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1114 Builder);
1115 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001116 }
John McCall6b5a61b2011-02-07 10:33:21 +00001117
John McCall8178df32011-02-22 22:38:33 +00001118 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001119 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001120 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001121 }
John McCall6b5a61b2011-02-07 10:33:21 +00001122
Mike Stumpde8c5c72009-10-01 00:27:30 +00001123 // And resume where we left off.
1124 if (resume == 0)
1125 Builder.ClearInsertionPoint();
1126 else
1127 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001128
John McCall6b5a61b2011-02-07 10:33:21 +00001129 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001130
John McCall6b5a61b2011-02-07 10:33:21 +00001131 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001132}
Mike Stumpa99038c2009-02-28 09:07:16 +00001133
John McCall6b5a61b2011-02-07 10:33:21 +00001134/*
1135 notes.push_back(HelperInfo());
1136 HelperInfo &note = notes.back();
1137 note.index = capture.getIndex();
1138 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1139 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001140
John McCall6b5a61b2011-02-07 10:33:21 +00001141 if (ci->isByRef()) {
1142 note.flag = BLOCK_FIELD_IS_BYREF;
1143 if (type.isObjCGCWeak())
1144 note.flag |= BLOCK_FIELD_IS_WEAK;
1145 } else if (type->isBlockPointerType()) {
1146 note.flag = BLOCK_FIELD_IS_BLOCK;
1147 } else {
1148 note.flag = BLOCK_FIELD_IS_OBJECT;
1149 }
1150 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001151
Mike Stump00470a12009-03-05 08:32:30 +00001152
Mike Stumpa99038c2009-02-28 09:07:16 +00001153
John McCall6b5a61b2011-02-07 10:33:21 +00001154llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001155CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001156 ASTContext &C = getContext();
1157
1158 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001159 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1160 args.push_back(&dstDecl);
1161 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1162 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Mike Stumpa4f668f2009-03-06 01:33:24 +00001164 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001165 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001166
John McCall6b5a61b2011-02-07 10:33:21 +00001167 // FIXME: it would be nice if these were mergeable with things with
1168 // identical semantics.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001169 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001170
1171 llvm::Function *Fn =
1172 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001173 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001174
1175 IdentifierInfo *II
1176 = &CGM.getContext().Idents.get("__copy_helper_block_");
1177
Devang Patel58dc5ca2011-05-02 20:37:08 +00001178 // Check if we should generate debug info for this block helper function.
1179 if (CGM.getModuleDebugInfo())
1180 DebugInfo = CGM.getModuleDebugInfo();
1181
John McCall6b5a61b2011-02-07 10:33:21 +00001182 FunctionDecl *FD = FunctionDecl::Create(C,
1183 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001184 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001185 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001186 SC_Static,
1187 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001188 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001189 true);
John McCalld26bc762011-03-09 04:27:21 +00001190 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001191
Chris Lattner2acc6e32011-07-18 04:24:23 +00001192 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001193
John McCalld26bc762011-03-09 04:27:21 +00001194 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001195 src = Builder.CreateLoad(src);
1196 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001197
John McCalld26bc762011-03-09 04:27:21 +00001198 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001199 dst = Builder.CreateLoad(dst);
1200 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001201
John McCall6b5a61b2011-02-07 10:33:21 +00001202 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001203
John McCall6b5a61b2011-02-07 10:33:21 +00001204 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1205 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1206 const VarDecl *variable = ci->getVariable();
1207 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001208
John McCall6b5a61b2011-02-07 10:33:21 +00001209 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1210 if (capture.isConstant()) continue;
1211
1212 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001213 BlockFieldFlags flags;
1214
1215 bool isARCWeakCapture = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001216
1217 if (copyExpr) {
1218 assert(!ci->isByRef());
1219 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001220
John McCall6b5a61b2011-02-07 10:33:21 +00001221 } else if (ci->isByRef()) {
1222 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001223 if (type.isObjCGCWeak())
1224 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001225
John McCallf85e1932011-06-15 23:02:42 +00001226 } else if (type->isObjCRetainableType()) {
1227 flags = BLOCK_FIELD_IS_OBJECT;
1228 if (type->isBlockPointerType())
1229 flags = BLOCK_FIELD_IS_BLOCK;
1230
1231 // Special rules for ARC captures:
1232 if (getLangOptions().ObjCAutoRefCount) {
1233 Qualifiers qs = type.getQualifiers();
1234
1235 // Don't generate special copy logic for a captured object
1236 // unless it's __strong or __weak.
1237 if (!qs.hasStrongOrWeakObjCLifetime())
1238 continue;
1239
1240 // Support __weak direct captures.
1241 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1242 isARCWeakCapture = true;
1243 }
1244 } else {
1245 continue;
1246 }
John McCall6b5a61b2011-02-07 10:33:21 +00001247
1248 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001249 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1250 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001251
1252 // If there's an explicit copy expression, we do that.
1253 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001254 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCallf85e1932011-06-15 23:02:42 +00001255 } else if (isARCWeakCapture) {
1256 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001257 } else {
1258 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001259 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1260 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001261 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCallf85e1932011-06-15 23:02:42 +00001262 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
Mike Stump08920992009-03-07 02:35:30 +00001263 }
1264 }
1265
John McCalld16c2cf2011-02-08 08:22:06 +00001266 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001267
John McCall5936e332011-02-15 09:22:45 +00001268 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001269}
1270
John McCall6b5a61b2011-02-07 10:33:21 +00001271llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001272CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001273 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001274
John McCall6b5a61b2011-02-07 10:33:21 +00001275 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001276 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1277 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Mike Stumpa4f668f2009-03-06 01:33:24 +00001279 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001280 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001281
Mike Stump3899a7f2009-06-05 23:26:36 +00001282 // FIXME: We'd like to put these into a mergable by content, with
1283 // internal linkage.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001284 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001285
1286 llvm::Function *Fn =
1287 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001288 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001289
Devang Patel58dc5ca2011-05-02 20:37:08 +00001290 // Check if we should generate debug info for this block destroy function.
1291 if (CGM.getModuleDebugInfo())
1292 DebugInfo = CGM.getModuleDebugInfo();
1293
Mike Stumpa4f668f2009-03-06 01:33:24 +00001294 IdentifierInfo *II
1295 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1296
John McCall6b5a61b2011-02-07 10:33:21 +00001297 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001298 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001299 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001300 SC_Static,
1301 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001302 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001303 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001304
Chris Lattner2acc6e32011-07-18 04:24:23 +00001305 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001306
John McCalld26bc762011-03-09 04:27:21 +00001307 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001308 src = Builder.CreateLoad(src);
1309 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001310
John McCall6b5a61b2011-02-07 10:33:21 +00001311 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1312
John McCalld16c2cf2011-02-08 08:22:06 +00001313 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001314
1315 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1316 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1317 const VarDecl *variable = ci->getVariable();
1318 QualType type = variable->getType();
1319
1320 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1321 if (capture.isConstant()) continue;
1322
John McCalld16c2cf2011-02-08 08:22:06 +00001323 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001324 const CXXDestructorDecl *dtor = 0;
1325
John McCallf85e1932011-06-15 23:02:42 +00001326 bool isARCWeakCapture = false;
1327
John McCall6b5a61b2011-02-07 10:33:21 +00001328 if (ci->isByRef()) {
1329 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001330 if (type.isObjCGCWeak())
1331 flags |= BLOCK_FIELD_IS_WEAK;
1332 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1333 if (record->hasTrivialDestructor())
1334 continue;
1335 dtor = record->getDestructor();
1336 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001337 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001338 if (type->isBlockPointerType())
1339 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001340
John McCallf85e1932011-06-15 23:02:42 +00001341 // Special rules for ARC captures.
1342 if (getLangOptions().ObjCAutoRefCount) {
1343 Qualifiers qs = type.getQualifiers();
1344
1345 // Don't generate special dispose logic for a captured object
1346 // unless it's __strong or __weak.
1347 if (!qs.hasStrongOrWeakObjCLifetime())
1348 continue;
1349
1350 // Support __weak direct captures.
1351 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1352 isARCWeakCapture = true;
1353 }
1354 } else {
1355 continue;
1356 }
John McCall6b5a61b2011-02-07 10:33:21 +00001357
1358 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001359 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001360
1361 // If there's an explicit copy expression, we do that.
1362 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001363 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001364
John McCallf85e1932011-06-15 23:02:42 +00001365 // If this is a __weak capture, emit the release directly.
1366 } else if (isARCWeakCapture) {
1367 EmitARCDestroyWeak(srcField);
1368
John McCall6b5a61b2011-02-07 10:33:21 +00001369 // Otherwise we call _Block_object_dispose. It wouldn't be too
1370 // hard to just emit this as a cleanup if we wanted to make sure
1371 // that things were done in reverse.
1372 } else {
1373 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001374 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001375 BuildBlockRelease(value, flags);
1376 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001377 }
1378
John McCall6b5a61b2011-02-07 10:33:21 +00001379 cleanups.ForceCleanup();
1380
John McCalld16c2cf2011-02-08 08:22:06 +00001381 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001382
John McCall5936e332011-02-15 09:22:45 +00001383 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001384}
1385
John McCallf0c11f72011-03-31 08:03:29 +00001386namespace {
1387
1388/// Emits the copy/dispose helper functions for a __block object of id type.
1389class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1390 BlockFieldFlags Flags;
1391
1392public:
1393 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1394 : ByrefHelpers(alignment), Flags(flags) {}
1395
John McCall36170192011-03-31 09:19:20 +00001396 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1397 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001398 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1399
1400 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1401 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1402
1403 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1404
1405 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1406 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1407 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1408 }
1409
1410 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1411 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1412 llvm::Value *value = CGF.Builder.CreateLoad(field);
1413
1414 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1415 }
1416
1417 void profileImpl(llvm::FoldingSetNodeID &id) const {
1418 id.AddInteger(Flags.getBitMask());
1419 }
1420};
1421
John McCallf85e1932011-06-15 23:02:42 +00001422/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1423class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1424public:
1425 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1426
1427 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1428 llvm::Value *srcField) {
1429 CGF.EmitARCMoveWeak(destField, srcField);
1430 }
1431
1432 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1433 CGF.EmitARCDestroyWeak(field);
1434 }
1435
1436 void profileImpl(llvm::FoldingSetNodeID &id) const {
1437 // 0 is distinguishable from all pointers and byref flags
1438 id.AddInteger(0);
1439 }
1440};
1441
1442/// Emits the copy/dispose helpers for an ARC __block __strong variable
1443/// that's not of block-pointer type.
1444class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1445public:
1446 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1447
1448 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1449 llvm::Value *srcField) {
1450 // Do a "move" by copying the value and then zeroing out the old
1451 // variable.
1452
John McCalla59e4b72011-11-09 03:17:26 +00001453 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1454 value->setAlignment(Alignment.getQuantity());
1455
John McCallf85e1932011-06-15 23:02:42 +00001456 llvm::Value *null =
1457 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001458
1459 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1460 store->setAlignment(Alignment.getQuantity());
1461
1462 store = CGF.Builder.CreateStore(null, srcField);
1463 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001464 }
1465
1466 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCalla59e4b72011-11-09 03:17:26 +00001467 llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1468 value->setAlignment(Alignment.getQuantity());
1469
John McCallf85e1932011-06-15 23:02:42 +00001470 CGF.EmitARCRelease(value, /*precise*/ false);
1471 }
1472
1473 void profileImpl(llvm::FoldingSetNodeID &id) const {
1474 // 1 is distinguishable from all pointers and byref flags
1475 id.AddInteger(1);
1476 }
1477};
1478
John McCalla59e4b72011-11-09 03:17:26 +00001479/// Emits the copy/dispose helpers for an ARC __block __strong
1480/// variable that's of block-pointer type.
1481class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1482public:
1483 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1484
1485 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1486 llvm::Value *srcField) {
1487 // Do the copy with objc_retainBlock; that's all that
1488 // _Block_object_assign would do anyway, and we'd have to pass the
1489 // right arguments to make sure it doesn't get no-op'ed.
1490 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1491 oldValue->setAlignment(Alignment.getQuantity());
1492
1493 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1494
1495 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1496 store->setAlignment(Alignment.getQuantity());
1497 }
1498
1499 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1500 llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1501 value->setAlignment(Alignment.getQuantity());
1502
1503 CGF.EmitARCRelease(value, /*precise*/ false);
1504 }
1505
1506 void profileImpl(llvm::FoldingSetNodeID &id) const {
1507 // 2 is distinguishable from all pointers and byref flags
1508 id.AddInteger(2);
1509 }
1510};
1511
John McCallf0c11f72011-03-31 08:03:29 +00001512/// Emits the copy/dispose helpers for a __block variable with a
1513/// nontrivial copy constructor or destructor.
1514class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1515 QualType VarType;
1516 const Expr *CopyExpr;
1517
1518public:
1519 CXXByrefHelpers(CharUnits alignment, QualType type,
1520 const Expr *copyExpr)
1521 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1522
1523 bool needsCopy() const { return CopyExpr != 0; }
1524 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1525 llvm::Value *srcField) {
1526 if (!CopyExpr) return;
1527 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1528 }
1529
1530 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1531 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1532 CGF.PushDestructorCleanup(VarType, field);
1533 CGF.PopCleanupBlocks(cleanupDepth);
1534 }
1535
1536 void profileImpl(llvm::FoldingSetNodeID &id) const {
1537 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1538 }
1539};
1540} // end anonymous namespace
1541
1542static llvm::Constant *
1543generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001544 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001545 CodeGenModule::ByrefHelpers &byrefInfo) {
1546 ASTContext &Context = CGF.getContext();
1547
1548 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001549
John McCalld26bc762011-03-09 04:27:21 +00001550 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001551 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001552 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001553
John McCallf0c11f72011-03-31 08:03:29 +00001554 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001555 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Mike Stump45031c02009-03-06 02:29:21 +00001557 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001558 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001559
John McCallf0c11f72011-03-31 08:03:29 +00001560 CodeGenTypes &Types = CGF.CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001561 llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
Mike Stump45031c02009-03-06 02:29:21 +00001562
Mike Stump3899a7f2009-06-05 23:26:36 +00001563 // FIXME: We'd like to put these into a mergable by content, with
1564 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001565 llvm::Function *Fn =
1566 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001567 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001568
1569 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001570 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001571
John McCallf0c11f72011-03-31 08:03:29 +00001572 FunctionDecl *FD = FunctionDecl::Create(Context,
1573 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001574 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001575 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001576 SC_Static,
1577 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001578 false, true);
John McCallf85e1932011-06-15 23:02:42 +00001579
John McCallf0c11f72011-03-31 08:03:29 +00001580 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001581
John McCallf0c11f72011-03-31 08:03:29 +00001582 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001583 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001584
John McCallf0c11f72011-03-31 08:03:29 +00001585 // dst->x
1586 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1587 destField = CGF.Builder.CreateLoad(destField);
1588 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1589 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001590
John McCallf0c11f72011-03-31 08:03:29 +00001591 // src->x
1592 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1593 srcField = CGF.Builder.CreateLoad(srcField);
1594 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1595 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1596
1597 byrefInfo.emitCopy(CGF, destField, srcField);
1598 }
1599
1600 CGF.FinishFunction();
1601
1602 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001603}
1604
John McCallf0c11f72011-03-31 08:03:29 +00001605/// Build the copy helper for a __block variable.
1606static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001607 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001608 CodeGenModule::ByrefHelpers &info) {
1609 CodeGenFunction CGF(CGM);
1610 return generateByrefCopyHelper(CGF, byrefType, info);
1611}
1612
1613/// Generate code for a __block variable's dispose helper.
1614static llvm::Constant *
1615generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001616 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001617 CodeGenModule::ByrefHelpers &byrefInfo) {
1618 ASTContext &Context = CGF.getContext();
1619 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001620
John McCalld26bc762011-03-09 04:27:21 +00001621 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001622 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001623 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Mike Stump45031c02009-03-06 02:29:21 +00001625 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001626 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001627
John McCallf0c11f72011-03-31 08:03:29 +00001628 CodeGenTypes &Types = CGF.CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001629 llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
Mike Stump45031c02009-03-06 02:29:21 +00001630
Mike Stump3899a7f2009-06-05 23:26:36 +00001631 // FIXME: We'd like to put these into a mergable by content, with
1632 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001633 llvm::Function *Fn =
1634 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001635 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001636 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001637
1638 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001639 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001640
John McCallf0c11f72011-03-31 08:03:29 +00001641 FunctionDecl *FD = FunctionDecl::Create(Context,
1642 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001643 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001644 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001645 SC_Static,
1646 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001647 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001648 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001649
John McCallf0c11f72011-03-31 08:03:29 +00001650 if (byrefInfo.needsDispose()) {
1651 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1652 V = CGF.Builder.CreateLoad(V);
1653 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1654 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001655
John McCallf0c11f72011-03-31 08:03:29 +00001656 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001657 }
Mike Stump45031c02009-03-06 02:29:21 +00001658
John McCallf0c11f72011-03-31 08:03:29 +00001659 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001660
John McCallf0c11f72011-03-31 08:03:29 +00001661 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001662}
1663
John McCallf0c11f72011-03-31 08:03:29 +00001664/// Build the dispose helper for a __block variable.
1665static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001666 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001667 CodeGenModule::ByrefHelpers &info) {
1668 CodeGenFunction CGF(CGM);
1669 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001670}
1671
John McCallf0c11f72011-03-31 08:03:29 +00001672///
1673template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001674 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001675 T &byrefInfo) {
1676 // Increase the field's alignment to be at least pointer alignment,
1677 // since the layout of the byref struct will guarantee at least that.
1678 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1679 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1680
1681 llvm::FoldingSetNodeID id;
1682 byrefInfo.Profile(id);
1683
1684 void *insertPos;
1685 CodeGenModule::ByrefHelpers *node
1686 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1687 if (node) return static_cast<T*>(node);
1688
1689 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1690 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1691
1692 T *copy = new (CGM.getContext()) T(byrefInfo);
1693 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1694 return copy;
1695}
1696
1697CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001698CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001699 const AutoVarEmission &emission) {
1700 const VarDecl &var = *emission.Variable;
1701 QualType type = var.getType();
1702
1703 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1704 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1705 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1706
1707 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1708 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1709 }
1710
John McCallf85e1932011-06-15 23:02:42 +00001711 // Otherwise, if we don't have a retainable type, there's nothing to do.
1712 // that the runtime does extra copies.
1713 if (!type->isObjCRetainableType()) return 0;
1714
1715 Qualifiers qs = type.getQualifiers();
1716
1717 // If we have lifetime, that dominates.
1718 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1719 assert(getLangOptions().ObjCAutoRefCount);
1720
1721 switch (lifetime) {
1722 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1723
1724 // These are just bits as far as the runtime is concerned.
1725 case Qualifiers::OCL_ExplicitNone:
1726 case Qualifiers::OCL_Autoreleasing:
1727 return 0;
1728
1729 // Tell the runtime that this is ARC __weak, called by the
1730 // byref routines.
1731 case Qualifiers::OCL_Weak: {
1732 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1733 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1734 }
1735
1736 // ARC __strong __block variables need to be retained.
1737 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001738 // Block pointers need to be copied, and there's no direct
1739 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001740 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001741 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001742 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1743
1744 // Otherwise, we transfer ownership of the retain from the stack
1745 // to the heap.
1746 } else {
1747 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1748 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1749 }
1750 }
1751 llvm_unreachable("fell out of lifetime switch!");
1752 }
1753
John McCallf0c11f72011-03-31 08:03:29 +00001754 BlockFieldFlags flags;
1755 if (type->isBlockPointerType()) {
1756 flags |= BLOCK_FIELD_IS_BLOCK;
1757 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1758 type->isObjCObjectPointerType()) {
1759 flags |= BLOCK_FIELD_IS_OBJECT;
1760 } else {
1761 return 0;
1762 }
1763
1764 if (type.isObjCGCWeak())
1765 flags |= BLOCK_FIELD_IS_WEAK;
1766
1767 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1768 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001769}
1770
John McCall5af02db2011-03-31 01:59:53 +00001771unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1772 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1773
1774 return ByRefValueInfo.find(VD)->second.second;
1775}
1776
1777llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1778 const VarDecl *V) {
1779 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1780 Loc = Builder.CreateLoad(Loc);
1781 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1782 V->getNameAsString());
1783 return Loc;
1784}
1785
1786/// BuildByRefType - This routine changes a __block variable declared as T x
1787/// into:
1788///
1789/// struct {
1790/// void *__isa;
1791/// void *__forwarding;
1792/// int32_t __flags;
1793/// int32_t __size;
1794/// void *__copy_helper; // only if needed
1795/// void *__destroy_helper; // only if needed
1796/// char padding[X]; // only if needed
1797/// T x;
1798/// } x
1799///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001800llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1801 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001802 if (Info.first)
1803 return Info.first;
1804
1805 QualType Ty = D->getType();
1806
Chris Lattner5f9e2722011-07-23 10:55:15 +00001807 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001808
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001809 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001810 llvm::StructType::create(getLLVMContext(),
1811 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001812
1813 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001814 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001815
1816 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001817 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001818
1819 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001820 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001821
1822 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001823 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001824
1825 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1826 if (HasCopyAndDispose) {
1827 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001828 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001829
1830 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001831 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001832 }
1833
1834 bool Packed = false;
1835 CharUnits Align = getContext().getDeclAlign(D);
1836 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1837 // We have to insert padding.
1838
1839 // The struct above has 2 32-bit integers.
1840 unsigned CurrentOffsetInBytes = 4 * 2;
1841
1842 // And either 2 or 4 pointers.
1843 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1844 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1845
1846 // Align the offset.
1847 unsigned AlignedOffsetInBytes =
1848 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1849
1850 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1851 if (NumPaddingBytes > 0) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001852 llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
John McCall5af02db2011-03-31 01:59:53 +00001853 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001854 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001855 if (NumPaddingBytes > 1)
1856 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1857
John McCall0774cb82011-05-15 01:53:33 +00001858 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001859
1860 // We want a packed struct.
1861 Packed = true;
1862 }
1863 }
1864
1865 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001866 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001867
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001868 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001869
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001870 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001871
John McCall0774cb82011-05-15 01:53:33 +00001872 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001873
1874 return Info.first;
1875}
1876
1877/// Initialize the structural components of a __block variable, i.e.
1878/// everything but the actual object.
1879void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001880 // Find the address of the local.
1881 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001882
John McCallf0c11f72011-03-31 08:03:29 +00001883 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001884 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001885 cast<llvm::PointerType>(addr->getType())->getElementType());
1886
1887 // Build the byref helpers if necessary. This is null if we don't need any.
1888 CodeGenModule::ByrefHelpers *helpers =
1889 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001890
1891 const VarDecl &D = *emission.Variable;
1892 QualType type = D.getType();
1893
John McCallf0c11f72011-03-31 08:03:29 +00001894 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001895
1896 // Initialize the 'isa', which is just 0 or 1.
1897 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001898 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001899 isa = 1;
1900 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1901 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1902
1903 // Store the address of the variable into its own forwarding pointer.
1904 Builder.CreateStore(addr,
1905 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1906
1907 // Blocks ABI:
1908 // c) the flags field is set to either 0 if no helper functions are
1909 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1910 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001911 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001912 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1913 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1914
John McCallf0c11f72011-03-31 08:03:29 +00001915 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1916 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001917 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1918
John McCallf0c11f72011-03-31 08:03:29 +00001919 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001920 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001921 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001922
1923 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001924 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001925 }
1926}
1927
John McCalld16c2cf2011-02-08 08:22:06 +00001928void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001929 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001930 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001931 V = Builder.CreateBitCast(V, Int8PtrTy);
1932 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001933 Builder.CreateCall2(F, V, N);
1934}
John McCall5af02db2011-03-31 01:59:53 +00001935
1936namespace {
1937 struct CallBlockRelease : EHScopeStack::Cleanup {
1938 llvm::Value *Addr;
1939 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1940
John McCallad346f42011-07-12 20:27:29 +00001941 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001942 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00001943 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1944 }
1945 };
1946}
1947
1948/// Enter a cleanup to destroy a __block variable. Note that this
1949/// cleanup should be a no-op if the variable hasn't left the stack
1950/// yet; if a cleanup is required for the variable itself, that needs
1951/// to be done externally.
1952void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1953 // We don't enter this cleanup if we're in pure-GC mode.
Douglas Gregore289d812011-09-13 17:21:33 +00001954 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00001955 return;
1956
1957 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1958}
John McCall13db5cf2011-09-09 20:41:01 +00001959
1960/// Adjust the declaration of something from the blocks API.
1961static void configureBlocksRuntimeObject(CodeGenModule &CGM,
1962 llvm::Constant *C) {
1963 if (!CGM.getLangOptions().BlocksRuntimeOptional) return;
1964
1965 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
1966 if (GV->isDeclaration() &&
1967 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
1968 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1969}
1970
1971llvm::Constant *CodeGenModule::getBlockObjectDispose() {
1972 if (BlockObjectDispose)
1973 return BlockObjectDispose;
1974
1975 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
1976 llvm::FunctionType *fty
1977 = llvm::FunctionType::get(VoidTy, args, false);
1978 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
1979 configureBlocksRuntimeObject(*this, BlockObjectDispose);
1980 return BlockObjectDispose;
1981}
1982
1983llvm::Constant *CodeGenModule::getBlockObjectAssign() {
1984 if (BlockObjectAssign)
1985 return BlockObjectAssign;
1986
1987 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
1988 llvm::FunctionType *fty
1989 = llvm::FunctionType::get(VoidTy, args, false);
1990 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
1991 configureBlocksRuntimeObject(*this, BlockObjectAssign);
1992 return BlockObjectAssign;
1993}
1994
1995llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
1996 if (NSConcreteGlobalBlock)
1997 return NSConcreteGlobalBlock;
1998
1999 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2000 Int8PtrTy->getPointerTo(), 0);
2001 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2002 return NSConcreteGlobalBlock;
2003}
2004
2005llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2006 if (NSConcreteStackBlock)
2007 return NSConcreteStackBlock;
2008
2009 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2010 Int8PtrTy->getPointerTo(), 0);
2011 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2012 return NSConcreteStackBlock;
2013}