blob: 9825c1ea697b972faa1454ee1871da6602c353da [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),
30 HasCXXObject(false), UsesStret(false), StructureType(0), Block(block) {
John McCallee504292010-05-21 04:11:14 +000031
John McCall1a343eb2011-11-10 08:15:53 +000032 // Skip asm prefix, if any. 'name' is usually taken directly from
33 // the mangled name of the enclosing function.
34 if (!name.empty() && name[0] == '\01')
35 name = name.substr(1);
John McCallee504292010-05-21 04:11:14 +000036}
37
John McCallf0c11f72011-03-31 08:03:29 +000038// Anchor the vtable to this translation unit.
39CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
40
John McCall6b5a61b2011-02-07 10:33:21 +000041/// Build the given block as a global block.
42static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
43 const CGBlockInfo &blockInfo,
44 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000045
John McCall6b5a61b2011-02-07 10:33:21 +000046/// Build the helper function to copy a block.
47static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
48 const CGBlockInfo &blockInfo) {
49 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
50}
51
52/// Build the helper function to dipose of a block.
53static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
54 const CGBlockInfo &blockInfo) {
55 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
56}
57
58/// Build the block descriptor constant for a block.
59static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
60 const CGBlockInfo &blockInfo) {
61 ASTContext &C = CGM.getContext();
62
Chris Lattner2acc6e32011-07-18 04:24:23 +000063 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
64 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000065
Chris Lattner5f9e2722011-07-23 10:55:15 +000066 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000067
68 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000069 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000070
71 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000072 // FIXME: What is the right way to say this doesn't fit? We should give
73 // a user diagnostic in that case. Better fix would be to change the
74 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000075 elements.push_back(llvm::ConstantInt::get(ulong,
76 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000077
John McCall6b5a61b2011-02-07 10:33:21 +000078 // Optional copy/dispose helpers.
79 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000080 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000081 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000082
83 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000084 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000085 }
86
John McCall6b5a61b2011-02-07 10:33:21 +000087 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
88 std::string typeAtEncoding =
89 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
90 elements.push_back(llvm::ConstantExpr::getBitCast(
91 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000092
John McCall6b5a61b2011-02-07 10:33:21 +000093 // GC layout.
94 if (C.getLangOptions().ObjC1)
95 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
96 else
97 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000098
Chris Lattnerc5cbb902011-06-20 04:01:35 +000099 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000100
John McCall6b5a61b2011-02-07 10:33:21 +0000101 llvm::GlobalVariable *global =
102 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
103 llvm::GlobalValue::InternalLinkage,
104 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000105
John McCall6b5a61b2011-02-07 10:33:21 +0000106 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000107}
108
John McCall6b5a61b2011-02-07 10:33:21 +0000109/*
110 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000111
John McCall6b5a61b2011-02-07 10:33:21 +0000112 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
113 struct Block_literal {
114 /// Initialized to one of:
115 /// extern void *_NSConcreteStackBlock[];
116 /// extern void *_NSConcreteGlobalBlock[];
117 ///
118 /// In theory, we could start one off malloc'ed by setting
119 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
120 /// this isa:
121 /// extern void *_NSConcreteMallocBlock[];
122 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000123
John McCall6b5a61b2011-02-07 10:33:21 +0000124 /// These are the flags (with corresponding bit number) that the
125 /// compiler is actually supposed to know about.
126 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
127 /// descriptor provides copy and dispose helper functions
128 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
129 /// object with a nontrivial destructor or copy constructor
130 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
131 /// as global memory
132 /// 29. BLOCK_USE_STRET - indicates that the block function
133 /// uses stret, which objc_msgSend needs to know about
134 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
135 /// @encoded signature string
136 /// And we're not supposed to manipulate these:
137 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
138 /// to malloc'ed memory
139 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
140 /// to GC-allocated memory
141 /// Additionally, the bottom 16 bits are a reference count which
142 /// should be zero on the stack.
143 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000144
John McCall6b5a61b2011-02-07 10:33:21 +0000145 /// Reserved; should be zero-initialized.
146 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000147
John McCall6b5a61b2011-02-07 10:33:21 +0000148 /// Function pointer generated from block literal.
149 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000150
John McCall6b5a61b2011-02-07 10:33:21 +0000151 /// Block description metadata generated from block literal.
152 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000153
John McCall6b5a61b2011-02-07 10:33:21 +0000154 /// Captured values follow.
155 _CapturesTypes captures...;
156 };
157 */
David Chisnall5e530af2009-11-17 19:33:30 +0000158
John McCall6b5a61b2011-02-07 10:33:21 +0000159/// The number of fields in a block header.
160const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000161
John McCall6b5a61b2011-02-07 10:33:21 +0000162namespace {
163 /// A chunk of data that we actually have to capture in the block.
164 struct BlockLayoutChunk {
165 CharUnits Alignment;
166 CharUnits Size;
167 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000168 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000169
John McCall6b5a61b2011-02-07 10:33:21 +0000170 BlockLayoutChunk(CharUnits align, CharUnits size,
171 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000172 llvm::Type *type)
John McCall6b5a61b2011-02-07 10:33:21 +0000173 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000174
John McCall6b5a61b2011-02-07 10:33:21 +0000175 /// Tell the block info that this chunk has the given field index.
176 void setIndex(CGBlockInfo &info, unsigned index) {
177 if (!Capture)
178 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000179 else
John McCall6b5a61b2011-02-07 10:33:21 +0000180 info.Captures[Capture->getVariable()]
181 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000182 }
John McCall6b5a61b2011-02-07 10:33:21 +0000183 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000184
John McCall6b5a61b2011-02-07 10:33:21 +0000185 /// Order by descending alignment.
186 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
187 return left.Alignment > right.Alignment;
188 }
189}
190
John McCall461c9c12011-02-08 03:07:00 +0000191/// Determines if the given type is safe for constant capture in C++.
192static bool isSafeForCXXConstantCapture(QualType type) {
193 const RecordType *recordType =
194 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
195
196 // Only records can be unsafe.
197 if (!recordType) return true;
198
199 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
200
201 // Maintain semantics for classes with non-trivial dtors or copy ctors.
202 if (!record->hasTrivialDestructor()) return false;
203 if (!record->hasTrivialCopyConstructor()) return false;
204
205 // Otherwise, we just have to make sure there aren't any mutable
206 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000207 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000208}
209
John McCall6b5a61b2011-02-07 10:33:21 +0000210/// It is illegal to modify a const object after initialization.
211/// Therefore, if a const object has a constant initializer, we don't
212/// actually need to keep storage for it in the block; we'll just
213/// rematerialize it at the start of the block function. This is
214/// acceptable because we make no promises about address stability of
215/// captured variables.
216static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
217 const VarDecl *var) {
218 QualType type = var->getType();
219
220 // We can only do this if the variable is const.
221 if (!type.isConstQualified()) return 0;
222
John McCall461c9c12011-02-08 03:07:00 +0000223 // Furthermore, in C++ we have to worry about mutable fields:
224 // C++ [dcl.type.cv]p4:
225 // Except that any class member declared mutable can be
226 // modified, any attempt to modify a const object during its
227 // lifetime results in undefined behavior.
228 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000229 return 0;
230
231 // If the variable doesn't have any initializer (shouldn't this be
232 // invalid?), it's not clear what we should do. Maybe capture as
233 // zero?
234 const Expr *init = var->getInit();
235 if (!init) return 0;
236
237 return CGM.EmitConstantExpr(init, var->getType());
238}
239
240/// Get the low bit of a nonzero character count. This is the
241/// alignment of the nth byte if the 0th byte is universally aligned.
242static CharUnits getLowBit(CharUnits v) {
243 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
244}
245
246static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000247 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000248 ASTContext &C = CGM.getContext();
249
250 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
251 CharUnits ptrSize, ptrAlign, intSize, intAlign;
252 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
253 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
254
255 // Are there crazy embedded platforms where this isn't true?
256 assert(intSize <= ptrSize && "layout assumptions horribly violated");
257
258 CharUnits headerSize = ptrSize;
259 if (2 * intSize < ptrAlign) headerSize += ptrSize;
260 else headerSize += 2 * intSize;
261 headerSize += 2 * ptrSize;
262
263 info.BlockAlign = ptrAlign;
264 info.BlockSize = headerSize;
265
266 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000267 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
268 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000269 elementTypes.push_back(i8p);
270 elementTypes.push_back(intTy);
271 elementTypes.push_back(intTy);
272 elementTypes.push_back(i8p);
273 elementTypes.push_back(CGM.getBlockDescriptorType());
274
275 assert(elementTypes.size() == BlockHeaderSize);
276}
277
278/// Compute the layout of the given block. Attempts to lay the block
279/// out with minimal space requirements.
280static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
281 ASTContext &C = CGM.getContext();
282 const BlockDecl *block = info.getBlockDecl();
283
Chris Lattner5f9e2722011-07-23 10:55:15 +0000284 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000285 initializeForBlockHeader(CGM, info, elementTypes);
286
287 if (!block->hasCaptures()) {
288 info.StructureType =
289 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
290 info.CanBeGlobal = true;
291 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000292 }
Mike Stump00470a12009-03-05 08:32:30 +0000293
John McCall6b5a61b2011-02-07 10:33:21 +0000294 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000295 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000296 layout.reserve(block->capturesCXXThis() +
297 (block->capture_end() - block->capture_begin()));
298
299 CharUnits maxFieldAlign;
300
301 // First, 'this'.
302 if (block->capturesCXXThis()) {
303 const DeclContext *DC = block->getDeclContext();
304 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
305 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000306 QualType thisType;
307 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
308 thisType = C.getPointerType(C.getRecordType(RD));
309 else
310 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000311
Jay Foadef6de3d2011-07-11 09:56:20 +0000312 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000313 std::pair<CharUnits,CharUnits> tinfo
314 = CGM.getContext().getTypeInfoInChars(thisType);
315 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
316
317 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
318 }
319
320 // Next, all the block captures.
321 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
322 ce = block->capture_end(); ci != ce; ++ci) {
323 const VarDecl *variable = ci->getVariable();
324
325 if (ci->isByRef()) {
326 // We have to copy/dispose of the __block reference.
327 info.NeedsCopyDispose = true;
328
John McCall6b5a61b2011-02-07 10:33:21 +0000329 // Just use void* instead of a pointer to the byref type.
330 QualType byRefPtrTy = C.VoidPtrTy;
331
Jay Foadef6de3d2011-07-11 09:56:20 +0000332 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000333 std::pair<CharUnits,CharUnits> tinfo
334 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
335 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
336
337 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
338 &*ci, llvmType));
339 continue;
340 }
341
342 // Otherwise, build a layout chunk with the size and alignment of
343 // the declaration.
344 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
345 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
346 continue;
347 }
348
John McCallf85e1932011-06-15 23:02:42 +0000349 // If we have a lifetime qualifier, honor it for capture purposes.
350 // That includes *not* copying it if it's __unsafe_unretained.
351 if (Qualifiers::ObjCLifetime lifetime
352 = variable->getType().getObjCLifetime()) {
353 switch (lifetime) {
354 case Qualifiers::OCL_None: llvm_unreachable("impossible");
355 case Qualifiers::OCL_ExplicitNone:
356 case Qualifiers::OCL_Autoreleasing:
357 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000358
John McCallf85e1932011-06-15 23:02:42 +0000359 case Qualifiers::OCL_Strong:
360 case Qualifiers::OCL_Weak:
361 info.NeedsCopyDispose = true;
362 }
363
364 // Block pointers require copy/dispose. So do Objective-C pointers.
365 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000366 info.NeedsCopyDispose = true;
367
368 // So do types that require non-trivial copy construction.
369 } else if (ci->hasCopyExpr()) {
370 info.NeedsCopyDispose = true;
371 info.HasCXXObject = true;
372
373 // And so do types with destructors.
374 } else if (CGM.getLangOptions().CPlusPlus) {
375 if (const CXXRecordDecl *record =
376 variable->getType()->getAsCXXRecordDecl()) {
377 if (!record->hasTrivialDestructor()) {
378 info.HasCXXObject = true;
379 info.NeedsCopyDispose = true;
380 }
381 }
382 }
383
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000384 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000385 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000386 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000387
John McCall6b5a61b2011-02-07 10:33:21 +0000388 maxFieldAlign = std::max(maxFieldAlign, align);
389
Jay Foadef6de3d2011-07-11 09:56:20 +0000390 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000391 CGM.getTypes().ConvertTypeForMem(VT);
392
John McCall6b5a61b2011-02-07 10:33:21 +0000393 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
394 }
395
396 // If that was everything, we're done here.
397 if (layout.empty()) {
398 info.StructureType =
399 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
400 info.CanBeGlobal = true;
401 return;
402 }
403
404 // Sort the layout by alignment. We have to use a stable sort here
405 // to get reproducible results. There should probably be an
406 // llvm::array_pod_stable_sort.
407 std::stable_sort(layout.begin(), layout.end());
408
409 CharUnits &blockSize = info.BlockSize;
410 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
411
412 // Assuming that the first byte in the header is maximally aligned,
413 // get the alignment of the first byte following the header.
414 CharUnits endAlign = getLowBit(blockSize);
415
416 // If the end of the header isn't satisfactorily aligned for the
417 // maximum thing, look for things that are okay with the header-end
418 // alignment, and keep appending them until we get something that's
419 // aligned right. This algorithm is only guaranteed optimal if
420 // that condition is satisfied at some point; otherwise we can get
421 // things like:
422 // header // next byte has alignment 4
423 // something_with_size_5; // next byte has alignment 1
424 // something_with_alignment_8;
425 // which has 7 bytes of padding, as opposed to the naive solution
426 // which might have less (?).
427 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000428 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000429 li = layout.begin() + 1, le = layout.end();
430
431 // Look for something that the header end is already
432 // satisfactorily aligned for.
433 for (; li != le && endAlign < li->Alignment; ++li)
434 ;
435
436 // If we found something that's naturally aligned for the end of
437 // the header, keep adding things...
438 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000439 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000440 for (; li != le; ++li) {
441 assert(endAlign >= li->Alignment);
442
443 li->setIndex(info, elementTypes.size());
444 elementTypes.push_back(li->Type);
445 blockSize += li->Size;
446 endAlign = getLowBit(blockSize);
447
448 // ...until we get to the alignment of the maximum field.
449 if (endAlign >= maxFieldAlign)
450 break;
451 }
452
453 // Don't re-append everything we just appended.
454 layout.erase(first, li);
455 }
456 }
457
458 // At this point, we just have to add padding if the end align still
459 // isn't aligned right.
460 if (endAlign < maxFieldAlign) {
461 CharUnits padding = maxFieldAlign - endAlign;
462
John McCall5936e332011-02-15 09:22:45 +0000463 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
464 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000465 blockSize += padding;
466
467 endAlign = getLowBit(blockSize);
468 assert(endAlign >= maxFieldAlign);
469 }
470
471 // Slam everything else on now. This works because they have
472 // strictly decreasing alignment and we expect that size is always a
473 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000474 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000475 li = layout.begin(), le = layout.end(); li != le; ++li) {
476 assert(endAlign >= li->Alignment);
477 li->setIndex(info, elementTypes.size());
478 elementTypes.push_back(li->Type);
479 blockSize += li->Size;
480 endAlign = getLowBit(blockSize);
481 }
482
483 info.StructureType =
484 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
485}
486
John McCall1a343eb2011-11-10 08:15:53 +0000487/// Enter the scope of a block. This should be run at the entrance to
488/// a full-expression so that the block's cleanups are pushed at the
489/// right place in the stack.
490static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
491 // Allocate the block info and place it at the head of the list.
492 CGBlockInfo &blockInfo =
493 *new CGBlockInfo(block, CGF.CurFn->getName());
494 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
495 CGF.FirstBlockInfo = &blockInfo;
496
497 // Compute information about the layout, etc., of this block,
498 // pushing cleanups as necessary.
499 computeBlockInfo(CGF.CGM, blockInfo);
500
501 // Nothing else to do if it can be global.
502 if (blockInfo.CanBeGlobal) return;
503
504 // Make the allocation for the block.
505 blockInfo.Address =
506 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
507 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
508
509 // If there are cleanups to emit, enter them (but inactive).
510 if (!blockInfo.NeedsCopyDispose) return;
511
512 // Walk through the captures (in order) and find the ones not
513 // captured by constant.
514 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
515 ce = block->capture_end(); ci != ce; ++ci) {
516 // Ignore __block captures; there's nothing special in the
517 // on-stack block that we need to do for them.
518 if (ci->isByRef()) continue;
519
520 // Ignore variables that are constant-captured.
521 const VarDecl *variable = ci->getVariable();
522 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
523 if (capture.isConstant()) continue;
524
525 // Ignore objects that aren't destructed.
526 QualType::DestructionKind dtorKind =
527 variable->getType().isDestructedType();
528 if (dtorKind == QualType::DK_none) continue;
529
530 CodeGenFunction::Destroyer *destroyer;
531
532 // Block captures count as local values and have imprecise semantics.
533 // They also can't be arrays, so need to worry about that.
534 if (dtorKind == QualType::DK_objc_strong_lifetime) {
535 destroyer = &CodeGenFunction::destroyARCStrongImprecise;
536 } else {
537 destroyer = &CGF.getDestroyer(dtorKind);
538 }
539
540 // GEP down to the address.
541 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
542 capture.getIndex());
543
544 CleanupKind cleanupKind = InactiveNormalCleanup;
545 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
546 if (useArrayEHCleanup)
547 cleanupKind = InactiveNormalAndEHCleanup;
548
549 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
550 *destroyer, useArrayEHCleanup);
551
552 // Remember where that cleanup was.
553 capture.setCleanup(CGF.EHStack.stable_begin());
554 }
555}
556
557/// Enter a full-expression with a non-trivial number of objects to
558/// clean up. This is in this file because, at the moment, the only
559/// kind of cleanup object is a BlockDecl*.
560void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
561 assert(E->getNumObjects() != 0);
562 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
563 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
564 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
565 enterBlockScope(*this, *i);
566 }
567}
568
569/// Find the layout for the given block in a linked list and remove it.
570static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
571 const BlockDecl *block) {
572 while (true) {
573 assert(head && *head);
574 CGBlockInfo *cur = *head;
575
576 // If this is the block we're looking for, splice it out of the list.
577 if (cur->getBlockDecl() == block) {
578 *head = cur->NextBlockInfo;
579 return cur;
580 }
581
582 head = &cur->NextBlockInfo;
583 }
584}
585
586/// Destroy a chain of block layouts.
587void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
588 assert(head && "destroying an empty chain");
589 do {
590 CGBlockInfo *cur = head;
591 head = cur->NextBlockInfo;
592 delete cur;
593 } while (head != 0);
594}
595
John McCall6b5a61b2011-02-07 10:33:21 +0000596/// Emit a block literal expression in the current function.
597llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000598 // If the block has no captures, we won't have a pre-computed
599 // layout for it.
600 if (!blockExpr->getBlockDecl()->hasCaptures()) {
601 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
602 computeBlockInfo(CGM, blockInfo);
603 blockInfo.BlockExpression = blockExpr;
604 return EmitBlockLiteral(blockInfo);
605 }
John McCall6b5a61b2011-02-07 10:33:21 +0000606
John McCall1a343eb2011-11-10 08:15:53 +0000607 // Find the block info for this block and take ownership of it.
608 llvm::OwningPtr<CGBlockInfo> blockInfo;
609 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
610 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000611
John McCall1a343eb2011-11-10 08:15:53 +0000612 blockInfo->BlockExpression = blockExpr;
613 return EmitBlockLiteral(*blockInfo);
614}
615
616llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
617 // Using the computed layout, generate the actual block function.
John McCall6b5a61b2011-02-07 10:33:21 +0000618 llvm::Constant *blockFn
619 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
620 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000621 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000622
623 // If there is nothing to capture, we can emit this as a global block.
624 if (blockInfo.CanBeGlobal)
625 return buildGlobalBlock(CGM, blockInfo, blockFn);
626
627 // Otherwise, we have to emit this as a local block.
628
629 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000630 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000631
632 // Build the block descriptor.
633 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
634
John McCall1a343eb2011-11-10 08:15:53 +0000635 llvm::AllocaInst *blockAddr = blockInfo.Address;
636 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000637
638 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000639 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000640 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
641 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000642 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000643
644 // Initialize the block literal.
645 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000646 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000647 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000648 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000649 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
650 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
651 "block.invoke"));
652 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
653 "block.descriptor"));
654
655 // Finally, capture all the values into the block.
656 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
657
658 // First, 'this'.
659 if (blockDecl->capturesCXXThis()) {
660 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
661 blockInfo.CXXThisIndex,
662 "block.captured-this.addr");
663 Builder.CreateStore(LoadCXXThis(), addr);
664 }
665
666 // Next, captured variables.
667 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
668 ce = blockDecl->capture_end(); ci != ce; ++ci) {
669 const VarDecl *variable = ci->getVariable();
670 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
671
672 // Ignore constant captures.
673 if (capture.isConstant()) continue;
674
675 QualType type = variable->getType();
676
677 // This will be a [[type]]*, except that a byref entry will just be
678 // an i8**.
679 llvm::Value *blockField =
680 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
681 "block.captured");
682
683 // Compute the address of the thing we're going to move into the
684 // block literal.
685 llvm::Value *src;
686 if (ci->isNested()) {
687 // We need to use the capture from the enclosing block.
688 const CGBlockInfo::Capture &enclosingCapture =
689 BlockInfo->getCapture(variable);
690
691 // This is a [[type]]*, except that a byref entry wil just be an i8**.
692 src = Builder.CreateStructGEP(LoadBlockStruct(),
693 enclosingCapture.getIndex(),
694 "block.capture.addr");
695 } else {
696 // This is a [[type]]*.
697 src = LocalDeclMap[variable];
698 }
699
700 // For byrefs, we just write the pointer to the byref struct into
701 // the block field. There's no need to chase the forwarding
702 // pointer at this point, since we're building something that will
703 // live a shorter life than the stack byref anyway.
704 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000705 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000706 if (ci->isNested())
707 src = Builder.CreateLoad(src, "byref.capture");
708 else
John McCall5936e332011-02-15 09:22:45 +0000709 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000710
John McCall5936e332011-02-15 09:22:45 +0000711 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000712 Builder.CreateStore(src, blockField);
713
714 // If we have a copy constructor, evaluate that into the block field.
715 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
716 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
717
718 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000719 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000720 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
721
722 // Otherwise, fake up a POD copy into the block field.
723 } else {
John McCallf85e1932011-06-15 23:02:42 +0000724 // Fake up a new variable so that EmitScalarInit doesn't think
725 // we're referring to the variable in its own initializer.
726 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000727 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000728
John McCallbb699b02011-02-07 18:37:40 +0000729 // We use one of these or the other depending on whether the
730 // reference is nested.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000731 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
John McCallbb699b02011-02-07 18:37:40 +0000732 SourceLocation());
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000733 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
John McCallbb699b02011-02-07 18:37:40 +0000734 VK_LValue, SourceLocation(), /*byref*/ false);
735
736 Expr *declRef =
737 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
738
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000739 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000740 declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000741 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000742 MakeAddrLValue(blockField, type,
Eli Friedman225bf772011-09-30 18:19:16 +0000743 getContext().getDeclAlign(variable)
744 .getQuantity()),
John McCalldf045202011-03-08 09:38:48 +0000745 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000746 }
747
John McCall1a343eb2011-11-10 08:15:53 +0000748 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000749 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000750 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
751 if (cleanup.isValid())
752 ActivateCleanupBlock(cleanup);
John McCallf85e1932011-06-15 23:02:42 +0000753 }
John McCall6b5a61b2011-02-07 10:33:21 +0000754 }
755
756 // Cast to the converted block-pointer type, which happens (somewhat
757 // unfortunately) to be a pointer to function type.
758 llvm::Value *result =
759 Builder.CreateBitCast(blockAddr,
760 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000761
John McCall6b5a61b2011-02-07 10:33:21 +0000762 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000763}
764
765
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000766llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000767 if (BlockDescriptorType)
768 return BlockDescriptorType;
769
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000770 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000771 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000772
Mike Stumpab695142009-02-13 15:16:56 +0000773 // struct __block_descriptor {
774 // unsigned long reserved;
775 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000776 //
777 // // later, the following will be added
778 //
779 // struct {
780 // void (*copyHelper)();
781 // void (*copyHelper)();
782 // } helpers; // !!! optional
783 //
784 // const char *signature; // the block signature
785 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000786 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000787 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000788 llvm::StructType::create("struct.__block_descriptor",
789 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000790
John McCall6b5a61b2011-02-07 10:33:21 +0000791 // Now form a pointer to that.
792 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000793 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000794}
795
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000796llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000797 if (GenericBlockLiteralType)
798 return GenericBlockLiteralType;
799
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000800 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000801
Mike Stump9b8a7972009-02-13 15:25:34 +0000802 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000803 // void *__isa;
804 // int __flags;
805 // int __reserved;
806 // void (*__invoke)(void *);
807 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000808 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000809 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000810 llvm::StructType::create("struct.__block_literal_generic",
811 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
812 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000813
Mike Stump9b8a7972009-02-13 15:25:34 +0000814 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000815}
816
Mike Stumpbd65cac2009-02-19 01:01:04 +0000817
Anders Carlssona1736c02009-12-24 21:13:40 +0000818RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
819 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000820 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000821 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000822
Anders Carlssonacfde802009-02-12 00:39:25 +0000823 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
824
825 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000826 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000827 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000828
829 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000830 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000831 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
832
833 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000834 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000835
Benjamin Kramer578faa82011-09-27 21:06:10 +0000836 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000837
Anders Carlssonacfde802009-02-12 00:39:25 +0000838 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000839 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000840 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000841
Anders Carlsson782f3972009-04-08 23:13:16 +0000842 QualType FnType = BPT->getPointeeType();
843
Anders Carlssonacfde802009-02-12 00:39:25 +0000844 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000845 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000846 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000847
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000848 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000849 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000850
John McCall64cd2322011-03-09 08:39:33 +0000851 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
Eli Friedmanc55db3b2011-08-09 17:38:12 +0000852 const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000854 // Cast the function pointer to the right type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000855 llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000856 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Chris Lattner2acc6e32011-07-18 04:24:23 +0000858 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000859 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Anders Carlssonacfde802009-02-12 00:39:25 +0000861 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000862 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000863}
Anders Carlssond5cab542009-02-12 17:55:02 +0000864
John McCall6b5a61b2011-02-07 10:33:21 +0000865llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
866 bool isByRef) {
867 assert(BlockInfo && "evaluating block ref without block information?");
868 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000869
John McCall6b5a61b2011-02-07 10:33:21 +0000870 // Handle constant captures.
871 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000872
John McCall6b5a61b2011-02-07 10:33:21 +0000873 llvm::Value *addr =
874 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
875 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000876
John McCall6b5a61b2011-02-07 10:33:21 +0000877 if (isByRef) {
878 // addr should be a void** right now. Load, then cast the result
879 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000880
John McCall6b5a61b2011-02-07 10:33:21 +0000881 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000882 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000883 = llvm::PointerType::get(BuildByRefType(variable), 0);
884 addr = Builder.CreateBitCast(addr, byrefPointerType,
885 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000886
John McCall6b5a61b2011-02-07 10:33:21 +0000887 // Follow the forwarding pointer.
888 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
889 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000890
John McCall6b5a61b2011-02-07 10:33:21 +0000891 // Cast back to byref* and GEP over to the actual object.
892 addr = Builder.CreateBitCast(addr, byrefPointerType);
893 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
894 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000895 }
896
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000897 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000898 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000899
John McCall6b5a61b2011-02-07 10:33:21 +0000900 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000901}
902
Mike Stump67a64482009-02-14 22:16:35 +0000903llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000904CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000905 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000906 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
907 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000908
John McCall6b5a61b2011-02-07 10:33:21 +0000909 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000910 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000911
John McCall6b5a61b2011-02-07 10:33:21 +0000912 // Using that metadata, generate the actual block function.
913 llvm::Constant *blockFn;
914 {
915 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000916 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
917 blockInfo,
918 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000919 }
John McCall5936e332011-02-15 09:22:45 +0000920 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000921
John McCalld16c2cf2011-02-08 08:22:06 +0000922 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000923}
924
John McCall6b5a61b2011-02-07 10:33:21 +0000925static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
926 const CGBlockInfo &blockInfo,
927 llvm::Constant *blockFn) {
928 assert(blockInfo.CanBeGlobal);
929
930 // Generate the constants for the block literal initializer.
931 llvm::Constant *fields[BlockHeaderSize];
932
933 // isa
934 fields[0] = CGM.getNSConcreteGlobalBlock();
935
936 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000937 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
938 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
939
John McCall5936e332011-02-15 09:22:45 +0000940 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000941
942 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000943 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000944
945 // Function
946 fields[3] = blockFn;
947
948 // Descriptor
949 fields[4] = buildBlockDescriptor(CGM, blockInfo);
950
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000951 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000952
953 llvm::GlobalVariable *literal =
954 new llvm::GlobalVariable(CGM.getModule(),
955 init->getType(),
956 /*constant*/ true,
957 llvm::GlobalVariable::InternalLinkage,
958 init,
959 "__block_literal_global");
960 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
961
962 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000963 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +0000964 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
965 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000966}
967
Mike Stump00470a12009-03-05 08:32:30 +0000968llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000969CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
970 const CGBlockInfo &blockInfo,
971 const Decl *outerFnDecl,
972 const DeclMapTy &ldm) {
973 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000974
Devang Patel6d1155b2011-03-07 21:53:18 +0000975 // Check if we should generate debug info for this block function.
976 if (CGM.getModuleDebugInfo())
977 DebugInfo = CGM.getModuleDebugInfo();
978
John McCall6b5a61b2011-02-07 10:33:21 +0000979 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Mike Stump7f28a9c2009-03-13 23:34:28 +0000981 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000982 // to be local to this function as well, in case they're directly
983 // referenced in a block.
984 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
985 const VarDecl *var = dyn_cast<VarDecl>(i->first);
986 if (var && !var->hasLocalStorage())
987 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000988 }
989
John McCall6b5a61b2011-02-07 10:33:21 +0000990 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000991
John McCall6b5a61b2011-02-07 10:33:21 +0000992 // Build the argument list.
993 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000994
John McCall6b5a61b2011-02-07 10:33:21 +0000995 // The first argument is the block pointer. Just take it as a void*
996 // and cast it later.
997 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000998 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000999
John McCall8178df32011-02-22 22:38:33 +00001000 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1001 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001002 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001003
John McCall6b5a61b2011-02-07 10:33:21 +00001004 // Now add the rest of the parameters.
1005 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1006 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001007 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001008
John McCall6b5a61b2011-02-07 10:33:21 +00001009 // Create the function declaration.
1010 const FunctionProtoType *fnType =
1011 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
1012 const CGFunctionInfo &fnInfo =
1013 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
1014 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +00001015 if (CGM.ReturnTypeUsesSRet(fnInfo))
1016 blockInfo.UsesStret = true;
1017
Chris Lattner2acc6e32011-07-18 04:24:23 +00001018 llvm::FunctionType *fnLLVMType =
John McCall6b5a61b2011-02-07 10:33:21 +00001019 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +00001020
John McCall6b5a61b2011-02-07 10:33:21 +00001021 MangleBuffer name;
1022 CGM.getBlockMangledName(GD, name, blockDecl);
1023 llvm::Function *fn =
1024 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1025 name.getString(), &CGM.getModule());
1026 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001027
John McCall6b5a61b2011-02-07 10:33:21 +00001028 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001029 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001030 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001031 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001032
John McCall8178df32011-02-22 22:38:33 +00001033 // Okay. Undo some of what StartFunction did.
1034
1035 // Pull the 'self' reference out of the local decl map.
1036 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1037 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001038 BlockPointer = Builder.CreateBitCast(blockAddr,
1039 blockInfo.StructureType->getPointerTo(),
1040 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001041
John McCallea1471e2010-05-20 01:18:31 +00001042 // If we have a C++ 'this' reference, go ahead and force it into
1043 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001044 if (blockDecl->capturesCXXThis()) {
1045 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1046 blockInfo.CXXThisIndex,
1047 "block.captured-this");
1048 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001049 }
1050
John McCall6b5a61b2011-02-07 10:33:21 +00001051 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1052 // appease it.
1053 if (const ObjCMethodDecl *method
1054 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1055 const VarDecl *self = method->getSelfDecl();
1056
1057 // There might not be a capture for 'self', but if there is...
1058 if (blockInfo.Captures.count(self)) {
1059 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1060 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1061 capture.getIndex(),
1062 "block.captured-self");
1063 LocalDeclMap[self] = selfAddr;
1064 }
1065 }
1066
1067 // Also force all the constant captures.
1068 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1069 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1070 const VarDecl *variable = ci->getVariable();
1071 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1072 if (!capture.isConstant()) continue;
1073
1074 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1075
1076 llvm::AllocaInst *alloca =
1077 CreateMemTemp(variable->getType(), "block.captured-const");
1078 alloca->setAlignment(align);
1079
1080 Builder.CreateStore(capture.getConstant(), alloca, align);
1081
1082 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001083 }
1084
Mike Stumpb289b3f2009-10-01 22:29:41 +00001085 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
1086 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1087 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1088 --entry_ptr;
1089
John McCall6b5a61b2011-02-07 10:33:21 +00001090 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001091
Mike Stumpde8c5c72009-10-01 00:27:30 +00001092 // Remember where we were...
1093 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001094
Mike Stumpde8c5c72009-10-01 00:27:30 +00001095 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001096 ++entry_ptr;
1097 Builder.SetInsertPoint(entry, entry_ptr);
1098
John McCall6b5a61b2011-02-07 10:33:21 +00001099 // Emit debug information for all the BlockDeclRefDecls.
1100 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001101 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001102 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1103 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1104 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001105 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001106
1107 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1108 if (capture.isConstant()) {
1109 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1110 Builder);
1111 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001112 }
John McCall6b5a61b2011-02-07 10:33:21 +00001113
John McCall8178df32011-02-22 22:38:33 +00001114 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001115 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001116 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001117 }
John McCall6b5a61b2011-02-07 10:33:21 +00001118
Mike Stumpde8c5c72009-10-01 00:27:30 +00001119 // And resume where we left off.
1120 if (resume == 0)
1121 Builder.ClearInsertionPoint();
1122 else
1123 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001124
John McCall6b5a61b2011-02-07 10:33:21 +00001125 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001126
John McCall6b5a61b2011-02-07 10:33:21 +00001127 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001128}
Mike Stumpa99038c2009-02-28 09:07:16 +00001129
John McCall6b5a61b2011-02-07 10:33:21 +00001130/*
1131 notes.push_back(HelperInfo());
1132 HelperInfo &note = notes.back();
1133 note.index = capture.getIndex();
1134 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1135 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001136
John McCall6b5a61b2011-02-07 10:33:21 +00001137 if (ci->isByRef()) {
1138 note.flag = BLOCK_FIELD_IS_BYREF;
1139 if (type.isObjCGCWeak())
1140 note.flag |= BLOCK_FIELD_IS_WEAK;
1141 } else if (type->isBlockPointerType()) {
1142 note.flag = BLOCK_FIELD_IS_BLOCK;
1143 } else {
1144 note.flag = BLOCK_FIELD_IS_OBJECT;
1145 }
1146 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001147
Mike Stump00470a12009-03-05 08:32:30 +00001148
Mike Stumpa99038c2009-02-28 09:07:16 +00001149
John McCall6b5a61b2011-02-07 10:33:21 +00001150llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001151CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001152 ASTContext &C = getContext();
1153
1154 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001155 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1156 args.push_back(&dstDecl);
1157 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1158 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Mike Stumpa4f668f2009-03-06 01:33:24 +00001160 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001161 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001162
John McCall6b5a61b2011-02-07 10:33:21 +00001163 // FIXME: it would be nice if these were mergeable with things with
1164 // identical semantics.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001165 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001166
1167 llvm::Function *Fn =
1168 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001169 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001170
1171 IdentifierInfo *II
1172 = &CGM.getContext().Idents.get("__copy_helper_block_");
1173
Devang Patel58dc5ca2011-05-02 20:37:08 +00001174 // Check if we should generate debug info for this block helper function.
1175 if (CGM.getModuleDebugInfo())
1176 DebugInfo = CGM.getModuleDebugInfo();
1177
John McCall6b5a61b2011-02-07 10:33:21 +00001178 FunctionDecl *FD = FunctionDecl::Create(C,
1179 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001180 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001181 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001182 SC_Static,
1183 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001184 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001185 true);
John McCalld26bc762011-03-09 04:27:21 +00001186 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001187
Chris Lattner2acc6e32011-07-18 04:24:23 +00001188 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001189
John McCalld26bc762011-03-09 04:27:21 +00001190 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001191 src = Builder.CreateLoad(src);
1192 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001193
John McCalld26bc762011-03-09 04:27:21 +00001194 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001195 dst = Builder.CreateLoad(dst);
1196 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001197
John McCall6b5a61b2011-02-07 10:33:21 +00001198 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001199
John McCall6b5a61b2011-02-07 10:33:21 +00001200 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1201 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1202 const VarDecl *variable = ci->getVariable();
1203 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001204
John McCall6b5a61b2011-02-07 10:33:21 +00001205 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1206 if (capture.isConstant()) continue;
1207
1208 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001209 BlockFieldFlags flags;
1210
1211 bool isARCWeakCapture = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001212
1213 if (copyExpr) {
1214 assert(!ci->isByRef());
1215 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001216
John McCall6b5a61b2011-02-07 10:33:21 +00001217 } else if (ci->isByRef()) {
1218 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001219 if (type.isObjCGCWeak())
1220 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001221
John McCallf85e1932011-06-15 23:02:42 +00001222 } else if (type->isObjCRetainableType()) {
1223 flags = BLOCK_FIELD_IS_OBJECT;
1224 if (type->isBlockPointerType())
1225 flags = BLOCK_FIELD_IS_BLOCK;
1226
1227 // Special rules for ARC captures:
1228 if (getLangOptions().ObjCAutoRefCount) {
1229 Qualifiers qs = type.getQualifiers();
1230
1231 // Don't generate special copy logic for a captured object
1232 // unless it's __strong or __weak.
1233 if (!qs.hasStrongOrWeakObjCLifetime())
1234 continue;
1235
1236 // Support __weak direct captures.
1237 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1238 isARCWeakCapture = true;
1239 }
1240 } else {
1241 continue;
1242 }
John McCall6b5a61b2011-02-07 10:33:21 +00001243
1244 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001245 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1246 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001247
1248 // If there's an explicit copy expression, we do that.
1249 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001250 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCallf85e1932011-06-15 23:02:42 +00001251 } else if (isARCWeakCapture) {
1252 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001253 } else {
1254 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001255 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1256 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001257 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCallf85e1932011-06-15 23:02:42 +00001258 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
Mike Stump08920992009-03-07 02:35:30 +00001259 }
1260 }
1261
John McCalld16c2cf2011-02-08 08:22:06 +00001262 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001263
John McCall5936e332011-02-15 09:22:45 +00001264 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001265}
1266
John McCall6b5a61b2011-02-07 10:33:21 +00001267llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001268CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001269 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001270
John McCall6b5a61b2011-02-07 10:33:21 +00001271 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001272 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1273 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Mike Stumpa4f668f2009-03-06 01:33:24 +00001275 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001276 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001277
Mike Stump3899a7f2009-06-05 23:26:36 +00001278 // FIXME: We'd like to put these into a mergable by content, with
1279 // internal linkage.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001280 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001281
1282 llvm::Function *Fn =
1283 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001284 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001285
Devang Patel58dc5ca2011-05-02 20:37:08 +00001286 // Check if we should generate debug info for this block destroy function.
1287 if (CGM.getModuleDebugInfo())
1288 DebugInfo = CGM.getModuleDebugInfo();
1289
Mike Stumpa4f668f2009-03-06 01:33:24 +00001290 IdentifierInfo *II
1291 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1292
John McCall6b5a61b2011-02-07 10:33:21 +00001293 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001294 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001295 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001296 SC_Static,
1297 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001298 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001299 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001300
Chris Lattner2acc6e32011-07-18 04:24:23 +00001301 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001302
John McCalld26bc762011-03-09 04:27:21 +00001303 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001304 src = Builder.CreateLoad(src);
1305 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001306
John McCall6b5a61b2011-02-07 10:33:21 +00001307 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1308
John McCalld16c2cf2011-02-08 08:22:06 +00001309 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001310
1311 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1312 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1313 const VarDecl *variable = ci->getVariable();
1314 QualType type = variable->getType();
1315
1316 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1317 if (capture.isConstant()) continue;
1318
John McCalld16c2cf2011-02-08 08:22:06 +00001319 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001320 const CXXDestructorDecl *dtor = 0;
1321
John McCallf85e1932011-06-15 23:02:42 +00001322 bool isARCWeakCapture = false;
1323
John McCall6b5a61b2011-02-07 10:33:21 +00001324 if (ci->isByRef()) {
1325 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001326 if (type.isObjCGCWeak())
1327 flags |= BLOCK_FIELD_IS_WEAK;
1328 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1329 if (record->hasTrivialDestructor())
1330 continue;
1331 dtor = record->getDestructor();
1332 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001333 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001334 if (type->isBlockPointerType())
1335 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001336
John McCallf85e1932011-06-15 23:02:42 +00001337 // Special rules for ARC captures.
1338 if (getLangOptions().ObjCAutoRefCount) {
1339 Qualifiers qs = type.getQualifiers();
1340
1341 // Don't generate special dispose logic for a captured object
1342 // unless it's __strong or __weak.
1343 if (!qs.hasStrongOrWeakObjCLifetime())
1344 continue;
1345
1346 // Support __weak direct captures.
1347 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1348 isARCWeakCapture = true;
1349 }
1350 } else {
1351 continue;
1352 }
John McCall6b5a61b2011-02-07 10:33:21 +00001353
1354 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001355 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001356
1357 // If there's an explicit copy expression, we do that.
1358 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001359 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001360
John McCallf85e1932011-06-15 23:02:42 +00001361 // If this is a __weak capture, emit the release directly.
1362 } else if (isARCWeakCapture) {
1363 EmitARCDestroyWeak(srcField);
1364
John McCall6b5a61b2011-02-07 10:33:21 +00001365 // Otherwise we call _Block_object_dispose. It wouldn't be too
1366 // hard to just emit this as a cleanup if we wanted to make sure
1367 // that things were done in reverse.
1368 } else {
1369 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001370 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001371 BuildBlockRelease(value, flags);
1372 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001373 }
1374
John McCall6b5a61b2011-02-07 10:33:21 +00001375 cleanups.ForceCleanup();
1376
John McCalld16c2cf2011-02-08 08:22:06 +00001377 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001378
John McCall5936e332011-02-15 09:22:45 +00001379 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001380}
1381
John McCallf0c11f72011-03-31 08:03:29 +00001382namespace {
1383
1384/// Emits the copy/dispose helper functions for a __block object of id type.
1385class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1386 BlockFieldFlags Flags;
1387
1388public:
1389 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1390 : ByrefHelpers(alignment), Flags(flags) {}
1391
John McCall36170192011-03-31 09:19:20 +00001392 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1393 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001394 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1395
1396 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1397 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1398
1399 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1400
1401 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1402 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1403 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1404 }
1405
1406 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1407 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1408 llvm::Value *value = CGF.Builder.CreateLoad(field);
1409
1410 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1411 }
1412
1413 void profileImpl(llvm::FoldingSetNodeID &id) const {
1414 id.AddInteger(Flags.getBitMask());
1415 }
1416};
1417
John McCallf85e1932011-06-15 23:02:42 +00001418/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1419class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1420public:
1421 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1422
1423 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1424 llvm::Value *srcField) {
1425 CGF.EmitARCMoveWeak(destField, srcField);
1426 }
1427
1428 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1429 CGF.EmitARCDestroyWeak(field);
1430 }
1431
1432 void profileImpl(llvm::FoldingSetNodeID &id) const {
1433 // 0 is distinguishable from all pointers and byref flags
1434 id.AddInteger(0);
1435 }
1436};
1437
1438/// Emits the copy/dispose helpers for an ARC __block __strong variable
1439/// that's not of block-pointer type.
1440class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1441public:
1442 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1443
1444 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1445 llvm::Value *srcField) {
1446 // Do a "move" by copying the value and then zeroing out the old
1447 // variable.
1448
John McCalla59e4b72011-11-09 03:17:26 +00001449 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1450 value->setAlignment(Alignment.getQuantity());
1451
John McCallf85e1932011-06-15 23:02:42 +00001452 llvm::Value *null =
1453 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001454
1455 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1456 store->setAlignment(Alignment.getQuantity());
1457
1458 store = CGF.Builder.CreateStore(null, srcField);
1459 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001460 }
1461
1462 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCalla59e4b72011-11-09 03:17:26 +00001463 llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1464 value->setAlignment(Alignment.getQuantity());
1465
John McCallf85e1932011-06-15 23:02:42 +00001466 CGF.EmitARCRelease(value, /*precise*/ false);
1467 }
1468
1469 void profileImpl(llvm::FoldingSetNodeID &id) const {
1470 // 1 is distinguishable from all pointers and byref flags
1471 id.AddInteger(1);
1472 }
1473};
1474
John McCalla59e4b72011-11-09 03:17:26 +00001475/// Emits the copy/dispose helpers for an ARC __block __strong
1476/// variable that's of block-pointer type.
1477class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1478public:
1479 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1480
1481 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1482 llvm::Value *srcField) {
1483 // Do the copy with objc_retainBlock; that's all that
1484 // _Block_object_assign would do anyway, and we'd have to pass the
1485 // right arguments to make sure it doesn't get no-op'ed.
1486 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1487 oldValue->setAlignment(Alignment.getQuantity());
1488
1489 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1490
1491 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1492 store->setAlignment(Alignment.getQuantity());
1493 }
1494
1495 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1496 llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1497 value->setAlignment(Alignment.getQuantity());
1498
1499 CGF.EmitARCRelease(value, /*precise*/ false);
1500 }
1501
1502 void profileImpl(llvm::FoldingSetNodeID &id) const {
1503 // 2 is distinguishable from all pointers and byref flags
1504 id.AddInteger(2);
1505 }
1506};
1507
John McCallf0c11f72011-03-31 08:03:29 +00001508/// Emits the copy/dispose helpers for a __block variable with a
1509/// nontrivial copy constructor or destructor.
1510class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1511 QualType VarType;
1512 const Expr *CopyExpr;
1513
1514public:
1515 CXXByrefHelpers(CharUnits alignment, QualType type,
1516 const Expr *copyExpr)
1517 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1518
1519 bool needsCopy() const { return CopyExpr != 0; }
1520 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1521 llvm::Value *srcField) {
1522 if (!CopyExpr) return;
1523 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1524 }
1525
1526 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1527 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1528 CGF.PushDestructorCleanup(VarType, field);
1529 CGF.PopCleanupBlocks(cleanupDepth);
1530 }
1531
1532 void profileImpl(llvm::FoldingSetNodeID &id) const {
1533 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1534 }
1535};
1536} // end anonymous namespace
1537
1538static llvm::Constant *
1539generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001540 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001541 CodeGenModule::ByrefHelpers &byrefInfo) {
1542 ASTContext &Context = CGF.getContext();
1543
1544 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001545
John McCalld26bc762011-03-09 04:27:21 +00001546 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001547 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001548 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001549
John McCallf0c11f72011-03-31 08:03:29 +00001550 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001551 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Mike Stump45031c02009-03-06 02:29:21 +00001553 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001554 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001555
John McCallf0c11f72011-03-31 08:03:29 +00001556 CodeGenTypes &Types = CGF.CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001557 llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
Mike Stump45031c02009-03-06 02:29:21 +00001558
Mike Stump3899a7f2009-06-05 23:26:36 +00001559 // FIXME: We'd like to put these into a mergable by content, with
1560 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001561 llvm::Function *Fn =
1562 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001563 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001564
1565 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001566 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001567
John McCallf0c11f72011-03-31 08:03:29 +00001568 FunctionDecl *FD = FunctionDecl::Create(Context,
1569 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001570 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001571 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001572 SC_Static,
1573 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001574 false, true);
John McCallf85e1932011-06-15 23:02:42 +00001575
John McCallf0c11f72011-03-31 08:03:29 +00001576 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001577
John McCallf0c11f72011-03-31 08:03:29 +00001578 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001579 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001580
John McCallf0c11f72011-03-31 08:03:29 +00001581 // dst->x
1582 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1583 destField = CGF.Builder.CreateLoad(destField);
1584 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1585 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001586
John McCallf0c11f72011-03-31 08:03:29 +00001587 // src->x
1588 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1589 srcField = CGF.Builder.CreateLoad(srcField);
1590 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1591 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1592
1593 byrefInfo.emitCopy(CGF, destField, srcField);
1594 }
1595
1596 CGF.FinishFunction();
1597
1598 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001599}
1600
John McCallf0c11f72011-03-31 08:03:29 +00001601/// Build the copy helper for a __block variable.
1602static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001603 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001604 CodeGenModule::ByrefHelpers &info) {
1605 CodeGenFunction CGF(CGM);
1606 return generateByrefCopyHelper(CGF, byrefType, info);
1607}
1608
1609/// Generate code for a __block variable's dispose helper.
1610static llvm::Constant *
1611generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001612 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001613 CodeGenModule::ByrefHelpers &byrefInfo) {
1614 ASTContext &Context = CGF.getContext();
1615 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001616
John McCalld26bc762011-03-09 04:27:21 +00001617 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001618 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001619 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Mike Stump45031c02009-03-06 02:29:21 +00001621 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001622 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001623
John McCallf0c11f72011-03-31 08:03:29 +00001624 CodeGenTypes &Types = CGF.CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001625 llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
Mike Stump45031c02009-03-06 02:29:21 +00001626
Mike Stump3899a7f2009-06-05 23:26:36 +00001627 // FIXME: We'd like to put these into a mergable by content, with
1628 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001629 llvm::Function *Fn =
1630 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001631 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001632 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001633
1634 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001635 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001636
John McCallf0c11f72011-03-31 08:03:29 +00001637 FunctionDecl *FD = FunctionDecl::Create(Context,
1638 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001639 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001640 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001641 SC_Static,
1642 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001643 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001644 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001645
John McCallf0c11f72011-03-31 08:03:29 +00001646 if (byrefInfo.needsDispose()) {
1647 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1648 V = CGF.Builder.CreateLoad(V);
1649 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1650 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001651
John McCallf0c11f72011-03-31 08:03:29 +00001652 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001653 }
Mike Stump45031c02009-03-06 02:29:21 +00001654
John McCallf0c11f72011-03-31 08:03:29 +00001655 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001656
John McCallf0c11f72011-03-31 08:03:29 +00001657 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001658}
1659
John McCallf0c11f72011-03-31 08:03:29 +00001660/// Build the dispose helper for a __block variable.
1661static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001662 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001663 CodeGenModule::ByrefHelpers &info) {
1664 CodeGenFunction CGF(CGM);
1665 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001666}
1667
John McCallf0c11f72011-03-31 08:03:29 +00001668///
1669template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001670 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001671 T &byrefInfo) {
1672 // Increase the field's alignment to be at least pointer alignment,
1673 // since the layout of the byref struct will guarantee at least that.
1674 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1675 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1676
1677 llvm::FoldingSetNodeID id;
1678 byrefInfo.Profile(id);
1679
1680 void *insertPos;
1681 CodeGenModule::ByrefHelpers *node
1682 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1683 if (node) return static_cast<T*>(node);
1684
1685 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1686 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1687
1688 T *copy = new (CGM.getContext()) T(byrefInfo);
1689 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1690 return copy;
1691}
1692
1693CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001694CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001695 const AutoVarEmission &emission) {
1696 const VarDecl &var = *emission.Variable;
1697 QualType type = var.getType();
1698
1699 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1700 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1701 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1702
1703 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1704 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1705 }
1706
John McCallf85e1932011-06-15 23:02:42 +00001707 // Otherwise, if we don't have a retainable type, there's nothing to do.
1708 // that the runtime does extra copies.
1709 if (!type->isObjCRetainableType()) return 0;
1710
1711 Qualifiers qs = type.getQualifiers();
1712
1713 // If we have lifetime, that dominates.
1714 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1715 assert(getLangOptions().ObjCAutoRefCount);
1716
1717 switch (lifetime) {
1718 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1719
1720 // These are just bits as far as the runtime is concerned.
1721 case Qualifiers::OCL_ExplicitNone:
1722 case Qualifiers::OCL_Autoreleasing:
1723 return 0;
1724
1725 // Tell the runtime that this is ARC __weak, called by the
1726 // byref routines.
1727 case Qualifiers::OCL_Weak: {
1728 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1729 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1730 }
1731
1732 // ARC __strong __block variables need to be retained.
1733 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001734 // Block pointers need to be copied, and there's no direct
1735 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001736 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001737 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001738 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1739
1740 // Otherwise, we transfer ownership of the retain from the stack
1741 // to the heap.
1742 } else {
1743 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1744 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1745 }
1746 }
1747 llvm_unreachable("fell out of lifetime switch!");
1748 }
1749
John McCallf0c11f72011-03-31 08:03:29 +00001750 BlockFieldFlags flags;
1751 if (type->isBlockPointerType()) {
1752 flags |= BLOCK_FIELD_IS_BLOCK;
1753 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1754 type->isObjCObjectPointerType()) {
1755 flags |= BLOCK_FIELD_IS_OBJECT;
1756 } else {
1757 return 0;
1758 }
1759
1760 if (type.isObjCGCWeak())
1761 flags |= BLOCK_FIELD_IS_WEAK;
1762
1763 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1764 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001765}
1766
John McCall5af02db2011-03-31 01:59:53 +00001767unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1768 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1769
1770 return ByRefValueInfo.find(VD)->second.second;
1771}
1772
1773llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1774 const VarDecl *V) {
1775 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1776 Loc = Builder.CreateLoad(Loc);
1777 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1778 V->getNameAsString());
1779 return Loc;
1780}
1781
1782/// BuildByRefType - This routine changes a __block variable declared as T x
1783/// into:
1784///
1785/// struct {
1786/// void *__isa;
1787/// void *__forwarding;
1788/// int32_t __flags;
1789/// int32_t __size;
1790/// void *__copy_helper; // only if needed
1791/// void *__destroy_helper; // only if needed
1792/// char padding[X]; // only if needed
1793/// T x;
1794/// } x
1795///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001796llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1797 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001798 if (Info.first)
1799 return Info.first;
1800
1801 QualType Ty = D->getType();
1802
Chris Lattner5f9e2722011-07-23 10:55:15 +00001803 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001804
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001805 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001806 llvm::StructType::create(getLLVMContext(),
1807 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001808
1809 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001810 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001811
1812 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001813 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001814
1815 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001816 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001817
1818 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001819 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001820
1821 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1822 if (HasCopyAndDispose) {
1823 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001824 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001825
1826 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001827 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001828 }
1829
1830 bool Packed = false;
1831 CharUnits Align = getContext().getDeclAlign(D);
1832 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1833 // We have to insert padding.
1834
1835 // The struct above has 2 32-bit integers.
1836 unsigned CurrentOffsetInBytes = 4 * 2;
1837
1838 // And either 2 or 4 pointers.
1839 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1840 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1841
1842 // Align the offset.
1843 unsigned AlignedOffsetInBytes =
1844 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1845
1846 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1847 if (NumPaddingBytes > 0) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001848 llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
John McCall5af02db2011-03-31 01:59:53 +00001849 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001850 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001851 if (NumPaddingBytes > 1)
1852 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1853
John McCall0774cb82011-05-15 01:53:33 +00001854 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001855
1856 // We want a packed struct.
1857 Packed = true;
1858 }
1859 }
1860
1861 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001862 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001863
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001864 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001865
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001866 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001867
John McCall0774cb82011-05-15 01:53:33 +00001868 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001869
1870 return Info.first;
1871}
1872
1873/// Initialize the structural components of a __block variable, i.e.
1874/// everything but the actual object.
1875void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001876 // Find the address of the local.
1877 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001878
John McCallf0c11f72011-03-31 08:03:29 +00001879 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001880 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001881 cast<llvm::PointerType>(addr->getType())->getElementType());
1882
1883 // Build the byref helpers if necessary. This is null if we don't need any.
1884 CodeGenModule::ByrefHelpers *helpers =
1885 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001886
1887 const VarDecl &D = *emission.Variable;
1888 QualType type = D.getType();
1889
John McCallf0c11f72011-03-31 08:03:29 +00001890 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001891
1892 // Initialize the 'isa', which is just 0 or 1.
1893 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001894 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001895 isa = 1;
1896 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1897 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1898
1899 // Store the address of the variable into its own forwarding pointer.
1900 Builder.CreateStore(addr,
1901 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1902
1903 // Blocks ABI:
1904 // c) the flags field is set to either 0 if no helper functions are
1905 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1906 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001907 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001908 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1909 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1910
John McCallf0c11f72011-03-31 08:03:29 +00001911 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1912 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001913 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1914
John McCallf0c11f72011-03-31 08:03:29 +00001915 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001916 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001917 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001918
1919 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001920 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001921 }
1922}
1923
John McCalld16c2cf2011-02-08 08:22:06 +00001924void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001925 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001926 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001927 V = Builder.CreateBitCast(V, Int8PtrTy);
1928 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001929 Builder.CreateCall2(F, V, N);
1930}
John McCall5af02db2011-03-31 01:59:53 +00001931
1932namespace {
1933 struct CallBlockRelease : EHScopeStack::Cleanup {
1934 llvm::Value *Addr;
1935 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1936
John McCallad346f42011-07-12 20:27:29 +00001937 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001938 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00001939 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1940 }
1941 };
1942}
1943
1944/// Enter a cleanup to destroy a __block variable. Note that this
1945/// cleanup should be a no-op if the variable hasn't left the stack
1946/// yet; if a cleanup is required for the variable itself, that needs
1947/// to be done externally.
1948void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1949 // We don't enter this cleanup if we're in pure-GC mode.
Douglas Gregore289d812011-09-13 17:21:33 +00001950 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00001951 return;
1952
1953 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1954}
John McCall13db5cf2011-09-09 20:41:01 +00001955
1956/// Adjust the declaration of something from the blocks API.
1957static void configureBlocksRuntimeObject(CodeGenModule &CGM,
1958 llvm::Constant *C) {
1959 if (!CGM.getLangOptions().BlocksRuntimeOptional) return;
1960
1961 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
1962 if (GV->isDeclaration() &&
1963 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
1964 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1965}
1966
1967llvm::Constant *CodeGenModule::getBlockObjectDispose() {
1968 if (BlockObjectDispose)
1969 return BlockObjectDispose;
1970
1971 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
1972 llvm::FunctionType *fty
1973 = llvm::FunctionType::get(VoidTy, args, false);
1974 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
1975 configureBlocksRuntimeObject(*this, BlockObjectDispose);
1976 return BlockObjectDispose;
1977}
1978
1979llvm::Constant *CodeGenModule::getBlockObjectAssign() {
1980 if (BlockObjectAssign)
1981 return BlockObjectAssign;
1982
1983 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
1984 llvm::FunctionType *fty
1985 = llvm::FunctionType::get(VoidTy, args, false);
1986 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
1987 configureBlocksRuntimeObject(*this, BlockObjectAssign);
1988 return BlockObjectAssign;
1989}
1990
1991llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
1992 if (NSConcreteGlobalBlock)
1993 return NSConcreteGlobalBlock;
1994
1995 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
1996 Int8PtrTy->getPointerTo(), 0);
1997 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
1998 return NSConcreteGlobalBlock;
1999}
2000
2001llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2002 if (NSConcreteStackBlock)
2003 return NSConcreteStackBlock;
2004
2005 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2006 Int8PtrTy->getPointerTo(), 0);
2007 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2008 return NSConcreteStackBlock;
2009}