blob: 1a7abd242aa8efe011e44c3465d929af66c8f38b [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"
Mike Stump6cc88f72009-03-20 21:53:12 +000018#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000019#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000020#include "llvm/ADT/SmallSet.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000021#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000022#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000023
Anders Carlssonacfde802009-02-12 00:39:25 +000024using namespace clang;
25using namespace CodeGen;
26
John McCall6b5a61b2011-02-07 10:33:21 +000027CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N)
28 : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
29 HasCXXObject(false), HasWeakBlockVariable(false),
30 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
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000107static unsigned computeBlockFlag(CodeGenModule &CGM,
108 const BlockExpr *BE, unsigned flags) {
109 QualType BPT = BE->getType();
110 const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
111 QualType ResultType = ftype->getResultType();
112
113 CallArgList Args;
114 CodeGenTypes &Types = CGM.getTypes();
115 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
116 FunctionType::ExtInfo());
117 if (CGM.ReturnTypeUsesSRet(FnInfo))
118 flags |= CodeGenFunction::BLOCK_USE_STRET;
119 return flags;
120}
121
John McCall6b5a61b2011-02-07 10:33:21 +0000122/*
123 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000124
John McCall6b5a61b2011-02-07 10:33:21 +0000125 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
126 struct Block_literal {
127 /// Initialized to one of:
128 /// extern void *_NSConcreteStackBlock[];
129 /// extern void *_NSConcreteGlobalBlock[];
130 ///
131 /// In theory, we could start one off malloc'ed by setting
132 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
133 /// this isa:
134 /// extern void *_NSConcreteMallocBlock[];
135 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000136
John McCall6b5a61b2011-02-07 10:33:21 +0000137 /// These are the flags (with corresponding bit number) that the
138 /// compiler is actually supposed to know about.
139 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
140 /// descriptor provides copy and dispose helper functions
141 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
142 /// object with a nontrivial destructor or copy constructor
143 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
144 /// as global memory
145 /// 29. BLOCK_USE_STRET - indicates that the block function
146 /// uses stret, which objc_msgSend needs to know about
147 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
148 /// @encoded signature string
149 /// And we're not supposed to manipulate these:
150 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
151 /// to malloc'ed memory
152 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
153 /// to GC-allocated memory
154 /// Additionally, the bottom 16 bits are a reference count which
155 /// should be zero on the stack.
156 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000157
John McCall6b5a61b2011-02-07 10:33:21 +0000158 /// Reserved; should be zero-initialized.
159 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000160
John McCall6b5a61b2011-02-07 10:33:21 +0000161 /// Function pointer generated from block literal.
162 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000163
John McCall6b5a61b2011-02-07 10:33:21 +0000164 /// Block description metadata generated from block literal.
165 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000166
John McCall6b5a61b2011-02-07 10:33:21 +0000167 /// Captured values follow.
168 _CapturesTypes captures...;
169 };
170 */
David Chisnall5e530af2009-11-17 19:33:30 +0000171
John McCall6b5a61b2011-02-07 10:33:21 +0000172/// The number of fields in a block header.
173const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000174
John McCall6b5a61b2011-02-07 10:33:21 +0000175namespace {
176 /// A chunk of data that we actually have to capture in the block.
177 struct BlockLayoutChunk {
178 CharUnits Alignment;
179 CharUnits Size;
180 const BlockDecl::Capture *Capture; // null for 'this'
181 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000182
John McCall6b5a61b2011-02-07 10:33:21 +0000183 BlockLayoutChunk(CharUnits align, CharUnits size,
184 const BlockDecl::Capture *capture,
185 const llvm::Type *type)
186 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000187
John McCall6b5a61b2011-02-07 10:33:21 +0000188 /// Tell the block info that this chunk has the given field index.
189 void setIndex(CGBlockInfo &info, unsigned index) {
190 if (!Capture)
191 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000192 else
John McCall6b5a61b2011-02-07 10:33:21 +0000193 info.Captures[Capture->getVariable()]
194 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000195 }
John McCall6b5a61b2011-02-07 10:33:21 +0000196 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000197
John McCall6b5a61b2011-02-07 10:33:21 +0000198 /// Order by descending alignment.
199 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
200 return left.Alignment > right.Alignment;
201 }
202}
203
204/// It is illegal to modify a const object after initialization.
205/// Therefore, if a const object has a constant initializer, we don't
206/// actually need to keep storage for it in the block; we'll just
207/// rematerialize it at the start of the block function. This is
208/// acceptable because we make no promises about address stability of
209/// captured variables.
210static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
211 const VarDecl *var) {
212 QualType type = var->getType();
213
214 // We can only do this if the variable is const.
215 if (!type.isConstQualified()) return 0;
216
217 // Furthermore, in C++ we can't do this for classes. TODO: we might
218 // actually be able to get away with it for classes with a trivial
219 // destructor and a trivial copy constructor and no mutable fields.
220 if (CGM.getLangOptions().CPlusPlus &&
221 type->getBaseElementTypeUnsafe()->isRecordType())
222 return 0;
223
224 // If the variable doesn't have any initializer (shouldn't this be
225 // invalid?), it's not clear what we should do. Maybe capture as
226 // zero?
227 const Expr *init = var->getInit();
228 if (!init) return 0;
229
230 return CGM.EmitConstantExpr(init, var->getType());
231}
232
233/// Get the low bit of a nonzero character count. This is the
234/// alignment of the nth byte if the 0th byte is universally aligned.
235static CharUnits getLowBit(CharUnits v) {
236 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
237}
238
239static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
240 std::vector<const llvm::Type*> &elementTypes) {
241 ASTContext &C = CGM.getContext();
242
243 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
244 CharUnits ptrSize, ptrAlign, intSize, intAlign;
245 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
246 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
247
248 // Are there crazy embedded platforms where this isn't true?
249 assert(intSize <= ptrSize && "layout assumptions horribly violated");
250
251 CharUnits headerSize = ptrSize;
252 if (2 * intSize < ptrAlign) headerSize += ptrSize;
253 else headerSize += 2 * intSize;
254 headerSize += 2 * ptrSize;
255
256 info.BlockAlign = ptrAlign;
257 info.BlockSize = headerSize;
258
259 assert(elementTypes.empty());
260 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
261 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
262 elementTypes.push_back(i8p);
263 elementTypes.push_back(intTy);
264 elementTypes.push_back(intTy);
265 elementTypes.push_back(i8p);
266 elementTypes.push_back(CGM.getBlockDescriptorType());
267
268 assert(elementTypes.size() == BlockHeaderSize);
269}
270
271/// Compute the layout of the given block. Attempts to lay the block
272/// out with minimal space requirements.
273static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
274 ASTContext &C = CGM.getContext();
275 const BlockDecl *block = info.getBlockDecl();
276
277 std::vector<const llvm::Type*> elementTypes;
278 initializeForBlockHeader(CGM, info, elementTypes);
279
280 if (!block->hasCaptures()) {
281 info.StructureType =
282 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
283 info.CanBeGlobal = true;
284 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000285 }
Mike Stump00470a12009-03-05 08:32:30 +0000286
John McCall6b5a61b2011-02-07 10:33:21 +0000287 // Collect the layout chunks.
288 llvm::SmallVector<BlockLayoutChunk, 16> layout;
289 layout.reserve(block->capturesCXXThis() +
290 (block->capture_end() - block->capture_begin()));
291
292 CharUnits maxFieldAlign;
293
294 // First, 'this'.
295 if (block->capturesCXXThis()) {
296 const DeclContext *DC = block->getDeclContext();
297 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
298 ;
299 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
300
301 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
302 std::pair<CharUnits,CharUnits> tinfo
303 = CGM.getContext().getTypeInfoInChars(thisType);
304 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
305
306 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
307 }
308
309 // Next, all the block captures.
310 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
311 ce = block->capture_end(); ci != ce; ++ci) {
312 const VarDecl *variable = ci->getVariable();
313
314 if (ci->isByRef()) {
315 // We have to copy/dispose of the __block reference.
316 info.NeedsCopyDispose = true;
317
318 // Also note that it's weak for GC purposes.
319 if (variable->getType().isObjCGCWeak())
320 info.HasWeakBlockVariable = true;
321
322 // Just use void* instead of a pointer to the byref type.
323 QualType byRefPtrTy = C.VoidPtrTy;
324
325 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
326 std::pair<CharUnits,CharUnits> tinfo
327 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
328 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
329
330 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
331 &*ci, llvmType));
332 continue;
333 }
334
335 // Otherwise, build a layout chunk with the size and alignment of
336 // the declaration.
337 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
338 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
339 continue;
340 }
341
342 // Block pointers require copy/dispose.
343 if (variable->getType()->isBlockPointerType()) {
344 info.NeedsCopyDispose = true;
345
346 // So do Objective-C pointers.
347 } else if (variable->getType()->isObjCObjectPointerType() ||
348 C.isObjCNSObjectType(variable->getType())) {
349 info.NeedsCopyDispose = true;
350
351 // So do types that require non-trivial copy construction.
352 } else if (ci->hasCopyExpr()) {
353 info.NeedsCopyDispose = true;
354 info.HasCXXObject = true;
355
356 // And so do types with destructors.
357 } else if (CGM.getLangOptions().CPlusPlus) {
358 if (const CXXRecordDecl *record =
359 variable->getType()->getAsCXXRecordDecl()) {
360 if (!record->hasTrivialDestructor()) {
361 info.HasCXXObject = true;
362 info.NeedsCopyDispose = true;
363 }
364 }
365 }
366
367 CharUnits size = C.getTypeSizeInChars(variable->getType());
368 CharUnits align = C.getDeclAlign(variable);
369 maxFieldAlign = std::max(maxFieldAlign, align);
370
371 const llvm::Type *llvmType =
372 CGM.getTypes().ConvertTypeForMem(variable->getType());
373
374 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
375 }
376
377 // If that was everything, we're done here.
378 if (layout.empty()) {
379 info.StructureType =
380 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
381 info.CanBeGlobal = true;
382 return;
383 }
384
385 // Sort the layout by alignment. We have to use a stable sort here
386 // to get reproducible results. There should probably be an
387 // llvm::array_pod_stable_sort.
388 std::stable_sort(layout.begin(), layout.end());
389
390 CharUnits &blockSize = info.BlockSize;
391 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
392
393 // Assuming that the first byte in the header is maximally aligned,
394 // get the alignment of the first byte following the header.
395 CharUnits endAlign = getLowBit(blockSize);
396
397 // If the end of the header isn't satisfactorily aligned for the
398 // maximum thing, look for things that are okay with the header-end
399 // alignment, and keep appending them until we get something that's
400 // aligned right. This algorithm is only guaranteed optimal if
401 // that condition is satisfied at some point; otherwise we can get
402 // things like:
403 // header // next byte has alignment 4
404 // something_with_size_5; // next byte has alignment 1
405 // something_with_alignment_8;
406 // which has 7 bytes of padding, as opposed to the naive solution
407 // which might have less (?).
408 if (endAlign < maxFieldAlign) {
409 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
410 li = layout.begin() + 1, le = layout.end();
411
412 // Look for something that the header end is already
413 // satisfactorily aligned for.
414 for (; li != le && endAlign < li->Alignment; ++li)
415 ;
416
417 // If we found something that's naturally aligned for the end of
418 // the header, keep adding things...
419 if (li != le) {
420 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
421 for (; li != le; ++li) {
422 assert(endAlign >= li->Alignment);
423
424 li->setIndex(info, elementTypes.size());
425 elementTypes.push_back(li->Type);
426 blockSize += li->Size;
427 endAlign = getLowBit(blockSize);
428
429 // ...until we get to the alignment of the maximum field.
430 if (endAlign >= maxFieldAlign)
431 break;
432 }
433
434 // Don't re-append everything we just appended.
435 layout.erase(first, li);
436 }
437 }
438
439 // At this point, we just have to add padding if the end align still
440 // isn't aligned right.
441 if (endAlign < maxFieldAlign) {
442 CharUnits padding = maxFieldAlign - endAlign;
443
444 const llvm::Type *i8 = llvm::IntegerType::get(CGM.getLLVMContext(), 8);
445 elementTypes.push_back(llvm::ArrayType::get(i8, padding.getQuantity()));
446 blockSize += padding;
447
448 endAlign = getLowBit(blockSize);
449 assert(endAlign >= maxFieldAlign);
450 }
451
452 // Slam everything else on now. This works because they have
453 // strictly decreasing alignment and we expect that size is always a
454 // multiple of alignment.
455 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
456 li = layout.begin(), le = layout.end(); li != le; ++li) {
457 assert(endAlign >= li->Alignment);
458 li->setIndex(info, elementTypes.size());
459 elementTypes.push_back(li->Type);
460 blockSize += li->Size;
461 endAlign = getLowBit(blockSize);
462 }
463
464 info.StructureType =
465 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
466}
467
468/// Emit a block literal expression in the current function.
469llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
470 std::string Name = CurFn->getName();
471 CGBlockInfo blockInfo(blockExpr, Name.c_str());
472
473 // Compute information about the layout, etc., of this block.
474 computeBlockInfo(CGM, blockInfo);
475
476 // Using that metadata, generate the actual block function.
477 llvm::Constant *blockFn
478 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
479 CurFuncDecl, LocalDeclMap);
480 blockFn = llvm::ConstantExpr::getBitCast(blockFn, PtrToInt8Ty);
481
482 // If there is nothing to capture, we can emit this as a global block.
483 if (blockInfo.CanBeGlobal)
484 return buildGlobalBlock(CGM, blockInfo, blockFn);
485
486 // Otherwise, we have to emit this as a local block.
487
488 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
489 isa = llvm::ConstantExpr::getBitCast(isa, PtrToInt8Ty);
490
491 // Build the block descriptor.
492 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
493
494 const llvm::Type *intTy = ConvertType(getContext().IntTy);
495
496 llvm::AllocaInst *blockAddr =
497 CreateTempAlloca(blockInfo.StructureType, "block");
498 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
499
500 // Compute the initial on-stack block flags.
501 unsigned int flags = BLOCK_HAS_SIGNATURE;
502 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
503 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
504 flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(), flags);
505
506 // Initialize the block literal.
507 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
508 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags),
509 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
510 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
511 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
512 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
513 "block.invoke"));
514 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
515 "block.descriptor"));
516
517 // Finally, capture all the values into the block.
518 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
519
520 // First, 'this'.
521 if (blockDecl->capturesCXXThis()) {
522 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
523 blockInfo.CXXThisIndex,
524 "block.captured-this.addr");
525 Builder.CreateStore(LoadCXXThis(), addr);
526 }
527
528 // Next, captured variables.
529 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
530 ce = blockDecl->capture_end(); ci != ce; ++ci) {
531 const VarDecl *variable = ci->getVariable();
532 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
533
534 // Ignore constant captures.
535 if (capture.isConstant()) continue;
536
537 QualType type = variable->getType();
538
539 // This will be a [[type]]*, except that a byref entry will just be
540 // an i8**.
541 llvm::Value *blockField =
542 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
543 "block.captured");
544
545 // Compute the address of the thing we're going to move into the
546 // block literal.
547 llvm::Value *src;
548 if (ci->isNested()) {
549 // We need to use the capture from the enclosing block.
550 const CGBlockInfo::Capture &enclosingCapture =
551 BlockInfo->getCapture(variable);
552
553 // This is a [[type]]*, except that a byref entry wil just be an i8**.
554 src = Builder.CreateStructGEP(LoadBlockStruct(),
555 enclosingCapture.getIndex(),
556 "block.capture.addr");
557 } else {
558 // This is a [[type]]*.
559 src = LocalDeclMap[variable];
560 }
561
562 // For byrefs, we just write the pointer to the byref struct into
563 // the block field. There's no need to chase the forwarding
564 // pointer at this point, since we're building something that will
565 // live a shorter life than the stack byref anyway.
566 if (ci->isByRef()) {
567 // Get an i8* that points to the byref struct.
568 if (ci->isNested())
569 src = Builder.CreateLoad(src, "byref.capture");
570 else
571 src = Builder.CreateBitCast(src, PtrToInt8Ty);
572
573 // Write that i8* into the capture field.
574 Builder.CreateStore(src, blockField);
575
576 // If we have a copy constructor, evaluate that into the block field.
577 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
578 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
579
580 // If it's a reference variable, copy the reference into the block field.
581 } else if (type->isReferenceType()) {
582 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
583
584 // Otherwise, fake up a POD copy into the block field.
585 } else {
John McCallbb699b02011-02-07 18:37:40 +0000586 // We use one of these or the other depending on whether the
587 // reference is nested.
588 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
589 SourceLocation());
590 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
591 VK_LValue, SourceLocation(), /*byref*/ false);
592
593 Expr *declRef =
594 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
595
John McCall6b5a61b2011-02-07 10:33:21 +0000596 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000597 declRef, VK_RValue);
John McCall6b5a61b2011-02-07 10:33:21 +0000598 EmitAnyExprToMem(&l2r, blockField, /*volatile*/ false, /*init*/ true);
599 }
600
601 // Push a destructor if necessary. The semantics for when this
602 // actually gets run are really obscure.
603 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus)
604 PushDestructorCleanup(type, blockField);
605 }
606
607 // Cast to the converted block-pointer type, which happens (somewhat
608 // unfortunately) to be a pointer to function type.
609 llvm::Value *result =
610 Builder.CreateBitCast(blockAddr,
611 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000612
613 // We must call objc_read_weak on the block literal itself if it closes
614 // on any __weak __block variables. For some reason.
John McCall6b5a61b2011-02-07 10:33:21 +0000615 if (blockInfo.HasWeakBlockVariable) {
616 const llvm::Type *OrigTy = result->getType();
John McCall711c52b2011-01-05 12:14:39 +0000617
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000618 // Must cast argument to id*
619 const llvm::Type *ObjectPtrTy =
620 ConvertType(CGM.getContext().getObjCIdType());
621 const llvm::Type *PtrObjectPtrTy =
622 llvm::PointerType::getUnqual(ObjectPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000623 result = Builder.CreateBitCast(result, PtrObjectPtrTy);
624 result = CGM.getObjCRuntime().EmitObjCWeakRead(*this, result);
John McCall711c52b2011-01-05 12:14:39 +0000625
626 // Cast back to the original type.
John McCall6b5a61b2011-02-07 10:33:21 +0000627 result = Builder.CreateBitCast(result, OrigTy);
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000628 }
John McCall6b5a61b2011-02-07 10:33:21 +0000629 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000630}
631
632
Mike Stump2a998142009-03-04 18:17:45 +0000633const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000634 if (BlockDescriptorType)
635 return BlockDescriptorType;
636
Mike Stumpa5448542009-02-13 15:32:32 +0000637 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000638 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000639
Mike Stumpab695142009-02-13 15:16:56 +0000640 // struct __block_descriptor {
641 // unsigned long reserved;
642 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000643 //
644 // // later, the following will be added
645 //
646 // struct {
647 // void (*copyHelper)();
648 // void (*copyHelper)();
649 // } helpers; // !!! optional
650 //
651 // const char *signature; // the block signature
652 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000653 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000654 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
655 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000656 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000657 NULL);
658
659 getModule().addTypeName("struct.__block_descriptor",
660 BlockDescriptorType);
661
John McCall6b5a61b2011-02-07 10:33:21 +0000662 // Now form a pointer to that.
663 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000664 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000665}
666
Mike Stump2a998142009-03-04 18:17:45 +0000667const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000668 if (GenericBlockLiteralType)
669 return GenericBlockLiteralType;
670
John McCall6b5a61b2011-02-07 10:33:21 +0000671 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000672
Mike Stump7cbb3602009-02-13 16:01:35 +0000673 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
674 getTypes().ConvertType(getContext().IntTy));
675
Mike Stump9b8a7972009-02-13 15:25:34 +0000676 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000677 // void *__isa;
678 // int __flags;
679 // int __reserved;
680 // void (*__invoke)(void *);
681 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000682 // };
Blaine Garst2a7eb282010-02-23 21:51:17 +0000683 GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
Owen Anderson47a434f2009-08-05 23:18:46 +0000684 PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000685 IntTy,
686 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000687 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000688 BlockDescPtrTy,
689 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000690
Mike Stump9b8a7972009-02-13 15:25:34 +0000691 getModule().addTypeName("struct.__block_literal_generic",
692 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000693
Mike Stump9b8a7972009-02-13 15:25:34 +0000694 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000695}
696
Mike Stumpbd65cac2009-02-19 01:01:04 +0000697
Anders Carlssona1736c02009-12-24 21:13:40 +0000698RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
699 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000700 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000701 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000702
Anders Carlssonacfde802009-02-12 00:39:25 +0000703 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
704
705 // Get a pointer to the generic block literal.
706 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000707 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000708
709 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000710 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000711 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
712
713 // Get the function pointer from the literal.
714 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000715
Mike Stumpa5448542009-02-13 15:32:32 +0000716 BlockLiteral =
717 Builder.CreateBitCast(BlockLiteral,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000718 llvm::Type::getInt8PtrTy(VMContext),
Anders Carlssonacfde802009-02-12 00:39:25 +0000719 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000720
Anders Carlssonacfde802009-02-12 00:39:25 +0000721 // Add the block literal.
722 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
723 CallArgList Args;
724 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000725
Anders Carlsson782f3972009-04-08 23:13:16 +0000726 QualType FnType = BPT->getPointeeType();
727
Anders Carlssonacfde802009-02-12 00:39:25 +0000728 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000729 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000730 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000731
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000732 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000733 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000734
John McCall04a67a62010-02-05 21:31:56 +0000735 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
736 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000737
Mike Stump1eb44332009-09-09 15:08:12 +0000738 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000739 CGM.getTypes().getFunctionInfo(ResultType, Args,
740 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000742 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000743 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000744 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Owen Anderson96e0fc72009-07-29 22:16:19 +0000746 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000747 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Anders Carlssonacfde802009-02-12 00:39:25 +0000749 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000750 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000751}
Anders Carlssond5cab542009-02-12 17:55:02 +0000752
John McCall6b5a61b2011-02-07 10:33:21 +0000753llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
754 bool isByRef) {
755 assert(BlockInfo && "evaluating block ref without block information?");
756 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000757
John McCall6b5a61b2011-02-07 10:33:21 +0000758 // Handle constant captures.
759 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000760
John McCall6b5a61b2011-02-07 10:33:21 +0000761 llvm::Value *addr =
762 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
763 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000764
John McCall6b5a61b2011-02-07 10:33:21 +0000765 if (isByRef) {
766 // addr should be a void** right now. Load, then cast the result
767 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000768
John McCall6b5a61b2011-02-07 10:33:21 +0000769 addr = Builder.CreateLoad(addr);
770 const llvm::PointerType *byrefPointerType
771 = llvm::PointerType::get(BuildByRefType(variable), 0);
772 addr = Builder.CreateBitCast(addr, byrefPointerType,
773 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000774
John McCall6b5a61b2011-02-07 10:33:21 +0000775 // Follow the forwarding pointer.
776 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
777 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000778
John McCall6b5a61b2011-02-07 10:33:21 +0000779 // Cast back to byref* and GEP over to the actual object.
780 addr = Builder.CreateBitCast(addr, byrefPointerType);
781 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
782 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000783 }
784
John McCall6b5a61b2011-02-07 10:33:21 +0000785 if (variable->getType()->isReferenceType())
786 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000787
John McCall6b5a61b2011-02-07 10:33:21 +0000788 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000789}
790
Mike Stump67a64482009-02-14 22:16:35 +0000791llvm::Constant *
John McCall6b5a61b2011-02-07 10:33:21 +0000792BlockModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
793 const char *name) {
794 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000795
John McCall6b5a61b2011-02-07 10:33:21 +0000796 // Compute information about the layout, etc., of this block.
797 computeBlockInfo(CGM, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000798
John McCall6b5a61b2011-02-07 10:33:21 +0000799 // Using that metadata, generate the actual block function.
800 llvm::Constant *blockFn;
801 {
802 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
803 blockFn = CodeGenFunction(CGM).GenerateBlockFunction(GlobalDecl(),
804 blockInfo,
805 0, LocalDeclMap);
806 }
807 blockFn = llvm::ConstantExpr::getBitCast(blockFn, PtrToInt8Ty);
Mike Stumpa5448542009-02-13 15:32:32 +0000808
John McCall6b5a61b2011-02-07 10:33:21 +0000809 return buildGlobalBlock(CGM, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000810}
811
John McCall6b5a61b2011-02-07 10:33:21 +0000812static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
813 const CGBlockInfo &blockInfo,
814 llvm::Constant *blockFn) {
815 assert(blockInfo.CanBeGlobal);
816
817 // Generate the constants for the block literal initializer.
818 llvm::Constant *fields[BlockHeaderSize];
819
820 // isa
821 fields[0] = CGM.getNSConcreteGlobalBlock();
822
823 // __flags
824 unsigned flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(),
825 BlockBase::BLOCK_IS_GLOBAL |
826 BlockBase::BLOCK_HAS_SIGNATURE);
827 const llvm::Type *intTy = CGM.getTypes().ConvertType(CGM.getContext().IntTy);
828 fields[1] = llvm::ConstantInt::get(intTy, flags);
829
830 // Reserved
831 fields[2] = llvm::Constant::getNullValue(intTy);
832
833 // Function
834 fields[3] = blockFn;
835
836 // Descriptor
837 fields[4] = buildBlockDescriptor(CGM, blockInfo);
838
839 llvm::Constant *init =
840 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
841 /*packed*/ false);
842
843 llvm::GlobalVariable *literal =
844 new llvm::GlobalVariable(CGM.getModule(),
845 init->getType(),
846 /*constant*/ true,
847 llvm::GlobalVariable::InternalLinkage,
848 init,
849 "__block_literal_global");
850 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
851
852 // Return a constant of the appropriately-casted type.
853 const llvm::Type *requiredType =
854 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
855 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000856}
857
Mike Stump00470a12009-03-05 08:32:30 +0000858llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000859CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
860 const CGBlockInfo &blockInfo,
861 const Decl *outerFnDecl,
862 const DeclMapTy &ldm) {
863 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000864
John McCall6b5a61b2011-02-07 10:33:21 +0000865 DebugInfo = CGM.getDebugInfo();
866 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 McCall6b5a61b2011-02-07 10:33:21 +0000887 // FIXME: this leaks, and we only need it very temporarily.
888 ImplicitParamDecl *selfDecl =
889 ImplicitParamDecl::Create(getContext(),
890 const_cast<BlockDecl*>(blockDecl),
891 SourceLocation(), II, selfTy);
892 args.push_back(std::make_pair(selfDecl, selfTy));
Mike Stumpea26cb52009-10-21 03:49:08 +0000893
John McCall6b5a61b2011-02-07 10:33:21 +0000894 // Now add the rest of the parameters.
895 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
896 e = blockDecl->param_end(); i != e; ++i)
897 args.push_back(std::make_pair(*i, (*i)->getType()));
John McCallea1471e2010-05-20 01:18:31 +0000898
John McCall6b5a61b2011-02-07 10:33:21 +0000899 // Create the function declaration.
900 const FunctionProtoType *fnType =
901 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
902 const CGFunctionInfo &fnInfo =
903 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
904 fnType->getExtInfo());
905 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.
916 StartFunction(blockDecl, fnType->getResultType(), fn, args,
917 blockInfo.getBlockExpr()->getBody()->getLocEnd());
918 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000919
John McCall6b5a61b2011-02-07 10:33:21 +0000920 // Okay. Undo some of what StartFunction did. We really don't need
921 // an alloca for the block address; in theory we could remove it,
922 // but that might do unpleasant things to debug info.
923 llvm::AllocaInst *blockAddrAlloca
924 = cast<llvm::AllocaInst>(LocalDeclMap[selfDecl]);
925 llvm::Value *blockAddr = Builder.CreateLoad(blockAddrAlloca);
926 BlockPointer = Builder.CreateBitCast(blockAddr,
927 blockInfo.StructureType->getPointerTo(),
928 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000929
John McCallea1471e2010-05-20 01:18:31 +0000930 // If we have a C++ 'this' reference, go ahead and force it into
931 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000932 if (blockDecl->capturesCXXThis()) {
933 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
934 blockInfo.CXXThisIndex,
935 "block.captured-this");
936 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000937 }
938
John McCall6b5a61b2011-02-07 10:33:21 +0000939 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
940 // appease it.
941 if (const ObjCMethodDecl *method
942 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
943 const VarDecl *self = method->getSelfDecl();
944
945 // There might not be a capture for 'self', but if there is...
946 if (blockInfo.Captures.count(self)) {
947 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
948 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
949 capture.getIndex(),
950 "block.captured-self");
951 LocalDeclMap[self] = selfAddr;
952 }
953 }
954
955 // Also force all the constant captures.
956 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
957 ce = blockDecl->capture_end(); ci != ce; ++ci) {
958 const VarDecl *variable = ci->getVariable();
959 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
960 if (!capture.isConstant()) continue;
961
962 unsigned align = getContext().getDeclAlign(variable).getQuantity();
963
964 llvm::AllocaInst *alloca =
965 CreateMemTemp(variable->getType(), "block.captured-const");
966 alloca->setAlignment(align);
967
968 Builder.CreateStore(capture.getConstant(), alloca, align);
969
970 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000971 }
972
Mike Stumpb289b3f2009-10-01 22:29:41 +0000973 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
974 llvm::BasicBlock *entry = Builder.GetInsertBlock();
975 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
976 --entry_ptr;
977
John McCall6b5a61b2011-02-07 10:33:21 +0000978 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000979
Mike Stumpde8c5c72009-10-01 00:27:30 +0000980 // Remember where we were...
981 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000982
Mike Stumpde8c5c72009-10-01 00:27:30 +0000983 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000984 ++entry_ptr;
985 Builder.SetInsertPoint(entry, entry_ptr);
986
John McCall6b5a61b2011-02-07 10:33:21 +0000987 // Emit debug information for all the BlockDeclRefDecls.
988 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +0000989 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000990 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
991 ce = blockDecl->capture_end(); ci != ce; ++ci) {
992 const VarDecl *variable = ci->getVariable();
993 DI->setLocation(variable->getLocation());
994
995 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
996 if (capture.isConstant()) {
997 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
998 Builder);
999 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001000 }
John McCall6b5a61b2011-02-07 10:33:21 +00001001
1002 DI->EmitDeclareOfBlockDeclRefVariable(variable, blockAddrAlloca,
1003 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001004 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001005 }
John McCall6b5a61b2011-02-07 10:33:21 +00001006
Mike Stumpde8c5c72009-10-01 00:27:30 +00001007 // And resume where we left off.
1008 if (resume == 0)
1009 Builder.ClearInsertionPoint();
1010 else
1011 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001012
John McCall6b5a61b2011-02-07 10:33:21 +00001013 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001014
John McCall6b5a61b2011-02-07 10:33:21 +00001015 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001016}
Mike Stumpa99038c2009-02-28 09:07:16 +00001017
John McCall6b5a61b2011-02-07 10:33:21 +00001018/*
1019 notes.push_back(HelperInfo());
1020 HelperInfo &note = notes.back();
1021 note.index = capture.getIndex();
1022 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1023 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001024
John McCall6b5a61b2011-02-07 10:33:21 +00001025 if (ci->isByRef()) {
1026 note.flag = BLOCK_FIELD_IS_BYREF;
1027 if (type.isObjCGCWeak())
1028 note.flag |= BLOCK_FIELD_IS_WEAK;
1029 } else if (type->isBlockPointerType()) {
1030 note.flag = BLOCK_FIELD_IS_BLOCK;
1031 } else {
1032 note.flag = BLOCK_FIELD_IS_OBJECT;
1033 }
1034 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001035
Mike Stump00470a12009-03-05 08:32:30 +00001036
Mike Stumpa99038c2009-02-28 09:07:16 +00001037
Mike Stumpdab514f2009-03-04 03:23:46 +00001038
Mike Stumpa4f668f2009-03-06 01:33:24 +00001039
John McCall6b5a61b2011-02-07 10:33:21 +00001040llvm::Constant *
1041BlockFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1042 ASTContext &C = getContext();
1043
1044 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001045 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001046 ImplicitParamDecl *dstDecl =
1047 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1048 args.push_back(std::make_pair(dstDecl, dstDecl->getType()));
1049 ImplicitParamDecl *srcDecl =
1050 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1051 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Mike Stumpa4f668f2009-03-06 01:33:24 +00001053 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001054 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001055
John McCall6b5a61b2011-02-07 10:33:21 +00001056 // FIXME: it would be nice if these were mergeable with things with
1057 // identical semantics.
1058 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001059
1060 llvm::Function *Fn =
1061 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001062 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001063
1064 IdentifierInfo *II
1065 = &CGM.getContext().Idents.get("__copy_helper_block_");
1066
John McCall6b5a61b2011-02-07 10:33:21 +00001067 FunctionDecl *FD = FunctionDecl::Create(C,
1068 C.getTranslationUnitDecl(),
1069 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001070 SC_Static,
1071 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001072 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001073 true);
John McCall6b5a61b2011-02-07 10:33:21 +00001074 CGF.StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001075
John McCall6b5a61b2011-02-07 10:33:21 +00001076 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001077
John McCall6b5a61b2011-02-07 10:33:21 +00001078 llvm::Value *src = CGF.GetAddrOfLocalVar(srcDecl);
1079 src = CGF.Builder.CreateLoad(src);
1080 src = CGF.Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001081
John McCall6b5a61b2011-02-07 10:33:21 +00001082 llvm::Value *dst = CGF.GetAddrOfLocalVar(dstDecl);
1083 dst = CGF.Builder.CreateLoad(dst);
1084 dst = CGF.Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001085
John McCall6b5a61b2011-02-07 10:33:21 +00001086 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001087
John McCall6b5a61b2011-02-07 10:33:21 +00001088 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1089 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1090 const VarDecl *variable = ci->getVariable();
1091 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001092
John McCall6b5a61b2011-02-07 10:33:21 +00001093 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1094 if (capture.isConstant()) continue;
1095
1096 const Expr *copyExpr = ci->getCopyExpr();
1097 unsigned flags = 0;
1098
1099 if (copyExpr) {
1100 assert(!ci->isByRef());
1101 // don't bother computing flags
1102 } else if (ci->isByRef()) {
1103 flags = BLOCK_FIELD_IS_BYREF;
1104 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1105 } else if (type->isBlockPointerType()) {
1106 flags = BLOCK_FIELD_IS_BLOCK;
1107 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1108 flags = BLOCK_FIELD_IS_OBJECT;
1109 }
1110
1111 if (!copyExpr && !flags) continue;
1112
1113 unsigned index = capture.getIndex();
1114 llvm::Value *srcField = CGF.Builder.CreateStructGEP(src, index);
1115 llvm::Value *dstField = CGF.Builder.CreateStructGEP(dst, index);
1116
1117 // If there's an explicit copy expression, we do that.
1118 if (copyExpr) {
1119 CGF.EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1120 } else {
1121 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1122 srcValue = Builder.CreateBitCast(srcValue, PtrToInt8Ty);
1123 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, PtrToInt8Ty);
1124 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1125 llvm::ConstantInt::get(CGF.Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001126 }
1127 }
1128
Mike Stumpa4f668f2009-03-06 01:33:24 +00001129 CGF.FinishFunction();
1130
Owen Anderson3c4972d2009-07-29 18:54:39 +00001131 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +00001132}
1133
John McCall6b5a61b2011-02-07 10:33:21 +00001134llvm::Constant *
1135BlockFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1136 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001137
John McCall6b5a61b2011-02-07 10:33:21 +00001138 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001139 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001140 ImplicitParamDecl *srcDecl =
1141 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1142 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Mike Stumpa4f668f2009-03-06 01:33:24 +00001144 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001145 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001146
Mike Stump3899a7f2009-06-05 23:26:36 +00001147 // FIXME: We'd like to put these into a mergable by content, with
1148 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001149 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001150
1151 llvm::Function *Fn =
1152 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001153 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001154
1155 IdentifierInfo *II
1156 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1157
John McCall6b5a61b2011-02-07 10:33:21 +00001158 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1159 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001160 SC_Static,
1161 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001162 false, true);
John McCall6b5a61b2011-02-07 10:33:21 +00001163 CGF.StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001164
John McCall6b5a61b2011-02-07 10:33:21 +00001165 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001166
John McCall6b5a61b2011-02-07 10:33:21 +00001167 llvm::Value *src = CGF.GetAddrOfLocalVar(srcDecl);
1168 src = CGF.Builder.CreateLoad(src);
1169 src = CGF.Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001170
John McCall6b5a61b2011-02-07 10:33:21 +00001171 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1172
1173 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1174
1175 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1176 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1177 const VarDecl *variable = ci->getVariable();
1178 QualType type = variable->getType();
1179
1180 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1181 if (capture.isConstant()) continue;
1182
1183 unsigned flags = 0;
1184 const CXXDestructorDecl *dtor = 0;
1185
1186 if (ci->isByRef()) {
1187 flags = BLOCK_FIELD_IS_BYREF;
1188 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1189 } else if (type->isBlockPointerType()) {
1190 flags = BLOCK_FIELD_IS_BLOCK;
1191 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1192 flags = BLOCK_FIELD_IS_OBJECT;
1193 } else if (C.getLangOptions().CPlusPlus) {
1194 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1195 if (!record->hasTrivialDestructor())
1196 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001197 }
John McCall6b5a61b2011-02-07 10:33:21 +00001198
1199 if (!dtor && !flags) continue;
1200
1201 unsigned index = capture.getIndex();
1202 llvm::Value *srcField = CGF.Builder.CreateStructGEP(src, index);
1203
1204 // If there's an explicit copy expression, we do that.
1205 if (dtor) {
1206 CGF.PushDestructorCleanup(dtor, srcField);
1207
1208 // Otherwise we call _Block_object_dispose. It wouldn't be too
1209 // hard to just emit this as a cleanup if we wanted to make sure
1210 // that things were done in reverse.
1211 } else {
1212 llvm::Value *value = Builder.CreateLoad(srcField);
1213 value = Builder.CreateBitCast(value, PtrToInt8Ty);
1214 BuildBlockRelease(value, flags);
1215 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001216 }
1217
John McCall6b5a61b2011-02-07 10:33:21 +00001218 cleanups.ForceCleanup();
1219
Mike Stumpa4f668f2009-03-06 01:33:24 +00001220 CGF.FinishFunction();
1221
Owen Anderson3c4972d2009-07-29 18:54:39 +00001222 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001223}
1224
Mike Stumpee094222009-03-06 06:12:24 +00001225llvm::Constant *BlockFunction::
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001226GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag,
1227 const VarDecl *BD) {
Mike Stump45031c02009-03-06 02:29:21 +00001228 QualType R = getContext().VoidTy;
1229
1230 FunctionArgList Args;
1231 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001232 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001233 ImplicitParamDecl::Create(getContext(), 0,
1234 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001235 getContext().getPointerType(getContext().VoidTy));
1236 Args.push_back(std::make_pair(Dst, Dst->getType()));
1237
1238 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001239 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001240 ImplicitParamDecl::Create(getContext(), 0,
1241 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001242 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001243 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Mike Stump45031c02009-03-06 02:29:21 +00001245 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001246 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001247
Mike Stump45031c02009-03-06 02:29:21 +00001248 CodeGenTypes &Types = CGM.getTypes();
1249 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1250
Mike Stump3899a7f2009-06-05 23:26:36 +00001251 // FIXME: We'd like to put these into a mergable by content, with
1252 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001253 llvm::Function *Fn =
1254 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001255 "__Block_byref_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001256
1257 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001258 = &CGM.getContext().Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001259
1260 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1261 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001262 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001263 SC_Static,
1264 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001265 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001266 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001267
1268 // dst->x
1269 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001270 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001271 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001272 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001273 llvm::Value *DstObj = V;
Mike Stumpee094222009-03-06 06:12:24 +00001274
1275 // src->x
1276 V = CGF.GetAddrOfLocalVar(Src);
1277 V = Builder.CreateLoad(V);
1278 V = Builder.CreateBitCast(V, T);
1279 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001280
1281 if (flag & BLOCK_HAS_CXX_OBJ) {
1282 assert (BD && "VarDecl is null - GeneratebyrefCopyHelperFunction");
1283 llvm::Value *SrcObj = V;
1284 CGF.EmitSynthesizedCXXCopyCtor(DstObj, SrcObj,
1285 getContext().getBlockVarCopyInits(BD));
1286 }
1287 else {
1288 DstObj = Builder.CreateBitCast(DstObj, PtrToInt8Ty);
1289 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1290 llvm::Value *SrcObj = Builder.CreateLoad(V);
1291 flag |= BLOCK_BYREF_CALLER;
1292 llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
1293 llvm::Value *F = CGM.getBlockObjectAssign();
1294 Builder.CreateCall3(F, DstObj, SrcObj, N);
1295 }
1296
Mike Stump45031c02009-03-06 02:29:21 +00001297 CGF.FinishFunction();
1298
Owen Anderson3c4972d2009-07-29 18:54:39 +00001299 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001300}
1301
Mike Stump1851b682009-03-06 04:53:30 +00001302llvm::Constant *
1303BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001304 int flag,
1305 const VarDecl *BD) {
Mike Stump45031c02009-03-06 02:29:21 +00001306 QualType R = getContext().VoidTy;
1307
1308 FunctionArgList Args;
1309 // FIXME: This leaks
1310 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001311 ImplicitParamDecl::Create(getContext(), 0,
1312 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001313 getContext().getPointerType(getContext().VoidTy));
1314
1315 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Mike Stump45031c02009-03-06 02:29:21 +00001317 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001318 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001319
Mike Stump45031c02009-03-06 02:29:21 +00001320 CodeGenTypes &Types = CGM.getTypes();
1321 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1322
Mike Stump3899a7f2009-06-05 23:26:36 +00001323 // FIXME: We'd like to put these into a mergable by content, with
1324 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001325 llvm::Function *Fn =
1326 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001327 "__Block_byref_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001328 &CGM.getModule());
1329
1330 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001331 = &CGM.getContext().Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001332
1333 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1334 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001335 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001336 SC_Static,
1337 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001338 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001339 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001340
1341 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001342 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001343 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001344 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001345 if (flag & BLOCK_HAS_CXX_OBJ) {
1346 EHScopeStack::stable_iterator CleanupDepth = CGF.EHStack.stable_begin();
1347 assert (BD && "VarDecl is null - GeneratebyrefDestroyHelperFunction");
1348 QualType ClassTy = BD->getType();
1349 CGF.PushDestructorCleanup(ClassTy, V);
1350 CGF.PopCleanupBlocks(CleanupDepth);
1351 }
1352 else {
1353 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1354 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001355
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001356 flag |= BLOCK_BYREF_CALLER;
1357 BuildBlockRelease(V, flag);
1358 }
Mike Stump45031c02009-03-06 02:29:21 +00001359 CGF.FinishFunction();
1360
Owen Anderson3c4972d2009-07-29 18:54:39 +00001361 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001362}
1363
Mike Stumpee094222009-03-06 06:12:24 +00001364llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
John McCall6b5a61b2011-02-07 10:33:21 +00001365 uint32_t flags,
1366 unsigned align,
1367 const VarDecl *var) {
Chris Lattner10976d92009-12-05 08:21:30 +00001368 // All alignments below that of pointer alignment collapse down to just
Mike Stump3899a7f2009-06-05 23:26:36 +00001369 // pointer alignment, as we always have at least that much alignment to begin
1370 // with.
John McCall6b5a61b2011-02-07 10:33:21 +00001371 align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001372
Mike Stump3899a7f2009-06-05 23:26:36 +00001373 // As an optimization, we only generate a single function of each kind we
1374 // might need. We need a different one for each alignment and for each
1375 // setting of flags. We mix Align and flag to get the kind.
John McCall6b5a61b2011-02-07 10:33:21 +00001376 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags;
Chris Lattner10976d92009-12-05 08:21:30 +00001377 llvm::Constant *&Entry = CGM.AssignCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001378 if (Entry)
1379 return Entry;
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001380 return Entry =
John McCall6b5a61b2011-02-07 10:33:21 +00001381 CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flags, var);
Mike Stump45031c02009-03-06 02:29:21 +00001382}
1383
Mike Stump1851b682009-03-06 04:53:30 +00001384llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
John McCall6b5a61b2011-02-07 10:33:21 +00001385 uint32_t flags,
1386 unsigned align,
1387 const VarDecl *var) {
Mike Stump3899a7f2009-06-05 23:26:36 +00001388 // All alignments below that of pointer alignment collpase down to just
1389 // pointer alignment, as we always have at least that much alignment to begin
1390 // with.
John McCall6b5a61b2011-02-07 10:33:21 +00001391 align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001392
Mike Stump3899a7f2009-06-05 23:26:36 +00001393 // As an optimization, we only generate a single function of each kind we
1394 // might need. We need a different one for each alignment and for each
1395 // setting of flags. We mix Align and flag to get the kind.
John McCall6b5a61b2011-02-07 10:33:21 +00001396 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags;
Chris Lattner10976d92009-12-05 08:21:30 +00001397 llvm::Constant *&Entry = CGM.DestroyCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001398 if (Entry)
1399 return Entry;
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001400 return Entry =
John McCall6b5a61b2011-02-07 10:33:21 +00001401 CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flags, var);
Mike Stump45031c02009-03-06 02:29:21 +00001402}
1403
John McCall6b5a61b2011-02-07 10:33:21 +00001404void BlockFunction::BuildBlockRelease(llvm::Value *V, uint32_t flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001405 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001406 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001407 V = Builder.CreateBitCast(V, PtrToInt8Ty);
John McCall6b5a61b2011-02-07 10:33:21 +00001408 N = llvm::ConstantInt::get(CGF.Int32Ty, flags);
Mike Stump797b6322009-03-05 01:23:13 +00001409 Builder.CreateCall2(F, V, N);
1410}
Mike Stump00470a12009-03-05 08:32:30 +00001411
1412ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001413
1414BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1415 CGBuilderTy &B)
John McCall6b5a61b2011-02-07 10:33:21 +00001416 : CGM(cgm), VMContext(cgm.getLLVMContext()), CGF(cgf),
1417 BlockInfo(0), BlockPointer(0), Builder(B) {
Owen Anderson0032b272009-08-13 21:57:51 +00001418 PtrToInt8Ty = llvm::PointerType::getUnqual(
1419 llvm::Type::getInt8Ty(VMContext));
Mike Stump08920992009-03-07 02:35:30 +00001420}