blob: 69449b1aa5a8838ec4efbe064147915d429a13f2 [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>
Fariborz Jahanian7d4b9fa2012-11-14 17:43:08 +000024#include <cstdio>
Torok Edwinf42e4a62009-08-24 13:25:12 +000025
Anders Carlssonacfde802009-02-12 00:39:25 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall1a343eb2011-11-10 08:15:53 +000029CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
30 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanianf22ae652012-11-01 18:32:55 +000031 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
32 StructureType(0), Block(block),
John McCall6f103ba2011-11-10 10:43:54 +000033 DominatingIP(0) {
John McCallee504292010-05-21 04:11:14 +000034
John McCall1a343eb2011-11-10 08:15:53 +000035 // Skip asm prefix, if any. 'name' is usually taken directly from
36 // the mangled name of the enclosing function.
37 if (!name.empty() && name[0] == '\01')
38 name = name.substr(1);
John McCallee504292010-05-21 04:11:14 +000039}
40
John McCallf0c11f72011-03-31 08:03:29 +000041// Anchor the vtable to this translation unit.
42CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
43
John McCall6b5a61b2011-02-07 10:33:21 +000044/// Build the given block as a global block.
45static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
46 const CGBlockInfo &blockInfo,
47 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000048
John McCall6b5a61b2011-02-07 10:33:21 +000049/// Build the helper function to copy a block.
50static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
51 const CGBlockInfo &blockInfo) {
52 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
53}
54
55/// Build the helper function to dipose of a block.
56static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
57 const CGBlockInfo &blockInfo) {
58 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
59}
60
Fariborz Jahanianaf879c02012-10-25 18:06:53 +000061/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
62/// buildBlockDescriptor is accessed from 5th field of the Block_literal
63/// meta-data and contains stationary information about the block literal.
64/// Its definition will have 4 (or optinally 6) words.
65/// struct Block_descriptor {
66/// unsigned long reserved;
67/// unsigned long size; // size of Block_literal metadata in bytes.
68/// void *copy_func_helper_decl; // optional copy helper.
69/// void *destroy_func_decl; // optioanl destructor helper.
70/// void *block_method_encoding_address;//@encode for block literal signature.
71/// void *block_layout_info; // encoding of captured block variables.
72/// };
John McCall6b5a61b2011-02-07 10:33:21 +000073static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
74 const CGBlockInfo &blockInfo) {
75 ASTContext &C = CGM.getContext();
76
Chris Lattner2acc6e32011-07-18 04:24:23 +000077 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
78 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000079
Chris Lattner5f9e2722011-07-23 10:55:15 +000080 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000081
82 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000083 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000084
85 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000086 // FIXME: What is the right way to say this doesn't fit? We should give
87 // a user diagnostic in that case. Better fix would be to change the
88 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000089 elements.push_back(llvm::ConstantInt::get(ulong,
90 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000091
John McCall6b5a61b2011-02-07 10:33:21 +000092 // Optional copy/dispose helpers.
93 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000094 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000095 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000096
97 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000098 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000099 }
100
John McCall6b5a61b2011-02-07 10:33:21 +0000101 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
102 std::string typeAtEncoding =
103 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
104 elements.push_back(llvm::ConstantExpr::getBitCast(
105 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000106
John McCall6b5a61b2011-02-07 10:33:21 +0000107 // GC layout.
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000108 if (C.getLangOpts().ObjC1) {
109 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
110 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
111 else
112 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
113 }
John McCall6b5a61b2011-02-07 10:33:21 +0000114 else
115 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000116
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000117 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000118
John McCall6b5a61b2011-02-07 10:33:21 +0000119 llvm::GlobalVariable *global =
120 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
121 llvm::GlobalValue::InternalLinkage,
122 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000123
John McCall6b5a61b2011-02-07 10:33:21 +0000124 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000125}
126
John McCall6b5a61b2011-02-07 10:33:21 +0000127/*
128 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000129
John McCall6b5a61b2011-02-07 10:33:21 +0000130 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
131 struct Block_literal {
132 /// Initialized to one of:
133 /// extern void *_NSConcreteStackBlock[];
134 /// extern void *_NSConcreteGlobalBlock[];
135 ///
136 /// In theory, we could start one off malloc'ed by setting
137 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
138 /// this isa:
139 /// extern void *_NSConcreteMallocBlock[];
140 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000141
John McCall6b5a61b2011-02-07 10:33:21 +0000142 /// These are the flags (with corresponding bit number) that the
143 /// compiler is actually supposed to know about.
144 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
145 /// descriptor provides copy and dispose helper functions
146 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
147 /// object with a nontrivial destructor or copy constructor
148 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
149 /// as global memory
150 /// 29. BLOCK_USE_STRET - indicates that the block function
151 /// uses stret, which objc_msgSend needs to know about
152 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
153 /// @encoded signature string
154 /// And we're not supposed to manipulate these:
155 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
156 /// to malloc'ed memory
157 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
158 /// to GC-allocated memory
159 /// Additionally, the bottom 16 bits are a reference count which
160 /// should be zero on the stack.
161 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163 /// Reserved; should be zero-initialized.
164 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000165
John McCall6b5a61b2011-02-07 10:33:21 +0000166 /// Function pointer generated from block literal.
167 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000168
John McCall6b5a61b2011-02-07 10:33:21 +0000169 /// Block description metadata generated from block literal.
170 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000171
John McCall6b5a61b2011-02-07 10:33:21 +0000172 /// Captured values follow.
173 _CapturesTypes captures...;
174 };
175 */
David Chisnall5e530af2009-11-17 19:33:30 +0000176
John McCall6b5a61b2011-02-07 10:33:21 +0000177/// The number of fields in a block header.
178const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000179
John McCall6b5a61b2011-02-07 10:33:21 +0000180namespace {
181 /// A chunk of data that we actually have to capture in the block.
182 struct BlockLayoutChunk {
183 CharUnits Alignment;
184 CharUnits Size;
185 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000186 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000187
John McCall6b5a61b2011-02-07 10:33:21 +0000188 BlockLayoutChunk(CharUnits align, CharUnits size,
189 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000190 llvm::Type *type)
John McCall6b5a61b2011-02-07 10:33:21 +0000191 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000192
John McCall6b5a61b2011-02-07 10:33:21 +0000193 /// Tell the block info that this chunk has the given field index.
194 void setIndex(CGBlockInfo &info, unsigned index) {
195 if (!Capture)
196 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000197 else
John McCall6b5a61b2011-02-07 10:33:21 +0000198 info.Captures[Capture->getVariable()]
199 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000200 }
John McCall6b5a61b2011-02-07 10:33:21 +0000201 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000202
John McCall6b5a61b2011-02-07 10:33:21 +0000203 /// Order by descending alignment.
204 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
205 return left.Alignment > right.Alignment;
206 }
207}
208
John McCall461c9c12011-02-08 03:07:00 +0000209/// Determines if the given type is safe for constant capture in C++.
210static bool isSafeForCXXConstantCapture(QualType type) {
211 const RecordType *recordType =
212 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
213
214 // Only records can be unsafe.
215 if (!recordType) return true;
216
217 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
218
219 // Maintain semantics for classes with non-trivial dtors or copy ctors.
220 if (!record->hasTrivialDestructor()) return false;
221 if (!record->hasTrivialCopyConstructor()) return false;
222
223 // Otherwise, we just have to make sure there aren't any mutable
224 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000225 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000226}
227
John McCall6b5a61b2011-02-07 10:33:21 +0000228/// It is illegal to modify a const object after initialization.
229/// Therefore, if a const object has a constant initializer, we don't
230/// actually need to keep storage for it in the block; we'll just
231/// rematerialize it at the start of the block function. This is
232/// acceptable because we make no promises about address stability of
233/// captured variables.
234static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000235 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000236 const VarDecl *var) {
237 QualType type = var->getType();
238
239 // We can only do this if the variable is const.
240 if (!type.isConstQualified()) return 0;
241
John McCall461c9c12011-02-08 03:07:00 +0000242 // Furthermore, in C++ we have to worry about mutable fields:
243 // C++ [dcl.type.cv]p4:
244 // Except that any class member declared mutable can be
245 // modified, any attempt to modify a const object during its
246 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000247 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000248 return 0;
249
250 // If the variable doesn't have any initializer (shouldn't this be
251 // invalid?), it's not clear what we should do. Maybe capture as
252 // zero?
253 const Expr *init = var->getInit();
254 if (!init) return 0;
255
Richard Smith2d6a5672012-01-14 04:30:29 +0000256 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000257}
258
259/// Get the low bit of a nonzero character count. This is the
260/// alignment of the nth byte if the 0th byte is universally aligned.
261static CharUnits getLowBit(CharUnits v) {
262 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
263}
264
265static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000266 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000267 ASTContext &C = CGM.getContext();
268
269 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
270 CharUnits ptrSize, ptrAlign, intSize, intAlign;
271 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
272 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
273
274 // Are there crazy embedded platforms where this isn't true?
275 assert(intSize <= ptrSize && "layout assumptions horribly violated");
276
277 CharUnits headerSize = ptrSize;
278 if (2 * intSize < ptrAlign) headerSize += ptrSize;
279 else headerSize += 2 * intSize;
280 headerSize += 2 * ptrSize;
281
282 info.BlockAlign = ptrAlign;
283 info.BlockSize = headerSize;
284
285 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000286 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
287 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000288 elementTypes.push_back(i8p);
289 elementTypes.push_back(intTy);
290 elementTypes.push_back(intTy);
291 elementTypes.push_back(i8p);
292 elementTypes.push_back(CGM.getBlockDescriptorType());
293
294 assert(elementTypes.size() == BlockHeaderSize);
295}
296
297/// Compute the layout of the given block. Attempts to lay the block
298/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000299static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
300 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000301 ASTContext &C = CGM.getContext();
302 const BlockDecl *block = info.getBlockDecl();
303
Chris Lattner5f9e2722011-07-23 10:55:15 +0000304 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000305 initializeForBlockHeader(CGM, info, elementTypes);
306
307 if (!block->hasCaptures()) {
308 info.StructureType =
309 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
310 info.CanBeGlobal = true;
311 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000312 }
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000313 else if (C.getLangOpts().ObjC1 &&
314 CGM.getLangOpts().getGC() == LangOptions::NonGC)
315 info.HasCapturedVariableLayout = true;
316
John McCall6b5a61b2011-02-07 10:33:21 +0000317 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000318 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000319 layout.reserve(block->capturesCXXThis() +
320 (block->capture_end() - block->capture_begin()));
321
322 CharUnits maxFieldAlign;
323
324 // First, 'this'.
325 if (block->capturesCXXThis()) {
326 const DeclContext *DC = block->getDeclContext();
327 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
328 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000329 QualType thisType;
330 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
331 thisType = C.getPointerType(C.getRecordType(RD));
332 else
333 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000334
Jay Foadef6de3d2011-07-11 09:56:20 +0000335 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000336 std::pair<CharUnits,CharUnits> tinfo
337 = CGM.getContext().getTypeInfoInChars(thisType);
338 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
339
340 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
341 }
342
343 // Next, all the block captures.
344 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
345 ce = block->capture_end(); ci != ce; ++ci) {
346 const VarDecl *variable = ci->getVariable();
347
348 if (ci->isByRef()) {
349 // We have to copy/dispose of the __block reference.
350 info.NeedsCopyDispose = true;
351
John McCall6b5a61b2011-02-07 10:33:21 +0000352 // Just use void* instead of a pointer to the byref type.
353 QualType byRefPtrTy = C.VoidPtrTy;
354
Jay Foadef6de3d2011-07-11 09:56:20 +0000355 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000356 std::pair<CharUnits,CharUnits> tinfo
357 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
358 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
359
360 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
361 &*ci, llvmType));
362 continue;
363 }
364
365 // Otherwise, build a layout chunk with the size and alignment of
366 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000367 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000368 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
369 continue;
370 }
371
John McCallf85e1932011-06-15 23:02:42 +0000372 // If we have a lifetime qualifier, honor it for capture purposes.
373 // That includes *not* copying it if it's __unsafe_unretained.
374 if (Qualifiers::ObjCLifetime lifetime
375 = variable->getType().getObjCLifetime()) {
376 switch (lifetime) {
377 case Qualifiers::OCL_None: llvm_unreachable("impossible");
378 case Qualifiers::OCL_ExplicitNone:
379 case Qualifiers::OCL_Autoreleasing:
380 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000381
John McCallf85e1932011-06-15 23:02:42 +0000382 case Qualifiers::OCL_Strong:
383 case Qualifiers::OCL_Weak:
384 info.NeedsCopyDispose = true;
385 }
386
387 // Block pointers require copy/dispose. So do Objective-C pointers.
388 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000389 info.NeedsCopyDispose = true;
390
391 // So do types that require non-trivial copy construction.
392 } else if (ci->hasCopyExpr()) {
393 info.NeedsCopyDispose = true;
394 info.HasCXXObject = true;
395
396 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000397 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000398 if (const CXXRecordDecl *record =
399 variable->getType()->getAsCXXRecordDecl()) {
400 if (!record->hasTrivialDestructor()) {
401 info.HasCXXObject = true;
402 info.NeedsCopyDispose = true;
403 }
404 }
405 }
406
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000407 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000408 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000409 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000410
John McCall6b5a61b2011-02-07 10:33:21 +0000411 maxFieldAlign = std::max(maxFieldAlign, align);
412
Jay Foadef6de3d2011-07-11 09:56:20 +0000413 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000414 CGM.getTypes().ConvertTypeForMem(VT);
415
John McCall6b5a61b2011-02-07 10:33:21 +0000416 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
417 }
418
419 // If that was everything, we're done here.
420 if (layout.empty()) {
421 info.StructureType =
422 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
423 info.CanBeGlobal = true;
424 return;
425 }
426
427 // Sort the layout by alignment. We have to use a stable sort here
428 // to get reproducible results. There should probably be an
429 // llvm::array_pod_stable_sort.
430 std::stable_sort(layout.begin(), layout.end());
431
432 CharUnits &blockSize = info.BlockSize;
433 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
434
435 // Assuming that the first byte in the header is maximally aligned,
436 // get the alignment of the first byte following the header.
437 CharUnits endAlign = getLowBit(blockSize);
438
439 // If the end of the header isn't satisfactorily aligned for the
440 // maximum thing, look for things that are okay with the header-end
441 // alignment, and keep appending them until we get something that's
442 // aligned right. This algorithm is only guaranteed optimal if
443 // that condition is satisfied at some point; otherwise we can get
444 // things like:
445 // header // next byte has alignment 4
446 // something_with_size_5; // next byte has alignment 1
447 // something_with_alignment_8;
448 // which has 7 bytes of padding, as opposed to the naive solution
449 // which might have less (?).
450 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000451 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000452 li = layout.begin() + 1, le = layout.end();
453
454 // Look for something that the header end is already
455 // satisfactorily aligned for.
456 for (; li != le && endAlign < li->Alignment; ++li)
457 ;
458
459 // If we found something that's naturally aligned for the end of
460 // the header, keep adding things...
461 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000462 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000463 for (; li != le; ++li) {
464 assert(endAlign >= li->Alignment);
465
466 li->setIndex(info, elementTypes.size());
467 elementTypes.push_back(li->Type);
468 blockSize += li->Size;
469 endAlign = getLowBit(blockSize);
470
471 // ...until we get to the alignment of the maximum field.
472 if (endAlign >= maxFieldAlign)
473 break;
474 }
475
476 // Don't re-append everything we just appended.
477 layout.erase(first, li);
478 }
479 }
480
John McCall6ea48412012-04-26 21:14:42 +0000481 assert(endAlign == getLowBit(blockSize));
482
John McCall6b5a61b2011-02-07 10:33:21 +0000483 // At this point, we just have to add padding if the end align still
484 // isn't aligned right.
485 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000486 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
487 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000488
John McCall5936e332011-02-15 09:22:45 +0000489 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
490 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000491 blockSize = newBlockSize;
John McCall6c803f72012-05-01 20:28:00 +0000492 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall6b5a61b2011-02-07 10:33:21 +0000493 }
494
John McCall6c803f72012-05-01 20:28:00 +0000495 assert(endAlign >= maxFieldAlign);
John McCall6ea48412012-04-26 21:14:42 +0000496 assert(endAlign == getLowBit(blockSize));
497
John McCall6b5a61b2011-02-07 10:33:21 +0000498 // Slam everything else on now. This works because they have
499 // strictly decreasing alignment and we expect that size is always a
500 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000501 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000502 li = layout.begin(), le = layout.end(); li != le; ++li) {
503 assert(endAlign >= li->Alignment);
504 li->setIndex(info, elementTypes.size());
505 elementTypes.push_back(li->Type);
506 blockSize += li->Size;
507 endAlign = getLowBit(blockSize);
508 }
509
510 info.StructureType =
511 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
512}
513
John McCall1a343eb2011-11-10 08:15:53 +0000514/// Enter the scope of a block. This should be run at the entrance to
515/// a full-expression so that the block's cleanups are pushed at the
516/// right place in the stack.
517static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000518 assert(CGF.HaveInsertPoint());
519
John McCall1a343eb2011-11-10 08:15:53 +0000520 // Allocate the block info and place it at the head of the list.
521 CGBlockInfo &blockInfo =
522 *new CGBlockInfo(block, CGF.CurFn->getName());
523 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
524 CGF.FirstBlockInfo = &blockInfo;
525
526 // Compute information about the layout, etc., of this block,
527 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000528 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000529
530 // Nothing else to do if it can be global.
531 if (blockInfo.CanBeGlobal) return;
532
533 // Make the allocation for the block.
534 blockInfo.Address =
535 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
536 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
537
538 // If there are cleanups to emit, enter them (but inactive).
539 if (!blockInfo.NeedsCopyDispose) return;
540
541 // Walk through the captures (in order) and find the ones not
542 // captured by constant.
543 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
544 ce = block->capture_end(); ci != ce; ++ci) {
545 // Ignore __block captures; there's nothing special in the
546 // on-stack block that we need to do for them.
547 if (ci->isByRef()) continue;
548
549 // Ignore variables that are constant-captured.
550 const VarDecl *variable = ci->getVariable();
551 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
552 if (capture.isConstant()) continue;
553
554 // Ignore objects that aren't destructed.
555 QualType::DestructionKind dtorKind =
556 variable->getType().isDestructedType();
557 if (dtorKind == QualType::DK_none) continue;
558
559 CodeGenFunction::Destroyer *destroyer;
560
561 // Block captures count as local values and have imprecise semantics.
562 // They also can't be arrays, so need to worry about that.
563 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000564 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000565 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000566 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000567 }
568
569 // GEP down to the address.
570 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
571 capture.getIndex());
572
John McCall6f103ba2011-11-10 10:43:54 +0000573 // We can use that GEP as the dominating IP.
574 if (!blockInfo.DominatingIP)
575 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
576
John McCall1a343eb2011-11-10 08:15:53 +0000577 CleanupKind cleanupKind = InactiveNormalCleanup;
578 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
579 if (useArrayEHCleanup)
580 cleanupKind = InactiveNormalAndEHCleanup;
581
582 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000583 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000584
585 // Remember where that cleanup was.
586 capture.setCleanup(CGF.EHStack.stable_begin());
587 }
588}
589
590/// Enter a full-expression with a non-trivial number of objects to
591/// clean up. This is in this file because, at the moment, the only
592/// kind of cleanup object is a BlockDecl*.
593void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
594 assert(E->getNumObjects() != 0);
595 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
596 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
597 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
598 enterBlockScope(*this, *i);
599 }
600}
601
602/// Find the layout for the given block in a linked list and remove it.
603static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
604 const BlockDecl *block) {
605 while (true) {
606 assert(head && *head);
607 CGBlockInfo *cur = *head;
608
609 // If this is the block we're looking for, splice it out of the list.
610 if (cur->getBlockDecl() == block) {
611 *head = cur->NextBlockInfo;
612 return cur;
613 }
614
615 head = &cur->NextBlockInfo;
616 }
617}
618
619/// Destroy a chain of block layouts.
620void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
621 assert(head && "destroying an empty chain");
622 do {
623 CGBlockInfo *cur = head;
624 head = cur->NextBlockInfo;
625 delete cur;
626 } while (head != 0);
627}
628
John McCall6b5a61b2011-02-07 10:33:21 +0000629/// Emit a block literal expression in the current function.
630llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000631 // If the block has no captures, we won't have a pre-computed
632 // layout for it.
633 if (!blockExpr->getBlockDecl()->hasCaptures()) {
634 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000635 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000636 blockInfo.BlockExpression = blockExpr;
637 return EmitBlockLiteral(blockInfo);
638 }
John McCall6b5a61b2011-02-07 10:33:21 +0000639
John McCall1a343eb2011-11-10 08:15:53 +0000640 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000641 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000642 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
643 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000644
John McCall1a343eb2011-11-10 08:15:53 +0000645 blockInfo->BlockExpression = blockExpr;
646 return EmitBlockLiteral(*blockInfo);
647}
648
649llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
650 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000651 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000652 llvm::Constant *blockFn
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000653 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000654 CurFuncDecl, LocalDeclMap,
Eli Friedman23f02672012-03-01 04:01:32 +0000655 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000656 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000657
658 // If there is nothing to capture, we can emit this as a global block.
659 if (blockInfo.CanBeGlobal)
660 return buildGlobalBlock(CGM, blockInfo, blockFn);
661
662 // Otherwise, we have to emit this as a local block.
663
664 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000665 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000666
667 // Build the block descriptor.
668 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
669
John McCall1a343eb2011-11-10 08:15:53 +0000670 llvm::AllocaInst *blockAddr = blockInfo.Address;
671 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000672
673 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000674 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000675 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall6b5a61b2011-02-07 10:33:21 +0000676 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
677 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000678 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000679
680 // Initialize the block literal.
681 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000682 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000683 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000684 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000685 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
686 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
687 "block.invoke"));
688 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
689 "block.descriptor"));
690
691 // Finally, capture all the values into the block.
692 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
693
694 // First, 'this'.
695 if (blockDecl->capturesCXXThis()) {
696 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
697 blockInfo.CXXThisIndex,
698 "block.captured-this.addr");
699 Builder.CreateStore(LoadCXXThis(), addr);
700 }
701
702 // Next, captured variables.
703 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
704 ce = blockDecl->capture_end(); ci != ce; ++ci) {
705 const VarDecl *variable = ci->getVariable();
706 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
707
708 // Ignore constant captures.
709 if (capture.isConstant()) continue;
710
711 QualType type = variable->getType();
712
713 // This will be a [[type]]*, except that a byref entry will just be
714 // an i8**.
715 llvm::Value *blockField =
716 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
717 "block.captured");
718
719 // Compute the address of the thing we're going to move into the
720 // block literal.
721 llvm::Value *src;
Douglas Gregor29a93f82012-05-16 16:50:20 +0000722 if (BlockInfo && ci->isNested()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000723 // We need to use the capture from the enclosing block.
724 const CGBlockInfo::Capture &enclosingCapture =
725 BlockInfo->getCapture(variable);
726
727 // This is a [[type]]*, except that a byref entry wil just be an i8**.
728 src = Builder.CreateStructGEP(LoadBlockStruct(),
729 enclosingCapture.getIndex(),
730 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000731 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000732 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000733 // special; we'll simply emit it directly.
734 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000735 } else {
736 // This is a [[type]]*.
737 src = LocalDeclMap[variable];
738 }
739
740 // For byrefs, we just write the pointer to the byref struct into
741 // the block field. There's no need to chase the forwarding
742 // pointer at this point, since we're building something that will
743 // live a shorter life than the stack byref anyway.
744 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000745 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000746 if (ci->isNested())
747 src = Builder.CreateLoad(src, "byref.capture");
748 else
John McCall5936e332011-02-15 09:22:45 +0000749 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000750
John McCall5936e332011-02-15 09:22:45 +0000751 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000752 Builder.CreateStore(src, blockField);
753
754 // If we have a copy constructor, evaluate that into the block field.
755 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000756 if (blockDecl->isConversionFromLambda()) {
757 // If we have a lambda conversion, emit the expression
758 // directly into the block instead.
759 CharUnits Align = getContext().getTypeAlignInChars(type);
760 AggValueSlot Slot =
761 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
762 AggValueSlot::IsDestructed,
763 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000764 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000765 EmitAggExpr(copyExpr, Slot);
766 } else {
767 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
768 }
John McCall6b5a61b2011-02-07 10:33:21 +0000769
770 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000771 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000772 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
773
774 // Otherwise, fake up a POD copy into the block field.
775 } else {
John McCallf85e1932011-06-15 23:02:42 +0000776 // Fake up a new variable so that EmitScalarInit doesn't think
777 // we're referring to the variable in its own initializer.
778 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000779 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000780
John McCallbb699b02011-02-07 18:37:40 +0000781 // We use one of these or the other depending on whether the
782 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000783 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
784 /*refersToEnclosing*/ ci->isNested(), type,
785 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000786
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000787 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000788 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000789 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000790 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000791 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000792 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000793 }
794
John McCall1a343eb2011-11-10 08:15:53 +0000795 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000796 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000797 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
798 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000799 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000800 }
John McCall6b5a61b2011-02-07 10:33:21 +0000801 }
802
803 // Cast to the converted block-pointer type, which happens (somewhat
804 // unfortunately) to be a pointer to function type.
805 llvm::Value *result =
806 Builder.CreateBitCast(blockAddr,
807 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000808
John McCall6b5a61b2011-02-07 10:33:21 +0000809 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000810}
811
812
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000813llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000814 if (BlockDescriptorType)
815 return BlockDescriptorType;
816
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000817 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000818 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000819
Mike Stumpab695142009-02-13 15:16:56 +0000820 // struct __block_descriptor {
821 // unsigned long reserved;
822 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000823 //
824 // // later, the following will be added
825 //
826 // struct {
827 // void (*copyHelper)();
828 // void (*copyHelper)();
829 // } helpers; // !!! optional
830 //
831 // const char *signature; // the block signature
832 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000833 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000834 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000835 llvm::StructType::create("struct.__block_descriptor",
836 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000837
John McCall6b5a61b2011-02-07 10:33:21 +0000838 // Now form a pointer to that.
839 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000840 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000841}
842
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000843llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000844 if (GenericBlockLiteralType)
845 return GenericBlockLiteralType;
846
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000847 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000848
Mike Stump9b8a7972009-02-13 15:25:34 +0000849 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000850 // void *__isa;
851 // int __flags;
852 // int __reserved;
853 // void (*__invoke)(void *);
854 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000855 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000856 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000857 llvm::StructType::create("struct.__block_literal_generic",
858 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
859 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000860
Mike Stump9b8a7972009-02-13 15:25:34 +0000861 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000862}
863
Mike Stumpbd65cac2009-02-19 01:01:04 +0000864
Anders Carlssona1736c02009-12-24 21:13:40 +0000865RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
866 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000867 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000868 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000869
Anders Carlssonacfde802009-02-12 00:39:25 +0000870 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
871
872 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000873 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000874 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000875
876 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000877 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000878 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
879
880 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000881 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000882
Benjamin Kramer578faa82011-09-27 21:06:10 +0000883 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000884
Anders Carlssonacfde802009-02-12 00:39:25 +0000885 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000886 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000887 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000888
Anders Carlsson782f3972009-04-08 23:13:16 +0000889 QualType FnType = BPT->getPointeeType();
890
Anders Carlssonacfde802009-02-12 00:39:25 +0000891 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000892 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000893 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000894
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000895 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000896 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000897
John McCall64cd2322011-03-09 08:39:33 +0000898 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000899 const CGFunctionInfo &FnInfo =
John McCall0f3d0972012-07-07 06:41:13 +0000900 CGM.getTypes().arrangeFreeFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000902 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000903 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Chris Lattner2acc6e32011-07-18 04:24:23 +0000905 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000906 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Anders Carlssonacfde802009-02-12 00:39:25 +0000908 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000909 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000910}
Anders Carlssond5cab542009-02-12 17:55:02 +0000911
John McCall6b5a61b2011-02-07 10:33:21 +0000912llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
913 bool isByRef) {
914 assert(BlockInfo && "evaluating block ref without block information?");
915 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000916
John McCall6b5a61b2011-02-07 10:33:21 +0000917 // Handle constant captures.
918 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000919
John McCall6b5a61b2011-02-07 10:33:21 +0000920 llvm::Value *addr =
921 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
922 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000923
John McCall6b5a61b2011-02-07 10:33:21 +0000924 if (isByRef) {
925 // addr should be a void** right now. Load, then cast the result
926 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000927
John McCall6b5a61b2011-02-07 10:33:21 +0000928 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000929 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000930 = llvm::PointerType::get(BuildByRefType(variable), 0);
931 addr = Builder.CreateBitCast(addr, byrefPointerType,
932 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000933
John McCall6b5a61b2011-02-07 10:33:21 +0000934 // Follow the forwarding pointer.
935 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
936 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000937
John McCall6b5a61b2011-02-07 10:33:21 +0000938 // Cast back to byref* and GEP over to the actual object.
939 addr = Builder.CreateBitCast(addr, byrefPointerType);
940 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
941 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000942 }
943
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000944 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000945 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000946
John McCall6b5a61b2011-02-07 10:33:21 +0000947 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000948}
949
Mike Stump67a64482009-02-14 22:16:35 +0000950llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000951CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000952 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000953 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
954 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000955
John McCall6b5a61b2011-02-07 10:33:21 +0000956 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +0000957 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000958
John McCall6b5a61b2011-02-07 10:33:21 +0000959 // Using that metadata, generate the actual block function.
960 llvm::Constant *blockFn;
961 {
962 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000963 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
964 blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000965 0, LocalDeclMap,
966 false);
John McCall6b5a61b2011-02-07 10:33:21 +0000967 }
John McCall5936e332011-02-15 09:22:45 +0000968 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000969
John McCalld16c2cf2011-02-08 08:22:06 +0000970 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000971}
972
John McCall6b5a61b2011-02-07 10:33:21 +0000973static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
974 const CGBlockInfo &blockInfo,
975 llvm::Constant *blockFn) {
976 assert(blockInfo.CanBeGlobal);
977
978 // Generate the constants for the block literal initializer.
979 llvm::Constant *fields[BlockHeaderSize];
980
981 // isa
982 fields[0] = CGM.getNSConcreteGlobalBlock();
983
984 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000985 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
986 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
987
John McCall5936e332011-02-15 09:22:45 +0000988 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000989
990 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000991 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000992
993 // Function
994 fields[3] = blockFn;
995
996 // Descriptor
997 fields[4] = buildBlockDescriptor(CGM, blockInfo);
998
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000999 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +00001000
1001 llvm::GlobalVariable *literal =
1002 new llvm::GlobalVariable(CGM.getModule(),
1003 init->getType(),
1004 /*constant*/ true,
1005 llvm::GlobalVariable::InternalLinkage,
1006 init,
1007 "__block_literal_global");
1008 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1009
1010 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001011 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +00001012 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1013 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +00001014}
1015
Mike Stump00470a12009-03-05 08:32:30 +00001016llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +00001017CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1018 const CGBlockInfo &blockInfo,
1019 const Decl *outerFnDecl,
Eli Friedman64bee652012-02-25 02:48:22 +00001020 const DeclMapTy &ldm,
1021 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001022 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001023
Devang Patel6d1155b2011-03-07 21:53:18 +00001024 // Check if we should generate debug info for this block function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001025 maybeInitializeDebugInfo();
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001026 CurGD = GD;
1027
John McCall6b5a61b2011-02-07 10:33:21 +00001028 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Mike Stump7f28a9c2009-03-13 23:34:28 +00001030 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001031 // to be local to this function as well, in case they're directly
1032 // referenced in a block.
1033 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1034 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1035 if (var && !var->hasLocalStorage())
1036 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001037 }
1038
John McCall6b5a61b2011-02-07 10:33:21 +00001039 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001040
John McCall6b5a61b2011-02-07 10:33:21 +00001041 // Build the argument list.
1042 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001043
John McCall6b5a61b2011-02-07 10:33:21 +00001044 // The first argument is the block pointer. Just take it as a void*
1045 // and cast it later.
1046 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001047 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001048
John McCall8178df32011-02-22 22:38:33 +00001049 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1050 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001051 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001052
John McCall6b5a61b2011-02-07 10:33:21 +00001053 // Now add the rest of the parameters.
1054 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1055 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001056 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001057
John McCall6b5a61b2011-02-07 10:33:21 +00001058 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001059 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001060 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001061 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1062 fnType->getExtInfo(),
1063 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001064 if (CGM.ReturnTypeUsesSRet(fnInfo))
1065 blockInfo.UsesStret = true;
1066
John McCallde5d3c72012-02-17 03:33:10 +00001067 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001068
John McCall6b5a61b2011-02-07 10:33:21 +00001069 MangleBuffer name;
1070 CGM.getBlockMangledName(GD, name, blockDecl);
1071 llvm::Function *fn =
1072 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1073 name.getString(), &CGM.getModule());
1074 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001075
John McCall6b5a61b2011-02-07 10:33:21 +00001076 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001077 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001078 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001079 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001080
John McCall8178df32011-02-22 22:38:33 +00001081 // Okay. Undo some of what StartFunction did.
1082
1083 // Pull the 'self' reference out of the local decl map.
1084 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1085 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001086 BlockPointer = Builder.CreateBitCast(blockAddr,
1087 blockInfo.StructureType->getPointerTo(),
1088 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001089
John McCallea1471e2010-05-20 01:18:31 +00001090 // If we have a C++ 'this' reference, go ahead and force it into
1091 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001092 if (blockDecl->capturesCXXThis()) {
1093 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1094 blockInfo.CXXThisIndex,
1095 "block.captured-this");
1096 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001097 }
1098
John McCall6b5a61b2011-02-07 10:33:21 +00001099 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1100 // appease it.
1101 if (const ObjCMethodDecl *method
1102 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1103 const VarDecl *self = method->getSelfDecl();
1104
1105 // There might not be a capture for 'self', but if there is...
1106 if (blockInfo.Captures.count(self)) {
1107 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1108 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1109 capture.getIndex(),
1110 "block.captured-self");
1111 LocalDeclMap[self] = selfAddr;
1112 }
1113 }
1114
1115 // Also force all the constant captures.
1116 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1117 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1118 const VarDecl *variable = ci->getVariable();
1119 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1120 if (!capture.isConstant()) continue;
1121
1122 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1123
1124 llvm::AllocaInst *alloca =
1125 CreateMemTemp(variable->getType(), "block.captured-const");
1126 alloca->setAlignment(align);
1127
1128 Builder.CreateStore(capture.getConstant(), alloca, align);
1129
1130 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001131 }
1132
John McCallf4b88a42012-03-10 09:33:50 +00001133 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001134 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1135 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1136 --entry_ptr;
1137
Eli Friedman64bee652012-02-25 02:48:22 +00001138 if (IsLambdaConversionToBlock)
1139 EmitLambdaBlockInvokeBody();
1140 else
1141 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001142
Mike Stumpde8c5c72009-10-01 00:27:30 +00001143 // Remember where we were...
1144 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001145
Mike Stumpde8c5c72009-10-01 00:27:30 +00001146 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001147 ++entry_ptr;
1148 Builder.SetInsertPoint(entry, entry_ptr);
1149
John McCallf4b88a42012-03-10 09:33:50 +00001150 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001151 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001152 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001153 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1154 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1155 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001156 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001157
Douglas Gregor4cdad312012-10-23 20:05:01 +00001158 if (CGM.getCodeGenOpts().getDebugInfo()
1159 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001160 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1161 if (capture.isConstant()) {
1162 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1163 Builder);
1164 continue;
1165 }
John McCall6b5a61b2011-02-07 10:33:21 +00001166
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001167 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1168 Builder, blockInfo);
1169 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001170 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001171 }
John McCall6b5a61b2011-02-07 10:33:21 +00001172
Mike Stumpde8c5c72009-10-01 00:27:30 +00001173 // And resume where we left off.
1174 if (resume == 0)
1175 Builder.ClearInsertionPoint();
1176 else
1177 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001178
John McCall6b5a61b2011-02-07 10:33:21 +00001179 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001180
John McCall6b5a61b2011-02-07 10:33:21 +00001181 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001182}
Mike Stumpa99038c2009-02-28 09:07:16 +00001183
John McCall6b5a61b2011-02-07 10:33:21 +00001184/*
1185 notes.push_back(HelperInfo());
1186 HelperInfo &note = notes.back();
1187 note.index = capture.getIndex();
1188 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1189 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001190
John McCall6b5a61b2011-02-07 10:33:21 +00001191 if (ci->isByRef()) {
1192 note.flag = BLOCK_FIELD_IS_BYREF;
1193 if (type.isObjCGCWeak())
1194 note.flag |= BLOCK_FIELD_IS_WEAK;
1195 } else if (type->isBlockPointerType()) {
1196 note.flag = BLOCK_FIELD_IS_BLOCK;
1197 } else {
1198 note.flag = BLOCK_FIELD_IS_OBJECT;
1199 }
1200 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001201
Mike Stump00470a12009-03-05 08:32:30 +00001202
Mike Stumpa99038c2009-02-28 09:07:16 +00001203
John McCall6b5a61b2011-02-07 10:33:21 +00001204llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001205CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001206 ASTContext &C = getContext();
1207
1208 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001209 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1210 args.push_back(&dstDecl);
1211 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1212 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Mike Stumpa4f668f2009-03-06 01:33:24 +00001214 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001215 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1216 FunctionType::ExtInfo(),
1217 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001218
John McCall6b5a61b2011-02-07 10:33:21 +00001219 // FIXME: it would be nice if these were mergeable with things with
1220 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001221 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001222
1223 llvm::Function *Fn =
1224 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001225 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001226
1227 IdentifierInfo *II
1228 = &CGM.getContext().Idents.get("__copy_helper_block_");
1229
Devang Patel58dc5ca2011-05-02 20:37:08 +00001230 // Check if we should generate debug info for this block helper function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001231 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001232
John McCall6b5a61b2011-02-07 10:33:21 +00001233 FunctionDecl *FD = FunctionDecl::Create(C,
1234 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001235 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001236 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001237 SC_Static,
1238 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001239 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001240 false);
John McCalld26bc762011-03-09 04:27:21 +00001241 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001242
Chris Lattner2acc6e32011-07-18 04:24:23 +00001243 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001244
John McCalld26bc762011-03-09 04:27:21 +00001245 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001246 src = Builder.CreateLoad(src);
1247 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001248
John McCalld26bc762011-03-09 04:27:21 +00001249 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001250 dst = Builder.CreateLoad(dst);
1251 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001252
John McCall6b5a61b2011-02-07 10:33:21 +00001253 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001254
John McCall6b5a61b2011-02-07 10:33:21 +00001255 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1256 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1257 const VarDecl *variable = ci->getVariable();
1258 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001259
John McCall6b5a61b2011-02-07 10:33:21 +00001260 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1261 if (capture.isConstant()) continue;
1262
1263 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001264 BlockFieldFlags flags;
1265
John McCall015f33b2012-10-17 02:28:37 +00001266 bool useARCWeakCopy = false;
1267 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001268
1269 if (copyExpr) {
1270 assert(!ci->isByRef());
1271 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001272
John McCall6b5a61b2011-02-07 10:33:21 +00001273 } else if (ci->isByRef()) {
1274 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001275 if (type.isObjCGCWeak())
1276 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001277
John McCallf85e1932011-06-15 23:02:42 +00001278 } else if (type->isObjCRetainableType()) {
1279 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001280 bool isBlockPointer = type->isBlockPointerType();
1281 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001282 flags = BLOCK_FIELD_IS_BLOCK;
1283
1284 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001285 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001286 Qualifiers qs = type.getQualifiers();
1287
John McCall015f33b2012-10-17 02:28:37 +00001288 // We need to register __weak direct captures with the runtime.
1289 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1290 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001291
John McCall015f33b2012-10-17 02:28:37 +00001292 // We need to retain the copied value for __strong direct captures.
1293 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1294 // If it's a block pointer, we have to copy the block and
1295 // assign that to the destination pointer, so we might as
1296 // well use _Block_object_assign. Otherwise we can avoid that.
1297 if (!isBlockPointer)
1298 useARCStrongCopy = true;
1299
1300 // Otherwise the memcpy is fine.
1301 } else {
1302 continue;
1303 }
1304
1305 // Non-ARC captures of retainable pointers are strong and
1306 // therefore require a call to _Block_object_assign.
1307 } else {
1308 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001309 }
1310 } else {
1311 continue;
1312 }
John McCall6b5a61b2011-02-07 10:33:21 +00001313
1314 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001315 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1316 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001317
1318 // If there's an explicit copy expression, we do that.
1319 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001320 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001321 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001322 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001323 } else {
1324 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001325 if (useARCStrongCopy) {
1326 // At -O0, store null into the destination field (so that the
1327 // storeStrong doesn't over-release) and then call storeStrong.
1328 // This is a workaround to not having an initStrong call.
1329 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1330 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1331 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1332 Builder.CreateStore(null, dstField);
1333 EmitARCStoreStrongCall(dstField, srcValue, true);
1334
1335 // With optimization enabled, take advantage of the fact that
1336 // the blocks runtime guarantees a memcpy of the block data, and
1337 // just emit a retain of the src field.
1338 } else {
1339 EmitARCRetainNonBlock(srcValue);
1340
1341 // We don't need this anymore, so kill it. It's not quite
1342 // worth the annoyance to avoid creating it in the first place.
1343 cast<llvm::Instruction>(dstField)->eraseFromParent();
1344 }
1345 } else {
1346 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1347 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1348 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1349 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
1350 }
Mike Stump08920992009-03-07 02:35:30 +00001351 }
1352 }
1353
John McCalld16c2cf2011-02-08 08:22:06 +00001354 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001355
John McCall5936e332011-02-15 09:22:45 +00001356 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001357}
1358
John McCall6b5a61b2011-02-07 10:33:21 +00001359llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001360CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001361 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001362
John McCall6b5a61b2011-02-07 10:33:21 +00001363 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001364 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1365 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Mike Stumpa4f668f2009-03-06 01:33:24 +00001367 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001368 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1369 FunctionType::ExtInfo(),
1370 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001371
Mike Stump3899a7f2009-06-05 23:26:36 +00001372 // FIXME: We'd like to put these into a mergable by content, with
1373 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001374 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001375
1376 llvm::Function *Fn =
1377 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001378 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001379
Devang Patel58dc5ca2011-05-02 20:37:08 +00001380 // Check if we should generate debug info for this block destroy function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001381 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001382
Mike Stumpa4f668f2009-03-06 01:33:24 +00001383 IdentifierInfo *II
1384 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1385
John McCall6b5a61b2011-02-07 10:33:21 +00001386 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001387 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001388 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001389 SC_Static,
1390 SC_None,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001391 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001392 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001393
Chris Lattner2acc6e32011-07-18 04:24:23 +00001394 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001395
John McCalld26bc762011-03-09 04:27:21 +00001396 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001397 src = Builder.CreateLoad(src);
1398 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001399
John McCall6b5a61b2011-02-07 10:33:21 +00001400 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1401
John McCalld16c2cf2011-02-08 08:22:06 +00001402 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001403
1404 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1405 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1406 const VarDecl *variable = ci->getVariable();
1407 QualType type = variable->getType();
1408
1409 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1410 if (capture.isConstant()) continue;
1411
John McCalld16c2cf2011-02-08 08:22:06 +00001412 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001413 const CXXDestructorDecl *dtor = 0;
1414
John McCall015f33b2012-10-17 02:28:37 +00001415 bool useARCWeakDestroy = false;
1416 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001417
John McCall6b5a61b2011-02-07 10:33:21 +00001418 if (ci->isByRef()) {
1419 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001420 if (type.isObjCGCWeak())
1421 flags |= BLOCK_FIELD_IS_WEAK;
1422 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1423 if (record->hasTrivialDestructor())
1424 continue;
1425 dtor = record->getDestructor();
1426 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001427 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001428 if (type->isBlockPointerType())
1429 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001430
John McCallf85e1932011-06-15 23:02:42 +00001431 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001432 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001433 Qualifiers qs = type.getQualifiers();
1434
1435 // Don't generate special dispose logic for a captured object
1436 // unless it's __strong or __weak.
1437 if (!qs.hasStrongOrWeakObjCLifetime())
1438 continue;
1439
1440 // Support __weak direct captures.
1441 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001442 useARCWeakDestroy = true;
1443
1444 // Tools really want us to use objc_storeStrong here.
1445 else
1446 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001447 }
1448 } else {
1449 continue;
1450 }
John McCall6b5a61b2011-02-07 10:33:21 +00001451
1452 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001453 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001454
1455 // If there's an explicit copy expression, we do that.
1456 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001457 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001458
John McCallf85e1932011-06-15 23:02:42 +00001459 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001460 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001461 EmitARCDestroyWeak(srcField);
1462
John McCall015f33b2012-10-17 02:28:37 +00001463 // Destroy strong objects with a call if requested.
1464 } else if (useARCStrongDestroy) {
1465 EmitARCDestroyStrong(srcField, /*precise*/ false);
1466
John McCall6b5a61b2011-02-07 10:33:21 +00001467 // Otherwise we call _Block_object_dispose. It wouldn't be too
1468 // hard to just emit this as a cleanup if we wanted to make sure
1469 // that things were done in reverse.
1470 } else {
1471 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001472 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001473 BuildBlockRelease(value, flags);
1474 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001475 }
1476
John McCall6b5a61b2011-02-07 10:33:21 +00001477 cleanups.ForceCleanup();
1478
John McCalld16c2cf2011-02-08 08:22:06 +00001479 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001480
John McCall5936e332011-02-15 09:22:45 +00001481 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001482}
1483
John McCallf0c11f72011-03-31 08:03:29 +00001484namespace {
1485
1486/// Emits the copy/dispose helper functions for a __block object of id type.
1487class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1488 BlockFieldFlags Flags;
1489
1490public:
1491 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1492 : ByrefHelpers(alignment), Flags(flags) {}
1493
John McCall36170192011-03-31 09:19:20 +00001494 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1495 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001496 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1497
1498 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1499 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1500
1501 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1502
1503 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1504 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1505 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1506 }
1507
1508 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1509 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1510 llvm::Value *value = CGF.Builder.CreateLoad(field);
1511
1512 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1513 }
1514
1515 void profileImpl(llvm::FoldingSetNodeID &id) const {
1516 id.AddInteger(Flags.getBitMask());
1517 }
1518};
1519
John McCallf85e1932011-06-15 23:02:42 +00001520/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1521class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1522public:
1523 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1524
1525 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1526 llvm::Value *srcField) {
1527 CGF.EmitARCMoveWeak(destField, srcField);
1528 }
1529
1530 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1531 CGF.EmitARCDestroyWeak(field);
1532 }
1533
1534 void profileImpl(llvm::FoldingSetNodeID &id) const {
1535 // 0 is distinguishable from all pointers and byref flags
1536 id.AddInteger(0);
1537 }
1538};
1539
1540/// Emits the copy/dispose helpers for an ARC __block __strong variable
1541/// that's not of block-pointer type.
1542class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1543public:
1544 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1545
1546 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1547 llvm::Value *srcField) {
1548 // Do a "move" by copying the value and then zeroing out the old
1549 // variable.
1550
John McCalla59e4b72011-11-09 03:17:26 +00001551 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1552 value->setAlignment(Alignment.getQuantity());
1553
John McCallf85e1932011-06-15 23:02:42 +00001554 llvm::Value *null =
1555 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001556
1557 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1558 store->setAlignment(Alignment.getQuantity());
1559
1560 store = CGF.Builder.CreateStore(null, srcField);
1561 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001562 }
1563
1564 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001565 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001566 }
1567
1568 void profileImpl(llvm::FoldingSetNodeID &id) const {
1569 // 1 is distinguishable from all pointers and byref flags
1570 id.AddInteger(1);
1571 }
1572};
1573
John McCalla59e4b72011-11-09 03:17:26 +00001574/// Emits the copy/dispose helpers for an ARC __block __strong
1575/// variable that's of block-pointer type.
1576class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1577public:
1578 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1579
1580 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1581 llvm::Value *srcField) {
1582 // Do the copy with objc_retainBlock; that's all that
1583 // _Block_object_assign would do anyway, and we'd have to pass the
1584 // right arguments to make sure it doesn't get no-op'ed.
1585 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1586 oldValue->setAlignment(Alignment.getQuantity());
1587
1588 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1589
1590 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1591 store->setAlignment(Alignment.getQuantity());
1592 }
1593
1594 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001595 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCalla59e4b72011-11-09 03:17:26 +00001596 }
1597
1598 void profileImpl(llvm::FoldingSetNodeID &id) const {
1599 // 2 is distinguishable from all pointers and byref flags
1600 id.AddInteger(2);
1601 }
1602};
1603
John McCallf0c11f72011-03-31 08:03:29 +00001604/// Emits the copy/dispose helpers for a __block variable with a
1605/// nontrivial copy constructor or destructor.
1606class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1607 QualType VarType;
1608 const Expr *CopyExpr;
1609
1610public:
1611 CXXByrefHelpers(CharUnits alignment, QualType type,
1612 const Expr *copyExpr)
1613 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1614
1615 bool needsCopy() const { return CopyExpr != 0; }
1616 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1617 llvm::Value *srcField) {
1618 if (!CopyExpr) return;
1619 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1620 }
1621
1622 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1623 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1624 CGF.PushDestructorCleanup(VarType, field);
1625 CGF.PopCleanupBlocks(cleanupDepth);
1626 }
1627
1628 void profileImpl(llvm::FoldingSetNodeID &id) const {
1629 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1630 }
1631};
1632} // end anonymous namespace
1633
1634static llvm::Constant *
1635generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001636 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001637 CodeGenModule::ByrefHelpers &byrefInfo) {
1638 ASTContext &Context = CGF.getContext();
1639
1640 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001641
John McCalld26bc762011-03-09 04:27:21 +00001642 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001643 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001644 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001645
John McCallf0c11f72011-03-31 08:03:29 +00001646 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001647 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Mike Stump45031c02009-03-06 02:29:21 +00001649 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001650 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1651 FunctionType::ExtInfo(),
1652 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001653
John McCallf0c11f72011-03-31 08:03:29 +00001654 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001655 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001656
Mike Stump3899a7f2009-06-05 23:26:36 +00001657 // FIXME: We'd like to put these into a mergable by content, with
1658 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001659 llvm::Function *Fn =
1660 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001661 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001662
1663 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001664 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001665
John McCallf0c11f72011-03-31 08:03:29 +00001666 FunctionDecl *FD = FunctionDecl::Create(Context,
1667 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001668 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001669 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001670 SC_Static,
1671 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001672 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001673
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001674 // Initialize debug info if necessary.
1675 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001676 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001677
John McCallf0c11f72011-03-31 08:03:29 +00001678 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001679 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001680
John McCallf0c11f72011-03-31 08:03:29 +00001681 // dst->x
1682 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1683 destField = CGF.Builder.CreateLoad(destField);
1684 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1685 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001686
John McCallf0c11f72011-03-31 08:03:29 +00001687 // src->x
1688 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1689 srcField = CGF.Builder.CreateLoad(srcField);
1690 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1691 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1692
1693 byrefInfo.emitCopy(CGF, destField, srcField);
1694 }
1695
1696 CGF.FinishFunction();
1697
1698 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001699}
1700
John McCallf0c11f72011-03-31 08:03:29 +00001701/// Build the copy helper for a __block variable.
1702static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001703 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001704 CodeGenModule::ByrefHelpers &info) {
1705 CodeGenFunction CGF(CGM);
1706 return generateByrefCopyHelper(CGF, byrefType, info);
1707}
1708
1709/// Generate code for a __block variable's dispose helper.
1710static llvm::Constant *
1711generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001712 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001713 CodeGenModule::ByrefHelpers &byrefInfo) {
1714 ASTContext &Context = CGF.getContext();
1715 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001716
John McCalld26bc762011-03-09 04:27:21 +00001717 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001718 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001719 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Mike Stump45031c02009-03-06 02:29:21 +00001721 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001722 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1723 FunctionType::ExtInfo(),
1724 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001725
John McCallf0c11f72011-03-31 08:03:29 +00001726 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001727 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001728
Mike Stump3899a7f2009-06-05 23:26:36 +00001729 // FIXME: We'd like to put these into a mergable by content, with
1730 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001731 llvm::Function *Fn =
1732 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001733 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001734 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001735
1736 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001737 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001738
John McCallf0c11f72011-03-31 08:03:29 +00001739 FunctionDecl *FD = FunctionDecl::Create(Context,
1740 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001741 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001742 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001743 SC_Static,
1744 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001745 false, false);
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001746 // Initialize debug info if necessary.
1747 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001748 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001749
John McCallf0c11f72011-03-31 08:03:29 +00001750 if (byrefInfo.needsDispose()) {
1751 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1752 V = CGF.Builder.CreateLoad(V);
1753 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1754 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001755
John McCallf0c11f72011-03-31 08:03:29 +00001756 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001757 }
Mike Stump45031c02009-03-06 02:29:21 +00001758
John McCallf0c11f72011-03-31 08:03:29 +00001759 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001760
John McCallf0c11f72011-03-31 08:03:29 +00001761 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001762}
1763
John McCallf0c11f72011-03-31 08:03:29 +00001764/// Build the dispose helper for a __block variable.
1765static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001766 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001767 CodeGenModule::ByrefHelpers &info) {
1768 CodeGenFunction CGF(CGM);
1769 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001770}
1771
John McCallf0c11f72011-03-31 08:03:29 +00001772///
1773template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001774 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001775 T &byrefInfo) {
1776 // Increase the field's alignment to be at least pointer alignment,
1777 // since the layout of the byref struct will guarantee at least that.
1778 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1779 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1780
1781 llvm::FoldingSetNodeID id;
1782 byrefInfo.Profile(id);
1783
1784 void *insertPos;
1785 CodeGenModule::ByrefHelpers *node
1786 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1787 if (node) return static_cast<T*>(node);
1788
1789 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1790 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1791
1792 T *copy = new (CGM.getContext()) T(byrefInfo);
1793 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1794 return copy;
1795}
1796
1797CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001798CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001799 const AutoVarEmission &emission) {
1800 const VarDecl &var = *emission.Variable;
1801 QualType type = var.getType();
1802
1803 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1804 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1805 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1806
1807 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1808 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1809 }
1810
John McCallf85e1932011-06-15 23:02:42 +00001811 // Otherwise, if we don't have a retainable type, there's nothing to do.
1812 // that the runtime does extra copies.
1813 if (!type->isObjCRetainableType()) return 0;
1814
1815 Qualifiers qs = type.getQualifiers();
1816
1817 // If we have lifetime, that dominates.
1818 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001819 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001820
1821 switch (lifetime) {
1822 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1823
1824 // These are just bits as far as the runtime is concerned.
1825 case Qualifiers::OCL_ExplicitNone:
1826 case Qualifiers::OCL_Autoreleasing:
1827 return 0;
1828
1829 // Tell the runtime that this is ARC __weak, called by the
1830 // byref routines.
1831 case Qualifiers::OCL_Weak: {
1832 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1833 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1834 }
1835
1836 // ARC __strong __block variables need to be retained.
1837 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001838 // Block pointers need to be copied, and there's no direct
1839 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001840 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001841 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001842 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1843
1844 // Otherwise, we transfer ownership of the retain from the stack
1845 // to the heap.
1846 } else {
1847 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1848 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1849 }
1850 }
1851 llvm_unreachable("fell out of lifetime switch!");
1852 }
1853
John McCallf0c11f72011-03-31 08:03:29 +00001854 BlockFieldFlags flags;
1855 if (type->isBlockPointerType()) {
1856 flags |= BLOCK_FIELD_IS_BLOCK;
1857 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1858 type->isObjCObjectPointerType()) {
1859 flags |= BLOCK_FIELD_IS_OBJECT;
1860 } else {
1861 return 0;
1862 }
1863
1864 if (type.isObjCGCWeak())
1865 flags |= BLOCK_FIELD_IS_WEAK;
1866
1867 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1868 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001869}
1870
John McCall5af02db2011-03-31 01:59:53 +00001871unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1872 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1873
1874 return ByRefValueInfo.find(VD)->second.second;
1875}
1876
1877llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1878 const VarDecl *V) {
1879 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1880 Loc = Builder.CreateLoad(Loc);
1881 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1882 V->getNameAsString());
1883 return Loc;
1884}
1885
1886/// BuildByRefType - This routine changes a __block variable declared as T x
1887/// into:
1888///
1889/// struct {
1890/// void *__isa;
1891/// void *__forwarding;
1892/// int32_t __flags;
1893/// int32_t __size;
1894/// void *__copy_helper; // only if needed
1895/// void *__destroy_helper; // only if needed
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001896/// void *__byref_variable_layout;// only if needed
John McCall5af02db2011-03-31 01:59:53 +00001897/// char padding[X]; // only if needed
1898/// T x;
1899/// } x
1900///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001901llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1902 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001903 if (Info.first)
1904 return Info.first;
1905
1906 QualType Ty = D->getType();
1907
Chris Lattner5f9e2722011-07-23 10:55:15 +00001908 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001909
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001910 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001911 llvm::StructType::create(getLLVMContext(),
1912 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001913
1914 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001915 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001916
1917 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001918 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001919
1920 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001921 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001922
1923 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001924 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001925
David Chisnall9595dae2012-04-04 13:07:13 +00001926 bool HasCopyAndDispose =
1927 (Ty->isObjCRetainableType()) || getContext().getBlockVarCopyInits(D);
John McCall5af02db2011-03-31 01:59:53 +00001928 if (HasCopyAndDispose) {
1929 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001930 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001931
1932 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001933 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001934 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001935 bool HasByrefExtendedLayout = false;
1936 Qualifiers::ObjCLifetime Lifetime;
1937 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
1938 HasByrefExtendedLayout)
1939 /// void *__byref_variable_layout;
1940 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001941
1942 bool Packed = false;
1943 CharUnits Align = getContext().getDeclAlign(D);
1944 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1945 // We have to insert padding.
1946
1947 // The struct above has 2 32-bit integers.
1948 unsigned CurrentOffsetInBytes = 4 * 2;
1949
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001950 // And either 2, 3, 4 or 5 pointers.
1951 unsigned noPointers = 2;
1952 if (HasCopyAndDispose)
1953 noPointers += 2;
1954 if (HasByrefExtendedLayout)
1955 noPointers += 1;
1956
1957 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001958
1959 // Align the offset.
1960 unsigned AlignedOffsetInBytes =
1961 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1962
1963 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1964 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00001965 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00001966 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001967 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001968 if (NumPaddingBytes > 1)
1969 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1970
John McCall0774cb82011-05-15 01:53:33 +00001971 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001972
1973 // We want a packed struct.
1974 Packed = true;
1975 }
1976 }
1977
1978 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001979 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001980
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001981 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001982
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001983 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001984
John McCall0774cb82011-05-15 01:53:33 +00001985 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001986
1987 return Info.first;
1988}
1989
1990/// Initialize the structural components of a __block variable, i.e.
1991/// everything but the actual object.
1992void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001993 // Find the address of the local.
1994 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001995
John McCallf0c11f72011-03-31 08:03:29 +00001996 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001997 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001998 cast<llvm::PointerType>(addr->getType())->getElementType());
1999
2000 // Build the byref helpers if necessary. This is null if we don't need any.
2001 CodeGenModule::ByrefHelpers *helpers =
2002 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00002003
2004 const VarDecl &D = *emission.Variable;
2005 QualType type = D.getType();
2006
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002007 bool HasByrefExtendedLayout;
2008 Qualifiers::ObjCLifetime ByrefLifetime;
2009 bool ByRefHasLifetime =
2010 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2011
John McCallf0c11f72011-03-31 08:03:29 +00002012 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00002013
2014 // Initialize the 'isa', which is just 0 or 1.
2015 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00002016 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00002017 isa = 1;
2018 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2019 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2020
2021 // Store the address of the variable into its own forwarding pointer.
2022 Builder.CreateStore(addr,
2023 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2024
2025 // Blocks ABI:
2026 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002027 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall5af02db2011-03-31 01:59:53 +00002028 BlockFlags flags;
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002029 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2030 if (ByRefHasLifetime) {
2031 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2032 else switch (ByrefLifetime) {
2033 case Qualifiers::OCL_Strong:
2034 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2035 break;
2036 case Qualifiers::OCL_Weak:
2037 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2038 break;
2039 case Qualifiers::OCL_ExplicitNone:
2040 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2041 break;
2042 case Qualifiers::OCL_None:
2043 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2044 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2045 break;
2046 default:
2047 break;
2048 }
2049 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2050 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2051 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2052 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2053 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2054 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2055 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2056 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2057 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2058 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2059 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2060 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2061 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2062 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2063 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2064 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2065 }
2066 printf("\n");
2067 }
2068 }
2069
John McCall5af02db2011-03-31 01:59:53 +00002070 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2071 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2072
John McCallf0c11f72011-03-31 08:03:29 +00002073 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2074 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00002075 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2076
John McCallf0c11f72011-03-31 08:03:29 +00002077 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00002078 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00002079 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002080
2081 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002082 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002083 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002084 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2085 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2086 llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2087 "byref.layout");
2088 // cast destination to pointer to source type.
2089 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2090 DesTy = DesTy->getPointerTo();
2091 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2092 Builder.CreateStore(ByrefLayoutInfo, BC);
2093 }
John McCall5af02db2011-03-31 01:59:53 +00002094}
2095
John McCalld16c2cf2011-02-08 08:22:06 +00002096void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002097 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00002098 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00002099 V = Builder.CreateBitCast(V, Int8PtrTy);
2100 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00002101 Builder.CreateCall2(F, V, N);
2102}
John McCall5af02db2011-03-31 01:59:53 +00002103
2104namespace {
2105 struct CallBlockRelease : EHScopeStack::Cleanup {
2106 llvm::Value *Addr;
2107 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2108
John McCallad346f42011-07-12 20:27:29 +00002109 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002110 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002111 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2112 }
2113 };
2114}
2115
2116/// Enter a cleanup to destroy a __block variable. Note that this
2117/// cleanup should be a no-op if the variable hasn't left the stack
2118/// yet; if a cleanup is required for the variable itself, that needs
2119/// to be done externally.
2120void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2121 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002122 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002123 return;
2124
2125 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2126}
John McCall13db5cf2011-09-09 20:41:01 +00002127
2128/// Adjust the declaration of something from the blocks API.
2129static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2130 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002131 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002132
2133 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2134 if (GV->isDeclaration() &&
2135 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2136 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2137}
2138
2139llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2140 if (BlockObjectDispose)
2141 return BlockObjectDispose;
2142
2143 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2144 llvm::FunctionType *fty
2145 = llvm::FunctionType::get(VoidTy, args, false);
2146 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2147 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2148 return BlockObjectDispose;
2149}
2150
2151llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2152 if (BlockObjectAssign)
2153 return BlockObjectAssign;
2154
2155 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2156 llvm::FunctionType *fty
2157 = llvm::FunctionType::get(VoidTy, args, false);
2158 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2159 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2160 return BlockObjectAssign;
2161}
2162
2163llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2164 if (NSConcreteGlobalBlock)
2165 return NSConcreteGlobalBlock;
2166
2167 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2168 Int8PtrTy->getPointerTo(), 0);
2169 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2170 return NSConcreteGlobalBlock;
2171}
2172
2173llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2174 if (NSConcreteStackBlock)
2175 return NSConcreteStackBlock;
2176
2177 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2178 Int8PtrTy->getPointerTo(), 0);
2179 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2180 return NSConcreteStackBlock;
2181}