blob: 3d825d33332f0fd742270e7201b4035ed8c95487 [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.
Dmitri Gribenko41487f32013-05-08 23:09:44 +000066/// \code
Fariborz Jahanianaf879c02012-10-25 18:06:53 +000067/// struct Block_descriptor {
68/// unsigned long reserved;
69/// unsigned long size; // size of Block_literal metadata in bytes.
70/// void *copy_func_helper_decl; // optional copy helper.
71/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko41487f32013-05-08 23:09:44 +000072/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianaf879c02012-10-25 18:06:53 +000073/// void *block_layout_info; // encoding of captured block variables.
74/// };
Dmitri Gribenko41487f32013-05-08 23:09:44 +000075/// \endcode
John McCall6b5a61b2011-02-07 10:33:21 +000076static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
77 const CGBlockInfo &blockInfo) {
78 ASTContext &C = CGM.getContext();
79
Chris Lattner2acc6e32011-07-18 04:24:23 +000080 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
81 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000082
Chris Lattner5f9e2722011-07-23 10:55:15 +000083 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000084
85 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000086 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000087
88 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000089 // FIXME: What is the right way to say this doesn't fit? We should give
90 // a user diagnostic in that case. Better fix would be to change the
91 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000092 elements.push_back(llvm::ConstantInt::get(ulong,
93 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000094
John McCall6b5a61b2011-02-07 10:33:21 +000095 // Optional copy/dispose helpers.
96 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000097 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000098 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000099
100 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +0000101 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +0000102 }
103
John McCall6b5a61b2011-02-07 10:33:21 +0000104 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
105 std::string typeAtEncoding =
106 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
107 elements.push_back(llvm::ConstantExpr::getBitCast(
108 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000109
John McCall6b5a61b2011-02-07 10:33:21 +0000110 // GC layout.
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000111 if (C.getLangOpts().ObjC1) {
112 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
113 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
114 else
115 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
116 }
John McCall6b5a61b2011-02-07 10:33:21 +0000117 else
118 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000119
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000120 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000121
John McCall6b5a61b2011-02-07 10:33:21 +0000122 llvm::GlobalVariable *global =
123 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
124 llvm::GlobalValue::InternalLinkage,
125 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000126
John McCall6b5a61b2011-02-07 10:33:21 +0000127 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000128}
129
John McCall6b5a61b2011-02-07 10:33:21 +0000130/*
131 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000132
John McCall6b5a61b2011-02-07 10:33:21 +0000133 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
134 struct Block_literal {
135 /// Initialized to one of:
136 /// extern void *_NSConcreteStackBlock[];
137 /// extern void *_NSConcreteGlobalBlock[];
138 ///
139 /// In theory, we could start one off malloc'ed by setting
140 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
141 /// this isa:
142 /// extern void *_NSConcreteMallocBlock[];
143 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000144
John McCall6b5a61b2011-02-07 10:33:21 +0000145 /// These are the flags (with corresponding bit number) that the
146 /// compiler is actually supposed to know about.
147 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
148 /// descriptor provides copy and dispose helper functions
149 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
150 /// object with a nontrivial destructor or copy constructor
151 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
152 /// as global memory
153 /// 29. BLOCK_USE_STRET - indicates that the block function
154 /// uses stret, which objc_msgSend needs to know about
155 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
156 /// @encoded signature string
157 /// And we're not supposed to manipulate these:
158 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
159 /// to malloc'ed memory
160 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
161 /// to GC-allocated memory
162 /// Additionally, the bottom 16 bits are a reference count which
163 /// should be zero on the stack.
164 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000165
John McCall6b5a61b2011-02-07 10:33:21 +0000166 /// Reserved; should be zero-initialized.
167 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000168
John McCall6b5a61b2011-02-07 10:33:21 +0000169 /// Function pointer generated from block literal.
170 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000171
John McCall6b5a61b2011-02-07 10:33:21 +0000172 /// Block description metadata generated from block literal.
173 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000174
John McCall6b5a61b2011-02-07 10:33:21 +0000175 /// Captured values follow.
176 _CapturesTypes captures...;
177 };
178 */
David Chisnall5e530af2009-11-17 19:33:30 +0000179
John McCall6b5a61b2011-02-07 10:33:21 +0000180/// The number of fields in a block header.
181const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000182
John McCall6b5a61b2011-02-07 10:33:21 +0000183namespace {
184 /// A chunk of data that we actually have to capture in the block.
185 struct BlockLayoutChunk {
186 CharUnits Alignment;
187 CharUnits Size;
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000188 Qualifiers::ObjCLifetime Lifetime;
John McCall6b5a61b2011-02-07 10:33:21 +0000189 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000190 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000191
John McCall6b5a61b2011-02-07 10:33:21 +0000192 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000193 Qualifiers::ObjCLifetime lifetime,
John McCall6b5a61b2011-02-07 10:33:21 +0000194 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000195 llvm::Type *type)
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000196 : Alignment(align), Size(size), Lifetime(lifetime),
197 Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000198
John McCall6b5a61b2011-02-07 10:33:21 +0000199 /// Tell the block info that this chunk has the given field index.
200 void setIndex(CGBlockInfo &info, unsigned index) {
201 if (!Capture)
202 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000203 else
John McCall6b5a61b2011-02-07 10:33:21 +0000204 info.Captures[Capture->getVariable()]
205 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000206 }
John McCall6b5a61b2011-02-07 10:33:21 +0000207 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000208
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000209 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
210 /// all __weak together. Preserve descending alignment in all situations.
John McCall6b5a61b2011-02-07 10:33:21 +0000211 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000212 CharUnits LeftValue, RightValue;
213 bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
214 bool RightByref = right.Capture ? right.Capture->isByRef() : false;
215
216 if (left.Lifetime == Qualifiers::OCL_Strong &&
217 left.Alignment >= right.Alignment)
218 LeftValue = CharUnits::fromQuantity(64);
219 else if (LeftByref && left.Alignment >= right.Alignment)
220 LeftValue = CharUnits::fromQuantity(32);
221 else if (left.Lifetime == Qualifiers::OCL_Weak &&
222 left.Alignment >= right.Alignment)
223 LeftValue = CharUnits::fromQuantity(16);
224 else
225 LeftValue = left.Alignment;
226 if (right.Lifetime == Qualifiers::OCL_Strong &&
227 right.Alignment >= left.Alignment)
228 RightValue = CharUnits::fromQuantity(64);
229 else if (RightByref && right.Alignment >= left.Alignment)
230 RightValue = CharUnits::fromQuantity(32);
231 else if (right.Lifetime == Qualifiers::OCL_Weak &&
232 right.Alignment >= left.Alignment)
233 RightValue = CharUnits::fromQuantity(16);
234 else
235 RightValue = right.Alignment;
236
237 return LeftValue > RightValue;
John McCall6b5a61b2011-02-07 10:33:21 +0000238 }
239}
240
John McCall461c9c12011-02-08 03:07:00 +0000241/// Determines if the given type is safe for constant capture in C++.
242static bool isSafeForCXXConstantCapture(QualType type) {
243 const RecordType *recordType =
244 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
245
246 // Only records can be unsafe.
247 if (!recordType) return true;
248
249 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
250
251 // Maintain semantics for classes with non-trivial dtors or copy ctors.
252 if (!record->hasTrivialDestructor()) return false;
Richard Smith426391c2012-11-16 00:53:38 +0000253 if (record->hasNonTrivialCopyConstructor()) return false;
John McCall461c9c12011-02-08 03:07:00 +0000254
255 // Otherwise, we just have to make sure there aren't any mutable
256 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000257 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000258}
259
John McCall6b5a61b2011-02-07 10:33:21 +0000260/// It is illegal to modify a const object after initialization.
261/// Therefore, if a const object has a constant initializer, we don't
262/// actually need to keep storage for it in the block; we'll just
263/// rematerialize it at the start of the block function. This is
264/// acceptable because we make no promises about address stability of
265/// captured variables.
266static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000267 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000268 const VarDecl *var) {
269 QualType type = var->getType();
270
271 // We can only do this if the variable is const.
272 if (!type.isConstQualified()) return 0;
273
John McCall461c9c12011-02-08 03:07:00 +0000274 // Furthermore, in C++ we have to worry about mutable fields:
275 // C++ [dcl.type.cv]p4:
276 // Except that any class member declared mutable can be
277 // modified, any attempt to modify a const object during its
278 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000279 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000280 return 0;
281
282 // If the variable doesn't have any initializer (shouldn't this be
283 // invalid?), it's not clear what we should do. Maybe capture as
284 // zero?
285 const Expr *init = var->getInit();
286 if (!init) return 0;
287
Richard Smith2d6a5672012-01-14 04:30:29 +0000288 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000289}
290
291/// Get the low bit of a nonzero character count. This is the
292/// alignment of the nth byte if the 0th byte is universally aligned.
293static CharUnits getLowBit(CharUnits v) {
294 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
295}
296
297static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000298 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000299 ASTContext &C = CGM.getContext();
300
301 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
302 CharUnits ptrSize, ptrAlign, intSize, intAlign;
303 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
304 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
305
306 // Are there crazy embedded platforms where this isn't true?
307 assert(intSize <= ptrSize && "layout assumptions horribly violated");
308
309 CharUnits headerSize = ptrSize;
310 if (2 * intSize < ptrAlign) headerSize += ptrSize;
311 else headerSize += 2 * intSize;
312 headerSize += 2 * ptrSize;
313
314 info.BlockAlign = ptrAlign;
315 info.BlockSize = headerSize;
316
317 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000318 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
319 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000320 elementTypes.push_back(i8p);
321 elementTypes.push_back(intTy);
322 elementTypes.push_back(intTy);
323 elementTypes.push_back(i8p);
324 elementTypes.push_back(CGM.getBlockDescriptorType());
325
326 assert(elementTypes.size() == BlockHeaderSize);
327}
328
329/// Compute the layout of the given block. Attempts to lay the block
330/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000331static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
332 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000333 ASTContext &C = CGM.getContext();
334 const BlockDecl *block = info.getBlockDecl();
335
Chris Lattner5f9e2722011-07-23 10:55:15 +0000336 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000337 initializeForBlockHeader(CGM, info, elementTypes);
338
339 if (!block->hasCaptures()) {
340 info.StructureType =
341 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
342 info.CanBeGlobal = true;
343 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000344 }
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000345 else if (C.getLangOpts().ObjC1 &&
346 CGM.getLangOpts().getGC() == LangOptions::NonGC)
347 info.HasCapturedVariableLayout = true;
348
John McCall6b5a61b2011-02-07 10:33:21 +0000349 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000350 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000351 layout.reserve(block->capturesCXXThis() +
352 (block->capture_end() - block->capture_begin()));
353
354 CharUnits maxFieldAlign;
355
356 // First, 'this'.
357 if (block->capturesCXXThis()) {
Eli Friedmanc1b8d092013-07-12 22:05:26 +0000358 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
359 "Can't capture 'this' outside a method");
360 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000361
Jay Foadef6de3d2011-07-11 09:56:20 +0000362 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000363 std::pair<CharUnits,CharUnits> tinfo
364 = CGM.getContext().getTypeInfoInChars(thisType);
365 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
366
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000367 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
368 Qualifiers::OCL_None,
369 0, llvmType));
John McCall6b5a61b2011-02-07 10:33:21 +0000370 }
371
372 // Next, all the block captures.
373 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
374 ce = block->capture_end(); ci != ce; ++ci) {
375 const VarDecl *variable = ci->getVariable();
376
377 if (ci->isByRef()) {
378 // We have to copy/dispose of the __block reference.
379 info.NeedsCopyDispose = true;
380
John McCall6b5a61b2011-02-07 10:33:21 +0000381 // Just use void* instead of a pointer to the byref type.
382 QualType byRefPtrTy = C.VoidPtrTy;
383
Jay Foadef6de3d2011-07-11 09:56:20 +0000384 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000385 std::pair<CharUnits,CharUnits> tinfo
386 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
387 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
388
389 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000390 Qualifiers::OCL_None,
John McCall6b5a61b2011-02-07 10:33:21 +0000391 &*ci, llvmType));
392 continue;
393 }
394
395 // Otherwise, build a layout chunk with the size and alignment of
396 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000397 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000398 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
399 continue;
400 }
401
John McCallf85e1932011-06-15 23:02:42 +0000402 // If we have a lifetime qualifier, honor it for capture purposes.
403 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000404 Qualifiers::ObjCLifetime lifetime =
405 variable->getType().getObjCLifetime();
406 if (lifetime) {
John McCallf85e1932011-06-15 23:02:42 +0000407 switch (lifetime) {
408 case Qualifiers::OCL_None: llvm_unreachable("impossible");
409 case Qualifiers::OCL_ExplicitNone:
410 case Qualifiers::OCL_Autoreleasing:
411 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000412
John McCallf85e1932011-06-15 23:02:42 +0000413 case Qualifiers::OCL_Strong:
414 case Qualifiers::OCL_Weak:
415 info.NeedsCopyDispose = true;
416 }
417
418 // Block pointers require copy/dispose. So do Objective-C pointers.
419 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000420 info.NeedsCopyDispose = true;
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000421 // used for mrr below.
422 lifetime = Qualifiers::OCL_Strong;
John McCall6b5a61b2011-02-07 10:33:21 +0000423
424 // So do types that require non-trivial copy construction.
425 } else if (ci->hasCopyExpr()) {
426 info.NeedsCopyDispose = true;
427 info.HasCXXObject = true;
428
429 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000430 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000431 if (const CXXRecordDecl *record =
432 variable->getType()->getAsCXXRecordDecl()) {
433 if (!record->hasTrivialDestructor()) {
434 info.HasCXXObject = true;
435 info.NeedsCopyDispose = true;
436 }
437 }
438 }
439
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000440 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000441 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000442 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000443
John McCall6b5a61b2011-02-07 10:33:21 +0000444 maxFieldAlign = std::max(maxFieldAlign, align);
445
Jay Foadef6de3d2011-07-11 09:56:20 +0000446 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000447 CGM.getTypes().ConvertTypeForMem(VT);
448
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000449 layout.push_back(BlockLayoutChunk(align, size, lifetime, &*ci, llvmType));
John McCall6b5a61b2011-02-07 10:33:21 +0000450 }
451
452 // If that was everything, we're done here.
453 if (layout.empty()) {
454 info.StructureType =
455 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
456 info.CanBeGlobal = true;
457 return;
458 }
459
460 // Sort the layout by alignment. We have to use a stable sort here
461 // to get reproducible results. There should probably be an
462 // llvm::array_pod_stable_sort.
463 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000464
465 // Needed for blocks layout info.
466 info.BlockHeaderForcedGapOffset = info.BlockSize;
467 info.BlockHeaderForcedGapSize = CharUnits::Zero();
468
John McCall6b5a61b2011-02-07 10:33:21 +0000469 CharUnits &blockSize = info.BlockSize;
470 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
471
472 // Assuming that the first byte in the header is maximally aligned,
473 // get the alignment of the first byte following the header.
474 CharUnits endAlign = getLowBit(blockSize);
475
476 // If the end of the header isn't satisfactorily aligned for the
477 // maximum thing, look for things that are okay with the header-end
478 // alignment, and keep appending them until we get something that's
479 // aligned right. This algorithm is only guaranteed optimal if
480 // that condition is satisfied at some point; otherwise we can get
481 // things like:
482 // header // next byte has alignment 4
483 // something_with_size_5; // next byte has alignment 1
484 // something_with_alignment_8;
485 // which has 7 bytes of padding, as opposed to the naive solution
486 // which might have less (?).
487 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000488 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000489 li = layout.begin() + 1, le = layout.end();
490
491 // Look for something that the header end is already
492 // satisfactorily aligned for.
493 for (; li != le && endAlign < li->Alignment; ++li)
494 ;
495
496 // If we found something that's naturally aligned for the end of
497 // the header, keep adding things...
498 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000499 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000500 for (; li != le; ++li) {
501 assert(endAlign >= li->Alignment);
502
503 li->setIndex(info, elementTypes.size());
504 elementTypes.push_back(li->Type);
505 blockSize += li->Size;
506 endAlign = getLowBit(blockSize);
507
508 // ...until we get to the alignment of the maximum field.
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000509 if (endAlign >= maxFieldAlign) {
510 if (li == first) {
511 // No user field was appended. So, a gap was added.
512 // Save total gap size for use in block layout bit map.
513 info.BlockHeaderForcedGapSize = li->Size;
514 }
John McCall6b5a61b2011-02-07 10:33:21 +0000515 break;
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000516 }
John McCall6b5a61b2011-02-07 10:33:21 +0000517 }
John McCall6b5a61b2011-02-07 10:33:21 +0000518 // Don't re-append everything we just appended.
519 layout.erase(first, li);
520 }
521 }
522
John McCall6ea48412012-04-26 21:14:42 +0000523 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000524
John McCall6b5a61b2011-02-07 10:33:21 +0000525 // At this point, we just have to add padding if the end align still
526 // isn't aligned right.
527 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000528 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
529 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000530
John McCall5936e332011-02-15 09:22:45 +0000531 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
532 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000533 blockSize = newBlockSize;
John McCall6c803f72012-05-01 20:28:00 +0000534 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall6b5a61b2011-02-07 10:33:21 +0000535 }
536
John McCall6c803f72012-05-01 20:28:00 +0000537 assert(endAlign >= maxFieldAlign);
John McCall6ea48412012-04-26 21:14:42 +0000538 assert(endAlign == getLowBit(blockSize));
John McCall6b5a61b2011-02-07 10:33:21 +0000539 // Slam everything else on now. This works because they have
540 // strictly decreasing alignment and we expect that size is always a
541 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000542 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000543 li = layout.begin(), le = layout.end(); li != le; ++li) {
544 assert(endAlign >= li->Alignment);
545 li->setIndex(info, elementTypes.size());
546 elementTypes.push_back(li->Type);
547 blockSize += li->Size;
548 endAlign = getLowBit(blockSize);
549 }
550
551 info.StructureType =
552 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
553}
554
John McCall1a343eb2011-11-10 08:15:53 +0000555/// Enter the scope of a block. This should be run at the entrance to
556/// a full-expression so that the block's cleanups are pushed at the
557/// right place in the stack.
558static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000559 assert(CGF.HaveInsertPoint());
560
John McCall1a343eb2011-11-10 08:15:53 +0000561 // Allocate the block info and place it at the head of the list.
562 CGBlockInfo &blockInfo =
563 *new CGBlockInfo(block, CGF.CurFn->getName());
564 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
565 CGF.FirstBlockInfo = &blockInfo;
566
567 // Compute information about the layout, etc., of this block,
568 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000569 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000570
571 // Nothing else to do if it can be global.
572 if (blockInfo.CanBeGlobal) return;
573
574 // Make the allocation for the block.
575 blockInfo.Address =
576 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
577 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
578
579 // If there are cleanups to emit, enter them (but inactive).
580 if (!blockInfo.NeedsCopyDispose) return;
581
582 // Walk through the captures (in order) and find the ones not
583 // captured by constant.
584 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
585 ce = block->capture_end(); ci != ce; ++ci) {
586 // Ignore __block captures; there's nothing special in the
587 // on-stack block that we need to do for them.
588 if (ci->isByRef()) continue;
589
590 // Ignore variables that are constant-captured.
591 const VarDecl *variable = ci->getVariable();
592 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
593 if (capture.isConstant()) continue;
594
595 // Ignore objects that aren't destructed.
596 QualType::DestructionKind dtorKind =
597 variable->getType().isDestructedType();
598 if (dtorKind == QualType::DK_none) continue;
599
600 CodeGenFunction::Destroyer *destroyer;
601
602 // Block captures count as local values and have imprecise semantics.
603 // They also can't be arrays, so need to worry about that.
604 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000605 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000606 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000607 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000608 }
609
610 // GEP down to the address.
611 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
612 capture.getIndex());
613
John McCall6f103ba2011-11-10 10:43:54 +0000614 // We can use that GEP as the dominating IP.
615 if (!blockInfo.DominatingIP)
616 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
617
John McCall1a343eb2011-11-10 08:15:53 +0000618 CleanupKind cleanupKind = InactiveNormalCleanup;
619 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
620 if (useArrayEHCleanup)
621 cleanupKind = InactiveNormalAndEHCleanup;
622
623 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000624 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000625
626 // Remember where that cleanup was.
627 capture.setCleanup(CGF.EHStack.stable_begin());
628 }
629}
630
631/// Enter a full-expression with a non-trivial number of objects to
632/// clean up. This is in this file because, at the moment, the only
633/// kind of cleanup object is a BlockDecl*.
634void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
635 assert(E->getNumObjects() != 0);
636 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
637 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
638 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
639 enterBlockScope(*this, *i);
640 }
641}
642
643/// Find the layout for the given block in a linked list and remove it.
644static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
645 const BlockDecl *block) {
646 while (true) {
647 assert(head && *head);
648 CGBlockInfo *cur = *head;
649
650 // If this is the block we're looking for, splice it out of the list.
651 if (cur->getBlockDecl() == block) {
652 *head = cur->NextBlockInfo;
653 return cur;
654 }
655
656 head = &cur->NextBlockInfo;
657 }
658}
659
660/// Destroy a chain of block layouts.
661void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
662 assert(head && "destroying an empty chain");
663 do {
664 CGBlockInfo *cur = head;
665 head = cur->NextBlockInfo;
666 delete cur;
667 } while (head != 0);
668}
669
John McCall6b5a61b2011-02-07 10:33:21 +0000670/// Emit a block literal expression in the current function.
671llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000672 // If the block has no captures, we won't have a pre-computed
673 // layout for it.
674 if (!blockExpr->getBlockDecl()->hasCaptures()) {
675 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000676 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000677 blockInfo.BlockExpression = blockExpr;
678 return EmitBlockLiteral(blockInfo);
679 }
John McCall6b5a61b2011-02-07 10:33:21 +0000680
John McCall1a343eb2011-11-10 08:15:53 +0000681 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000682 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000683 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
684 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000685
John McCall1a343eb2011-11-10 08:15:53 +0000686 blockInfo->BlockExpression = blockExpr;
687 return EmitBlockLiteral(*blockInfo);
688}
689
690llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
691 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000692 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000693 llvm::Constant *blockFn
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000694 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCallf5ebf9b2013-05-03 07:33:41 +0000695 LocalDeclMap,
696 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000697 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000698
699 // If there is nothing to capture, we can emit this as a global block.
700 if (blockInfo.CanBeGlobal)
701 return buildGlobalBlock(CGM, blockInfo, blockFn);
702
703 // Otherwise, we have to emit this as a local block.
704
705 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000706 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000707
708 // Build the block descriptor.
709 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
710
John McCall1a343eb2011-11-10 08:15:53 +0000711 llvm::AllocaInst *blockAddr = blockInfo.Address;
712 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000713
714 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000715 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000716 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall6b5a61b2011-02-07 10:33:21 +0000717 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
718 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000719 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000720
721 // Initialize the block literal.
722 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000723 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000724 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000725 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000726 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
727 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
728 "block.invoke"));
729 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
730 "block.descriptor"));
731
732 // Finally, capture all the values into the block.
733 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
734
735 // First, 'this'.
736 if (blockDecl->capturesCXXThis()) {
737 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
738 blockInfo.CXXThisIndex,
739 "block.captured-this.addr");
740 Builder.CreateStore(LoadCXXThis(), addr);
741 }
742
743 // Next, captured variables.
744 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
745 ce = blockDecl->capture_end(); ci != ce; ++ci) {
746 const VarDecl *variable = ci->getVariable();
747 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
748
749 // Ignore constant captures.
750 if (capture.isConstant()) continue;
751
752 QualType type = variable->getType();
John McCall4b9bcd62013-04-08 23:27:49 +0000753 CharUnits align = getContext().getDeclAlign(variable);
John McCall6b5a61b2011-02-07 10:33:21 +0000754
755 // This will be a [[type]]*, except that a byref entry will just be
756 // an i8**.
757 llvm::Value *blockField =
758 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
759 "block.captured");
760
761 // Compute the address of the thing we're going to move into the
762 // block literal.
763 llvm::Value *src;
Douglas Gregor29a93f82012-05-16 16:50:20 +0000764 if (BlockInfo && ci->isNested()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000765 // We need to use the capture from the enclosing block.
766 const CGBlockInfo::Capture &enclosingCapture =
767 BlockInfo->getCapture(variable);
768
769 // This is a [[type]]*, except that a byref entry wil just be an i8**.
770 src = Builder.CreateStructGEP(LoadBlockStruct(),
771 enclosingCapture.getIndex(),
772 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000773 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000774 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000775 // special; we'll simply emit it directly.
776 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000777 } else {
John McCall0353a7b2013-03-04 06:32:36 +0000778 // Just look it up in the locals map, which will give us back a
779 // [[type]]*. If that doesn't work, do the more elaborate DRE
780 // emission.
781 src = LocalDeclMap.lookup(variable);
782 if (!src) {
783 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
784 /*refersToEnclosing*/ ci->isNested(), type,
785 VK_LValue, SourceLocation());
786 src = EmitDeclRefLValue(&declRef).getAddress();
787 }
John McCall6b5a61b2011-02-07 10:33:21 +0000788 }
789
790 // For byrefs, we just write the pointer to the byref struct into
791 // the block field. There's no need to chase the forwarding
792 // pointer at this point, since we're building something that will
793 // live a shorter life than the stack byref anyway.
794 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000795 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000796 if (ci->isNested())
John McCall4b9bcd62013-04-08 23:27:49 +0000797 src = Builder.CreateAlignedLoad(src, align.getQuantity(),
798 "byref.capture");
John McCall6b5a61b2011-02-07 10:33:21 +0000799 else
John McCall5936e332011-02-15 09:22:45 +0000800 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000801
John McCall5936e332011-02-15 09:22:45 +0000802 // Write that void* into the capture field.
John McCall4b9bcd62013-04-08 23:27:49 +0000803 Builder.CreateAlignedStore(src, blockField, align.getQuantity());
John McCall6b5a61b2011-02-07 10:33:21 +0000804
805 // If we have a copy constructor, evaluate that into the block field.
806 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000807 if (blockDecl->isConversionFromLambda()) {
808 // If we have a lambda conversion, emit the expression
809 // directly into the block instead.
Eli Friedman23f02672012-03-01 04:01:32 +0000810 AggValueSlot Slot =
John McCall4b9bcd62013-04-08 23:27:49 +0000811 AggValueSlot::forAddr(blockField, align, Qualifiers(),
Eli Friedman23f02672012-03-01 04:01:32 +0000812 AggValueSlot::IsDestructed,
813 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000814 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000815 EmitAggExpr(copyExpr, Slot);
816 } else {
817 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
818 }
John McCall6b5a61b2011-02-07 10:33:21 +0000819
820 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000821 } else if (type->isReferenceType()) {
John McCall4b9bcd62013-04-08 23:27:49 +0000822 llvm::Value *ref =
823 Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
824 Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
825
826 // If this is an ARC __strong block-pointer variable, don't do a
827 // block copy.
828 //
829 // TODO: this can be generalized into the normal initialization logic:
830 // we should never need to do a block-copy when initializing a local
831 // variable, because the local variable's lifetime should be strictly
832 // contained within the stack block's.
833 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
834 type->isBlockPointerType()) {
835 // Load the block and do a simple retain.
836 LValue srcLV = MakeAddrLValue(src, type, align);
837 llvm::Value *value = EmitLoadOfScalar(srcLV);
838 value = EmitARCRetainNonBlock(value);
839
840 // Do a primitive store to the block field.
841 LValue destLV = MakeAddrLValue(blockField, type, align);
842 EmitStoreOfScalar(value, destLV, /*init*/ true);
John McCall6b5a61b2011-02-07 10:33:21 +0000843
844 // Otherwise, fake up a POD copy into the block field.
845 } else {
John McCallf85e1932011-06-15 23:02:42 +0000846 // Fake up a new variable so that EmitScalarInit doesn't think
847 // we're referring to the variable in its own initializer.
848 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000849 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000850
John McCallbb699b02011-02-07 18:37:40 +0000851 // We use one of these or the other depending on whether the
852 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000853 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
854 /*refersToEnclosing*/ ci->isNested(), type,
855 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000856
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000857 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000858 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000859 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall4b9bcd62013-04-08 23:27:49 +0000860 MakeAddrLValue(blockField, type, align),
John McCalldf045202011-03-08 09:38:48 +0000861 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000862 }
863
John McCall1a343eb2011-11-10 08:15:53 +0000864 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000865 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000866 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
867 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000868 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000869 }
John McCall6b5a61b2011-02-07 10:33:21 +0000870 }
871
872 // Cast to the converted block-pointer type, which happens (somewhat
873 // unfortunately) to be a pointer to function type.
874 llvm::Value *result =
875 Builder.CreateBitCast(blockAddr,
876 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000877
John McCall6b5a61b2011-02-07 10:33:21 +0000878 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000879}
880
881
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000882llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000883 if (BlockDescriptorType)
884 return BlockDescriptorType;
885
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000886 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000887 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000888
Mike Stumpab695142009-02-13 15:16:56 +0000889 // struct __block_descriptor {
890 // unsigned long reserved;
891 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000892 //
893 // // later, the following will be added
894 //
895 // struct {
896 // void (*copyHelper)();
897 // void (*copyHelper)();
898 // } helpers; // !!! optional
899 //
900 // const char *signature; // the block signature
901 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000902 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000903 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000904 llvm::StructType::create("struct.__block_descriptor",
905 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000906
John McCall6b5a61b2011-02-07 10:33:21 +0000907 // Now form a pointer to that.
908 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000909 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000910}
911
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000912llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000913 if (GenericBlockLiteralType)
914 return GenericBlockLiteralType;
915
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000916 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000917
Mike Stump9b8a7972009-02-13 15:25:34 +0000918 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000919 // void *__isa;
920 // int __flags;
921 // int __reserved;
922 // void (*__invoke)(void *);
923 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000924 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000925 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000926 llvm::StructType::create("struct.__block_literal_generic",
927 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
928 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000929
Mike Stump9b8a7972009-02-13 15:25:34 +0000930 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000931}
932
Mike Stumpbd65cac2009-02-19 01:01:04 +0000933
Anders Carlssona1736c02009-12-24 21:13:40 +0000934RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
935 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000936 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000937 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000938
Anders Carlssonacfde802009-02-12 00:39:25 +0000939 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
940
941 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000942 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000943 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000944
945 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000946 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000947 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
948
949 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000950 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000951
Benjamin Kramer578faa82011-09-27 21:06:10 +0000952 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000953
Anders Carlssonacfde802009-02-12 00:39:25 +0000954 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000955 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000956 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000957
Anders Carlsson782f3972009-04-08 23:13:16 +0000958 QualType FnType = BPT->getPointeeType();
959
Anders Carlssonacfde802009-02-12 00:39:25 +0000960 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000961 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000962 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000963
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000964 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000965 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000966
John McCall64cd2322011-03-09 08:39:33 +0000967 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000968 const CGFunctionInfo &FnInfo =
John McCalle56bb362012-12-07 07:03:17 +0000969 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000971 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000972 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Chris Lattner2acc6e32011-07-18 04:24:23 +0000974 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000975 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Anders Carlssonacfde802009-02-12 00:39:25 +0000977 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000978 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000979}
Anders Carlssond5cab542009-02-12 17:55:02 +0000980
John McCall6b5a61b2011-02-07 10:33:21 +0000981llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
982 bool isByRef) {
983 assert(BlockInfo && "evaluating block ref without block information?");
984 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000985
John McCall6b5a61b2011-02-07 10:33:21 +0000986 // Handle constant captures.
987 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000988
John McCall6b5a61b2011-02-07 10:33:21 +0000989 llvm::Value *addr =
990 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
991 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000992
John McCall6b5a61b2011-02-07 10:33:21 +0000993 if (isByRef) {
994 // addr should be a void** right now. Load, then cast the result
995 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000996
John McCall6b5a61b2011-02-07 10:33:21 +0000997 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000998 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000999 = llvm::PointerType::get(BuildByRefType(variable), 0);
1000 addr = Builder.CreateBitCast(addr, byrefPointerType,
1001 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +00001002
John McCall6b5a61b2011-02-07 10:33:21 +00001003 // Follow the forwarding pointer.
1004 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
1005 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +00001006
John McCall6b5a61b2011-02-07 10:33:21 +00001007 // Cast back to byref* and GEP over to the actual object.
1008 addr = Builder.CreateBitCast(addr, byrefPointerType);
1009 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
1010 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +00001011 }
1012
Fariborz Jahanianc637d732011-11-02 22:53:43 +00001013 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +00001014 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +00001015
John McCall6b5a61b2011-02-07 10:33:21 +00001016 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +00001017}
1018
Mike Stump67a64482009-02-14 22:16:35 +00001019llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001020CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +00001021 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +00001022 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1023 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +00001024
John McCall6b5a61b2011-02-07 10:33:21 +00001025 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +00001026 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001027
John McCall6b5a61b2011-02-07 10:33:21 +00001028 // Using that metadata, generate the actual block function.
1029 llvm::Constant *blockFn;
1030 {
1031 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +00001032 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1033 blockInfo,
John McCallf5ebf9b2013-05-03 07:33:41 +00001034 LocalDeclMap,
Eli Friedman64bee652012-02-25 02:48:22 +00001035 false);
John McCall6b5a61b2011-02-07 10:33:21 +00001036 }
John McCall5936e332011-02-15 09:22:45 +00001037 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +00001038
John McCalld16c2cf2011-02-08 08:22:06 +00001039 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +00001040}
1041
John McCall6b5a61b2011-02-07 10:33:21 +00001042static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1043 const CGBlockInfo &blockInfo,
1044 llvm::Constant *blockFn) {
1045 assert(blockInfo.CanBeGlobal);
1046
1047 // Generate the constants for the block literal initializer.
1048 llvm::Constant *fields[BlockHeaderSize];
1049
1050 // isa
1051 fields[0] = CGM.getNSConcreteGlobalBlock();
1052
1053 // __flags
John McCall64cd2322011-03-09 08:39:33 +00001054 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1055 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1056
John McCall5936e332011-02-15 09:22:45 +00001057 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +00001058
1059 // Reserved
John McCall5936e332011-02-15 09:22:45 +00001060 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001061
1062 // Function
1063 fields[3] = blockFn;
1064
1065 // Descriptor
1066 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1067
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001068 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +00001069
1070 llvm::GlobalVariable *literal =
1071 new llvm::GlobalVariable(CGM.getModule(),
1072 init->getType(),
1073 /*constant*/ true,
1074 llvm::GlobalVariable::InternalLinkage,
1075 init,
1076 "__block_literal_global");
1077 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1078
1079 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001080 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +00001081 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1082 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +00001083}
1084
Mike Stump00470a12009-03-05 08:32:30 +00001085llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +00001086CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1087 const CGBlockInfo &blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +00001088 const DeclMapTy &ldm,
1089 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001090 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001091
Devang Patel6d1155b2011-03-07 21:53:18 +00001092 // Check if we should generate debug info for this block function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001093 maybeInitializeDebugInfo();
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001094 CurGD = GD;
1095
John McCall6b5a61b2011-02-07 10:33:21 +00001096 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Mike Stump7f28a9c2009-03-13 23:34:28 +00001098 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001099 // to be local to this function as well, in case they're directly
1100 // referenced in a block.
1101 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1102 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1103 if (var && !var->hasLocalStorage())
1104 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001105 }
1106
John McCall6b5a61b2011-02-07 10:33:21 +00001107 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001108
John McCall6b5a61b2011-02-07 10:33:21 +00001109 // Build the argument list.
1110 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001111
John McCall6b5a61b2011-02-07 10:33:21 +00001112 // The first argument is the block pointer. Just take it as a void*
1113 // and cast it later.
1114 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001115 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001116
John McCall8178df32011-02-22 22:38:33 +00001117 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1118 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001119 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001120
John McCall6b5a61b2011-02-07 10:33:21 +00001121 // Now add the rest of the parameters.
1122 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1123 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001124 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001125
John McCall6b5a61b2011-02-07 10:33:21 +00001126 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001127 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001128 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001129 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1130 fnType->getExtInfo(),
1131 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001132 if (CGM.ReturnTypeUsesSRet(fnInfo))
1133 blockInfo.UsesStret = true;
1134
John McCallde5d3c72012-02-17 03:33:10 +00001135 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001136
John McCall6b5a61b2011-02-07 10:33:21 +00001137 MangleBuffer name;
1138 CGM.getBlockMangledName(GD, name, blockDecl);
1139 llvm::Function *fn =
1140 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1141 name.getString(), &CGM.getModule());
1142 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001143
John McCall6b5a61b2011-02-07 10:33:21 +00001144 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001145 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001146 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpa5448542009-02-13 15:32:32 +00001147
John McCall8178df32011-02-22 22:38:33 +00001148 // Okay. Undo some of what StartFunction did.
1149
1150 // Pull the 'self' reference out of the local decl map.
1151 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1152 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001153 BlockPointer = Builder.CreateBitCast(blockAddr,
1154 blockInfo.StructureType->getPointerTo(),
1155 "block");
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001156 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1157 // won't delete the dbg.declare intrinsics for captured variables.
1158 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1159 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1160 // Allocate a stack slot for it, so we can point the debugger to it
1161 llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
1162 "block.addr");
1163 unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
1164 Alloca->setAlignment(Align);
Adrian Prantl79591942013-04-02 01:00:48 +00001165 // Set the DebugLocation to empty, so the store is recognized as a
1166 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantled6bbe42013-07-18 00:28:02 +00001167 NoLocation NL(*this, Builder);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001168 Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
1169 BlockPointerDbgLoc = Alloca;
1170 }
Anders Carlssond5cab542009-02-12 17:55:02 +00001171
John McCallea1471e2010-05-20 01:18:31 +00001172 // If we have a C++ 'this' reference, go ahead and force it into
1173 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001174 if (blockDecl->capturesCXXThis()) {
1175 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1176 blockInfo.CXXThisIndex,
1177 "block.captured-this");
1178 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001179 }
1180
John McCall6b5a61b2011-02-07 10:33:21 +00001181 // Also force all the constant captures.
1182 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1183 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1184 const VarDecl *variable = ci->getVariable();
1185 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1186 if (!capture.isConstant()) continue;
1187
1188 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1189
1190 llvm::AllocaInst *alloca =
1191 CreateMemTemp(variable->getType(), "block.captured-const");
1192 alloca->setAlignment(align);
1193
Adrian Prantl836e7c92013-03-14 17:53:33 +00001194 Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
John McCall6b5a61b2011-02-07 10:33:21 +00001195
1196 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001197 }
1198
John McCallf4b88a42012-03-10 09:33:50 +00001199 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001200 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1201 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1202 --entry_ptr;
1203
Eli Friedman64bee652012-02-25 02:48:22 +00001204 if (IsLambdaConversionToBlock)
1205 EmitLambdaBlockInvokeBody();
1206 else
1207 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001208
Mike Stumpde8c5c72009-10-01 00:27:30 +00001209 // Remember where we were...
1210 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001211
Mike Stumpde8c5c72009-10-01 00:27:30 +00001212 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001213 ++entry_ptr;
1214 Builder.SetInsertPoint(entry, entry_ptr);
1215
John McCallf4b88a42012-03-10 09:33:50 +00001216 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001217 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001218 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001219 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1220 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1221 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001222 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001223
Douglas Gregor4cdad312012-10-23 20:05:01 +00001224 if (CGM.getCodeGenOpts().getDebugInfo()
1225 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001226 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1227 if (capture.isConstant()) {
1228 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1229 Builder);
1230 continue;
1231 }
John McCall6b5a61b2011-02-07 10:33:21 +00001232
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001233 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001234 Builder, blockInfo);
1235 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001236 }
Manman Ren3c7a0e12013-01-04 18:51:35 +00001237 // Recover location if it was changed in the above loop.
1238 DI->EmitLocation(Builder,
Adrian Prantld83cdd62013-04-08 20:52:12 +00001239 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stumpb1a6e682009-09-30 02:43:10 +00001240 }
John McCall6b5a61b2011-02-07 10:33:21 +00001241
Mike Stumpde8c5c72009-10-01 00:27:30 +00001242 // And resume where we left off.
1243 if (resume == 0)
1244 Builder.ClearInsertionPoint();
1245 else
1246 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001247
John McCall6b5a61b2011-02-07 10:33:21 +00001248 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001249
John McCall6b5a61b2011-02-07 10:33:21 +00001250 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001251}
Mike Stumpa99038c2009-02-28 09:07:16 +00001252
John McCall6b5a61b2011-02-07 10:33:21 +00001253/*
1254 notes.push_back(HelperInfo());
1255 HelperInfo &note = notes.back();
1256 note.index = capture.getIndex();
1257 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1258 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001259
John McCall6b5a61b2011-02-07 10:33:21 +00001260 if (ci->isByRef()) {
1261 note.flag = BLOCK_FIELD_IS_BYREF;
1262 if (type.isObjCGCWeak())
1263 note.flag |= BLOCK_FIELD_IS_WEAK;
1264 } else if (type->isBlockPointerType()) {
1265 note.flag = BLOCK_FIELD_IS_BLOCK;
1266 } else {
1267 note.flag = BLOCK_FIELD_IS_OBJECT;
1268 }
1269 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001270
Mike Stump00470a12009-03-05 08:32:30 +00001271
John McCallb62faef2013-01-22 03:56:22 +00001272/// Generate the copy-helper function for a block closure object:
1273/// static void block_copy_helper(block_t *dst, block_t *src);
1274/// The runtime will have previously initialized 'dst' by doing a
1275/// bit-copy of 'src'.
1276///
1277/// Note that this copies an entire block closure object to the heap;
1278/// it should not be confused with a 'byref copy helper', which moves
1279/// the contents of an individual __block variable to the heap.
John McCall6b5a61b2011-02-07 10:33:21 +00001280llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001281CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001282 ASTContext &C = getContext();
1283
1284 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001285 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1286 args.push_back(&dstDecl);
1287 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1288 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Mike Stumpa4f668f2009-03-06 01:33:24 +00001290 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001291 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1292 FunctionType::ExtInfo(),
1293 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001294
John McCall6b5a61b2011-02-07 10:33:21 +00001295 // FIXME: it would be nice if these were mergeable with things with
1296 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001297 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001298
1299 llvm::Function *Fn =
1300 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001301 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001302
1303 IdentifierInfo *II
1304 = &CGM.getContext().Idents.get("__copy_helper_block_");
1305
Devang Patel58dc5ca2011-05-02 20:37:08 +00001306 // Check if we should generate debug info for this block helper function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001307 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001308
John McCall6b5a61b2011-02-07 10:33:21 +00001309 FunctionDecl *FD = FunctionDecl::Create(C,
1310 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001311 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001312 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001313 SC_Static,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001314 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001315 false);
John McCalld26bc762011-03-09 04:27:21 +00001316 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001317
Chris Lattner2acc6e32011-07-18 04:24:23 +00001318 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001319
John McCalld26bc762011-03-09 04:27:21 +00001320 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001321 src = Builder.CreateLoad(src);
1322 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001323
John McCalld26bc762011-03-09 04:27:21 +00001324 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001325 dst = Builder.CreateLoad(dst);
1326 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001327
John McCall6b5a61b2011-02-07 10:33:21 +00001328 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001329
John McCall6b5a61b2011-02-07 10:33:21 +00001330 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1331 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1332 const VarDecl *variable = ci->getVariable();
1333 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001334
John McCall6b5a61b2011-02-07 10:33:21 +00001335 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1336 if (capture.isConstant()) continue;
1337
1338 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001339 BlockFieldFlags flags;
1340
John McCall015f33b2012-10-17 02:28:37 +00001341 bool useARCWeakCopy = false;
1342 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001343
1344 if (copyExpr) {
1345 assert(!ci->isByRef());
1346 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001347
John McCall6b5a61b2011-02-07 10:33:21 +00001348 } else if (ci->isByRef()) {
1349 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001350 if (type.isObjCGCWeak())
1351 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001352
John McCallf85e1932011-06-15 23:02:42 +00001353 } else if (type->isObjCRetainableType()) {
1354 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001355 bool isBlockPointer = type->isBlockPointerType();
1356 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001357 flags = BLOCK_FIELD_IS_BLOCK;
1358
1359 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001360 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001361 Qualifiers qs = type.getQualifiers();
1362
John McCall015f33b2012-10-17 02:28:37 +00001363 // We need to register __weak direct captures with the runtime.
1364 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1365 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001366
John McCall015f33b2012-10-17 02:28:37 +00001367 // We need to retain the copied value for __strong direct captures.
1368 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1369 // If it's a block pointer, we have to copy the block and
1370 // assign that to the destination pointer, so we might as
1371 // well use _Block_object_assign. Otherwise we can avoid that.
1372 if (!isBlockPointer)
1373 useARCStrongCopy = true;
1374
1375 // Otherwise the memcpy is fine.
1376 } else {
1377 continue;
1378 }
1379
1380 // Non-ARC captures of retainable pointers are strong and
1381 // therefore require a call to _Block_object_assign.
1382 } else {
1383 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001384 }
1385 } else {
1386 continue;
1387 }
John McCall6b5a61b2011-02-07 10:33:21 +00001388
1389 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001390 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1391 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001392
1393 // If there's an explicit copy expression, we do that.
1394 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001395 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001396 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001397 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001398 } else {
1399 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001400 if (useARCStrongCopy) {
1401 // At -O0, store null into the destination field (so that the
1402 // storeStrong doesn't over-release) and then call storeStrong.
1403 // This is a workaround to not having an initStrong call.
1404 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1405 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1406 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1407 Builder.CreateStore(null, dstField);
1408 EmitARCStoreStrongCall(dstField, srcValue, true);
1409
1410 // With optimization enabled, take advantage of the fact that
1411 // the blocks runtime guarantees a memcpy of the block data, and
1412 // just emit a retain of the src field.
1413 } else {
1414 EmitARCRetainNonBlock(srcValue);
1415
1416 // We don't need this anymore, so kill it. It's not quite
1417 // worth the annoyance to avoid creating it in the first place.
1418 cast<llvm::Instruction>(dstField)->eraseFromParent();
1419 }
1420 } else {
1421 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1422 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCallbd7370a2013-02-28 19:01:20 +00001423 llvm::Value *args[] = {
1424 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1425 };
1426
1427 bool copyCanThrow = false;
1428 if (ci->isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1429 const Expr *copyExpr =
1430 CGM.getContext().getBlockVarCopyInits(variable);
1431 if (copyExpr) {
1432 copyCanThrow = true; // FIXME: reuse the noexcept logic
1433 }
1434 }
1435
1436 if (copyCanThrow) {
1437 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1438 } else {
1439 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1440 }
John McCall015f33b2012-10-17 02:28:37 +00001441 }
Mike Stump08920992009-03-07 02:35:30 +00001442 }
1443 }
1444
John McCalld16c2cf2011-02-08 08:22:06 +00001445 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001446
John McCall5936e332011-02-15 09:22:45 +00001447 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001448}
1449
John McCallb62faef2013-01-22 03:56:22 +00001450/// Generate the destroy-helper function for a block closure object:
1451/// static void block_destroy_helper(block_t *theBlock);
1452///
1453/// Note that this destroys a heap-allocated block closure object;
1454/// it should not be confused with a 'byref destroy helper', which
1455/// destroys the heap-allocated contents of an individual __block
1456/// variable.
John McCall6b5a61b2011-02-07 10:33:21 +00001457llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001458CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001459 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001460
John McCall6b5a61b2011-02-07 10:33:21 +00001461 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001462 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1463 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Mike Stumpa4f668f2009-03-06 01:33:24 +00001465 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001466 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1467 FunctionType::ExtInfo(),
1468 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001469
Mike Stump3899a7f2009-06-05 23:26:36 +00001470 // FIXME: We'd like to put these into a mergable by content, with
1471 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001472 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001473
1474 llvm::Function *Fn =
1475 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001476 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001477
Devang Patel58dc5ca2011-05-02 20:37:08 +00001478 // Check if we should generate debug info for this block destroy function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001479 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001480
Mike Stumpa4f668f2009-03-06 01:33:24 +00001481 IdentifierInfo *II
1482 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1483
John McCall6b5a61b2011-02-07 10:33:21 +00001484 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001485 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001486 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001487 SC_Static,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001488 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001489 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001490
Chris Lattner2acc6e32011-07-18 04:24:23 +00001491 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001492
John McCalld26bc762011-03-09 04:27:21 +00001493 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001494 src = Builder.CreateLoad(src);
1495 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001496
John McCall6b5a61b2011-02-07 10:33:21 +00001497 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1498
John McCalld16c2cf2011-02-08 08:22:06 +00001499 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001500
1501 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1502 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1503 const VarDecl *variable = ci->getVariable();
1504 QualType type = variable->getType();
1505
1506 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1507 if (capture.isConstant()) continue;
1508
John McCalld16c2cf2011-02-08 08:22:06 +00001509 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001510 const CXXDestructorDecl *dtor = 0;
1511
John McCall015f33b2012-10-17 02:28:37 +00001512 bool useARCWeakDestroy = false;
1513 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001514
John McCall6b5a61b2011-02-07 10:33:21 +00001515 if (ci->isByRef()) {
1516 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001517 if (type.isObjCGCWeak())
1518 flags |= BLOCK_FIELD_IS_WEAK;
1519 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1520 if (record->hasTrivialDestructor())
1521 continue;
1522 dtor = record->getDestructor();
1523 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001524 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001525 if (type->isBlockPointerType())
1526 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001527
John McCallf85e1932011-06-15 23:02:42 +00001528 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001529 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001530 Qualifiers qs = type.getQualifiers();
1531
1532 // Don't generate special dispose logic for a captured object
1533 // unless it's __strong or __weak.
1534 if (!qs.hasStrongOrWeakObjCLifetime())
1535 continue;
1536
1537 // Support __weak direct captures.
1538 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001539 useARCWeakDestroy = true;
1540
1541 // Tools really want us to use objc_storeStrong here.
1542 else
1543 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001544 }
1545 } else {
1546 continue;
1547 }
John McCall6b5a61b2011-02-07 10:33:21 +00001548
1549 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001550 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001551
1552 // If there's an explicit copy expression, we do that.
1553 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001554 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001555
John McCallf85e1932011-06-15 23:02:42 +00001556 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001557 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001558 EmitARCDestroyWeak(srcField);
1559
John McCall015f33b2012-10-17 02:28:37 +00001560 // Destroy strong objects with a call if requested.
1561 } else if (useARCStrongDestroy) {
John McCall5b07e802013-03-13 03:10:54 +00001562 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCall015f33b2012-10-17 02:28:37 +00001563
John McCall6b5a61b2011-02-07 10:33:21 +00001564 // Otherwise we call _Block_object_dispose. It wouldn't be too
1565 // hard to just emit this as a cleanup if we wanted to make sure
1566 // that things were done in reverse.
1567 } else {
1568 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001569 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001570 BuildBlockRelease(value, flags);
1571 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001572 }
1573
John McCall6b5a61b2011-02-07 10:33:21 +00001574 cleanups.ForceCleanup();
1575
John McCalld16c2cf2011-02-08 08:22:06 +00001576 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001577
John McCall5936e332011-02-15 09:22:45 +00001578 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001579}
1580
John McCallf0c11f72011-03-31 08:03:29 +00001581namespace {
1582
1583/// Emits the copy/dispose helper functions for a __block object of id type.
1584class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1585 BlockFieldFlags Flags;
1586
1587public:
1588 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1589 : ByrefHelpers(alignment), Flags(flags) {}
1590
John McCall36170192011-03-31 09:19:20 +00001591 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1592 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001593 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1594
1595 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1596 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1597
1598 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1599
1600 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1601 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCallbd7370a2013-02-28 19:01:20 +00001602
1603 llvm::Value *args[] = { destField, srcValue, flagsVal };
1604 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf0c11f72011-03-31 08:03:29 +00001605 }
1606
1607 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1608 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1609 llvm::Value *value = CGF.Builder.CreateLoad(field);
1610
1611 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1612 }
1613
1614 void profileImpl(llvm::FoldingSetNodeID &id) const {
1615 id.AddInteger(Flags.getBitMask());
1616 }
1617};
1618
John McCallf85e1932011-06-15 23:02:42 +00001619/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1620class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1621public:
1622 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1623
1624 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1625 llvm::Value *srcField) {
1626 CGF.EmitARCMoveWeak(destField, srcField);
1627 }
1628
1629 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1630 CGF.EmitARCDestroyWeak(field);
1631 }
1632
1633 void profileImpl(llvm::FoldingSetNodeID &id) const {
1634 // 0 is distinguishable from all pointers and byref flags
1635 id.AddInteger(0);
1636 }
1637};
1638
1639/// Emits the copy/dispose helpers for an ARC __block __strong variable
1640/// that's not of block-pointer type.
1641class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1642public:
1643 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1644
1645 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1646 llvm::Value *srcField) {
1647 // Do a "move" by copying the value and then zeroing out the old
1648 // variable.
1649
John McCalla59e4b72011-11-09 03:17:26 +00001650 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1651 value->setAlignment(Alignment.getQuantity());
1652
John McCallf85e1932011-06-15 23:02:42 +00001653 llvm::Value *null =
1654 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001655
Fariborz Jahanian7a77f192013-01-04 23:32:24 +00001656 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
Fariborz Jahanianba3c9ca2013-01-05 00:32:13 +00001657 llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1658 store->setAlignment(Alignment.getQuantity());
Fariborz Jahanian7a77f192013-01-04 23:32:24 +00001659 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1660 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1661 return;
1662 }
John McCalla59e4b72011-11-09 03:17:26 +00001663 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1664 store->setAlignment(Alignment.getQuantity());
1665
1666 store = CGF.Builder.CreateStore(null, srcField);
1667 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001668 }
1669
1670 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall5b07e802013-03-13 03:10:54 +00001671 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001672 }
1673
1674 void profileImpl(llvm::FoldingSetNodeID &id) const {
1675 // 1 is distinguishable from all pointers and byref flags
1676 id.AddInteger(1);
1677 }
1678};
1679
John McCalla59e4b72011-11-09 03:17:26 +00001680/// Emits the copy/dispose helpers for an ARC __block __strong
1681/// variable that's of block-pointer type.
1682class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1683public:
1684 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1685
1686 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1687 llvm::Value *srcField) {
1688 // Do the copy with objc_retainBlock; that's all that
1689 // _Block_object_assign would do anyway, and we'd have to pass the
1690 // right arguments to make sure it doesn't get no-op'ed.
1691 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1692 oldValue->setAlignment(Alignment.getQuantity());
1693
1694 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1695
1696 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1697 store->setAlignment(Alignment.getQuantity());
1698 }
1699
1700 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall5b07e802013-03-13 03:10:54 +00001701 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCalla59e4b72011-11-09 03:17:26 +00001702 }
1703
1704 void profileImpl(llvm::FoldingSetNodeID &id) const {
1705 // 2 is distinguishable from all pointers and byref flags
1706 id.AddInteger(2);
1707 }
1708};
1709
John McCallf0c11f72011-03-31 08:03:29 +00001710/// Emits the copy/dispose helpers for a __block variable with a
1711/// nontrivial copy constructor or destructor.
1712class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1713 QualType VarType;
1714 const Expr *CopyExpr;
1715
1716public:
1717 CXXByrefHelpers(CharUnits alignment, QualType type,
1718 const Expr *copyExpr)
1719 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1720
1721 bool needsCopy() const { return CopyExpr != 0; }
1722 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1723 llvm::Value *srcField) {
1724 if (!CopyExpr) return;
1725 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1726 }
1727
1728 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1729 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1730 CGF.PushDestructorCleanup(VarType, field);
1731 CGF.PopCleanupBlocks(cleanupDepth);
1732 }
1733
1734 void profileImpl(llvm::FoldingSetNodeID &id) const {
1735 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1736 }
1737};
1738} // end anonymous namespace
1739
1740static llvm::Constant *
1741generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001742 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001743 unsigned valueFieldIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001744 CodeGenModule::ByrefHelpers &byrefInfo) {
1745 ASTContext &Context = CGF.getContext();
1746
1747 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001748
John McCalld26bc762011-03-09 04:27:21 +00001749 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001750 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001751 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001752
John McCallf0c11f72011-03-31 08:03:29 +00001753 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001754 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Mike Stump45031c02009-03-06 02:29:21 +00001756 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001757 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1758 FunctionType::ExtInfo(),
1759 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001760
John McCallf0c11f72011-03-31 08:03:29 +00001761 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001762 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001763
Mike Stump3899a7f2009-06-05 23:26:36 +00001764 // FIXME: We'd like to put these into a mergable by content, with
1765 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001766 llvm::Function *Fn =
1767 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001768 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001769
1770 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001771 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001772
John McCallf0c11f72011-03-31 08:03:29 +00001773 FunctionDecl *FD = FunctionDecl::Create(Context,
1774 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001775 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001776 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001777 SC_Static,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001778 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001779
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001780 // Initialize debug info if necessary.
1781 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001782 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001783
John McCallf0c11f72011-03-31 08:03:29 +00001784 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001785 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001786
John McCallf0c11f72011-03-31 08:03:29 +00001787 // dst->x
1788 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1789 destField = CGF.Builder.CreateLoad(destField);
1790 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCallb62faef2013-01-22 03:56:22 +00001791 destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001792
John McCallf0c11f72011-03-31 08:03:29 +00001793 // src->x
1794 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1795 srcField = CGF.Builder.CreateLoad(srcField);
1796 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCallb62faef2013-01-22 03:56:22 +00001797 srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
John McCallf0c11f72011-03-31 08:03:29 +00001798
1799 byrefInfo.emitCopy(CGF, destField, srcField);
1800 }
1801
1802 CGF.FinishFunction();
1803
1804 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001805}
1806
John McCallf0c11f72011-03-31 08:03:29 +00001807/// Build the copy helper for a __block variable.
1808static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001809 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001810 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001811 CodeGenModule::ByrefHelpers &info) {
1812 CodeGenFunction CGF(CGM);
John McCallb62faef2013-01-22 03:56:22 +00001813 return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
John McCallf0c11f72011-03-31 08:03:29 +00001814}
1815
1816/// Generate code for a __block variable's dispose helper.
1817static llvm::Constant *
1818generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001819 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001820 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001821 CodeGenModule::ByrefHelpers &byrefInfo) {
1822 ASTContext &Context = CGF.getContext();
1823 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001824
John McCalld26bc762011-03-09 04:27:21 +00001825 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001826 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001827 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Mike Stump45031c02009-03-06 02:29:21 +00001829 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001830 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1831 FunctionType::ExtInfo(),
1832 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001833
John McCallf0c11f72011-03-31 08:03:29 +00001834 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001835 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001836
Mike Stump3899a7f2009-06-05 23:26:36 +00001837 // FIXME: We'd like to put these into a mergable by content, with
1838 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001839 llvm::Function *Fn =
1840 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001841 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001842 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001843
1844 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001845 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001846
John McCallf0c11f72011-03-31 08:03:29 +00001847 FunctionDecl *FD = FunctionDecl::Create(Context,
1848 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001849 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001850 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001851 SC_Static,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001852 false, false);
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001853 // Initialize debug info if necessary.
1854 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001855 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001856
John McCallf0c11f72011-03-31 08:03:29 +00001857 if (byrefInfo.needsDispose()) {
1858 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1859 V = CGF.Builder.CreateLoad(V);
1860 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
John McCallb62faef2013-01-22 03:56:22 +00001861 V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001862
John McCallf0c11f72011-03-31 08:03:29 +00001863 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001864 }
Mike Stump45031c02009-03-06 02:29:21 +00001865
John McCallf0c11f72011-03-31 08:03:29 +00001866 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001867
John McCallf0c11f72011-03-31 08:03:29 +00001868 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001869}
1870
John McCallf0c11f72011-03-31 08:03:29 +00001871/// Build the dispose helper for a __block variable.
1872static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001873 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001874 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001875 CodeGenModule::ByrefHelpers &info) {
1876 CodeGenFunction CGF(CGM);
John McCallb62faef2013-01-22 03:56:22 +00001877 return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
Mike Stump45031c02009-03-06 02:29:21 +00001878}
1879
John McCallb62faef2013-01-22 03:56:22 +00001880/// Lazily build the copy and dispose helpers for a __block variable
1881/// with the given information.
John McCallf0c11f72011-03-31 08:03:29 +00001882template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001883 llvm::StructType &byrefTy,
John McCallb62faef2013-01-22 03:56:22 +00001884 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001885 T &byrefInfo) {
1886 // Increase the field's alignment to be at least pointer alignment,
1887 // since the layout of the byref struct will guarantee at least that.
1888 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1889 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1890
1891 llvm::FoldingSetNodeID id;
1892 byrefInfo.Profile(id);
1893
1894 void *insertPos;
1895 CodeGenModule::ByrefHelpers *node
1896 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1897 if (node) return static_cast<T*>(node);
1898
John McCallb62faef2013-01-22 03:56:22 +00001899 byrefInfo.CopyHelper =
1900 buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1901 byrefInfo.DisposeHelper =
1902 buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
John McCallf0c11f72011-03-31 08:03:29 +00001903
1904 T *copy = new (CGM.getContext()) T(byrefInfo);
1905 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1906 return copy;
1907}
1908
John McCallb62faef2013-01-22 03:56:22 +00001909/// Build the copy and dispose helpers for the given __block variable
1910/// emission. Places the helpers in the global cache. Returns null
1911/// if no helpers are required.
John McCallf0c11f72011-03-31 08:03:29 +00001912CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001913CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001914 const AutoVarEmission &emission) {
1915 const VarDecl &var = *emission.Variable;
1916 QualType type = var.getType();
1917
John McCallb62faef2013-01-22 03:56:22 +00001918 unsigned byrefValueIndex = getByRefValueLLVMField(&var);
1919
John McCallf0c11f72011-03-31 08:03:29 +00001920 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1921 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1922 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1923
1924 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
John McCallb62faef2013-01-22 03:56:22 +00001925 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf0c11f72011-03-31 08:03:29 +00001926 }
1927
John McCallf85e1932011-06-15 23:02:42 +00001928 // Otherwise, if we don't have a retainable type, there's nothing to do.
1929 // that the runtime does extra copies.
1930 if (!type->isObjCRetainableType()) return 0;
1931
1932 Qualifiers qs = type.getQualifiers();
1933
1934 // If we have lifetime, that dominates.
1935 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001936 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001937
1938 switch (lifetime) {
1939 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1940
1941 // These are just bits as far as the runtime is concerned.
1942 case Qualifiers::OCL_ExplicitNone:
1943 case Qualifiers::OCL_Autoreleasing:
1944 return 0;
1945
1946 // Tell the runtime that this is ARC __weak, called by the
1947 // byref routines.
1948 case Qualifiers::OCL_Weak: {
1949 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001950 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001951 }
1952
1953 // ARC __strong __block variables need to be retained.
1954 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001955 // Block pointers need to be copied, and there's no direct
1956 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001957 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001958 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001959 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001960
1961 // Otherwise, we transfer ownership of the retain from the stack
1962 // to the heap.
1963 } else {
1964 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001965 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001966 }
1967 }
1968 llvm_unreachable("fell out of lifetime switch!");
1969 }
1970
John McCallf0c11f72011-03-31 08:03:29 +00001971 BlockFieldFlags flags;
1972 if (type->isBlockPointerType()) {
1973 flags |= BLOCK_FIELD_IS_BLOCK;
1974 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1975 type->isObjCObjectPointerType()) {
1976 flags |= BLOCK_FIELD_IS_OBJECT;
1977 } else {
1978 return 0;
1979 }
1980
1981 if (type.isObjCGCWeak())
1982 flags |= BLOCK_FIELD_IS_WEAK;
1983
1984 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
John McCallb62faef2013-01-22 03:56:22 +00001985 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001986}
1987
John McCall5af02db2011-03-31 01:59:53 +00001988unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1989 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1990
1991 return ByRefValueInfo.find(VD)->second.second;
1992}
1993
1994llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1995 const VarDecl *V) {
1996 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1997 Loc = Builder.CreateLoad(Loc);
1998 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1999 V->getNameAsString());
2000 return Loc;
2001}
2002
2003/// BuildByRefType - This routine changes a __block variable declared as T x
2004/// into:
2005///
2006/// struct {
2007/// void *__isa;
2008/// void *__forwarding;
2009/// int32_t __flags;
2010/// int32_t __size;
2011/// void *__copy_helper; // only if needed
2012/// void *__destroy_helper; // only if needed
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002013/// void *__byref_variable_layout;// only if needed
John McCall5af02db2011-03-31 01:59:53 +00002014/// char padding[X]; // only if needed
2015/// T x;
2016/// } x
2017///
Chris Lattner2acc6e32011-07-18 04:24:23 +00002018llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
2019 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00002020 if (Info.first)
2021 return Info.first;
2022
2023 QualType Ty = D->getType();
2024
Chris Lattner5f9e2722011-07-23 10:55:15 +00002025 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00002026
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002027 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00002028 llvm::StructType::create(getLLVMContext(),
2029 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00002030
2031 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00002032 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002033
2034 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002035 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00002036
2037 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00002038 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00002039
2040 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00002041 types.push_back(Int32Ty);
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00002042 // Note that this must match *exactly* the logic in buildByrefHelpers.
2043 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
John McCall5af02db2011-03-31 01:59:53 +00002044 if (HasCopyAndDispose) {
2045 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00002046 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002047
2048 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00002049 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002050 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002051 bool HasByrefExtendedLayout = false;
2052 Qualifiers::ObjCLifetime Lifetime;
2053 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2054 HasByrefExtendedLayout)
2055 /// void *__byref_variable_layout;
2056 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002057
2058 bool Packed = false;
2059 CharUnits Align = getContext().getDeclAlign(D);
John McCall64aa4b32013-04-16 22:48:15 +00002060 if (Align >
2061 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
John McCall5af02db2011-03-31 01:59:53 +00002062 // We have to insert padding.
2063
2064 // The struct above has 2 32-bit integers.
2065 unsigned CurrentOffsetInBytes = 4 * 2;
2066
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002067 // And either 2, 3, 4 or 5 pointers.
2068 unsigned noPointers = 2;
2069 if (HasCopyAndDispose)
2070 noPointers += 2;
2071 if (HasByrefExtendedLayout)
2072 noPointers += 1;
2073
2074 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002075
2076 // Align the offset.
2077 unsigned AlignedOffsetInBytes =
2078 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2079
2080 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2081 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00002082 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00002083 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00002084 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00002085 if (NumPaddingBytes > 1)
2086 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2087
John McCall0774cb82011-05-15 01:53:33 +00002088 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00002089
2090 // We want a packed struct.
2091 Packed = true;
2092 }
2093 }
2094
2095 // T x;
John McCall0774cb82011-05-15 01:53:33 +00002096 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00002097
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002098 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00002099
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002100 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00002101
John McCall0774cb82011-05-15 01:53:33 +00002102 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00002103
2104 return Info.first;
2105}
2106
2107/// Initialize the structural components of a __block variable, i.e.
2108/// everything but the actual object.
2109void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00002110 // Find the address of the local.
2111 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00002112
John McCallf0c11f72011-03-31 08:03:29 +00002113 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002114 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00002115 cast<llvm::PointerType>(addr->getType())->getElementType());
2116
2117 // Build the byref helpers if necessary. This is null if we don't need any.
2118 CodeGenModule::ByrefHelpers *helpers =
2119 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00002120
2121 const VarDecl &D = *emission.Variable;
2122 QualType type = D.getType();
2123
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002124 bool HasByrefExtendedLayout;
2125 Qualifiers::ObjCLifetime ByrefLifetime;
2126 bool ByRefHasLifetime =
2127 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2128
John McCallf0c11f72011-03-31 08:03:29 +00002129 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00002130
2131 // Initialize the 'isa', which is just 0 or 1.
2132 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00002133 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00002134 isa = 1;
2135 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2136 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2137
2138 // Store the address of the variable into its own forwarding pointer.
2139 Builder.CreateStore(addr,
2140 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2141
2142 // Blocks ABI:
2143 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002144 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall5af02db2011-03-31 01:59:53 +00002145 BlockFlags flags;
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002146 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2147 if (ByRefHasLifetime) {
2148 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2149 else switch (ByrefLifetime) {
2150 case Qualifiers::OCL_Strong:
2151 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2152 break;
2153 case Qualifiers::OCL_Weak:
2154 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2155 break;
2156 case Qualifiers::OCL_ExplicitNone:
2157 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2158 break;
2159 case Qualifiers::OCL_None:
2160 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2161 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2162 break;
2163 default:
2164 break;
2165 }
2166 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2167 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2168 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2169 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2170 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2171 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2172 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2173 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2174 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2175 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2176 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2177 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2178 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2179 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2180 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2181 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2182 }
2183 printf("\n");
2184 }
2185 }
2186
John McCall5af02db2011-03-31 01:59:53 +00002187 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2188 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2189
John McCallf0c11f72011-03-31 08:03:29 +00002190 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2191 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00002192 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2193
John McCallf0c11f72011-03-31 08:03:29 +00002194 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00002195 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00002196 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002197
2198 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002199 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002200 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002201 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2202 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2203 llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2204 "byref.layout");
2205 // cast destination to pointer to source type.
2206 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2207 DesTy = DesTy->getPointerTo();
2208 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2209 Builder.CreateStore(ByrefLayoutInfo, BC);
2210 }
John McCall5af02db2011-03-31 01:59:53 +00002211}
2212
John McCalld16c2cf2011-02-08 08:22:06 +00002213void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002214 llvm::Value *F = CGM.getBlockObjectDispose();
John McCallbd7370a2013-02-28 19:01:20 +00002215 llvm::Value *args[] = {
2216 Builder.CreateBitCast(V, Int8PtrTy),
2217 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2218 };
2219 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump797b6322009-03-05 01:23:13 +00002220}
John McCall5af02db2011-03-31 01:59:53 +00002221
2222namespace {
2223 struct CallBlockRelease : EHScopeStack::Cleanup {
2224 llvm::Value *Addr;
2225 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2226
John McCallad346f42011-07-12 20:27:29 +00002227 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002228 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002229 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2230 }
2231 };
2232}
2233
2234/// Enter a cleanup to destroy a __block variable. Note that this
2235/// cleanup should be a no-op if the variable hasn't left the stack
2236/// yet; if a cleanup is required for the variable itself, that needs
2237/// to be done externally.
2238void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2239 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002240 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002241 return;
2242
2243 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2244}
John McCall13db5cf2011-09-09 20:41:01 +00002245
2246/// Adjust the declaration of something from the blocks API.
2247static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2248 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002249 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002250
2251 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2252 if (GV->isDeclaration() &&
2253 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2254 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2255}
2256
2257llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2258 if (BlockObjectDispose)
2259 return BlockObjectDispose;
2260
2261 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2262 llvm::FunctionType *fty
2263 = llvm::FunctionType::get(VoidTy, args, false);
2264 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2265 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2266 return BlockObjectDispose;
2267}
2268
2269llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2270 if (BlockObjectAssign)
2271 return BlockObjectAssign;
2272
2273 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2274 llvm::FunctionType *fty
2275 = llvm::FunctionType::get(VoidTy, args, false);
2276 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2277 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2278 return BlockObjectAssign;
2279}
2280
2281llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2282 if (NSConcreteGlobalBlock)
2283 return NSConcreteGlobalBlock;
2284
2285 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2286 Int8PtrTy->getPointerTo(), 0);
2287 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2288 return NSConcreteGlobalBlock;
2289}
2290
2291llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2292 if (NSConcreteStackBlock)
2293 return NSConcreteStackBlock;
2294
2295 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2296 Int8PtrTy->getPointerTo(), 0);
2297 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2298 return NSConcreteStackBlock;
2299}