blob: 20350c8e6ab466efa42affab627760b84f3839b3 [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 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 McCall6b5a61b2011-02-07 10:33:21 +0000107/*
108 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000109
John McCall6b5a61b2011-02-07 10:33:21 +0000110 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
111 struct Block_literal {
112 /// Initialized to one of:
113 /// extern void *_NSConcreteStackBlock[];
114 /// extern void *_NSConcreteGlobalBlock[];
115 ///
116 /// In theory, we could start one off malloc'ed by setting
117 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
118 /// this isa:
119 /// extern void *_NSConcreteMallocBlock[];
120 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000121
John McCall6b5a61b2011-02-07 10:33:21 +0000122 /// These are the flags (with corresponding bit number) that the
123 /// compiler is actually supposed to know about.
124 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
125 /// descriptor provides copy and dispose helper functions
126 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
127 /// object with a nontrivial destructor or copy constructor
128 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
129 /// as global memory
130 /// 29. BLOCK_USE_STRET - indicates that the block function
131 /// uses stret, which objc_msgSend needs to know about
132 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
133 /// @encoded signature string
134 /// And we're not supposed to manipulate these:
135 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
136 /// to malloc'ed memory
137 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
138 /// to GC-allocated memory
139 /// Additionally, the bottom 16 bits are a reference count which
140 /// should be zero on the stack.
141 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000142
John McCall6b5a61b2011-02-07 10:33:21 +0000143 /// Reserved; should be zero-initialized.
144 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000145
John McCall6b5a61b2011-02-07 10:33:21 +0000146 /// Function pointer generated from block literal.
147 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000148
John McCall6b5a61b2011-02-07 10:33:21 +0000149 /// Block description metadata generated from block literal.
150 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000151
John McCall6b5a61b2011-02-07 10:33:21 +0000152 /// Captured values follow.
153 _CapturesTypes captures...;
154 };
155 */
David Chisnall5e530af2009-11-17 19:33:30 +0000156
John McCall6b5a61b2011-02-07 10:33:21 +0000157/// The number of fields in a block header.
158const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160namespace {
161 /// A chunk of data that we actually have to capture in the block.
162 struct BlockLayoutChunk {
163 CharUnits Alignment;
164 CharUnits Size;
165 const BlockDecl::Capture *Capture; // null for 'this'
166 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000167
John McCall6b5a61b2011-02-07 10:33:21 +0000168 BlockLayoutChunk(CharUnits align, CharUnits size,
169 const BlockDecl::Capture *capture,
170 const llvm::Type *type)
171 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000172
John McCall6b5a61b2011-02-07 10:33:21 +0000173 /// Tell the block info that this chunk has the given field index.
174 void setIndex(CGBlockInfo &info, unsigned index) {
175 if (!Capture)
176 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000177 else
John McCall6b5a61b2011-02-07 10:33:21 +0000178 info.Captures[Capture->getVariable()]
179 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000180 }
John McCall6b5a61b2011-02-07 10:33:21 +0000181 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000182
John McCall6b5a61b2011-02-07 10:33:21 +0000183 /// Order by descending alignment.
184 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
185 return left.Alignment > right.Alignment;
186 }
187}
188
John McCall461c9c12011-02-08 03:07:00 +0000189/// Determines if the given record type has a mutable field.
190static bool hasMutableField(const CXXRecordDecl *record) {
191 for (CXXRecordDecl::field_iterator
192 i = record->field_begin(), e = record->field_end(); i != e; ++i)
193 if ((*i)->isMutable())
194 return true;
195
196 for (CXXRecordDecl::base_class_const_iterator
197 i = record->bases_begin(), e = record->bases_end(); i != e; ++i) {
198 const RecordType *record = i->getType()->castAs<RecordType>();
199 if (hasMutableField(cast<CXXRecordDecl>(record->getDecl())))
200 return true;
201 }
202
203 return false;
204}
205
206/// Determines if the given type is safe for constant capture in C++.
207static bool isSafeForCXXConstantCapture(QualType type) {
208 const RecordType *recordType =
209 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
210
211 // Only records can be unsafe.
212 if (!recordType) return true;
213
214 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
215
216 // Maintain semantics for classes with non-trivial dtors or copy ctors.
217 if (!record->hasTrivialDestructor()) return false;
218 if (!record->hasTrivialCopyConstructor()) return false;
219
220 // Otherwise, we just have to make sure there aren't any mutable
221 // fields that might have changed since initialization.
222 return !hasMutableField(record);
223}
224
John McCall6b5a61b2011-02-07 10:33:21 +0000225/// It is illegal to modify a const object after initialization.
226/// Therefore, if a const object has a constant initializer, we don't
227/// actually need to keep storage for it in the block; we'll just
228/// rematerialize it at the start of the block function. This is
229/// acceptable because we make no promises about address stability of
230/// captured variables.
231static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
232 const VarDecl *var) {
233 QualType type = var->getType();
234
235 // We can only do this if the variable is const.
236 if (!type.isConstQualified()) return 0;
237
John McCall461c9c12011-02-08 03:07:00 +0000238 // Furthermore, in C++ we have to worry about mutable fields:
239 // C++ [dcl.type.cv]p4:
240 // Except that any class member declared mutable can be
241 // modified, any attempt to modify a const object during its
242 // lifetime results in undefined behavior.
243 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000244 return 0;
245
246 // If the variable doesn't have any initializer (shouldn't this be
247 // invalid?), it's not clear what we should do. Maybe capture as
248 // zero?
249 const Expr *init = var->getInit();
250 if (!init) return 0;
251
252 return CGM.EmitConstantExpr(init, var->getType());
253}
254
255/// Get the low bit of a nonzero character count. This is the
256/// alignment of the nth byte if the 0th byte is universally aligned.
257static CharUnits getLowBit(CharUnits v) {
258 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
259}
260
261static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
262 std::vector<const llvm::Type*> &elementTypes) {
263 ASTContext &C = CGM.getContext();
264
265 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
266 CharUnits ptrSize, ptrAlign, intSize, intAlign;
267 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
268 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
269
270 // Are there crazy embedded platforms where this isn't true?
271 assert(intSize <= ptrSize && "layout assumptions horribly violated");
272
273 CharUnits headerSize = ptrSize;
274 if (2 * intSize < ptrAlign) headerSize += ptrSize;
275 else headerSize += 2 * intSize;
276 headerSize += 2 * ptrSize;
277
278 info.BlockAlign = ptrAlign;
279 info.BlockSize = headerSize;
280
281 assert(elementTypes.empty());
282 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
283 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
284 elementTypes.push_back(i8p);
285 elementTypes.push_back(intTy);
286 elementTypes.push_back(intTy);
287 elementTypes.push_back(i8p);
288 elementTypes.push_back(CGM.getBlockDescriptorType());
289
290 assert(elementTypes.size() == BlockHeaderSize);
291}
292
293/// Compute the layout of the given block. Attempts to lay the block
294/// out with minimal space requirements.
295static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
296 ASTContext &C = CGM.getContext();
297 const BlockDecl *block = info.getBlockDecl();
298
299 std::vector<const llvm::Type*> elementTypes;
300 initializeForBlockHeader(CGM, info, elementTypes);
301
302 if (!block->hasCaptures()) {
303 info.StructureType =
304 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
305 info.CanBeGlobal = true;
306 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000307 }
Mike Stump00470a12009-03-05 08:32:30 +0000308
John McCall6b5a61b2011-02-07 10:33:21 +0000309 // Collect the layout chunks.
310 llvm::SmallVector<BlockLayoutChunk, 16> layout;
311 layout.reserve(block->capturesCXXThis() +
312 (block->capture_end() - block->capture_begin()));
313
314 CharUnits maxFieldAlign;
315
316 // First, 'this'.
317 if (block->capturesCXXThis()) {
318 const DeclContext *DC = block->getDeclContext();
319 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
320 ;
321 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
322
323 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
324 std::pair<CharUnits,CharUnits> tinfo
325 = CGM.getContext().getTypeInfoInChars(thisType);
326 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
327
328 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
329 }
330
331 // Next, all the block captures.
332 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
333 ce = block->capture_end(); ci != ce; ++ci) {
334 const VarDecl *variable = ci->getVariable();
335
336 if (ci->isByRef()) {
337 // We have to copy/dispose of the __block reference.
338 info.NeedsCopyDispose = true;
339
John McCall6b5a61b2011-02-07 10:33:21 +0000340 // Just use void* instead of a pointer to the byref type.
341 QualType byRefPtrTy = C.VoidPtrTy;
342
343 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
344 std::pair<CharUnits,CharUnits> tinfo
345 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
346 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
347
348 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
349 &*ci, llvmType));
350 continue;
351 }
352
353 // Otherwise, build a layout chunk with the size and alignment of
354 // the declaration.
355 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
356 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
357 continue;
358 }
359
360 // Block pointers require copy/dispose.
361 if (variable->getType()->isBlockPointerType()) {
362 info.NeedsCopyDispose = true;
363
364 // So do Objective-C pointers.
365 } else if (variable->getType()->isObjCObjectPointerType() ||
366 C.isObjCNSObjectType(variable->getType())) {
367 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 McCallbb699b02011-02-07 18:37:40 +0000604 // We use one of these or the other depending on whether the
605 // reference is nested.
606 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
607 SourceLocation());
608 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
609 VK_LValue, SourceLocation(), /*byref*/ false);
610
611 Expr *declRef =
612 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
613
John McCall6b5a61b2011-02-07 10:33:21 +0000614 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000615 declRef, VK_RValue);
John McCalldf045202011-03-08 09:38:48 +0000616 EmitExprAsInit(&l2r, variable, blockField,
617 getContext().getDeclAlign(variable),
618 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000619 }
620
621 // Push a destructor if necessary. The semantics for when this
622 // actually gets run are really obscure.
623 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus)
624 PushDestructorCleanup(type, blockField);
625 }
626
627 // Cast to the converted block-pointer type, which happens (somewhat
628 // unfortunately) to be a pointer to function type.
629 llvm::Value *result =
630 Builder.CreateBitCast(blockAddr,
631 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000632
John McCall6b5a61b2011-02-07 10:33:21 +0000633 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000634}
635
636
John McCalld16c2cf2011-02-08 08:22:06 +0000637const llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000638 if (BlockDescriptorType)
639 return BlockDescriptorType;
640
Mike Stumpa5448542009-02-13 15:32:32 +0000641 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000642 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000643
Mike Stumpab695142009-02-13 15:16:56 +0000644 // struct __block_descriptor {
645 // unsigned long reserved;
646 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000647 //
648 // // later, the following will be added
649 //
650 // struct {
651 // void (*copyHelper)();
652 // void (*copyHelper)();
653 // } helpers; // !!! optional
654 //
655 // const char *signature; // the block signature
656 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000657 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000658 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
659 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000660 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000661 NULL);
662
663 getModule().addTypeName("struct.__block_descriptor",
664 BlockDescriptorType);
665
John McCall6b5a61b2011-02-07 10:33:21 +0000666 // Now form a pointer to that.
667 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000668 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000669}
670
John McCalld16c2cf2011-02-08 08:22:06 +0000671const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000672 if (GenericBlockLiteralType)
673 return GenericBlockLiteralType;
674
John McCall6b5a61b2011-02-07 10:33:21 +0000675 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000676
Mike Stump9b8a7972009-02-13 15:25:34 +0000677 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000678 // void *__isa;
679 // int __flags;
680 // int __reserved;
681 // void (*__invoke)(void *);
682 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000683 // };
John McCall5936e332011-02-15 09:22:45 +0000684 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(),
685 VoidPtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000686 IntTy,
687 IntTy,
John McCall5936e332011-02-15 09:22:45 +0000688 VoidPtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000689 BlockDescPtrTy,
690 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000691
Mike Stump9b8a7972009-02-13 15:25:34 +0000692 getModule().addTypeName("struct.__block_literal_generic",
693 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000694
Mike Stump9b8a7972009-02-13 15:25:34 +0000695 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000696}
697
Mike Stumpbd65cac2009-02-19 01:01:04 +0000698
Anders Carlssona1736c02009-12-24 21:13:40 +0000699RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
700 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000701 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000702 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000703
Anders Carlssonacfde802009-02-12 00:39:25 +0000704 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
705
706 // Get a pointer to the generic block literal.
707 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000708 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000709
710 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000711 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000712 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
713
714 // Get the function pointer from the literal.
715 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000716
John McCall5936e332011-02-15 09:22:45 +0000717 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000718
Anders Carlssonacfde802009-02-12 00:39:25 +0000719 // Add the block literal.
720 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
721 CallArgList Args;
722 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000723
Anders Carlsson782f3972009-04-08 23:13:16 +0000724 QualType FnType = BPT->getPointeeType();
725
Anders Carlssonacfde802009-02-12 00:39:25 +0000726 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000727 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000728 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000729
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000730 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000731 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000732
John McCall64cd2322011-03-09 08:39:33 +0000733 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCall04a67a62010-02-05 21:31:56 +0000734 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000735
Mike Stump1eb44332009-09-09 15:08:12 +0000736 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000737 CGM.getTypes().getFunctionInfo(ResultType, Args,
738 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000740 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000741 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000742 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Owen Anderson96e0fc72009-07-29 22:16:19 +0000744 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000745 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Anders Carlssonacfde802009-02-12 00:39:25 +0000747 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000748 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000749}
Anders Carlssond5cab542009-02-12 17:55:02 +0000750
John McCall6b5a61b2011-02-07 10:33:21 +0000751llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
752 bool isByRef) {
753 assert(BlockInfo && "evaluating block ref without block information?");
754 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000755
John McCall6b5a61b2011-02-07 10:33:21 +0000756 // Handle constant captures.
757 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000758
John McCall6b5a61b2011-02-07 10:33:21 +0000759 llvm::Value *addr =
760 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
761 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000762
John McCall6b5a61b2011-02-07 10:33:21 +0000763 if (isByRef) {
764 // addr should be a void** right now. Load, then cast the result
765 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000766
John McCall6b5a61b2011-02-07 10:33:21 +0000767 addr = Builder.CreateLoad(addr);
768 const llvm::PointerType *byrefPointerType
769 = llvm::PointerType::get(BuildByRefType(variable), 0);
770 addr = Builder.CreateBitCast(addr, byrefPointerType,
771 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000772
John McCall6b5a61b2011-02-07 10:33:21 +0000773 // Follow the forwarding pointer.
774 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
775 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000776
John McCall6b5a61b2011-02-07 10:33:21 +0000777 // Cast back to byref* and GEP over to the actual object.
778 addr = Builder.CreateBitCast(addr, byrefPointerType);
779 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
780 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000781 }
782
John McCall6b5a61b2011-02-07 10:33:21 +0000783 if (variable->getType()->isReferenceType())
784 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000785
John McCall6b5a61b2011-02-07 10:33:21 +0000786 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000787}
788
Mike Stump67a64482009-02-14 22:16:35 +0000789llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000790CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000791 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000792 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000793
John McCall6b5a61b2011-02-07 10:33:21 +0000794 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000795 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000796
John McCall6b5a61b2011-02-07 10:33:21 +0000797 // Using that metadata, generate the actual block function.
798 llvm::Constant *blockFn;
799 {
800 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000801 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
802 blockInfo,
803 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000804 }
John McCall5936e332011-02-15 09:22:45 +0000805 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000806
John McCalld16c2cf2011-02-08 08:22:06 +0000807 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000808}
809
John McCall6b5a61b2011-02-07 10:33:21 +0000810static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
811 const CGBlockInfo &blockInfo,
812 llvm::Constant *blockFn) {
813 assert(blockInfo.CanBeGlobal);
814
815 // Generate the constants for the block literal initializer.
816 llvm::Constant *fields[BlockHeaderSize];
817
818 // isa
819 fields[0] = CGM.getNSConcreteGlobalBlock();
820
821 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000822 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
823 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
824
John McCall5936e332011-02-15 09:22:45 +0000825 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000826
827 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000828 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000829
830 // Function
831 fields[3] = blockFn;
832
833 // Descriptor
834 fields[4] = buildBlockDescriptor(CGM, blockInfo);
835
836 llvm::Constant *init =
837 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
838 /*packed*/ false);
839
840 llvm::GlobalVariable *literal =
841 new llvm::GlobalVariable(CGM.getModule(),
842 init->getType(),
843 /*constant*/ true,
844 llvm::GlobalVariable::InternalLinkage,
845 init,
846 "__block_literal_global");
847 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
848
849 // Return a constant of the appropriately-casted type.
850 const llvm::Type *requiredType =
851 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
852 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000853}
854
Mike Stump00470a12009-03-05 08:32:30 +0000855llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000856CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
857 const CGBlockInfo &blockInfo,
858 const Decl *outerFnDecl,
859 const DeclMapTy &ldm) {
860 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000861
Devang Patel6d1155b2011-03-07 21:53:18 +0000862 // Check if we should generate debug info for this block function.
863 if (CGM.getModuleDebugInfo())
864 DebugInfo = CGM.getModuleDebugInfo();
865
John McCall6b5a61b2011-02-07 10:33:21 +0000866 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Mike Stump7f28a9c2009-03-13 23:34:28 +0000868 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000869 // to be local to this function as well, in case they're directly
870 // referenced in a block.
871 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
872 const VarDecl *var = dyn_cast<VarDecl>(i->first);
873 if (var && !var->hasLocalStorage())
874 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000875 }
876
John McCall6b5a61b2011-02-07 10:33:21 +0000877 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000878
John McCall6b5a61b2011-02-07 10:33:21 +0000879 // Build the argument list.
880 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000881
John McCall6b5a61b2011-02-07 10:33:21 +0000882 // The first argument is the block pointer. Just take it as a void*
883 // and cast it later.
884 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000885 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000886
John McCall8178df32011-02-22 22:38:33 +0000887 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
888 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +0000889 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +0000890
John McCall6b5a61b2011-02-07 10:33:21 +0000891 // Now add the rest of the parameters.
892 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
893 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000894 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +0000895
John McCall6b5a61b2011-02-07 10:33:21 +0000896 // Create the function declaration.
897 const FunctionProtoType *fnType =
898 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
899 const CGFunctionInfo &fnInfo =
900 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
901 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +0000902 if (CGM.ReturnTypeUsesSRet(fnInfo))
903 blockInfo.UsesStret = true;
904
John McCall6b5a61b2011-02-07 10:33:21 +0000905 const llvm::FunctionType *fnLLVMType =
906 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000907
John McCall6b5a61b2011-02-07 10:33:21 +0000908 MangleBuffer name;
909 CGM.getBlockMangledName(GD, name, blockDecl);
910 llvm::Function *fn =
911 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
912 name.getString(), &CGM.getModule());
913 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000914
John McCall6b5a61b2011-02-07 10:33:21 +0000915 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +0000916 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +0000917 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +0000918 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000919
John McCall8178df32011-02-22 22:38:33 +0000920 // Okay. Undo some of what StartFunction did.
921
922 // Pull the 'self' reference out of the local decl map.
923 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
924 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000925 BlockPointer = Builder.CreateBitCast(blockAddr,
926 blockInfo.StructureType->getPointerTo(),
927 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000928
John McCallea1471e2010-05-20 01:18:31 +0000929 // If we have a C++ 'this' reference, go ahead and force it into
930 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000931 if (blockDecl->capturesCXXThis()) {
932 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
933 blockInfo.CXXThisIndex,
934 "block.captured-this");
935 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000936 }
937
John McCall6b5a61b2011-02-07 10:33:21 +0000938 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
939 // appease it.
940 if (const ObjCMethodDecl *method
941 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
942 const VarDecl *self = method->getSelfDecl();
943
944 // There might not be a capture for 'self', but if there is...
945 if (blockInfo.Captures.count(self)) {
946 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
947 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
948 capture.getIndex(),
949 "block.captured-self");
950 LocalDeclMap[self] = selfAddr;
951 }
952 }
953
954 // Also force all the constant captures.
955 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
956 ce = blockDecl->capture_end(); ci != ce; ++ci) {
957 const VarDecl *variable = ci->getVariable();
958 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
959 if (!capture.isConstant()) continue;
960
961 unsigned align = getContext().getDeclAlign(variable).getQuantity();
962
963 llvm::AllocaInst *alloca =
964 CreateMemTemp(variable->getType(), "block.captured-const");
965 alloca->setAlignment(align);
966
967 Builder.CreateStore(capture.getConstant(), alloca, align);
968
969 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000970 }
971
Mike Stumpb289b3f2009-10-01 22:29:41 +0000972 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
973 llvm::BasicBlock *entry = Builder.GetInsertBlock();
974 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
975 --entry_ptr;
976
John McCall6b5a61b2011-02-07 10:33:21 +0000977 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000978
Mike Stumpde8c5c72009-10-01 00:27:30 +0000979 // Remember where we were...
980 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000981
Mike Stumpde8c5c72009-10-01 00:27:30 +0000982 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000983 ++entry_ptr;
984 Builder.SetInsertPoint(entry, entry_ptr);
985
John McCall6b5a61b2011-02-07 10:33:21 +0000986 // Emit debug information for all the BlockDeclRefDecls.
987 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +0000988 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000989 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
990 ce = blockDecl->capture_end(); ci != ce; ++ci) {
991 const VarDecl *variable = ci->getVariable();
992 DI->setLocation(variable->getLocation());
993
994 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
995 if (capture.isConstant()) {
996 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
997 Builder);
998 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +0000999 }
John McCall6b5a61b2011-02-07 10:33:21 +00001000
John McCall8178df32011-02-22 22:38:33 +00001001 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001002 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001003 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001004 }
John McCall6b5a61b2011-02-07 10:33:21 +00001005
Mike Stumpde8c5c72009-10-01 00:27:30 +00001006 // And resume where we left off.
1007 if (resume == 0)
1008 Builder.ClearInsertionPoint();
1009 else
1010 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001011
John McCall6b5a61b2011-02-07 10:33:21 +00001012 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001013
John McCall6b5a61b2011-02-07 10:33:21 +00001014 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001015}
Mike Stumpa99038c2009-02-28 09:07:16 +00001016
John McCall6b5a61b2011-02-07 10:33:21 +00001017/*
1018 notes.push_back(HelperInfo());
1019 HelperInfo &note = notes.back();
1020 note.index = capture.getIndex();
1021 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1022 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001023
John McCall6b5a61b2011-02-07 10:33:21 +00001024 if (ci->isByRef()) {
1025 note.flag = BLOCK_FIELD_IS_BYREF;
1026 if (type.isObjCGCWeak())
1027 note.flag |= BLOCK_FIELD_IS_WEAK;
1028 } else if (type->isBlockPointerType()) {
1029 note.flag = BLOCK_FIELD_IS_BLOCK;
1030 } else {
1031 note.flag = BLOCK_FIELD_IS_OBJECT;
1032 }
1033 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001034
Mike Stump00470a12009-03-05 08:32:30 +00001035
Mike Stumpa99038c2009-02-28 09:07:16 +00001036
Mike Stumpdab514f2009-03-04 03:23:46 +00001037
Mike Stumpa4f668f2009-03-06 01:33:24 +00001038
John McCall6b5a61b2011-02-07 10:33:21 +00001039llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001040CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001041 ASTContext &C = getContext();
1042
1043 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001044 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1045 args.push_back(&dstDecl);
1046 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1047 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Mike Stumpa4f668f2009-03-06 01:33:24 +00001049 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001050 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001051
John McCall6b5a61b2011-02-07 10:33:21 +00001052 // FIXME: it would be nice if these were mergeable with things with
1053 // identical semantics.
1054 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001055
1056 llvm::Function *Fn =
1057 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001058 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001059
1060 IdentifierInfo *II
1061 = &CGM.getContext().Idents.get("__copy_helper_block_");
1062
John McCall6b5a61b2011-02-07 10:33:21 +00001063 FunctionDecl *FD = FunctionDecl::Create(C,
1064 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001065 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001066 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001067 SC_Static,
1068 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001069 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001070 true);
John McCalld26bc762011-03-09 04:27:21 +00001071 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001072
John McCall6b5a61b2011-02-07 10:33:21 +00001073 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001074
John McCalld26bc762011-03-09 04:27:21 +00001075 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001076 src = Builder.CreateLoad(src);
1077 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001078
John McCalld26bc762011-03-09 04:27:21 +00001079 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001080 dst = Builder.CreateLoad(dst);
1081 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001082
John McCall6b5a61b2011-02-07 10:33:21 +00001083 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001084
John McCall6b5a61b2011-02-07 10:33:21 +00001085 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1086 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1087 const VarDecl *variable = ci->getVariable();
1088 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001089
John McCall6b5a61b2011-02-07 10:33:21 +00001090 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1091 if (capture.isConstant()) continue;
1092
1093 const Expr *copyExpr = ci->getCopyExpr();
1094 unsigned flags = 0;
1095
1096 if (copyExpr) {
1097 assert(!ci->isByRef());
1098 // don't bother computing flags
1099 } else if (ci->isByRef()) {
1100 flags = BLOCK_FIELD_IS_BYREF;
1101 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1102 } else if (type->isBlockPointerType()) {
1103 flags = BLOCK_FIELD_IS_BLOCK;
1104 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1105 flags = BLOCK_FIELD_IS_OBJECT;
1106 }
1107
1108 if (!copyExpr && !flags) continue;
1109
1110 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001111 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1112 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001113
1114 // If there's an explicit copy expression, we do that.
1115 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001116 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall6b5a61b2011-02-07 10:33:21 +00001117 } else {
1118 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001119 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1120 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001121 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCalld16c2cf2011-02-08 08:22:06 +00001122 llvm::ConstantInt::get(Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001123 }
1124 }
1125
John McCalld16c2cf2011-02-08 08:22:06 +00001126 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001127
John McCall5936e332011-02-15 09:22:45 +00001128 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001129}
1130
John McCall6b5a61b2011-02-07 10:33:21 +00001131llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001132CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001133 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001134
John McCall6b5a61b2011-02-07 10:33:21 +00001135 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001136 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1137 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Mike Stumpa4f668f2009-03-06 01:33:24 +00001139 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001140 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001141
Mike Stump3899a7f2009-06-05 23:26:36 +00001142 // FIXME: We'd like to put these into a mergable by content, with
1143 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001144 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001145
1146 llvm::Function *Fn =
1147 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001148 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001149
1150 IdentifierInfo *II
1151 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1152
John McCall6b5a61b2011-02-07 10:33:21 +00001153 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001154 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001155 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001156 SC_Static,
1157 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001158 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001159 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001160
John McCall6b5a61b2011-02-07 10:33:21 +00001161 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001162
John McCalld26bc762011-03-09 04:27:21 +00001163 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001164 src = Builder.CreateLoad(src);
1165 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001166
John McCall6b5a61b2011-02-07 10:33:21 +00001167 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1168
John McCalld16c2cf2011-02-08 08:22:06 +00001169 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001170
1171 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1172 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1173 const VarDecl *variable = ci->getVariable();
1174 QualType type = variable->getType();
1175
1176 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1177 if (capture.isConstant()) continue;
1178
John McCalld16c2cf2011-02-08 08:22:06 +00001179 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001180 const CXXDestructorDecl *dtor = 0;
1181
1182 if (ci->isByRef()) {
1183 flags = BLOCK_FIELD_IS_BYREF;
1184 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1185 } else if (type->isBlockPointerType()) {
1186 flags = BLOCK_FIELD_IS_BLOCK;
1187 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1188 flags = BLOCK_FIELD_IS_OBJECT;
1189 } else if (C.getLangOptions().CPlusPlus) {
1190 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1191 if (!record->hasTrivialDestructor())
1192 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001193 }
John McCall6b5a61b2011-02-07 10:33:21 +00001194
John McCalld16c2cf2011-02-08 08:22:06 +00001195 if (!dtor && flags.empty()) continue;
John McCall6b5a61b2011-02-07 10:33:21 +00001196
1197 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001198 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001199
1200 // If there's an explicit copy expression, we do that.
1201 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001202 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001203
1204 // Otherwise we call _Block_object_dispose. It wouldn't be too
1205 // hard to just emit this as a cleanup if we wanted to make sure
1206 // that things were done in reverse.
1207 } else {
1208 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001209 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001210 BuildBlockRelease(value, flags);
1211 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001212 }
1213
John McCall6b5a61b2011-02-07 10:33:21 +00001214 cleanups.ForceCleanup();
1215
John McCalld16c2cf2011-02-08 08:22:06 +00001216 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001217
John McCall5936e332011-02-15 09:22:45 +00001218 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001219}
1220
John McCalld16c2cf2011-02-08 08:22:06 +00001221llvm::Constant *CodeGenFunction::
1222GeneratebyrefCopyHelperFunction(const llvm::Type *T, BlockFieldFlags flags,
1223 const VarDecl *variable) {
Mike Stump45031c02009-03-06 02:29:21 +00001224 QualType R = getContext().VoidTy;
1225
John McCalld26bc762011-03-09 04:27:21 +00001226 FunctionArgList args;
1227 ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
1228 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001229
John McCalld26bc762011-03-09 04:27:21 +00001230 ImplicitParamDecl src(0, SourceLocation(), 0, getContext().VoidPtrTy);
1231 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Mike Stump45031c02009-03-06 02:29:21 +00001233 const CGFunctionInfo &FI =
John McCalld26bc762011-03-09 04:27:21 +00001234 CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001235
Mike Stump45031c02009-03-06 02:29:21 +00001236 CodeGenTypes &Types = CGM.getTypes();
1237 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1238
Mike Stump3899a7f2009-06-05 23:26:36 +00001239 // FIXME: We'd like to put these into a mergable by content, with
1240 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001241 llvm::Function *Fn =
1242 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001243 "__Block_byref_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001244
1245 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001246 = &CGM.getContext().Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001247
1248 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1249 getContext().getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001250 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001251 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001252 SC_Static,
1253 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001254 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001255 StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001256
1257 // dst->x
John McCalld26bc762011-03-09 04:27:21 +00001258 llvm::Value *V = GetAddrOfLocalVar(&dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001259 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001260 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001261 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001262 llvm::Value *DstObj = V;
Mike Stumpee094222009-03-06 06:12:24 +00001263
1264 // src->x
John McCalld26bc762011-03-09 04:27:21 +00001265 V = GetAddrOfLocalVar(&src);
Mike Stumpee094222009-03-06 06:12:24 +00001266 V = Builder.CreateLoad(V);
1267 V = Builder.CreateBitCast(V, T);
1268 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001269
John McCalld16c2cf2011-02-08 08:22:06 +00001270 if (Expr *copyExpr = getContext().getBlockVarCopyInits(variable)) {
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001271 llvm::Value *SrcObj = V;
John McCalld16c2cf2011-02-08 08:22:06 +00001272 EmitSynthesizedCXXCopyCtor(DstObj, SrcObj, copyExpr);
1273 } else {
John McCall5936e332011-02-15 09:22:45 +00001274 DstObj = Builder.CreateBitCast(DstObj, VoidPtrTy);
1275 V = Builder.CreateBitCast(V, VoidPtrPtrTy);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001276 llvm::Value *SrcObj = Builder.CreateLoad(V);
John McCalld16c2cf2011-02-08 08:22:06 +00001277 flags |= BLOCK_BYREF_CALLER;
1278 llvm::Value *N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001279 llvm::Value *F = CGM.getBlockObjectAssign();
1280 Builder.CreateCall3(F, DstObj, SrcObj, N);
1281 }
1282
John McCalld16c2cf2011-02-08 08:22:06 +00001283 FinishFunction();
Mike Stump45031c02009-03-06 02:29:21 +00001284
John McCalld16c2cf2011-02-08 08:22:06 +00001285 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001286}
1287
Mike Stump1851b682009-03-06 04:53:30 +00001288llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001289CodeGenFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1290 BlockFieldFlags flags,
1291 const VarDecl *variable) {
Mike Stump45031c02009-03-06 02:29:21 +00001292 QualType R = getContext().VoidTy;
1293
John McCalld26bc762011-03-09 04:27:21 +00001294 FunctionArgList args;
1295 ImplicitParamDecl src(0, SourceLocation(), 0, getContext().VoidPtrTy);
1296 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Mike Stump45031c02009-03-06 02:29:21 +00001298 const CGFunctionInfo &FI =
John McCalld26bc762011-03-09 04:27:21 +00001299 CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001300
Mike Stump45031c02009-03-06 02:29:21 +00001301 CodeGenTypes &Types = CGM.getTypes();
1302 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1303
Mike Stump3899a7f2009-06-05 23:26:36 +00001304 // FIXME: We'd like to put these into a mergable by content, with
1305 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001306 llvm::Function *Fn =
1307 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001308 "__Block_byref_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001309 &CGM.getModule());
1310
1311 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001312 = &CGM.getContext().Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001313
1314 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1315 getContext().getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001316 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001317 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001318 SC_Static,
1319 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001320 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001321 StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001322
John McCalld26bc762011-03-09 04:27:21 +00001323 llvm::Value *V = GetAddrOfLocalVar(&src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001324 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001325 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001326 V = Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001327
1328 // If it's not any kind of special object, it must have a destructor
1329 // or something.
1330 if (!flags.isSpecialPointer()) {
1331 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
1332 PushDestructorCleanup(variable->getType(), V);
1333 PopCleanupBlocks(CleanupDepth);
1334
1335 // Otherwise, call _Block_object_dispose.
1336 } else {
1337 V = Builder.CreateBitCast(V, llvm::PointerType::get(Int8PtrTy, 0));
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001338 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001339
John McCalld16c2cf2011-02-08 08:22:06 +00001340 flags |= BLOCK_BYREF_CALLER;
1341 BuildBlockRelease(V, flags);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001342 }
Mike Stump45031c02009-03-06 02:29:21 +00001343
John McCalld16c2cf2011-02-08 08:22:06 +00001344 FinishFunction();
1345
1346 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001347}
1348
John McCalld16c2cf2011-02-08 08:22:06 +00001349llvm::Constant *CodeGenModule::BuildbyrefCopyHelper(const llvm::Type *T,
1350 BlockFieldFlags flags,
John McCall6b5a61b2011-02-07 10:33:21 +00001351 unsigned align,
1352 const VarDecl *var) {
John McCall34695852011-02-22 06:44:22 +00001353 // All alignments below pointer alignment are bumped up, as we
1354 // always have at least that much alignment to begin with.
1355 if (align < PointerAlignInBytes) align = PointerAlignInBytes;
Chris Lattner10976d92009-12-05 08:21:30 +00001356
Mike Stump3899a7f2009-06-05 23:26:36 +00001357 // As an optimization, we only generate a single function of each kind we
1358 // might need. We need a different one for each alignment and for each
1359 // setting of flags. We mix Align and flag to get the kind.
John McCalld16c2cf2011-02-08 08:22:06 +00001360 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags.getBitMask();
1361 llvm::Constant *&Entry = AssignCache[Kind];
1362 if (!Entry)
1363 Entry = CodeGenFunction(*this).
1364 GeneratebyrefCopyHelperFunction(T, flags, var);
1365 return Entry;
Mike Stump45031c02009-03-06 02:29:21 +00001366}
1367
John McCalld16c2cf2011-02-08 08:22:06 +00001368llvm::Constant *CodeGenModule::BuildbyrefDestroyHelper(const llvm::Type *T,
1369 BlockFieldFlags flags,
John McCall6b5a61b2011-02-07 10:33:21 +00001370 unsigned align,
1371 const VarDecl *var) {
John McCall34695852011-02-22 06:44:22 +00001372 // All alignments below pointer alignment are bumped up, as we
1373 // always have at least that much alignment to begin with.
1374 if (align < PointerAlignInBytes) align = PointerAlignInBytes;
Chris Lattner10976d92009-12-05 08:21:30 +00001375
Mike Stump3899a7f2009-06-05 23:26:36 +00001376 // As an optimization, we only generate a single function of each kind we
1377 // might need. We need a different one for each alignment and for each
1378 // setting of flags. We mix Align and flag to get the kind.
John McCalld16c2cf2011-02-08 08:22:06 +00001379 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags.getBitMask();
1380 llvm::Constant *&Entry = DestroyCache[Kind];
1381 if (!Entry)
1382 Entry = CodeGenFunction(*this).
1383 GeneratebyrefDestroyHelperFunction(T, flags, var);
1384 return Entry;
Mike Stump45031c02009-03-06 02:29:21 +00001385}
1386
John McCalld16c2cf2011-02-08 08:22:06 +00001387void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001388 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001389 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001390 V = Builder.CreateBitCast(V, Int8PtrTy);
1391 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001392 Builder.CreateCall2(F, V, N);
1393}