blob: 33f6eebd679eeb18b320d1602527ef3021215ab4 [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stumpb1a6e682009-09-30 02:43:10 +000014#include "CGDebugInfo.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000015#include "CodeGenFunction.h"
Fariborz Jahanian263c4de2010-02-10 23:34:57 +000016#include "CGObjCRuntime.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "CodeGenModule.h"
John McCalld16c2cf2011-02-08 08:22:06 +000018#include "CGBlocks.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000020#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Micah Villmow25a6a842012-10-08 16:25:52 +000022#include "llvm/DataLayout.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000023#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000024
Anders Carlssonacfde802009-02-12 00:39:25 +000025using namespace clang;
26using namespace CodeGen;
27
John McCall1a343eb2011-11-10 08:15:53 +000028CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
29 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanianf22ae652012-11-01 18:32:55 +000030 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
31 StructureType(0), Block(block),
John McCall6f103ba2011-11-10 10:43:54 +000032 DominatingIP(0) {
John McCallee504292010-05-21 04:11:14 +000033
John McCall1a343eb2011-11-10 08:15:53 +000034 // Skip asm prefix, if any. 'name' is usually taken directly from
35 // the mangled name of the enclosing function.
36 if (!name.empty() && name[0] == '\01')
37 name = name.substr(1);
John McCallee504292010-05-21 04:11:14 +000038}
39
John McCallf0c11f72011-03-31 08:03:29 +000040// Anchor the vtable to this translation unit.
41CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
42
John McCall6b5a61b2011-02-07 10:33:21 +000043/// Build the given block as a global block.
44static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
45 const CGBlockInfo &blockInfo,
46 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000047
John McCall6b5a61b2011-02-07 10:33:21 +000048/// Build the helper function to copy a block.
49static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
50 const CGBlockInfo &blockInfo) {
51 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
52}
53
54/// Build the helper function to dipose of a block.
55static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
56 const CGBlockInfo &blockInfo) {
57 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
58}
59
Fariborz Jahanianaf879c02012-10-25 18:06:53 +000060/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
61/// buildBlockDescriptor is accessed from 5th field of the Block_literal
62/// meta-data and contains stationary information about the block literal.
63/// Its definition will have 4 (or optinally 6) words.
64/// struct Block_descriptor {
65/// unsigned long reserved;
66/// unsigned long size; // size of Block_literal metadata in bytes.
67/// void *copy_func_helper_decl; // optional copy helper.
68/// void *destroy_func_decl; // optioanl destructor helper.
69/// void *block_method_encoding_address;//@encode for block literal signature.
70/// void *block_layout_info; // encoding of captured block variables.
71/// };
John McCall6b5a61b2011-02-07 10:33:21 +000072static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
73 const CGBlockInfo &blockInfo) {
74 ASTContext &C = CGM.getContext();
75
Chris Lattner2acc6e32011-07-18 04:24:23 +000076 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
77 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000078
Chris Lattner5f9e2722011-07-23 10:55:15 +000079 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000080
81 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000082 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000083
84 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000085 // FIXME: What is the right way to say this doesn't fit? We should give
86 // a user diagnostic in that case. Better fix would be to change the
87 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000088 elements.push_back(llvm::ConstantInt::get(ulong,
89 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000090
John McCall6b5a61b2011-02-07 10:33:21 +000091 // Optional copy/dispose helpers.
92 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000093 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000094 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000095
96 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000097 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000098 }
99
John McCall6b5a61b2011-02-07 10:33:21 +0000100 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
101 std::string typeAtEncoding =
102 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
103 elements.push_back(llvm::ConstantExpr::getBitCast(
104 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000105
John McCall6b5a61b2011-02-07 10:33:21 +0000106 // GC layout.
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000107 if (C.getLangOpts().ObjC1) {
108 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
109 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
110 else
111 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
112 }
John McCall6b5a61b2011-02-07 10:33:21 +0000113 else
114 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000115
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000116 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000117
John McCall6b5a61b2011-02-07 10:33:21 +0000118 llvm::GlobalVariable *global =
119 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
120 llvm::GlobalValue::InternalLinkage,
121 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000122
John McCall6b5a61b2011-02-07 10:33:21 +0000123 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000124}
125
John McCall6b5a61b2011-02-07 10:33:21 +0000126/*
127 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000128
John McCall6b5a61b2011-02-07 10:33:21 +0000129 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
130 struct Block_literal {
131 /// Initialized to one of:
132 /// extern void *_NSConcreteStackBlock[];
133 /// extern void *_NSConcreteGlobalBlock[];
134 ///
135 /// In theory, we could start one off malloc'ed by setting
136 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
137 /// this isa:
138 /// extern void *_NSConcreteMallocBlock[];
139 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000140
John McCall6b5a61b2011-02-07 10:33:21 +0000141 /// These are the flags (with corresponding bit number) that the
142 /// compiler is actually supposed to know about.
143 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
144 /// descriptor provides copy and dispose helper functions
145 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
146 /// object with a nontrivial destructor or copy constructor
147 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
148 /// as global memory
149 /// 29. BLOCK_USE_STRET - indicates that the block function
150 /// uses stret, which objc_msgSend needs to know about
151 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
152 /// @encoded signature string
153 /// And we're not supposed to manipulate these:
154 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
155 /// to malloc'ed memory
156 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
157 /// to GC-allocated memory
158 /// Additionally, the bottom 16 bits are a reference count which
159 /// should be zero on the stack.
160 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000161
John McCall6b5a61b2011-02-07 10:33:21 +0000162 /// Reserved; should be zero-initialized.
163 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000164
John McCall6b5a61b2011-02-07 10:33:21 +0000165 /// Function pointer generated from block literal.
166 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000167
John McCall6b5a61b2011-02-07 10:33:21 +0000168 /// Block description metadata generated from block literal.
169 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000170
John McCall6b5a61b2011-02-07 10:33:21 +0000171 /// Captured values follow.
172 _CapturesTypes captures...;
173 };
174 */
David Chisnall5e530af2009-11-17 19:33:30 +0000175
John McCall6b5a61b2011-02-07 10:33:21 +0000176/// The number of fields in a block header.
177const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000178
John McCall6b5a61b2011-02-07 10:33:21 +0000179namespace {
180 /// A chunk of data that we actually have to capture in the block.
181 struct BlockLayoutChunk {
182 CharUnits Alignment;
183 CharUnits Size;
184 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000185 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000186
John McCall6b5a61b2011-02-07 10:33:21 +0000187 BlockLayoutChunk(CharUnits align, CharUnits size,
188 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000189 llvm::Type *type)
John McCall6b5a61b2011-02-07 10:33:21 +0000190 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000191
John McCall6b5a61b2011-02-07 10:33:21 +0000192 /// Tell the block info that this chunk has the given field index.
193 void setIndex(CGBlockInfo &info, unsigned index) {
194 if (!Capture)
195 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000196 else
John McCall6b5a61b2011-02-07 10:33:21 +0000197 info.Captures[Capture->getVariable()]
198 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000199 }
John McCall6b5a61b2011-02-07 10:33:21 +0000200 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000201
John McCall6b5a61b2011-02-07 10:33:21 +0000202 /// Order by descending alignment.
203 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
204 return left.Alignment > right.Alignment;
205 }
206}
207
John McCall461c9c12011-02-08 03:07:00 +0000208/// Determines if the given type is safe for constant capture in C++.
209static bool isSafeForCXXConstantCapture(QualType type) {
210 const RecordType *recordType =
211 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
212
213 // Only records can be unsafe.
214 if (!recordType) return true;
215
216 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
217
218 // Maintain semantics for classes with non-trivial dtors or copy ctors.
219 if (!record->hasTrivialDestructor()) return false;
220 if (!record->hasTrivialCopyConstructor()) return false;
221
222 // Otherwise, we just have to make sure there aren't any mutable
223 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000224 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000225}
226
John McCall6b5a61b2011-02-07 10:33:21 +0000227/// It is illegal to modify a const object after initialization.
228/// Therefore, if a const object has a constant initializer, we don't
229/// actually need to keep storage for it in the block; we'll just
230/// rematerialize it at the start of the block function. This is
231/// acceptable because we make no promises about address stability of
232/// captured variables.
233static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000234 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000235 const VarDecl *var) {
236 QualType type = var->getType();
237
238 // We can only do this if the variable is const.
239 if (!type.isConstQualified()) return 0;
240
John McCall461c9c12011-02-08 03:07:00 +0000241 // Furthermore, in C++ we have to worry about mutable fields:
242 // C++ [dcl.type.cv]p4:
243 // Except that any class member declared mutable can be
244 // modified, any attempt to modify a const object during its
245 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000246 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000247 return 0;
248
249 // If the variable doesn't have any initializer (shouldn't this be
250 // invalid?), it's not clear what we should do. Maybe capture as
251 // zero?
252 const Expr *init = var->getInit();
253 if (!init) return 0;
254
Richard Smith2d6a5672012-01-14 04:30:29 +0000255 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000256}
257
258/// Get the low bit of a nonzero character count. This is the
259/// alignment of the nth byte if the 0th byte is universally aligned.
260static CharUnits getLowBit(CharUnits v) {
261 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
262}
263
264static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000265 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000266 ASTContext &C = CGM.getContext();
267
268 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
269 CharUnits ptrSize, ptrAlign, intSize, intAlign;
270 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
271 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
272
273 // Are there crazy embedded platforms where this isn't true?
274 assert(intSize <= ptrSize && "layout assumptions horribly violated");
275
276 CharUnits headerSize = ptrSize;
277 if (2 * intSize < ptrAlign) headerSize += ptrSize;
278 else headerSize += 2 * intSize;
279 headerSize += 2 * ptrSize;
280
281 info.BlockAlign = ptrAlign;
282 info.BlockSize = headerSize;
283
284 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000285 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
286 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000287 elementTypes.push_back(i8p);
288 elementTypes.push_back(intTy);
289 elementTypes.push_back(intTy);
290 elementTypes.push_back(i8p);
291 elementTypes.push_back(CGM.getBlockDescriptorType());
292
293 assert(elementTypes.size() == BlockHeaderSize);
294}
295
296/// Compute the layout of the given block. Attempts to lay the block
297/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000298static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
299 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000300 ASTContext &C = CGM.getContext();
301 const BlockDecl *block = info.getBlockDecl();
302
Chris Lattner5f9e2722011-07-23 10:55:15 +0000303 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000304 initializeForBlockHeader(CGM, info, elementTypes);
305
306 if (!block->hasCaptures()) {
307 info.StructureType =
308 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
309 info.CanBeGlobal = true;
310 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000311 }
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000312 else if (C.getLangOpts().ObjC1 &&
313 CGM.getLangOpts().getGC() == LangOptions::NonGC)
314 info.HasCapturedVariableLayout = true;
315
John McCall6b5a61b2011-02-07 10:33:21 +0000316 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000317 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000318 layout.reserve(block->capturesCXXThis() +
319 (block->capture_end() - block->capture_begin()));
320
321 CharUnits maxFieldAlign;
322
323 // First, 'this'.
324 if (block->capturesCXXThis()) {
325 const DeclContext *DC = block->getDeclContext();
326 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
327 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000328 QualType thisType;
329 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
330 thisType = C.getPointerType(C.getRecordType(RD));
331 else
332 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000333
Jay Foadef6de3d2011-07-11 09:56:20 +0000334 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000335 std::pair<CharUnits,CharUnits> tinfo
336 = CGM.getContext().getTypeInfoInChars(thisType);
337 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
338
339 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
340 }
341
342 // Next, all the block captures.
343 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
344 ce = block->capture_end(); ci != ce; ++ci) {
345 const VarDecl *variable = ci->getVariable();
346
347 if (ci->isByRef()) {
348 // We have to copy/dispose of the __block reference.
349 info.NeedsCopyDispose = true;
350
John McCall6b5a61b2011-02-07 10:33:21 +0000351 // Just use void* instead of a pointer to the byref type.
352 QualType byRefPtrTy = C.VoidPtrTy;
353
Jay Foadef6de3d2011-07-11 09:56:20 +0000354 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000355 std::pair<CharUnits,CharUnits> tinfo
356 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
357 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
358
359 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
360 &*ci, llvmType));
361 continue;
362 }
363
364 // Otherwise, build a layout chunk with the size and alignment of
365 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000366 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000367 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
368 continue;
369 }
370
John McCallf85e1932011-06-15 23:02:42 +0000371 // If we have a lifetime qualifier, honor it for capture purposes.
372 // That includes *not* copying it if it's __unsafe_unretained.
373 if (Qualifiers::ObjCLifetime lifetime
374 = variable->getType().getObjCLifetime()) {
375 switch (lifetime) {
376 case Qualifiers::OCL_None: llvm_unreachable("impossible");
377 case Qualifiers::OCL_ExplicitNone:
378 case Qualifiers::OCL_Autoreleasing:
379 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000380
John McCallf85e1932011-06-15 23:02:42 +0000381 case Qualifiers::OCL_Strong:
382 case Qualifiers::OCL_Weak:
383 info.NeedsCopyDispose = true;
384 }
385
386 // Block pointers require copy/dispose. So do Objective-C pointers.
387 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000388 info.NeedsCopyDispose = true;
389
390 // So do types that require non-trivial copy construction.
391 } else if (ci->hasCopyExpr()) {
392 info.NeedsCopyDispose = true;
393 info.HasCXXObject = true;
394
395 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000396 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000397 if (const CXXRecordDecl *record =
398 variable->getType()->getAsCXXRecordDecl()) {
399 if (!record->hasTrivialDestructor()) {
400 info.HasCXXObject = true;
401 info.NeedsCopyDispose = true;
402 }
403 }
404 }
405
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000406 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000407 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000408 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000409
John McCall6b5a61b2011-02-07 10:33:21 +0000410 maxFieldAlign = std::max(maxFieldAlign, align);
411
Jay Foadef6de3d2011-07-11 09:56:20 +0000412 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000413 CGM.getTypes().ConvertTypeForMem(VT);
414
John McCall6b5a61b2011-02-07 10:33:21 +0000415 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
416 }
417
418 // If that was everything, we're done here.
419 if (layout.empty()) {
420 info.StructureType =
421 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
422 info.CanBeGlobal = true;
423 return;
424 }
425
426 // Sort the layout by alignment. We have to use a stable sort here
427 // to get reproducible results. There should probably be an
428 // llvm::array_pod_stable_sort.
429 std::stable_sort(layout.begin(), layout.end());
430
431 CharUnits &blockSize = info.BlockSize;
432 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
433
434 // Assuming that the first byte in the header is maximally aligned,
435 // get the alignment of the first byte following the header.
436 CharUnits endAlign = getLowBit(blockSize);
437
438 // If the end of the header isn't satisfactorily aligned for the
439 // maximum thing, look for things that are okay with the header-end
440 // alignment, and keep appending them until we get something that's
441 // aligned right. This algorithm is only guaranteed optimal if
442 // that condition is satisfied at some point; otherwise we can get
443 // things like:
444 // header // next byte has alignment 4
445 // something_with_size_5; // next byte has alignment 1
446 // something_with_alignment_8;
447 // which has 7 bytes of padding, as opposed to the naive solution
448 // which might have less (?).
449 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000450 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000451 li = layout.begin() + 1, le = layout.end();
452
453 // Look for something that the header end is already
454 // satisfactorily aligned for.
455 for (; li != le && endAlign < li->Alignment; ++li)
456 ;
457
458 // If we found something that's naturally aligned for the end of
459 // the header, keep adding things...
460 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000461 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000462 for (; li != le; ++li) {
463 assert(endAlign >= li->Alignment);
464
465 li->setIndex(info, elementTypes.size());
466 elementTypes.push_back(li->Type);
467 blockSize += li->Size;
468 endAlign = getLowBit(blockSize);
469
470 // ...until we get to the alignment of the maximum field.
471 if (endAlign >= maxFieldAlign)
472 break;
473 }
474
475 // Don't re-append everything we just appended.
476 layout.erase(first, li);
477 }
478 }
479
John McCall6ea48412012-04-26 21:14:42 +0000480 assert(endAlign == getLowBit(blockSize));
481
John McCall6b5a61b2011-02-07 10:33:21 +0000482 // At this point, we just have to add padding if the end align still
483 // isn't aligned right.
484 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000485 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
486 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000487
John McCall5936e332011-02-15 09:22:45 +0000488 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
489 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000490 blockSize = newBlockSize;
John McCall6c803f72012-05-01 20:28:00 +0000491 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall6b5a61b2011-02-07 10:33:21 +0000492 }
493
John McCall6c803f72012-05-01 20:28:00 +0000494 assert(endAlign >= maxFieldAlign);
John McCall6ea48412012-04-26 21:14:42 +0000495 assert(endAlign == getLowBit(blockSize));
496
John McCall6b5a61b2011-02-07 10:33:21 +0000497 // Slam everything else on now. This works because they have
498 // strictly decreasing alignment and we expect that size is always a
499 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000500 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000501 li = layout.begin(), le = layout.end(); li != le; ++li) {
502 assert(endAlign >= li->Alignment);
503 li->setIndex(info, elementTypes.size());
504 elementTypes.push_back(li->Type);
505 blockSize += li->Size;
506 endAlign = getLowBit(blockSize);
507 }
508
509 info.StructureType =
510 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
511}
512
John McCall1a343eb2011-11-10 08:15:53 +0000513/// Enter the scope of a block. This should be run at the entrance to
514/// a full-expression so that the block's cleanups are pushed at the
515/// right place in the stack.
516static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000517 assert(CGF.HaveInsertPoint());
518
John McCall1a343eb2011-11-10 08:15:53 +0000519 // Allocate the block info and place it at the head of the list.
520 CGBlockInfo &blockInfo =
521 *new CGBlockInfo(block, CGF.CurFn->getName());
522 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
523 CGF.FirstBlockInfo = &blockInfo;
524
525 // Compute information about the layout, etc., of this block,
526 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000527 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000528
529 // Nothing else to do if it can be global.
530 if (blockInfo.CanBeGlobal) return;
531
532 // Make the allocation for the block.
533 blockInfo.Address =
534 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
535 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
536
537 // If there are cleanups to emit, enter them (but inactive).
538 if (!blockInfo.NeedsCopyDispose) return;
539
540 // Walk through the captures (in order) and find the ones not
541 // captured by constant.
542 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
543 ce = block->capture_end(); ci != ce; ++ci) {
544 // Ignore __block captures; there's nothing special in the
545 // on-stack block that we need to do for them.
546 if (ci->isByRef()) continue;
547
548 // Ignore variables that are constant-captured.
549 const VarDecl *variable = ci->getVariable();
550 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
551 if (capture.isConstant()) continue;
552
553 // Ignore objects that aren't destructed.
554 QualType::DestructionKind dtorKind =
555 variable->getType().isDestructedType();
556 if (dtorKind == QualType::DK_none) continue;
557
558 CodeGenFunction::Destroyer *destroyer;
559
560 // Block captures count as local values and have imprecise semantics.
561 // They also can't be arrays, so need to worry about that.
562 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000563 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000564 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000565 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000566 }
567
568 // GEP down to the address.
569 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
570 capture.getIndex());
571
John McCall6f103ba2011-11-10 10:43:54 +0000572 // We can use that GEP as the dominating IP.
573 if (!blockInfo.DominatingIP)
574 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
575
John McCall1a343eb2011-11-10 08:15:53 +0000576 CleanupKind cleanupKind = InactiveNormalCleanup;
577 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
578 if (useArrayEHCleanup)
579 cleanupKind = InactiveNormalAndEHCleanup;
580
581 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000582 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000583
584 // Remember where that cleanup was.
585 capture.setCleanup(CGF.EHStack.stable_begin());
586 }
587}
588
589/// Enter a full-expression with a non-trivial number of objects to
590/// clean up. This is in this file because, at the moment, the only
591/// kind of cleanup object is a BlockDecl*.
592void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
593 assert(E->getNumObjects() != 0);
594 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
595 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
596 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
597 enterBlockScope(*this, *i);
598 }
599}
600
601/// Find the layout for the given block in a linked list and remove it.
602static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
603 const BlockDecl *block) {
604 while (true) {
605 assert(head && *head);
606 CGBlockInfo *cur = *head;
607
608 // If this is the block we're looking for, splice it out of the list.
609 if (cur->getBlockDecl() == block) {
610 *head = cur->NextBlockInfo;
611 return cur;
612 }
613
614 head = &cur->NextBlockInfo;
615 }
616}
617
618/// Destroy a chain of block layouts.
619void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
620 assert(head && "destroying an empty chain");
621 do {
622 CGBlockInfo *cur = head;
623 head = cur->NextBlockInfo;
624 delete cur;
625 } while (head != 0);
626}
627
John McCall6b5a61b2011-02-07 10:33:21 +0000628/// Emit a block literal expression in the current function.
629llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000630 // If the block has no captures, we won't have a pre-computed
631 // layout for it.
632 if (!blockExpr->getBlockDecl()->hasCaptures()) {
633 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000634 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000635 blockInfo.BlockExpression = blockExpr;
636 return EmitBlockLiteral(blockInfo);
637 }
John McCall6b5a61b2011-02-07 10:33:21 +0000638
John McCall1a343eb2011-11-10 08:15:53 +0000639 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000640 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000641 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
642 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000643
John McCall1a343eb2011-11-10 08:15:53 +0000644 blockInfo->BlockExpression = blockExpr;
645 return EmitBlockLiteral(*blockInfo);
646}
647
648llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
649 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000650 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000651 llvm::Constant *blockFn
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000652 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000653 CurFuncDecl, LocalDeclMap,
Eli Friedman23f02672012-03-01 04:01:32 +0000654 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000655 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000656
657 // If there is nothing to capture, we can emit this as a global block.
658 if (blockInfo.CanBeGlobal)
659 return buildGlobalBlock(CGM, blockInfo, blockFn);
660
661 // Otherwise, we have to emit this as a local block.
662
663 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000664 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000665
666 // Build the block descriptor.
667 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
668
John McCall1a343eb2011-11-10 08:15:53 +0000669 llvm::AllocaInst *blockAddr = blockInfo.Address;
670 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000671
672 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000673 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000674 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall6b5a61b2011-02-07 10:33:21 +0000675 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
676 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000677 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000678
679 // Initialize the block literal.
680 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000681 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000682 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000683 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000684 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
685 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
686 "block.invoke"));
687 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
688 "block.descriptor"));
689
690 // Finally, capture all the values into the block.
691 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
692
693 // First, 'this'.
694 if (blockDecl->capturesCXXThis()) {
695 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
696 blockInfo.CXXThisIndex,
697 "block.captured-this.addr");
698 Builder.CreateStore(LoadCXXThis(), addr);
699 }
700
701 // Next, captured variables.
702 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
703 ce = blockDecl->capture_end(); ci != ce; ++ci) {
704 const VarDecl *variable = ci->getVariable();
705 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
706
707 // Ignore constant captures.
708 if (capture.isConstant()) continue;
709
710 QualType type = variable->getType();
711
712 // This will be a [[type]]*, except that a byref entry will just be
713 // an i8**.
714 llvm::Value *blockField =
715 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
716 "block.captured");
717
718 // Compute the address of the thing we're going to move into the
719 // block literal.
720 llvm::Value *src;
Douglas Gregor29a93f82012-05-16 16:50:20 +0000721 if (BlockInfo && ci->isNested()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000722 // We need to use the capture from the enclosing block.
723 const CGBlockInfo::Capture &enclosingCapture =
724 BlockInfo->getCapture(variable);
725
726 // This is a [[type]]*, except that a byref entry wil just be an i8**.
727 src = Builder.CreateStructGEP(LoadBlockStruct(),
728 enclosingCapture.getIndex(),
729 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000730 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000731 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000732 // special; we'll simply emit it directly.
733 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000734 } else {
735 // This is a [[type]]*.
736 src = LocalDeclMap[variable];
737 }
738
739 // For byrefs, we just write the pointer to the byref struct into
740 // the block field. There's no need to chase the forwarding
741 // pointer at this point, since we're building something that will
742 // live a shorter life than the stack byref anyway.
743 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000744 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000745 if (ci->isNested())
746 src = Builder.CreateLoad(src, "byref.capture");
747 else
John McCall5936e332011-02-15 09:22:45 +0000748 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000749
John McCall5936e332011-02-15 09:22:45 +0000750 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000751 Builder.CreateStore(src, blockField);
752
753 // If we have a copy constructor, evaluate that into the block field.
754 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000755 if (blockDecl->isConversionFromLambda()) {
756 // If we have a lambda conversion, emit the expression
757 // directly into the block instead.
758 CharUnits Align = getContext().getTypeAlignInChars(type);
759 AggValueSlot Slot =
760 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
761 AggValueSlot::IsDestructed,
762 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000763 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000764 EmitAggExpr(copyExpr, Slot);
765 } else {
766 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
767 }
John McCall6b5a61b2011-02-07 10:33:21 +0000768
769 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000770 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000771 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
772
773 // Otherwise, fake up a POD copy into the block field.
774 } else {
John McCallf85e1932011-06-15 23:02:42 +0000775 // Fake up a new variable so that EmitScalarInit doesn't think
776 // we're referring to the variable in its own initializer.
777 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000778 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000779
John McCallbb699b02011-02-07 18:37:40 +0000780 // We use one of these or the other depending on whether the
781 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000782 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
783 /*refersToEnclosing*/ ci->isNested(), type,
784 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000785
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000786 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000787 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000788 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000789 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000790 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000791 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000792 }
793
John McCall1a343eb2011-11-10 08:15:53 +0000794 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000795 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000796 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
797 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000798 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000799 }
John McCall6b5a61b2011-02-07 10:33:21 +0000800 }
801
802 // Cast to the converted block-pointer type, which happens (somewhat
803 // unfortunately) to be a pointer to function type.
804 llvm::Value *result =
805 Builder.CreateBitCast(blockAddr,
806 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000807
John McCall6b5a61b2011-02-07 10:33:21 +0000808 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000809}
810
811
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000812llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000813 if (BlockDescriptorType)
814 return BlockDescriptorType;
815
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000816 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000817 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000818
Mike Stumpab695142009-02-13 15:16:56 +0000819 // struct __block_descriptor {
820 // unsigned long reserved;
821 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000822 //
823 // // later, the following will be added
824 //
825 // struct {
826 // void (*copyHelper)();
827 // void (*copyHelper)();
828 // } helpers; // !!! optional
829 //
830 // const char *signature; // the block signature
831 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000832 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000833 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000834 llvm::StructType::create("struct.__block_descriptor",
835 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000836
John McCall6b5a61b2011-02-07 10:33:21 +0000837 // Now form a pointer to that.
838 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000839 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000840}
841
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000842llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000843 if (GenericBlockLiteralType)
844 return GenericBlockLiteralType;
845
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000846 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000847
Mike Stump9b8a7972009-02-13 15:25:34 +0000848 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000849 // void *__isa;
850 // int __flags;
851 // int __reserved;
852 // void (*__invoke)(void *);
853 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000854 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000855 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000856 llvm::StructType::create("struct.__block_literal_generic",
857 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
858 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000859
Mike Stump9b8a7972009-02-13 15:25:34 +0000860 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000861}
862
Mike Stumpbd65cac2009-02-19 01:01:04 +0000863
Anders Carlssona1736c02009-12-24 21:13:40 +0000864RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
865 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000866 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000867 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000868
Anders Carlssonacfde802009-02-12 00:39:25 +0000869 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
870
871 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000872 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000873 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000874
875 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000876 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000877 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
878
879 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000880 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000881
Benjamin Kramer578faa82011-09-27 21:06:10 +0000882 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000883
Anders Carlssonacfde802009-02-12 00:39:25 +0000884 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000885 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000886 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000887
Anders Carlsson782f3972009-04-08 23:13:16 +0000888 QualType FnType = BPT->getPointeeType();
889
Anders Carlssonacfde802009-02-12 00:39:25 +0000890 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000891 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000892 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000893
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000894 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000895 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000896
John McCall64cd2322011-03-09 08:39:33 +0000897 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000898 const CGFunctionInfo &FnInfo =
John McCall0f3d0972012-07-07 06:41:13 +0000899 CGM.getTypes().arrangeFreeFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000901 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000902 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner2acc6e32011-07-18 04:24:23 +0000904 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000905 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Anders Carlssonacfde802009-02-12 00:39:25 +0000907 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000908 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000909}
Anders Carlssond5cab542009-02-12 17:55:02 +0000910
John McCall6b5a61b2011-02-07 10:33:21 +0000911llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
912 bool isByRef) {
913 assert(BlockInfo && "evaluating block ref without block information?");
914 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000915
John McCall6b5a61b2011-02-07 10:33:21 +0000916 // Handle constant captures.
917 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000918
John McCall6b5a61b2011-02-07 10:33:21 +0000919 llvm::Value *addr =
920 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
921 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000922
John McCall6b5a61b2011-02-07 10:33:21 +0000923 if (isByRef) {
924 // addr should be a void** right now. Load, then cast the result
925 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000926
John McCall6b5a61b2011-02-07 10:33:21 +0000927 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000928 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000929 = llvm::PointerType::get(BuildByRefType(variable), 0);
930 addr = Builder.CreateBitCast(addr, byrefPointerType,
931 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000932
John McCall6b5a61b2011-02-07 10:33:21 +0000933 // Follow the forwarding pointer.
934 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
935 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000936
John McCall6b5a61b2011-02-07 10:33:21 +0000937 // Cast back to byref* and GEP over to the actual object.
938 addr = Builder.CreateBitCast(addr, byrefPointerType);
939 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
940 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000941 }
942
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000943 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000944 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000945
John McCall6b5a61b2011-02-07 10:33:21 +0000946 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000947}
948
Mike Stump67a64482009-02-14 22:16:35 +0000949llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000950CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000951 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000952 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
953 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000954
John McCall6b5a61b2011-02-07 10:33:21 +0000955 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +0000956 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000957
John McCall6b5a61b2011-02-07 10:33:21 +0000958 // Using that metadata, generate the actual block function.
959 llvm::Constant *blockFn;
960 {
961 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000962 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
963 blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000964 0, LocalDeclMap,
965 false);
John McCall6b5a61b2011-02-07 10:33:21 +0000966 }
John McCall5936e332011-02-15 09:22:45 +0000967 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000968
John McCalld16c2cf2011-02-08 08:22:06 +0000969 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000970}
971
John McCall6b5a61b2011-02-07 10:33:21 +0000972static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
973 const CGBlockInfo &blockInfo,
974 llvm::Constant *blockFn) {
975 assert(blockInfo.CanBeGlobal);
976
977 // Generate the constants for the block literal initializer.
978 llvm::Constant *fields[BlockHeaderSize];
979
980 // isa
981 fields[0] = CGM.getNSConcreteGlobalBlock();
982
983 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000984 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
985 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
986
John McCall5936e332011-02-15 09:22:45 +0000987 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000988
989 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000990 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000991
992 // Function
993 fields[3] = blockFn;
994
995 // Descriptor
996 fields[4] = buildBlockDescriptor(CGM, blockInfo);
997
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000998 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000999
1000 llvm::GlobalVariable *literal =
1001 new llvm::GlobalVariable(CGM.getModule(),
1002 init->getType(),
1003 /*constant*/ true,
1004 llvm::GlobalVariable::InternalLinkage,
1005 init,
1006 "__block_literal_global");
1007 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1008
1009 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001010 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +00001011 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1012 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +00001013}
1014
Mike Stump00470a12009-03-05 08:32:30 +00001015llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +00001016CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1017 const CGBlockInfo &blockInfo,
1018 const Decl *outerFnDecl,
Eli Friedman64bee652012-02-25 02:48:22 +00001019 const DeclMapTy &ldm,
1020 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001021 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001022
Devang Patel6d1155b2011-03-07 21:53:18 +00001023 // Check if we should generate debug info for this block function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001024 maybeInitializeDebugInfo();
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001025 CurGD = GD;
1026
John McCall6b5a61b2011-02-07 10:33:21 +00001027 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Mike Stump7f28a9c2009-03-13 23:34:28 +00001029 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001030 // to be local to this function as well, in case they're directly
1031 // referenced in a block.
1032 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1033 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1034 if (var && !var->hasLocalStorage())
1035 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001036 }
1037
John McCall6b5a61b2011-02-07 10:33:21 +00001038 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001039
John McCall6b5a61b2011-02-07 10:33:21 +00001040 // Build the argument list.
1041 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001042
John McCall6b5a61b2011-02-07 10:33:21 +00001043 // The first argument is the block pointer. Just take it as a void*
1044 // and cast it later.
1045 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001046 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001047
John McCall8178df32011-02-22 22:38:33 +00001048 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1049 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001050 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001051
John McCall6b5a61b2011-02-07 10:33:21 +00001052 // Now add the rest of the parameters.
1053 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1054 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001055 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001056
John McCall6b5a61b2011-02-07 10:33:21 +00001057 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001058 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001059 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001060 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1061 fnType->getExtInfo(),
1062 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001063 if (CGM.ReturnTypeUsesSRet(fnInfo))
1064 blockInfo.UsesStret = true;
1065
John McCallde5d3c72012-02-17 03:33:10 +00001066 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001067
John McCall6b5a61b2011-02-07 10:33:21 +00001068 MangleBuffer name;
1069 CGM.getBlockMangledName(GD, name, blockDecl);
1070 llvm::Function *fn =
1071 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1072 name.getString(), &CGM.getModule());
1073 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001074
John McCall6b5a61b2011-02-07 10:33:21 +00001075 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001076 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001077 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001078 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001079
John McCall8178df32011-02-22 22:38:33 +00001080 // Okay. Undo some of what StartFunction did.
1081
1082 // Pull the 'self' reference out of the local decl map.
1083 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1084 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001085 BlockPointer = Builder.CreateBitCast(blockAddr,
1086 blockInfo.StructureType->getPointerTo(),
1087 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001088
John McCallea1471e2010-05-20 01:18:31 +00001089 // If we have a C++ 'this' reference, go ahead and force it into
1090 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001091 if (blockDecl->capturesCXXThis()) {
1092 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1093 blockInfo.CXXThisIndex,
1094 "block.captured-this");
1095 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001096 }
1097
John McCall6b5a61b2011-02-07 10:33:21 +00001098 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1099 // appease it.
1100 if (const ObjCMethodDecl *method
1101 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1102 const VarDecl *self = method->getSelfDecl();
1103
1104 // There might not be a capture for 'self', but if there is...
1105 if (blockInfo.Captures.count(self)) {
1106 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1107 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1108 capture.getIndex(),
1109 "block.captured-self");
1110 LocalDeclMap[self] = selfAddr;
1111 }
1112 }
1113
1114 // Also force all the constant captures.
1115 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1116 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1117 const VarDecl *variable = ci->getVariable();
1118 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1119 if (!capture.isConstant()) continue;
1120
1121 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1122
1123 llvm::AllocaInst *alloca =
1124 CreateMemTemp(variable->getType(), "block.captured-const");
1125 alloca->setAlignment(align);
1126
1127 Builder.CreateStore(capture.getConstant(), alloca, align);
1128
1129 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001130 }
1131
John McCallf4b88a42012-03-10 09:33:50 +00001132 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001133 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1134 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1135 --entry_ptr;
1136
Eli Friedman64bee652012-02-25 02:48:22 +00001137 if (IsLambdaConversionToBlock)
1138 EmitLambdaBlockInvokeBody();
1139 else
1140 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001141
Mike Stumpde8c5c72009-10-01 00:27:30 +00001142 // Remember where we were...
1143 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001144
Mike Stumpde8c5c72009-10-01 00:27:30 +00001145 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001146 ++entry_ptr;
1147 Builder.SetInsertPoint(entry, entry_ptr);
1148
John McCallf4b88a42012-03-10 09:33:50 +00001149 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001150 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001151 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001152 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1153 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1154 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001155 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001156
Douglas Gregor4cdad312012-10-23 20:05:01 +00001157 if (CGM.getCodeGenOpts().getDebugInfo()
1158 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001159 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1160 if (capture.isConstant()) {
1161 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1162 Builder);
1163 continue;
1164 }
John McCall6b5a61b2011-02-07 10:33:21 +00001165
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001166 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1167 Builder, blockInfo);
1168 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001169 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001170 }
John McCall6b5a61b2011-02-07 10:33:21 +00001171
Mike Stumpde8c5c72009-10-01 00:27:30 +00001172 // And resume where we left off.
1173 if (resume == 0)
1174 Builder.ClearInsertionPoint();
1175 else
1176 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001177
John McCall6b5a61b2011-02-07 10:33:21 +00001178 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001179
John McCall6b5a61b2011-02-07 10:33:21 +00001180 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001181}
Mike Stumpa99038c2009-02-28 09:07:16 +00001182
John McCall6b5a61b2011-02-07 10:33:21 +00001183/*
1184 notes.push_back(HelperInfo());
1185 HelperInfo &note = notes.back();
1186 note.index = capture.getIndex();
1187 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1188 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001189
John McCall6b5a61b2011-02-07 10:33:21 +00001190 if (ci->isByRef()) {
1191 note.flag = BLOCK_FIELD_IS_BYREF;
1192 if (type.isObjCGCWeak())
1193 note.flag |= BLOCK_FIELD_IS_WEAK;
1194 } else if (type->isBlockPointerType()) {
1195 note.flag = BLOCK_FIELD_IS_BLOCK;
1196 } else {
1197 note.flag = BLOCK_FIELD_IS_OBJECT;
1198 }
1199 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001200
Mike Stump00470a12009-03-05 08:32:30 +00001201
Mike Stumpa99038c2009-02-28 09:07:16 +00001202
John McCall6b5a61b2011-02-07 10:33:21 +00001203llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001204CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001205 ASTContext &C = getContext();
1206
1207 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001208 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1209 args.push_back(&dstDecl);
1210 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1211 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Mike Stumpa4f668f2009-03-06 01:33:24 +00001213 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001214 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1215 FunctionType::ExtInfo(),
1216 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001217
John McCall6b5a61b2011-02-07 10:33:21 +00001218 // FIXME: it would be nice if these were mergeable with things with
1219 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001220 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001221
1222 llvm::Function *Fn =
1223 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001224 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001225
1226 IdentifierInfo *II
1227 = &CGM.getContext().Idents.get("__copy_helper_block_");
1228
Devang Patel58dc5ca2011-05-02 20:37:08 +00001229 // Check if we should generate debug info for this block helper function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001230 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001231
John McCall6b5a61b2011-02-07 10:33:21 +00001232 FunctionDecl *FD = FunctionDecl::Create(C,
1233 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001234 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001235 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001236 SC_Static,
1237 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001238 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001239 false);
John McCalld26bc762011-03-09 04:27:21 +00001240 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001241
Chris Lattner2acc6e32011-07-18 04:24:23 +00001242 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001243
John McCalld26bc762011-03-09 04:27:21 +00001244 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001245 src = Builder.CreateLoad(src);
1246 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001247
John McCalld26bc762011-03-09 04:27:21 +00001248 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001249 dst = Builder.CreateLoad(dst);
1250 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001251
John McCall6b5a61b2011-02-07 10:33:21 +00001252 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001253
John McCall6b5a61b2011-02-07 10:33:21 +00001254 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1255 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1256 const VarDecl *variable = ci->getVariable();
1257 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001258
John McCall6b5a61b2011-02-07 10:33:21 +00001259 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1260 if (capture.isConstant()) continue;
1261
1262 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001263 BlockFieldFlags flags;
1264
John McCall015f33b2012-10-17 02:28:37 +00001265 bool useARCWeakCopy = false;
1266 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001267
1268 if (copyExpr) {
1269 assert(!ci->isByRef());
1270 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001271
John McCall6b5a61b2011-02-07 10:33:21 +00001272 } else if (ci->isByRef()) {
1273 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001274 if (type.isObjCGCWeak())
1275 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001276
John McCallf85e1932011-06-15 23:02:42 +00001277 } else if (type->isObjCRetainableType()) {
1278 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001279 bool isBlockPointer = type->isBlockPointerType();
1280 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001281 flags = BLOCK_FIELD_IS_BLOCK;
1282
1283 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001284 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001285 Qualifiers qs = type.getQualifiers();
1286
John McCall015f33b2012-10-17 02:28:37 +00001287 // We need to register __weak direct captures with the runtime.
1288 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1289 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001290
John McCall015f33b2012-10-17 02:28:37 +00001291 // We need to retain the copied value for __strong direct captures.
1292 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1293 // If it's a block pointer, we have to copy the block and
1294 // assign that to the destination pointer, so we might as
1295 // well use _Block_object_assign. Otherwise we can avoid that.
1296 if (!isBlockPointer)
1297 useARCStrongCopy = true;
1298
1299 // Otherwise the memcpy is fine.
1300 } else {
1301 continue;
1302 }
1303
1304 // Non-ARC captures of retainable pointers are strong and
1305 // therefore require a call to _Block_object_assign.
1306 } else {
1307 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001308 }
1309 } else {
1310 continue;
1311 }
John McCall6b5a61b2011-02-07 10:33:21 +00001312
1313 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001314 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1315 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001316
1317 // If there's an explicit copy expression, we do that.
1318 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001319 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001320 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001321 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001322 } else {
1323 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001324 if (useARCStrongCopy) {
1325 // At -O0, store null into the destination field (so that the
1326 // storeStrong doesn't over-release) and then call storeStrong.
1327 // This is a workaround to not having an initStrong call.
1328 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1329 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1330 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1331 Builder.CreateStore(null, dstField);
1332 EmitARCStoreStrongCall(dstField, srcValue, true);
1333
1334 // With optimization enabled, take advantage of the fact that
1335 // the blocks runtime guarantees a memcpy of the block data, and
1336 // just emit a retain of the src field.
1337 } else {
1338 EmitARCRetainNonBlock(srcValue);
1339
1340 // We don't need this anymore, so kill it. It's not quite
1341 // worth the annoyance to avoid creating it in the first place.
1342 cast<llvm::Instruction>(dstField)->eraseFromParent();
1343 }
1344 } else {
1345 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1346 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1347 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1348 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
1349 }
Mike Stump08920992009-03-07 02:35:30 +00001350 }
1351 }
1352
John McCalld16c2cf2011-02-08 08:22:06 +00001353 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001354
John McCall5936e332011-02-15 09:22:45 +00001355 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001356}
1357
John McCall6b5a61b2011-02-07 10:33:21 +00001358llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001359CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001360 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001361
John McCall6b5a61b2011-02-07 10:33:21 +00001362 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001363 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1364 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Mike Stumpa4f668f2009-03-06 01:33:24 +00001366 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001367 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1368 FunctionType::ExtInfo(),
1369 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001370
Mike Stump3899a7f2009-06-05 23:26:36 +00001371 // FIXME: We'd like to put these into a mergable by content, with
1372 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001373 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001374
1375 llvm::Function *Fn =
1376 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001377 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001378
Devang Patel58dc5ca2011-05-02 20:37:08 +00001379 // Check if we should generate debug info for this block destroy function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001380 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001381
Mike Stumpa4f668f2009-03-06 01:33:24 +00001382 IdentifierInfo *II
1383 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1384
John McCall6b5a61b2011-02-07 10:33:21 +00001385 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001386 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001387 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001388 SC_Static,
1389 SC_None,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001390 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001391 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001392
Chris Lattner2acc6e32011-07-18 04:24:23 +00001393 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001394
John McCalld26bc762011-03-09 04:27:21 +00001395 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001396 src = Builder.CreateLoad(src);
1397 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001398
John McCall6b5a61b2011-02-07 10:33:21 +00001399 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1400
John McCalld16c2cf2011-02-08 08:22:06 +00001401 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001402
1403 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1404 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1405 const VarDecl *variable = ci->getVariable();
1406 QualType type = variable->getType();
1407
1408 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1409 if (capture.isConstant()) continue;
1410
John McCalld16c2cf2011-02-08 08:22:06 +00001411 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001412 const CXXDestructorDecl *dtor = 0;
1413
John McCall015f33b2012-10-17 02:28:37 +00001414 bool useARCWeakDestroy = false;
1415 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001416
John McCall6b5a61b2011-02-07 10:33:21 +00001417 if (ci->isByRef()) {
1418 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001419 if (type.isObjCGCWeak())
1420 flags |= BLOCK_FIELD_IS_WEAK;
1421 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1422 if (record->hasTrivialDestructor())
1423 continue;
1424 dtor = record->getDestructor();
1425 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001426 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001427 if (type->isBlockPointerType())
1428 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001429
John McCallf85e1932011-06-15 23:02:42 +00001430 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001431 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001432 Qualifiers qs = type.getQualifiers();
1433
1434 // Don't generate special dispose logic for a captured object
1435 // unless it's __strong or __weak.
1436 if (!qs.hasStrongOrWeakObjCLifetime())
1437 continue;
1438
1439 // Support __weak direct captures.
1440 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001441 useARCWeakDestroy = true;
1442
1443 // Tools really want us to use objc_storeStrong here.
1444 else
1445 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001446 }
1447 } else {
1448 continue;
1449 }
John McCall6b5a61b2011-02-07 10:33:21 +00001450
1451 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001452 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001453
1454 // If there's an explicit copy expression, we do that.
1455 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001456 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001457
John McCallf85e1932011-06-15 23:02:42 +00001458 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001459 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001460 EmitARCDestroyWeak(srcField);
1461
John McCall015f33b2012-10-17 02:28:37 +00001462 // Destroy strong objects with a call if requested.
1463 } else if (useARCStrongDestroy) {
1464 EmitARCDestroyStrong(srcField, /*precise*/ false);
1465
John McCall6b5a61b2011-02-07 10:33:21 +00001466 // Otherwise we call _Block_object_dispose. It wouldn't be too
1467 // hard to just emit this as a cleanup if we wanted to make sure
1468 // that things were done in reverse.
1469 } else {
1470 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001471 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001472 BuildBlockRelease(value, flags);
1473 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001474 }
1475
John McCall6b5a61b2011-02-07 10:33:21 +00001476 cleanups.ForceCleanup();
1477
John McCalld16c2cf2011-02-08 08:22:06 +00001478 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001479
John McCall5936e332011-02-15 09:22:45 +00001480 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001481}
1482
John McCallf0c11f72011-03-31 08:03:29 +00001483namespace {
1484
1485/// Emits the copy/dispose helper functions for a __block object of id type.
1486class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1487 BlockFieldFlags Flags;
1488
1489public:
1490 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1491 : ByrefHelpers(alignment), Flags(flags) {}
1492
John McCall36170192011-03-31 09:19:20 +00001493 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1494 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001495 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1496
1497 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1498 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1499
1500 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1501
1502 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1503 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1504 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1505 }
1506
1507 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1508 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1509 llvm::Value *value = CGF.Builder.CreateLoad(field);
1510
1511 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1512 }
1513
1514 void profileImpl(llvm::FoldingSetNodeID &id) const {
1515 id.AddInteger(Flags.getBitMask());
1516 }
1517};
1518
John McCallf85e1932011-06-15 23:02:42 +00001519/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1520class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1521public:
1522 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1523
1524 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1525 llvm::Value *srcField) {
1526 CGF.EmitARCMoveWeak(destField, srcField);
1527 }
1528
1529 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1530 CGF.EmitARCDestroyWeak(field);
1531 }
1532
1533 void profileImpl(llvm::FoldingSetNodeID &id) const {
1534 // 0 is distinguishable from all pointers and byref flags
1535 id.AddInteger(0);
1536 }
1537};
1538
1539/// Emits the copy/dispose helpers for an ARC __block __strong variable
1540/// that's not of block-pointer type.
1541class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1542public:
1543 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1544
1545 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1546 llvm::Value *srcField) {
1547 // Do a "move" by copying the value and then zeroing out the old
1548 // variable.
1549
John McCalla59e4b72011-11-09 03:17:26 +00001550 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1551 value->setAlignment(Alignment.getQuantity());
1552
John McCallf85e1932011-06-15 23:02:42 +00001553 llvm::Value *null =
1554 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001555
1556 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1557 store->setAlignment(Alignment.getQuantity());
1558
1559 store = CGF.Builder.CreateStore(null, srcField);
1560 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001561 }
1562
1563 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001564 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001565 }
1566
1567 void profileImpl(llvm::FoldingSetNodeID &id) const {
1568 // 1 is distinguishable from all pointers and byref flags
1569 id.AddInteger(1);
1570 }
1571};
1572
John McCalla59e4b72011-11-09 03:17:26 +00001573/// Emits the copy/dispose helpers for an ARC __block __strong
1574/// variable that's of block-pointer type.
1575class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1576public:
1577 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1578
1579 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1580 llvm::Value *srcField) {
1581 // Do the copy with objc_retainBlock; that's all that
1582 // _Block_object_assign would do anyway, and we'd have to pass the
1583 // right arguments to make sure it doesn't get no-op'ed.
1584 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1585 oldValue->setAlignment(Alignment.getQuantity());
1586
1587 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1588
1589 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1590 store->setAlignment(Alignment.getQuantity());
1591 }
1592
1593 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001594 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCalla59e4b72011-11-09 03:17:26 +00001595 }
1596
1597 void profileImpl(llvm::FoldingSetNodeID &id) const {
1598 // 2 is distinguishable from all pointers and byref flags
1599 id.AddInteger(2);
1600 }
1601};
1602
John McCallf0c11f72011-03-31 08:03:29 +00001603/// Emits the copy/dispose helpers for a __block variable with a
1604/// nontrivial copy constructor or destructor.
1605class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1606 QualType VarType;
1607 const Expr *CopyExpr;
1608
1609public:
1610 CXXByrefHelpers(CharUnits alignment, QualType type,
1611 const Expr *copyExpr)
1612 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1613
1614 bool needsCopy() const { return CopyExpr != 0; }
1615 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1616 llvm::Value *srcField) {
1617 if (!CopyExpr) return;
1618 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1619 }
1620
1621 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1622 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1623 CGF.PushDestructorCleanup(VarType, field);
1624 CGF.PopCleanupBlocks(cleanupDepth);
1625 }
1626
1627 void profileImpl(llvm::FoldingSetNodeID &id) const {
1628 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1629 }
1630};
1631} // end anonymous namespace
1632
1633static llvm::Constant *
1634generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001635 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001636 CodeGenModule::ByrefHelpers &byrefInfo) {
1637 ASTContext &Context = CGF.getContext();
1638
1639 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001640
John McCalld26bc762011-03-09 04:27:21 +00001641 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001642 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001643 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001644
John McCallf0c11f72011-03-31 08:03:29 +00001645 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001646 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Mike Stump45031c02009-03-06 02:29:21 +00001648 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001649 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1650 FunctionType::ExtInfo(),
1651 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001652
John McCallf0c11f72011-03-31 08:03:29 +00001653 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001654 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001655
Mike Stump3899a7f2009-06-05 23:26:36 +00001656 // FIXME: We'd like to put these into a mergable by content, with
1657 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001658 llvm::Function *Fn =
1659 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001660 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001661
1662 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001663 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001664
John McCallf0c11f72011-03-31 08:03:29 +00001665 FunctionDecl *FD = FunctionDecl::Create(Context,
1666 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001667 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001668 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001669 SC_Static,
1670 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001671 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001672
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001673 // Initialize debug info if necessary.
1674 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001675 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001676
John McCallf0c11f72011-03-31 08:03:29 +00001677 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001678 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001679
John McCallf0c11f72011-03-31 08:03:29 +00001680 // dst->x
1681 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1682 destField = CGF.Builder.CreateLoad(destField);
1683 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1684 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001685
John McCallf0c11f72011-03-31 08:03:29 +00001686 // src->x
1687 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1688 srcField = CGF.Builder.CreateLoad(srcField);
1689 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1690 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1691
1692 byrefInfo.emitCopy(CGF, destField, srcField);
1693 }
1694
1695 CGF.FinishFunction();
1696
1697 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001698}
1699
John McCallf0c11f72011-03-31 08:03:29 +00001700/// Build the copy helper for a __block variable.
1701static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001702 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001703 CodeGenModule::ByrefHelpers &info) {
1704 CodeGenFunction CGF(CGM);
1705 return generateByrefCopyHelper(CGF, byrefType, info);
1706}
1707
1708/// Generate code for a __block variable's dispose helper.
1709static llvm::Constant *
1710generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001711 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001712 CodeGenModule::ByrefHelpers &byrefInfo) {
1713 ASTContext &Context = CGF.getContext();
1714 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001715
John McCalld26bc762011-03-09 04:27:21 +00001716 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001717 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001718 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Mike Stump45031c02009-03-06 02:29:21 +00001720 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001721 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1722 FunctionType::ExtInfo(),
1723 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001724
John McCallf0c11f72011-03-31 08:03:29 +00001725 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001726 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001727
Mike Stump3899a7f2009-06-05 23:26:36 +00001728 // FIXME: We'd like to put these into a mergable by content, with
1729 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001730 llvm::Function *Fn =
1731 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001732 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001733 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001734
1735 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001736 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001737
John McCallf0c11f72011-03-31 08:03:29 +00001738 FunctionDecl *FD = FunctionDecl::Create(Context,
1739 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001740 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001741 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001742 SC_Static,
1743 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001744 false, false);
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001745 // Initialize debug info if necessary.
1746 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001747 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001748
John McCallf0c11f72011-03-31 08:03:29 +00001749 if (byrefInfo.needsDispose()) {
1750 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1751 V = CGF.Builder.CreateLoad(V);
1752 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1753 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001754
John McCallf0c11f72011-03-31 08:03:29 +00001755 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001756 }
Mike Stump45031c02009-03-06 02:29:21 +00001757
John McCallf0c11f72011-03-31 08:03:29 +00001758 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001759
John McCallf0c11f72011-03-31 08:03:29 +00001760 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001761}
1762
John McCallf0c11f72011-03-31 08:03:29 +00001763/// Build the dispose helper for a __block variable.
1764static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001765 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001766 CodeGenModule::ByrefHelpers &info) {
1767 CodeGenFunction CGF(CGM);
1768 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001769}
1770
John McCallf0c11f72011-03-31 08:03:29 +00001771///
1772template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001773 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001774 T &byrefInfo) {
1775 // Increase the field's alignment to be at least pointer alignment,
1776 // since the layout of the byref struct will guarantee at least that.
1777 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1778 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1779
1780 llvm::FoldingSetNodeID id;
1781 byrefInfo.Profile(id);
1782
1783 void *insertPos;
1784 CodeGenModule::ByrefHelpers *node
1785 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1786 if (node) return static_cast<T*>(node);
1787
1788 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1789 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1790
1791 T *copy = new (CGM.getContext()) T(byrefInfo);
1792 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1793 return copy;
1794}
1795
1796CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001797CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001798 const AutoVarEmission &emission) {
1799 const VarDecl &var = *emission.Variable;
1800 QualType type = var.getType();
1801
1802 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1803 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1804 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1805
1806 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1807 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1808 }
1809
John McCallf85e1932011-06-15 23:02:42 +00001810 // Otherwise, if we don't have a retainable type, there's nothing to do.
1811 // that the runtime does extra copies.
1812 if (!type->isObjCRetainableType()) return 0;
1813
1814 Qualifiers qs = type.getQualifiers();
1815
1816 // If we have lifetime, that dominates.
1817 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001818 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001819
1820 switch (lifetime) {
1821 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1822
1823 // These are just bits as far as the runtime is concerned.
1824 case Qualifiers::OCL_ExplicitNone:
1825 case Qualifiers::OCL_Autoreleasing:
1826 return 0;
1827
1828 // Tell the runtime that this is ARC __weak, called by the
1829 // byref routines.
1830 case Qualifiers::OCL_Weak: {
1831 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1832 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1833 }
1834
1835 // ARC __strong __block variables need to be retained.
1836 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001837 // Block pointers need to be copied, and there's no direct
1838 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001839 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001840 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001841 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1842
1843 // Otherwise, we transfer ownership of the retain from the stack
1844 // to the heap.
1845 } else {
1846 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1847 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1848 }
1849 }
1850 llvm_unreachable("fell out of lifetime switch!");
1851 }
1852
John McCallf0c11f72011-03-31 08:03:29 +00001853 BlockFieldFlags flags;
1854 if (type->isBlockPointerType()) {
1855 flags |= BLOCK_FIELD_IS_BLOCK;
1856 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1857 type->isObjCObjectPointerType()) {
1858 flags |= BLOCK_FIELD_IS_OBJECT;
1859 } else {
1860 return 0;
1861 }
1862
1863 if (type.isObjCGCWeak())
1864 flags |= BLOCK_FIELD_IS_WEAK;
1865
1866 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1867 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001868}
1869
John McCall5af02db2011-03-31 01:59:53 +00001870unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1871 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1872
1873 return ByRefValueInfo.find(VD)->second.second;
1874}
1875
1876llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1877 const VarDecl *V) {
1878 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1879 Loc = Builder.CreateLoad(Loc);
1880 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1881 V->getNameAsString());
1882 return Loc;
1883}
1884
1885/// BuildByRefType - This routine changes a __block variable declared as T x
1886/// into:
1887///
1888/// struct {
1889/// void *__isa;
1890/// void *__forwarding;
1891/// int32_t __flags;
1892/// int32_t __size;
1893/// void *__copy_helper; // only if needed
1894/// void *__destroy_helper; // only if needed
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001895/// void *__byref_variable_layout;// only if needed
John McCall5af02db2011-03-31 01:59:53 +00001896/// char padding[X]; // only if needed
1897/// T x;
1898/// } x
1899///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001900llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1901 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001902 if (Info.first)
1903 return Info.first;
1904
1905 QualType Ty = D->getType();
1906
Chris Lattner5f9e2722011-07-23 10:55:15 +00001907 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001908
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001909 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001910 llvm::StructType::create(getLLVMContext(),
1911 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001912
1913 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001914 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001915
1916 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001917 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001918
1919 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001920 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001921
1922 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001923 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001924
David Chisnall9595dae2012-04-04 13:07:13 +00001925 bool HasCopyAndDispose =
1926 (Ty->isObjCRetainableType()) || getContext().getBlockVarCopyInits(D);
John McCall5af02db2011-03-31 01:59:53 +00001927 if (HasCopyAndDispose) {
1928 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001929 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001930
1931 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001932 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001933 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001934 bool HasByrefExtendedLayout = false;
1935 Qualifiers::ObjCLifetime Lifetime;
1936 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
1937 HasByrefExtendedLayout)
1938 /// void *__byref_variable_layout;
1939 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001940
1941 bool Packed = false;
1942 CharUnits Align = getContext().getDeclAlign(D);
1943 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1944 // We have to insert padding.
1945
1946 // The struct above has 2 32-bit integers.
1947 unsigned CurrentOffsetInBytes = 4 * 2;
1948
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001949 // And either 2, 3, 4 or 5 pointers.
1950 unsigned noPointers = 2;
1951 if (HasCopyAndDispose)
1952 noPointers += 2;
1953 if (HasByrefExtendedLayout)
1954 noPointers += 1;
1955
1956 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001957
1958 // Align the offset.
1959 unsigned AlignedOffsetInBytes =
1960 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1961
1962 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1963 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00001964 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00001965 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001966 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001967 if (NumPaddingBytes > 1)
1968 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1969
John McCall0774cb82011-05-15 01:53:33 +00001970 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001971
1972 // We want a packed struct.
1973 Packed = true;
1974 }
1975 }
1976
1977 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001978 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001979
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001980 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001981
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001982 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001983
John McCall0774cb82011-05-15 01:53:33 +00001984 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001985
1986 return Info.first;
1987}
1988
1989/// Initialize the structural components of a __block variable, i.e.
1990/// everything but the actual object.
1991void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001992 // Find the address of the local.
1993 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001994
John McCallf0c11f72011-03-31 08:03:29 +00001995 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001996 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001997 cast<llvm::PointerType>(addr->getType())->getElementType());
1998
1999 // Build the byref helpers if necessary. This is null if we don't need any.
2000 CodeGenModule::ByrefHelpers *helpers =
2001 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00002002
2003 const VarDecl &D = *emission.Variable;
2004 QualType type = D.getType();
2005
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002006 bool HasByrefExtendedLayout;
2007 Qualifiers::ObjCLifetime ByrefLifetime;
2008 bool ByRefHasLifetime =
2009 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2010
John McCallf0c11f72011-03-31 08:03:29 +00002011 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00002012
2013 // Initialize the 'isa', which is just 0 or 1.
2014 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00002015 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00002016 isa = 1;
2017 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2018 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2019
2020 // Store the address of the variable into its own forwarding pointer.
2021 Builder.CreateStore(addr,
2022 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2023
2024 // Blocks ABI:
2025 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002026 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall5af02db2011-03-31 01:59:53 +00002027 BlockFlags flags;
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002028 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2029 if (ByRefHasLifetime) {
2030 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2031 else switch (ByrefLifetime) {
2032 case Qualifiers::OCL_Strong:
2033 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2034 break;
2035 case Qualifiers::OCL_Weak:
2036 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2037 break;
2038 case Qualifiers::OCL_ExplicitNone:
2039 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2040 break;
2041 case Qualifiers::OCL_None:
2042 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2043 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2044 break;
2045 default:
2046 break;
2047 }
2048 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2049 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2050 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2051 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2052 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2053 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2054 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2055 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2056 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2057 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2058 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2059 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2060 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2061 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2062 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2063 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2064 }
2065 printf("\n");
2066 }
2067 }
2068
John McCall5af02db2011-03-31 01:59:53 +00002069 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2070 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2071
John McCallf0c11f72011-03-31 08:03:29 +00002072 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2073 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00002074 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2075
John McCallf0c11f72011-03-31 08:03:29 +00002076 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00002077 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00002078 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002079
2080 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002081 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002082 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002083 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2084 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2085 llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2086 "byref.layout");
2087 // cast destination to pointer to source type.
2088 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2089 DesTy = DesTy->getPointerTo();
2090 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2091 Builder.CreateStore(ByrefLayoutInfo, BC);
2092 }
John McCall5af02db2011-03-31 01:59:53 +00002093}
2094
John McCalld16c2cf2011-02-08 08:22:06 +00002095void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002096 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00002097 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00002098 V = Builder.CreateBitCast(V, Int8PtrTy);
2099 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00002100 Builder.CreateCall2(F, V, N);
2101}
John McCall5af02db2011-03-31 01:59:53 +00002102
2103namespace {
2104 struct CallBlockRelease : EHScopeStack::Cleanup {
2105 llvm::Value *Addr;
2106 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2107
John McCallad346f42011-07-12 20:27:29 +00002108 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002109 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002110 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2111 }
2112 };
2113}
2114
2115/// Enter a cleanup to destroy a __block variable. Note that this
2116/// cleanup should be a no-op if the variable hasn't left the stack
2117/// yet; if a cleanup is required for the variable itself, that needs
2118/// to be done externally.
2119void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2120 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002121 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002122 return;
2123
2124 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2125}
John McCall13db5cf2011-09-09 20:41:01 +00002126
2127/// Adjust the declaration of something from the blocks API.
2128static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2129 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002130 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002131
2132 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2133 if (GV->isDeclaration() &&
2134 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2135 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2136}
2137
2138llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2139 if (BlockObjectDispose)
2140 return BlockObjectDispose;
2141
2142 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2143 llvm::FunctionType *fty
2144 = llvm::FunctionType::get(VoidTy, args, false);
2145 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2146 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2147 return BlockObjectDispose;
2148}
2149
2150llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2151 if (BlockObjectAssign)
2152 return BlockObjectAssign;
2153
2154 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2155 llvm::FunctionType *fty
2156 = llvm::FunctionType::get(VoidTy, args, false);
2157 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2158 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2159 return BlockObjectAssign;
2160}
2161
2162llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2163 if (NSConcreteGlobalBlock)
2164 return NSConcreteGlobalBlock;
2165
2166 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2167 Int8PtrTy->getPointerTo(), 0);
2168 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2169 return NSConcreteGlobalBlock;
2170}
2171
2172llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2173 if (NSConcreteStackBlock)
2174 return NSConcreteStackBlock;
2175
2176 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2177 Int8PtrTy->getPointerTo(), 0);
2178 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2179 return NSConcreteStackBlock;
2180}