blob: 8d9c032f5f8bbba44cd610f5a3e8e122edbd5942 [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stumpb1a6e682009-09-30 02:43:10 +000014#include "CGDebugInfo.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000015#include "CodeGenFunction.h"
Fariborz Jahanian263c4de2010-02-10 23:34:57 +000016#include "CGObjCRuntime.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "CodeGenModule.h"
John McCalld16c2cf2011-02-08 08:22:06 +000018#include "CGBlocks.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000020#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000022#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000023#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000024
Anders Carlssonacfde802009-02-12 00:39:25 +000025using namespace clang;
26using namespace CodeGen;
27
John McCall6b5a61b2011-02-07 10:33:21 +000028CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N)
29 : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
John McCall64cd2322011-03-09 08:39:33 +000030 HasCXXObject(false), UsesStret(false), StructureType(0), Block(blockExpr) {
John McCallee504292010-05-21 04:11:14 +000031
32 // Skip asm prefix, if any.
33 if (Name && Name[0] == '\01')
34 ++Name;
35}
36
John McCallf0c11f72011-03-31 08:03:29 +000037// Anchor the vtable to this translation unit.
38CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
39
John McCall6b5a61b2011-02-07 10:33:21 +000040/// Build the given block as a global block.
41static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
42 const CGBlockInfo &blockInfo,
43 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000044
John McCall6b5a61b2011-02-07 10:33:21 +000045/// Build the helper function to copy a block.
46static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
47 const CGBlockInfo &blockInfo) {
48 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
49}
50
51/// Build the helper function to dipose of a block.
52static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo) {
54 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
55}
56
57/// Build the block descriptor constant for a block.
58static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
59 const CGBlockInfo &blockInfo) {
60 ASTContext &C = CGM.getContext();
61
62 const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
63 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
64
65 llvm::SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000066
67 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000068 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000069
70 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000071 // FIXME: What is the right way to say this doesn't fit? We should give
72 // a user diagnostic in that case. Better fix would be to change the
73 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000074 elements.push_back(llvm::ConstantInt::get(ulong,
75 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000076
John McCall6b5a61b2011-02-07 10:33:21 +000077 // Optional copy/dispose helpers.
78 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000079 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000080 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000081
82 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000083 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000084 }
85
John McCall6b5a61b2011-02-07 10:33:21 +000086 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
87 std::string typeAtEncoding =
88 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
89 elements.push_back(llvm::ConstantExpr::getBitCast(
90 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000091
John McCall6b5a61b2011-02-07 10:33:21 +000092 // GC layout.
93 if (C.getLangOptions().ObjC1)
94 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
95 else
96 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000097
John McCall6b5a61b2011-02-07 10:33:21 +000098 llvm::Constant *init =
99 llvm::ConstantStruct::get(CGM.getLLVMContext(), elements.data(),
100 elements.size(), false);
Mike Stumpe5fee252009-02-13 16:19:19 +0000101
John McCall6b5a61b2011-02-07 10:33:21 +0000102 llvm::GlobalVariable *global =
103 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
104 llvm::GlobalValue::InternalLinkage,
105 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000106
John McCall6b5a61b2011-02-07 10:33:21 +0000107 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000108}
109
John McCall6b5a61b2011-02-07 10:33:21 +0000110/*
111 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000112
John McCall6b5a61b2011-02-07 10:33:21 +0000113 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
114 struct Block_literal {
115 /// Initialized to one of:
116 /// extern void *_NSConcreteStackBlock[];
117 /// extern void *_NSConcreteGlobalBlock[];
118 ///
119 /// In theory, we could start one off malloc'ed by setting
120 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
121 /// this isa:
122 /// extern void *_NSConcreteMallocBlock[];
123 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000124
John McCall6b5a61b2011-02-07 10:33:21 +0000125 /// These are the flags (with corresponding bit number) that the
126 /// compiler is actually supposed to know about.
127 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
128 /// descriptor provides copy and dispose helper functions
129 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
130 /// object with a nontrivial destructor or copy constructor
131 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
132 /// as global memory
133 /// 29. BLOCK_USE_STRET - indicates that the block function
134 /// uses stret, which objc_msgSend needs to know about
135 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
136 /// @encoded signature string
137 /// And we're not supposed to manipulate these:
138 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
139 /// to malloc'ed memory
140 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
141 /// to GC-allocated memory
142 /// Additionally, the bottom 16 bits are a reference count which
143 /// should be zero on the stack.
144 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000145
John McCall6b5a61b2011-02-07 10:33:21 +0000146 /// Reserved; should be zero-initialized.
147 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000148
John McCall6b5a61b2011-02-07 10:33:21 +0000149 /// Function pointer generated from block literal.
150 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000151
John McCall6b5a61b2011-02-07 10:33:21 +0000152 /// Block description metadata generated from block literal.
153 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000154
John McCall6b5a61b2011-02-07 10:33:21 +0000155 /// Captured values follow.
156 _CapturesTypes captures...;
157 };
158 */
David Chisnall5e530af2009-11-17 19:33:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160/// The number of fields in a block header.
161const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163namespace {
164 /// A chunk of data that we actually have to capture in the block.
165 struct BlockLayoutChunk {
166 CharUnits Alignment;
167 CharUnits Size;
168 const BlockDecl::Capture *Capture; // null for 'this'
169 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000170
John McCall6b5a61b2011-02-07 10:33:21 +0000171 BlockLayoutChunk(CharUnits align, CharUnits size,
172 const BlockDecl::Capture *capture,
173 const llvm::Type *type)
174 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000175
John McCall6b5a61b2011-02-07 10:33:21 +0000176 /// Tell the block info that this chunk has the given field index.
177 void setIndex(CGBlockInfo &info, unsigned index) {
178 if (!Capture)
179 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000180 else
John McCall6b5a61b2011-02-07 10:33:21 +0000181 info.Captures[Capture->getVariable()]
182 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000183 }
John McCall6b5a61b2011-02-07 10:33:21 +0000184 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000185
John McCall6b5a61b2011-02-07 10:33:21 +0000186 /// Order by descending alignment.
187 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
188 return left.Alignment > right.Alignment;
189 }
190}
191
John McCall461c9c12011-02-08 03:07:00 +0000192/// Determines if the given record type has a mutable field.
193static bool hasMutableField(const CXXRecordDecl *record) {
194 for (CXXRecordDecl::field_iterator
195 i = record->field_begin(), e = record->field_end(); i != e; ++i)
196 if ((*i)->isMutable())
197 return true;
198
199 for (CXXRecordDecl::base_class_const_iterator
200 i = record->bases_begin(), e = record->bases_end(); i != e; ++i) {
201 const RecordType *record = i->getType()->castAs<RecordType>();
202 if (hasMutableField(cast<CXXRecordDecl>(record->getDecl())))
203 return true;
204 }
205
206 return false;
207}
208
209/// Determines if the given type is safe for constant capture in C++.
210static bool isSafeForCXXConstantCapture(QualType type) {
211 const RecordType *recordType =
212 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
213
214 // Only records can be unsafe.
215 if (!recordType) return true;
216
217 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
218
219 // Maintain semantics for classes with non-trivial dtors or copy ctors.
220 if (!record->hasTrivialDestructor()) return false;
221 if (!record->hasTrivialCopyConstructor()) return false;
222
223 // Otherwise, we just have to make sure there aren't any mutable
224 // fields that might have changed since initialization.
225 return !hasMutableField(record);
226}
227
John McCall6b5a61b2011-02-07 10:33:21 +0000228/// It is illegal to modify a const object after initialization.
229/// Therefore, if a const object has a constant initializer, we don't
230/// actually need to keep storage for it in the block; we'll just
231/// rematerialize it at the start of the block function. This is
232/// acceptable because we make no promises about address stability of
233/// captured variables.
234static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
235 const VarDecl *var) {
236 QualType type = var->getType();
237
238 // We can only do this if the variable is const.
239 if (!type.isConstQualified()) return 0;
240
John McCall461c9c12011-02-08 03:07:00 +0000241 // Furthermore, in C++ we have to worry about mutable fields:
242 // C++ [dcl.type.cv]p4:
243 // Except that any class member declared mutable can be
244 // modified, any attempt to modify a const object during its
245 // lifetime results in undefined behavior.
246 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000247 return 0;
248
249 // If the variable doesn't have any initializer (shouldn't this be
250 // invalid?), it's not clear what we should do. Maybe capture as
251 // zero?
252 const Expr *init = var->getInit();
253 if (!init) return 0;
254
255 return CGM.EmitConstantExpr(init, var->getType());
256}
257
258/// Get the low bit of a nonzero character count. This is the
259/// alignment of the nth byte if the 0th byte is universally aligned.
260static CharUnits getLowBit(CharUnits v) {
261 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
262}
263
264static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
265 std::vector<const llvm::Type*> &elementTypes) {
266 ASTContext &C = CGM.getContext();
267
268 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
269 CharUnits ptrSize, ptrAlign, intSize, intAlign;
270 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
271 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
272
273 // Are there crazy embedded platforms where this isn't true?
274 assert(intSize <= ptrSize && "layout assumptions horribly violated");
275
276 CharUnits headerSize = ptrSize;
277 if (2 * intSize < ptrAlign) headerSize += ptrSize;
278 else headerSize += 2 * intSize;
279 headerSize += 2 * ptrSize;
280
281 info.BlockAlign = ptrAlign;
282 info.BlockSize = headerSize;
283
284 assert(elementTypes.empty());
285 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
286 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
287 elementTypes.push_back(i8p);
288 elementTypes.push_back(intTy);
289 elementTypes.push_back(intTy);
290 elementTypes.push_back(i8p);
291 elementTypes.push_back(CGM.getBlockDescriptorType());
292
293 assert(elementTypes.size() == BlockHeaderSize);
294}
295
296/// Compute the layout of the given block. Attempts to lay the block
297/// out with minimal space requirements.
298static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
299 ASTContext &C = CGM.getContext();
300 const BlockDecl *block = info.getBlockDecl();
301
302 std::vector<const llvm::Type*> elementTypes;
303 initializeForBlockHeader(CGM, info, elementTypes);
304
305 if (!block->hasCaptures()) {
306 info.StructureType =
307 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
308 info.CanBeGlobal = true;
309 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000310 }
Mike Stump00470a12009-03-05 08:32:30 +0000311
John McCall6b5a61b2011-02-07 10:33:21 +0000312 // Collect the layout chunks.
313 llvm::SmallVector<BlockLayoutChunk, 16> layout;
314 layout.reserve(block->capturesCXXThis() +
315 (block->capture_end() - block->capture_begin()));
316
317 CharUnits maxFieldAlign;
318
319 // First, 'this'.
320 if (block->capturesCXXThis()) {
321 const DeclContext *DC = block->getDeclContext();
322 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
323 ;
324 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
325
326 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
327 std::pair<CharUnits,CharUnits> tinfo
328 = CGM.getContext().getTypeInfoInChars(thisType);
329 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
330
331 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
332 }
333
334 // Next, all the block captures.
335 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
336 ce = block->capture_end(); ci != ce; ++ci) {
337 const VarDecl *variable = ci->getVariable();
338
339 if (ci->isByRef()) {
340 // We have to copy/dispose of the __block reference.
341 info.NeedsCopyDispose = true;
342
John McCall6b5a61b2011-02-07 10:33:21 +0000343 // Just use void* instead of a pointer to the byref type.
344 QualType byRefPtrTy = C.VoidPtrTy;
345
346 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
347 std::pair<CharUnits,CharUnits> tinfo
348 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
349 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
350
351 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
352 &*ci, llvmType));
353 continue;
354 }
355
356 // Otherwise, build a layout chunk with the size and alignment of
357 // the declaration.
358 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
359 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
360 continue;
361 }
362
363 // Block pointers require copy/dispose.
364 if (variable->getType()->isBlockPointerType()) {
365 info.NeedsCopyDispose = true;
366
367 // So do Objective-C pointers.
368 } else if (variable->getType()->isObjCObjectPointerType() ||
369 C.isObjCNSObjectType(variable->getType())) {
370 info.NeedsCopyDispose = true;
371
372 // So do types that require non-trivial copy construction.
373 } else if (ci->hasCopyExpr()) {
374 info.NeedsCopyDispose = true;
375 info.HasCXXObject = true;
376
377 // And so do types with destructors.
378 } else if (CGM.getLangOptions().CPlusPlus) {
379 if (const CXXRecordDecl *record =
380 variable->getType()->getAsCXXRecordDecl()) {
381 if (!record->hasTrivialDestructor()) {
382 info.HasCXXObject = true;
383 info.NeedsCopyDispose = true;
384 }
385 }
386 }
387
388 CharUnits size = C.getTypeSizeInChars(variable->getType());
389 CharUnits align = C.getDeclAlign(variable);
390 maxFieldAlign = std::max(maxFieldAlign, align);
391
392 const llvm::Type *llvmType =
393 CGM.getTypes().ConvertTypeForMem(variable->getType());
394
395 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
396 }
397
398 // If that was everything, we're done here.
399 if (layout.empty()) {
400 info.StructureType =
401 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
402 info.CanBeGlobal = true;
403 return;
404 }
405
406 // Sort the layout by alignment. We have to use a stable sort here
407 // to get reproducible results. There should probably be an
408 // llvm::array_pod_stable_sort.
409 std::stable_sort(layout.begin(), layout.end());
410
411 CharUnits &blockSize = info.BlockSize;
412 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
413
414 // Assuming that the first byte in the header is maximally aligned,
415 // get the alignment of the first byte following the header.
416 CharUnits endAlign = getLowBit(blockSize);
417
418 // If the end of the header isn't satisfactorily aligned for the
419 // maximum thing, look for things that are okay with the header-end
420 // alignment, and keep appending them until we get something that's
421 // aligned right. This algorithm is only guaranteed optimal if
422 // that condition is satisfied at some point; otherwise we can get
423 // things like:
424 // header // next byte has alignment 4
425 // something_with_size_5; // next byte has alignment 1
426 // something_with_alignment_8;
427 // which has 7 bytes of padding, as opposed to the naive solution
428 // which might have less (?).
429 if (endAlign < maxFieldAlign) {
430 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
431 li = layout.begin() + 1, le = layout.end();
432
433 // Look for something that the header end is already
434 // satisfactorily aligned for.
435 for (; li != le && endAlign < li->Alignment; ++li)
436 ;
437
438 // If we found something that's naturally aligned for the end of
439 // the header, keep adding things...
440 if (li != le) {
441 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
442 for (; li != le; ++li) {
443 assert(endAlign >= li->Alignment);
444
445 li->setIndex(info, elementTypes.size());
446 elementTypes.push_back(li->Type);
447 blockSize += li->Size;
448 endAlign = getLowBit(blockSize);
449
450 // ...until we get to the alignment of the maximum field.
451 if (endAlign >= maxFieldAlign)
452 break;
453 }
454
455 // Don't re-append everything we just appended.
456 layout.erase(first, li);
457 }
458 }
459
460 // At this point, we just have to add padding if the end align still
461 // isn't aligned right.
462 if (endAlign < maxFieldAlign) {
463 CharUnits padding = maxFieldAlign - endAlign;
464
John McCall5936e332011-02-15 09:22:45 +0000465 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
466 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000467 blockSize += padding;
468
469 endAlign = getLowBit(blockSize);
470 assert(endAlign >= maxFieldAlign);
471 }
472
473 // Slam everything else on now. This works because they have
474 // strictly decreasing alignment and we expect that size is always a
475 // multiple of alignment.
476 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
477 li = layout.begin(), le = layout.end(); li != le; ++li) {
478 assert(endAlign >= li->Alignment);
479 li->setIndex(info, elementTypes.size());
480 elementTypes.push_back(li->Type);
481 blockSize += li->Size;
482 endAlign = getLowBit(blockSize);
483 }
484
485 info.StructureType =
486 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
487}
488
489/// Emit a block literal expression in the current function.
490llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
491 std::string Name = CurFn->getName();
492 CGBlockInfo blockInfo(blockExpr, Name.c_str());
493
494 // Compute information about the layout, etc., of this block.
495 computeBlockInfo(CGM, blockInfo);
496
497 // Using that metadata, generate the actual block function.
498 llvm::Constant *blockFn
499 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
500 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000501 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000502
503 // If there is nothing to capture, we can emit this as a global block.
504 if (blockInfo.CanBeGlobal)
505 return buildGlobalBlock(CGM, blockInfo, blockFn);
506
507 // Otherwise, we have to emit this as a local block.
508
509 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000510 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000511
512 // Build the block descriptor.
513 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
514
515 const llvm::Type *intTy = ConvertType(getContext().IntTy);
516
517 llvm::AllocaInst *blockAddr =
518 CreateTempAlloca(blockInfo.StructureType, "block");
519 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
520
521 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000522 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000523 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
524 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000525 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000526
527 // Initialize the block literal.
528 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000529 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000530 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
531 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
532 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
533 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
534 "block.invoke"));
535 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
536 "block.descriptor"));
537
538 // Finally, capture all the values into the block.
539 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
540
541 // First, 'this'.
542 if (blockDecl->capturesCXXThis()) {
543 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
544 blockInfo.CXXThisIndex,
545 "block.captured-this.addr");
546 Builder.CreateStore(LoadCXXThis(), addr);
547 }
548
549 // Next, captured variables.
550 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
551 ce = blockDecl->capture_end(); ci != ce; ++ci) {
552 const VarDecl *variable = ci->getVariable();
553 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
554
555 // Ignore constant captures.
556 if (capture.isConstant()) continue;
557
558 QualType type = variable->getType();
559
560 // This will be a [[type]]*, except that a byref entry will just be
561 // an i8**.
562 llvm::Value *blockField =
563 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
564 "block.captured");
565
566 // Compute the address of the thing we're going to move into the
567 // block literal.
568 llvm::Value *src;
569 if (ci->isNested()) {
570 // We need to use the capture from the enclosing block.
571 const CGBlockInfo::Capture &enclosingCapture =
572 BlockInfo->getCapture(variable);
573
574 // This is a [[type]]*, except that a byref entry wil just be an i8**.
575 src = Builder.CreateStructGEP(LoadBlockStruct(),
576 enclosingCapture.getIndex(),
577 "block.capture.addr");
578 } else {
579 // This is a [[type]]*.
580 src = LocalDeclMap[variable];
581 }
582
583 // For byrefs, we just write the pointer to the byref struct into
584 // the block field. There's no need to chase the forwarding
585 // pointer at this point, since we're building something that will
586 // live a shorter life than the stack byref anyway.
587 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000588 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000589 if (ci->isNested())
590 src = Builder.CreateLoad(src, "byref.capture");
591 else
John McCall5936e332011-02-15 09:22:45 +0000592 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000593
John McCall5936e332011-02-15 09:22:45 +0000594 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000595 Builder.CreateStore(src, blockField);
596
597 // If we have a copy constructor, evaluate that into the block field.
598 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
599 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
600
601 // If it's a reference variable, copy the reference into the block field.
602 } else if (type->isReferenceType()) {
603 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
604
605 // Otherwise, fake up a POD copy into the block field.
606 } else {
John McCallbb699b02011-02-07 18:37:40 +0000607 // We use one of these or the other depending on whether the
608 // reference is nested.
609 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
610 SourceLocation());
611 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
612 VK_LValue, SourceLocation(), /*byref*/ false);
613
614 Expr *declRef =
615 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
616
John McCall6b5a61b2011-02-07 10:33:21 +0000617 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000618 declRef, VK_RValue);
John McCalldf045202011-03-08 09:38:48 +0000619 EmitExprAsInit(&l2r, variable, blockField,
620 getContext().getDeclAlign(variable),
621 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000622 }
623
624 // Push a destructor if necessary. The semantics for when this
625 // actually gets run are really obscure.
626 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus)
627 PushDestructorCleanup(type, blockField);
628 }
629
630 // Cast to the converted block-pointer type, which happens (somewhat
631 // unfortunately) to be a pointer to function type.
632 llvm::Value *result =
633 Builder.CreateBitCast(blockAddr,
634 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000635
John McCall6b5a61b2011-02-07 10:33:21 +0000636 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000637}
638
639
John McCalld16c2cf2011-02-08 08:22:06 +0000640const llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000641 if (BlockDescriptorType)
642 return BlockDescriptorType;
643
Mike Stumpa5448542009-02-13 15:32:32 +0000644 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000645 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000646
Mike Stumpab695142009-02-13 15:16:56 +0000647 // struct __block_descriptor {
648 // unsigned long reserved;
649 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000650 //
651 // // later, the following will be added
652 //
653 // struct {
654 // void (*copyHelper)();
655 // void (*copyHelper)();
656 // } helpers; // !!! optional
657 //
658 // const char *signature; // the block signature
659 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000660 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000661 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
662 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000663 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000664 NULL);
665
666 getModule().addTypeName("struct.__block_descriptor",
667 BlockDescriptorType);
668
John McCall6b5a61b2011-02-07 10:33:21 +0000669 // Now form a pointer to that.
670 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000671 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000672}
673
John McCalld16c2cf2011-02-08 08:22:06 +0000674const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000675 if (GenericBlockLiteralType)
676 return GenericBlockLiteralType;
677
John McCall6b5a61b2011-02-07 10:33:21 +0000678 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000679
Mike Stump9b8a7972009-02-13 15:25:34 +0000680 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000681 // void *__isa;
682 // int __flags;
683 // int __reserved;
684 // void (*__invoke)(void *);
685 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000686 // };
John McCall5936e332011-02-15 09:22:45 +0000687 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(),
688 VoidPtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000689 IntTy,
690 IntTy,
John McCall5936e332011-02-15 09:22:45 +0000691 VoidPtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000692 BlockDescPtrTy,
693 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000694
Mike Stump9b8a7972009-02-13 15:25:34 +0000695 getModule().addTypeName("struct.__block_literal_generic",
696 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000697
Mike Stump9b8a7972009-02-13 15:25:34 +0000698 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000699}
700
Mike Stumpbd65cac2009-02-19 01:01:04 +0000701
Anders Carlssona1736c02009-12-24 21:13:40 +0000702RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
703 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000704 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000705 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000706
Anders Carlssonacfde802009-02-12 00:39:25 +0000707 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
708
709 // Get a pointer to the generic block literal.
710 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000711 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000712
713 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000714 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000715 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
716
717 // Get the function pointer from the literal.
718 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000719
John McCall5936e332011-02-15 09:22:45 +0000720 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000721
Anders Carlssonacfde802009-02-12 00:39:25 +0000722 // Add the block literal.
723 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
724 CallArgList Args;
725 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000726
Anders Carlsson782f3972009-04-08 23:13:16 +0000727 QualType FnType = BPT->getPointeeType();
728
Anders Carlssonacfde802009-02-12 00:39:25 +0000729 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000730 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000731 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000732
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000733 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000734 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000735
John McCall64cd2322011-03-09 08:39:33 +0000736 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCall04a67a62010-02-05 21:31:56 +0000737 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000738
Mike Stump1eb44332009-09-09 15:08:12 +0000739 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000740 CGM.getTypes().getFunctionInfo(ResultType, Args,
741 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000743 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000744 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000745 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Owen Anderson96e0fc72009-07-29 22:16:19 +0000747 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000748 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Anders Carlssonacfde802009-02-12 00:39:25 +0000750 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000751 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000752}
Anders Carlssond5cab542009-02-12 17:55:02 +0000753
John McCall6b5a61b2011-02-07 10:33:21 +0000754llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
755 bool isByRef) {
756 assert(BlockInfo && "evaluating block ref without block information?");
757 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000758
John McCall6b5a61b2011-02-07 10:33:21 +0000759 // Handle constant captures.
760 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000761
John McCall6b5a61b2011-02-07 10:33:21 +0000762 llvm::Value *addr =
763 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
764 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000765
John McCall6b5a61b2011-02-07 10:33:21 +0000766 if (isByRef) {
767 // addr should be a void** right now. Load, then cast the result
768 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000769
John McCall6b5a61b2011-02-07 10:33:21 +0000770 addr = Builder.CreateLoad(addr);
771 const llvm::PointerType *byrefPointerType
772 = llvm::PointerType::get(BuildByRefType(variable), 0);
773 addr = Builder.CreateBitCast(addr, byrefPointerType,
774 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000775
John McCall6b5a61b2011-02-07 10:33:21 +0000776 // Follow the forwarding pointer.
777 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
778 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000779
John McCall6b5a61b2011-02-07 10:33:21 +0000780 // Cast back to byref* and GEP over to the actual object.
781 addr = Builder.CreateBitCast(addr, byrefPointerType);
782 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
783 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000784 }
785
John McCall6b5a61b2011-02-07 10:33:21 +0000786 if (variable->getType()->isReferenceType())
787 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000788
John McCall6b5a61b2011-02-07 10:33:21 +0000789 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000790}
791
Mike Stump67a64482009-02-14 22:16:35 +0000792llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000793CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000794 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000795 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000796
John McCall6b5a61b2011-02-07 10:33:21 +0000797 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000798 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000799
John McCall6b5a61b2011-02-07 10:33:21 +0000800 // Using that metadata, generate the actual block function.
801 llvm::Constant *blockFn;
802 {
803 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000804 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
805 blockInfo,
806 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000807 }
John McCall5936e332011-02-15 09:22:45 +0000808 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000809
John McCalld16c2cf2011-02-08 08:22:06 +0000810 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000811}
812
John McCall6b5a61b2011-02-07 10:33:21 +0000813static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
814 const CGBlockInfo &blockInfo,
815 llvm::Constant *blockFn) {
816 assert(blockInfo.CanBeGlobal);
817
818 // Generate the constants for the block literal initializer.
819 llvm::Constant *fields[BlockHeaderSize];
820
821 // isa
822 fields[0] = CGM.getNSConcreteGlobalBlock();
823
824 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000825 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
826 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
827
John McCall5936e332011-02-15 09:22:45 +0000828 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000829
830 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000831 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000832
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
Devang Patel6d1155b2011-03-07 21:53:18 +0000865 // Check if we should generate debug info for this block function.
866 if (CGM.getModuleDebugInfo())
867 DebugInfo = CGM.getModuleDebugInfo();
868
John McCall6b5a61b2011-02-07 10:33:21 +0000869 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Mike Stump7f28a9c2009-03-13 23:34:28 +0000871 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000872 // to be local to this function as well, in case they're directly
873 // referenced in a block.
874 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
875 const VarDecl *var = dyn_cast<VarDecl>(i->first);
876 if (var && !var->hasLocalStorage())
877 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000878 }
879
John McCall6b5a61b2011-02-07 10:33:21 +0000880 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000881
John McCall6b5a61b2011-02-07 10:33:21 +0000882 // Build the argument list.
883 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000884
John McCall6b5a61b2011-02-07 10:33:21 +0000885 // The first argument is the block pointer. Just take it as a void*
886 // and cast it later.
887 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000888 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000889
John McCall8178df32011-02-22 22:38:33 +0000890 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
891 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +0000892 args.push_back(&selfDecl);
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)
John McCalld26bc762011-03-09 04:27:21 +0000897 args.push_back(*i);
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());
John McCall64cd2322011-03-09 08:39:33 +0000905 if (CGM.ReturnTypeUsesSRet(fnInfo))
906 blockInfo.UsesStret = true;
907
John McCall6b5a61b2011-02-07 10:33:21 +0000908 const llvm::FunctionType *fnLLVMType =
909 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000910
John McCall6b5a61b2011-02-07 10:33:21 +0000911 MangleBuffer name;
912 CGM.getBlockMangledName(GD, name, blockDecl);
913 llvm::Function *fn =
914 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
915 name.getString(), &CGM.getModule());
916 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000917
John McCall6b5a61b2011-02-07 10:33:21 +0000918 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +0000919 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +0000920 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +0000921 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000922
John McCall8178df32011-02-22 22:38:33 +0000923 // Okay. Undo some of what StartFunction did.
924
925 // Pull the 'self' reference out of the local decl map.
926 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
927 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000928 BlockPointer = Builder.CreateBitCast(blockAddr,
929 blockInfo.StructureType->getPointerTo(),
930 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000931
John McCallea1471e2010-05-20 01:18:31 +0000932 // If we have a C++ 'this' reference, go ahead and force it into
933 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000934 if (blockDecl->capturesCXXThis()) {
935 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
936 blockInfo.CXXThisIndex,
937 "block.captured-this");
938 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000939 }
940
John McCall6b5a61b2011-02-07 10:33:21 +0000941 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
942 // appease it.
943 if (const ObjCMethodDecl *method
944 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
945 const VarDecl *self = method->getSelfDecl();
946
947 // There might not be a capture for 'self', but if there is...
948 if (blockInfo.Captures.count(self)) {
949 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
950 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
951 capture.getIndex(),
952 "block.captured-self");
953 LocalDeclMap[self] = selfAddr;
954 }
955 }
956
957 // Also force all the constant captures.
958 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
959 ce = blockDecl->capture_end(); ci != ce; ++ci) {
960 const VarDecl *variable = ci->getVariable();
961 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
962 if (!capture.isConstant()) continue;
963
964 unsigned align = getContext().getDeclAlign(variable).getQuantity();
965
966 llvm::AllocaInst *alloca =
967 CreateMemTemp(variable->getType(), "block.captured-const");
968 alloca->setAlignment(align);
969
970 Builder.CreateStore(capture.getConstant(), alloca, align);
971
972 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000973 }
974
Mike Stumpb289b3f2009-10-01 22:29:41 +0000975 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
976 llvm::BasicBlock *entry = Builder.GetInsertBlock();
977 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
978 --entry_ptr;
979
John McCall6b5a61b2011-02-07 10:33:21 +0000980 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000981
Mike Stumpde8c5c72009-10-01 00:27:30 +0000982 // Remember where we were...
983 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000984
Mike Stumpde8c5c72009-10-01 00:27:30 +0000985 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000986 ++entry_ptr;
987 Builder.SetInsertPoint(entry, entry_ptr);
988
John McCall6b5a61b2011-02-07 10:33:21 +0000989 // Emit debug information for all the BlockDeclRefDecls.
990 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +0000991 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000992 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
993 ce = blockDecl->capture_end(); ci != ce; ++ci) {
994 const VarDecl *variable = ci->getVariable();
995 DI->setLocation(variable->getLocation());
996
997 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
998 if (capture.isConstant()) {
999 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1000 Builder);
1001 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001002 }
John McCall6b5a61b2011-02-07 10:33:21 +00001003
John McCall8178df32011-02-22 22:38:33 +00001004 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001005 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001006 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001007 }
John McCall6b5a61b2011-02-07 10:33:21 +00001008
Mike Stumpde8c5c72009-10-01 00:27:30 +00001009 // And resume where we left off.
1010 if (resume == 0)
1011 Builder.ClearInsertionPoint();
1012 else
1013 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001014
John McCall6b5a61b2011-02-07 10:33:21 +00001015 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001016
John McCall6b5a61b2011-02-07 10:33:21 +00001017 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001018}
Mike Stumpa99038c2009-02-28 09:07:16 +00001019
John McCall6b5a61b2011-02-07 10:33:21 +00001020/*
1021 notes.push_back(HelperInfo());
1022 HelperInfo &note = notes.back();
1023 note.index = capture.getIndex();
1024 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1025 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001026
John McCall6b5a61b2011-02-07 10:33:21 +00001027 if (ci->isByRef()) {
1028 note.flag = BLOCK_FIELD_IS_BYREF;
1029 if (type.isObjCGCWeak())
1030 note.flag |= BLOCK_FIELD_IS_WEAK;
1031 } else if (type->isBlockPointerType()) {
1032 note.flag = BLOCK_FIELD_IS_BLOCK;
1033 } else {
1034 note.flag = BLOCK_FIELD_IS_OBJECT;
1035 }
1036 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001037
Mike Stump00470a12009-03-05 08:32:30 +00001038
Mike Stumpa99038c2009-02-28 09:07:16 +00001039
Mike Stumpdab514f2009-03-04 03:23:46 +00001040
Mike Stumpa4f668f2009-03-06 01:33:24 +00001041
John McCall6b5a61b2011-02-07 10:33:21 +00001042llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001043CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001044 ASTContext &C = getContext();
1045
1046 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001047 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1048 args.push_back(&dstDecl);
1049 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1050 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Mike Stumpa4f668f2009-03-06 01:33:24 +00001052 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001053 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001054
John McCall6b5a61b2011-02-07 10:33:21 +00001055 // FIXME: it would be nice if these were mergeable with things with
1056 // identical semantics.
1057 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001058
1059 llvm::Function *Fn =
1060 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001061 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001062
1063 IdentifierInfo *II
1064 = &CGM.getContext().Idents.get("__copy_helper_block_");
1065
John McCall6b5a61b2011-02-07 10:33:21 +00001066 FunctionDecl *FD = FunctionDecl::Create(C,
1067 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001068 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001069 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 McCalld26bc762011-03-09 04:27:21 +00001074 StartFunction(FD, C.VoidTy, Fn, FI, 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 McCalld26bc762011-03-09 04:27:21 +00001078 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001079 src = Builder.CreateLoad(src);
1080 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001081
John McCalld26bc762011-03-09 04:27:21 +00001082 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001083 dst = Builder.CreateLoad(dst);
1084 dst = 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();
John McCalld16c2cf2011-02-08 08:22:06 +00001114 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1115 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001116
1117 // If there's an explicit copy expression, we do that.
1118 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001119 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall6b5a61b2011-02-07 10:33:21 +00001120 } else {
1121 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001122 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1123 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001124 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCalld16c2cf2011-02-08 08:22:06 +00001125 llvm::ConstantInt::get(Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001126 }
1127 }
1128
John McCalld16c2cf2011-02-08 08:22:06 +00001129 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001130
John McCall5936e332011-02-15 09:22:45 +00001131 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001132}
1133
John McCall6b5a61b2011-02-07 10:33:21 +00001134llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001135CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001136 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001137
John McCall6b5a61b2011-02-07 10:33:21 +00001138 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001139 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1140 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Mike Stumpa4f668f2009-03-06 01:33:24 +00001142 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001143 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001144
Mike Stump3899a7f2009-06-05 23:26:36 +00001145 // FIXME: We'd like to put these into a mergable by content, with
1146 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001147 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001148
1149 llvm::Function *Fn =
1150 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001151 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001152
1153 IdentifierInfo *II
1154 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1155
John McCall6b5a61b2011-02-07 10:33:21 +00001156 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001157 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001158 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001159 SC_Static,
1160 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001161 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001162 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001163
John McCall6b5a61b2011-02-07 10:33:21 +00001164 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001165
John McCalld26bc762011-03-09 04:27:21 +00001166 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001167 src = Builder.CreateLoad(src);
1168 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001169
John McCall6b5a61b2011-02-07 10:33:21 +00001170 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1171
John McCalld16c2cf2011-02-08 08:22:06 +00001172 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001173
1174 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1175 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1176 const VarDecl *variable = ci->getVariable();
1177 QualType type = variable->getType();
1178
1179 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1180 if (capture.isConstant()) continue;
1181
John McCalld16c2cf2011-02-08 08:22:06 +00001182 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001183 const CXXDestructorDecl *dtor = 0;
1184
1185 if (ci->isByRef()) {
1186 flags = BLOCK_FIELD_IS_BYREF;
1187 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1188 } else if (type->isBlockPointerType()) {
1189 flags = BLOCK_FIELD_IS_BLOCK;
1190 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1191 flags = BLOCK_FIELD_IS_OBJECT;
1192 } else if (C.getLangOptions().CPlusPlus) {
1193 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1194 if (!record->hasTrivialDestructor())
1195 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001196 }
John McCall6b5a61b2011-02-07 10:33:21 +00001197
John McCalld16c2cf2011-02-08 08:22:06 +00001198 if (!dtor && flags.empty()) continue;
John McCall6b5a61b2011-02-07 10:33:21 +00001199
1200 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001201 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001202
1203 // If there's an explicit copy expression, we do that.
1204 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001205 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001206
1207 // Otherwise we call _Block_object_dispose. It wouldn't be too
1208 // hard to just emit this as a cleanup if we wanted to make sure
1209 // that things were done in reverse.
1210 } else {
1211 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001212 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001213 BuildBlockRelease(value, flags);
1214 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001215 }
1216
John McCall6b5a61b2011-02-07 10:33:21 +00001217 cleanups.ForceCleanup();
1218
John McCalld16c2cf2011-02-08 08:22:06 +00001219 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001220
John McCall5936e332011-02-15 09:22:45 +00001221 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001222}
1223
John McCallf0c11f72011-03-31 08:03:29 +00001224namespace {
1225
1226/// Emits the copy/dispose helper functions for a __block object of id type.
1227class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1228 BlockFieldFlags Flags;
1229
1230public:
1231 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1232 : ByrefHelpers(alignment), Flags(flags) {}
1233
John McCall36170192011-03-31 09:19:20 +00001234 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1235 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001236 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1237
1238 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1239 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1240
1241 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1242
1243 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1244 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1245 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1246 }
1247
1248 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1249 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1250 llvm::Value *value = CGF.Builder.CreateLoad(field);
1251
1252 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1253 }
1254
1255 void profileImpl(llvm::FoldingSetNodeID &id) const {
1256 id.AddInteger(Flags.getBitMask());
1257 }
1258};
1259
1260/// Emits the copy/dispose helpers for a __block variable with a
1261/// nontrivial copy constructor or destructor.
1262class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1263 QualType VarType;
1264 const Expr *CopyExpr;
1265
1266public:
1267 CXXByrefHelpers(CharUnits alignment, QualType type,
1268 const Expr *copyExpr)
1269 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1270
1271 bool needsCopy() const { return CopyExpr != 0; }
1272 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1273 llvm::Value *srcField) {
1274 if (!CopyExpr) return;
1275 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1276 }
1277
1278 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1279 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1280 CGF.PushDestructorCleanup(VarType, field);
1281 CGF.PopCleanupBlocks(cleanupDepth);
1282 }
1283
1284 void profileImpl(llvm::FoldingSetNodeID &id) const {
1285 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1286 }
1287};
1288} // end anonymous namespace
1289
1290static llvm::Constant *
1291generateByrefCopyHelper(CodeGenFunction &CGF,
1292 const llvm::StructType &byrefType,
1293 CodeGenModule::ByrefHelpers &byrefInfo) {
1294 ASTContext &Context = CGF.getContext();
1295
1296 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001297
John McCalld26bc762011-03-09 04:27:21 +00001298 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001299 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001300 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001301
John McCallf0c11f72011-03-31 08:03:29 +00001302 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001303 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Mike Stump45031c02009-03-06 02:29:21 +00001305 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001306 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001307
John McCallf0c11f72011-03-31 08:03:29 +00001308 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001309 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1310
Mike Stump3899a7f2009-06-05 23:26:36 +00001311 // FIXME: We'd like to put these into a mergable by content, with
1312 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001313 llvm::Function *Fn =
1314 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001315 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001316
1317 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001318 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001319
John McCallf0c11f72011-03-31 08:03:29 +00001320 FunctionDecl *FD = FunctionDecl::Create(Context,
1321 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001322 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001323 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001324 SC_Static,
1325 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001326 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001327 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001328
John McCallf0c11f72011-03-31 08:03:29 +00001329 if (byrefInfo.needsCopy()) {
1330 const llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001331
John McCallf0c11f72011-03-31 08:03:29 +00001332 // dst->x
1333 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1334 destField = CGF.Builder.CreateLoad(destField);
1335 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1336 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001337
John McCallf0c11f72011-03-31 08:03:29 +00001338 // src->x
1339 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1340 srcField = CGF.Builder.CreateLoad(srcField);
1341 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1342 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1343
1344 byrefInfo.emitCopy(CGF, destField, srcField);
1345 }
1346
1347 CGF.FinishFunction();
1348
1349 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001350}
1351
John McCallf0c11f72011-03-31 08:03:29 +00001352/// Build the copy helper for a __block variable.
1353static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1354 const llvm::StructType &byrefType,
1355 CodeGenModule::ByrefHelpers &info) {
1356 CodeGenFunction CGF(CGM);
1357 return generateByrefCopyHelper(CGF, byrefType, info);
1358}
1359
1360/// Generate code for a __block variable's dispose helper.
1361static llvm::Constant *
1362generateByrefDisposeHelper(CodeGenFunction &CGF,
1363 const llvm::StructType &byrefType,
1364 CodeGenModule::ByrefHelpers &byrefInfo) {
1365 ASTContext &Context = CGF.getContext();
1366 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001367
John McCalld26bc762011-03-09 04:27:21 +00001368 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001369 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001370 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Mike Stump45031c02009-03-06 02:29:21 +00001372 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001373 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001374
John McCallf0c11f72011-03-31 08:03:29 +00001375 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001376 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1377
Mike Stump3899a7f2009-06-05 23:26:36 +00001378 // FIXME: We'd like to put these into a mergable by content, with
1379 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001380 llvm::Function *Fn =
1381 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001382 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001383 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001384
1385 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001386 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001387
John McCallf0c11f72011-03-31 08:03:29 +00001388 FunctionDecl *FD = FunctionDecl::Create(Context,
1389 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001390 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001391 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001392 SC_Static,
1393 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001394 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001395 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001396
John McCallf0c11f72011-03-31 08:03:29 +00001397 if (byrefInfo.needsDispose()) {
1398 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1399 V = CGF.Builder.CreateLoad(V);
1400 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1401 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001402
John McCallf0c11f72011-03-31 08:03:29 +00001403 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001404 }
Mike Stump45031c02009-03-06 02:29:21 +00001405
John McCallf0c11f72011-03-31 08:03:29 +00001406 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001407
John McCallf0c11f72011-03-31 08:03:29 +00001408 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001409}
1410
John McCallf0c11f72011-03-31 08:03:29 +00001411/// Build the dispose helper for a __block variable.
1412static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1413 const llvm::StructType &byrefType,
1414 CodeGenModule::ByrefHelpers &info) {
1415 CodeGenFunction CGF(CGM);
1416 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001417}
1418
John McCallf0c11f72011-03-31 08:03:29 +00001419///
1420template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1421 const llvm::StructType &byrefTy,
1422 T &byrefInfo) {
1423 // Increase the field's alignment to be at least pointer alignment,
1424 // since the layout of the byref struct will guarantee at least that.
1425 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1426 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1427
1428 llvm::FoldingSetNodeID id;
1429 byrefInfo.Profile(id);
1430
1431 void *insertPos;
1432 CodeGenModule::ByrefHelpers *node
1433 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1434 if (node) return static_cast<T*>(node);
1435
1436 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1437 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1438
1439 T *copy = new (CGM.getContext()) T(byrefInfo);
1440 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1441 return copy;
1442}
1443
1444CodeGenModule::ByrefHelpers *
1445CodeGenFunction::buildByrefHelpers(const llvm::StructType &byrefType,
1446 const AutoVarEmission &emission) {
1447 const VarDecl &var = *emission.Variable;
1448 QualType type = var.getType();
1449
1450 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1451 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1452 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1453
1454 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1455 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1456 }
1457
1458 BlockFieldFlags flags;
1459 if (type->isBlockPointerType()) {
1460 flags |= BLOCK_FIELD_IS_BLOCK;
1461 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1462 type->isObjCObjectPointerType()) {
1463 flags |= BLOCK_FIELD_IS_OBJECT;
1464 } else {
1465 return 0;
1466 }
1467
1468 if (type.isObjCGCWeak())
1469 flags |= BLOCK_FIELD_IS_WEAK;
1470
1471 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1472 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001473}
1474
John McCall5af02db2011-03-31 01:59:53 +00001475unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1476 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1477
1478 return ByRefValueInfo.find(VD)->second.second;
1479}
1480
1481llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1482 const VarDecl *V) {
1483 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1484 Loc = Builder.CreateLoad(Loc);
1485 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1486 V->getNameAsString());
1487 return Loc;
1488}
1489
1490/// BuildByRefType - This routine changes a __block variable declared as T x
1491/// into:
1492///
1493/// struct {
1494/// void *__isa;
1495/// void *__forwarding;
1496/// int32_t __flags;
1497/// int32_t __size;
1498/// void *__copy_helper; // only if needed
1499/// void *__destroy_helper; // only if needed
1500/// char padding[X]; // only if needed
1501/// T x;
1502/// } x
1503///
1504const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1505 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
1506 if (Info.first)
1507 return Info.first;
1508
1509 QualType Ty = D->getType();
1510
1511 std::vector<const llvm::Type *> Types;
1512
1513 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext());
1514
1515 // void *__isa;
1516 Types.push_back(Int8PtrTy);
1517
1518 // void *__forwarding;
1519 Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
1520
1521 // int32_t __flags;
1522 Types.push_back(Int32Ty);
1523
1524 // int32_t __size;
1525 Types.push_back(Int32Ty);
1526
1527 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1528 if (HasCopyAndDispose) {
1529 /// void *__copy_helper;
1530 Types.push_back(Int8PtrTy);
1531
1532 /// void *__destroy_helper;
1533 Types.push_back(Int8PtrTy);
1534 }
1535
1536 bool Packed = false;
1537 CharUnits Align = getContext().getDeclAlign(D);
1538 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1539 // We have to insert padding.
1540
1541 // The struct above has 2 32-bit integers.
1542 unsigned CurrentOffsetInBytes = 4 * 2;
1543
1544 // And either 2 or 4 pointers.
1545 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1546 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1547
1548 // Align the offset.
1549 unsigned AlignedOffsetInBytes =
1550 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1551
1552 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1553 if (NumPaddingBytes > 0) {
1554 const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
1555 // FIXME: We need a sema error for alignment larger than the minimum of
1556 // the maximal stack alignmint and the alignment of malloc on the system.
1557 if (NumPaddingBytes > 1)
1558 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1559
1560 Types.push_back(Ty);
1561
1562 // We want a packed struct.
1563 Packed = true;
1564 }
1565 }
1566
1567 // T x;
1568 Types.push_back(ConvertTypeForMem(Ty));
1569
1570 const llvm::Type *T = llvm::StructType::get(getLLVMContext(), Types, Packed);
1571
1572 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
1573 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
1574 ByRefTypeHolder.get());
1575
1576 Info.first = ByRefTypeHolder.get();
1577
1578 Info.second = Types.size() - 1;
1579
1580 return Info.first;
1581}
1582
1583/// Initialize the structural components of a __block variable, i.e.
1584/// everything but the actual object.
1585void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001586 // Find the address of the local.
1587 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001588
John McCallf0c11f72011-03-31 08:03:29 +00001589 // That's an alloca of the byref structure type.
1590 const llvm::StructType *byrefType = cast<llvm::StructType>(
1591 cast<llvm::PointerType>(addr->getType())->getElementType());
1592
1593 // Build the byref helpers if necessary. This is null if we don't need any.
1594 CodeGenModule::ByrefHelpers *helpers =
1595 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001596
1597 const VarDecl &D = *emission.Variable;
1598 QualType type = D.getType();
1599
John McCallf0c11f72011-03-31 08:03:29 +00001600 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001601
1602 // Initialize the 'isa', which is just 0 or 1.
1603 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001604 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001605 isa = 1;
1606 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1607 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1608
1609 // Store the address of the variable into its own forwarding pointer.
1610 Builder.CreateStore(addr,
1611 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1612
1613 // Blocks ABI:
1614 // c) the flags field is set to either 0 if no helper functions are
1615 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1616 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001617 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001618 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1619 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1620
John McCallf0c11f72011-03-31 08:03:29 +00001621 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1622 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001623 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1624
John McCallf0c11f72011-03-31 08:03:29 +00001625 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001626 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001627 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001628
1629 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001630 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001631 }
1632}
1633
John McCalld16c2cf2011-02-08 08:22:06 +00001634void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001635 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001636 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001637 V = Builder.CreateBitCast(V, Int8PtrTy);
1638 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001639 Builder.CreateCall2(F, V, N);
1640}
John McCall5af02db2011-03-31 01:59:53 +00001641
1642namespace {
1643 struct CallBlockRelease : EHScopeStack::Cleanup {
1644 llvm::Value *Addr;
1645 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1646
1647 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1648 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1649 }
1650 };
1651}
1652
1653/// Enter a cleanup to destroy a __block variable. Note that this
1654/// cleanup should be a no-op if the variable hasn't left the stack
1655/// yet; if a cleanup is required for the variable itself, that needs
1656/// to be done externally.
1657void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1658 // We don't enter this cleanup if we're in pure-GC mode.
1659 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1660 return;
1661
1662 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1663}