blob: aace5bb6f5fbf75fd013d311a926cc73bab6be12 [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 McCallc20e2042011-02-16 00:49:34 +000030 HasCXXObject(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 McCall6b5a61b2011-02-07 10:33:21 +000037/// Build the given block as a global block.
38static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
39 const CGBlockInfo &blockInfo,
40 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000041
John McCall6b5a61b2011-02-07 10:33:21 +000042/// Build the helper function to copy a block.
43static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
44 const CGBlockInfo &blockInfo) {
45 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
46}
47
48/// Build the helper function to dipose of a block.
49static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
50 const CGBlockInfo &blockInfo) {
51 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
52}
53
54/// Build the block descriptor constant for a block.
55static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
56 const CGBlockInfo &blockInfo) {
57 ASTContext &C = CGM.getContext();
58
59 const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
60 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
61
62 llvm::SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000063
64 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000065 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000066
67 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000068 // FIXME: What is the right way to say this doesn't fit? We should give
69 // a user diagnostic in that case. Better fix would be to change the
70 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000071 elements.push_back(llvm::ConstantInt::get(ulong,
72 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000073
John McCall6b5a61b2011-02-07 10:33:21 +000074 // Optional copy/dispose helpers.
75 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000076 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000077 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000078
79 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000080 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000081 }
82
John McCall6b5a61b2011-02-07 10:33:21 +000083 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
84 std::string typeAtEncoding =
85 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
86 elements.push_back(llvm::ConstantExpr::getBitCast(
87 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000088
John McCall6b5a61b2011-02-07 10:33:21 +000089 // GC layout.
90 if (C.getLangOptions().ObjC1)
91 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
92 else
93 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000094
John McCall6b5a61b2011-02-07 10:33:21 +000095 llvm::Constant *init =
96 llvm::ConstantStruct::get(CGM.getLLVMContext(), elements.data(),
97 elements.size(), false);
Mike Stumpe5fee252009-02-13 16:19:19 +000098
John McCall6b5a61b2011-02-07 10:33:21 +000099 llvm::GlobalVariable *global =
100 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
101 llvm::GlobalValue::InternalLinkage,
102 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000103
John McCall6b5a61b2011-02-07 10:33:21 +0000104 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000105}
106
John McCalld16c2cf2011-02-08 08:22:06 +0000107static BlockFlags computeBlockFlag(CodeGenModule &CGM,
108 const BlockExpr *BE,
109 BlockFlags flags) {
110 const FunctionType *ftype = BE->getFunctionType();
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000111
John McCalld16c2cf2011-02-08 08:22:06 +0000112 // This is a bit overboard.
113 CallArgList args;
114 const CGFunctionInfo &fnInfo =
115 CGM.getTypes().getFunctionInfo(ftype->getResultType(), args,
116 ftype->getExtInfo());
117
118 if (CGM.ReturnTypeUsesSRet(fnInfo))
119 flags |= BLOCK_USE_STRET;
120
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000121 return flags;
122}
123
John McCall6b5a61b2011-02-07 10:33:21 +0000124/*
125 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000126
John McCall6b5a61b2011-02-07 10:33:21 +0000127 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
128 struct Block_literal {
129 /// Initialized to one of:
130 /// extern void *_NSConcreteStackBlock[];
131 /// extern void *_NSConcreteGlobalBlock[];
132 ///
133 /// In theory, we could start one off malloc'ed by setting
134 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
135 /// this isa:
136 /// extern void *_NSConcreteMallocBlock[];
137 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000138
John McCall6b5a61b2011-02-07 10:33:21 +0000139 /// These are the flags (with corresponding bit number) that the
140 /// compiler is actually supposed to know about.
141 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
142 /// descriptor provides copy and dispose helper functions
143 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
144 /// object with a nontrivial destructor or copy constructor
145 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
146 /// as global memory
147 /// 29. BLOCK_USE_STRET - indicates that the block function
148 /// uses stret, which objc_msgSend needs to know about
149 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
150 /// @encoded signature string
151 /// And we're not supposed to manipulate these:
152 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
153 /// to malloc'ed memory
154 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
155 /// to GC-allocated memory
156 /// Additionally, the bottom 16 bits are a reference count which
157 /// should be zero on the stack.
158 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160 /// Reserved; should be zero-initialized.
161 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163 /// Function pointer generated from block literal.
164 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000165
John McCall6b5a61b2011-02-07 10:33:21 +0000166 /// Block description metadata generated from block literal.
167 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000168
John McCall6b5a61b2011-02-07 10:33:21 +0000169 /// Captured values follow.
170 _CapturesTypes captures...;
171 };
172 */
David Chisnall5e530af2009-11-17 19:33:30 +0000173
John McCall6b5a61b2011-02-07 10:33:21 +0000174/// The number of fields in a block header.
175const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000176
John McCall6b5a61b2011-02-07 10:33:21 +0000177namespace {
178 /// A chunk of data that we actually have to capture in the block.
179 struct BlockLayoutChunk {
180 CharUnits Alignment;
181 CharUnits Size;
182 const BlockDecl::Capture *Capture; // null for 'this'
183 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000184
John McCall6b5a61b2011-02-07 10:33:21 +0000185 BlockLayoutChunk(CharUnits align, CharUnits size,
186 const BlockDecl::Capture *capture,
187 const llvm::Type *type)
188 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000189
John McCall6b5a61b2011-02-07 10:33:21 +0000190 /// Tell the block info that this chunk has the given field index.
191 void setIndex(CGBlockInfo &info, unsigned index) {
192 if (!Capture)
193 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000194 else
John McCall6b5a61b2011-02-07 10:33:21 +0000195 info.Captures[Capture->getVariable()]
196 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000197 }
John McCall6b5a61b2011-02-07 10:33:21 +0000198 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000199
John McCall6b5a61b2011-02-07 10:33:21 +0000200 /// Order by descending alignment.
201 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
202 return left.Alignment > right.Alignment;
203 }
204}
205
John McCall461c9c12011-02-08 03:07:00 +0000206/// Determines if the given record type has a mutable field.
207static bool hasMutableField(const CXXRecordDecl *record) {
208 for (CXXRecordDecl::field_iterator
209 i = record->field_begin(), e = record->field_end(); i != e; ++i)
210 if ((*i)->isMutable())
211 return true;
212
213 for (CXXRecordDecl::base_class_const_iterator
214 i = record->bases_begin(), e = record->bases_end(); i != e; ++i) {
215 const RecordType *record = i->getType()->castAs<RecordType>();
216 if (hasMutableField(cast<CXXRecordDecl>(record->getDecl())))
217 return true;
218 }
219
220 return false;
221}
222
223/// Determines if the given type is safe for constant capture in C++.
224static bool isSafeForCXXConstantCapture(QualType type) {
225 const RecordType *recordType =
226 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
227
228 // Only records can be unsafe.
229 if (!recordType) return true;
230
231 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
232
233 // Maintain semantics for classes with non-trivial dtors or copy ctors.
234 if (!record->hasTrivialDestructor()) return false;
235 if (!record->hasTrivialCopyConstructor()) return false;
236
237 // Otherwise, we just have to make sure there aren't any mutable
238 // fields that might have changed since initialization.
239 return !hasMutableField(record);
240}
241
John McCall6b5a61b2011-02-07 10:33:21 +0000242/// It is illegal to modify a const object after initialization.
243/// Therefore, if a const object has a constant initializer, we don't
244/// actually need to keep storage for it in the block; we'll just
245/// rematerialize it at the start of the block function. This is
246/// acceptable because we make no promises about address stability of
247/// captured variables.
248static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
249 const VarDecl *var) {
250 QualType type = var->getType();
251
252 // We can only do this if the variable is const.
253 if (!type.isConstQualified()) return 0;
254
John McCall461c9c12011-02-08 03:07:00 +0000255 // Furthermore, in C++ we have to worry about mutable fields:
256 // C++ [dcl.type.cv]p4:
257 // Except that any class member declared mutable can be
258 // modified, any attempt to modify a const object during its
259 // lifetime results in undefined behavior.
260 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000261 return 0;
262
263 // If the variable doesn't have any initializer (shouldn't this be
264 // invalid?), it's not clear what we should do. Maybe capture as
265 // zero?
266 const Expr *init = var->getInit();
267 if (!init) return 0;
268
269 return CGM.EmitConstantExpr(init, var->getType());
270}
271
272/// Get the low bit of a nonzero character count. This is the
273/// alignment of the nth byte if the 0th byte is universally aligned.
274static CharUnits getLowBit(CharUnits v) {
275 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
276}
277
278static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
279 std::vector<const llvm::Type*> &elementTypes) {
280 ASTContext &C = CGM.getContext();
281
282 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
283 CharUnits ptrSize, ptrAlign, intSize, intAlign;
284 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
285 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
286
287 // Are there crazy embedded platforms where this isn't true?
288 assert(intSize <= ptrSize && "layout assumptions horribly violated");
289
290 CharUnits headerSize = ptrSize;
291 if (2 * intSize < ptrAlign) headerSize += ptrSize;
292 else headerSize += 2 * intSize;
293 headerSize += 2 * ptrSize;
294
295 info.BlockAlign = ptrAlign;
296 info.BlockSize = headerSize;
297
298 assert(elementTypes.empty());
299 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
300 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
301 elementTypes.push_back(i8p);
302 elementTypes.push_back(intTy);
303 elementTypes.push_back(intTy);
304 elementTypes.push_back(i8p);
305 elementTypes.push_back(CGM.getBlockDescriptorType());
306
307 assert(elementTypes.size() == BlockHeaderSize);
308}
309
310/// Compute the layout of the given block. Attempts to lay the block
311/// out with minimal space requirements.
312static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
313 ASTContext &C = CGM.getContext();
314 const BlockDecl *block = info.getBlockDecl();
315
316 std::vector<const llvm::Type*> elementTypes;
317 initializeForBlockHeader(CGM, info, elementTypes);
318
319 if (!block->hasCaptures()) {
320 info.StructureType =
321 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
322 info.CanBeGlobal = true;
323 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000324 }
Mike Stump00470a12009-03-05 08:32:30 +0000325
John McCall6b5a61b2011-02-07 10:33:21 +0000326 // Collect the layout chunks.
327 llvm::SmallVector<BlockLayoutChunk, 16> layout;
328 layout.reserve(block->capturesCXXThis() +
329 (block->capture_end() - block->capture_begin()));
330
331 CharUnits maxFieldAlign;
332
333 // First, 'this'.
334 if (block->capturesCXXThis()) {
335 const DeclContext *DC = block->getDeclContext();
336 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
337 ;
338 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
339
340 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
341 std::pair<CharUnits,CharUnits> tinfo
342 = CGM.getContext().getTypeInfoInChars(thisType);
343 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
344
345 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
346 }
347
348 // Next, all the block captures.
349 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
350 ce = block->capture_end(); ci != ce; ++ci) {
351 const VarDecl *variable = ci->getVariable();
352
353 if (ci->isByRef()) {
354 // We have to copy/dispose of the __block reference.
355 info.NeedsCopyDispose = true;
356
John McCall6b5a61b2011-02-07 10:33:21 +0000357 // Just use void* instead of a pointer to the byref type.
358 QualType byRefPtrTy = C.VoidPtrTy;
359
360 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
361 std::pair<CharUnits,CharUnits> tinfo
362 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
363 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
364
365 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
366 &*ci, llvmType));
367 continue;
368 }
369
370 // Otherwise, build a layout chunk with the size and alignment of
371 // the declaration.
372 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
373 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
374 continue;
375 }
376
377 // Block pointers require copy/dispose.
378 if (variable->getType()->isBlockPointerType()) {
379 info.NeedsCopyDispose = true;
380
381 // So do Objective-C pointers.
382 } else if (variable->getType()->isObjCObjectPointerType() ||
383 C.isObjCNSObjectType(variable->getType())) {
384 info.NeedsCopyDispose = true;
385
386 // So do types that require non-trivial copy construction.
387 } else if (ci->hasCopyExpr()) {
388 info.NeedsCopyDispose = true;
389 info.HasCXXObject = true;
390
391 // And so do types with destructors.
392 } else if (CGM.getLangOptions().CPlusPlus) {
393 if (const CXXRecordDecl *record =
394 variable->getType()->getAsCXXRecordDecl()) {
395 if (!record->hasTrivialDestructor()) {
396 info.HasCXXObject = true;
397 info.NeedsCopyDispose = true;
398 }
399 }
400 }
401
402 CharUnits size = C.getTypeSizeInChars(variable->getType());
403 CharUnits align = C.getDeclAlign(variable);
404 maxFieldAlign = std::max(maxFieldAlign, align);
405
406 const llvm::Type *llvmType =
407 CGM.getTypes().ConvertTypeForMem(variable->getType());
408
409 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
410 }
411
412 // If that was everything, we're done here.
413 if (layout.empty()) {
414 info.StructureType =
415 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
416 info.CanBeGlobal = true;
417 return;
418 }
419
420 // Sort the layout by alignment. We have to use a stable sort here
421 // to get reproducible results. There should probably be an
422 // llvm::array_pod_stable_sort.
423 std::stable_sort(layout.begin(), layout.end());
424
425 CharUnits &blockSize = info.BlockSize;
426 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
427
428 // Assuming that the first byte in the header is maximally aligned,
429 // get the alignment of the first byte following the header.
430 CharUnits endAlign = getLowBit(blockSize);
431
432 // If the end of the header isn't satisfactorily aligned for the
433 // maximum thing, look for things that are okay with the header-end
434 // alignment, and keep appending them until we get something that's
435 // aligned right. This algorithm is only guaranteed optimal if
436 // that condition is satisfied at some point; otherwise we can get
437 // things like:
438 // header // next byte has alignment 4
439 // something_with_size_5; // next byte has alignment 1
440 // something_with_alignment_8;
441 // which has 7 bytes of padding, as opposed to the naive solution
442 // which might have less (?).
443 if (endAlign < maxFieldAlign) {
444 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
445 li = layout.begin() + 1, le = layout.end();
446
447 // Look for something that the header end is already
448 // satisfactorily aligned for.
449 for (; li != le && endAlign < li->Alignment; ++li)
450 ;
451
452 // If we found something that's naturally aligned for the end of
453 // the header, keep adding things...
454 if (li != le) {
455 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
456 for (; li != le; ++li) {
457 assert(endAlign >= li->Alignment);
458
459 li->setIndex(info, elementTypes.size());
460 elementTypes.push_back(li->Type);
461 blockSize += li->Size;
462 endAlign = getLowBit(blockSize);
463
464 // ...until we get to the alignment of the maximum field.
465 if (endAlign >= maxFieldAlign)
466 break;
467 }
468
469 // Don't re-append everything we just appended.
470 layout.erase(first, li);
471 }
472 }
473
474 // At this point, we just have to add padding if the end align still
475 // isn't aligned right.
476 if (endAlign < maxFieldAlign) {
477 CharUnits padding = maxFieldAlign - endAlign;
478
John McCall5936e332011-02-15 09:22:45 +0000479 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
480 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000481 blockSize += padding;
482
483 endAlign = getLowBit(blockSize);
484 assert(endAlign >= maxFieldAlign);
485 }
486
487 // Slam everything else on now. This works because they have
488 // strictly decreasing alignment and we expect that size is always a
489 // multiple of alignment.
490 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
491 li = layout.begin(), le = layout.end(); li != le; ++li) {
492 assert(endAlign >= li->Alignment);
493 li->setIndex(info, elementTypes.size());
494 elementTypes.push_back(li->Type);
495 blockSize += li->Size;
496 endAlign = getLowBit(blockSize);
497 }
498
499 info.StructureType =
500 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
501}
502
503/// Emit a block literal expression in the current function.
504llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
505 std::string Name = CurFn->getName();
506 CGBlockInfo blockInfo(blockExpr, Name.c_str());
507
508 // Compute information about the layout, etc., of this block.
509 computeBlockInfo(CGM, blockInfo);
510
511 // Using that metadata, generate the actual block function.
512 llvm::Constant *blockFn
513 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
514 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000515 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000516
517 // If there is nothing to capture, we can emit this as a global block.
518 if (blockInfo.CanBeGlobal)
519 return buildGlobalBlock(CGM, blockInfo, blockFn);
520
521 // Otherwise, we have to emit this as a local block.
522
523 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000524 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000525
526 // Build the block descriptor.
527 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
528
529 const llvm::Type *intTy = ConvertType(getContext().IntTy);
530
531 llvm::AllocaInst *blockAddr =
532 CreateTempAlloca(blockInfo.StructureType, "block");
533 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
534
535 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000536 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000537 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
538 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
539 flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(), flags);
540
541 // Initialize the block literal.
542 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000543 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000544 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
545 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
546 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
547 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
548 "block.invoke"));
549 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
550 "block.descriptor"));
551
552 // Finally, capture all the values into the block.
553 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
554
555 // First, 'this'.
556 if (blockDecl->capturesCXXThis()) {
557 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
558 blockInfo.CXXThisIndex,
559 "block.captured-this.addr");
560 Builder.CreateStore(LoadCXXThis(), addr);
561 }
562
563 // Next, captured variables.
564 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
565 ce = blockDecl->capture_end(); ci != ce; ++ci) {
566 const VarDecl *variable = ci->getVariable();
567 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
568
569 // Ignore constant captures.
570 if (capture.isConstant()) continue;
571
572 QualType type = variable->getType();
573
574 // This will be a [[type]]*, except that a byref entry will just be
575 // an i8**.
576 llvm::Value *blockField =
577 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
578 "block.captured");
579
580 // Compute the address of the thing we're going to move into the
581 // block literal.
582 llvm::Value *src;
583 if (ci->isNested()) {
584 // We need to use the capture from the enclosing block.
585 const CGBlockInfo::Capture &enclosingCapture =
586 BlockInfo->getCapture(variable);
587
588 // This is a [[type]]*, except that a byref entry wil just be an i8**.
589 src = Builder.CreateStructGEP(LoadBlockStruct(),
590 enclosingCapture.getIndex(),
591 "block.capture.addr");
592 } else {
593 // This is a [[type]]*.
594 src = LocalDeclMap[variable];
595 }
596
597 // For byrefs, we just write the pointer to the byref struct into
598 // the block field. There's no need to chase the forwarding
599 // pointer at this point, since we're building something that will
600 // live a shorter life than the stack byref anyway.
601 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000602 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000603 if (ci->isNested())
604 src = Builder.CreateLoad(src, "byref.capture");
605 else
John McCall5936e332011-02-15 09:22:45 +0000606 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000607
John McCall5936e332011-02-15 09:22:45 +0000608 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000609 Builder.CreateStore(src, blockField);
610
611 // If we have a copy constructor, evaluate that into the block field.
612 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
613 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
614
615 // If it's a reference variable, copy the reference into the block field.
616 } else if (type->isReferenceType()) {
617 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
618
619 // Otherwise, fake up a POD copy into the block field.
620 } else {
John McCallbb699b02011-02-07 18:37:40 +0000621 // We use one of these or the other depending on whether the
622 // reference is nested.
623 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
624 SourceLocation());
625 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
626 VK_LValue, SourceLocation(), /*byref*/ false);
627
628 Expr *declRef =
629 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
630
John McCall6b5a61b2011-02-07 10:33:21 +0000631 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000632 declRef, VK_RValue);
John McCall6b5a61b2011-02-07 10:33:21 +0000633 EmitAnyExprToMem(&l2r, blockField, /*volatile*/ false, /*init*/ true);
634 }
635
636 // Push a destructor if necessary. The semantics for when this
637 // actually gets run are really obscure.
638 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus)
639 PushDestructorCleanup(type, blockField);
640 }
641
642 // Cast to the converted block-pointer type, which happens (somewhat
643 // unfortunately) to be a pointer to function type.
644 llvm::Value *result =
645 Builder.CreateBitCast(blockAddr,
646 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000647
John McCall6b5a61b2011-02-07 10:33:21 +0000648 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000649}
650
651
John McCalld16c2cf2011-02-08 08:22:06 +0000652const llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000653 if (BlockDescriptorType)
654 return BlockDescriptorType;
655
Mike Stumpa5448542009-02-13 15:32:32 +0000656 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000657 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000658
Mike Stumpab695142009-02-13 15:16:56 +0000659 // struct __block_descriptor {
660 // unsigned long reserved;
661 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000662 //
663 // // later, the following will be added
664 //
665 // struct {
666 // void (*copyHelper)();
667 // void (*copyHelper)();
668 // } helpers; // !!! optional
669 //
670 // const char *signature; // the block signature
671 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000672 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000673 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
674 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000675 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000676 NULL);
677
678 getModule().addTypeName("struct.__block_descriptor",
679 BlockDescriptorType);
680
John McCall6b5a61b2011-02-07 10:33:21 +0000681 // Now form a pointer to that.
682 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000683 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000684}
685
John McCalld16c2cf2011-02-08 08:22:06 +0000686const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000687 if (GenericBlockLiteralType)
688 return GenericBlockLiteralType;
689
John McCall6b5a61b2011-02-07 10:33:21 +0000690 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000691
Mike Stump9b8a7972009-02-13 15:25:34 +0000692 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000693 // void *__isa;
694 // int __flags;
695 // int __reserved;
696 // void (*__invoke)(void *);
697 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000698 // };
John McCall5936e332011-02-15 09:22:45 +0000699 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(),
700 VoidPtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000701 IntTy,
702 IntTy,
John McCall5936e332011-02-15 09:22:45 +0000703 VoidPtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000704 BlockDescPtrTy,
705 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000706
Mike Stump9b8a7972009-02-13 15:25:34 +0000707 getModule().addTypeName("struct.__block_literal_generic",
708 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000709
Mike Stump9b8a7972009-02-13 15:25:34 +0000710 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000711}
712
Mike Stumpbd65cac2009-02-19 01:01:04 +0000713
Anders Carlssona1736c02009-12-24 21:13:40 +0000714RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
715 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000716 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000717 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000718
Anders Carlssonacfde802009-02-12 00:39:25 +0000719 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
720
721 // Get a pointer to the generic block literal.
722 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000723 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000724
725 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000726 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000727 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
728
729 // Get the function pointer from the literal.
730 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000731
John McCall5936e332011-02-15 09:22:45 +0000732 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000733
Anders Carlssonacfde802009-02-12 00:39:25 +0000734 // Add the block literal.
735 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
736 CallArgList Args;
737 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000738
Anders Carlsson782f3972009-04-08 23:13:16 +0000739 QualType FnType = BPT->getPointeeType();
740
Anders Carlssonacfde802009-02-12 00:39:25 +0000741 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000742 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000743 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000744
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000745 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000746 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000747
John McCall04a67a62010-02-05 21:31:56 +0000748 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
749 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000750
Mike Stump1eb44332009-09-09 15:08:12 +0000751 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000752 CGM.getTypes().getFunctionInfo(ResultType, Args,
753 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000755 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000756 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000757 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Owen Anderson96e0fc72009-07-29 22:16:19 +0000759 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000760 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Anders Carlssonacfde802009-02-12 00:39:25 +0000762 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000763 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000764}
Anders Carlssond5cab542009-02-12 17:55:02 +0000765
John McCall6b5a61b2011-02-07 10:33:21 +0000766llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
767 bool isByRef) {
768 assert(BlockInfo && "evaluating block ref without block information?");
769 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000770
John McCall6b5a61b2011-02-07 10:33:21 +0000771 // Handle constant captures.
772 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000773
John McCall6b5a61b2011-02-07 10:33:21 +0000774 llvm::Value *addr =
775 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
776 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000777
John McCall6b5a61b2011-02-07 10:33:21 +0000778 if (isByRef) {
779 // addr should be a void** right now. Load, then cast the result
780 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000781
John McCall6b5a61b2011-02-07 10:33:21 +0000782 addr = Builder.CreateLoad(addr);
783 const llvm::PointerType *byrefPointerType
784 = llvm::PointerType::get(BuildByRefType(variable), 0);
785 addr = Builder.CreateBitCast(addr, byrefPointerType,
786 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000787
John McCall6b5a61b2011-02-07 10:33:21 +0000788 // Follow the forwarding pointer.
789 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
790 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000791
John McCall6b5a61b2011-02-07 10:33:21 +0000792 // Cast back to byref* and GEP over to the actual object.
793 addr = Builder.CreateBitCast(addr, byrefPointerType);
794 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
795 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000796 }
797
John McCall6b5a61b2011-02-07 10:33:21 +0000798 if (variable->getType()->isReferenceType())
799 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000800
John McCall6b5a61b2011-02-07 10:33:21 +0000801 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000802}
803
Mike Stump67a64482009-02-14 22:16:35 +0000804llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000805CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000806 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000807 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000808
John McCall6b5a61b2011-02-07 10:33:21 +0000809 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000810 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000811
John McCall6b5a61b2011-02-07 10:33:21 +0000812 // Using that metadata, generate the actual block function.
813 llvm::Constant *blockFn;
814 {
815 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000816 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
817 blockInfo,
818 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000819 }
John McCall5936e332011-02-15 09:22:45 +0000820 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000821
John McCalld16c2cf2011-02-08 08:22:06 +0000822 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000823}
824
John McCall6b5a61b2011-02-07 10:33:21 +0000825static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
826 const CGBlockInfo &blockInfo,
827 llvm::Constant *blockFn) {
828 assert(blockInfo.CanBeGlobal);
829
830 // Generate the constants for the block literal initializer.
831 llvm::Constant *fields[BlockHeaderSize];
832
833 // isa
834 fields[0] = CGM.getNSConcreteGlobalBlock();
835
836 // __flags
John McCalld16c2cf2011-02-08 08:22:06 +0000837 BlockFlags flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(),
838 BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
John McCall5936e332011-02-15 09:22:45 +0000839 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000840
841 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000842 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000843
844 // Function
845 fields[3] = blockFn;
846
847 // Descriptor
848 fields[4] = buildBlockDescriptor(CGM, blockInfo);
849
850 llvm::Constant *init =
851 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
852 /*packed*/ false);
853
854 llvm::GlobalVariable *literal =
855 new llvm::GlobalVariable(CGM.getModule(),
856 init->getType(),
857 /*constant*/ true,
858 llvm::GlobalVariable::InternalLinkage,
859 init,
860 "__block_literal_global");
861 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
862
863 // Return a constant of the appropriately-casted type.
864 const llvm::Type *requiredType =
865 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
866 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000867}
868
Mike Stump00470a12009-03-05 08:32:30 +0000869llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000870CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
871 const CGBlockInfo &blockInfo,
872 const Decl *outerFnDecl,
873 const DeclMapTy &ldm) {
874 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000875
Devang Patel6d1155b2011-03-07 21:53:18 +0000876 // Check if we should generate debug info for this block function.
877 if (CGM.getModuleDebugInfo())
878 DebugInfo = CGM.getModuleDebugInfo();
879
John McCall6b5a61b2011-02-07 10:33:21 +0000880 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Mike Stump7f28a9c2009-03-13 23:34:28 +0000882 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000883 // to be local to this function as well, in case they're directly
884 // referenced in a block.
885 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
886 const VarDecl *var = dyn_cast<VarDecl>(i->first);
887 if (var && !var->hasLocalStorage())
888 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000889 }
890
John McCall6b5a61b2011-02-07 10:33:21 +0000891 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000892
John McCall6b5a61b2011-02-07 10:33:21 +0000893 // Build the argument list.
894 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000895
John McCall6b5a61b2011-02-07 10:33:21 +0000896 // The first argument is the block pointer. Just take it as a void*
897 // and cast it later.
898 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000899 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000900
John McCall8178df32011-02-22 22:38:33 +0000901 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
902 SourceLocation(), II, selfTy);
903 args.push_back(std::make_pair(&selfDecl, selfTy));
Mike Stumpea26cb52009-10-21 03:49:08 +0000904
John McCall6b5a61b2011-02-07 10:33:21 +0000905 // Now add the rest of the parameters.
906 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
907 e = blockDecl->param_end(); i != e; ++i)
908 args.push_back(std::make_pair(*i, (*i)->getType()));
John McCallea1471e2010-05-20 01:18:31 +0000909
John McCall6b5a61b2011-02-07 10:33:21 +0000910 // Create the function declaration.
911 const FunctionProtoType *fnType =
912 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
913 const CGFunctionInfo &fnInfo =
914 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
915 fnType->getExtInfo());
916 const llvm::FunctionType *fnLLVMType =
917 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000918
John McCall6b5a61b2011-02-07 10:33:21 +0000919 MangleBuffer name;
920 CGM.getBlockMangledName(GD, name, blockDecl);
921 llvm::Function *fn =
922 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
923 name.getString(), &CGM.getModule());
924 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000925
John McCall6b5a61b2011-02-07 10:33:21 +0000926 // Begin generating the function.
927 StartFunction(blockDecl, fnType->getResultType(), fn, args,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000928 blockInfo.getBlockExpr()->getBody()->getLocEnd());
John McCall6b5a61b2011-02-07 10:33:21 +0000929 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000930
John McCall8178df32011-02-22 22:38:33 +0000931 // Okay. Undo some of what StartFunction did.
932
933 // Pull the 'self' reference out of the local decl map.
934 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
935 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000936 BlockPointer = Builder.CreateBitCast(blockAddr,
937 blockInfo.StructureType->getPointerTo(),
938 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000939
John McCallea1471e2010-05-20 01:18:31 +0000940 // If we have a C++ 'this' reference, go ahead and force it into
941 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000942 if (blockDecl->capturesCXXThis()) {
943 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
944 blockInfo.CXXThisIndex,
945 "block.captured-this");
946 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000947 }
948
John McCall6b5a61b2011-02-07 10:33:21 +0000949 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
950 // appease it.
951 if (const ObjCMethodDecl *method
952 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
953 const VarDecl *self = method->getSelfDecl();
954
955 // There might not be a capture for 'self', but if there is...
956 if (blockInfo.Captures.count(self)) {
957 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
958 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
959 capture.getIndex(),
960 "block.captured-self");
961 LocalDeclMap[self] = selfAddr;
962 }
963 }
964
965 // Also force all the constant captures.
966 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
967 ce = blockDecl->capture_end(); ci != ce; ++ci) {
968 const VarDecl *variable = ci->getVariable();
969 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
970 if (!capture.isConstant()) continue;
971
972 unsigned align = getContext().getDeclAlign(variable).getQuantity();
973
974 llvm::AllocaInst *alloca =
975 CreateMemTemp(variable->getType(), "block.captured-const");
976 alloca->setAlignment(align);
977
978 Builder.CreateStore(capture.getConstant(), alloca, align);
979
980 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000981 }
982
Mike Stumpb289b3f2009-10-01 22:29:41 +0000983 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
984 llvm::BasicBlock *entry = Builder.GetInsertBlock();
985 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
986 --entry_ptr;
987
John McCall6b5a61b2011-02-07 10:33:21 +0000988 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000989
Mike Stumpde8c5c72009-10-01 00:27:30 +0000990 // Remember where we were...
991 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000992
Mike Stumpde8c5c72009-10-01 00:27:30 +0000993 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000994 ++entry_ptr;
995 Builder.SetInsertPoint(entry, entry_ptr);
996
John McCall6b5a61b2011-02-07 10:33:21 +0000997 // Emit debug information for all the BlockDeclRefDecls.
998 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +0000999 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001000 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1001 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1002 const VarDecl *variable = ci->getVariable();
1003 DI->setLocation(variable->getLocation());
1004
1005 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1006 if (capture.isConstant()) {
1007 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1008 Builder);
1009 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001010 }
John McCall6b5a61b2011-02-07 10:33:21 +00001011
John McCall8178df32011-02-22 22:38:33 +00001012 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001013 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001014 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001015 }
John McCall6b5a61b2011-02-07 10:33:21 +00001016
Mike Stumpde8c5c72009-10-01 00:27:30 +00001017 // And resume where we left off.
1018 if (resume == 0)
1019 Builder.ClearInsertionPoint();
1020 else
1021 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001022
John McCall6b5a61b2011-02-07 10:33:21 +00001023 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001024
John McCall6b5a61b2011-02-07 10:33:21 +00001025 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001026}
Mike Stumpa99038c2009-02-28 09:07:16 +00001027
John McCall6b5a61b2011-02-07 10:33:21 +00001028/*
1029 notes.push_back(HelperInfo());
1030 HelperInfo &note = notes.back();
1031 note.index = capture.getIndex();
1032 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1033 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001034
John McCall6b5a61b2011-02-07 10:33:21 +00001035 if (ci->isByRef()) {
1036 note.flag = BLOCK_FIELD_IS_BYREF;
1037 if (type.isObjCGCWeak())
1038 note.flag |= BLOCK_FIELD_IS_WEAK;
1039 } else if (type->isBlockPointerType()) {
1040 note.flag = BLOCK_FIELD_IS_BLOCK;
1041 } else {
1042 note.flag = BLOCK_FIELD_IS_OBJECT;
1043 }
1044 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001045
Mike Stump00470a12009-03-05 08:32:30 +00001046
Mike Stumpa99038c2009-02-28 09:07:16 +00001047
Mike Stumpdab514f2009-03-04 03:23:46 +00001048
Mike Stumpa4f668f2009-03-06 01:33:24 +00001049
John McCall6b5a61b2011-02-07 10:33:21 +00001050llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001051CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001052 ASTContext &C = getContext();
1053
1054 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001055 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001056 ImplicitParamDecl *dstDecl =
1057 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1058 args.push_back(std::make_pair(dstDecl, dstDecl->getType()));
1059 ImplicitParamDecl *srcDecl =
1060 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1061 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Mike Stumpa4f668f2009-03-06 01:33:24 +00001063 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001064 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001065
John McCall6b5a61b2011-02-07 10:33:21 +00001066 // FIXME: it would be nice if these were mergeable with things with
1067 // identical semantics.
1068 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001069
1070 llvm::Function *Fn =
1071 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001072 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001073
1074 IdentifierInfo *II
1075 = &CGM.getContext().Idents.get("__copy_helper_block_");
1076
John McCall6b5a61b2011-02-07 10:33:21 +00001077 FunctionDecl *FD = FunctionDecl::Create(C,
1078 C.getTranslationUnitDecl(),
1079 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001080 SC_Static,
1081 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001082 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001083 true);
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001084 StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001085
John McCall6b5a61b2011-02-07 10:33:21 +00001086 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001087
John McCalld16c2cf2011-02-08 08:22:06 +00001088 llvm::Value *src = GetAddrOfLocalVar(srcDecl);
1089 src = Builder.CreateLoad(src);
1090 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001091
John McCalld16c2cf2011-02-08 08:22:06 +00001092 llvm::Value *dst = GetAddrOfLocalVar(dstDecl);
1093 dst = Builder.CreateLoad(dst);
1094 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001095
John McCall6b5a61b2011-02-07 10:33:21 +00001096 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001097
John McCall6b5a61b2011-02-07 10:33:21 +00001098 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1099 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1100 const VarDecl *variable = ci->getVariable();
1101 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001102
John McCall6b5a61b2011-02-07 10:33:21 +00001103 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1104 if (capture.isConstant()) continue;
1105
1106 const Expr *copyExpr = ci->getCopyExpr();
1107 unsigned flags = 0;
1108
1109 if (copyExpr) {
1110 assert(!ci->isByRef());
1111 // don't bother computing flags
1112 } else if (ci->isByRef()) {
1113 flags = BLOCK_FIELD_IS_BYREF;
1114 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1115 } else if (type->isBlockPointerType()) {
1116 flags = BLOCK_FIELD_IS_BLOCK;
1117 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1118 flags = BLOCK_FIELD_IS_OBJECT;
1119 }
1120
1121 if (!copyExpr && !flags) continue;
1122
1123 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001124 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1125 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001126
1127 // If there's an explicit copy expression, we do that.
1128 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001129 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall6b5a61b2011-02-07 10:33:21 +00001130 } else {
1131 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001132 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1133 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001134 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCalld16c2cf2011-02-08 08:22:06 +00001135 llvm::ConstantInt::get(Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001136 }
1137 }
1138
John McCalld16c2cf2011-02-08 08:22:06 +00001139 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001140
John McCall5936e332011-02-15 09:22:45 +00001141 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001142}
1143
John McCall6b5a61b2011-02-07 10:33:21 +00001144llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001145CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001146 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001147
John McCall6b5a61b2011-02-07 10:33:21 +00001148 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001149 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001150 ImplicitParamDecl *srcDecl =
1151 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1152 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Mike Stumpa4f668f2009-03-06 01:33:24 +00001154 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001155 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001156
Mike Stump3899a7f2009-06-05 23:26:36 +00001157 // FIXME: We'd like to put these into a mergable by content, with
1158 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001159 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001160
1161 llvm::Function *Fn =
1162 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001163 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001164
1165 IdentifierInfo *II
1166 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1167
John McCall6b5a61b2011-02-07 10:33:21 +00001168 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1169 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001170 SC_Static,
1171 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001172 false, true);
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001173 StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001174
John McCall6b5a61b2011-02-07 10:33:21 +00001175 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001176
John McCalld16c2cf2011-02-08 08:22:06 +00001177 llvm::Value *src = GetAddrOfLocalVar(srcDecl);
1178 src = Builder.CreateLoad(src);
1179 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001180
John McCall6b5a61b2011-02-07 10:33:21 +00001181 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1182
John McCalld16c2cf2011-02-08 08:22:06 +00001183 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001184
1185 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1186 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1187 const VarDecl *variable = ci->getVariable();
1188 QualType type = variable->getType();
1189
1190 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1191 if (capture.isConstant()) continue;
1192
John McCalld16c2cf2011-02-08 08:22:06 +00001193 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001194 const CXXDestructorDecl *dtor = 0;
1195
1196 if (ci->isByRef()) {
1197 flags = BLOCK_FIELD_IS_BYREF;
1198 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1199 } else if (type->isBlockPointerType()) {
1200 flags = BLOCK_FIELD_IS_BLOCK;
1201 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1202 flags = BLOCK_FIELD_IS_OBJECT;
1203 } else if (C.getLangOptions().CPlusPlus) {
1204 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1205 if (!record->hasTrivialDestructor())
1206 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001207 }
John McCall6b5a61b2011-02-07 10:33:21 +00001208
John McCalld16c2cf2011-02-08 08:22:06 +00001209 if (!dtor && flags.empty()) continue;
John McCall6b5a61b2011-02-07 10:33:21 +00001210
1211 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001212 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001213
1214 // If there's an explicit copy expression, we do that.
1215 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001216 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001217
1218 // Otherwise we call _Block_object_dispose. It wouldn't be too
1219 // hard to just emit this as a cleanup if we wanted to make sure
1220 // that things were done in reverse.
1221 } else {
1222 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001223 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001224 BuildBlockRelease(value, flags);
1225 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001226 }
1227
John McCall6b5a61b2011-02-07 10:33:21 +00001228 cleanups.ForceCleanup();
1229
John McCalld16c2cf2011-02-08 08:22:06 +00001230 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001231
John McCall5936e332011-02-15 09:22:45 +00001232 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001233}
1234
John McCalld16c2cf2011-02-08 08:22:06 +00001235llvm::Constant *CodeGenFunction::
1236GeneratebyrefCopyHelperFunction(const llvm::Type *T, BlockFieldFlags flags,
1237 const VarDecl *variable) {
Mike Stump45031c02009-03-06 02:29:21 +00001238 QualType R = getContext().VoidTy;
1239
1240 FunctionArgList Args;
1241 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001242 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001243 ImplicitParamDecl::Create(getContext(), 0,
1244 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001245 getContext().getPointerType(getContext().VoidTy));
1246 Args.push_back(std::make_pair(Dst, Dst->getType()));
1247
1248 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001249 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001250 ImplicitParamDecl::Create(getContext(), 0,
1251 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001252 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001253 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Mike Stump45031c02009-03-06 02:29:21 +00001255 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001256 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001257
Mike Stump45031c02009-03-06 02:29:21 +00001258 CodeGenTypes &Types = CGM.getTypes();
1259 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1260
Mike Stump3899a7f2009-06-05 23:26:36 +00001261 // FIXME: We'd like to put these into a mergable by content, with
1262 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001263 llvm::Function *Fn =
1264 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001265 "__Block_byref_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001266
1267 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001268 = &CGM.getContext().Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001269
1270 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1271 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001272 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001273 SC_Static,
1274 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001275 false, true);
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001276 StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001277
1278 // dst->x
John McCalld16c2cf2011-02-08 08:22:06 +00001279 llvm::Value *V = GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001280 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001281 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001282 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001283 llvm::Value *DstObj = V;
Mike Stumpee094222009-03-06 06:12:24 +00001284
1285 // src->x
John McCalld16c2cf2011-02-08 08:22:06 +00001286 V = GetAddrOfLocalVar(Src);
Mike Stumpee094222009-03-06 06:12:24 +00001287 V = Builder.CreateLoad(V);
1288 V = Builder.CreateBitCast(V, T);
1289 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001290
John McCalld16c2cf2011-02-08 08:22:06 +00001291 if (Expr *copyExpr = getContext().getBlockVarCopyInits(variable)) {
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001292 llvm::Value *SrcObj = V;
John McCalld16c2cf2011-02-08 08:22:06 +00001293 EmitSynthesizedCXXCopyCtor(DstObj, SrcObj, copyExpr);
1294 } else {
John McCall5936e332011-02-15 09:22:45 +00001295 DstObj = Builder.CreateBitCast(DstObj, VoidPtrTy);
1296 V = Builder.CreateBitCast(V, VoidPtrPtrTy);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001297 llvm::Value *SrcObj = Builder.CreateLoad(V);
John McCalld16c2cf2011-02-08 08:22:06 +00001298 flags |= BLOCK_BYREF_CALLER;
1299 llvm::Value *N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001300 llvm::Value *F = CGM.getBlockObjectAssign();
1301 Builder.CreateCall3(F, DstObj, SrcObj, N);
1302 }
1303
John McCalld16c2cf2011-02-08 08:22:06 +00001304 FinishFunction();
Mike Stump45031c02009-03-06 02:29:21 +00001305
John McCalld16c2cf2011-02-08 08:22:06 +00001306 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001307}
1308
Mike Stump1851b682009-03-06 04:53:30 +00001309llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001310CodeGenFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1311 BlockFieldFlags flags,
1312 const VarDecl *variable) {
Mike Stump45031c02009-03-06 02:29:21 +00001313 QualType R = getContext().VoidTy;
1314
1315 FunctionArgList Args;
1316 // FIXME: This leaks
1317 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001318 ImplicitParamDecl::Create(getContext(), 0,
1319 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001320 getContext().getPointerType(getContext().VoidTy));
1321
1322 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Mike Stump45031c02009-03-06 02:29:21 +00001324 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001325 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001326
Mike Stump45031c02009-03-06 02:29:21 +00001327 CodeGenTypes &Types = CGM.getTypes();
1328 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1329
Mike Stump3899a7f2009-06-05 23:26:36 +00001330 // FIXME: We'd like to put these into a mergable by content, with
1331 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001332 llvm::Function *Fn =
1333 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001334 "__Block_byref_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001335 &CGM.getModule());
1336
1337 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001338 = &CGM.getContext().Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001339
1340 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1341 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001342 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001343 SC_Static,
1344 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001345 false, true);
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001346 StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001347
John McCalld16c2cf2011-02-08 08:22:06 +00001348 llvm::Value *V = GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001349 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001350 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001351 V = Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001352
1353 // If it's not any kind of special object, it must have a destructor
1354 // or something.
1355 if (!flags.isSpecialPointer()) {
1356 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
1357 PushDestructorCleanup(variable->getType(), V);
1358 PopCleanupBlocks(CleanupDepth);
1359
1360 // Otherwise, call _Block_object_dispose.
1361 } else {
1362 V = Builder.CreateBitCast(V, llvm::PointerType::get(Int8PtrTy, 0));
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001363 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001364
John McCalld16c2cf2011-02-08 08:22:06 +00001365 flags |= BLOCK_BYREF_CALLER;
1366 BuildBlockRelease(V, flags);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001367 }
Mike Stump45031c02009-03-06 02:29:21 +00001368
John McCalld16c2cf2011-02-08 08:22:06 +00001369 FinishFunction();
1370
1371 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001372}
1373
John McCalld16c2cf2011-02-08 08:22:06 +00001374llvm::Constant *CodeGenModule::BuildbyrefCopyHelper(const llvm::Type *T,
1375 BlockFieldFlags flags,
John McCall6b5a61b2011-02-07 10:33:21 +00001376 unsigned align,
1377 const VarDecl *var) {
John McCall34695852011-02-22 06:44:22 +00001378 // All alignments below pointer alignment are bumped up, as we
1379 // always have at least that much alignment to begin with.
1380 if (align < PointerAlignInBytes) align = PointerAlignInBytes;
Chris Lattner10976d92009-12-05 08:21:30 +00001381
Mike Stump3899a7f2009-06-05 23:26:36 +00001382 // As an optimization, we only generate a single function of each kind we
1383 // might need. We need a different one for each alignment and for each
1384 // setting of flags. We mix Align and flag to get the kind.
John McCalld16c2cf2011-02-08 08:22:06 +00001385 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags.getBitMask();
1386 llvm::Constant *&Entry = AssignCache[Kind];
1387 if (!Entry)
1388 Entry = CodeGenFunction(*this).
1389 GeneratebyrefCopyHelperFunction(T, flags, var);
1390 return Entry;
Mike Stump45031c02009-03-06 02:29:21 +00001391}
1392
John McCalld16c2cf2011-02-08 08:22:06 +00001393llvm::Constant *CodeGenModule::BuildbyrefDestroyHelper(const llvm::Type *T,
1394 BlockFieldFlags flags,
John McCall6b5a61b2011-02-07 10:33:21 +00001395 unsigned align,
1396 const VarDecl *var) {
John McCall34695852011-02-22 06:44:22 +00001397 // All alignments below pointer alignment are bumped up, as we
1398 // always have at least that much alignment to begin with.
1399 if (align < PointerAlignInBytes) align = PointerAlignInBytes;
Chris Lattner10976d92009-12-05 08:21:30 +00001400
Mike Stump3899a7f2009-06-05 23:26:36 +00001401 // As an optimization, we only generate a single function of each kind we
1402 // might need. We need a different one for each alignment and for each
1403 // setting of flags. We mix Align and flag to get the kind.
John McCalld16c2cf2011-02-08 08:22:06 +00001404 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags.getBitMask();
1405 llvm::Constant *&Entry = DestroyCache[Kind];
1406 if (!Entry)
1407 Entry = CodeGenFunction(*this).
1408 GeneratebyrefDestroyHelperFunction(T, flags, var);
1409 return Entry;
Mike Stump45031c02009-03-06 02:29:21 +00001410}
1411
John McCalld16c2cf2011-02-08 08:22:06 +00001412void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001413 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001414 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001415 V = Builder.CreateBitCast(V, Int8PtrTy);
1416 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001417 Builder.CreateCall2(F, V, N);
1418}