blob: 049294ec01d5a88fbad098d2f6b0a235bf1ea3e0 [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"
Micah Villmow25a6a842012-10-08 16:25:52 +000022#include "llvm/DataLayout.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 McCall1a343eb2011-11-10 08:15:53 +000028CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
29 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
John McCall6f103ba2011-11-10 10:43:54 +000030 HasCXXObject(false), UsesStret(false), StructureType(0), Block(block),
31 DominatingIP(0) {
John McCallee504292010-05-21 04:11:14 +000032
John McCall1a343eb2011-11-10 08:15:53 +000033 // Skip asm prefix, if any. 'name' is usually taken directly from
34 // the mangled name of the enclosing function.
35 if (!name.empty() && name[0] == '\01')
36 name = name.substr(1);
John McCallee504292010-05-21 04:11:14 +000037}
38
John McCallf0c11f72011-03-31 08:03:29 +000039// Anchor the vtable to this translation unit.
40CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
41
John McCall6b5a61b2011-02-07 10:33:21 +000042/// Build the given block as a global block.
43static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
44 const CGBlockInfo &blockInfo,
45 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000046
John McCall6b5a61b2011-02-07 10:33:21 +000047/// Build the helper function to copy a block.
48static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
49 const CGBlockInfo &blockInfo) {
50 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
51}
52
53/// Build the helper function to dipose of a block.
54static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
55 const CGBlockInfo &blockInfo) {
56 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
57}
58
59/// Build the block descriptor constant for a block.
60static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
61 const CGBlockInfo &blockInfo) {
62 ASTContext &C = CGM.getContext();
63
Chris Lattner2acc6e32011-07-18 04:24:23 +000064 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
65 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000066
Chris Lattner5f9e2722011-07-23 10:55:15 +000067 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000068
69 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000070 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000071
72 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000073 // FIXME: What is the right way to say this doesn't fit? We should give
74 // a user diagnostic in that case. Better fix would be to change the
75 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000076 elements.push_back(llvm::ConstantInt::get(ulong,
77 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000078
John McCall6b5a61b2011-02-07 10:33:21 +000079 // Optional copy/dispose helpers.
80 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000081 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000082 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000083
84 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000085 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000086 }
87
John McCall6b5a61b2011-02-07 10:33:21 +000088 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
89 std::string typeAtEncoding =
90 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
91 elements.push_back(llvm::ConstantExpr::getBitCast(
92 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000093
John McCall6b5a61b2011-02-07 10:33:21 +000094 // GC layout.
David Blaikie4e4d0842012-03-11 07:00:24 +000095 if (C.getLangOpts().ObjC1)
John McCall6b5a61b2011-02-07 10:33:21 +000096 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
97 else
98 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000099
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000100 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
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'
Jay Foadef6de3d2011-07-11 09:56:20 +0000169 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,
Jay Foadef6de3d2011-07-11 09:56:20 +0000173 llvm::Type *type)
John McCall6b5a61b2011-02-07 10:33:21 +0000174 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000175
John McCall6b5a61b2011-02-07 10:33:21 +0000176 /// Tell the block info that this chunk has the given field index.
177 void setIndex(CGBlockInfo &info, unsigned index) {
178 if (!Capture)
179 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000180 else
John McCall6b5a61b2011-02-07 10:33:21 +0000181 info.Captures[Capture->getVariable()]
182 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000183 }
John McCall6b5a61b2011-02-07 10:33:21 +0000184 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000185
John McCall6b5a61b2011-02-07 10:33:21 +0000186 /// Order by descending alignment.
187 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
188 return left.Alignment > right.Alignment;
189 }
190}
191
John McCall461c9c12011-02-08 03:07:00 +0000192/// Determines if the given type is safe for constant capture in C++.
193static bool isSafeForCXXConstantCapture(QualType type) {
194 const RecordType *recordType =
195 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
196
197 // Only records can be unsafe.
198 if (!recordType) return true;
199
200 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
201
202 // Maintain semantics for classes with non-trivial dtors or copy ctors.
203 if (!record->hasTrivialDestructor()) return false;
204 if (!record->hasTrivialCopyConstructor()) return false;
205
206 // Otherwise, we just have to make sure there aren't any mutable
207 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000208 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000209}
210
John McCall6b5a61b2011-02-07 10:33:21 +0000211/// It is illegal to modify a const object after initialization.
212/// Therefore, if a const object has a constant initializer, we don't
213/// actually need to keep storage for it in the block; we'll just
214/// rematerialize it at the start of the block function. This is
215/// acceptable because we make no promises about address stability of
216/// captured variables.
217static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000218 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000219 const VarDecl *var) {
220 QualType type = var->getType();
221
222 // We can only do this if the variable is const.
223 if (!type.isConstQualified()) return 0;
224
John McCall461c9c12011-02-08 03:07:00 +0000225 // Furthermore, in C++ we have to worry about mutable fields:
226 // C++ [dcl.type.cv]p4:
227 // Except that any class member declared mutable can be
228 // modified, any attempt to modify a const object during its
229 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000230 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000231 return 0;
232
233 // If the variable doesn't have any initializer (shouldn't this be
234 // invalid?), it's not clear what we should do. Maybe capture as
235 // zero?
236 const Expr *init = var->getInit();
237 if (!init) return 0;
238
Richard Smith2d6a5672012-01-14 04:30:29 +0000239 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000240}
241
242/// Get the low bit of a nonzero character count. This is the
243/// alignment of the nth byte if the 0th byte is universally aligned.
244static CharUnits getLowBit(CharUnits v) {
245 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
246}
247
248static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000249 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000250 ASTContext &C = CGM.getContext();
251
252 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
253 CharUnits ptrSize, ptrAlign, intSize, intAlign;
254 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
255 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
256
257 // Are there crazy embedded platforms where this isn't true?
258 assert(intSize <= ptrSize && "layout assumptions horribly violated");
259
260 CharUnits headerSize = ptrSize;
261 if (2 * intSize < ptrAlign) headerSize += ptrSize;
262 else headerSize += 2 * intSize;
263 headerSize += 2 * ptrSize;
264
265 info.BlockAlign = ptrAlign;
266 info.BlockSize = headerSize;
267
268 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000269 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
270 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000271 elementTypes.push_back(i8p);
272 elementTypes.push_back(intTy);
273 elementTypes.push_back(intTy);
274 elementTypes.push_back(i8p);
275 elementTypes.push_back(CGM.getBlockDescriptorType());
276
277 assert(elementTypes.size() == BlockHeaderSize);
278}
279
280/// Compute the layout of the given block. Attempts to lay the block
281/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000282static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
283 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000284 ASTContext &C = CGM.getContext();
285 const BlockDecl *block = info.getBlockDecl();
286
Chris Lattner5f9e2722011-07-23 10:55:15 +0000287 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000288 initializeForBlockHeader(CGM, info, elementTypes);
289
290 if (!block->hasCaptures()) {
291 info.StructureType =
292 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
293 info.CanBeGlobal = true;
294 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000295 }
Mike Stump00470a12009-03-05 08:32:30 +0000296
John McCall6b5a61b2011-02-07 10:33:21 +0000297 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000298 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000299 layout.reserve(block->capturesCXXThis() +
300 (block->capture_end() - block->capture_begin()));
301
302 CharUnits maxFieldAlign;
303
304 // First, 'this'.
305 if (block->capturesCXXThis()) {
306 const DeclContext *DC = block->getDeclContext();
307 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
308 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000309 QualType thisType;
310 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
311 thisType = C.getPointerType(C.getRecordType(RD));
312 else
313 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000314
Jay Foadef6de3d2011-07-11 09:56:20 +0000315 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000316 std::pair<CharUnits,CharUnits> tinfo
317 = CGM.getContext().getTypeInfoInChars(thisType);
318 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
319
320 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
321 }
322
323 // Next, all the block captures.
324 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
325 ce = block->capture_end(); ci != ce; ++ci) {
326 const VarDecl *variable = ci->getVariable();
327
328 if (ci->isByRef()) {
329 // We have to copy/dispose of the __block reference.
330 info.NeedsCopyDispose = true;
331
John McCall6b5a61b2011-02-07 10:33:21 +0000332 // Just use void* instead of a pointer to the byref type.
333 QualType byRefPtrTy = C.VoidPtrTy;
334
Jay Foadef6de3d2011-07-11 09:56:20 +0000335 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000336 std::pair<CharUnits,CharUnits> tinfo
337 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
338 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
339
340 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
341 &*ci, llvmType));
342 continue;
343 }
344
345 // Otherwise, build a layout chunk with the size and alignment of
346 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000347 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000348 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
349 continue;
350 }
351
John McCallf85e1932011-06-15 23:02:42 +0000352 // If we have a lifetime qualifier, honor it for capture purposes.
353 // That includes *not* copying it if it's __unsafe_unretained.
354 if (Qualifiers::ObjCLifetime lifetime
355 = variable->getType().getObjCLifetime()) {
356 switch (lifetime) {
357 case Qualifiers::OCL_None: llvm_unreachable("impossible");
358 case Qualifiers::OCL_ExplicitNone:
359 case Qualifiers::OCL_Autoreleasing:
360 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000361
John McCallf85e1932011-06-15 23:02:42 +0000362 case Qualifiers::OCL_Strong:
363 case Qualifiers::OCL_Weak:
364 info.NeedsCopyDispose = true;
365 }
366
367 // Block pointers require copy/dispose. So do Objective-C pointers.
368 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000369 info.NeedsCopyDispose = true;
370
371 // So do types that require non-trivial copy construction.
372 } else if (ci->hasCopyExpr()) {
373 info.NeedsCopyDispose = true;
374 info.HasCXXObject = true;
375
376 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000377 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000378 if (const CXXRecordDecl *record =
379 variable->getType()->getAsCXXRecordDecl()) {
380 if (!record->hasTrivialDestructor()) {
381 info.HasCXXObject = true;
382 info.NeedsCopyDispose = true;
383 }
384 }
385 }
386
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000387 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000388 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000389 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000390
John McCall6b5a61b2011-02-07 10:33:21 +0000391 maxFieldAlign = std::max(maxFieldAlign, align);
392
Jay Foadef6de3d2011-07-11 09:56:20 +0000393 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000394 CGM.getTypes().ConvertTypeForMem(VT);
395
John McCall6b5a61b2011-02-07 10:33:21 +0000396 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
397 }
398
399 // If that was everything, we're done here.
400 if (layout.empty()) {
401 info.StructureType =
402 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
403 info.CanBeGlobal = true;
404 return;
405 }
406
407 // Sort the layout by alignment. We have to use a stable sort here
408 // to get reproducible results. There should probably be an
409 // llvm::array_pod_stable_sort.
410 std::stable_sort(layout.begin(), layout.end());
411
412 CharUnits &blockSize = info.BlockSize;
413 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
414
415 // Assuming that the first byte in the header is maximally aligned,
416 // get the alignment of the first byte following the header.
417 CharUnits endAlign = getLowBit(blockSize);
418
419 // If the end of the header isn't satisfactorily aligned for the
420 // maximum thing, look for things that are okay with the header-end
421 // alignment, and keep appending them until we get something that's
422 // aligned right. This algorithm is only guaranteed optimal if
423 // that condition is satisfied at some point; otherwise we can get
424 // things like:
425 // header // next byte has alignment 4
426 // something_with_size_5; // next byte has alignment 1
427 // something_with_alignment_8;
428 // which has 7 bytes of padding, as opposed to the naive solution
429 // which might have less (?).
430 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000431 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000432 li = layout.begin() + 1, le = layout.end();
433
434 // Look for something that the header end is already
435 // satisfactorily aligned for.
436 for (; li != le && endAlign < li->Alignment; ++li)
437 ;
438
439 // If we found something that's naturally aligned for the end of
440 // the header, keep adding things...
441 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000442 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000443 for (; li != le; ++li) {
444 assert(endAlign >= li->Alignment);
445
446 li->setIndex(info, elementTypes.size());
447 elementTypes.push_back(li->Type);
448 blockSize += li->Size;
449 endAlign = getLowBit(blockSize);
450
451 // ...until we get to the alignment of the maximum field.
452 if (endAlign >= maxFieldAlign)
453 break;
454 }
455
456 // Don't re-append everything we just appended.
457 layout.erase(first, li);
458 }
459 }
460
John McCall6ea48412012-04-26 21:14:42 +0000461 assert(endAlign == getLowBit(blockSize));
462
John McCall6b5a61b2011-02-07 10:33:21 +0000463 // At this point, we just have to add padding if the end align still
464 // isn't aligned right.
465 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000466 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
467 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000468
John McCall5936e332011-02-15 09:22:45 +0000469 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
470 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000471 blockSize = newBlockSize;
John McCall6c803f72012-05-01 20:28:00 +0000472 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall6b5a61b2011-02-07 10:33:21 +0000473 }
474
John McCall6c803f72012-05-01 20:28:00 +0000475 assert(endAlign >= maxFieldAlign);
John McCall6ea48412012-04-26 21:14:42 +0000476 assert(endAlign == getLowBit(blockSize));
477
John McCall6b5a61b2011-02-07 10:33:21 +0000478 // Slam everything else on now. This works because they have
479 // strictly decreasing alignment and we expect that size is always a
480 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000481 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000482 li = layout.begin(), le = layout.end(); li != le; ++li) {
483 assert(endAlign >= li->Alignment);
484 li->setIndex(info, elementTypes.size());
485 elementTypes.push_back(li->Type);
486 blockSize += li->Size;
487 endAlign = getLowBit(blockSize);
488 }
489
490 info.StructureType =
491 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
492}
493
John McCall1a343eb2011-11-10 08:15:53 +0000494/// Enter the scope of a block. This should be run at the entrance to
495/// a full-expression so that the block's cleanups are pushed at the
496/// right place in the stack.
497static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000498 assert(CGF.HaveInsertPoint());
499
John McCall1a343eb2011-11-10 08:15:53 +0000500 // Allocate the block info and place it at the head of the list.
501 CGBlockInfo &blockInfo =
502 *new CGBlockInfo(block, CGF.CurFn->getName());
503 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
504 CGF.FirstBlockInfo = &blockInfo;
505
506 // Compute information about the layout, etc., of this block,
507 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000508 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000509
510 // Nothing else to do if it can be global.
511 if (blockInfo.CanBeGlobal) return;
512
513 // Make the allocation for the block.
514 blockInfo.Address =
515 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
516 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
517
518 // If there are cleanups to emit, enter them (but inactive).
519 if (!blockInfo.NeedsCopyDispose) return;
520
521 // Walk through the captures (in order) and find the ones not
522 // captured by constant.
523 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
524 ce = block->capture_end(); ci != ce; ++ci) {
525 // Ignore __block captures; there's nothing special in the
526 // on-stack block that we need to do for them.
527 if (ci->isByRef()) continue;
528
529 // Ignore variables that are constant-captured.
530 const VarDecl *variable = ci->getVariable();
531 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
532 if (capture.isConstant()) continue;
533
534 // Ignore objects that aren't destructed.
535 QualType::DestructionKind dtorKind =
536 variable->getType().isDestructedType();
537 if (dtorKind == QualType::DK_none) continue;
538
539 CodeGenFunction::Destroyer *destroyer;
540
541 // Block captures count as local values and have imprecise semantics.
542 // They also can't be arrays, so need to worry about that.
543 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000544 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000545 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000546 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000547 }
548
549 // GEP down to the address.
550 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
551 capture.getIndex());
552
John McCall6f103ba2011-11-10 10:43:54 +0000553 // We can use that GEP as the dominating IP.
554 if (!blockInfo.DominatingIP)
555 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
556
John McCall1a343eb2011-11-10 08:15:53 +0000557 CleanupKind cleanupKind = InactiveNormalCleanup;
558 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
559 if (useArrayEHCleanup)
560 cleanupKind = InactiveNormalAndEHCleanup;
561
562 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000563 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000564
565 // Remember where that cleanup was.
566 capture.setCleanup(CGF.EHStack.stable_begin());
567 }
568}
569
570/// Enter a full-expression with a non-trivial number of objects to
571/// clean up. This is in this file because, at the moment, the only
572/// kind of cleanup object is a BlockDecl*.
573void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
574 assert(E->getNumObjects() != 0);
575 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
576 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
577 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
578 enterBlockScope(*this, *i);
579 }
580}
581
582/// Find the layout for the given block in a linked list and remove it.
583static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
584 const BlockDecl *block) {
585 while (true) {
586 assert(head && *head);
587 CGBlockInfo *cur = *head;
588
589 // If this is the block we're looking for, splice it out of the list.
590 if (cur->getBlockDecl() == block) {
591 *head = cur->NextBlockInfo;
592 return cur;
593 }
594
595 head = &cur->NextBlockInfo;
596 }
597}
598
599/// Destroy a chain of block layouts.
600void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
601 assert(head && "destroying an empty chain");
602 do {
603 CGBlockInfo *cur = head;
604 head = cur->NextBlockInfo;
605 delete cur;
606 } while (head != 0);
607}
608
John McCall6b5a61b2011-02-07 10:33:21 +0000609/// Emit a block literal expression in the current function.
610llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000611 // If the block has no captures, we won't have a pre-computed
612 // layout for it.
613 if (!blockExpr->getBlockDecl()->hasCaptures()) {
614 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000615 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000616 blockInfo.BlockExpression = blockExpr;
617 return EmitBlockLiteral(blockInfo);
618 }
John McCall6b5a61b2011-02-07 10:33:21 +0000619
John McCall1a343eb2011-11-10 08:15:53 +0000620 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000621 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000622 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
623 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000624
John McCall1a343eb2011-11-10 08:15:53 +0000625 blockInfo->BlockExpression = blockExpr;
626 return EmitBlockLiteral(*blockInfo);
627}
628
629llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
630 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000631 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000632 llvm::Constant *blockFn
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000633 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000634 CurFuncDecl, LocalDeclMap,
Eli Friedman23f02672012-03-01 04:01:32 +0000635 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000636 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000637
638 // If there is nothing to capture, we can emit this as a global block.
639 if (blockInfo.CanBeGlobal)
640 return buildGlobalBlock(CGM, blockInfo, blockFn);
641
642 // Otherwise, we have to emit this as a local block.
643
644 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000645 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000646
647 // Build the block descriptor.
648 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
649
John McCall1a343eb2011-11-10 08:15:53 +0000650 llvm::AllocaInst *blockAddr = blockInfo.Address;
651 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000652
653 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000654 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000655 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
656 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000657 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000658
659 // Initialize the block literal.
660 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000661 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000662 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000663 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000664 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
665 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
666 "block.invoke"));
667 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
668 "block.descriptor"));
669
670 // Finally, capture all the values into the block.
671 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
672
673 // First, 'this'.
674 if (blockDecl->capturesCXXThis()) {
675 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
676 blockInfo.CXXThisIndex,
677 "block.captured-this.addr");
678 Builder.CreateStore(LoadCXXThis(), addr);
679 }
680
681 // Next, captured variables.
682 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
683 ce = blockDecl->capture_end(); ci != ce; ++ci) {
684 const VarDecl *variable = ci->getVariable();
685 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
686
687 // Ignore constant captures.
688 if (capture.isConstant()) continue;
689
690 QualType type = variable->getType();
691
692 // This will be a [[type]]*, except that a byref entry will just be
693 // an i8**.
694 llvm::Value *blockField =
695 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
696 "block.captured");
697
698 // Compute the address of the thing we're going to move into the
699 // block literal.
700 llvm::Value *src;
Douglas Gregor29a93f82012-05-16 16:50:20 +0000701 if (BlockInfo && ci->isNested()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000702 // We need to use the capture from the enclosing block.
703 const CGBlockInfo::Capture &enclosingCapture =
704 BlockInfo->getCapture(variable);
705
706 // This is a [[type]]*, except that a byref entry wil just be an i8**.
707 src = Builder.CreateStructGEP(LoadBlockStruct(),
708 enclosingCapture.getIndex(),
709 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000710 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000711 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000712 // special; we'll simply emit it directly.
713 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000714 } else {
715 // This is a [[type]]*.
716 src = LocalDeclMap[variable];
717 }
718
719 // For byrefs, we just write the pointer to the byref struct into
720 // the block field. There's no need to chase the forwarding
721 // pointer at this point, since we're building something that will
722 // live a shorter life than the stack byref anyway.
723 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000724 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000725 if (ci->isNested())
726 src = Builder.CreateLoad(src, "byref.capture");
727 else
John McCall5936e332011-02-15 09:22:45 +0000728 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000729
John McCall5936e332011-02-15 09:22:45 +0000730 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000731 Builder.CreateStore(src, blockField);
732
733 // If we have a copy constructor, evaluate that into the block field.
734 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000735 if (blockDecl->isConversionFromLambda()) {
736 // If we have a lambda conversion, emit the expression
737 // directly into the block instead.
738 CharUnits Align = getContext().getTypeAlignInChars(type);
739 AggValueSlot Slot =
740 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
741 AggValueSlot::IsDestructed,
742 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000743 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000744 EmitAggExpr(copyExpr, Slot);
745 } else {
746 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
747 }
John McCall6b5a61b2011-02-07 10:33:21 +0000748
749 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000750 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000751 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
752
753 // Otherwise, fake up a POD copy into the block field.
754 } else {
John McCallf85e1932011-06-15 23:02:42 +0000755 // Fake up a new variable so that EmitScalarInit doesn't think
756 // we're referring to the variable in its own initializer.
757 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000758 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000759
John McCallbb699b02011-02-07 18:37:40 +0000760 // We use one of these or the other depending on whether the
761 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000762 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
763 /*refersToEnclosing*/ ci->isNested(), type,
764 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000765
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000766 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000767 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000768 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000769 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000770 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000771 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000772 }
773
John McCall1a343eb2011-11-10 08:15:53 +0000774 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000775 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000776 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
777 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000778 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000779 }
John McCall6b5a61b2011-02-07 10:33:21 +0000780 }
781
782 // Cast to the converted block-pointer type, which happens (somewhat
783 // unfortunately) to be a pointer to function type.
784 llvm::Value *result =
785 Builder.CreateBitCast(blockAddr,
786 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000787
John McCall6b5a61b2011-02-07 10:33:21 +0000788 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000789}
790
791
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000792llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000793 if (BlockDescriptorType)
794 return BlockDescriptorType;
795
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000796 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000797 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000798
Mike Stumpab695142009-02-13 15:16:56 +0000799 // struct __block_descriptor {
800 // unsigned long reserved;
801 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000802 //
803 // // later, the following will be added
804 //
805 // struct {
806 // void (*copyHelper)();
807 // void (*copyHelper)();
808 // } helpers; // !!! optional
809 //
810 // const char *signature; // the block signature
811 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000812 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000813 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000814 llvm::StructType::create("struct.__block_descriptor",
815 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000816
John McCall6b5a61b2011-02-07 10:33:21 +0000817 // Now form a pointer to that.
818 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000819 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000820}
821
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000822llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000823 if (GenericBlockLiteralType)
824 return GenericBlockLiteralType;
825
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000826 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000827
Mike Stump9b8a7972009-02-13 15:25:34 +0000828 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000829 // void *__isa;
830 // int __flags;
831 // int __reserved;
832 // void (*__invoke)(void *);
833 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000834 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000835 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000836 llvm::StructType::create("struct.__block_literal_generic",
837 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
838 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000839
Mike Stump9b8a7972009-02-13 15:25:34 +0000840 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000841}
842
Mike Stumpbd65cac2009-02-19 01:01:04 +0000843
Anders Carlssona1736c02009-12-24 21:13:40 +0000844RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
845 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000846 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000847 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000848
Anders Carlssonacfde802009-02-12 00:39:25 +0000849 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
850
851 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000852 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000853 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000854
855 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000856 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000857 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
858
859 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000860 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000861
Benjamin Kramer578faa82011-09-27 21:06:10 +0000862 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000863
Anders Carlssonacfde802009-02-12 00:39:25 +0000864 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000865 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000866 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000867
Anders Carlsson782f3972009-04-08 23:13:16 +0000868 QualType FnType = BPT->getPointeeType();
869
Anders Carlssonacfde802009-02-12 00:39:25 +0000870 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000871 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000872 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000873
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000874 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000875 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000876
John McCall64cd2322011-03-09 08:39:33 +0000877 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000878 const CGFunctionInfo &FnInfo =
John McCall0f3d0972012-07-07 06:41:13 +0000879 CGM.getTypes().arrangeFreeFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000881 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000882 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattner2acc6e32011-07-18 04:24:23 +0000884 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000885 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Anders Carlssonacfde802009-02-12 00:39:25 +0000887 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000888 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000889}
Anders Carlssond5cab542009-02-12 17:55:02 +0000890
John McCall6b5a61b2011-02-07 10:33:21 +0000891llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
892 bool isByRef) {
893 assert(BlockInfo && "evaluating block ref without block information?");
894 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000895
John McCall6b5a61b2011-02-07 10:33:21 +0000896 // Handle constant captures.
897 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000898
John McCall6b5a61b2011-02-07 10:33:21 +0000899 llvm::Value *addr =
900 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
901 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000902
John McCall6b5a61b2011-02-07 10:33:21 +0000903 if (isByRef) {
904 // addr should be a void** right now. Load, then cast the result
905 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000906
John McCall6b5a61b2011-02-07 10:33:21 +0000907 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000908 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000909 = llvm::PointerType::get(BuildByRefType(variable), 0);
910 addr = Builder.CreateBitCast(addr, byrefPointerType,
911 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000912
John McCall6b5a61b2011-02-07 10:33:21 +0000913 // Follow the forwarding pointer.
914 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
915 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000916
John McCall6b5a61b2011-02-07 10:33:21 +0000917 // Cast back to byref* and GEP over to the actual object.
918 addr = Builder.CreateBitCast(addr, byrefPointerType);
919 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
920 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000921 }
922
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000923 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000924 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000925
John McCall6b5a61b2011-02-07 10:33:21 +0000926 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000927}
928
Mike Stump67a64482009-02-14 22:16:35 +0000929llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000930CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000931 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000932 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
933 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000934
John McCall6b5a61b2011-02-07 10:33:21 +0000935 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +0000936 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000937
John McCall6b5a61b2011-02-07 10:33:21 +0000938 // Using that metadata, generate the actual block function.
939 llvm::Constant *blockFn;
940 {
941 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000942 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
943 blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000944 0, LocalDeclMap,
945 false);
John McCall6b5a61b2011-02-07 10:33:21 +0000946 }
John McCall5936e332011-02-15 09:22:45 +0000947 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000948
John McCalld16c2cf2011-02-08 08:22:06 +0000949 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000950}
951
John McCall6b5a61b2011-02-07 10:33:21 +0000952static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
953 const CGBlockInfo &blockInfo,
954 llvm::Constant *blockFn) {
955 assert(blockInfo.CanBeGlobal);
956
957 // Generate the constants for the block literal initializer.
958 llvm::Constant *fields[BlockHeaderSize];
959
960 // isa
961 fields[0] = CGM.getNSConcreteGlobalBlock();
962
963 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000964 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
965 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
966
John McCall5936e332011-02-15 09:22:45 +0000967 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000968
969 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000970 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000971
972 // Function
973 fields[3] = blockFn;
974
975 // Descriptor
976 fields[4] = buildBlockDescriptor(CGM, blockInfo);
977
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000978 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000979
980 llvm::GlobalVariable *literal =
981 new llvm::GlobalVariable(CGM.getModule(),
982 init->getType(),
983 /*constant*/ true,
984 llvm::GlobalVariable::InternalLinkage,
985 init,
986 "__block_literal_global");
987 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
988
989 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000990 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +0000991 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
992 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000993}
994
Mike Stump00470a12009-03-05 08:32:30 +0000995llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000996CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
997 const CGBlockInfo &blockInfo,
998 const Decl *outerFnDecl,
Eli Friedman64bee652012-02-25 02:48:22 +0000999 const DeclMapTy &ldm,
1000 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001001 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001002
Devang Patel6d1155b2011-03-07 21:53:18 +00001003 // Check if we should generate debug info for this block function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001004 maybeInitializeDebugInfo();
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001005 CurGD = GD;
1006
John McCall6b5a61b2011-02-07 10:33:21 +00001007 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Mike Stump7f28a9c2009-03-13 23:34:28 +00001009 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001010 // to be local to this function as well, in case they're directly
1011 // referenced in a block.
1012 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1013 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1014 if (var && !var->hasLocalStorage())
1015 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001016 }
1017
John McCall6b5a61b2011-02-07 10:33:21 +00001018 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001019
John McCall6b5a61b2011-02-07 10:33:21 +00001020 // Build the argument list.
1021 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001022
John McCall6b5a61b2011-02-07 10:33:21 +00001023 // The first argument is the block pointer. Just take it as a void*
1024 // and cast it later.
1025 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001026 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001027
John McCall8178df32011-02-22 22:38:33 +00001028 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1029 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001030 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001031
John McCall6b5a61b2011-02-07 10:33:21 +00001032 // Now add the rest of the parameters.
1033 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1034 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001035 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001036
John McCall6b5a61b2011-02-07 10:33:21 +00001037 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001038 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001039 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001040 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1041 fnType->getExtInfo(),
1042 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001043 if (CGM.ReturnTypeUsesSRet(fnInfo))
1044 blockInfo.UsesStret = true;
1045
John McCallde5d3c72012-02-17 03:33:10 +00001046 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001047
John McCall6b5a61b2011-02-07 10:33:21 +00001048 MangleBuffer name;
1049 CGM.getBlockMangledName(GD, name, blockDecl);
1050 llvm::Function *fn =
1051 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1052 name.getString(), &CGM.getModule());
1053 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001054
John McCall6b5a61b2011-02-07 10:33:21 +00001055 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001056 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001057 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001058 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001059
John McCall8178df32011-02-22 22:38:33 +00001060 // Okay. Undo some of what StartFunction did.
1061
1062 // Pull the 'self' reference out of the local decl map.
1063 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1064 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001065 BlockPointer = Builder.CreateBitCast(blockAddr,
1066 blockInfo.StructureType->getPointerTo(),
1067 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001068
John McCallea1471e2010-05-20 01:18:31 +00001069 // If we have a C++ 'this' reference, go ahead and force it into
1070 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001071 if (blockDecl->capturesCXXThis()) {
1072 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1073 blockInfo.CXXThisIndex,
1074 "block.captured-this");
1075 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001076 }
1077
John McCall6b5a61b2011-02-07 10:33:21 +00001078 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1079 // appease it.
1080 if (const ObjCMethodDecl *method
1081 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1082 const VarDecl *self = method->getSelfDecl();
1083
1084 // There might not be a capture for 'self', but if there is...
1085 if (blockInfo.Captures.count(self)) {
1086 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1087 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1088 capture.getIndex(),
1089 "block.captured-self");
1090 LocalDeclMap[self] = selfAddr;
1091 }
1092 }
1093
1094 // Also force all the constant captures.
1095 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1096 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1097 const VarDecl *variable = ci->getVariable();
1098 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1099 if (!capture.isConstant()) continue;
1100
1101 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1102
1103 llvm::AllocaInst *alloca =
1104 CreateMemTemp(variable->getType(), "block.captured-const");
1105 alloca->setAlignment(align);
1106
1107 Builder.CreateStore(capture.getConstant(), alloca, align);
1108
1109 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001110 }
1111
John McCallf4b88a42012-03-10 09:33:50 +00001112 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001113 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1114 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1115 --entry_ptr;
1116
Eli Friedman64bee652012-02-25 02:48:22 +00001117 if (IsLambdaConversionToBlock)
1118 EmitLambdaBlockInvokeBody();
1119 else
1120 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001121
Mike Stumpde8c5c72009-10-01 00:27:30 +00001122 // Remember where we were...
1123 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001124
Mike Stumpde8c5c72009-10-01 00:27:30 +00001125 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001126 ++entry_ptr;
1127 Builder.SetInsertPoint(entry, entry_ptr);
1128
John McCallf4b88a42012-03-10 09:33:50 +00001129 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001130 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001131 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001132 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1133 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1134 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001135 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001136
Douglas Gregor4cdad312012-10-23 20:05:01 +00001137 if (CGM.getCodeGenOpts().getDebugInfo()
1138 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001139 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1140 if (capture.isConstant()) {
1141 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1142 Builder);
1143 continue;
1144 }
John McCall6b5a61b2011-02-07 10:33:21 +00001145
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001146 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1147 Builder, blockInfo);
1148 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001149 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001150 }
John McCall6b5a61b2011-02-07 10:33:21 +00001151
Mike Stumpde8c5c72009-10-01 00:27:30 +00001152 // And resume where we left off.
1153 if (resume == 0)
1154 Builder.ClearInsertionPoint();
1155 else
1156 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001157
John McCall6b5a61b2011-02-07 10:33:21 +00001158 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001159
John McCall6b5a61b2011-02-07 10:33:21 +00001160 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001161}
Mike Stumpa99038c2009-02-28 09:07:16 +00001162
John McCall6b5a61b2011-02-07 10:33:21 +00001163/*
1164 notes.push_back(HelperInfo());
1165 HelperInfo &note = notes.back();
1166 note.index = capture.getIndex();
1167 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1168 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001169
John McCall6b5a61b2011-02-07 10:33:21 +00001170 if (ci->isByRef()) {
1171 note.flag = BLOCK_FIELD_IS_BYREF;
1172 if (type.isObjCGCWeak())
1173 note.flag |= BLOCK_FIELD_IS_WEAK;
1174 } else if (type->isBlockPointerType()) {
1175 note.flag = BLOCK_FIELD_IS_BLOCK;
1176 } else {
1177 note.flag = BLOCK_FIELD_IS_OBJECT;
1178 }
1179 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001180
Mike Stump00470a12009-03-05 08:32:30 +00001181
Mike Stumpa99038c2009-02-28 09:07:16 +00001182
John McCall6b5a61b2011-02-07 10:33:21 +00001183llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001184CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001185 ASTContext &C = getContext();
1186
1187 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001188 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1189 args.push_back(&dstDecl);
1190 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1191 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Mike Stumpa4f668f2009-03-06 01:33:24 +00001193 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001194 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1195 FunctionType::ExtInfo(),
1196 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001197
John McCall6b5a61b2011-02-07 10:33:21 +00001198 // FIXME: it would be nice if these were mergeable with things with
1199 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001200 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001201
1202 llvm::Function *Fn =
1203 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001204 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001205
1206 IdentifierInfo *II
1207 = &CGM.getContext().Idents.get("__copy_helper_block_");
1208
Devang Patel58dc5ca2011-05-02 20:37:08 +00001209 // Check if we should generate debug info for this block helper function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001210 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001211
John McCall6b5a61b2011-02-07 10:33:21 +00001212 FunctionDecl *FD = FunctionDecl::Create(C,
1213 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001214 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001215 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001216 SC_Static,
1217 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001218 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001219 false);
John McCalld26bc762011-03-09 04:27:21 +00001220 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001221
Chris Lattner2acc6e32011-07-18 04:24:23 +00001222 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001223
John McCalld26bc762011-03-09 04:27:21 +00001224 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001225 src = Builder.CreateLoad(src);
1226 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001227
John McCalld26bc762011-03-09 04:27:21 +00001228 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001229 dst = Builder.CreateLoad(dst);
1230 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001231
John McCall6b5a61b2011-02-07 10:33:21 +00001232 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001233
John McCall6b5a61b2011-02-07 10:33:21 +00001234 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1235 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1236 const VarDecl *variable = ci->getVariable();
1237 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001238
John McCall6b5a61b2011-02-07 10:33:21 +00001239 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1240 if (capture.isConstant()) continue;
1241
1242 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001243 BlockFieldFlags flags;
1244
John McCall015f33b2012-10-17 02:28:37 +00001245 bool useARCWeakCopy = false;
1246 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001247
1248 if (copyExpr) {
1249 assert(!ci->isByRef());
1250 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001251
John McCall6b5a61b2011-02-07 10:33:21 +00001252 } else if (ci->isByRef()) {
1253 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001254 if (type.isObjCGCWeak())
1255 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001256
John McCallf85e1932011-06-15 23:02:42 +00001257 } else if (type->isObjCRetainableType()) {
1258 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001259 bool isBlockPointer = type->isBlockPointerType();
1260 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001261 flags = BLOCK_FIELD_IS_BLOCK;
1262
1263 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001264 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001265 Qualifiers qs = type.getQualifiers();
1266
John McCall015f33b2012-10-17 02:28:37 +00001267 // We need to register __weak direct captures with the runtime.
1268 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1269 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001270
John McCall015f33b2012-10-17 02:28:37 +00001271 // We need to retain the copied value for __strong direct captures.
1272 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1273 // If it's a block pointer, we have to copy the block and
1274 // assign that to the destination pointer, so we might as
1275 // well use _Block_object_assign. Otherwise we can avoid that.
1276 if (!isBlockPointer)
1277 useARCStrongCopy = true;
1278
1279 // Otherwise the memcpy is fine.
1280 } else {
1281 continue;
1282 }
1283
1284 // Non-ARC captures of retainable pointers are strong and
1285 // therefore require a call to _Block_object_assign.
1286 } else {
1287 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001288 }
1289 } else {
1290 continue;
1291 }
John McCall6b5a61b2011-02-07 10:33:21 +00001292
1293 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001294 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1295 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001296
1297 // If there's an explicit copy expression, we do that.
1298 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001299 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001300 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001301 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001302 } else {
1303 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001304 if (useARCStrongCopy) {
1305 // At -O0, store null into the destination field (so that the
1306 // storeStrong doesn't over-release) and then call storeStrong.
1307 // This is a workaround to not having an initStrong call.
1308 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1309 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1310 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1311 Builder.CreateStore(null, dstField);
1312 EmitARCStoreStrongCall(dstField, srcValue, true);
1313
1314 // With optimization enabled, take advantage of the fact that
1315 // the blocks runtime guarantees a memcpy of the block data, and
1316 // just emit a retain of the src field.
1317 } else {
1318 EmitARCRetainNonBlock(srcValue);
1319
1320 // We don't need this anymore, so kill it. It's not quite
1321 // worth the annoyance to avoid creating it in the first place.
1322 cast<llvm::Instruction>(dstField)->eraseFromParent();
1323 }
1324 } else {
1325 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1326 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1327 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1328 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
1329 }
Mike Stump08920992009-03-07 02:35:30 +00001330 }
1331 }
1332
John McCalld16c2cf2011-02-08 08:22:06 +00001333 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001334
John McCall5936e332011-02-15 09:22:45 +00001335 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001336}
1337
John McCall6b5a61b2011-02-07 10:33:21 +00001338llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001339CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001340 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001341
John McCall6b5a61b2011-02-07 10:33:21 +00001342 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001343 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1344 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Mike Stumpa4f668f2009-03-06 01:33:24 +00001346 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001347 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1348 FunctionType::ExtInfo(),
1349 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001350
Mike Stump3899a7f2009-06-05 23:26:36 +00001351 // FIXME: We'd like to put these into a mergable by content, with
1352 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001353 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001354
1355 llvm::Function *Fn =
1356 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001357 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001358
Devang Patel58dc5ca2011-05-02 20:37:08 +00001359 // Check if we should generate debug info for this block destroy function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001360 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001361
Mike Stumpa4f668f2009-03-06 01:33:24 +00001362 IdentifierInfo *II
1363 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1364
John McCall6b5a61b2011-02-07 10:33:21 +00001365 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001366 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001367 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001368 SC_Static,
1369 SC_None,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001370 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001371 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001372
Chris Lattner2acc6e32011-07-18 04:24:23 +00001373 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001374
John McCalld26bc762011-03-09 04:27:21 +00001375 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001376 src = Builder.CreateLoad(src);
1377 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001378
John McCall6b5a61b2011-02-07 10:33:21 +00001379 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1380
John McCalld16c2cf2011-02-08 08:22:06 +00001381 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001382
1383 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1384 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1385 const VarDecl *variable = ci->getVariable();
1386 QualType type = variable->getType();
1387
1388 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1389 if (capture.isConstant()) continue;
1390
John McCalld16c2cf2011-02-08 08:22:06 +00001391 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001392 const CXXDestructorDecl *dtor = 0;
1393
John McCall015f33b2012-10-17 02:28:37 +00001394 bool useARCWeakDestroy = false;
1395 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001396
John McCall6b5a61b2011-02-07 10:33:21 +00001397 if (ci->isByRef()) {
1398 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001399 if (type.isObjCGCWeak())
1400 flags |= BLOCK_FIELD_IS_WEAK;
1401 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1402 if (record->hasTrivialDestructor())
1403 continue;
1404 dtor = record->getDestructor();
1405 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001406 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001407 if (type->isBlockPointerType())
1408 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001409
John McCallf85e1932011-06-15 23:02:42 +00001410 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001411 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001412 Qualifiers qs = type.getQualifiers();
1413
1414 // Don't generate special dispose logic for a captured object
1415 // unless it's __strong or __weak.
1416 if (!qs.hasStrongOrWeakObjCLifetime())
1417 continue;
1418
1419 // Support __weak direct captures.
1420 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001421 useARCWeakDestroy = true;
1422
1423 // Tools really want us to use objc_storeStrong here.
1424 else
1425 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001426 }
1427 } else {
1428 continue;
1429 }
John McCall6b5a61b2011-02-07 10:33:21 +00001430
1431 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001432 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001433
1434 // If there's an explicit copy expression, we do that.
1435 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001436 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001437
John McCallf85e1932011-06-15 23:02:42 +00001438 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001439 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001440 EmitARCDestroyWeak(srcField);
1441
John McCall015f33b2012-10-17 02:28:37 +00001442 // Destroy strong objects with a call if requested.
1443 } else if (useARCStrongDestroy) {
1444 EmitARCDestroyStrong(srcField, /*precise*/ false);
1445
John McCall6b5a61b2011-02-07 10:33:21 +00001446 // Otherwise we call _Block_object_dispose. It wouldn't be too
1447 // hard to just emit this as a cleanup if we wanted to make sure
1448 // that things were done in reverse.
1449 } else {
1450 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001451 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001452 BuildBlockRelease(value, flags);
1453 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001454 }
1455
John McCall6b5a61b2011-02-07 10:33:21 +00001456 cleanups.ForceCleanup();
1457
John McCalld16c2cf2011-02-08 08:22:06 +00001458 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001459
John McCall5936e332011-02-15 09:22:45 +00001460 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001461}
1462
John McCallf0c11f72011-03-31 08:03:29 +00001463namespace {
1464
1465/// Emits the copy/dispose helper functions for a __block object of id type.
1466class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1467 BlockFieldFlags Flags;
1468
1469public:
1470 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1471 : ByrefHelpers(alignment), Flags(flags) {}
1472
John McCall36170192011-03-31 09:19:20 +00001473 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1474 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001475 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1476
1477 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1478 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1479
1480 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1481
1482 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1483 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1484 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1485 }
1486
1487 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1488 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1489 llvm::Value *value = CGF.Builder.CreateLoad(field);
1490
1491 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1492 }
1493
1494 void profileImpl(llvm::FoldingSetNodeID &id) const {
1495 id.AddInteger(Flags.getBitMask());
1496 }
1497};
1498
John McCallf85e1932011-06-15 23:02:42 +00001499/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1500class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1501public:
1502 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1503
1504 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1505 llvm::Value *srcField) {
1506 CGF.EmitARCMoveWeak(destField, srcField);
1507 }
1508
1509 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1510 CGF.EmitARCDestroyWeak(field);
1511 }
1512
1513 void profileImpl(llvm::FoldingSetNodeID &id) const {
1514 // 0 is distinguishable from all pointers and byref flags
1515 id.AddInteger(0);
1516 }
1517};
1518
1519/// Emits the copy/dispose helpers for an ARC __block __strong variable
1520/// that's not of block-pointer type.
1521class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1522public:
1523 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1524
1525 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1526 llvm::Value *srcField) {
1527 // Do a "move" by copying the value and then zeroing out the old
1528 // variable.
1529
John McCalla59e4b72011-11-09 03:17:26 +00001530 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1531 value->setAlignment(Alignment.getQuantity());
1532
John McCallf85e1932011-06-15 23:02:42 +00001533 llvm::Value *null =
1534 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001535
1536 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1537 store->setAlignment(Alignment.getQuantity());
1538
1539 store = CGF.Builder.CreateStore(null, srcField);
1540 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001541 }
1542
1543 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001544 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001545 }
1546
1547 void profileImpl(llvm::FoldingSetNodeID &id) const {
1548 // 1 is distinguishable from all pointers and byref flags
1549 id.AddInteger(1);
1550 }
1551};
1552
John McCalla59e4b72011-11-09 03:17:26 +00001553/// Emits the copy/dispose helpers for an ARC __block __strong
1554/// variable that's of block-pointer type.
1555class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1556public:
1557 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1558
1559 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1560 llvm::Value *srcField) {
1561 // Do the copy with objc_retainBlock; that's all that
1562 // _Block_object_assign would do anyway, and we'd have to pass the
1563 // right arguments to make sure it doesn't get no-op'ed.
1564 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1565 oldValue->setAlignment(Alignment.getQuantity());
1566
1567 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1568
1569 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1570 store->setAlignment(Alignment.getQuantity());
1571 }
1572
1573 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001574 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCalla59e4b72011-11-09 03:17:26 +00001575 }
1576
1577 void profileImpl(llvm::FoldingSetNodeID &id) const {
1578 // 2 is distinguishable from all pointers and byref flags
1579 id.AddInteger(2);
1580 }
1581};
1582
John McCallf0c11f72011-03-31 08:03:29 +00001583/// Emits the copy/dispose helpers for a __block variable with a
1584/// nontrivial copy constructor or destructor.
1585class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1586 QualType VarType;
1587 const Expr *CopyExpr;
1588
1589public:
1590 CXXByrefHelpers(CharUnits alignment, QualType type,
1591 const Expr *copyExpr)
1592 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1593
1594 bool needsCopy() const { return CopyExpr != 0; }
1595 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1596 llvm::Value *srcField) {
1597 if (!CopyExpr) return;
1598 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1599 }
1600
1601 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1602 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1603 CGF.PushDestructorCleanup(VarType, field);
1604 CGF.PopCleanupBlocks(cleanupDepth);
1605 }
1606
1607 void profileImpl(llvm::FoldingSetNodeID &id) const {
1608 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1609 }
1610};
1611} // end anonymous namespace
1612
1613static llvm::Constant *
1614generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001615 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001616 CodeGenModule::ByrefHelpers &byrefInfo) {
1617 ASTContext &Context = CGF.getContext();
1618
1619 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001620
John McCalld26bc762011-03-09 04:27:21 +00001621 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001622 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001623 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001624
John McCallf0c11f72011-03-31 08:03:29 +00001625 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001626 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Mike Stump45031c02009-03-06 02:29:21 +00001628 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001629 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1630 FunctionType::ExtInfo(),
1631 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001632
John McCallf0c11f72011-03-31 08:03:29 +00001633 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001634 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001635
Mike Stump3899a7f2009-06-05 23:26:36 +00001636 // FIXME: We'd like to put these into a mergable by content, with
1637 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001638 llvm::Function *Fn =
1639 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001640 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001641
1642 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001643 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001644
John McCallf0c11f72011-03-31 08:03:29 +00001645 FunctionDecl *FD = FunctionDecl::Create(Context,
1646 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001647 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001648 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001649 SC_Static,
1650 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001651 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001652
John McCallf0c11f72011-03-31 08:03:29 +00001653 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001654
John McCallf0c11f72011-03-31 08:03:29 +00001655 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001656 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001657
John McCallf0c11f72011-03-31 08:03:29 +00001658 // dst->x
1659 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1660 destField = CGF.Builder.CreateLoad(destField);
1661 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1662 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001663
John McCallf0c11f72011-03-31 08:03:29 +00001664 // src->x
1665 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1666 srcField = CGF.Builder.CreateLoad(srcField);
1667 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1668 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1669
1670 byrefInfo.emitCopy(CGF, destField, srcField);
1671 }
1672
1673 CGF.FinishFunction();
1674
1675 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001676}
1677
John McCallf0c11f72011-03-31 08:03:29 +00001678/// Build the copy helper for a __block variable.
1679static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001680 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001681 CodeGenModule::ByrefHelpers &info) {
1682 CodeGenFunction CGF(CGM);
1683 return generateByrefCopyHelper(CGF, byrefType, info);
1684}
1685
1686/// Generate code for a __block variable's dispose helper.
1687static llvm::Constant *
1688generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001689 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001690 CodeGenModule::ByrefHelpers &byrefInfo) {
1691 ASTContext &Context = CGF.getContext();
1692 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001693
John McCalld26bc762011-03-09 04:27:21 +00001694 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001695 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001696 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Mike Stump45031c02009-03-06 02:29:21 +00001698 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001699 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1700 FunctionType::ExtInfo(),
1701 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001702
John McCallf0c11f72011-03-31 08:03:29 +00001703 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001704 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001705
Mike Stump3899a7f2009-06-05 23:26:36 +00001706 // FIXME: We'd like to put these into a mergable by content, with
1707 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001708 llvm::Function *Fn =
1709 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001710 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001711 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001712
1713 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001714 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001715
John McCallf0c11f72011-03-31 08:03:29 +00001716 FunctionDecl *FD = FunctionDecl::Create(Context,
1717 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001718 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001719 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001720 SC_Static,
1721 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001722 false, false);
John McCallf0c11f72011-03-31 08:03:29 +00001723 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001724
John McCallf0c11f72011-03-31 08:03:29 +00001725 if (byrefInfo.needsDispose()) {
1726 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1727 V = CGF.Builder.CreateLoad(V);
1728 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1729 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001730
John McCallf0c11f72011-03-31 08:03:29 +00001731 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001732 }
Mike Stump45031c02009-03-06 02:29:21 +00001733
John McCallf0c11f72011-03-31 08:03:29 +00001734 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001735
John McCallf0c11f72011-03-31 08:03:29 +00001736 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001737}
1738
John McCallf0c11f72011-03-31 08:03:29 +00001739/// Build the dispose helper for a __block variable.
1740static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001741 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001742 CodeGenModule::ByrefHelpers &info) {
1743 CodeGenFunction CGF(CGM);
1744 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001745}
1746
John McCallf0c11f72011-03-31 08:03:29 +00001747///
1748template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001749 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001750 T &byrefInfo) {
1751 // Increase the field's alignment to be at least pointer alignment,
1752 // since the layout of the byref struct will guarantee at least that.
1753 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1754 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1755
1756 llvm::FoldingSetNodeID id;
1757 byrefInfo.Profile(id);
1758
1759 void *insertPos;
1760 CodeGenModule::ByrefHelpers *node
1761 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1762 if (node) return static_cast<T*>(node);
1763
1764 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1765 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1766
1767 T *copy = new (CGM.getContext()) T(byrefInfo);
1768 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1769 return copy;
1770}
1771
1772CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001773CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001774 const AutoVarEmission &emission) {
1775 const VarDecl &var = *emission.Variable;
1776 QualType type = var.getType();
1777
1778 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1779 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1780 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1781
1782 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1783 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1784 }
1785
John McCallf85e1932011-06-15 23:02:42 +00001786 // Otherwise, if we don't have a retainable type, there's nothing to do.
1787 // that the runtime does extra copies.
1788 if (!type->isObjCRetainableType()) return 0;
1789
1790 Qualifiers qs = type.getQualifiers();
1791
1792 // If we have lifetime, that dominates.
1793 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001794 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001795
1796 switch (lifetime) {
1797 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1798
1799 // These are just bits as far as the runtime is concerned.
1800 case Qualifiers::OCL_ExplicitNone:
1801 case Qualifiers::OCL_Autoreleasing:
1802 return 0;
1803
1804 // Tell the runtime that this is ARC __weak, called by the
1805 // byref routines.
1806 case Qualifiers::OCL_Weak: {
1807 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1808 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1809 }
1810
1811 // ARC __strong __block variables need to be retained.
1812 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001813 // Block pointers need to be copied, and there's no direct
1814 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001815 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001816 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001817 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1818
1819 // Otherwise, we transfer ownership of the retain from the stack
1820 // to the heap.
1821 } else {
1822 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1823 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1824 }
1825 }
1826 llvm_unreachable("fell out of lifetime switch!");
1827 }
1828
John McCallf0c11f72011-03-31 08:03:29 +00001829 BlockFieldFlags flags;
1830 if (type->isBlockPointerType()) {
1831 flags |= BLOCK_FIELD_IS_BLOCK;
1832 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1833 type->isObjCObjectPointerType()) {
1834 flags |= BLOCK_FIELD_IS_OBJECT;
1835 } else {
1836 return 0;
1837 }
1838
1839 if (type.isObjCGCWeak())
1840 flags |= BLOCK_FIELD_IS_WEAK;
1841
1842 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1843 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001844}
1845
John McCall5af02db2011-03-31 01:59:53 +00001846unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1847 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1848
1849 return ByRefValueInfo.find(VD)->second.second;
1850}
1851
1852llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1853 const VarDecl *V) {
1854 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1855 Loc = Builder.CreateLoad(Loc);
1856 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1857 V->getNameAsString());
1858 return Loc;
1859}
1860
1861/// BuildByRefType - This routine changes a __block variable declared as T x
1862/// into:
1863///
1864/// struct {
1865/// void *__isa;
1866/// void *__forwarding;
1867/// int32_t __flags;
1868/// int32_t __size;
1869/// void *__copy_helper; // only if needed
1870/// void *__destroy_helper; // only if needed
1871/// char padding[X]; // only if needed
1872/// T x;
1873/// } x
1874///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001875llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1876 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001877 if (Info.first)
1878 return Info.first;
1879
1880 QualType Ty = D->getType();
1881
Chris Lattner5f9e2722011-07-23 10:55:15 +00001882 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001883
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001884 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001885 llvm::StructType::create(getLLVMContext(),
1886 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001887
1888 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001889 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001890
1891 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001892 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001893
1894 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001895 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001896
1897 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001898 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001899
David Chisnall9595dae2012-04-04 13:07:13 +00001900 bool HasCopyAndDispose =
1901 (Ty->isObjCRetainableType()) || getContext().getBlockVarCopyInits(D);
John McCall5af02db2011-03-31 01:59:53 +00001902 if (HasCopyAndDispose) {
1903 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001904 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001905
1906 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001907 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001908 }
1909
1910 bool Packed = false;
1911 CharUnits Align = getContext().getDeclAlign(D);
1912 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1913 // We have to insert padding.
1914
1915 // The struct above has 2 32-bit integers.
1916 unsigned CurrentOffsetInBytes = 4 * 2;
1917
1918 // And either 2 or 4 pointers.
1919 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
Micah Villmow25a6a842012-10-08 16:25:52 +00001920 CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001921
1922 // Align the offset.
1923 unsigned AlignedOffsetInBytes =
1924 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1925
1926 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1927 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00001928 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00001929 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001930 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001931 if (NumPaddingBytes > 1)
1932 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1933
John McCall0774cb82011-05-15 01:53:33 +00001934 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001935
1936 // We want a packed struct.
1937 Packed = true;
1938 }
1939 }
1940
1941 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001942 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001943
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001944 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001945
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001946 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001947
John McCall0774cb82011-05-15 01:53:33 +00001948 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001949
1950 return Info.first;
1951}
1952
1953/// Initialize the structural components of a __block variable, i.e.
1954/// everything but the actual object.
1955void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001956 // Find the address of the local.
1957 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001958
John McCallf0c11f72011-03-31 08:03:29 +00001959 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001960 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001961 cast<llvm::PointerType>(addr->getType())->getElementType());
1962
1963 // Build the byref helpers if necessary. This is null if we don't need any.
1964 CodeGenModule::ByrefHelpers *helpers =
1965 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001966
1967 const VarDecl &D = *emission.Variable;
1968 QualType type = D.getType();
1969
John McCallf0c11f72011-03-31 08:03:29 +00001970 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001971
1972 // Initialize the 'isa', which is just 0 or 1.
1973 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001974 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001975 isa = 1;
1976 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1977 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1978
1979 // Store the address of the variable into its own forwarding pointer.
1980 Builder.CreateStore(addr,
1981 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1982
1983 // Blocks ABI:
1984 // c) the flags field is set to either 0 if no helper functions are
1985 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1986 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001987 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001988 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1989 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1990
John McCallf0c11f72011-03-31 08:03:29 +00001991 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1992 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001993 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1994
John McCallf0c11f72011-03-31 08:03:29 +00001995 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001996 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001997 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001998
1999 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002000 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002001 }
2002}
2003
John McCalld16c2cf2011-02-08 08:22:06 +00002004void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002005 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00002006 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00002007 V = Builder.CreateBitCast(V, Int8PtrTy);
2008 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00002009 Builder.CreateCall2(F, V, N);
2010}
John McCall5af02db2011-03-31 01:59:53 +00002011
2012namespace {
2013 struct CallBlockRelease : EHScopeStack::Cleanup {
2014 llvm::Value *Addr;
2015 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2016
John McCallad346f42011-07-12 20:27:29 +00002017 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002018 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002019 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2020 }
2021 };
2022}
2023
2024/// Enter a cleanup to destroy a __block variable. Note that this
2025/// cleanup should be a no-op if the variable hasn't left the stack
2026/// yet; if a cleanup is required for the variable itself, that needs
2027/// to be done externally.
2028void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2029 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002030 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002031 return;
2032
2033 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2034}
John McCall13db5cf2011-09-09 20:41:01 +00002035
2036/// Adjust the declaration of something from the blocks API.
2037static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2038 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002039 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002040
2041 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2042 if (GV->isDeclaration() &&
2043 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2044 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2045}
2046
2047llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2048 if (BlockObjectDispose)
2049 return BlockObjectDispose;
2050
2051 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2052 llvm::FunctionType *fty
2053 = llvm::FunctionType::get(VoidTy, args, false);
2054 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2055 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2056 return BlockObjectDispose;
2057}
2058
2059llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2060 if (BlockObjectAssign)
2061 return BlockObjectAssign;
2062
2063 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2064 llvm::FunctionType *fty
2065 = llvm::FunctionType::get(VoidTy, args, false);
2066 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2067 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2068 return BlockObjectAssign;
2069}
2070
2071llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2072 if (NSConcreteGlobalBlock)
2073 return NSConcreteGlobalBlock;
2074
2075 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2076 Int8PtrTy->getPointerTo(), 0);
2077 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2078 return NSConcreteGlobalBlock;
2079}
2080
2081llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2082 if (NSConcreteStackBlock)
2083 return NSConcreteStackBlock;
2084
2085 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2086 Int8PtrTy->getPointerTo(), 0);
2087 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2088 return NSConcreteStackBlock;
2089}