blob: 317d3c217d570b92ef6e2131d1c0ba48c913f99b [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
John McCalld16c2cf2011-02-08 08:22:06 +000014#include "CGBlocks.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000020#include "llvm/ADT/SmallSet.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000021#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Module.h"
John McCallbd7370a2013-02-28 19:01:20 +000023#include "llvm/Support/CallSite.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000024#include <algorithm>
Fariborz Jahanian7d4b9fa2012-11-14 17:43:08 +000025#include <cstdio>
Torok Edwinf42e4a62009-08-24 13:25:12 +000026
Anders Carlssonacfde802009-02-12 00:39:25 +000027using namespace clang;
28using namespace CodeGen;
29
John McCall1a343eb2011-11-10 08:15:53 +000030CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
31 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanianf22ae652012-11-01 18:32:55 +000032 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
33 StructureType(0), Block(block),
John McCall6f103ba2011-11-10 10:43:54 +000034 DominatingIP(0) {
John McCallee504292010-05-21 04:11:14 +000035
John McCall1a343eb2011-11-10 08:15:53 +000036 // Skip asm prefix, if any. 'name' is usually taken directly from
37 // the mangled name of the enclosing function.
38 if (!name.empty() && name[0] == '\01')
39 name = name.substr(1);
John McCallee504292010-05-21 04:11:14 +000040}
41
John McCallf0c11f72011-03-31 08:03:29 +000042// Anchor the vtable to this translation unit.
43CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
44
John McCall6b5a61b2011-02-07 10:33:21 +000045/// Build the given block as a global block.
46static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
47 const CGBlockInfo &blockInfo,
48 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000049
John McCall6b5a61b2011-02-07 10:33:21 +000050/// Build the helper function to copy a block.
51static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
52 const CGBlockInfo &blockInfo) {
53 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
54}
55
56/// Build the helper function to dipose of a block.
57static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
60}
61
Fariborz Jahanianaf879c02012-10-25 18:06:53 +000062/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
63/// buildBlockDescriptor is accessed from 5th field of the Block_literal
64/// meta-data and contains stationary information about the block literal.
65/// Its definition will have 4 (or optinally 6) words.
66/// struct Block_descriptor {
67/// unsigned long reserved;
68/// unsigned long size; // size of Block_literal metadata in bytes.
69/// void *copy_func_helper_decl; // optional copy helper.
70/// void *destroy_func_decl; // optioanl destructor helper.
71/// void *block_method_encoding_address;//@encode for block literal signature.
72/// void *block_layout_info; // encoding of captured block variables.
73/// };
John McCall6b5a61b2011-02-07 10:33:21 +000074static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
75 const CGBlockInfo &blockInfo) {
76 ASTContext &C = CGM.getContext();
77
Chris Lattner2acc6e32011-07-18 04:24:23 +000078 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
79 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000080
Chris Lattner5f9e2722011-07-23 10:55:15 +000081 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000082
83 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000084 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000085
86 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000087 // FIXME: What is the right way to say this doesn't fit? We should give
88 // a user diagnostic in that case. Better fix would be to change the
89 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000090 elements.push_back(llvm::ConstantInt::get(ulong,
91 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000092
John McCall6b5a61b2011-02-07 10:33:21 +000093 // Optional copy/dispose helpers.
94 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000095 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000096 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000097
98 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000099 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +0000100 }
101
John McCall6b5a61b2011-02-07 10:33:21 +0000102 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
103 std::string typeAtEncoding =
104 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
105 elements.push_back(llvm::ConstantExpr::getBitCast(
106 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000107
John McCall6b5a61b2011-02-07 10:33:21 +0000108 // GC layout.
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000109 if (C.getLangOpts().ObjC1) {
110 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
111 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
112 else
113 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
114 }
John McCall6b5a61b2011-02-07 10:33:21 +0000115 else
116 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000117
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000118 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000119
John McCall6b5a61b2011-02-07 10:33:21 +0000120 llvm::GlobalVariable *global =
121 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
122 llvm::GlobalValue::InternalLinkage,
123 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000124
John McCall6b5a61b2011-02-07 10:33:21 +0000125 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000126}
127
John McCall6b5a61b2011-02-07 10:33:21 +0000128/*
129 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000130
John McCall6b5a61b2011-02-07 10:33:21 +0000131 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
132 struct Block_literal {
133 /// Initialized to one of:
134 /// extern void *_NSConcreteStackBlock[];
135 /// extern void *_NSConcreteGlobalBlock[];
136 ///
137 /// In theory, we could start one off malloc'ed by setting
138 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
139 /// this isa:
140 /// extern void *_NSConcreteMallocBlock[];
141 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000142
John McCall6b5a61b2011-02-07 10:33:21 +0000143 /// These are the flags (with corresponding bit number) that the
144 /// compiler is actually supposed to know about.
145 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
146 /// descriptor provides copy and dispose helper functions
147 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
148 /// object with a nontrivial destructor or copy constructor
149 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
150 /// as global memory
151 /// 29. BLOCK_USE_STRET - indicates that the block function
152 /// uses stret, which objc_msgSend needs to know about
153 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
154 /// @encoded signature string
155 /// And we're not supposed to manipulate these:
156 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
157 /// to malloc'ed memory
158 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
159 /// to GC-allocated memory
160 /// Additionally, the bottom 16 bits are a reference count which
161 /// should be zero on the stack.
162 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000163
John McCall6b5a61b2011-02-07 10:33:21 +0000164 /// Reserved; should be zero-initialized.
165 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000166
John McCall6b5a61b2011-02-07 10:33:21 +0000167 /// Function pointer generated from block literal.
168 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000169
John McCall6b5a61b2011-02-07 10:33:21 +0000170 /// Block description metadata generated from block literal.
171 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000172
John McCall6b5a61b2011-02-07 10:33:21 +0000173 /// Captured values follow.
174 _CapturesTypes captures...;
175 };
176 */
David Chisnall5e530af2009-11-17 19:33:30 +0000177
John McCall6b5a61b2011-02-07 10:33:21 +0000178/// The number of fields in a block header.
179const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000180
John McCall6b5a61b2011-02-07 10:33:21 +0000181namespace {
182 /// A chunk of data that we actually have to capture in the block.
183 struct BlockLayoutChunk {
184 CharUnits Alignment;
185 CharUnits Size;
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000186 Qualifiers::ObjCLifetime Lifetime;
John McCall6b5a61b2011-02-07 10:33:21 +0000187 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000188 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000189
John McCall6b5a61b2011-02-07 10:33:21 +0000190 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000191 Qualifiers::ObjCLifetime lifetime,
John McCall6b5a61b2011-02-07 10:33:21 +0000192 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000193 llvm::Type *type)
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000194 : Alignment(align), Size(size), Lifetime(lifetime),
195 Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000196
John McCall6b5a61b2011-02-07 10:33:21 +0000197 /// Tell the block info that this chunk has the given field index.
198 void setIndex(CGBlockInfo &info, unsigned index) {
199 if (!Capture)
200 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000201 else
John McCall6b5a61b2011-02-07 10:33:21 +0000202 info.Captures[Capture->getVariable()]
203 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000204 }
John McCall6b5a61b2011-02-07 10:33:21 +0000205 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000206
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000207 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
208 /// all __weak together. Preserve descending alignment in all situations.
John McCall6b5a61b2011-02-07 10:33:21 +0000209 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000210 CharUnits LeftValue, RightValue;
211 bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
212 bool RightByref = right.Capture ? right.Capture->isByRef() : false;
213
214 if (left.Lifetime == Qualifiers::OCL_Strong &&
215 left.Alignment >= right.Alignment)
216 LeftValue = CharUnits::fromQuantity(64);
217 else if (LeftByref && left.Alignment >= right.Alignment)
218 LeftValue = CharUnits::fromQuantity(32);
219 else if (left.Lifetime == Qualifiers::OCL_Weak &&
220 left.Alignment >= right.Alignment)
221 LeftValue = CharUnits::fromQuantity(16);
222 else
223 LeftValue = left.Alignment;
224 if (right.Lifetime == Qualifiers::OCL_Strong &&
225 right.Alignment >= left.Alignment)
226 RightValue = CharUnits::fromQuantity(64);
227 else if (RightByref && right.Alignment >= left.Alignment)
228 RightValue = CharUnits::fromQuantity(32);
229 else if (right.Lifetime == Qualifiers::OCL_Weak &&
230 right.Alignment >= left.Alignment)
231 RightValue = CharUnits::fromQuantity(16);
232 else
233 RightValue = right.Alignment;
234
235 return LeftValue > RightValue;
John McCall6b5a61b2011-02-07 10:33:21 +0000236 }
237}
238
John McCall461c9c12011-02-08 03:07:00 +0000239/// Determines if the given type is safe for constant capture in C++.
240static bool isSafeForCXXConstantCapture(QualType type) {
241 const RecordType *recordType =
242 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
243
244 // Only records can be unsafe.
245 if (!recordType) return true;
246
247 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
248
249 // Maintain semantics for classes with non-trivial dtors or copy ctors.
250 if (!record->hasTrivialDestructor()) return false;
Richard Smith426391c2012-11-16 00:53:38 +0000251 if (record->hasNonTrivialCopyConstructor()) return false;
John McCall461c9c12011-02-08 03:07:00 +0000252
253 // Otherwise, we just have to make sure there aren't any mutable
254 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000255 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000256}
257
John McCall6b5a61b2011-02-07 10:33:21 +0000258/// It is illegal to modify a const object after initialization.
259/// Therefore, if a const object has a constant initializer, we don't
260/// actually need to keep storage for it in the block; we'll just
261/// rematerialize it at the start of the block function. This is
262/// acceptable because we make no promises about address stability of
263/// captured variables.
264static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000265 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000266 const VarDecl *var) {
267 QualType type = var->getType();
268
269 // We can only do this if the variable is const.
270 if (!type.isConstQualified()) return 0;
271
John McCall461c9c12011-02-08 03:07:00 +0000272 // Furthermore, in C++ we have to worry about mutable fields:
273 // C++ [dcl.type.cv]p4:
274 // Except that any class member declared mutable can be
275 // modified, any attempt to modify a const object during its
276 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000277 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000278 return 0;
279
280 // If the variable doesn't have any initializer (shouldn't this be
281 // invalid?), it's not clear what we should do. Maybe capture as
282 // zero?
283 const Expr *init = var->getInit();
284 if (!init) return 0;
285
Richard Smith2d6a5672012-01-14 04:30:29 +0000286 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000287}
288
289/// Get the low bit of a nonzero character count. This is the
290/// alignment of the nth byte if the 0th byte is universally aligned.
291static CharUnits getLowBit(CharUnits v) {
292 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
293}
294
295static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000296 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000297 ASTContext &C = CGM.getContext();
298
299 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
300 CharUnits ptrSize, ptrAlign, intSize, intAlign;
301 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
302 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
303
304 // Are there crazy embedded platforms where this isn't true?
305 assert(intSize <= ptrSize && "layout assumptions horribly violated");
306
307 CharUnits headerSize = ptrSize;
308 if (2 * intSize < ptrAlign) headerSize += ptrSize;
309 else headerSize += 2 * intSize;
310 headerSize += 2 * ptrSize;
311
312 info.BlockAlign = ptrAlign;
313 info.BlockSize = headerSize;
314
315 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000316 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
317 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000318 elementTypes.push_back(i8p);
319 elementTypes.push_back(intTy);
320 elementTypes.push_back(intTy);
321 elementTypes.push_back(i8p);
322 elementTypes.push_back(CGM.getBlockDescriptorType());
323
324 assert(elementTypes.size() == BlockHeaderSize);
325}
326
327/// Compute the layout of the given block. Attempts to lay the block
328/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000329static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
330 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000331 ASTContext &C = CGM.getContext();
332 const BlockDecl *block = info.getBlockDecl();
333
Chris Lattner5f9e2722011-07-23 10:55:15 +0000334 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000335 initializeForBlockHeader(CGM, info, elementTypes);
336
337 if (!block->hasCaptures()) {
338 info.StructureType =
339 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
340 info.CanBeGlobal = true;
341 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000342 }
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000343 else if (C.getLangOpts().ObjC1 &&
344 CGM.getLangOpts().getGC() == LangOptions::NonGC)
345 info.HasCapturedVariableLayout = true;
346
John McCall6b5a61b2011-02-07 10:33:21 +0000347 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000348 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000349 layout.reserve(block->capturesCXXThis() +
350 (block->capture_end() - block->capture_begin()));
351
352 CharUnits maxFieldAlign;
353
354 // First, 'this'.
355 if (block->capturesCXXThis()) {
356 const DeclContext *DC = block->getDeclContext();
357 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
358 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000359 QualType thisType;
360 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
361 thisType = C.getPointerType(C.getRecordType(RD));
362 else
363 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000364
Jay Foadef6de3d2011-07-11 09:56:20 +0000365 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000366 std::pair<CharUnits,CharUnits> tinfo
367 = CGM.getContext().getTypeInfoInChars(thisType);
368 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
369
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000370 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
371 Qualifiers::OCL_None,
372 0, llvmType));
John McCall6b5a61b2011-02-07 10:33:21 +0000373 }
374
375 // Next, all the block captures.
376 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
377 ce = block->capture_end(); ci != ce; ++ci) {
378 const VarDecl *variable = ci->getVariable();
379
380 if (ci->isByRef()) {
381 // We have to copy/dispose of the __block reference.
382 info.NeedsCopyDispose = true;
383
John McCall6b5a61b2011-02-07 10:33:21 +0000384 // Just use void* instead of a pointer to the byref type.
385 QualType byRefPtrTy = C.VoidPtrTy;
386
Jay Foadef6de3d2011-07-11 09:56:20 +0000387 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000388 std::pair<CharUnits,CharUnits> tinfo
389 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
390 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
391
392 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000393 Qualifiers::OCL_None,
John McCall6b5a61b2011-02-07 10:33:21 +0000394 &*ci, llvmType));
395 continue;
396 }
397
398 // Otherwise, build a layout chunk with the size and alignment of
399 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000400 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000401 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
402 continue;
403 }
404
John McCallf85e1932011-06-15 23:02:42 +0000405 // If we have a lifetime qualifier, honor it for capture purposes.
406 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000407 Qualifiers::ObjCLifetime lifetime =
408 variable->getType().getObjCLifetime();
409 if (lifetime) {
John McCallf85e1932011-06-15 23:02:42 +0000410 switch (lifetime) {
411 case Qualifiers::OCL_None: llvm_unreachable("impossible");
412 case Qualifiers::OCL_ExplicitNone:
413 case Qualifiers::OCL_Autoreleasing:
414 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000415
John McCallf85e1932011-06-15 23:02:42 +0000416 case Qualifiers::OCL_Strong:
417 case Qualifiers::OCL_Weak:
418 info.NeedsCopyDispose = true;
419 }
420
421 // Block pointers require copy/dispose. So do Objective-C pointers.
422 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000423 info.NeedsCopyDispose = true;
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000424 // used for mrr below.
425 lifetime = Qualifiers::OCL_Strong;
John McCall6b5a61b2011-02-07 10:33:21 +0000426
427 // So do types that require non-trivial copy construction.
428 } else if (ci->hasCopyExpr()) {
429 info.NeedsCopyDispose = true;
430 info.HasCXXObject = true;
431
432 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000433 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000434 if (const CXXRecordDecl *record =
435 variable->getType()->getAsCXXRecordDecl()) {
436 if (!record->hasTrivialDestructor()) {
437 info.HasCXXObject = true;
438 info.NeedsCopyDispose = true;
439 }
440 }
441 }
442
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000443 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000444 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000445 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000446
John McCall6b5a61b2011-02-07 10:33:21 +0000447 maxFieldAlign = std::max(maxFieldAlign, align);
448
Jay Foadef6de3d2011-07-11 09:56:20 +0000449 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000450 CGM.getTypes().ConvertTypeForMem(VT);
451
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000452 layout.push_back(BlockLayoutChunk(align, size, lifetime, &*ci, llvmType));
John McCall6b5a61b2011-02-07 10:33:21 +0000453 }
454
455 // If that was everything, we're done here.
456 if (layout.empty()) {
457 info.StructureType =
458 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
459 info.CanBeGlobal = true;
460 return;
461 }
462
463 // Sort the layout by alignment. We have to use a stable sort here
464 // to get reproducible results. There should probably be an
465 // llvm::array_pod_stable_sort.
466 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000467
468 // Needed for blocks layout info.
469 info.BlockHeaderForcedGapOffset = info.BlockSize;
470 info.BlockHeaderForcedGapSize = CharUnits::Zero();
471
John McCall6b5a61b2011-02-07 10:33:21 +0000472 CharUnits &blockSize = info.BlockSize;
473 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
474
475 // Assuming that the first byte in the header is maximally aligned,
476 // get the alignment of the first byte following the header.
477 CharUnits endAlign = getLowBit(blockSize);
478
479 // If the end of the header isn't satisfactorily aligned for the
480 // maximum thing, look for things that are okay with the header-end
481 // alignment, and keep appending them until we get something that's
482 // aligned right. This algorithm is only guaranteed optimal if
483 // that condition is satisfied at some point; otherwise we can get
484 // things like:
485 // header // next byte has alignment 4
486 // something_with_size_5; // next byte has alignment 1
487 // something_with_alignment_8;
488 // which has 7 bytes of padding, as opposed to the naive solution
489 // which might have less (?).
490 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000491 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000492 li = layout.begin() + 1, le = layout.end();
493
494 // Look for something that the header end is already
495 // satisfactorily aligned for.
496 for (; li != le && endAlign < li->Alignment; ++li)
497 ;
498
499 // If we found something that's naturally aligned for the end of
500 // the header, keep adding things...
501 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000502 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000503 for (; li != le; ++li) {
504 assert(endAlign >= li->Alignment);
505
506 li->setIndex(info, elementTypes.size());
507 elementTypes.push_back(li->Type);
508 blockSize += li->Size;
509 endAlign = getLowBit(blockSize);
510
511 // ...until we get to the alignment of the maximum field.
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000512 if (endAlign >= maxFieldAlign) {
513 if (li == first) {
514 // No user field was appended. So, a gap was added.
515 // Save total gap size for use in block layout bit map.
516 info.BlockHeaderForcedGapSize = li->Size;
517 }
John McCall6b5a61b2011-02-07 10:33:21 +0000518 break;
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000519 }
John McCall6b5a61b2011-02-07 10:33:21 +0000520 }
John McCall6b5a61b2011-02-07 10:33:21 +0000521 // Don't re-append everything we just appended.
522 layout.erase(first, li);
523 }
524 }
525
John McCall6ea48412012-04-26 21:14:42 +0000526 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000527
John McCall6b5a61b2011-02-07 10:33:21 +0000528 // At this point, we just have to add padding if the end align still
529 // isn't aligned right.
530 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000531 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
532 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000533
John McCall5936e332011-02-15 09:22:45 +0000534 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
535 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000536 blockSize = newBlockSize;
John McCall6c803f72012-05-01 20:28:00 +0000537 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall6b5a61b2011-02-07 10:33:21 +0000538 }
539
John McCall6c803f72012-05-01 20:28:00 +0000540 assert(endAlign >= maxFieldAlign);
John McCall6ea48412012-04-26 21:14:42 +0000541 assert(endAlign == getLowBit(blockSize));
John McCall6b5a61b2011-02-07 10:33:21 +0000542 // Slam everything else on now. This works because they have
543 // strictly decreasing alignment and we expect that size is always a
544 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000545 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000546 li = layout.begin(), le = layout.end(); li != le; ++li) {
547 assert(endAlign >= li->Alignment);
548 li->setIndex(info, elementTypes.size());
549 elementTypes.push_back(li->Type);
550 blockSize += li->Size;
551 endAlign = getLowBit(blockSize);
552 }
553
554 info.StructureType =
555 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
556}
557
John McCall1a343eb2011-11-10 08:15:53 +0000558/// Enter the scope of a block. This should be run at the entrance to
559/// a full-expression so that the block's cleanups are pushed at the
560/// right place in the stack.
561static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000562 assert(CGF.HaveInsertPoint());
563
John McCall1a343eb2011-11-10 08:15:53 +0000564 // Allocate the block info and place it at the head of the list.
565 CGBlockInfo &blockInfo =
566 *new CGBlockInfo(block, CGF.CurFn->getName());
567 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
568 CGF.FirstBlockInfo = &blockInfo;
569
570 // Compute information about the layout, etc., of this block,
571 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000572 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000573
574 // Nothing else to do if it can be global.
575 if (blockInfo.CanBeGlobal) return;
576
577 // Make the allocation for the block.
578 blockInfo.Address =
579 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
580 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
581
582 // If there are cleanups to emit, enter them (but inactive).
583 if (!blockInfo.NeedsCopyDispose) return;
584
585 // Walk through the captures (in order) and find the ones not
586 // captured by constant.
587 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
588 ce = block->capture_end(); ci != ce; ++ci) {
589 // Ignore __block captures; there's nothing special in the
590 // on-stack block that we need to do for them.
591 if (ci->isByRef()) continue;
592
593 // Ignore variables that are constant-captured.
594 const VarDecl *variable = ci->getVariable();
595 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
596 if (capture.isConstant()) continue;
597
598 // Ignore objects that aren't destructed.
599 QualType::DestructionKind dtorKind =
600 variable->getType().isDestructedType();
601 if (dtorKind == QualType::DK_none) continue;
602
603 CodeGenFunction::Destroyer *destroyer;
604
605 // Block captures count as local values and have imprecise semantics.
606 // They also can't be arrays, so need to worry about that.
607 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000608 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000609 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000610 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000611 }
612
613 // GEP down to the address.
614 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
615 capture.getIndex());
616
John McCall6f103ba2011-11-10 10:43:54 +0000617 // We can use that GEP as the dominating IP.
618 if (!blockInfo.DominatingIP)
619 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
620
John McCall1a343eb2011-11-10 08:15:53 +0000621 CleanupKind cleanupKind = InactiveNormalCleanup;
622 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
623 if (useArrayEHCleanup)
624 cleanupKind = InactiveNormalAndEHCleanup;
625
626 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000627 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000628
629 // Remember where that cleanup was.
630 capture.setCleanup(CGF.EHStack.stable_begin());
631 }
632}
633
634/// Enter a full-expression with a non-trivial number of objects to
635/// clean up. This is in this file because, at the moment, the only
636/// kind of cleanup object is a BlockDecl*.
637void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
638 assert(E->getNumObjects() != 0);
639 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
640 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
641 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
642 enterBlockScope(*this, *i);
643 }
644}
645
646/// Find the layout for the given block in a linked list and remove it.
647static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
648 const BlockDecl *block) {
649 while (true) {
650 assert(head && *head);
651 CGBlockInfo *cur = *head;
652
653 // If this is the block we're looking for, splice it out of the list.
654 if (cur->getBlockDecl() == block) {
655 *head = cur->NextBlockInfo;
656 return cur;
657 }
658
659 head = &cur->NextBlockInfo;
660 }
661}
662
663/// Destroy a chain of block layouts.
664void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
665 assert(head && "destroying an empty chain");
666 do {
667 CGBlockInfo *cur = head;
668 head = cur->NextBlockInfo;
669 delete cur;
670 } while (head != 0);
671}
672
John McCall6b5a61b2011-02-07 10:33:21 +0000673/// Emit a block literal expression in the current function.
674llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000675 // If the block has no captures, we won't have a pre-computed
676 // layout for it.
677 if (!blockExpr->getBlockDecl()->hasCaptures()) {
678 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000679 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000680 blockInfo.BlockExpression = blockExpr;
681 return EmitBlockLiteral(blockInfo);
682 }
John McCall6b5a61b2011-02-07 10:33:21 +0000683
John McCall1a343eb2011-11-10 08:15:53 +0000684 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000685 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000686 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
687 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000688
John McCall1a343eb2011-11-10 08:15:53 +0000689 blockInfo->BlockExpression = blockExpr;
690 return EmitBlockLiteral(*blockInfo);
691}
692
693llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
694 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000695 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000696 llvm::Constant *blockFn
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000697 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000698 CurFuncDecl, LocalDeclMap,
Eli Friedman23f02672012-03-01 04:01:32 +0000699 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000700 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000701
702 // If there is nothing to capture, we can emit this as a global block.
703 if (blockInfo.CanBeGlobal)
704 return buildGlobalBlock(CGM, blockInfo, blockFn);
705
706 // Otherwise, we have to emit this as a local block.
707
708 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000709 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000710
711 // Build the block descriptor.
712 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
713
John McCall1a343eb2011-11-10 08:15:53 +0000714 llvm::AllocaInst *blockAddr = blockInfo.Address;
715 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000716
717 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000718 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000719 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall6b5a61b2011-02-07 10:33:21 +0000720 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
721 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000722 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000723
724 // Initialize the block literal.
725 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000726 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000727 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000728 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000729 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
730 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
731 "block.invoke"));
732 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
733 "block.descriptor"));
734
735 // Finally, capture all the values into the block.
736 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
737
738 // First, 'this'.
739 if (blockDecl->capturesCXXThis()) {
740 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
741 blockInfo.CXXThisIndex,
742 "block.captured-this.addr");
743 Builder.CreateStore(LoadCXXThis(), addr);
744 }
745
746 // Next, captured variables.
747 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
748 ce = blockDecl->capture_end(); ci != ce; ++ci) {
749 const VarDecl *variable = ci->getVariable();
750 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
751
752 // Ignore constant captures.
753 if (capture.isConstant()) continue;
754
755 QualType type = variable->getType();
756
757 // This will be a [[type]]*, except that a byref entry will just be
758 // an i8**.
759 llvm::Value *blockField =
760 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
761 "block.captured");
762
763 // Compute the address of the thing we're going to move into the
764 // block literal.
765 llvm::Value *src;
Douglas Gregor29a93f82012-05-16 16:50:20 +0000766 if (BlockInfo && ci->isNested()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000767 // We need to use the capture from the enclosing block.
768 const CGBlockInfo::Capture &enclosingCapture =
769 BlockInfo->getCapture(variable);
770
771 // This is a [[type]]*, except that a byref entry wil just be an i8**.
772 src = Builder.CreateStructGEP(LoadBlockStruct(),
773 enclosingCapture.getIndex(),
774 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000775 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000776 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000777 // special; we'll simply emit it directly.
778 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000779 } else {
John McCall0353a7b2013-03-04 06:32:36 +0000780 // Just look it up in the locals map, which will give us back a
781 // [[type]]*. If that doesn't work, do the more elaborate DRE
782 // emission.
783 src = LocalDeclMap.lookup(variable);
784 if (!src) {
785 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
786 /*refersToEnclosing*/ ci->isNested(), type,
787 VK_LValue, SourceLocation());
788 src = EmitDeclRefLValue(&declRef).getAddress();
789 }
John McCall6b5a61b2011-02-07 10:33:21 +0000790 }
791
792 // For byrefs, we just write the pointer to the byref struct into
793 // the block field. There's no need to chase the forwarding
794 // pointer at this point, since we're building something that will
795 // live a shorter life than the stack byref anyway.
796 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000797 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000798 if (ci->isNested())
799 src = Builder.CreateLoad(src, "byref.capture");
800 else
John McCall5936e332011-02-15 09:22:45 +0000801 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000802
John McCall5936e332011-02-15 09:22:45 +0000803 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000804 Builder.CreateStore(src, blockField);
805
806 // If we have a copy constructor, evaluate that into the block field.
807 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000808 if (blockDecl->isConversionFromLambda()) {
809 // If we have a lambda conversion, emit the expression
810 // directly into the block instead.
811 CharUnits Align = getContext().getTypeAlignInChars(type);
812 AggValueSlot Slot =
813 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
814 AggValueSlot::IsDestructed,
815 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000816 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000817 EmitAggExpr(copyExpr, Slot);
818 } else {
819 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
820 }
John McCall6b5a61b2011-02-07 10:33:21 +0000821
822 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000823 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000824 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
825
826 // Otherwise, fake up a POD copy into the block field.
827 } else {
John McCallf85e1932011-06-15 23:02:42 +0000828 // Fake up a new variable so that EmitScalarInit doesn't think
829 // we're referring to the variable in its own initializer.
830 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000831 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000832
John McCallbb699b02011-02-07 18:37:40 +0000833 // We use one of these or the other depending on whether the
834 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000835 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
836 /*refersToEnclosing*/ ci->isNested(), type,
837 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000838
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000839 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000840 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000841 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000842 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000843 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000844 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000845 }
846
John McCall1a343eb2011-11-10 08:15:53 +0000847 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000848 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000849 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
850 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000851 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000852 }
John McCall6b5a61b2011-02-07 10:33:21 +0000853 }
854
855 // Cast to the converted block-pointer type, which happens (somewhat
856 // unfortunately) to be a pointer to function type.
857 llvm::Value *result =
858 Builder.CreateBitCast(blockAddr,
859 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000860
John McCall6b5a61b2011-02-07 10:33:21 +0000861 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000862}
863
864
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000865llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000866 if (BlockDescriptorType)
867 return BlockDescriptorType;
868
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000869 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000870 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000871
Mike Stumpab695142009-02-13 15:16:56 +0000872 // struct __block_descriptor {
873 // unsigned long reserved;
874 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000875 //
876 // // later, the following will be added
877 //
878 // struct {
879 // void (*copyHelper)();
880 // void (*copyHelper)();
881 // } helpers; // !!! optional
882 //
883 // const char *signature; // the block signature
884 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000885 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000886 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000887 llvm::StructType::create("struct.__block_descriptor",
888 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000889
John McCall6b5a61b2011-02-07 10:33:21 +0000890 // Now form a pointer to that.
891 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000892 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000893}
894
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000895llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000896 if (GenericBlockLiteralType)
897 return GenericBlockLiteralType;
898
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000899 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000900
Mike Stump9b8a7972009-02-13 15:25:34 +0000901 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000902 // void *__isa;
903 // int __flags;
904 // int __reserved;
905 // void (*__invoke)(void *);
906 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000907 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000908 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000909 llvm::StructType::create("struct.__block_literal_generic",
910 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
911 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000912
Mike Stump9b8a7972009-02-13 15:25:34 +0000913 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000914}
915
Mike Stumpbd65cac2009-02-19 01:01:04 +0000916
Anders Carlssona1736c02009-12-24 21:13:40 +0000917RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
918 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000919 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000920 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000921
Anders Carlssonacfde802009-02-12 00:39:25 +0000922 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
923
924 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000925 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000926 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000927
928 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000929 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000930 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
931
932 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000933 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000934
Benjamin Kramer578faa82011-09-27 21:06:10 +0000935 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000936
Anders Carlssonacfde802009-02-12 00:39:25 +0000937 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000938 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000939 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000940
Anders Carlsson782f3972009-04-08 23:13:16 +0000941 QualType FnType = BPT->getPointeeType();
942
Anders Carlssonacfde802009-02-12 00:39:25 +0000943 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000944 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000945 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000946
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000947 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000948 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000949
John McCall64cd2322011-03-09 08:39:33 +0000950 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000951 const CGFunctionInfo &FnInfo =
John McCalle56bb362012-12-07 07:03:17 +0000952 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000954 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000955 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Chris Lattner2acc6e32011-07-18 04:24:23 +0000957 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000958 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Anders Carlssonacfde802009-02-12 00:39:25 +0000960 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000961 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000962}
Anders Carlssond5cab542009-02-12 17:55:02 +0000963
John McCall6b5a61b2011-02-07 10:33:21 +0000964llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
965 bool isByRef) {
966 assert(BlockInfo && "evaluating block ref without block information?");
967 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000968
John McCall6b5a61b2011-02-07 10:33:21 +0000969 // Handle constant captures.
970 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000971
John McCall6b5a61b2011-02-07 10:33:21 +0000972 llvm::Value *addr =
973 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
974 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000975
John McCall6b5a61b2011-02-07 10:33:21 +0000976 if (isByRef) {
977 // addr should be a void** right now. Load, then cast the result
978 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000979
John McCall6b5a61b2011-02-07 10:33:21 +0000980 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000981 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000982 = llvm::PointerType::get(BuildByRefType(variable), 0);
983 addr = Builder.CreateBitCast(addr, byrefPointerType,
984 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000985
John McCall6b5a61b2011-02-07 10:33:21 +0000986 // Follow the forwarding pointer.
987 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
988 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000989
John McCall6b5a61b2011-02-07 10:33:21 +0000990 // Cast back to byref* and GEP over to the actual object.
991 addr = Builder.CreateBitCast(addr, byrefPointerType);
992 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
993 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000994 }
995
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000996 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000997 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000998
John McCall6b5a61b2011-02-07 10:33:21 +0000999 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +00001000}
1001
Mike Stump67a64482009-02-14 22:16:35 +00001002llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001003CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +00001004 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +00001005 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1006 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +00001007
John McCall6b5a61b2011-02-07 10:33:21 +00001008 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +00001009 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001010
John McCall6b5a61b2011-02-07 10:33:21 +00001011 // Using that metadata, generate the actual block function.
1012 llvm::Constant *blockFn;
1013 {
1014 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +00001015 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1016 blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +00001017 0, LocalDeclMap,
1018 false);
John McCall6b5a61b2011-02-07 10:33:21 +00001019 }
John McCall5936e332011-02-15 09:22:45 +00001020 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +00001021
John McCalld16c2cf2011-02-08 08:22:06 +00001022 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +00001023}
1024
John McCall6b5a61b2011-02-07 10:33:21 +00001025static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1026 const CGBlockInfo &blockInfo,
1027 llvm::Constant *blockFn) {
1028 assert(blockInfo.CanBeGlobal);
1029
1030 // Generate the constants for the block literal initializer.
1031 llvm::Constant *fields[BlockHeaderSize];
1032
1033 // isa
1034 fields[0] = CGM.getNSConcreteGlobalBlock();
1035
1036 // __flags
John McCall64cd2322011-03-09 08:39:33 +00001037 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1038 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1039
John McCall5936e332011-02-15 09:22:45 +00001040 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +00001041
1042 // Reserved
John McCall5936e332011-02-15 09:22:45 +00001043 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001044
1045 // Function
1046 fields[3] = blockFn;
1047
1048 // Descriptor
1049 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1050
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001051 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +00001052
1053 llvm::GlobalVariable *literal =
1054 new llvm::GlobalVariable(CGM.getModule(),
1055 init->getType(),
1056 /*constant*/ true,
1057 llvm::GlobalVariable::InternalLinkage,
1058 init,
1059 "__block_literal_global");
1060 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1061
1062 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001063 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +00001064 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1065 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +00001066}
1067
Mike Stump00470a12009-03-05 08:32:30 +00001068llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +00001069CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1070 const CGBlockInfo &blockInfo,
1071 const Decl *outerFnDecl,
Eli Friedman64bee652012-02-25 02:48:22 +00001072 const DeclMapTy &ldm,
1073 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001074 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001075
Devang Patel6d1155b2011-03-07 21:53:18 +00001076 // Check if we should generate debug info for this block function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001077 maybeInitializeDebugInfo();
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001078 CurGD = GD;
1079
John McCall6b5a61b2011-02-07 10:33:21 +00001080 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Mike Stump7f28a9c2009-03-13 23:34:28 +00001082 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001083 // to be local to this function as well, in case they're directly
1084 // referenced in a block.
1085 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1086 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1087 if (var && !var->hasLocalStorage())
1088 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001089 }
1090
John McCall6b5a61b2011-02-07 10:33:21 +00001091 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001092
John McCall6b5a61b2011-02-07 10:33:21 +00001093 // Build the argument list.
1094 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001095
John McCall6b5a61b2011-02-07 10:33:21 +00001096 // The first argument is the block pointer. Just take it as a void*
1097 // and cast it later.
1098 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001099 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001100
John McCall8178df32011-02-22 22:38:33 +00001101 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1102 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001103 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001104
John McCall6b5a61b2011-02-07 10:33:21 +00001105 // Now add the rest of the parameters.
1106 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1107 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001108 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001109
John McCall6b5a61b2011-02-07 10:33:21 +00001110 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001111 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001112 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001113 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1114 fnType->getExtInfo(),
1115 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001116 if (CGM.ReturnTypeUsesSRet(fnInfo))
1117 blockInfo.UsesStret = true;
1118
John McCallde5d3c72012-02-17 03:33:10 +00001119 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001120
John McCall6b5a61b2011-02-07 10:33:21 +00001121 MangleBuffer name;
1122 CGM.getBlockMangledName(GD, name, blockDecl);
1123 llvm::Function *fn =
1124 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1125 name.getString(), &CGM.getModule());
1126 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001127
John McCall6b5a61b2011-02-07 10:33:21 +00001128 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001129 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001130 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001131 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001132
John McCall8178df32011-02-22 22:38:33 +00001133 // Okay. Undo some of what StartFunction did.
1134
1135 // Pull the 'self' reference out of the local decl map.
1136 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1137 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001138 BlockPointer = Builder.CreateBitCast(blockAddr,
1139 blockInfo.StructureType->getPointerTo(),
1140 "block");
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001141 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1142 // won't delete the dbg.declare intrinsics for captured variables.
1143 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1144 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1145 // Allocate a stack slot for it, so we can point the debugger to it
1146 llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
1147 "block.addr");
1148 unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
1149 Alloca->setAlignment(Align);
Adrian Prantl79591942013-04-02 01:00:48 +00001150 // Set the DebugLocation to empty, so the store is recognized as a
1151 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1152 llvm::DebugLoc Empty;
1153 llvm::DebugLoc Loc = Builder.getCurrentDebugLocation();
1154 Builder.SetCurrentDebugLocation(Empty);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001155 Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
Adrian Prantl79591942013-04-02 01:00:48 +00001156 Builder.SetCurrentDebugLocation(Loc);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001157 BlockPointerDbgLoc = Alloca;
1158 }
Anders Carlssond5cab542009-02-12 17:55:02 +00001159
John McCallea1471e2010-05-20 01:18:31 +00001160 // If we have a C++ 'this' reference, go ahead and force it into
1161 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001162 if (blockDecl->capturesCXXThis()) {
1163 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1164 blockInfo.CXXThisIndex,
1165 "block.captured-this");
1166 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001167 }
1168
John McCall6b5a61b2011-02-07 10:33:21 +00001169 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1170 // appease it.
1171 if (const ObjCMethodDecl *method
1172 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1173 const VarDecl *self = method->getSelfDecl();
1174
1175 // There might not be a capture for 'self', but if there is...
1176 if (blockInfo.Captures.count(self)) {
1177 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
Adrian Prantl836e7c92013-03-14 17:53:33 +00001178
John McCall6b5a61b2011-02-07 10:33:21 +00001179 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1180 capture.getIndex(),
1181 "block.captured-self");
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001182 LocalDeclMap[self] = selfAddr;
John McCall6b5a61b2011-02-07 10:33:21 +00001183 }
1184 }
1185
1186 // Also force all the constant captures.
1187 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1188 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1189 const VarDecl *variable = ci->getVariable();
1190 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1191 if (!capture.isConstant()) continue;
1192
1193 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1194
1195 llvm::AllocaInst *alloca =
1196 CreateMemTemp(variable->getType(), "block.captured-const");
1197 alloca->setAlignment(align);
1198
Adrian Prantl836e7c92013-03-14 17:53:33 +00001199 Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
John McCall6b5a61b2011-02-07 10:33:21 +00001200
1201 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001202 }
1203
John McCallf4b88a42012-03-10 09:33:50 +00001204 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001205 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1206 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1207 --entry_ptr;
1208
Eli Friedman64bee652012-02-25 02:48:22 +00001209 if (IsLambdaConversionToBlock)
1210 EmitLambdaBlockInvokeBody();
1211 else
1212 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001213
Mike Stumpde8c5c72009-10-01 00:27:30 +00001214 // Remember where we were...
1215 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001216
Mike Stumpde8c5c72009-10-01 00:27:30 +00001217 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001218 ++entry_ptr;
1219 Builder.SetInsertPoint(entry, entry_ptr);
1220
John McCallf4b88a42012-03-10 09:33:50 +00001221 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001222 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001223 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001224 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1225 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1226 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001227 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001228
Douglas Gregor4cdad312012-10-23 20:05:01 +00001229 if (CGM.getCodeGenOpts().getDebugInfo()
1230 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001231 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1232 if (capture.isConstant()) {
1233 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1234 Builder);
1235 continue;
1236 }
John McCall6b5a61b2011-02-07 10:33:21 +00001237
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001238 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001239 Builder, blockInfo);
1240 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001241 }
Manman Ren3c7a0e12013-01-04 18:51:35 +00001242 // Recover location if it was changed in the above loop.
1243 DI->EmitLocation(Builder,
Adrian Prantld83cdd62013-04-08 20:52:12 +00001244 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stumpb1a6e682009-09-30 02:43:10 +00001245 }
John McCall6b5a61b2011-02-07 10:33:21 +00001246
Mike Stumpde8c5c72009-10-01 00:27:30 +00001247 // And resume where we left off.
1248 if (resume == 0)
1249 Builder.ClearInsertionPoint();
1250 else
1251 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001252
John McCall6b5a61b2011-02-07 10:33:21 +00001253 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001254
John McCall6b5a61b2011-02-07 10:33:21 +00001255 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001256}
Mike Stumpa99038c2009-02-28 09:07:16 +00001257
John McCall6b5a61b2011-02-07 10:33:21 +00001258/*
1259 notes.push_back(HelperInfo());
1260 HelperInfo &note = notes.back();
1261 note.index = capture.getIndex();
1262 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1263 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001264
John McCall6b5a61b2011-02-07 10:33:21 +00001265 if (ci->isByRef()) {
1266 note.flag = BLOCK_FIELD_IS_BYREF;
1267 if (type.isObjCGCWeak())
1268 note.flag |= BLOCK_FIELD_IS_WEAK;
1269 } else if (type->isBlockPointerType()) {
1270 note.flag = BLOCK_FIELD_IS_BLOCK;
1271 } else {
1272 note.flag = BLOCK_FIELD_IS_OBJECT;
1273 }
1274 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001275
Mike Stump00470a12009-03-05 08:32:30 +00001276
John McCallb62faef2013-01-22 03:56:22 +00001277/// Generate the copy-helper function for a block closure object:
1278/// static void block_copy_helper(block_t *dst, block_t *src);
1279/// The runtime will have previously initialized 'dst' by doing a
1280/// bit-copy of 'src'.
1281///
1282/// Note that this copies an entire block closure object to the heap;
1283/// it should not be confused with a 'byref copy helper', which moves
1284/// the contents of an individual __block variable to the heap.
John McCall6b5a61b2011-02-07 10:33:21 +00001285llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001286CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001287 ASTContext &C = getContext();
1288
1289 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001290 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1291 args.push_back(&dstDecl);
1292 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1293 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Mike Stumpa4f668f2009-03-06 01:33:24 +00001295 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001296 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1297 FunctionType::ExtInfo(),
1298 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001299
John McCall6b5a61b2011-02-07 10:33:21 +00001300 // FIXME: it would be nice if these were mergeable with things with
1301 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001302 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001303
1304 llvm::Function *Fn =
1305 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001306 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001307
1308 IdentifierInfo *II
1309 = &CGM.getContext().Idents.get("__copy_helper_block_");
1310
Devang Patel58dc5ca2011-05-02 20:37:08 +00001311 // Check if we should generate debug info for this block helper function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001312 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001313
John McCall6b5a61b2011-02-07 10:33:21 +00001314 FunctionDecl *FD = FunctionDecl::Create(C,
1315 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001316 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001317 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001318 SC_Static,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001319 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001320 false);
John McCalld26bc762011-03-09 04:27:21 +00001321 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001322
Chris Lattner2acc6e32011-07-18 04:24:23 +00001323 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001324
John McCalld26bc762011-03-09 04:27:21 +00001325 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001326 src = Builder.CreateLoad(src);
1327 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001328
John McCalld26bc762011-03-09 04:27:21 +00001329 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001330 dst = Builder.CreateLoad(dst);
1331 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001332
John McCall6b5a61b2011-02-07 10:33:21 +00001333 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001334
John McCall6b5a61b2011-02-07 10:33:21 +00001335 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1336 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1337 const VarDecl *variable = ci->getVariable();
1338 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001339
John McCall6b5a61b2011-02-07 10:33:21 +00001340 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1341 if (capture.isConstant()) continue;
1342
1343 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001344 BlockFieldFlags flags;
1345
John McCall015f33b2012-10-17 02:28:37 +00001346 bool useARCWeakCopy = false;
1347 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001348
1349 if (copyExpr) {
1350 assert(!ci->isByRef());
1351 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001352
John McCall6b5a61b2011-02-07 10:33:21 +00001353 } else if (ci->isByRef()) {
1354 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001355 if (type.isObjCGCWeak())
1356 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001357
John McCallf85e1932011-06-15 23:02:42 +00001358 } else if (type->isObjCRetainableType()) {
1359 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001360 bool isBlockPointer = type->isBlockPointerType();
1361 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001362 flags = BLOCK_FIELD_IS_BLOCK;
1363
1364 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001365 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001366 Qualifiers qs = type.getQualifiers();
1367
John McCall015f33b2012-10-17 02:28:37 +00001368 // We need to register __weak direct captures with the runtime.
1369 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1370 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001371
John McCall015f33b2012-10-17 02:28:37 +00001372 // We need to retain the copied value for __strong direct captures.
1373 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1374 // If it's a block pointer, we have to copy the block and
1375 // assign that to the destination pointer, so we might as
1376 // well use _Block_object_assign. Otherwise we can avoid that.
1377 if (!isBlockPointer)
1378 useARCStrongCopy = true;
1379
1380 // Otherwise the memcpy is fine.
1381 } else {
1382 continue;
1383 }
1384
1385 // Non-ARC captures of retainable pointers are strong and
1386 // therefore require a call to _Block_object_assign.
1387 } else {
1388 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001389 }
1390 } else {
1391 continue;
1392 }
John McCall6b5a61b2011-02-07 10:33:21 +00001393
1394 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001395 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1396 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001397
1398 // If there's an explicit copy expression, we do that.
1399 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001400 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001401 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001402 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001403 } else {
1404 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001405 if (useARCStrongCopy) {
1406 // At -O0, store null into the destination field (so that the
1407 // storeStrong doesn't over-release) and then call storeStrong.
1408 // This is a workaround to not having an initStrong call.
1409 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1410 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1411 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1412 Builder.CreateStore(null, dstField);
1413 EmitARCStoreStrongCall(dstField, srcValue, true);
1414
1415 // With optimization enabled, take advantage of the fact that
1416 // the blocks runtime guarantees a memcpy of the block data, and
1417 // just emit a retain of the src field.
1418 } else {
1419 EmitARCRetainNonBlock(srcValue);
1420
1421 // We don't need this anymore, so kill it. It's not quite
1422 // worth the annoyance to avoid creating it in the first place.
1423 cast<llvm::Instruction>(dstField)->eraseFromParent();
1424 }
1425 } else {
1426 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1427 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCallbd7370a2013-02-28 19:01:20 +00001428 llvm::Value *args[] = {
1429 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1430 };
1431
1432 bool copyCanThrow = false;
1433 if (ci->isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1434 const Expr *copyExpr =
1435 CGM.getContext().getBlockVarCopyInits(variable);
1436 if (copyExpr) {
1437 copyCanThrow = true; // FIXME: reuse the noexcept logic
1438 }
1439 }
1440
1441 if (copyCanThrow) {
1442 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1443 } else {
1444 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1445 }
John McCall015f33b2012-10-17 02:28:37 +00001446 }
Mike Stump08920992009-03-07 02:35:30 +00001447 }
1448 }
1449
John McCalld16c2cf2011-02-08 08:22:06 +00001450 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001451
John McCall5936e332011-02-15 09:22:45 +00001452 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001453}
1454
John McCallb62faef2013-01-22 03:56:22 +00001455/// Generate the destroy-helper function for a block closure object:
1456/// static void block_destroy_helper(block_t *theBlock);
1457///
1458/// Note that this destroys a heap-allocated block closure object;
1459/// it should not be confused with a 'byref destroy helper', which
1460/// destroys the heap-allocated contents of an individual __block
1461/// variable.
John McCall6b5a61b2011-02-07 10:33:21 +00001462llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001463CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001464 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001465
John McCall6b5a61b2011-02-07 10:33:21 +00001466 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001467 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1468 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Mike Stumpa4f668f2009-03-06 01:33:24 +00001470 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001471 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1472 FunctionType::ExtInfo(),
1473 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001474
Mike Stump3899a7f2009-06-05 23:26:36 +00001475 // FIXME: We'd like to put these into a mergable by content, with
1476 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001477 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001478
1479 llvm::Function *Fn =
1480 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001481 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001482
Devang Patel58dc5ca2011-05-02 20:37:08 +00001483 // Check if we should generate debug info for this block destroy function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001484 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001485
Mike Stumpa4f668f2009-03-06 01:33:24 +00001486 IdentifierInfo *II
1487 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1488
John McCall6b5a61b2011-02-07 10:33:21 +00001489 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001490 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001491 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001492 SC_Static,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001493 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001494 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001495
Chris Lattner2acc6e32011-07-18 04:24:23 +00001496 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001497
John McCalld26bc762011-03-09 04:27:21 +00001498 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001499 src = Builder.CreateLoad(src);
1500 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001501
John McCall6b5a61b2011-02-07 10:33:21 +00001502 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1503
John McCalld16c2cf2011-02-08 08:22:06 +00001504 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001505
1506 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1507 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1508 const VarDecl *variable = ci->getVariable();
1509 QualType type = variable->getType();
1510
1511 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1512 if (capture.isConstant()) continue;
1513
John McCalld16c2cf2011-02-08 08:22:06 +00001514 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001515 const CXXDestructorDecl *dtor = 0;
1516
John McCall015f33b2012-10-17 02:28:37 +00001517 bool useARCWeakDestroy = false;
1518 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001519
John McCall6b5a61b2011-02-07 10:33:21 +00001520 if (ci->isByRef()) {
1521 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001522 if (type.isObjCGCWeak())
1523 flags |= BLOCK_FIELD_IS_WEAK;
1524 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1525 if (record->hasTrivialDestructor())
1526 continue;
1527 dtor = record->getDestructor();
1528 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001529 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001530 if (type->isBlockPointerType())
1531 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001532
John McCallf85e1932011-06-15 23:02:42 +00001533 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001534 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001535 Qualifiers qs = type.getQualifiers();
1536
1537 // Don't generate special dispose logic for a captured object
1538 // unless it's __strong or __weak.
1539 if (!qs.hasStrongOrWeakObjCLifetime())
1540 continue;
1541
1542 // Support __weak direct captures.
1543 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001544 useARCWeakDestroy = true;
1545
1546 // Tools really want us to use objc_storeStrong here.
1547 else
1548 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001549 }
1550 } else {
1551 continue;
1552 }
John McCall6b5a61b2011-02-07 10:33:21 +00001553
1554 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001555 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001556
1557 // If there's an explicit copy expression, we do that.
1558 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001559 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001560
John McCallf85e1932011-06-15 23:02:42 +00001561 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001562 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001563 EmitARCDestroyWeak(srcField);
1564
John McCall015f33b2012-10-17 02:28:37 +00001565 // Destroy strong objects with a call if requested.
1566 } else if (useARCStrongDestroy) {
John McCall5b07e802013-03-13 03:10:54 +00001567 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCall015f33b2012-10-17 02:28:37 +00001568
John McCall6b5a61b2011-02-07 10:33:21 +00001569 // Otherwise we call _Block_object_dispose. It wouldn't be too
1570 // hard to just emit this as a cleanup if we wanted to make sure
1571 // that things were done in reverse.
1572 } else {
1573 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001574 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001575 BuildBlockRelease(value, flags);
1576 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001577 }
1578
John McCall6b5a61b2011-02-07 10:33:21 +00001579 cleanups.ForceCleanup();
1580
John McCalld16c2cf2011-02-08 08:22:06 +00001581 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001582
John McCall5936e332011-02-15 09:22:45 +00001583 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001584}
1585
John McCallf0c11f72011-03-31 08:03:29 +00001586namespace {
1587
1588/// Emits the copy/dispose helper functions for a __block object of id type.
1589class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1590 BlockFieldFlags Flags;
1591
1592public:
1593 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1594 : ByrefHelpers(alignment), Flags(flags) {}
1595
John McCall36170192011-03-31 09:19:20 +00001596 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1597 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001598 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1599
1600 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1601 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1602
1603 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1604
1605 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1606 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCallbd7370a2013-02-28 19:01:20 +00001607
1608 llvm::Value *args[] = { destField, srcValue, flagsVal };
1609 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf0c11f72011-03-31 08:03:29 +00001610 }
1611
1612 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1613 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1614 llvm::Value *value = CGF.Builder.CreateLoad(field);
1615
1616 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1617 }
1618
1619 void profileImpl(llvm::FoldingSetNodeID &id) const {
1620 id.AddInteger(Flags.getBitMask());
1621 }
1622};
1623
John McCallf85e1932011-06-15 23:02:42 +00001624/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1625class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1626public:
1627 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1628
1629 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1630 llvm::Value *srcField) {
1631 CGF.EmitARCMoveWeak(destField, srcField);
1632 }
1633
1634 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1635 CGF.EmitARCDestroyWeak(field);
1636 }
1637
1638 void profileImpl(llvm::FoldingSetNodeID &id) const {
1639 // 0 is distinguishable from all pointers and byref flags
1640 id.AddInteger(0);
1641 }
1642};
1643
1644/// Emits the copy/dispose helpers for an ARC __block __strong variable
1645/// that's not of block-pointer type.
1646class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1647public:
1648 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1649
1650 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1651 llvm::Value *srcField) {
1652 // Do a "move" by copying the value and then zeroing out the old
1653 // variable.
1654
John McCalla59e4b72011-11-09 03:17:26 +00001655 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1656 value->setAlignment(Alignment.getQuantity());
1657
John McCallf85e1932011-06-15 23:02:42 +00001658 llvm::Value *null =
1659 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001660
Fariborz Jahanian7a77f192013-01-04 23:32:24 +00001661 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
Fariborz Jahanianba3c9ca2013-01-05 00:32:13 +00001662 llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1663 store->setAlignment(Alignment.getQuantity());
Fariborz Jahanian7a77f192013-01-04 23:32:24 +00001664 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1665 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1666 return;
1667 }
John McCalla59e4b72011-11-09 03:17:26 +00001668 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1669 store->setAlignment(Alignment.getQuantity());
1670
1671 store = CGF.Builder.CreateStore(null, srcField);
1672 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001673 }
1674
1675 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall5b07e802013-03-13 03:10:54 +00001676 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001677 }
1678
1679 void profileImpl(llvm::FoldingSetNodeID &id) const {
1680 // 1 is distinguishable from all pointers and byref flags
1681 id.AddInteger(1);
1682 }
1683};
1684
John McCalla59e4b72011-11-09 03:17:26 +00001685/// Emits the copy/dispose helpers for an ARC __block __strong
1686/// variable that's of block-pointer type.
1687class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1688public:
1689 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1690
1691 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1692 llvm::Value *srcField) {
1693 // Do the copy with objc_retainBlock; that's all that
1694 // _Block_object_assign would do anyway, and we'd have to pass the
1695 // right arguments to make sure it doesn't get no-op'ed.
1696 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1697 oldValue->setAlignment(Alignment.getQuantity());
1698
1699 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1700
1701 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1702 store->setAlignment(Alignment.getQuantity());
1703 }
1704
1705 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall5b07e802013-03-13 03:10:54 +00001706 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCalla59e4b72011-11-09 03:17:26 +00001707 }
1708
1709 void profileImpl(llvm::FoldingSetNodeID &id) const {
1710 // 2 is distinguishable from all pointers and byref flags
1711 id.AddInteger(2);
1712 }
1713};
1714
John McCallf0c11f72011-03-31 08:03:29 +00001715/// Emits the copy/dispose helpers for a __block variable with a
1716/// nontrivial copy constructor or destructor.
1717class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1718 QualType VarType;
1719 const Expr *CopyExpr;
1720
1721public:
1722 CXXByrefHelpers(CharUnits alignment, QualType type,
1723 const Expr *copyExpr)
1724 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1725
1726 bool needsCopy() const { return CopyExpr != 0; }
1727 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1728 llvm::Value *srcField) {
1729 if (!CopyExpr) return;
1730 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1731 }
1732
1733 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1734 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1735 CGF.PushDestructorCleanup(VarType, field);
1736 CGF.PopCleanupBlocks(cleanupDepth);
1737 }
1738
1739 void profileImpl(llvm::FoldingSetNodeID &id) const {
1740 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1741 }
1742};
1743} // end anonymous namespace
1744
1745static llvm::Constant *
1746generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001747 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001748 unsigned valueFieldIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001749 CodeGenModule::ByrefHelpers &byrefInfo) {
1750 ASTContext &Context = CGF.getContext();
1751
1752 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001753
John McCalld26bc762011-03-09 04:27:21 +00001754 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001755 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001756 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001757
John McCallf0c11f72011-03-31 08:03:29 +00001758 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001759 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Mike Stump45031c02009-03-06 02:29:21 +00001761 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001762 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1763 FunctionType::ExtInfo(),
1764 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001765
John McCallf0c11f72011-03-31 08:03:29 +00001766 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001767 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001768
Mike Stump3899a7f2009-06-05 23:26:36 +00001769 // FIXME: We'd like to put these into a mergable by content, with
1770 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001771 llvm::Function *Fn =
1772 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001773 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001774
1775 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001776 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001777
John McCallf0c11f72011-03-31 08:03:29 +00001778 FunctionDecl *FD = FunctionDecl::Create(Context,
1779 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001780 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001781 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001782 SC_Static,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001783 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001784
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001785 // Initialize debug info if necessary.
1786 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001787 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001788
John McCallf0c11f72011-03-31 08:03:29 +00001789 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001790 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001791
John McCallf0c11f72011-03-31 08:03:29 +00001792 // dst->x
1793 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1794 destField = CGF.Builder.CreateLoad(destField);
1795 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCallb62faef2013-01-22 03:56:22 +00001796 destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001797
John McCallf0c11f72011-03-31 08:03:29 +00001798 // src->x
1799 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1800 srcField = CGF.Builder.CreateLoad(srcField);
1801 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCallb62faef2013-01-22 03:56:22 +00001802 srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
John McCallf0c11f72011-03-31 08:03:29 +00001803
1804 byrefInfo.emitCopy(CGF, destField, srcField);
1805 }
1806
1807 CGF.FinishFunction();
1808
1809 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001810}
1811
John McCallf0c11f72011-03-31 08:03:29 +00001812/// Build the copy helper for a __block variable.
1813static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001814 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001815 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001816 CodeGenModule::ByrefHelpers &info) {
1817 CodeGenFunction CGF(CGM);
John McCallb62faef2013-01-22 03:56:22 +00001818 return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
John McCallf0c11f72011-03-31 08:03:29 +00001819}
1820
1821/// Generate code for a __block variable's dispose helper.
1822static llvm::Constant *
1823generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001824 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001825 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001826 CodeGenModule::ByrefHelpers &byrefInfo) {
1827 ASTContext &Context = CGF.getContext();
1828 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001829
John McCalld26bc762011-03-09 04:27:21 +00001830 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001831 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001832 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Mike Stump45031c02009-03-06 02:29:21 +00001834 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001835 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1836 FunctionType::ExtInfo(),
1837 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001838
John McCallf0c11f72011-03-31 08:03:29 +00001839 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001840 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001841
Mike Stump3899a7f2009-06-05 23:26:36 +00001842 // FIXME: We'd like to put these into a mergable by content, with
1843 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001844 llvm::Function *Fn =
1845 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001846 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001847 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001848
1849 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001850 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001851
John McCallf0c11f72011-03-31 08:03:29 +00001852 FunctionDecl *FD = FunctionDecl::Create(Context,
1853 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001854 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001855 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001856 SC_Static,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001857 false, false);
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001858 // Initialize debug info if necessary.
1859 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001860 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001861
John McCallf0c11f72011-03-31 08:03:29 +00001862 if (byrefInfo.needsDispose()) {
1863 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1864 V = CGF.Builder.CreateLoad(V);
1865 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
John McCallb62faef2013-01-22 03:56:22 +00001866 V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001867
John McCallf0c11f72011-03-31 08:03:29 +00001868 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001869 }
Mike Stump45031c02009-03-06 02:29:21 +00001870
John McCallf0c11f72011-03-31 08:03:29 +00001871 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001872
John McCallf0c11f72011-03-31 08:03:29 +00001873 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001874}
1875
John McCallf0c11f72011-03-31 08:03:29 +00001876/// Build the dispose helper for a __block variable.
1877static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001878 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001879 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001880 CodeGenModule::ByrefHelpers &info) {
1881 CodeGenFunction CGF(CGM);
John McCallb62faef2013-01-22 03:56:22 +00001882 return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
Mike Stump45031c02009-03-06 02:29:21 +00001883}
1884
John McCallb62faef2013-01-22 03:56:22 +00001885/// Lazily build the copy and dispose helpers for a __block variable
1886/// with the given information.
John McCallf0c11f72011-03-31 08:03:29 +00001887template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001888 llvm::StructType &byrefTy,
John McCallb62faef2013-01-22 03:56:22 +00001889 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001890 T &byrefInfo) {
1891 // Increase the field's alignment to be at least pointer alignment,
1892 // since the layout of the byref struct will guarantee at least that.
1893 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1894 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1895
1896 llvm::FoldingSetNodeID id;
1897 byrefInfo.Profile(id);
1898
1899 void *insertPos;
1900 CodeGenModule::ByrefHelpers *node
1901 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1902 if (node) return static_cast<T*>(node);
1903
John McCallb62faef2013-01-22 03:56:22 +00001904 byrefInfo.CopyHelper =
1905 buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1906 byrefInfo.DisposeHelper =
1907 buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
John McCallf0c11f72011-03-31 08:03:29 +00001908
1909 T *copy = new (CGM.getContext()) T(byrefInfo);
1910 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1911 return copy;
1912}
1913
John McCallb62faef2013-01-22 03:56:22 +00001914/// Build the copy and dispose helpers for the given __block variable
1915/// emission. Places the helpers in the global cache. Returns null
1916/// if no helpers are required.
John McCallf0c11f72011-03-31 08:03:29 +00001917CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001918CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001919 const AutoVarEmission &emission) {
1920 const VarDecl &var = *emission.Variable;
1921 QualType type = var.getType();
1922
John McCallb62faef2013-01-22 03:56:22 +00001923 unsigned byrefValueIndex = getByRefValueLLVMField(&var);
1924
John McCallf0c11f72011-03-31 08:03:29 +00001925 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1926 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1927 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1928
1929 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
John McCallb62faef2013-01-22 03:56:22 +00001930 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf0c11f72011-03-31 08:03:29 +00001931 }
1932
John McCallf85e1932011-06-15 23:02:42 +00001933 // Otherwise, if we don't have a retainable type, there's nothing to do.
1934 // that the runtime does extra copies.
1935 if (!type->isObjCRetainableType()) return 0;
1936
1937 Qualifiers qs = type.getQualifiers();
1938
1939 // If we have lifetime, that dominates.
1940 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001941 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001942
1943 switch (lifetime) {
1944 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1945
1946 // These are just bits as far as the runtime is concerned.
1947 case Qualifiers::OCL_ExplicitNone:
1948 case Qualifiers::OCL_Autoreleasing:
1949 return 0;
1950
1951 // Tell the runtime that this is ARC __weak, called by the
1952 // byref routines.
1953 case Qualifiers::OCL_Weak: {
1954 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001955 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001956 }
1957
1958 // ARC __strong __block variables need to be retained.
1959 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001960 // Block pointers need to be copied, and there's no direct
1961 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001962 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001963 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001964 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001965
1966 // Otherwise, we transfer ownership of the retain from the stack
1967 // to the heap.
1968 } else {
1969 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001970 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001971 }
1972 }
1973 llvm_unreachable("fell out of lifetime switch!");
1974 }
1975
John McCallf0c11f72011-03-31 08:03:29 +00001976 BlockFieldFlags flags;
1977 if (type->isBlockPointerType()) {
1978 flags |= BLOCK_FIELD_IS_BLOCK;
1979 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1980 type->isObjCObjectPointerType()) {
1981 flags |= BLOCK_FIELD_IS_OBJECT;
1982 } else {
1983 return 0;
1984 }
1985
1986 if (type.isObjCGCWeak())
1987 flags |= BLOCK_FIELD_IS_WEAK;
1988
1989 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
John McCallb62faef2013-01-22 03:56:22 +00001990 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001991}
1992
John McCall5af02db2011-03-31 01:59:53 +00001993unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1994 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1995
1996 return ByRefValueInfo.find(VD)->second.second;
1997}
1998
1999llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
2000 const VarDecl *V) {
2001 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
2002 Loc = Builder.CreateLoad(Loc);
2003 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
2004 V->getNameAsString());
2005 return Loc;
2006}
2007
2008/// BuildByRefType - This routine changes a __block variable declared as T x
2009/// into:
2010///
2011/// struct {
2012/// void *__isa;
2013/// void *__forwarding;
2014/// int32_t __flags;
2015/// int32_t __size;
2016/// void *__copy_helper; // only if needed
2017/// void *__destroy_helper; // only if needed
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002018/// void *__byref_variable_layout;// only if needed
John McCall5af02db2011-03-31 01:59:53 +00002019/// char padding[X]; // only if needed
2020/// T x;
2021/// } x
2022///
Chris Lattner2acc6e32011-07-18 04:24:23 +00002023llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
2024 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00002025 if (Info.first)
2026 return Info.first;
2027
2028 QualType Ty = D->getType();
2029
Chris Lattner5f9e2722011-07-23 10:55:15 +00002030 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00002031
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002032 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00002033 llvm::StructType::create(getLLVMContext(),
2034 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00002035
2036 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00002037 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002038
2039 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002040 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00002041
2042 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00002043 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00002044
2045 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00002046 types.push_back(Int32Ty);
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00002047 // Note that this must match *exactly* the logic in buildByrefHelpers.
2048 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
John McCall5af02db2011-03-31 01:59:53 +00002049 if (HasCopyAndDispose) {
2050 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00002051 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002052
2053 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00002054 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002055 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002056 bool HasByrefExtendedLayout = false;
2057 Qualifiers::ObjCLifetime Lifetime;
2058 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2059 HasByrefExtendedLayout)
2060 /// void *__byref_variable_layout;
2061 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002062
2063 bool Packed = false;
2064 CharUnits Align = getContext().getDeclAlign(D);
2065 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
2066 // We have to insert padding.
2067
2068 // The struct above has 2 32-bit integers.
2069 unsigned CurrentOffsetInBytes = 4 * 2;
2070
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002071 // And either 2, 3, 4 or 5 pointers.
2072 unsigned noPointers = 2;
2073 if (HasCopyAndDispose)
2074 noPointers += 2;
2075 if (HasByrefExtendedLayout)
2076 noPointers += 1;
2077
2078 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002079
2080 // Align the offset.
2081 unsigned AlignedOffsetInBytes =
2082 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2083
2084 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2085 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00002086 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00002087 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00002088 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00002089 if (NumPaddingBytes > 1)
2090 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2091
John McCall0774cb82011-05-15 01:53:33 +00002092 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00002093
2094 // We want a packed struct.
2095 Packed = true;
2096 }
2097 }
2098
2099 // T x;
John McCall0774cb82011-05-15 01:53:33 +00002100 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00002101
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002102 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00002103
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002104 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00002105
John McCall0774cb82011-05-15 01:53:33 +00002106 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00002107
2108 return Info.first;
2109}
2110
2111/// Initialize the structural components of a __block variable, i.e.
2112/// everything but the actual object.
2113void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00002114 // Find the address of the local.
2115 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00002116
John McCallf0c11f72011-03-31 08:03:29 +00002117 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002118 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00002119 cast<llvm::PointerType>(addr->getType())->getElementType());
2120
2121 // Build the byref helpers if necessary. This is null if we don't need any.
2122 CodeGenModule::ByrefHelpers *helpers =
2123 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00002124
2125 const VarDecl &D = *emission.Variable;
2126 QualType type = D.getType();
2127
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002128 bool HasByrefExtendedLayout;
2129 Qualifiers::ObjCLifetime ByrefLifetime;
2130 bool ByRefHasLifetime =
2131 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2132
John McCallf0c11f72011-03-31 08:03:29 +00002133 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00002134
2135 // Initialize the 'isa', which is just 0 or 1.
2136 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00002137 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00002138 isa = 1;
2139 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2140 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2141
2142 // Store the address of the variable into its own forwarding pointer.
2143 Builder.CreateStore(addr,
2144 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2145
2146 // Blocks ABI:
2147 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002148 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall5af02db2011-03-31 01:59:53 +00002149 BlockFlags flags;
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002150 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2151 if (ByRefHasLifetime) {
2152 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2153 else switch (ByrefLifetime) {
2154 case Qualifiers::OCL_Strong:
2155 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2156 break;
2157 case Qualifiers::OCL_Weak:
2158 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2159 break;
2160 case Qualifiers::OCL_ExplicitNone:
2161 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2162 break;
2163 case Qualifiers::OCL_None:
2164 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2165 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2166 break;
2167 default:
2168 break;
2169 }
2170 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2171 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2172 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2173 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2174 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2175 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2176 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2177 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2178 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2179 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2180 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2181 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2182 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2183 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2184 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2185 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2186 }
2187 printf("\n");
2188 }
2189 }
2190
John McCall5af02db2011-03-31 01:59:53 +00002191 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2192 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2193
John McCallf0c11f72011-03-31 08:03:29 +00002194 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2195 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00002196 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2197
John McCallf0c11f72011-03-31 08:03:29 +00002198 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00002199 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00002200 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002201
2202 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002203 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002204 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002205 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2206 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2207 llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2208 "byref.layout");
2209 // cast destination to pointer to source type.
2210 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2211 DesTy = DesTy->getPointerTo();
2212 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2213 Builder.CreateStore(ByrefLayoutInfo, BC);
2214 }
John McCall5af02db2011-03-31 01:59:53 +00002215}
2216
John McCalld16c2cf2011-02-08 08:22:06 +00002217void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002218 llvm::Value *F = CGM.getBlockObjectDispose();
John McCallbd7370a2013-02-28 19:01:20 +00002219 llvm::Value *args[] = {
2220 Builder.CreateBitCast(V, Int8PtrTy),
2221 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2222 };
2223 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump797b6322009-03-05 01:23:13 +00002224}
John McCall5af02db2011-03-31 01:59:53 +00002225
2226namespace {
2227 struct CallBlockRelease : EHScopeStack::Cleanup {
2228 llvm::Value *Addr;
2229 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2230
John McCallad346f42011-07-12 20:27:29 +00002231 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002232 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002233 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2234 }
2235 };
2236}
2237
2238/// Enter a cleanup to destroy a __block variable. Note that this
2239/// cleanup should be a no-op if the variable hasn't left the stack
2240/// yet; if a cleanup is required for the variable itself, that needs
2241/// to be done externally.
2242void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2243 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002244 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002245 return;
2246
2247 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2248}
John McCall13db5cf2011-09-09 20:41:01 +00002249
2250/// Adjust the declaration of something from the blocks API.
2251static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2252 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002253 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002254
2255 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2256 if (GV->isDeclaration() &&
2257 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2258 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2259}
2260
2261llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2262 if (BlockObjectDispose)
2263 return BlockObjectDispose;
2264
2265 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2266 llvm::FunctionType *fty
2267 = llvm::FunctionType::get(VoidTy, args, false);
2268 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2269 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2270 return BlockObjectDispose;
2271}
2272
2273llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2274 if (BlockObjectAssign)
2275 return BlockObjectAssign;
2276
2277 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2278 llvm::FunctionType *fty
2279 = llvm::FunctionType::get(VoidTy, args, false);
2280 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2281 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2282 return BlockObjectAssign;
2283}
2284
2285llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2286 if (NSConcreteGlobalBlock)
2287 return NSConcreteGlobalBlock;
2288
2289 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2290 Int8PtrTy->getPointerTo(), 0);
2291 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2292 return NSConcreteGlobalBlock;
2293}
2294
2295llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2296 if (NSConcreteStackBlock)
2297 return NSConcreteStackBlock;
2298
2299 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2300 Int8PtrTy->getPointerTo(), 0);
2301 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2302 return NSConcreteStackBlock;
2303}