blob: 7b8e839efa5628ea34e08b6fd7ec08ddb1845730 [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
John McCalld16c2cf2011-02-08 08:22:06 +000014#include "CGBlocks.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000020#include "llvm/ADT/SmallSet.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070021#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Module.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000024#include <algorithm>
Fariborz Jahanian7d4b9fa2012-11-14 17:43:08 +000025#include <cstdio>
Torok Edwinf42e4a62009-08-24 13:25:12 +000026
Anders Carlssonacfde802009-02-12 00:39:25 +000027using namespace clang;
28using namespace CodeGen;
29
John McCall1a343eb2011-11-10 08:15:53 +000030CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
31 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanianf22ae652012-11-01 18:32:55 +000032 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070033 StructureType(nullptr), Block(block),
34 DominatingIP(nullptr) {
35
John McCall1a343eb2011-11-10 08:15:53 +000036 // Skip asm prefix, if any. 'name' is usually taken directly from
37 // the mangled name of the enclosing function.
38 if (!name.empty() && name[0] == '\01')
39 name = name.substr(1);
John McCallee504292010-05-21 04:11:14 +000040}
41
John McCallf0c11f72011-03-31 08:03:29 +000042// Anchor the vtable to this translation unit.
43CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
44
John McCall6b5a61b2011-02-07 10:33:21 +000045/// Build the given block as a global block.
46static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
47 const CGBlockInfo &blockInfo,
48 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000049
John McCall6b5a61b2011-02-07 10:33:21 +000050/// Build the helper function to copy a block.
51static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
52 const CGBlockInfo &blockInfo) {
53 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
54}
55
Stephen Hines651f13c2014-04-23 16:59:28 -070056/// Build the helper function to dispose of a block.
John McCall6b5a61b2011-02-07 10:33:21 +000057static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
60}
61
Fariborz Jahanianaf879c02012-10-25 18:06:53 +000062/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
63/// buildBlockDescriptor is accessed from 5th field of the Block_literal
64/// meta-data and contains stationary information about the block literal.
65/// Its definition will have 4 (or optinally 6) words.
Dmitri Gribenko41487f32013-05-08 23:09:44 +000066/// \code
Fariborz Jahanianaf879c02012-10-25 18:06:53 +000067/// struct Block_descriptor {
68/// unsigned long reserved;
69/// unsigned long size; // size of Block_literal metadata in bytes.
70/// void *copy_func_helper_decl; // optional copy helper.
71/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko41487f32013-05-08 23:09:44 +000072/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianaf879c02012-10-25 18:06:53 +000073/// void *block_layout_info; // encoding of captured block variables.
74/// };
Dmitri Gribenko41487f32013-05-08 23:09:44 +000075/// \endcode
John McCall6b5a61b2011-02-07 10:33:21 +000076static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
77 const CGBlockInfo &blockInfo) {
78 ASTContext &C = CGM.getContext();
79
Chris Lattner2acc6e32011-07-18 04:24:23 +000080 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
Stephen Hines176edba2014-12-01 14:53:08 -080081 llvm::Type *i8p = NULL;
82 if (CGM.getLangOpts().OpenCL)
83 i8p =
84 llvm::Type::getInt8PtrTy(
85 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
86 else
87 i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000088
Chris Lattner5f9e2722011-07-23 10:55:15 +000089 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000090
91 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000092 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000093
94 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000095 // FIXME: What is the right way to say this doesn't fit? We should give
96 // a user diagnostic in that case. Better fix would be to change the
97 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000098 elements.push_back(llvm::ConstantInt::get(ulong,
99 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +0000100
John McCall6b5a61b2011-02-07 10:33:21 +0000101 // Optional copy/dispose helpers.
102 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +0000103 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +0000104 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +0000105
106 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +0000107 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +0000108 }
109
John McCall6b5a61b2011-02-07 10:33:21 +0000110 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
111 std::string typeAtEncoding =
112 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
113 elements.push_back(llvm::ConstantExpr::getBitCast(
114 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000115
John McCall6b5a61b2011-02-07 10:33:21 +0000116 // GC layout.
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000117 if (C.getLangOpts().ObjC1) {
118 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
119 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
120 else
121 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
122 }
John McCall6b5a61b2011-02-07 10:33:21 +0000123 else
124 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000125
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000126 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000127
John McCall6b5a61b2011-02-07 10:33:21 +0000128 llvm::GlobalVariable *global =
129 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
130 llvm::GlobalValue::InternalLinkage,
131 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000132
John McCall6b5a61b2011-02-07 10:33:21 +0000133 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000134}
135
John McCall6b5a61b2011-02-07 10:33:21 +0000136/*
137 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000138
John McCall6b5a61b2011-02-07 10:33:21 +0000139 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
140 struct Block_literal {
141 /// Initialized to one of:
142 /// extern void *_NSConcreteStackBlock[];
143 /// extern void *_NSConcreteGlobalBlock[];
144 ///
145 /// In theory, we could start one off malloc'ed by setting
146 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
147 /// this isa:
148 /// extern void *_NSConcreteMallocBlock[];
149 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000150
John McCall6b5a61b2011-02-07 10:33:21 +0000151 /// These are the flags (with corresponding bit number) that the
152 /// compiler is actually supposed to know about.
153 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
154 /// descriptor provides copy and dispose helper functions
155 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
156 /// object with a nontrivial destructor or copy constructor
157 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
158 /// as global memory
159 /// 29. BLOCK_USE_STRET - indicates that the block function
160 /// uses stret, which objc_msgSend needs to know about
161 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
162 /// @encoded signature string
163 /// And we're not supposed to manipulate these:
164 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
165 /// to malloc'ed memory
166 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
167 /// to GC-allocated memory
168 /// Additionally, the bottom 16 bits are a reference count which
169 /// should be zero on the stack.
170 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000171
John McCall6b5a61b2011-02-07 10:33:21 +0000172 /// Reserved; should be zero-initialized.
173 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000174
John McCall6b5a61b2011-02-07 10:33:21 +0000175 /// Function pointer generated from block literal.
176 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000177
John McCall6b5a61b2011-02-07 10:33:21 +0000178 /// Block description metadata generated from block literal.
179 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000180
John McCall6b5a61b2011-02-07 10:33:21 +0000181 /// Captured values follow.
182 _CapturesTypes captures...;
183 };
184 */
David Chisnall5e530af2009-11-17 19:33:30 +0000185
John McCall6b5a61b2011-02-07 10:33:21 +0000186/// The number of fields in a block header.
187const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000188
John McCall6b5a61b2011-02-07 10:33:21 +0000189namespace {
190 /// A chunk of data that we actually have to capture in the block.
191 struct BlockLayoutChunk {
192 CharUnits Alignment;
193 CharUnits Size;
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000194 Qualifiers::ObjCLifetime Lifetime;
John McCall6b5a61b2011-02-07 10:33:21 +0000195 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000196 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000197
John McCall6b5a61b2011-02-07 10:33:21 +0000198 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000199 Qualifiers::ObjCLifetime lifetime,
John McCall6b5a61b2011-02-07 10:33:21 +0000200 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000201 llvm::Type *type)
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000202 : Alignment(align), Size(size), Lifetime(lifetime),
203 Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000204
John McCall6b5a61b2011-02-07 10:33:21 +0000205 /// Tell the block info that this chunk has the given field index.
206 void setIndex(CGBlockInfo &info, unsigned index) {
207 if (!Capture)
208 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000209 else
John McCall6b5a61b2011-02-07 10:33:21 +0000210 info.Captures[Capture->getVariable()]
211 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000212 }
John McCall6b5a61b2011-02-07 10:33:21 +0000213 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000214
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000215 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
216 /// all __weak together. Preserve descending alignment in all situations.
John McCall6b5a61b2011-02-07 10:33:21 +0000217 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000218 CharUnits LeftValue, RightValue;
219 bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
220 bool RightByref = right.Capture ? right.Capture->isByRef() : false;
221
222 if (left.Lifetime == Qualifiers::OCL_Strong &&
223 left.Alignment >= right.Alignment)
224 LeftValue = CharUnits::fromQuantity(64);
225 else if (LeftByref && left.Alignment >= right.Alignment)
226 LeftValue = CharUnits::fromQuantity(32);
227 else if (left.Lifetime == Qualifiers::OCL_Weak &&
228 left.Alignment >= right.Alignment)
229 LeftValue = CharUnits::fromQuantity(16);
230 else
231 LeftValue = left.Alignment;
232 if (right.Lifetime == Qualifiers::OCL_Strong &&
233 right.Alignment >= left.Alignment)
234 RightValue = CharUnits::fromQuantity(64);
235 else if (RightByref && right.Alignment >= left.Alignment)
236 RightValue = CharUnits::fromQuantity(32);
237 else if (right.Lifetime == Qualifiers::OCL_Weak &&
238 right.Alignment >= left.Alignment)
239 RightValue = CharUnits::fromQuantity(16);
240 else
241 RightValue = right.Alignment;
242
243 return LeftValue > RightValue;
John McCall6b5a61b2011-02-07 10:33:21 +0000244 }
245}
246
John McCall461c9c12011-02-08 03:07:00 +0000247/// Determines if the given type is safe for constant capture in C++.
248static bool isSafeForCXXConstantCapture(QualType type) {
249 const RecordType *recordType =
250 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
251
252 // Only records can be unsafe.
253 if (!recordType) return true;
254
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700255 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCall461c9c12011-02-08 03:07:00 +0000256
257 // Maintain semantics for classes with non-trivial dtors or copy ctors.
258 if (!record->hasTrivialDestructor()) return false;
Richard Smith426391c2012-11-16 00:53:38 +0000259 if (record->hasNonTrivialCopyConstructor()) return false;
John McCall461c9c12011-02-08 03:07:00 +0000260
261 // Otherwise, we just have to make sure there aren't any mutable
262 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000263 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000264}
265
John McCall6b5a61b2011-02-07 10:33:21 +0000266/// It is illegal to modify a const object after initialization.
267/// Therefore, if a const object has a constant initializer, we don't
268/// actually need to keep storage for it in the block; we'll just
269/// rematerialize it at the start of the block function. This is
270/// acceptable because we make no promises about address stability of
271/// captured variables.
272static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000273 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000274 const VarDecl *var) {
275 QualType type = var->getType();
276
277 // We can only do this if the variable is const.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700278 if (!type.isConstQualified()) return nullptr;
John McCall6b5a61b2011-02-07 10:33:21 +0000279
John McCall461c9c12011-02-08 03:07:00 +0000280 // Furthermore, in C++ we have to worry about mutable fields:
281 // C++ [dcl.type.cv]p4:
282 // Except that any class member declared mutable can be
283 // modified, any attempt to modify a const object during its
284 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000285 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700286 return nullptr;
John McCall6b5a61b2011-02-07 10:33:21 +0000287
288 // If the variable doesn't have any initializer (shouldn't this be
289 // invalid?), it's not clear what we should do. Maybe capture as
290 // zero?
291 const Expr *init = var->getInit();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700292 if (!init) return nullptr;
John McCall6b5a61b2011-02-07 10:33:21 +0000293
Richard Smith2d6a5672012-01-14 04:30:29 +0000294 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000295}
296
297/// Get the low bit of a nonzero character count. This is the
298/// alignment of the nth byte if the 0th byte is universally aligned.
299static CharUnits getLowBit(CharUnits v) {
300 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
301}
302
303static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000304 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000305 ASTContext &C = CGM.getContext();
306
307 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
308 CharUnits ptrSize, ptrAlign, intSize, intAlign;
Stephen Hines651f13c2014-04-23 16:59:28 -0700309 std::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
310 std::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000311
312 // Are there crazy embedded platforms where this isn't true?
313 assert(intSize <= ptrSize && "layout assumptions horribly violated");
314
315 CharUnits headerSize = ptrSize;
316 if (2 * intSize < ptrAlign) headerSize += ptrSize;
317 else headerSize += 2 * intSize;
318 headerSize += 2 * ptrSize;
319
320 info.BlockAlign = ptrAlign;
321 info.BlockSize = headerSize;
322
323 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000324 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
325 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000326 elementTypes.push_back(i8p);
327 elementTypes.push_back(intTy);
328 elementTypes.push_back(intTy);
329 elementTypes.push_back(i8p);
330 elementTypes.push_back(CGM.getBlockDescriptorType());
331
332 assert(elementTypes.size() == BlockHeaderSize);
333}
334
335/// Compute the layout of the given block. Attempts to lay the block
336/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000337static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
338 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000339 ASTContext &C = CGM.getContext();
340 const BlockDecl *block = info.getBlockDecl();
341
Chris Lattner5f9e2722011-07-23 10:55:15 +0000342 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000343 initializeForBlockHeader(CGM, info, elementTypes);
344
345 if (!block->hasCaptures()) {
346 info.StructureType =
347 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
348 info.CanBeGlobal = true;
349 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000350 }
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000351 else if (C.getLangOpts().ObjC1 &&
352 CGM.getLangOpts().getGC() == LangOptions::NonGC)
353 info.HasCapturedVariableLayout = true;
354
John McCall6b5a61b2011-02-07 10:33:21 +0000355 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000356 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000357 layout.reserve(block->capturesCXXThis() +
358 (block->capture_end() - block->capture_begin()));
359
360 CharUnits maxFieldAlign;
361
362 // First, 'this'.
363 if (block->capturesCXXThis()) {
Eli Friedmanc1b8d092013-07-12 22:05:26 +0000364 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
365 "Can't capture 'this' outside a method");
366 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000367
Jay Foadef6de3d2011-07-11 09:56:20 +0000368 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000369 std::pair<CharUnits,CharUnits> tinfo
370 = CGM.getContext().getTypeInfoInChars(thisType);
371 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
372
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000373 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
374 Qualifiers::OCL_None,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700375 nullptr, llvmType));
John McCall6b5a61b2011-02-07 10:33:21 +0000376 }
377
378 // Next, all the block captures.
Stephen Hines651f13c2014-04-23 16:59:28 -0700379 for (const auto &CI : block->captures()) {
380 const VarDecl *variable = CI.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +0000381
Stephen Hines651f13c2014-04-23 16:59:28 -0700382 if (CI.isByRef()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000383 // We have to copy/dispose of the __block reference.
384 info.NeedsCopyDispose = true;
385
John McCall6b5a61b2011-02-07 10:33:21 +0000386 // Just use void* instead of a pointer to the byref type.
387 QualType byRefPtrTy = C.VoidPtrTy;
388
Jay Foadef6de3d2011-07-11 09:56:20 +0000389 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000390 std::pair<CharUnits,CharUnits> tinfo
391 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
392 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
393
394 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
Stephen Hines651f13c2014-04-23 16:59:28 -0700395 Qualifiers::OCL_None, &CI, llvmType));
John McCall6b5a61b2011-02-07 10:33:21 +0000396 continue;
397 }
398
399 // Otherwise, build a layout chunk with the size and alignment of
400 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000401 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000402 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
403 continue;
404 }
405
John McCallf85e1932011-06-15 23:02:42 +0000406 // If we have a lifetime qualifier, honor it for capture purposes.
407 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000408 Qualifiers::ObjCLifetime lifetime =
409 variable->getType().getObjCLifetime();
410 if (lifetime) {
John McCallf85e1932011-06-15 23:02:42 +0000411 switch (lifetime) {
412 case Qualifiers::OCL_None: llvm_unreachable("impossible");
413 case Qualifiers::OCL_ExplicitNone:
414 case Qualifiers::OCL_Autoreleasing:
415 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000416
John McCallf85e1932011-06-15 23:02:42 +0000417 case Qualifiers::OCL_Strong:
418 case Qualifiers::OCL_Weak:
419 info.NeedsCopyDispose = true;
420 }
421
422 // Block pointers require copy/dispose. So do Objective-C pointers.
423 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000424 info.NeedsCopyDispose = true;
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000425 // used for mrr below.
426 lifetime = Qualifiers::OCL_Strong;
John McCall6b5a61b2011-02-07 10:33:21 +0000427
428 // So do types that require non-trivial copy construction.
Stephen Hines651f13c2014-04-23 16:59:28 -0700429 } else if (CI.hasCopyExpr()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000430 info.NeedsCopyDispose = true;
431 info.HasCXXObject = true;
432
433 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000434 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000435 if (const CXXRecordDecl *record =
436 variable->getType()->getAsCXXRecordDecl()) {
437 if (!record->hasTrivialDestructor()) {
438 info.HasCXXObject = true;
439 info.NeedsCopyDispose = true;
440 }
441 }
442 }
443
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000444 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000445 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000446 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000447
John McCall6b5a61b2011-02-07 10:33:21 +0000448 maxFieldAlign = std::max(maxFieldAlign, align);
449
Jay Foadef6de3d2011-07-11 09:56:20 +0000450 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000451 CGM.getTypes().ConvertTypeForMem(VT);
452
Stephen Hines651f13c2014-04-23 16:59:28 -0700453 layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
John McCall6b5a61b2011-02-07 10:33:21 +0000454 }
455
456 // If that was everything, we're done here.
457 if (layout.empty()) {
458 info.StructureType =
459 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
460 info.CanBeGlobal = true;
461 return;
462 }
463
464 // Sort the layout by alignment. We have to use a stable sort here
465 // to get reproducible results. There should probably be an
466 // llvm::array_pod_stable_sort.
467 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000468
469 // Needed for blocks layout info.
470 info.BlockHeaderForcedGapOffset = info.BlockSize;
471 info.BlockHeaderForcedGapSize = CharUnits::Zero();
472
John McCall6b5a61b2011-02-07 10:33:21 +0000473 CharUnits &blockSize = info.BlockSize;
474 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
475
476 // Assuming that the first byte in the header is maximally aligned,
477 // get the alignment of the first byte following the header.
478 CharUnits endAlign = getLowBit(blockSize);
479
480 // If the end of the header isn't satisfactorily aligned for the
481 // maximum thing, look for things that are okay with the header-end
482 // alignment, and keep appending them until we get something that's
483 // aligned right. This algorithm is only guaranteed optimal if
484 // that condition is satisfied at some point; otherwise we can get
485 // things like:
486 // header // next byte has alignment 4
487 // something_with_size_5; // next byte has alignment 1
488 // something_with_alignment_8;
489 // which has 7 bytes of padding, as opposed to the naive solution
490 // which might have less (?).
491 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000492 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000493 li = layout.begin() + 1, le = layout.end();
494
495 // Look for something that the header end is already
496 // satisfactorily aligned for.
497 for (; li != le && endAlign < li->Alignment; ++li)
498 ;
499
500 // If we found something that's naturally aligned for the end of
501 // the header, keep adding things...
502 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000503 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000504 for (; li != le; ++li) {
505 assert(endAlign >= li->Alignment);
506
507 li->setIndex(info, elementTypes.size());
508 elementTypes.push_back(li->Type);
509 blockSize += li->Size;
510 endAlign = getLowBit(blockSize);
511
512 // ...until we get to the alignment of the maximum field.
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000513 if (endAlign >= maxFieldAlign) {
514 if (li == first) {
515 // No user field was appended. So, a gap was added.
516 // Save total gap size for use in block layout bit map.
517 info.BlockHeaderForcedGapSize = li->Size;
518 }
John McCall6b5a61b2011-02-07 10:33:21 +0000519 break;
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000520 }
John McCall6b5a61b2011-02-07 10:33:21 +0000521 }
John McCall6b5a61b2011-02-07 10:33:21 +0000522 // Don't re-append everything we just appended.
523 layout.erase(first, li);
524 }
525 }
526
John McCall6ea48412012-04-26 21:14:42 +0000527 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000528
John McCall6b5a61b2011-02-07 10:33:21 +0000529 // At this point, we just have to add padding if the end align still
530 // isn't aligned right.
531 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000532 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
533 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000534
John McCall5936e332011-02-15 09:22:45 +0000535 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
536 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000537 blockSize = newBlockSize;
John McCall6c803f72012-05-01 20:28:00 +0000538 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall6b5a61b2011-02-07 10:33:21 +0000539 }
540
John McCall6c803f72012-05-01 20:28:00 +0000541 assert(endAlign >= maxFieldAlign);
John McCall6ea48412012-04-26 21:14:42 +0000542 assert(endAlign == getLowBit(blockSize));
John McCall6b5a61b2011-02-07 10:33:21 +0000543 // Slam everything else on now. This works because they have
544 // strictly decreasing alignment and we expect that size is always a
545 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000546 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000547 li = layout.begin(), le = layout.end(); li != le; ++li) {
Stephen Hines176edba2014-12-01 14:53:08 -0800548 if (endAlign < li->Alignment) {
549 // size may not be multiple of alignment. This can only happen with
550 // an over-aligned variable. We will be adding a padding field to
551 // make the size be multiple of alignment.
552 CharUnits padding = li->Alignment - endAlign;
553 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
554 padding.getQuantity()));
555 blockSize += padding;
556 endAlign = getLowBit(blockSize);
557 }
John McCall6b5a61b2011-02-07 10:33:21 +0000558 assert(endAlign >= li->Alignment);
559 li->setIndex(info, elementTypes.size());
560 elementTypes.push_back(li->Type);
561 blockSize += li->Size;
562 endAlign = getLowBit(blockSize);
563 }
564
565 info.StructureType =
566 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
567}
568
John McCall1a343eb2011-11-10 08:15:53 +0000569/// Enter the scope of a block. This should be run at the entrance to
570/// a full-expression so that the block's cleanups are pushed at the
571/// right place in the stack.
572static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000573 assert(CGF.HaveInsertPoint());
574
John McCall1a343eb2011-11-10 08:15:53 +0000575 // Allocate the block info and place it at the head of the list.
576 CGBlockInfo &blockInfo =
577 *new CGBlockInfo(block, CGF.CurFn->getName());
578 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
579 CGF.FirstBlockInfo = &blockInfo;
580
581 // Compute information about the layout, etc., of this block,
582 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000583 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000584
585 // Nothing else to do if it can be global.
586 if (blockInfo.CanBeGlobal) return;
587
588 // Make the allocation for the block.
589 blockInfo.Address =
590 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
591 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
592
593 // If there are cleanups to emit, enter them (but inactive).
594 if (!blockInfo.NeedsCopyDispose) return;
595
596 // Walk through the captures (in order) and find the ones not
597 // captured by constant.
Stephen Hines651f13c2014-04-23 16:59:28 -0700598 for (const auto &CI : block->captures()) {
John McCall1a343eb2011-11-10 08:15:53 +0000599 // Ignore __block captures; there's nothing special in the
600 // on-stack block that we need to do for them.
Stephen Hines651f13c2014-04-23 16:59:28 -0700601 if (CI.isByRef()) continue;
John McCall1a343eb2011-11-10 08:15:53 +0000602
603 // Ignore variables that are constant-captured.
Stephen Hines651f13c2014-04-23 16:59:28 -0700604 const VarDecl *variable = CI.getVariable();
John McCall1a343eb2011-11-10 08:15:53 +0000605 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
606 if (capture.isConstant()) continue;
607
608 // Ignore objects that aren't destructed.
609 QualType::DestructionKind dtorKind =
610 variable->getType().isDestructedType();
611 if (dtorKind == QualType::DK_none) continue;
612
613 CodeGenFunction::Destroyer *destroyer;
614
615 // Block captures count as local values and have imprecise semantics.
616 // They also can't be arrays, so need to worry about that.
617 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000618 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000619 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000620 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000621 }
622
623 // GEP down to the address.
624 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
625 capture.getIndex());
626
John McCall6f103ba2011-11-10 10:43:54 +0000627 // We can use that GEP as the dominating IP.
628 if (!blockInfo.DominatingIP)
629 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
630
John McCall1a343eb2011-11-10 08:15:53 +0000631 CleanupKind cleanupKind = InactiveNormalCleanup;
632 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
633 if (useArrayEHCleanup)
634 cleanupKind = InactiveNormalAndEHCleanup;
635
636 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000637 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000638
639 // Remember where that cleanup was.
640 capture.setCleanup(CGF.EHStack.stable_begin());
641 }
642}
643
644/// Enter a full-expression with a non-trivial number of objects to
645/// clean up. This is in this file because, at the moment, the only
646/// kind of cleanup object is a BlockDecl*.
647void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
648 assert(E->getNumObjects() != 0);
649 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
650 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
651 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
652 enterBlockScope(*this, *i);
653 }
654}
655
656/// Find the layout for the given block in a linked list and remove it.
657static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
658 const BlockDecl *block) {
659 while (true) {
660 assert(head && *head);
661 CGBlockInfo *cur = *head;
662
663 // If this is the block we're looking for, splice it out of the list.
664 if (cur->getBlockDecl() == block) {
665 *head = cur->NextBlockInfo;
666 return cur;
667 }
668
669 head = &cur->NextBlockInfo;
670 }
671}
672
673/// Destroy a chain of block layouts.
674void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
675 assert(head && "destroying an empty chain");
676 do {
677 CGBlockInfo *cur = head;
678 head = cur->NextBlockInfo;
679 delete cur;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700680 } while (head != nullptr);
John McCall1a343eb2011-11-10 08:15:53 +0000681}
682
John McCall6b5a61b2011-02-07 10:33:21 +0000683/// Emit a block literal expression in the current function.
684llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000685 // If the block has no captures, we won't have a pre-computed
686 // layout for it.
687 if (!blockExpr->getBlockDecl()->hasCaptures()) {
688 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000689 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000690 blockInfo.BlockExpression = blockExpr;
691 return EmitBlockLiteral(blockInfo);
692 }
John McCall6b5a61b2011-02-07 10:33:21 +0000693
John McCall1a343eb2011-11-10 08:15:53 +0000694 // Find the block info for this block and take ownership of it.
Stephen Hines651f13c2014-04-23 16:59:28 -0700695 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000696 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
697 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000698
John McCall1a343eb2011-11-10 08:15:53 +0000699 blockInfo->BlockExpression = blockExpr;
700 return EmitBlockLiteral(*blockInfo);
701}
702
703llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
704 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000705 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000706 llvm::Constant *blockFn
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000707 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCallf5ebf9b2013-05-03 07:33:41 +0000708 LocalDeclMap,
709 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000710 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000711
712 // If there is nothing to capture, we can emit this as a global block.
713 if (blockInfo.CanBeGlobal)
714 return buildGlobalBlock(CGM, blockInfo, blockFn);
715
716 // Otherwise, we have to emit this as a local block.
717
718 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000719 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000720
721 // Build the block descriptor.
722 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
723
John McCall1a343eb2011-11-10 08:15:53 +0000724 llvm::AllocaInst *blockAddr = blockInfo.Address;
725 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000726
727 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000728 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000729 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall6b5a61b2011-02-07 10:33:21 +0000730 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
731 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000732 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000733
734 // Initialize the block literal.
735 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000736 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000737 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000738 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000739 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
740 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
741 "block.invoke"));
742 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
743 "block.descriptor"));
744
745 // Finally, capture all the values into the block.
746 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
747
748 // First, 'this'.
749 if (blockDecl->capturesCXXThis()) {
750 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
751 blockInfo.CXXThisIndex,
752 "block.captured-this.addr");
753 Builder.CreateStore(LoadCXXThis(), addr);
754 }
755
756 // Next, captured variables.
Stephen Hines651f13c2014-04-23 16:59:28 -0700757 for (const auto &CI : blockDecl->captures()) {
758 const VarDecl *variable = CI.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +0000759 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
760
761 // Ignore constant captures.
762 if (capture.isConstant()) continue;
763
764 QualType type = variable->getType();
John McCall4b9bcd62013-04-08 23:27:49 +0000765 CharUnits align = getContext().getDeclAlign(variable);
John McCall6b5a61b2011-02-07 10:33:21 +0000766
767 // This will be a [[type]]*, except that a byref entry will just be
768 // an i8**.
769 llvm::Value *blockField =
770 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
771 "block.captured");
772
773 // Compute the address of the thing we're going to move into the
774 // block literal.
775 llvm::Value *src;
Stephen Hines651f13c2014-04-23 16:59:28 -0700776 if (BlockInfo && CI.isNested()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000777 // We need to use the capture from the enclosing block.
778 const CGBlockInfo::Capture &enclosingCapture =
779 BlockInfo->getCapture(variable);
780
781 // This is a [[type]]*, except that a byref entry wil just be an i8**.
782 src = Builder.CreateStructGEP(LoadBlockStruct(),
783 enclosingCapture.getIndex(),
784 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000785 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000786 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000787 // special; we'll simply emit it directly.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700788 src = nullptr;
John McCall6b5a61b2011-02-07 10:33:21 +0000789 } else {
John McCall0353a7b2013-03-04 06:32:36 +0000790 // Just look it up in the locals map, which will give us back a
791 // [[type]]*. If that doesn't work, do the more elaborate DRE
792 // emission.
793 src = LocalDeclMap.lookup(variable);
794 if (!src) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700795 DeclRefExpr declRef(
796 const_cast<VarDecl *>(variable),
797 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
798 VK_LValue, SourceLocation());
John McCall0353a7b2013-03-04 06:32:36 +0000799 src = EmitDeclRefLValue(&declRef).getAddress();
800 }
John McCall6b5a61b2011-02-07 10:33:21 +0000801 }
802
803 // For byrefs, we just write the pointer to the byref struct into
804 // the block field. There's no need to chase the forwarding
805 // pointer at this point, since we're building something that will
806 // live a shorter life than the stack byref anyway.
Stephen Hines651f13c2014-04-23 16:59:28 -0700807 if (CI.isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000808 // Get a void* that points to the byref struct.
Stephen Hines651f13c2014-04-23 16:59:28 -0700809 if (CI.isNested())
John McCall4b9bcd62013-04-08 23:27:49 +0000810 src = Builder.CreateAlignedLoad(src, align.getQuantity(),
811 "byref.capture");
John McCall6b5a61b2011-02-07 10:33:21 +0000812 else
John McCall5936e332011-02-15 09:22:45 +0000813 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000814
John McCall5936e332011-02-15 09:22:45 +0000815 // Write that void* into the capture field.
John McCall4b9bcd62013-04-08 23:27:49 +0000816 Builder.CreateAlignedStore(src, blockField, align.getQuantity());
John McCall6b5a61b2011-02-07 10:33:21 +0000817
818 // If we have a copy constructor, evaluate that into the block field.
Stephen Hines651f13c2014-04-23 16:59:28 -0700819 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000820 if (blockDecl->isConversionFromLambda()) {
821 // If we have a lambda conversion, emit the expression
822 // directly into the block instead.
Eli Friedman23f02672012-03-01 04:01:32 +0000823 AggValueSlot Slot =
John McCall4b9bcd62013-04-08 23:27:49 +0000824 AggValueSlot::forAddr(blockField, align, Qualifiers(),
Eli Friedman23f02672012-03-01 04:01:32 +0000825 AggValueSlot::IsDestructed,
826 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000827 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000828 EmitAggExpr(copyExpr, Slot);
829 } else {
830 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
831 }
John McCall6b5a61b2011-02-07 10:33:21 +0000832
833 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000834 } else if (type->isReferenceType()) {
John McCall4b9bcd62013-04-08 23:27:49 +0000835 llvm::Value *ref =
836 Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
837 Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
838
839 // If this is an ARC __strong block-pointer variable, don't do a
840 // block copy.
841 //
842 // TODO: this can be generalized into the normal initialization logic:
843 // we should never need to do a block-copy when initializing a local
844 // variable, because the local variable's lifetime should be strictly
845 // contained within the stack block's.
846 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
847 type->isBlockPointerType()) {
848 // Load the block and do a simple retain.
849 LValue srcLV = MakeAddrLValue(src, type, align);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000850 llvm::Value *value = EmitLoadOfScalar(srcLV, SourceLocation());
John McCall4b9bcd62013-04-08 23:27:49 +0000851 value = EmitARCRetainNonBlock(value);
852
853 // Do a primitive store to the block field.
854 LValue destLV = MakeAddrLValue(blockField, type, align);
855 EmitStoreOfScalar(value, destLV, /*init*/ true);
John McCall6b5a61b2011-02-07 10:33:21 +0000856
857 // Otherwise, fake up a POD copy into the block field.
858 } else {
John McCallf85e1932011-06-15 23:02:42 +0000859 // Fake up a new variable so that EmitScalarInit doesn't think
860 // we're referring to the variable in its own initializer.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700861 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
862 SourceLocation(), /*name*/ nullptr,
863 type);
John McCallf85e1932011-06-15 23:02:42 +0000864
John McCallbb699b02011-02-07 18:37:40 +0000865 // We use one of these or the other depending on whether the
866 // reference is nested.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700867 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
868 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
869 type, VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000870
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000871 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000872 &declRef, VK_RValue);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700873 // FIXME: Pass a specific location for the expr init so that the store is
874 // attributed to a reasonable location - otherwise it may be attributed to
875 // locations of subexpressions in the initialization.
John McCalla07398e2011-06-16 04:16:24 +0000876 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall4b9bcd62013-04-08 23:27:49 +0000877 MakeAddrLValue(blockField, type, align),
John McCalldf045202011-03-08 09:38:48 +0000878 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000879 }
880
John McCall1a343eb2011-11-10 08:15:53 +0000881 // Activate the cleanup if layout pushed one.
Stephen Hines651f13c2014-04-23 16:59:28 -0700882 if (!CI.isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000883 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
884 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000885 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000886 }
John McCall6b5a61b2011-02-07 10:33:21 +0000887 }
888
889 // Cast to the converted block-pointer type, which happens (somewhat
890 // unfortunately) to be a pointer to function type.
891 llvm::Value *result =
892 Builder.CreateBitCast(blockAddr,
893 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000894
John McCall6b5a61b2011-02-07 10:33:21 +0000895 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000896}
897
898
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000899llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000900 if (BlockDescriptorType)
901 return BlockDescriptorType;
902
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000903 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000904 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000905
Mike Stumpab695142009-02-13 15:16:56 +0000906 // struct __block_descriptor {
907 // unsigned long reserved;
908 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000909 //
910 // // later, the following will be added
911 //
912 // struct {
913 // void (*copyHelper)();
914 // void (*copyHelper)();
915 // } helpers; // !!! optional
916 //
917 // const char *signature; // the block signature
918 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000919 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000920 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000921 llvm::StructType::create("struct.__block_descriptor",
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700922 UnsignedLongTy, UnsignedLongTy, nullptr);
Mike Stumpab695142009-02-13 15:16:56 +0000923
John McCall6b5a61b2011-02-07 10:33:21 +0000924 // Now form a pointer to that.
925 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000926 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000927}
928
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000929llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000930 if (GenericBlockLiteralType)
931 return GenericBlockLiteralType;
932
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000933 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000934
Mike Stump9b8a7972009-02-13 15:25:34 +0000935 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000936 // void *__isa;
937 // int __flags;
938 // int __reserved;
939 // void (*__invoke)(void *);
940 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000941 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000942 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000943 llvm::StructType::create("struct.__block_literal_generic",
944 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700945 BlockDescPtrTy, nullptr);
Mike Stumpa5448542009-02-13 15:32:32 +0000946
Mike Stump9b8a7972009-02-13 15:25:34 +0000947 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000948}
949
Mike Stumpbd65cac2009-02-19 01:01:04 +0000950
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000951RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssona1736c02009-12-24 21:13:40 +0000952 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000953 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000954 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000955
Anders Carlssonacfde802009-02-12 00:39:25 +0000956 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
957
958 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000959 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000960 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000961
962 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000963 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000964 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
965
966 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000967 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000968
Benjamin Kramer578faa82011-09-27 21:06:10 +0000969 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000970
Anders Carlssonacfde802009-02-12 00:39:25 +0000971 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000972 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000973 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000974
Anders Carlsson782f3972009-04-08 23:13:16 +0000975 QualType FnType = BPT->getPointeeType();
976
Anders Carlssonacfde802009-02-12 00:39:25 +0000977 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000978 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000979 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000980
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000981 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000982 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000983
John McCall64cd2322011-03-09 08:39:33 +0000984 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000985 const CGFunctionInfo &FnInfo =
John McCalle56bb362012-12-07 07:03:17 +0000986 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000988 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000989 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattner2acc6e32011-07-18 04:24:23 +0000991 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000992 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Anders Carlssonacfde802009-02-12 00:39:25 +0000994 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000995 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000996}
Anders Carlssond5cab542009-02-12 17:55:02 +0000997
John McCall6b5a61b2011-02-07 10:33:21 +0000998llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
999 bool isByRef) {
1000 assert(BlockInfo && "evaluating block ref without block information?");
1001 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +00001002
John McCall6b5a61b2011-02-07 10:33:21 +00001003 // Handle constant captures.
1004 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +00001005
John McCall6b5a61b2011-02-07 10:33:21 +00001006 llvm::Value *addr =
1007 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1008 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +00001009
John McCall6b5a61b2011-02-07 10:33:21 +00001010 if (isByRef) {
1011 // addr should be a void** right now. Load, then cast the result
1012 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +00001013
John McCall6b5a61b2011-02-07 10:33:21 +00001014 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001015 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +00001016 = llvm::PointerType::get(BuildByRefType(variable), 0);
1017 addr = Builder.CreateBitCast(addr, byrefPointerType,
1018 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +00001019
John McCall6b5a61b2011-02-07 10:33:21 +00001020 // Follow the forwarding pointer.
1021 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
1022 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +00001023
John McCall6b5a61b2011-02-07 10:33:21 +00001024 // Cast back to byref* and GEP over to the actual object.
1025 addr = Builder.CreateBitCast(addr, byrefPointerType);
1026 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
1027 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +00001028 }
1029
Fariborz Jahanianc637d732011-11-02 22:53:43 +00001030 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +00001031 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +00001032
John McCall6b5a61b2011-02-07 10:33:21 +00001033 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +00001034}
1035
Mike Stump67a64482009-02-14 22:16:35 +00001036llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001037CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +00001038 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +00001039 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1040 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +00001041
John McCall6b5a61b2011-02-07 10:33:21 +00001042 // Compute information about the layout, etc., of this block.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001043 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001044
John McCall6b5a61b2011-02-07 10:33:21 +00001045 // Using that metadata, generate the actual block function.
1046 llvm::Constant *blockFn;
1047 {
1048 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +00001049 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1050 blockInfo,
John McCallf5ebf9b2013-05-03 07:33:41 +00001051 LocalDeclMap,
Eli Friedman64bee652012-02-25 02:48:22 +00001052 false);
John McCall6b5a61b2011-02-07 10:33:21 +00001053 }
John McCall5936e332011-02-15 09:22:45 +00001054 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +00001055
John McCalld16c2cf2011-02-08 08:22:06 +00001056 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +00001057}
1058
John McCall6b5a61b2011-02-07 10:33:21 +00001059static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1060 const CGBlockInfo &blockInfo,
1061 llvm::Constant *blockFn) {
1062 assert(blockInfo.CanBeGlobal);
1063
1064 // Generate the constants for the block literal initializer.
1065 llvm::Constant *fields[BlockHeaderSize];
1066
1067 // isa
1068 fields[0] = CGM.getNSConcreteGlobalBlock();
1069
1070 // __flags
John McCall64cd2322011-03-09 08:39:33 +00001071 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1072 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1073
John McCall5936e332011-02-15 09:22:45 +00001074 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +00001075
1076 // Reserved
John McCall5936e332011-02-15 09:22:45 +00001077 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001078
1079 // Function
1080 fields[3] = blockFn;
1081
1082 // Descriptor
1083 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1084
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001085 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +00001086
1087 llvm::GlobalVariable *literal =
1088 new llvm::GlobalVariable(CGM.getModule(),
1089 init->getType(),
1090 /*constant*/ true,
1091 llvm::GlobalVariable::InternalLinkage,
1092 init,
1093 "__block_literal_global");
1094 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1095
1096 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001097 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +00001098 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1099 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +00001100}
1101
Mike Stump00470a12009-03-05 08:32:30 +00001102llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +00001103CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1104 const CGBlockInfo &blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +00001105 const DeclMapTy &ldm,
1106 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001107 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001108
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001109 CurGD = GD;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001110
1111 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001112
John McCall6b5a61b2011-02-07 10:33:21 +00001113 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Mike Stump7f28a9c2009-03-13 23:34:28 +00001115 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001116 // to be local to this function as well, in case they're directly
1117 // referenced in a block.
1118 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001119 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall6b5a61b2011-02-07 10:33:21 +00001120 if (var && !var->hasLocalStorage())
1121 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001122 }
1123
John McCall6b5a61b2011-02-07 10:33:21 +00001124 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001125
John McCall6b5a61b2011-02-07 10:33:21 +00001126 // Build the argument list.
1127 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001128
John McCall6b5a61b2011-02-07 10:33:21 +00001129 // The first argument is the block pointer. Just take it as a void*
1130 // and cast it later.
1131 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001132 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001133
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001134 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
John McCall8178df32011-02-22 22:38:33 +00001135 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001136 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001137
John McCall6b5a61b2011-02-07 10:33:21 +00001138 // Now add the rest of the parameters.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001139 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCallea1471e2010-05-20 01:18:31 +00001140
John McCall6b5a61b2011-02-07 10:33:21 +00001141 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001142 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
Stephen Hines651f13c2014-04-23 16:59:28 -07001143 const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1144 fnType->getReturnType(), args, fnType->getExtInfo(),
1145 fnType->isVariadic());
1146 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall64cd2322011-03-09 08:39:33 +00001147 blockInfo.UsesStret = true;
1148
John McCallde5d3c72012-02-17 03:33:10 +00001149 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001150
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001151 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1152 llvm::Function *fn = llvm::Function::Create(
1153 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall6b5a61b2011-02-07 10:33:21 +00001154 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001155
John McCall6b5a61b2011-02-07 10:33:21 +00001156 // Begin generating the function.
Stephen Hines651f13c2014-04-23 16:59:28 -07001157 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001158 blockDecl->getLocation(),
Devang Patel3f4cb252011-03-25 21:26:13 +00001159 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpa5448542009-02-13 15:32:32 +00001160
John McCall8178df32011-02-22 22:38:33 +00001161 // Okay. Undo some of what StartFunction did.
1162
1163 // Pull the 'self' reference out of the local decl map.
1164 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1165 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001166 BlockPointer = Builder.CreateBitCast(blockAddr,
1167 blockInfo.StructureType->getPointerTo(),
1168 "block");
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001169 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1170 // won't delete the dbg.declare intrinsics for captured variables.
1171 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1172 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1173 // Allocate a stack slot for it, so we can point the debugger to it
1174 llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
1175 "block.addr");
1176 unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
1177 Alloca->setAlignment(Align);
Adrian Prantl79591942013-04-02 01:00:48 +00001178 // Set the DebugLocation to empty, so the store is recognized as a
1179 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001180 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001181 Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
1182 BlockPointerDbgLoc = Alloca;
1183 }
Anders Carlssond5cab542009-02-12 17:55:02 +00001184
John McCallea1471e2010-05-20 01:18:31 +00001185 // If we have a C++ 'this' reference, go ahead and force it into
1186 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001187 if (blockDecl->capturesCXXThis()) {
1188 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1189 blockInfo.CXXThisIndex,
1190 "block.captured-this");
1191 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001192 }
1193
John McCall6b5a61b2011-02-07 10:33:21 +00001194 // Also force all the constant captures.
Stephen Hines651f13c2014-04-23 16:59:28 -07001195 for (const auto &CI : blockDecl->captures()) {
1196 const VarDecl *variable = CI.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +00001197 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1198 if (!capture.isConstant()) continue;
1199
1200 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1201
1202 llvm::AllocaInst *alloca =
1203 CreateMemTemp(variable->getType(), "block.captured-const");
1204 alloca->setAlignment(align);
1205
Adrian Prantl836e7c92013-03-14 17:53:33 +00001206 Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
John McCall6b5a61b2011-02-07 10:33:21 +00001207
1208 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001209 }
1210
John McCallf4b88a42012-03-10 09:33:50 +00001211 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001212 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1213 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1214 --entry_ptr;
1215
Eli Friedman64bee652012-02-25 02:48:22 +00001216 if (IsLambdaConversionToBlock)
1217 EmitLambdaBlockInvokeBody();
Stephen Hines651f13c2014-04-23 16:59:28 -07001218 else {
1219 PGO.assignRegionCounters(blockDecl, fn);
1220 RegionCounter Cnt = getPGORegionCounter(blockDecl->getBody());
1221 Cnt.beginRegion(Builder);
Eli Friedman64bee652012-02-25 02:48:22 +00001222 EmitStmt(blockDecl->getBody());
Stephen Hines651f13c2014-04-23 16:59:28 -07001223 }
Mike Stumpb289b3f2009-10-01 22:29:41 +00001224
Mike Stumpde8c5c72009-10-01 00:27:30 +00001225 // Remember where we were...
1226 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001227
Mike Stumpde8c5c72009-10-01 00:27:30 +00001228 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001229 ++entry_ptr;
1230 Builder.SetInsertPoint(entry, entry_ptr);
1231
John McCallf4b88a42012-03-10 09:33:50 +00001232 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001233 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001234 if (CGDebugInfo *DI = getDebugInfo()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001235 for (const auto &CI : blockDecl->captures()) {
1236 const VarDecl *variable = CI.getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001237 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001238
Douglas Gregor4cdad312012-10-23 20:05:01 +00001239 if (CGM.getCodeGenOpts().getDebugInfo()
1240 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001241 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1242 if (capture.isConstant()) {
1243 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1244 Builder);
1245 continue;
1246 }
John McCall6b5a61b2011-02-07 10:33:21 +00001247
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001248 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
Stephen Hines176edba2014-12-01 14:53:08 -08001249 Builder, blockInfo,
1250 entry_ptr == entry->end()
1251 ? nullptr : entry_ptr);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001252 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001253 }
Manman Ren3c7a0e12013-01-04 18:51:35 +00001254 // Recover location if it was changed in the above loop.
1255 DI->EmitLocation(Builder,
Adrian Prantld83cdd62013-04-08 20:52:12 +00001256 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stumpb1a6e682009-09-30 02:43:10 +00001257 }
John McCall6b5a61b2011-02-07 10:33:21 +00001258
Mike Stumpde8c5c72009-10-01 00:27:30 +00001259 // And resume where we left off.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001260 if (resume == nullptr)
Mike Stumpde8c5c72009-10-01 00:27:30 +00001261 Builder.ClearInsertionPoint();
1262 else
1263 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001264
John McCall6b5a61b2011-02-07 10:33:21 +00001265 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001266
John McCall6b5a61b2011-02-07 10:33:21 +00001267 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001268}
Mike Stumpa99038c2009-02-28 09:07:16 +00001269
John McCall6b5a61b2011-02-07 10:33:21 +00001270/*
1271 notes.push_back(HelperInfo());
1272 HelperInfo &note = notes.back();
1273 note.index = capture.getIndex();
1274 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1275 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001276
John McCall6b5a61b2011-02-07 10:33:21 +00001277 if (ci->isByRef()) {
1278 note.flag = BLOCK_FIELD_IS_BYREF;
1279 if (type.isObjCGCWeak())
1280 note.flag |= BLOCK_FIELD_IS_WEAK;
1281 } else if (type->isBlockPointerType()) {
1282 note.flag = BLOCK_FIELD_IS_BLOCK;
1283 } else {
1284 note.flag = BLOCK_FIELD_IS_OBJECT;
1285 }
1286 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001287
Mike Stump00470a12009-03-05 08:32:30 +00001288
John McCallb62faef2013-01-22 03:56:22 +00001289/// Generate the copy-helper function for a block closure object:
1290/// static void block_copy_helper(block_t *dst, block_t *src);
1291/// The runtime will have previously initialized 'dst' by doing a
1292/// bit-copy of 'src'.
1293///
1294/// Note that this copies an entire block closure object to the heap;
1295/// it should not be confused with a 'byref copy helper', which moves
1296/// the contents of an individual __block variable to the heap.
John McCall6b5a61b2011-02-07 10:33:21 +00001297llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001298CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001299 ASTContext &C = getContext();
1300
1301 FunctionArgList args;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001302 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1303 C.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001304 args.push_back(&dstDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001305 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1306 C.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001307 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Stephen Hines651f13c2014-04-23 16:59:28 -07001309 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1310 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001311
John McCall6b5a61b2011-02-07 10:33:21 +00001312 // FIXME: it would be nice if these were mergeable with things with
1313 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001314 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001315
1316 llvm::Function *Fn =
1317 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001318 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001319
1320 IdentifierInfo *II
1321 = &CGM.getContext().Idents.get("__copy_helper_block_");
1322
John McCall6b5a61b2011-02-07 10:33:21 +00001323 FunctionDecl *FD = FunctionDecl::Create(C,
1324 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001325 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001326 SourceLocation(), II, C.VoidTy,
1327 nullptr, SC_Static,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001328 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001329 false);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001330 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001331 StartFunction(FD, C.VoidTy, Fn, FI, args);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001332 // Create a scope with an artificial location for the body of this function.
1333 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001334 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001335
John McCalld26bc762011-03-09 04:27:21 +00001336 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001337 src = Builder.CreateLoad(src);
1338 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001339
John McCalld26bc762011-03-09 04:27:21 +00001340 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001341 dst = Builder.CreateLoad(dst);
1342 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001343
John McCall6b5a61b2011-02-07 10:33:21 +00001344 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001345
Stephen Hines651f13c2014-04-23 16:59:28 -07001346 for (const auto &CI : blockDecl->captures()) {
1347 const VarDecl *variable = CI.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +00001348 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001349
John McCall6b5a61b2011-02-07 10:33:21 +00001350 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1351 if (capture.isConstant()) continue;
1352
Stephen Hines651f13c2014-04-23 16:59:28 -07001353 const Expr *copyExpr = CI.getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001354 BlockFieldFlags flags;
1355
John McCall015f33b2012-10-17 02:28:37 +00001356 bool useARCWeakCopy = false;
1357 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001358
1359 if (copyExpr) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001360 assert(!CI.isByRef());
John McCall6b5a61b2011-02-07 10:33:21 +00001361 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001362
Stephen Hines651f13c2014-04-23 16:59:28 -07001363 } else if (CI.isByRef()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001364 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001365 if (type.isObjCGCWeak())
1366 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001367
John McCallf85e1932011-06-15 23:02:42 +00001368 } else if (type->isObjCRetainableType()) {
1369 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001370 bool isBlockPointer = type->isBlockPointerType();
1371 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001372 flags = BLOCK_FIELD_IS_BLOCK;
1373
1374 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001375 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001376 Qualifiers qs = type.getQualifiers();
1377
John McCall015f33b2012-10-17 02:28:37 +00001378 // We need to register __weak direct captures with the runtime.
1379 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1380 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001381
John McCall015f33b2012-10-17 02:28:37 +00001382 // We need to retain the copied value for __strong direct captures.
1383 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1384 // If it's a block pointer, we have to copy the block and
1385 // assign that to the destination pointer, so we might as
1386 // well use _Block_object_assign. Otherwise we can avoid that.
1387 if (!isBlockPointer)
1388 useARCStrongCopy = true;
1389
1390 // Otherwise the memcpy is fine.
1391 } else {
1392 continue;
1393 }
1394
1395 // Non-ARC captures of retainable pointers are strong and
1396 // therefore require a call to _Block_object_assign.
1397 } else {
1398 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001399 }
1400 } else {
1401 continue;
1402 }
John McCall6b5a61b2011-02-07 10:33:21 +00001403
1404 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001405 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1406 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001407
1408 // If there's an explicit copy expression, we do that.
1409 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001410 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001411 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001412 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001413 } else {
1414 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001415 if (useARCStrongCopy) {
1416 // At -O0, store null into the destination field (so that the
1417 // storeStrong doesn't over-release) and then call storeStrong.
1418 // This is a workaround to not having an initStrong call.
1419 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001420 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCall015f33b2012-10-17 02:28:37 +00001421 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1422 Builder.CreateStore(null, dstField);
1423 EmitARCStoreStrongCall(dstField, srcValue, true);
1424
1425 // With optimization enabled, take advantage of the fact that
1426 // the blocks runtime guarantees a memcpy of the block data, and
1427 // just emit a retain of the src field.
1428 } else {
1429 EmitARCRetainNonBlock(srcValue);
1430
1431 // We don't need this anymore, so kill it. It's not quite
1432 // worth the annoyance to avoid creating it in the first place.
1433 cast<llvm::Instruction>(dstField)->eraseFromParent();
1434 }
1435 } else {
1436 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1437 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCallbd7370a2013-02-28 19:01:20 +00001438 llvm::Value *args[] = {
1439 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1440 };
1441
1442 bool copyCanThrow = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07001443 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCallbd7370a2013-02-28 19:01:20 +00001444 const Expr *copyExpr =
1445 CGM.getContext().getBlockVarCopyInits(variable);
1446 if (copyExpr) {
1447 copyCanThrow = true; // FIXME: reuse the noexcept logic
1448 }
1449 }
1450
1451 if (copyCanThrow) {
1452 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1453 } else {
1454 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1455 }
John McCall015f33b2012-10-17 02:28:37 +00001456 }
Mike Stump08920992009-03-07 02:35:30 +00001457 }
1458 }
1459
John McCalld16c2cf2011-02-08 08:22:06 +00001460 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001461
John McCall5936e332011-02-15 09:22:45 +00001462 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001463}
1464
John McCallb62faef2013-01-22 03:56:22 +00001465/// Generate the destroy-helper function for a block closure object:
1466/// static void block_destroy_helper(block_t *theBlock);
1467///
1468/// Note that this destroys a heap-allocated block closure object;
1469/// it should not be confused with a 'byref destroy helper', which
1470/// destroys the heap-allocated contents of an individual __block
1471/// variable.
John McCall6b5a61b2011-02-07 10:33:21 +00001472llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001473CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001474 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001475
John McCall6b5a61b2011-02-07 10:33:21 +00001476 FunctionArgList args;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001477 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1478 C.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001479 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Stephen Hines651f13c2014-04-23 16:59:28 -07001481 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1482 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001483
Mike Stump3899a7f2009-06-05 23:26:36 +00001484 // FIXME: We'd like to put these into a mergable by content, with
1485 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001486 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001487
1488 llvm::Function *Fn =
1489 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001490 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001491
1492 IdentifierInfo *II
1493 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1494
John McCall6b5a61b2011-02-07 10:33:21 +00001495 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001496 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001497 SourceLocation(), II, C.VoidTy,
1498 nullptr, SC_Static,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001499 false, false);
Adrian Prantlb6cdc962013-07-24 20:34:39 +00001500 // Create a scope with an artificial location for the body of this function.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001501 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001502 StartFunction(FD, C.VoidTy, Fn, FI, args);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001503 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump1edf6b62009-03-07 02:53:18 +00001504
Chris Lattner2acc6e32011-07-18 04:24:23 +00001505 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001506
John McCalld26bc762011-03-09 04:27:21 +00001507 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001508 src = Builder.CreateLoad(src);
1509 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001510
John McCall6b5a61b2011-02-07 10:33:21 +00001511 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1512
John McCalld16c2cf2011-02-08 08:22:06 +00001513 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001514
Stephen Hines651f13c2014-04-23 16:59:28 -07001515 for (const auto &CI : blockDecl->captures()) {
1516 const VarDecl *variable = CI.getVariable();
John McCall6b5a61b2011-02-07 10:33:21 +00001517 QualType type = variable->getType();
1518
1519 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1520 if (capture.isConstant()) continue;
1521
John McCalld16c2cf2011-02-08 08:22:06 +00001522 BlockFieldFlags flags;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001523 const CXXDestructorDecl *dtor = nullptr;
John McCall6b5a61b2011-02-07 10:33:21 +00001524
John McCall015f33b2012-10-17 02:28:37 +00001525 bool useARCWeakDestroy = false;
1526 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001527
Stephen Hines651f13c2014-04-23 16:59:28 -07001528 if (CI.isByRef()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001529 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001530 if (type.isObjCGCWeak())
1531 flags |= BLOCK_FIELD_IS_WEAK;
1532 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1533 if (record->hasTrivialDestructor())
1534 continue;
1535 dtor = record->getDestructor();
1536 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001537 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001538 if (type->isBlockPointerType())
1539 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001540
John McCallf85e1932011-06-15 23:02:42 +00001541 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001542 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001543 Qualifiers qs = type.getQualifiers();
1544
1545 // Don't generate special dispose logic for a captured object
1546 // unless it's __strong or __weak.
1547 if (!qs.hasStrongOrWeakObjCLifetime())
1548 continue;
1549
1550 // Support __weak direct captures.
1551 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001552 useARCWeakDestroy = true;
1553
1554 // Tools really want us to use objc_storeStrong here.
1555 else
1556 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001557 }
1558 } else {
1559 continue;
1560 }
John McCall6b5a61b2011-02-07 10:33:21 +00001561
1562 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001563 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001564
1565 // If there's an explicit copy expression, we do that.
1566 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001567 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001568
John McCallf85e1932011-06-15 23:02:42 +00001569 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001570 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001571 EmitARCDestroyWeak(srcField);
1572
John McCall015f33b2012-10-17 02:28:37 +00001573 // Destroy strong objects with a call if requested.
1574 } else if (useARCStrongDestroy) {
John McCall5b07e802013-03-13 03:10:54 +00001575 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCall015f33b2012-10-17 02:28:37 +00001576
John McCall6b5a61b2011-02-07 10:33:21 +00001577 // Otherwise we call _Block_object_dispose. It wouldn't be too
1578 // hard to just emit this as a cleanup if we wanted to make sure
1579 // that things were done in reverse.
1580 } else {
1581 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001582 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001583 BuildBlockRelease(value, flags);
1584 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001585 }
1586
John McCall6b5a61b2011-02-07 10:33:21 +00001587 cleanups.ForceCleanup();
1588
John McCalld16c2cf2011-02-08 08:22:06 +00001589 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001590
John McCall5936e332011-02-15 09:22:45 +00001591 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001592}
1593
John McCallf0c11f72011-03-31 08:03:29 +00001594namespace {
1595
1596/// Emits the copy/dispose helper functions for a __block object of id type.
1597class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1598 BlockFieldFlags Flags;
1599
1600public:
1601 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1602 : ByrefHelpers(alignment), Flags(flags) {}
1603
John McCall36170192011-03-31 09:19:20 +00001604 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Stephen Hines651f13c2014-04-23 16:59:28 -07001605 llvm::Value *srcField) override {
John McCallf0c11f72011-03-31 08:03:29 +00001606 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1607
1608 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1609 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1610
1611 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1612
1613 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1614 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCallbd7370a2013-02-28 19:01:20 +00001615
1616 llvm::Value *args[] = { destField, srcValue, flagsVal };
1617 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf0c11f72011-03-31 08:03:29 +00001618 }
1619
Stephen Hines651f13c2014-04-23 16:59:28 -07001620 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallf0c11f72011-03-31 08:03:29 +00001621 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1622 llvm::Value *value = CGF.Builder.CreateLoad(field);
1623
1624 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1625 }
1626
Stephen Hines651f13c2014-04-23 16:59:28 -07001627 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf0c11f72011-03-31 08:03:29 +00001628 id.AddInteger(Flags.getBitMask());
1629 }
1630};
1631
John McCallf85e1932011-06-15 23:02:42 +00001632/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1633class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1634public:
1635 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1636
1637 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Stephen Hines651f13c2014-04-23 16:59:28 -07001638 llvm::Value *srcField) override {
John McCallf85e1932011-06-15 23:02:42 +00001639 CGF.EmitARCMoveWeak(destField, srcField);
1640 }
1641
Stephen Hines651f13c2014-04-23 16:59:28 -07001642 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallf85e1932011-06-15 23:02:42 +00001643 CGF.EmitARCDestroyWeak(field);
1644 }
1645
Stephen Hines651f13c2014-04-23 16:59:28 -07001646 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf85e1932011-06-15 23:02:42 +00001647 // 0 is distinguishable from all pointers and byref flags
1648 id.AddInteger(0);
1649 }
1650};
1651
1652/// Emits the copy/dispose helpers for an ARC __block __strong variable
1653/// that's not of block-pointer type.
1654class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1655public:
1656 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1657
1658 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Stephen Hines651f13c2014-04-23 16:59:28 -07001659 llvm::Value *srcField) override {
John McCallf85e1932011-06-15 23:02:42 +00001660 // Do a "move" by copying the value and then zeroing out the old
1661 // variable.
1662
John McCalla59e4b72011-11-09 03:17:26 +00001663 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1664 value->setAlignment(Alignment.getQuantity());
1665
John McCallf85e1932011-06-15 23:02:42 +00001666 llvm::Value *null =
1667 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001668
Fariborz Jahanian7a77f192013-01-04 23:32:24 +00001669 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
Fariborz Jahanianba3c9ca2013-01-05 00:32:13 +00001670 llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1671 store->setAlignment(Alignment.getQuantity());
Fariborz Jahanian7a77f192013-01-04 23:32:24 +00001672 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1673 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1674 return;
1675 }
John McCalla59e4b72011-11-09 03:17:26 +00001676 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1677 store->setAlignment(Alignment.getQuantity());
1678
1679 store = CGF.Builder.CreateStore(null, srcField);
1680 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001681 }
1682
Stephen Hines651f13c2014-04-23 16:59:28 -07001683 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCall5b07e802013-03-13 03:10:54 +00001684 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001685 }
1686
Stephen Hines651f13c2014-04-23 16:59:28 -07001687 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf85e1932011-06-15 23:02:42 +00001688 // 1 is distinguishable from all pointers and byref flags
1689 id.AddInteger(1);
1690 }
1691};
1692
John McCalla59e4b72011-11-09 03:17:26 +00001693/// Emits the copy/dispose helpers for an ARC __block __strong
1694/// variable that's of block-pointer type.
1695class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1696public:
1697 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1698
1699 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Stephen Hines651f13c2014-04-23 16:59:28 -07001700 llvm::Value *srcField) override {
John McCalla59e4b72011-11-09 03:17:26 +00001701 // Do the copy with objc_retainBlock; that's all that
1702 // _Block_object_assign would do anyway, and we'd have to pass the
1703 // right arguments to make sure it doesn't get no-op'ed.
1704 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1705 oldValue->setAlignment(Alignment.getQuantity());
1706
1707 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1708
1709 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1710 store->setAlignment(Alignment.getQuantity());
1711 }
1712
Stephen Hines651f13c2014-04-23 16:59:28 -07001713 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCall5b07e802013-03-13 03:10:54 +00001714 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCalla59e4b72011-11-09 03:17:26 +00001715 }
1716
Stephen Hines651f13c2014-04-23 16:59:28 -07001717 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCalla59e4b72011-11-09 03:17:26 +00001718 // 2 is distinguishable from all pointers and byref flags
1719 id.AddInteger(2);
1720 }
1721};
1722
John McCallf0c11f72011-03-31 08:03:29 +00001723/// Emits the copy/dispose helpers for a __block variable with a
1724/// nontrivial copy constructor or destructor.
1725class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1726 QualType VarType;
1727 const Expr *CopyExpr;
1728
1729public:
1730 CXXByrefHelpers(CharUnits alignment, QualType type,
1731 const Expr *copyExpr)
1732 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1733
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001734 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCallf0c11f72011-03-31 08:03:29 +00001735 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Stephen Hines651f13c2014-04-23 16:59:28 -07001736 llvm::Value *srcField) override {
John McCallf0c11f72011-03-31 08:03:29 +00001737 if (!CopyExpr) return;
1738 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1739 }
1740
Stephen Hines651f13c2014-04-23 16:59:28 -07001741 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallf0c11f72011-03-31 08:03:29 +00001742 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1743 CGF.PushDestructorCleanup(VarType, field);
1744 CGF.PopCleanupBlocks(cleanupDepth);
1745 }
1746
Stephen Hines651f13c2014-04-23 16:59:28 -07001747 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf0c11f72011-03-31 08:03:29 +00001748 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1749 }
1750};
1751} // end anonymous namespace
1752
1753static llvm::Constant *
1754generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001755 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001756 unsigned valueFieldIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001757 CodeGenModule::ByrefHelpers &byrefInfo) {
1758 ASTContext &Context = CGF.getContext();
1759
1760 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001761
John McCalld26bc762011-03-09 04:27:21 +00001762 FunctionArgList args;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001763 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1764 Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001765 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001766
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001767 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1768 Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001769 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Stephen Hines651f13c2014-04-23 16:59:28 -07001771 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1772 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stump45031c02009-03-06 02:29:21 +00001773
John McCallf0c11f72011-03-31 08:03:29 +00001774 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001775 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001776
Mike Stump3899a7f2009-06-05 23:26:36 +00001777 // FIXME: We'd like to put these into a mergable by content, with
1778 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001779 llvm::Function *Fn =
1780 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001781 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001782
1783 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001784 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001785
John McCallf0c11f72011-03-31 08:03:29 +00001786 FunctionDecl *FD = FunctionDecl::Create(Context,
1787 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001788 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001789 SourceLocation(), II, R, nullptr,
John McCalld931b082010-08-26 03:08:43 +00001790 SC_Static,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001791 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001792
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001793 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpee094222009-03-06 06:12:24 +00001794
John McCallf0c11f72011-03-31 08:03:29 +00001795 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001796 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001797
John McCallf0c11f72011-03-31 08:03:29 +00001798 // dst->x
1799 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1800 destField = CGF.Builder.CreateLoad(destField);
1801 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCallb62faef2013-01-22 03:56:22 +00001802 destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001803
John McCallf0c11f72011-03-31 08:03:29 +00001804 // src->x
1805 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1806 srcField = CGF.Builder.CreateLoad(srcField);
1807 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCallb62faef2013-01-22 03:56:22 +00001808 srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
John McCallf0c11f72011-03-31 08:03:29 +00001809
1810 byrefInfo.emitCopy(CGF, destField, srcField);
1811 }
1812
1813 CGF.FinishFunction();
1814
1815 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001816}
1817
John McCallf0c11f72011-03-31 08:03:29 +00001818/// Build the copy helper for a __block variable.
1819static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001820 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001821 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001822 CodeGenModule::ByrefHelpers &info) {
1823 CodeGenFunction CGF(CGM);
John McCallb62faef2013-01-22 03:56:22 +00001824 return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
John McCallf0c11f72011-03-31 08:03:29 +00001825}
1826
1827/// Generate code for a __block variable's dispose helper.
1828static llvm::Constant *
1829generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001830 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001831 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001832 CodeGenModule::ByrefHelpers &byrefInfo) {
1833 ASTContext &Context = CGF.getContext();
1834 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001835
John McCalld26bc762011-03-09 04:27:21 +00001836 FunctionArgList args;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001837 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1838 Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001839 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Stephen Hines651f13c2014-04-23 16:59:28 -07001841 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1842 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stump45031c02009-03-06 02:29:21 +00001843
John McCallf0c11f72011-03-31 08:03:29 +00001844 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001845 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001846
Mike Stump3899a7f2009-06-05 23:26:36 +00001847 // FIXME: We'd like to put these into a mergable by content, with
1848 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001849 llvm::Function *Fn =
1850 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001851 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001852 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001853
1854 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001855 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001856
John McCallf0c11f72011-03-31 08:03:29 +00001857 FunctionDecl *FD = FunctionDecl::Create(Context,
1858 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001859 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001860 SourceLocation(), II, R, nullptr,
John McCalld931b082010-08-26 03:08:43 +00001861 SC_Static,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001862 false, false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001863 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stump1851b682009-03-06 04:53:30 +00001864
John McCallf0c11f72011-03-31 08:03:29 +00001865 if (byrefInfo.needsDispose()) {
1866 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1867 V = CGF.Builder.CreateLoad(V);
1868 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
John McCallb62faef2013-01-22 03:56:22 +00001869 V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001870
John McCallf0c11f72011-03-31 08:03:29 +00001871 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001872 }
Mike Stump45031c02009-03-06 02:29:21 +00001873
John McCallf0c11f72011-03-31 08:03:29 +00001874 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001875
John McCallf0c11f72011-03-31 08:03:29 +00001876 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001877}
1878
John McCallf0c11f72011-03-31 08:03:29 +00001879/// Build the dispose helper for a __block variable.
1880static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001881 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001882 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001883 CodeGenModule::ByrefHelpers &info) {
1884 CodeGenFunction CGF(CGM);
John McCallb62faef2013-01-22 03:56:22 +00001885 return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
Mike Stump45031c02009-03-06 02:29:21 +00001886}
1887
John McCallb62faef2013-01-22 03:56:22 +00001888/// Lazily build the copy and dispose helpers for a __block variable
1889/// with the given information.
John McCallf0c11f72011-03-31 08:03:29 +00001890template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001891 llvm::StructType &byrefTy,
John McCallb62faef2013-01-22 03:56:22 +00001892 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001893 T &byrefInfo) {
1894 // Increase the field's alignment to be at least pointer alignment,
1895 // since the layout of the byref struct will guarantee at least that.
1896 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1897 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1898
1899 llvm::FoldingSetNodeID id;
1900 byrefInfo.Profile(id);
1901
1902 void *insertPos;
1903 CodeGenModule::ByrefHelpers *node
1904 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1905 if (node) return static_cast<T*>(node);
1906
John McCallb62faef2013-01-22 03:56:22 +00001907 byrefInfo.CopyHelper =
1908 buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1909 byrefInfo.DisposeHelper =
1910 buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
John McCallf0c11f72011-03-31 08:03:29 +00001911
1912 T *copy = new (CGM.getContext()) T(byrefInfo);
1913 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1914 return copy;
1915}
1916
John McCallb62faef2013-01-22 03:56:22 +00001917/// Build the copy and dispose helpers for the given __block variable
1918/// emission. Places the helpers in the global cache. Returns null
1919/// if no helpers are required.
John McCallf0c11f72011-03-31 08:03:29 +00001920CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001921CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001922 const AutoVarEmission &emission) {
1923 const VarDecl &var = *emission.Variable;
1924 QualType type = var.getType();
1925
John McCallb62faef2013-01-22 03:56:22 +00001926 unsigned byrefValueIndex = getByRefValueLLVMField(&var);
1927
John McCallf0c11f72011-03-31 08:03:29 +00001928 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1929 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001930 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf0c11f72011-03-31 08:03:29 +00001931
1932 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
John McCallb62faef2013-01-22 03:56:22 +00001933 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf0c11f72011-03-31 08:03:29 +00001934 }
1935
John McCallf85e1932011-06-15 23:02:42 +00001936 // Otherwise, if we don't have a retainable type, there's nothing to do.
1937 // that the runtime does extra copies.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001938 if (!type->isObjCRetainableType()) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00001939
1940 Qualifiers qs = type.getQualifiers();
1941
1942 // If we have lifetime, that dominates.
1943 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001944 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001945
1946 switch (lifetime) {
1947 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1948
1949 // These are just bits as far as the runtime is concerned.
1950 case Qualifiers::OCL_ExplicitNone:
1951 case Qualifiers::OCL_Autoreleasing:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001952 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00001953
1954 // Tell the runtime that this is ARC __weak, called by the
1955 // byref routines.
1956 case Qualifiers::OCL_Weak: {
1957 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001958 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001959 }
1960
1961 // ARC __strong __block variables need to be retained.
1962 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001963 // Block pointers need to be copied, and there's no direct
1964 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001965 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001966 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001967 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001968
1969 // Otherwise, we transfer ownership of the retain from the stack
1970 // to the heap.
1971 } else {
1972 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001973 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001974 }
1975 }
1976 llvm_unreachable("fell out of lifetime switch!");
1977 }
1978
John McCallf0c11f72011-03-31 08:03:29 +00001979 BlockFieldFlags flags;
1980 if (type->isBlockPointerType()) {
1981 flags |= BLOCK_FIELD_IS_BLOCK;
1982 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1983 type->isObjCObjectPointerType()) {
1984 flags |= BLOCK_FIELD_IS_OBJECT;
1985 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001986 return nullptr;
John McCallf0c11f72011-03-31 08:03:29 +00001987 }
1988
1989 if (type.isObjCGCWeak())
1990 flags |= BLOCK_FIELD_IS_WEAK;
1991
1992 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
John McCallb62faef2013-01-22 03:56:22 +00001993 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001994}
1995
John McCall5af02db2011-03-31 01:59:53 +00001996unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1997 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1998
1999 return ByRefValueInfo.find(VD)->second.second;
2000}
2001
2002llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
2003 const VarDecl *V) {
2004 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
2005 Loc = Builder.CreateLoad(Loc);
2006 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
2007 V->getNameAsString());
2008 return Loc;
2009}
2010
2011/// BuildByRefType - This routine changes a __block variable declared as T x
2012/// into:
2013///
2014/// struct {
2015/// void *__isa;
2016/// void *__forwarding;
2017/// int32_t __flags;
2018/// int32_t __size;
2019/// void *__copy_helper; // only if needed
2020/// void *__destroy_helper; // only if needed
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002021/// void *__byref_variable_layout;// only if needed
John McCall5af02db2011-03-31 01:59:53 +00002022/// char padding[X]; // only if needed
2023/// T x;
2024/// } x
2025///
Chris Lattner2acc6e32011-07-18 04:24:23 +00002026llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
2027 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00002028 if (Info.first)
2029 return Info.first;
2030
2031 QualType Ty = D->getType();
2032
Chris Lattner5f9e2722011-07-23 10:55:15 +00002033 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00002034
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002035 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00002036 llvm::StructType::create(getLLVMContext(),
2037 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00002038
2039 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00002040 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002041
2042 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002043 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00002044
2045 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00002046 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00002047
2048 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00002049 types.push_back(Int32Ty);
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00002050 // Note that this must match *exactly* the logic in buildByrefHelpers.
2051 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
John McCall5af02db2011-03-31 01:59:53 +00002052 if (HasCopyAndDispose) {
2053 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00002054 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002055
2056 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00002057 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002058 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002059 bool HasByrefExtendedLayout = false;
2060 Qualifiers::ObjCLifetime Lifetime;
2061 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2062 HasByrefExtendedLayout)
2063 /// void *__byref_variable_layout;
2064 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002065
2066 bool Packed = false;
2067 CharUnits Align = getContext().getDeclAlign(D);
John McCall64aa4b32013-04-16 22:48:15 +00002068 if (Align >
2069 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
John McCall5af02db2011-03-31 01:59:53 +00002070 // We have to insert padding.
2071
2072 // The struct above has 2 32-bit integers.
2073 unsigned CurrentOffsetInBytes = 4 * 2;
2074
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002075 // And either 2, 3, 4 or 5 pointers.
2076 unsigned noPointers = 2;
2077 if (HasCopyAndDispose)
2078 noPointers += 2;
2079 if (HasByrefExtendedLayout)
2080 noPointers += 1;
2081
2082 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002083
2084 // Align the offset.
2085 unsigned AlignedOffsetInBytes =
2086 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2087
2088 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2089 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00002090 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00002091 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00002092 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00002093 if (NumPaddingBytes > 1)
2094 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2095
John McCall0774cb82011-05-15 01:53:33 +00002096 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00002097
2098 // We want a packed struct.
2099 Packed = true;
2100 }
2101 }
2102
2103 // T x;
John McCall0774cb82011-05-15 01:53:33 +00002104 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00002105
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002106 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00002107
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002108 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00002109
John McCall0774cb82011-05-15 01:53:33 +00002110 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00002111
2112 return Info.first;
2113}
2114
2115/// Initialize the structural components of a __block variable, i.e.
2116/// everything but the actual object.
2117void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00002118 // Find the address of the local.
2119 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00002120
John McCallf0c11f72011-03-31 08:03:29 +00002121 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002122 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00002123 cast<llvm::PointerType>(addr->getType())->getElementType());
2124
2125 // Build the byref helpers if necessary. This is null if we don't need any.
2126 CodeGenModule::ByrefHelpers *helpers =
2127 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00002128
2129 const VarDecl &D = *emission.Variable;
2130 QualType type = D.getType();
2131
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002132 bool HasByrefExtendedLayout;
2133 Qualifiers::ObjCLifetime ByrefLifetime;
2134 bool ByRefHasLifetime =
2135 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2136
John McCallf0c11f72011-03-31 08:03:29 +00002137 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00002138
2139 // Initialize the 'isa', which is just 0 or 1.
2140 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00002141 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00002142 isa = 1;
2143 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2144 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2145
2146 // Store the address of the variable into its own forwarding pointer.
2147 Builder.CreateStore(addr,
2148 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2149
2150 // Blocks ABI:
2151 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002152 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall5af02db2011-03-31 01:59:53 +00002153 BlockFlags flags;
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002154 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2155 if (ByRefHasLifetime) {
2156 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2157 else switch (ByrefLifetime) {
2158 case Qualifiers::OCL_Strong:
2159 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2160 break;
2161 case Qualifiers::OCL_Weak:
2162 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2163 break;
2164 case Qualifiers::OCL_ExplicitNone:
2165 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2166 break;
2167 case Qualifiers::OCL_None:
2168 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2169 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2170 break;
2171 default:
2172 break;
2173 }
2174 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2175 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2176 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2177 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2178 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2179 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2180 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2181 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2182 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2183 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2184 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2185 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2186 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2187 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2188 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2189 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2190 }
2191 printf("\n");
2192 }
2193 }
2194
John McCall5af02db2011-03-31 01:59:53 +00002195 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2196 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2197
John McCallf0c11f72011-03-31 08:03:29 +00002198 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2199 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00002200 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2201
John McCallf0c11f72011-03-31 08:03:29 +00002202 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00002203 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00002204 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002205
2206 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002207 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002208 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002209 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2210 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2211 llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2212 "byref.layout");
2213 // cast destination to pointer to source type.
2214 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2215 DesTy = DesTy->getPointerTo();
2216 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2217 Builder.CreateStore(ByrefLayoutInfo, BC);
2218 }
John McCall5af02db2011-03-31 01:59:53 +00002219}
2220
John McCalld16c2cf2011-02-08 08:22:06 +00002221void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002222 llvm::Value *F = CGM.getBlockObjectDispose();
John McCallbd7370a2013-02-28 19:01:20 +00002223 llvm::Value *args[] = {
2224 Builder.CreateBitCast(V, Int8PtrTy),
2225 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2226 };
2227 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump797b6322009-03-05 01:23:13 +00002228}
John McCall5af02db2011-03-31 01:59:53 +00002229
2230namespace {
2231 struct CallBlockRelease : EHScopeStack::Cleanup {
2232 llvm::Value *Addr;
2233 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2234
Stephen Hines651f13c2014-04-23 16:59:28 -07002235 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf85e1932011-06-15 23:02:42 +00002236 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002237 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2238 }
2239 };
2240}
2241
2242/// Enter a cleanup to destroy a __block variable. Note that this
2243/// cleanup should be a no-op if the variable hasn't left the stack
2244/// yet; if a cleanup is required for the variable itself, that needs
2245/// to be done externally.
2246void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2247 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002248 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002249 return;
2250
2251 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2252}
John McCall13db5cf2011-09-09 20:41:01 +00002253
2254/// Adjust the declaration of something from the blocks API.
2255static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2256 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002257 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002258
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002259 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2260 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall13db5cf2011-09-09 20:41:01 +00002261 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2262}
2263
2264llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2265 if (BlockObjectDispose)
2266 return BlockObjectDispose;
2267
2268 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2269 llvm::FunctionType *fty
2270 = llvm::FunctionType::get(VoidTy, args, false);
2271 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2272 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2273 return BlockObjectDispose;
2274}
2275
2276llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2277 if (BlockObjectAssign)
2278 return BlockObjectAssign;
2279
2280 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2281 llvm::FunctionType *fty
2282 = llvm::FunctionType::get(VoidTy, args, false);
2283 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2284 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2285 return BlockObjectAssign;
2286}
2287
2288llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2289 if (NSConcreteGlobalBlock)
2290 return NSConcreteGlobalBlock;
2291
2292 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002293 Int8PtrTy->getPointerTo(),
2294 nullptr);
John McCall13db5cf2011-09-09 20:41:01 +00002295 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2296 return NSConcreteGlobalBlock;
2297}
2298
2299llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2300 if (NSConcreteStackBlock)
2301 return NSConcreteStackBlock;
2302
2303 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002304 Int8PtrTy->getPointerTo(),
2305 nullptr);
John McCall13db5cf2011-09-09 20:41:01 +00002306 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2307 return NSConcreteStackBlock;
2308}