blob: 8ad82a614e247c9da62ff0434b2ed825daca9196 [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 McCall6b5a61b2011-02-07 10:33:21 +000028CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N)
29 : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
John McCall64cd2322011-03-09 08:39:33 +000030 HasCXXObject(false), UsesStret(false), StructureType(0), Block(blockExpr) {
John McCallee504292010-05-21 04:11:14 +000031
32 // Skip asm prefix, if any.
33 if (Name && Name[0] == '\01')
34 ++Name;
35}
36
John McCallf0c11f72011-03-31 08:03:29 +000037// Anchor the vtable to this translation unit.
38CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
39
John McCall6b5a61b2011-02-07 10:33:21 +000040/// Build the given block as a global block.
41static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
42 const CGBlockInfo &blockInfo,
43 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000044
John McCall6b5a61b2011-02-07 10:33:21 +000045/// Build the helper function to copy a block.
46static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
47 const CGBlockInfo &blockInfo) {
48 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
49}
50
51/// Build the helper function to dipose of a block.
52static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo) {
54 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
55}
56
57/// Build the block descriptor constant for a block.
58static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
59 const CGBlockInfo &blockInfo) {
60 ASTContext &C = CGM.getContext();
61
62 const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
63 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
64
65 llvm::SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000066
67 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000068 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000069
70 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000071 // FIXME: What is the right way to say this doesn't fit? We should give
72 // a user diagnostic in that case. Better fix would be to change the
73 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000074 elements.push_back(llvm::ConstantInt::get(ulong,
75 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000076
John McCall6b5a61b2011-02-07 10:33:21 +000077 // Optional copy/dispose helpers.
78 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000079 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000080 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000081
82 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000083 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000084 }
85
John McCall6b5a61b2011-02-07 10:33:21 +000086 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
87 std::string typeAtEncoding =
88 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
89 elements.push_back(llvm::ConstantExpr::getBitCast(
90 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000091
John McCall6b5a61b2011-02-07 10:33:21 +000092 // GC layout.
93 if (C.getLangOptions().ObjC1)
94 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
95 else
96 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000097
John McCall6b5a61b2011-02-07 10:33:21 +000098 llvm::Constant *init =
99 llvm::ConstantStruct::get(CGM.getLLVMContext(), elements.data(),
100 elements.size(), false);
Mike Stumpe5fee252009-02-13 16:19:19 +0000101
John McCall6b5a61b2011-02-07 10:33:21 +0000102 llvm::GlobalVariable *global =
103 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
104 llvm::GlobalValue::InternalLinkage,
105 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000106
John McCall6b5a61b2011-02-07 10:33:21 +0000107 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000108}
109
John McCall6b5a61b2011-02-07 10:33:21 +0000110/*
111 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000112
John McCall6b5a61b2011-02-07 10:33:21 +0000113 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
114 struct Block_literal {
115 /// Initialized to one of:
116 /// extern void *_NSConcreteStackBlock[];
117 /// extern void *_NSConcreteGlobalBlock[];
118 ///
119 /// In theory, we could start one off malloc'ed by setting
120 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
121 /// this isa:
122 /// extern void *_NSConcreteMallocBlock[];
123 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000124
John McCall6b5a61b2011-02-07 10:33:21 +0000125 /// These are the flags (with corresponding bit number) that the
126 /// compiler is actually supposed to know about.
127 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
128 /// descriptor provides copy and dispose helper functions
129 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
130 /// object with a nontrivial destructor or copy constructor
131 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
132 /// as global memory
133 /// 29. BLOCK_USE_STRET - indicates that the block function
134 /// uses stret, which objc_msgSend needs to know about
135 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
136 /// @encoded signature string
137 /// And we're not supposed to manipulate these:
138 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
139 /// to malloc'ed memory
140 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
141 /// to GC-allocated memory
142 /// Additionally, the bottom 16 bits are a reference count which
143 /// should be zero on the stack.
144 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000145
John McCall6b5a61b2011-02-07 10:33:21 +0000146 /// Reserved; should be zero-initialized.
147 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000148
John McCall6b5a61b2011-02-07 10:33:21 +0000149 /// Function pointer generated from block literal.
150 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000151
John McCall6b5a61b2011-02-07 10:33:21 +0000152 /// Block description metadata generated from block literal.
153 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000154
John McCall6b5a61b2011-02-07 10:33:21 +0000155 /// Captured values follow.
156 _CapturesTypes captures...;
157 };
158 */
David Chisnall5e530af2009-11-17 19:33:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160/// The number of fields in a block header.
161const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163namespace {
164 /// A chunk of data that we actually have to capture in the block.
165 struct BlockLayoutChunk {
166 CharUnits Alignment;
167 CharUnits Size;
168 const BlockDecl::Capture *Capture; // null for 'this'
169 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000170
John McCall6b5a61b2011-02-07 10:33:21 +0000171 BlockLayoutChunk(CharUnits align, CharUnits size,
172 const BlockDecl::Capture *capture,
173 const llvm::Type *type)
174 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000175
John McCall6b5a61b2011-02-07 10:33:21 +0000176 /// Tell the block info that this chunk has the given field index.
177 void setIndex(CGBlockInfo &info, unsigned index) {
178 if (!Capture)
179 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000180 else
John McCall6b5a61b2011-02-07 10:33:21 +0000181 info.Captures[Capture->getVariable()]
182 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000183 }
John McCall6b5a61b2011-02-07 10:33:21 +0000184 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000185
John McCall6b5a61b2011-02-07 10:33:21 +0000186 /// Order by descending alignment.
187 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
188 return left.Alignment > right.Alignment;
189 }
190}
191
John McCall461c9c12011-02-08 03:07:00 +0000192/// Determines if the given type is safe for constant capture in C++.
193static bool isSafeForCXXConstantCapture(QualType type) {
194 const RecordType *recordType =
195 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
196
197 // Only records can be unsafe.
198 if (!recordType) return true;
199
200 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
201
202 // Maintain semantics for classes with non-trivial dtors or copy ctors.
203 if (!record->hasTrivialDestructor()) return false;
204 if (!record->hasTrivialCopyConstructor()) return false;
205
206 // Otherwise, we just have to make sure there aren't any mutable
207 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000208 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000209}
210
John McCall6b5a61b2011-02-07 10:33:21 +0000211/// It is illegal to modify a const object after initialization.
212/// Therefore, if a const object has a constant initializer, we don't
213/// actually need to keep storage for it in the block; we'll just
214/// rematerialize it at the start of the block function. This is
215/// acceptable because we make no promises about address stability of
216/// captured variables.
217static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
218 const VarDecl *var) {
219 QualType type = var->getType();
220
221 // We can only do this if the variable is const.
222 if (!type.isConstQualified()) return 0;
223
John McCall461c9c12011-02-08 03:07:00 +0000224 // Furthermore, in C++ we have to worry about mutable fields:
225 // C++ [dcl.type.cv]p4:
226 // Except that any class member declared mutable can be
227 // modified, any attempt to modify a const object during its
228 // lifetime results in undefined behavior.
229 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000230 return 0;
231
232 // If the variable doesn't have any initializer (shouldn't this be
233 // invalid?), it's not clear what we should do. Maybe capture as
234 // zero?
235 const Expr *init = var->getInit();
236 if (!init) return 0;
237
238 return CGM.EmitConstantExpr(init, var->getType());
239}
240
241/// Get the low bit of a nonzero character count. This is the
242/// alignment of the nth byte if the 0th byte is universally aligned.
243static CharUnits getLowBit(CharUnits v) {
244 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
245}
246
247static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
John McCall0774cb82011-05-15 01:53:33 +0000248 llvm::SmallVectorImpl<const llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000249 ASTContext &C = CGM.getContext();
250
251 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
252 CharUnits ptrSize, ptrAlign, intSize, intAlign;
253 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
254 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
255
256 // Are there crazy embedded platforms where this isn't true?
257 assert(intSize <= ptrSize && "layout assumptions horribly violated");
258
259 CharUnits headerSize = ptrSize;
260 if (2 * intSize < ptrAlign) headerSize += ptrSize;
261 else headerSize += 2 * intSize;
262 headerSize += 2 * ptrSize;
263
264 info.BlockAlign = ptrAlign;
265 info.BlockSize = headerSize;
266
267 assert(elementTypes.empty());
268 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
269 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
270 elementTypes.push_back(i8p);
271 elementTypes.push_back(intTy);
272 elementTypes.push_back(intTy);
273 elementTypes.push_back(i8p);
274 elementTypes.push_back(CGM.getBlockDescriptorType());
275
276 assert(elementTypes.size() == BlockHeaderSize);
277}
278
279/// Compute the layout of the given block. Attempts to lay the block
280/// out with minimal space requirements.
281static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
282 ASTContext &C = CGM.getContext();
283 const BlockDecl *block = info.getBlockDecl();
284
John McCall0774cb82011-05-15 01:53:33 +0000285 llvm::SmallVector<const llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000286 initializeForBlockHeader(CGM, info, elementTypes);
287
288 if (!block->hasCaptures()) {
289 info.StructureType =
290 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
291 info.CanBeGlobal = true;
292 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000293 }
Mike Stump00470a12009-03-05 08:32:30 +0000294
John McCall6b5a61b2011-02-07 10:33:21 +0000295 // Collect the layout chunks.
296 llvm::SmallVector<BlockLayoutChunk, 16> layout;
297 layout.reserve(block->capturesCXXThis() +
298 (block->capture_end() - block->capture_begin()));
299
300 CharUnits maxFieldAlign;
301
302 // First, 'this'.
303 if (block->capturesCXXThis()) {
304 const DeclContext *DC = block->getDeclContext();
305 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
306 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000307 QualType thisType;
308 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
309 thisType = C.getPointerType(C.getRecordType(RD));
310 else
311 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000312
313 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
314 std::pair<CharUnits,CharUnits> tinfo
315 = CGM.getContext().getTypeInfoInChars(thisType);
316 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
317
318 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
319 }
320
321 // Next, all the block captures.
322 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
323 ce = block->capture_end(); ci != ce; ++ci) {
324 const VarDecl *variable = ci->getVariable();
325
326 if (ci->isByRef()) {
327 // We have to copy/dispose of the __block reference.
328 info.NeedsCopyDispose = true;
329
John McCall6b5a61b2011-02-07 10:33:21 +0000330 // Just use void* instead of a pointer to the byref type.
331 QualType byRefPtrTy = C.VoidPtrTy;
332
333 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
334 std::pair<CharUnits,CharUnits> tinfo
335 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
336 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
337
338 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
339 &*ci, llvmType));
340 continue;
341 }
342
343 // Otherwise, build a layout chunk with the size and alignment of
344 // the declaration.
345 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
346 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
347 continue;
348 }
349
John McCallf85e1932011-06-15 23:02:42 +0000350 // If we have a lifetime qualifier, honor it for capture purposes.
351 // That includes *not* copying it if it's __unsafe_unretained.
352 if (Qualifiers::ObjCLifetime lifetime
353 = variable->getType().getObjCLifetime()) {
354 switch (lifetime) {
355 case Qualifiers::OCL_None: llvm_unreachable("impossible");
356 case Qualifiers::OCL_ExplicitNone:
357 case Qualifiers::OCL_Autoreleasing:
358 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000359
John McCallf85e1932011-06-15 23:02:42 +0000360 case Qualifiers::OCL_Strong:
361 case Qualifiers::OCL_Weak:
362 info.NeedsCopyDispose = true;
363 }
364
365 // Block pointers require copy/dispose. So do Objective-C pointers.
366 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000367 info.NeedsCopyDispose = true;
368
369 // So do types that require non-trivial copy construction.
370 } else if (ci->hasCopyExpr()) {
371 info.NeedsCopyDispose = true;
372 info.HasCXXObject = true;
373
374 // And so do types with destructors.
375 } else if (CGM.getLangOptions().CPlusPlus) {
376 if (const CXXRecordDecl *record =
377 variable->getType()->getAsCXXRecordDecl()) {
378 if (!record->hasTrivialDestructor()) {
379 info.HasCXXObject = true;
380 info.NeedsCopyDispose = true;
381 }
382 }
383 }
384
385 CharUnits size = C.getTypeSizeInChars(variable->getType());
386 CharUnits align = C.getDeclAlign(variable);
387 maxFieldAlign = std::max(maxFieldAlign, align);
388
389 const llvm::Type *llvmType =
390 CGM.getTypes().ConvertTypeForMem(variable->getType());
391
392 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
393 }
394
395 // If that was everything, we're done here.
396 if (layout.empty()) {
397 info.StructureType =
398 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
399 info.CanBeGlobal = true;
400 return;
401 }
402
403 // Sort the layout by alignment. We have to use a stable sort here
404 // to get reproducible results. There should probably be an
405 // llvm::array_pod_stable_sort.
406 std::stable_sort(layout.begin(), layout.end());
407
408 CharUnits &blockSize = info.BlockSize;
409 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
410
411 // Assuming that the first byte in the header is maximally aligned,
412 // get the alignment of the first byte following the header.
413 CharUnits endAlign = getLowBit(blockSize);
414
415 // If the end of the header isn't satisfactorily aligned for the
416 // maximum thing, look for things that are okay with the header-end
417 // alignment, and keep appending them until we get something that's
418 // aligned right. This algorithm is only guaranteed optimal if
419 // that condition is satisfied at some point; otherwise we can get
420 // things like:
421 // header // next byte has alignment 4
422 // something_with_size_5; // next byte has alignment 1
423 // something_with_alignment_8;
424 // which has 7 bytes of padding, as opposed to the naive solution
425 // which might have less (?).
426 if (endAlign < maxFieldAlign) {
427 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
428 li = layout.begin() + 1, le = layout.end();
429
430 // Look for something that the header end is already
431 // satisfactorily aligned for.
432 for (; li != le && endAlign < li->Alignment; ++li)
433 ;
434
435 // If we found something that's naturally aligned for the end of
436 // the header, keep adding things...
437 if (li != le) {
438 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
439 for (; li != le; ++li) {
440 assert(endAlign >= li->Alignment);
441
442 li->setIndex(info, elementTypes.size());
443 elementTypes.push_back(li->Type);
444 blockSize += li->Size;
445 endAlign = getLowBit(blockSize);
446
447 // ...until we get to the alignment of the maximum field.
448 if (endAlign >= maxFieldAlign)
449 break;
450 }
451
452 // Don't re-append everything we just appended.
453 layout.erase(first, li);
454 }
455 }
456
457 // At this point, we just have to add padding if the end align still
458 // isn't aligned right.
459 if (endAlign < maxFieldAlign) {
460 CharUnits padding = maxFieldAlign - endAlign;
461
John McCall5936e332011-02-15 09:22:45 +0000462 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
463 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000464 blockSize += padding;
465
466 endAlign = getLowBit(blockSize);
467 assert(endAlign >= maxFieldAlign);
468 }
469
470 // Slam everything else on now. This works because they have
471 // strictly decreasing alignment and we expect that size is always a
472 // multiple of alignment.
473 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
474 li = layout.begin(), le = layout.end(); li != le; ++li) {
475 assert(endAlign >= li->Alignment);
476 li->setIndex(info, elementTypes.size());
477 elementTypes.push_back(li->Type);
478 blockSize += li->Size;
479 endAlign = getLowBit(blockSize);
480 }
481
482 info.StructureType =
483 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
484}
485
486/// Emit a block literal expression in the current function.
487llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
488 std::string Name = CurFn->getName();
489 CGBlockInfo blockInfo(blockExpr, Name.c_str());
490
491 // Compute information about the layout, etc., of this block.
492 computeBlockInfo(CGM, blockInfo);
493
494 // Using that metadata, generate the actual block function.
495 llvm::Constant *blockFn
496 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
497 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000498 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000499
500 // If there is nothing to capture, we can emit this as a global block.
501 if (blockInfo.CanBeGlobal)
502 return buildGlobalBlock(CGM, blockInfo, blockFn);
503
504 // Otherwise, we have to emit this as a local block.
505
506 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000507 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000508
509 // Build the block descriptor.
510 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
511
512 const llvm::Type *intTy = ConvertType(getContext().IntTy);
513
514 llvm::AllocaInst *blockAddr =
515 CreateTempAlloca(blockInfo.StructureType, "block");
516 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
517
518 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000519 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000520 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
521 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000522 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000523
524 // Initialize the block literal.
525 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000526 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000527 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
528 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
529 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
530 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
531 "block.invoke"));
532 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
533 "block.descriptor"));
534
535 // Finally, capture all the values into the block.
536 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
537
538 // First, 'this'.
539 if (blockDecl->capturesCXXThis()) {
540 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
541 blockInfo.CXXThisIndex,
542 "block.captured-this.addr");
543 Builder.CreateStore(LoadCXXThis(), addr);
544 }
545
546 // Next, captured variables.
547 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
548 ce = blockDecl->capture_end(); ci != ce; ++ci) {
549 const VarDecl *variable = ci->getVariable();
550 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
551
552 // Ignore constant captures.
553 if (capture.isConstant()) continue;
554
555 QualType type = variable->getType();
556
557 // This will be a [[type]]*, except that a byref entry will just be
558 // an i8**.
559 llvm::Value *blockField =
560 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
561 "block.captured");
562
563 // Compute the address of the thing we're going to move into the
564 // block literal.
565 llvm::Value *src;
566 if (ci->isNested()) {
567 // We need to use the capture from the enclosing block.
568 const CGBlockInfo::Capture &enclosingCapture =
569 BlockInfo->getCapture(variable);
570
571 // This is a [[type]]*, except that a byref entry wil just be an i8**.
572 src = Builder.CreateStructGEP(LoadBlockStruct(),
573 enclosingCapture.getIndex(),
574 "block.capture.addr");
575 } else {
576 // This is a [[type]]*.
577 src = LocalDeclMap[variable];
578 }
579
580 // For byrefs, we just write the pointer to the byref struct into
581 // the block field. There's no need to chase the forwarding
582 // pointer at this point, since we're building something that will
583 // live a shorter life than the stack byref anyway.
584 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000585 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000586 if (ci->isNested())
587 src = Builder.CreateLoad(src, "byref.capture");
588 else
John McCall5936e332011-02-15 09:22:45 +0000589 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000590
John McCall5936e332011-02-15 09:22:45 +0000591 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000592 Builder.CreateStore(src, blockField);
593
594 // If we have a copy constructor, evaluate that into the block field.
595 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
596 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
597
598 // If it's a reference variable, copy the reference into the block field.
599 } else if (type->isReferenceType()) {
600 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
601
602 // Otherwise, fake up a POD copy into the block field.
603 } else {
John McCallf85e1932011-06-15 23:02:42 +0000604 // Fake up a new variable so that EmitScalarInit doesn't think
605 // we're referring to the variable in its own initializer.
606 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
607 /*name*/ 0, type);
608
John McCallbb699b02011-02-07 18:37:40 +0000609 // We use one of these or the other depending on whether the
610 // reference is nested.
611 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
612 SourceLocation());
613 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
614 VK_LValue, SourceLocation(), /*byref*/ false);
615
616 Expr *declRef =
617 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
618
John McCall6b5a61b2011-02-07 10:33:21 +0000619 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000620 declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000621 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
622 LValue::MakeAddr(blockField, type,
623 getContext().getDeclAlign(variable)
624 .getQuantity(),
625 getContext()),
John McCalldf045202011-03-08 09:38:48 +0000626 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000627 }
628
629 // Push a destructor if necessary. The semantics for when this
630 // actually gets run are really obscure.
John McCallf85e1932011-06-15 23:02:42 +0000631 if (!ci->isByRef()) {
632 switch (type.isDestructedType()) {
633 case QualType::DK_none:
634 break;
635 case QualType::DK_cxx_destructor:
636 PushDestructorCleanup(type, blockField);
637 break;
638 case QualType::DK_objc_strong_lifetime:
639 PushARCReleaseCleanup(getARCCleanupKind(), type, blockField, false);
640 break;
641 case QualType::DK_objc_weak_lifetime:
642 // __weak objects on the stack always get EH cleanups.
643 PushARCWeakReleaseCleanup(NormalAndEHCleanup, type, blockField);
644 break;
645 }
646 }
John McCall6b5a61b2011-02-07 10:33:21 +0000647 }
648
649 // Cast to the converted block-pointer type, which happens (somewhat
650 // unfortunately) to be a pointer to function type.
651 llvm::Value *result =
652 Builder.CreateBitCast(blockAddr,
653 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000654
John McCall6b5a61b2011-02-07 10:33:21 +0000655 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000656}
657
658
John McCalld16c2cf2011-02-08 08:22:06 +0000659const llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000660 if (BlockDescriptorType)
661 return BlockDescriptorType;
662
Mike Stumpa5448542009-02-13 15:32:32 +0000663 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000664 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000665
Mike Stumpab695142009-02-13 15:16:56 +0000666 // struct __block_descriptor {
667 // unsigned long reserved;
668 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000669 //
670 // // later, the following will be added
671 //
672 // struct {
673 // void (*copyHelper)();
674 // void (*copyHelper)();
675 // } helpers; // !!! optional
676 //
677 // const char *signature; // the block signature
678 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000679 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000680 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
681 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000682 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000683 NULL);
684
685 getModule().addTypeName("struct.__block_descriptor",
686 BlockDescriptorType);
687
John McCall6b5a61b2011-02-07 10:33:21 +0000688 // Now form a pointer to that.
689 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000690 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000691}
692
John McCalld16c2cf2011-02-08 08:22:06 +0000693const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000694 if (GenericBlockLiteralType)
695 return GenericBlockLiteralType;
696
John McCall6b5a61b2011-02-07 10:33:21 +0000697 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000698
Mike Stump9b8a7972009-02-13 15:25:34 +0000699 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000700 // void *__isa;
701 // int __flags;
702 // int __reserved;
703 // void (*__invoke)(void *);
704 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000705 // };
John McCall5936e332011-02-15 09:22:45 +0000706 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(),
707 VoidPtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000708 IntTy,
709 IntTy,
John McCall5936e332011-02-15 09:22:45 +0000710 VoidPtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000711 BlockDescPtrTy,
712 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000713
Mike Stump9b8a7972009-02-13 15:25:34 +0000714 getModule().addTypeName("struct.__block_literal_generic",
715 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000716
Mike Stump9b8a7972009-02-13 15:25:34 +0000717 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000718}
719
Mike Stumpbd65cac2009-02-19 01:01:04 +0000720
Anders Carlssona1736c02009-12-24 21:13:40 +0000721RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
722 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000723 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000724 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000725
Anders Carlssonacfde802009-02-12 00:39:25 +0000726 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
727
728 // Get a pointer to the generic block literal.
729 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000730 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000731
732 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000733 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000734 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
735
736 // Get the function pointer from the literal.
737 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000738
John McCall5936e332011-02-15 09:22:45 +0000739 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000740
Anders Carlssonacfde802009-02-12 00:39:25 +0000741 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000742 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000743 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000744
Anders Carlsson782f3972009-04-08 23:13:16 +0000745 QualType FnType = BPT->getPointeeType();
746
Anders Carlssonacfde802009-02-12 00:39:25 +0000747 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000748 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000749 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000750
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000751 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000752 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000753
John McCall64cd2322011-03-09 08:39:33 +0000754 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCall04a67a62010-02-05 21:31:56 +0000755 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000756
Mike Stump1eb44332009-09-09 15:08:12 +0000757 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000758 CGM.getTypes().getFunctionInfo(ResultType, Args,
759 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000761 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000762 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000763 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Owen Anderson96e0fc72009-07-29 22:16:19 +0000765 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000766 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Anders Carlssonacfde802009-02-12 00:39:25 +0000768 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000769 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000770}
Anders Carlssond5cab542009-02-12 17:55:02 +0000771
John McCall6b5a61b2011-02-07 10:33:21 +0000772llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
773 bool isByRef) {
774 assert(BlockInfo && "evaluating block ref without block information?");
775 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000776
John McCall6b5a61b2011-02-07 10:33:21 +0000777 // Handle constant captures.
778 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000779
John McCall6b5a61b2011-02-07 10:33:21 +0000780 llvm::Value *addr =
781 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
782 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000783
John McCall6b5a61b2011-02-07 10:33:21 +0000784 if (isByRef) {
785 // addr should be a void** right now. Load, then cast the result
786 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000787
John McCall6b5a61b2011-02-07 10:33:21 +0000788 addr = Builder.CreateLoad(addr);
789 const llvm::PointerType *byrefPointerType
790 = llvm::PointerType::get(BuildByRefType(variable), 0);
791 addr = Builder.CreateBitCast(addr, byrefPointerType,
792 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000793
John McCall6b5a61b2011-02-07 10:33:21 +0000794 // Follow the forwarding pointer.
795 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
796 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000797
John McCall6b5a61b2011-02-07 10:33:21 +0000798 // Cast back to byref* and GEP over to the actual object.
799 addr = Builder.CreateBitCast(addr, byrefPointerType);
800 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
801 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000802 }
803
John McCall6b5a61b2011-02-07 10:33:21 +0000804 if (variable->getType()->isReferenceType())
805 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000806
John McCall6b5a61b2011-02-07 10:33:21 +0000807 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000808}
809
Mike Stump67a64482009-02-14 22:16:35 +0000810llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000811CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000812 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000813 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000814
John McCall6b5a61b2011-02-07 10:33:21 +0000815 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000816 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000817
John McCall6b5a61b2011-02-07 10:33:21 +0000818 // Using that metadata, generate the actual block function.
819 llvm::Constant *blockFn;
820 {
821 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000822 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
823 blockInfo,
824 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000825 }
John McCall5936e332011-02-15 09:22:45 +0000826 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000827
John McCalld16c2cf2011-02-08 08:22:06 +0000828 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000829}
830
John McCall6b5a61b2011-02-07 10:33:21 +0000831static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
832 const CGBlockInfo &blockInfo,
833 llvm::Constant *blockFn) {
834 assert(blockInfo.CanBeGlobal);
835
836 // Generate the constants for the block literal initializer.
837 llvm::Constant *fields[BlockHeaderSize];
838
839 // isa
840 fields[0] = CGM.getNSConcreteGlobalBlock();
841
842 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000843 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
844 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
845
John McCall5936e332011-02-15 09:22:45 +0000846 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000847
848 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000849 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000850
851 // Function
852 fields[3] = blockFn;
853
854 // Descriptor
855 fields[4] = buildBlockDescriptor(CGM, blockInfo);
856
857 llvm::Constant *init =
858 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
859 /*packed*/ false);
860
861 llvm::GlobalVariable *literal =
862 new llvm::GlobalVariable(CGM.getModule(),
863 init->getType(),
864 /*constant*/ true,
865 llvm::GlobalVariable::InternalLinkage,
866 init,
867 "__block_literal_global");
868 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
869
870 // Return a constant of the appropriately-casted type.
871 const llvm::Type *requiredType =
872 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
873 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000874}
875
Mike Stump00470a12009-03-05 08:32:30 +0000876llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000877CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
878 const CGBlockInfo &blockInfo,
879 const Decl *outerFnDecl,
880 const DeclMapTy &ldm) {
881 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000882
Devang Patel6d1155b2011-03-07 21:53:18 +0000883 // Check if we should generate debug info for this block function.
884 if (CGM.getModuleDebugInfo())
885 DebugInfo = CGM.getModuleDebugInfo();
886
John McCall6b5a61b2011-02-07 10:33:21 +0000887 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Mike Stump7f28a9c2009-03-13 23:34:28 +0000889 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000890 // to be local to this function as well, in case they're directly
891 // referenced in a block.
892 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
893 const VarDecl *var = dyn_cast<VarDecl>(i->first);
894 if (var && !var->hasLocalStorage())
895 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000896 }
897
John McCall6b5a61b2011-02-07 10:33:21 +0000898 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000899
John McCall6b5a61b2011-02-07 10:33:21 +0000900 // Build the argument list.
901 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000902
John McCall6b5a61b2011-02-07 10:33:21 +0000903 // The first argument is the block pointer. Just take it as a void*
904 // and cast it later.
905 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000906 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000907
John McCall8178df32011-02-22 22:38:33 +0000908 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
909 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +0000910 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +0000911
John McCall6b5a61b2011-02-07 10:33:21 +0000912 // Now add the rest of the parameters.
913 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
914 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000915 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +0000916
John McCall6b5a61b2011-02-07 10:33:21 +0000917 // Create the function declaration.
918 const FunctionProtoType *fnType =
919 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
920 const CGFunctionInfo &fnInfo =
921 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
922 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +0000923 if (CGM.ReturnTypeUsesSRet(fnInfo))
924 blockInfo.UsesStret = true;
925
John McCall6b5a61b2011-02-07 10:33:21 +0000926 const llvm::FunctionType *fnLLVMType =
927 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000928
John McCall6b5a61b2011-02-07 10:33:21 +0000929 MangleBuffer name;
930 CGM.getBlockMangledName(GD, name, blockDecl);
931 llvm::Function *fn =
932 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
933 name.getString(), &CGM.getModule());
934 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000935
John McCall6b5a61b2011-02-07 10:33:21 +0000936 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +0000937 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +0000938 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +0000939 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000940
John McCall8178df32011-02-22 22:38:33 +0000941 // Okay. Undo some of what StartFunction did.
942
943 // Pull the 'self' reference out of the local decl map.
944 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
945 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000946 BlockPointer = Builder.CreateBitCast(blockAddr,
947 blockInfo.StructureType->getPointerTo(),
948 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000949
John McCallea1471e2010-05-20 01:18:31 +0000950 // If we have a C++ 'this' reference, go ahead and force it into
951 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000952 if (blockDecl->capturesCXXThis()) {
953 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
954 blockInfo.CXXThisIndex,
955 "block.captured-this");
956 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000957 }
958
John McCall6b5a61b2011-02-07 10:33:21 +0000959 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
960 // appease it.
961 if (const ObjCMethodDecl *method
962 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
963 const VarDecl *self = method->getSelfDecl();
964
965 // There might not be a capture for 'self', but if there is...
966 if (blockInfo.Captures.count(self)) {
967 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
968 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
969 capture.getIndex(),
970 "block.captured-self");
971 LocalDeclMap[self] = selfAddr;
972 }
973 }
974
975 // Also force all the constant captures.
976 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
977 ce = blockDecl->capture_end(); ci != ce; ++ci) {
978 const VarDecl *variable = ci->getVariable();
979 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
980 if (!capture.isConstant()) continue;
981
982 unsigned align = getContext().getDeclAlign(variable).getQuantity();
983
984 llvm::AllocaInst *alloca =
985 CreateMemTemp(variable->getType(), "block.captured-const");
986 alloca->setAlignment(align);
987
988 Builder.CreateStore(capture.getConstant(), alloca, align);
989
990 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000991 }
992
Mike Stumpb289b3f2009-10-01 22:29:41 +0000993 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
994 llvm::BasicBlock *entry = Builder.GetInsertBlock();
995 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
996 --entry_ptr;
997
John McCall6b5a61b2011-02-07 10:33:21 +0000998 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000999
Mike Stumpde8c5c72009-10-01 00:27:30 +00001000 // Remember where we were...
1001 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001002
Mike Stumpde8c5c72009-10-01 00:27:30 +00001003 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001004 ++entry_ptr;
1005 Builder.SetInsertPoint(entry, entry_ptr);
1006
John McCall6b5a61b2011-02-07 10:33:21 +00001007 // Emit debug information for all the BlockDeclRefDecls.
1008 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001009 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001010 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1011 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1012 const VarDecl *variable = ci->getVariable();
1013 DI->setLocation(variable->getLocation());
1014
1015 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1016 if (capture.isConstant()) {
1017 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1018 Builder);
1019 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001020 }
John McCall6b5a61b2011-02-07 10:33:21 +00001021
John McCall8178df32011-02-22 22:38:33 +00001022 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001023 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001024 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001025 }
John McCall6b5a61b2011-02-07 10:33:21 +00001026
Mike Stumpde8c5c72009-10-01 00:27:30 +00001027 // And resume where we left off.
1028 if (resume == 0)
1029 Builder.ClearInsertionPoint();
1030 else
1031 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001032
John McCall6b5a61b2011-02-07 10:33:21 +00001033 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001034
John McCall6b5a61b2011-02-07 10:33:21 +00001035 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001036}
Mike Stumpa99038c2009-02-28 09:07:16 +00001037
John McCall6b5a61b2011-02-07 10:33:21 +00001038/*
1039 notes.push_back(HelperInfo());
1040 HelperInfo &note = notes.back();
1041 note.index = capture.getIndex();
1042 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1043 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001044
John McCall6b5a61b2011-02-07 10:33:21 +00001045 if (ci->isByRef()) {
1046 note.flag = BLOCK_FIELD_IS_BYREF;
1047 if (type.isObjCGCWeak())
1048 note.flag |= BLOCK_FIELD_IS_WEAK;
1049 } else if (type->isBlockPointerType()) {
1050 note.flag = BLOCK_FIELD_IS_BLOCK;
1051 } else {
1052 note.flag = BLOCK_FIELD_IS_OBJECT;
1053 }
1054 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001055
Mike Stump00470a12009-03-05 08:32:30 +00001056
Mike Stumpa99038c2009-02-28 09:07:16 +00001057
John McCall6b5a61b2011-02-07 10:33:21 +00001058llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001059CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001060 ASTContext &C = getContext();
1061
1062 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001063 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1064 args.push_back(&dstDecl);
1065 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1066 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Mike Stumpa4f668f2009-03-06 01:33:24 +00001068 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001069 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001070
John McCall6b5a61b2011-02-07 10:33:21 +00001071 // FIXME: it would be nice if these were mergeable with things with
1072 // identical semantics.
1073 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001074
1075 llvm::Function *Fn =
1076 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001077 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001078
1079 IdentifierInfo *II
1080 = &CGM.getContext().Idents.get("__copy_helper_block_");
1081
Devang Patel58dc5ca2011-05-02 20:37:08 +00001082 // Check if we should generate debug info for this block helper function.
1083 if (CGM.getModuleDebugInfo())
1084 DebugInfo = CGM.getModuleDebugInfo();
1085
John McCall6b5a61b2011-02-07 10:33:21 +00001086 FunctionDecl *FD = FunctionDecl::Create(C,
1087 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001088 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001089 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001090 SC_Static,
1091 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001092 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001093 true);
John McCalld26bc762011-03-09 04:27:21 +00001094 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001095
John McCall6b5a61b2011-02-07 10:33:21 +00001096 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001097
John McCalld26bc762011-03-09 04:27:21 +00001098 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001099 src = Builder.CreateLoad(src);
1100 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001101
John McCalld26bc762011-03-09 04:27:21 +00001102 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001103 dst = Builder.CreateLoad(dst);
1104 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001105
John McCall6b5a61b2011-02-07 10:33:21 +00001106 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001107
John McCall6b5a61b2011-02-07 10:33:21 +00001108 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1109 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1110 const VarDecl *variable = ci->getVariable();
1111 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001112
John McCall6b5a61b2011-02-07 10:33:21 +00001113 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1114 if (capture.isConstant()) continue;
1115
1116 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001117 BlockFieldFlags flags;
1118
1119 bool isARCWeakCapture = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001120
1121 if (copyExpr) {
1122 assert(!ci->isByRef());
1123 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001124
John McCall6b5a61b2011-02-07 10:33:21 +00001125 } else if (ci->isByRef()) {
1126 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001127 if (type.isObjCGCWeak())
1128 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001129
John McCallf85e1932011-06-15 23:02:42 +00001130 } else if (type->isObjCRetainableType()) {
1131 flags = BLOCK_FIELD_IS_OBJECT;
1132 if (type->isBlockPointerType())
1133 flags = BLOCK_FIELD_IS_BLOCK;
1134
1135 // Special rules for ARC captures:
1136 if (getLangOptions().ObjCAutoRefCount) {
1137 Qualifiers qs = type.getQualifiers();
1138
1139 // Don't generate special copy logic for a captured object
1140 // unless it's __strong or __weak.
1141 if (!qs.hasStrongOrWeakObjCLifetime())
1142 continue;
1143
1144 // Support __weak direct captures.
1145 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1146 isARCWeakCapture = true;
1147 }
1148 } else {
1149 continue;
1150 }
John McCall6b5a61b2011-02-07 10:33:21 +00001151
1152 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001153 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1154 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001155
1156 // If there's an explicit copy expression, we do that.
1157 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001158 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCallf85e1932011-06-15 23:02:42 +00001159 } else if (isARCWeakCapture) {
1160 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001161 } else {
1162 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001163 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1164 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001165 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCallf85e1932011-06-15 23:02:42 +00001166 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
Mike Stump08920992009-03-07 02:35:30 +00001167 }
1168 }
1169
John McCalld16c2cf2011-02-08 08:22:06 +00001170 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001171
John McCall5936e332011-02-15 09:22:45 +00001172 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001173}
1174
John McCall6b5a61b2011-02-07 10:33:21 +00001175llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001176CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001177 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001178
John McCall6b5a61b2011-02-07 10:33:21 +00001179 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001180 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1181 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Mike Stumpa4f668f2009-03-06 01:33:24 +00001183 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001184 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001185
Mike Stump3899a7f2009-06-05 23:26:36 +00001186 // FIXME: We'd like to put these into a mergable by content, with
1187 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001188 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001189
1190 llvm::Function *Fn =
1191 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001192 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001193
Devang Patel58dc5ca2011-05-02 20:37:08 +00001194 // Check if we should generate debug info for this block destroy function.
1195 if (CGM.getModuleDebugInfo())
1196 DebugInfo = CGM.getModuleDebugInfo();
1197
Mike Stumpa4f668f2009-03-06 01:33:24 +00001198 IdentifierInfo *II
1199 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1200
John McCall6b5a61b2011-02-07 10:33:21 +00001201 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001202 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001203 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001204 SC_Static,
1205 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001206 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001207 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001208
John McCall6b5a61b2011-02-07 10:33:21 +00001209 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001210
John McCalld26bc762011-03-09 04:27:21 +00001211 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001212 src = Builder.CreateLoad(src);
1213 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001214
John McCall6b5a61b2011-02-07 10:33:21 +00001215 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1216
John McCalld16c2cf2011-02-08 08:22:06 +00001217 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001218
1219 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1220 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1221 const VarDecl *variable = ci->getVariable();
1222 QualType type = variable->getType();
1223
1224 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1225 if (capture.isConstant()) continue;
1226
John McCalld16c2cf2011-02-08 08:22:06 +00001227 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001228 const CXXDestructorDecl *dtor = 0;
1229
John McCallf85e1932011-06-15 23:02:42 +00001230 bool isARCWeakCapture = false;
1231
John McCall6b5a61b2011-02-07 10:33:21 +00001232 if (ci->isByRef()) {
1233 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001234 if (type.isObjCGCWeak())
1235 flags |= BLOCK_FIELD_IS_WEAK;
1236 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1237 if (record->hasTrivialDestructor())
1238 continue;
1239 dtor = record->getDestructor();
1240 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001241 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001242 if (type->isBlockPointerType())
1243 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001244
John McCallf85e1932011-06-15 23:02:42 +00001245 // Special rules for ARC captures.
1246 if (getLangOptions().ObjCAutoRefCount) {
1247 Qualifiers qs = type.getQualifiers();
1248
1249 // Don't generate special dispose logic for a captured object
1250 // unless it's __strong or __weak.
1251 if (!qs.hasStrongOrWeakObjCLifetime())
1252 continue;
1253
1254 // Support __weak direct captures.
1255 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1256 isARCWeakCapture = true;
1257 }
1258 } else {
1259 continue;
1260 }
John McCall6b5a61b2011-02-07 10:33:21 +00001261
1262 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001263 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001264
1265 // If there's an explicit copy expression, we do that.
1266 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001267 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001268
John McCallf85e1932011-06-15 23:02:42 +00001269 // If this is a __weak capture, emit the release directly.
1270 } else if (isARCWeakCapture) {
1271 EmitARCDestroyWeak(srcField);
1272
John McCall6b5a61b2011-02-07 10:33:21 +00001273 // Otherwise we call _Block_object_dispose. It wouldn't be too
1274 // hard to just emit this as a cleanup if we wanted to make sure
1275 // that things were done in reverse.
1276 } else {
1277 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001278 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001279 BuildBlockRelease(value, flags);
1280 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001281 }
1282
John McCall6b5a61b2011-02-07 10:33:21 +00001283 cleanups.ForceCleanup();
1284
John McCalld16c2cf2011-02-08 08:22:06 +00001285 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001286
John McCall5936e332011-02-15 09:22:45 +00001287 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001288}
1289
John McCallf0c11f72011-03-31 08:03:29 +00001290namespace {
1291
1292/// Emits the copy/dispose helper functions for a __block object of id type.
1293class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1294 BlockFieldFlags Flags;
1295
1296public:
1297 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1298 : ByrefHelpers(alignment), Flags(flags) {}
1299
John McCall36170192011-03-31 09:19:20 +00001300 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1301 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001302 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1303
1304 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1305 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1306
1307 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1308
1309 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1310 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1311 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1312 }
1313
1314 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1315 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1316 llvm::Value *value = CGF.Builder.CreateLoad(field);
1317
1318 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1319 }
1320
1321 void profileImpl(llvm::FoldingSetNodeID &id) const {
1322 id.AddInteger(Flags.getBitMask());
1323 }
1324};
1325
John McCallf85e1932011-06-15 23:02:42 +00001326/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1327class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1328public:
1329 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1330
1331 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1332 llvm::Value *srcField) {
1333 CGF.EmitARCMoveWeak(destField, srcField);
1334 }
1335
1336 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1337 CGF.EmitARCDestroyWeak(field);
1338 }
1339
1340 void profileImpl(llvm::FoldingSetNodeID &id) const {
1341 // 0 is distinguishable from all pointers and byref flags
1342 id.AddInteger(0);
1343 }
1344};
1345
1346/// Emits the copy/dispose helpers for an ARC __block __strong variable
1347/// that's not of block-pointer type.
1348class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1349public:
1350 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1351
1352 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1353 llvm::Value *srcField) {
1354 // Do a "move" by copying the value and then zeroing out the old
1355 // variable.
1356
1357 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1358 llvm::Value *null =
1359 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1360 CGF.Builder.CreateStore(value, destField);
1361 CGF.Builder.CreateStore(null, srcField);
1362 }
1363
1364 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1365 llvm::Value *value = CGF.Builder.CreateLoad(field);
1366 CGF.EmitARCRelease(value, /*precise*/ false);
1367 }
1368
1369 void profileImpl(llvm::FoldingSetNodeID &id) const {
1370 // 1 is distinguishable from all pointers and byref flags
1371 id.AddInteger(1);
1372 }
1373};
1374
John McCallf0c11f72011-03-31 08:03:29 +00001375/// Emits the copy/dispose helpers for a __block variable with a
1376/// nontrivial copy constructor or destructor.
1377class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1378 QualType VarType;
1379 const Expr *CopyExpr;
1380
1381public:
1382 CXXByrefHelpers(CharUnits alignment, QualType type,
1383 const Expr *copyExpr)
1384 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1385
1386 bool needsCopy() const { return CopyExpr != 0; }
1387 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1388 llvm::Value *srcField) {
1389 if (!CopyExpr) return;
1390 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1391 }
1392
1393 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1394 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1395 CGF.PushDestructorCleanup(VarType, field);
1396 CGF.PopCleanupBlocks(cleanupDepth);
1397 }
1398
1399 void profileImpl(llvm::FoldingSetNodeID &id) const {
1400 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1401 }
1402};
1403} // end anonymous namespace
1404
1405static llvm::Constant *
1406generateByrefCopyHelper(CodeGenFunction &CGF,
1407 const llvm::StructType &byrefType,
1408 CodeGenModule::ByrefHelpers &byrefInfo) {
1409 ASTContext &Context = CGF.getContext();
1410
1411 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001412
John McCalld26bc762011-03-09 04:27:21 +00001413 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001414 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001415 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001416
John McCallf0c11f72011-03-31 08:03:29 +00001417 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001418 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Mike Stump45031c02009-03-06 02:29:21 +00001420 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001421 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001422
John McCallf0c11f72011-03-31 08:03:29 +00001423 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001424 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1425
Mike Stump3899a7f2009-06-05 23:26:36 +00001426 // FIXME: We'd like to put these into a mergable by content, with
1427 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001428 llvm::Function *Fn =
1429 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001430 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001431
1432 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001433 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001434
John McCallf0c11f72011-03-31 08:03:29 +00001435 FunctionDecl *FD = FunctionDecl::Create(Context,
1436 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001437 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001438 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001439 SC_Static,
1440 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001441 false, true);
John McCallf85e1932011-06-15 23:02:42 +00001442
John McCallf0c11f72011-03-31 08:03:29 +00001443 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001444
John McCallf0c11f72011-03-31 08:03:29 +00001445 if (byrefInfo.needsCopy()) {
1446 const llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001447
John McCallf0c11f72011-03-31 08:03:29 +00001448 // dst->x
1449 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1450 destField = CGF.Builder.CreateLoad(destField);
1451 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1452 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001453
John McCallf0c11f72011-03-31 08:03:29 +00001454 // src->x
1455 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1456 srcField = CGF.Builder.CreateLoad(srcField);
1457 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1458 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1459
1460 byrefInfo.emitCopy(CGF, destField, srcField);
1461 }
1462
1463 CGF.FinishFunction();
1464
1465 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001466}
1467
John McCallf0c11f72011-03-31 08:03:29 +00001468/// Build the copy helper for a __block variable.
1469static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1470 const llvm::StructType &byrefType,
1471 CodeGenModule::ByrefHelpers &info) {
1472 CodeGenFunction CGF(CGM);
1473 return generateByrefCopyHelper(CGF, byrefType, info);
1474}
1475
1476/// Generate code for a __block variable's dispose helper.
1477static llvm::Constant *
1478generateByrefDisposeHelper(CodeGenFunction &CGF,
1479 const llvm::StructType &byrefType,
1480 CodeGenModule::ByrefHelpers &byrefInfo) {
1481 ASTContext &Context = CGF.getContext();
1482 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001483
John McCalld26bc762011-03-09 04:27:21 +00001484 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001485 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001486 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Mike Stump45031c02009-03-06 02:29:21 +00001488 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001489 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001490
John McCallf0c11f72011-03-31 08:03:29 +00001491 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001492 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1493
Mike Stump3899a7f2009-06-05 23:26:36 +00001494 // FIXME: We'd like to put these into a mergable by content, with
1495 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001496 llvm::Function *Fn =
1497 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001498 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001499 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001500
1501 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001502 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001503
John McCallf0c11f72011-03-31 08:03:29 +00001504 FunctionDecl *FD = FunctionDecl::Create(Context,
1505 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001506 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001507 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001508 SC_Static,
1509 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001510 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001511 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001512
John McCallf0c11f72011-03-31 08:03:29 +00001513 if (byrefInfo.needsDispose()) {
1514 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1515 V = CGF.Builder.CreateLoad(V);
1516 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1517 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001518
John McCallf0c11f72011-03-31 08:03:29 +00001519 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001520 }
Mike Stump45031c02009-03-06 02:29:21 +00001521
John McCallf0c11f72011-03-31 08:03:29 +00001522 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001523
John McCallf0c11f72011-03-31 08:03:29 +00001524 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001525}
1526
John McCallf0c11f72011-03-31 08:03:29 +00001527/// Build the dispose helper for a __block variable.
1528static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1529 const llvm::StructType &byrefType,
1530 CodeGenModule::ByrefHelpers &info) {
1531 CodeGenFunction CGF(CGM);
1532 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001533}
1534
John McCallf0c11f72011-03-31 08:03:29 +00001535///
1536template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1537 const llvm::StructType &byrefTy,
1538 T &byrefInfo) {
1539 // Increase the field's alignment to be at least pointer alignment,
1540 // since the layout of the byref struct will guarantee at least that.
1541 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1542 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1543
1544 llvm::FoldingSetNodeID id;
1545 byrefInfo.Profile(id);
1546
1547 void *insertPos;
1548 CodeGenModule::ByrefHelpers *node
1549 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1550 if (node) return static_cast<T*>(node);
1551
1552 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1553 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1554
1555 T *copy = new (CGM.getContext()) T(byrefInfo);
1556 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1557 return copy;
1558}
1559
1560CodeGenModule::ByrefHelpers *
1561CodeGenFunction::buildByrefHelpers(const llvm::StructType &byrefType,
1562 const AutoVarEmission &emission) {
1563 const VarDecl &var = *emission.Variable;
1564 QualType type = var.getType();
1565
1566 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1567 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1568 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1569
1570 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1571 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1572 }
1573
John McCallf85e1932011-06-15 23:02:42 +00001574 // Otherwise, if we don't have a retainable type, there's nothing to do.
1575 // that the runtime does extra copies.
1576 if (!type->isObjCRetainableType()) return 0;
1577
1578 Qualifiers qs = type.getQualifiers();
1579
1580 // If we have lifetime, that dominates.
1581 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1582 assert(getLangOptions().ObjCAutoRefCount);
1583
1584 switch (lifetime) {
1585 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1586
1587 // These are just bits as far as the runtime is concerned.
1588 case Qualifiers::OCL_ExplicitNone:
1589 case Qualifiers::OCL_Autoreleasing:
1590 return 0;
1591
1592 // Tell the runtime that this is ARC __weak, called by the
1593 // byref routines.
1594 case Qualifiers::OCL_Weak: {
1595 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1596 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1597 }
1598
1599 // ARC __strong __block variables need to be retained.
1600 case Qualifiers::OCL_Strong:
1601 // Block-pointers need to be _Block_copy'ed, so we let the
1602 // runtime be in charge. But we can't use the code below
1603 // because we don't want to set BYREF_CALLER, which will
1604 // just make the runtime ignore us.
1605 if (type->isBlockPointerType()) {
1606 BlockFieldFlags flags = BLOCK_FIELD_IS_BLOCK;
1607 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1608 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1609
1610 // Otherwise, we transfer ownership of the retain from the stack
1611 // to the heap.
1612 } else {
1613 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1614 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1615 }
1616 }
1617 llvm_unreachable("fell out of lifetime switch!");
1618 }
1619
John McCallf0c11f72011-03-31 08:03:29 +00001620 BlockFieldFlags flags;
1621 if (type->isBlockPointerType()) {
1622 flags |= BLOCK_FIELD_IS_BLOCK;
1623 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1624 type->isObjCObjectPointerType()) {
1625 flags |= BLOCK_FIELD_IS_OBJECT;
1626 } else {
1627 return 0;
1628 }
1629
1630 if (type.isObjCGCWeak())
1631 flags |= BLOCK_FIELD_IS_WEAK;
1632
1633 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1634 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001635}
1636
John McCall5af02db2011-03-31 01:59:53 +00001637unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1638 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1639
1640 return ByRefValueInfo.find(VD)->second.second;
1641}
1642
1643llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1644 const VarDecl *V) {
1645 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1646 Loc = Builder.CreateLoad(Loc);
1647 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1648 V->getNameAsString());
1649 return Loc;
1650}
1651
1652/// BuildByRefType - This routine changes a __block variable declared as T x
1653/// into:
1654///
1655/// struct {
1656/// void *__isa;
1657/// void *__forwarding;
1658/// int32_t __flags;
1659/// int32_t __size;
1660/// void *__copy_helper; // only if needed
1661/// void *__destroy_helper; // only if needed
1662/// char padding[X]; // only if needed
1663/// T x;
1664/// } x
1665///
1666const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1667 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
1668 if (Info.first)
1669 return Info.first;
1670
1671 QualType Ty = D->getType();
1672
John McCall0774cb82011-05-15 01:53:33 +00001673 llvm::SmallVector<const llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001674
1675 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext());
1676
1677 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001678 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001679
1680 // void *__forwarding;
John McCall0774cb82011-05-15 01:53:33 +00001681 types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
John McCall5af02db2011-03-31 01:59:53 +00001682
1683 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001684 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001685
1686 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001687 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001688
1689 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1690 if (HasCopyAndDispose) {
1691 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001692 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001693
1694 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001695 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001696 }
1697
1698 bool Packed = false;
1699 CharUnits Align = getContext().getDeclAlign(D);
1700 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1701 // We have to insert padding.
1702
1703 // The struct above has 2 32-bit integers.
1704 unsigned CurrentOffsetInBytes = 4 * 2;
1705
1706 // And either 2 or 4 pointers.
1707 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1708 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1709
1710 // Align the offset.
1711 unsigned AlignedOffsetInBytes =
1712 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1713
1714 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1715 if (NumPaddingBytes > 0) {
1716 const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
1717 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001718 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001719 if (NumPaddingBytes > 1)
1720 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1721
John McCall0774cb82011-05-15 01:53:33 +00001722 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001723
1724 // We want a packed struct.
1725 Packed = true;
1726 }
1727 }
1728
1729 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001730 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001731
John McCall0774cb82011-05-15 01:53:33 +00001732 const llvm::Type *T = llvm::StructType::get(getLLVMContext(), types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001733
1734 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
1735 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
1736 ByRefTypeHolder.get());
1737
1738 Info.first = ByRefTypeHolder.get();
1739
John McCall0774cb82011-05-15 01:53:33 +00001740 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001741
1742 return Info.first;
1743}
1744
1745/// Initialize the structural components of a __block variable, i.e.
1746/// everything but the actual object.
1747void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001748 // Find the address of the local.
1749 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001750
John McCallf0c11f72011-03-31 08:03:29 +00001751 // That's an alloca of the byref structure type.
1752 const llvm::StructType *byrefType = cast<llvm::StructType>(
1753 cast<llvm::PointerType>(addr->getType())->getElementType());
1754
1755 // Build the byref helpers if necessary. This is null if we don't need any.
1756 CodeGenModule::ByrefHelpers *helpers =
1757 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001758
1759 const VarDecl &D = *emission.Variable;
1760 QualType type = D.getType();
1761
John McCallf0c11f72011-03-31 08:03:29 +00001762 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001763
1764 // Initialize the 'isa', which is just 0 or 1.
1765 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001766 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001767 isa = 1;
1768 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1769 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1770
1771 // Store the address of the variable into its own forwarding pointer.
1772 Builder.CreateStore(addr,
1773 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1774
1775 // Blocks ABI:
1776 // c) the flags field is set to either 0 if no helper functions are
1777 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1778 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001779 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001780 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1781 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1782
John McCallf0c11f72011-03-31 08:03:29 +00001783 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1784 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001785 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1786
John McCallf0c11f72011-03-31 08:03:29 +00001787 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001788 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001789 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001790
1791 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001792 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001793 }
1794}
1795
John McCalld16c2cf2011-02-08 08:22:06 +00001796void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001797 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001798 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001799 V = Builder.CreateBitCast(V, Int8PtrTy);
1800 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001801 Builder.CreateCall2(F, V, N);
1802}
John McCall5af02db2011-03-31 01:59:53 +00001803
1804namespace {
1805 struct CallBlockRelease : EHScopeStack::Cleanup {
1806 llvm::Value *Addr;
1807 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1808
1809 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCallf85e1932011-06-15 23:02:42 +00001810 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00001811 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1812 }
1813 };
1814}
1815
1816/// Enter a cleanup to destroy a __block variable. Note that this
1817/// cleanup should be a no-op if the variable hasn't left the stack
1818/// yet; if a cleanup is required for the variable itself, that needs
1819/// to be done externally.
1820void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1821 // We don't enter this cleanup if we're in pure-GC mode.
1822 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1823 return;
1824
1825 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1826}