blob: 18e766dba53ba5f68a1aa173ae3da9d5e7a47c92 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
Anders Carlsson2437cbf2009-02-12 00:39:25 +00002//
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 McCallad7c5c12011-02-08 08:22:06 +000014#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
Mike Stump692c6e32009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000020#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Module.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000024#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000025#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000026
Anders Carlsson2437cbf2009-02-12 00:39:25 +000027using namespace clang;
28using namespace CodeGen;
29
John McCall08ef4662011-11-10 08:15:53 +000030CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
31 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000032 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
John McCall7f416cc2015-09-08 08:05:57 +000033 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
Craig Topper8a13c412014-05-21 05:09:00 +000034 DominatingIP(nullptr) {
35
John McCall08ef4662011-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 McCall9d42f0f2010-05-21 04:11:14 +000040}
41
John McCallf9b056b2011-03-31 08:03:29 +000042// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000043BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000044
John McCall351762c2011-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 McCall9d42f0f2010-05-21 04:11:14 +000049
John McCall351762c2011-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
Alp Tokerf6a24ce2013-12-05 16:25:25 +000056/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000057static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
60}
61
Fariborz Jahanianbf7bf292012-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 Gribenko6c96ba22013-05-08 23:09:44 +000066/// \code
Fariborz Jahanianbf7bf292012-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 Gribenko6c96ba22013-05-08 23:09:44 +000072/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000073/// void *block_layout_info; // encoding of captured block variables.
74/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000075/// \endcode
John McCall351762c2011-02-07 10:33:21 +000076static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
77 const CGBlockInfo &blockInfo) {
78 ASTContext &C = CGM.getContext();
79
Chris Lattner2192fe52011-07-18 04:24:23 +000080 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
Hans Wennborgdcfba332015-10-06 23:40:43 +000081 llvm::Type *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000082 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 McCall351762c2011-02-07 10:33:21 +000088
Chris Lattner0e62c1c2011-07-23 10:55:15 +000089 SmallVector<llvm::Constant*, 6> elements;
Mike Stump85284ba2009-02-13 16:19:19 +000090
91 // reserved
John McCall351762c2011-02-07 10:33:21 +000092 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stump85284ba2009-02-13 16:19:19 +000093
94 // Size
Mike Stump2ac40a92009-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 McCall351762c2011-02-07 10:33:21 +000098 elements.push_back(llvm::ConstantInt::get(ulong,
99 blockInfo.BlockSize.getQuantity()));
Mike Stump85284ba2009-02-13 16:19:19 +0000100
John McCall351762c2011-02-07 10:33:21 +0000101 // Optional copy/dispose helpers.
102 if (blockInfo.NeedsCopyDispose) {
Mike Stump85284ba2009-02-13 16:19:19 +0000103 // copy_func_helper_decl
John McCall351762c2011-02-07 10:33:21 +0000104 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000105
106 // destroy_func_decl
John McCall351762c2011-02-07 10:33:21 +0000107 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000108 }
109
John McCall351762c2011-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(
John McCall7f416cc2015-09-08 08:05:57 +0000114 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000115
John McCall351762c2011-02-07 10:33:21 +0000116 // GC layout.
Fariborz Jahanian0c58ce92012-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 McCall351762c2011-02-07 10:33:21 +0000123 else
124 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000125
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000126 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stump85284ba2009-02-13 16:19:19 +0000127
John McCall351762c2011-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 Stump85284ba2009-02-13 16:19:19 +0000132
John McCall351762c2011-02-07 10:33:21 +0000133 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000134}
135
John McCall351762c2011-02-07 10:33:21 +0000136/*
137 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000138
John McCall351762c2011-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 Stump4446dcf2009-03-05 08:32:30 +0000150
John McCall351762c2011-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 Chisnall950a9512009-11-17 19:33:30 +0000171
John McCall351762c2011-02-07 10:33:21 +0000172 /// Reserved; should be zero-initialized.
173 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000174
John McCall351762c2011-02-07 10:33:21 +0000175 /// Function pointer generated from block literal.
176 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000177
John McCall351762c2011-02-07 10:33:21 +0000178 /// Block description metadata generated from block literal.
179 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000180
John McCall351762c2011-02-07 10:33:21 +0000181 /// Captured values follow.
182 _CapturesTypes captures...;
183 };
184 */
David Chisnall950a9512009-11-17 19:33:30 +0000185
John McCall351762c2011-02-07 10:33:21 +0000186/// The number of fields in a block header.
187const unsigned BlockHeaderSize = 5;
Mike Stump4446dcf2009-03-05 08:32:30 +0000188
John McCall351762c2011-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 Jahanianc8892052013-01-17 00:25:06 +0000194 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000195 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000196 llvm::Type *Type;
Mike Stump85284ba2009-02-13 16:19:19 +0000197
John McCall351762c2011-02-07 10:33:21 +0000198 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000199 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000200 const BlockDecl::Capture *capture,
Jay Foad7c57be32011-07-11 09:56:20 +0000201 llvm::Type *type)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000202 : Alignment(align), Size(size), Lifetime(lifetime),
203 Capture(capture), Type(type) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000204
John McCall351762c2011-02-07 10:33:21 +0000205 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000206 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
207 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000208 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000209 info.CXXThisOffset = offset;
210 } else {
211 info.Captures.insert({Capture->getVariable(),
212 CGBlockInfo::Capture::makeIndex(index, offset)});
213 }
John McCall87fe5d52010-05-20 01:18:31 +0000214 }
John McCall351762c2011-02-07 10:33:21 +0000215 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000216
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000217 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
218 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000219 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000220 if (left.Alignment != right.Alignment)
221 return left.Alignment > right.Alignment;
222
223 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000224 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000225 return 1;
226 if (chunk.Lifetime == Qualifiers::OCL_Strong)
227 return 0;
228 if (chunk.Lifetime == Qualifiers::OCL_Weak)
229 return 2;
230 return 3;
231 };
232
233 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000234 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000235} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000236
John McCallb0a3ecb2011-02-08 03:07:00 +0000237/// Determines if the given type is safe for constant capture in C++.
238static bool isSafeForCXXConstantCapture(QualType type) {
239 const RecordType *recordType =
240 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
241
242 // Only records can be unsafe.
243 if (!recordType) return true;
244
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000245 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000246
247 // Maintain semantics for classes with non-trivial dtors or copy ctors.
248 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000249 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000250
251 // Otherwise, we just have to make sure there aren't any mutable
252 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000253 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000254}
255
John McCall351762c2011-02-07 10:33:21 +0000256/// It is illegal to modify a const object after initialization.
257/// Therefore, if a const object has a constant initializer, we don't
258/// actually need to keep storage for it in the block; we'll just
259/// rematerialize it at the start of the block function. This is
260/// acceptable because we make no promises about address stability of
261/// captured variables.
262static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000263 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000264 const VarDecl *var) {
265 QualType type = var->getType();
266
267 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000268 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000269
John McCallb0a3ecb2011-02-08 03:07:00 +0000270 // Furthermore, in C++ we have to worry about mutable fields:
271 // C++ [dcl.type.cv]p4:
272 // Except that any class member declared mutable can be
273 // modified, any attempt to modify a const object during its
274 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000275 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000276 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000277
278 // If the variable doesn't have any initializer (shouldn't this be
279 // invalid?), it's not clear what we should do. Maybe capture as
280 // zero?
281 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000282 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000283
Richard Smithdafff942012-01-14 04:30:29 +0000284 return CGM.EmitConstantInit(*var, CGF);
John McCall351762c2011-02-07 10:33:21 +0000285}
286
287/// Get the low bit of a nonzero character count. This is the
288/// alignment of the nth byte if the 0th byte is universally aligned.
289static CharUnits getLowBit(CharUnits v) {
290 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
291}
292
293static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000294 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall7f416cc2015-09-08 08:05:57 +0000295 // The header is basically 'struct { void *; int; int; void *; void *; }'.
296 // Assert that that struct is packed.
297 assert(CGM.getIntSize() <= CGM.getPointerSize());
298 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
299 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
John McCall351762c2011-02-07 10:33:21 +0000300
John McCall7f416cc2015-09-08 08:05:57 +0000301 info.BlockAlign = CGM.getPointerAlign();
302 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
John McCall351762c2011-02-07 10:33:21 +0000303
304 assert(elementTypes.empty());
John McCall7f416cc2015-09-08 08:05:57 +0000305 elementTypes.push_back(CGM.VoidPtrTy);
306 elementTypes.push_back(CGM.IntTy);
307 elementTypes.push_back(CGM.IntTy);
308 elementTypes.push_back(CGM.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000309 elementTypes.push_back(CGM.getBlockDescriptorType());
310
311 assert(elementTypes.size() == BlockHeaderSize);
312}
313
314/// Compute the layout of the given block. Attempts to lay the block
315/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000316static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
317 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000318 ASTContext &C = CGM.getContext();
319 const BlockDecl *block = info.getBlockDecl();
320
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000322 initializeForBlockHeader(CGM, info, elementTypes);
323
324 if (!block->hasCaptures()) {
325 info.StructureType =
326 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
327 info.CanBeGlobal = true;
328 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000329 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000330 else if (C.getLangOpts().ObjC1 &&
331 CGM.getLangOpts().getGC() == LangOptions::NonGC)
332 info.HasCapturedVariableLayout = true;
333
John McCall351762c2011-02-07 10:33:21 +0000334 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000335 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000336 layout.reserve(block->capturesCXXThis() +
337 (block->capture_end() - block->capture_begin()));
338
339 CharUnits maxFieldAlign;
340
341 // First, 'this'.
342 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000343 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
344 "Can't capture 'this' outside a method");
345 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000346
John McCall7f416cc2015-09-08 08:05:57 +0000347 // Theoretically, this could be in a different address space, so
348 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000349 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000350 std::pair<CharUnits,CharUnits> tinfo
351 = CGM.getContext().getTypeInfoInChars(thisType);
352 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
353
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000354 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
355 Qualifiers::OCL_None,
Craig Topper8a13c412014-05-21 05:09:00 +0000356 nullptr, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000357 }
358
359 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000360 for (const auto &CI : block->captures()) {
361 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000362
Aaron Ballman9371dd22014-03-14 18:34:04 +0000363 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000364 // We have to copy/dispose of the __block reference.
365 info.NeedsCopyDispose = true;
366
John McCall351762c2011-02-07 10:33:21 +0000367 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000368 CharUnits align = CGM.getPointerAlign();
369 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000370
John McCall7f416cc2015-09-08 08:05:57 +0000371 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
372 Qualifiers::OCL_None, &CI,
373 CGM.VoidPtrTy));
John McCall351762c2011-02-07 10:33:21 +0000374 continue;
375 }
376
377 // Otherwise, build a layout chunk with the size and alignment of
378 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000379 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000380 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
381 continue;
382 }
383
John McCall31168b02011-06-15 23:02:42 +0000384 // If we have a lifetime qualifier, honor it for capture purposes.
385 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000386 Qualifiers::ObjCLifetime lifetime =
387 variable->getType().getObjCLifetime();
388 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000389 switch (lifetime) {
390 case Qualifiers::OCL_None: llvm_unreachable("impossible");
391 case Qualifiers::OCL_ExplicitNone:
392 case Qualifiers::OCL_Autoreleasing:
393 break;
John McCall351762c2011-02-07 10:33:21 +0000394
John McCall31168b02011-06-15 23:02:42 +0000395 case Qualifiers::OCL_Strong:
396 case Qualifiers::OCL_Weak:
397 info.NeedsCopyDispose = true;
398 }
399
400 // Block pointers require copy/dispose. So do Objective-C pointers.
401 } else if (variable->getType()->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +0000402 info.NeedsCopyDispose = true;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000403 // used for mrr below.
404 lifetime = Qualifiers::OCL_Strong;
John McCall351762c2011-02-07 10:33:21 +0000405
406 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000407 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000408 info.NeedsCopyDispose = true;
409 info.HasCXXObject = true;
410
411 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000412 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000413 if (const CXXRecordDecl *record =
414 variable->getType()->getAsCXXRecordDecl()) {
415 if (!record->hasTrivialDestructor()) {
416 info.HasCXXObject = true;
417 info.NeedsCopyDispose = true;
418 }
419 }
420 }
421
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000422 QualType VT = variable->getType();
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000423 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000424 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000425
John McCall351762c2011-02-07 10:33:21 +0000426 maxFieldAlign = std::max(maxFieldAlign, align);
427
Jay Foad7c57be32011-07-11 09:56:20 +0000428 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000429 CGM.getTypes().ConvertTypeForMem(VT);
430
Aaron Ballman9371dd22014-03-14 18:34:04 +0000431 layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000432 }
433
434 // If that was everything, we're done here.
435 if (layout.empty()) {
436 info.StructureType =
437 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
438 info.CanBeGlobal = true;
439 return;
440 }
441
442 // Sort the layout by alignment. We have to use a stable sort here
443 // to get reproducible results. There should probably be an
444 // llvm::array_pod_stable_sort.
445 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000446
447 // Needed for blocks layout info.
448 info.BlockHeaderForcedGapOffset = info.BlockSize;
449 info.BlockHeaderForcedGapSize = CharUnits::Zero();
450
John McCall351762c2011-02-07 10:33:21 +0000451 CharUnits &blockSize = info.BlockSize;
452 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
453
454 // Assuming that the first byte in the header is maximally aligned,
455 // get the alignment of the first byte following the header.
456 CharUnits endAlign = getLowBit(blockSize);
457
458 // If the end of the header isn't satisfactorily aligned for the
459 // maximum thing, look for things that are okay with the header-end
460 // alignment, and keep appending them until we get something that's
461 // aligned right. This algorithm is only guaranteed optimal if
462 // that condition is satisfied at some point; otherwise we can get
463 // things like:
464 // header // next byte has alignment 4
465 // something_with_size_5; // next byte has alignment 1
466 // something_with_alignment_8;
467 // which has 7 bytes of padding, as opposed to the naive solution
468 // which might have less (?).
469 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000470 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000471 li = layout.begin() + 1, le = layout.end();
472
473 // Look for something that the header end is already
474 // satisfactorily aligned for.
475 for (; li != le && endAlign < li->Alignment; ++li)
476 ;
477
478 // If we found something that's naturally aligned for the end of
479 // the header, keep adding things...
480 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000481 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000482 for (; li != le; ++li) {
483 assert(endAlign >= li->Alignment);
484
John McCall7f416cc2015-09-08 08:05:57 +0000485 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000486 elementTypes.push_back(li->Type);
487 blockSize += li->Size;
488 endAlign = getLowBit(blockSize);
489
490 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000491 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000492 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000493 }
John McCall351762c2011-02-07 10:33:21 +0000494 }
John McCall351762c2011-02-07 10:33:21 +0000495 // Don't re-append everything we just appended.
496 layout.erase(first, li);
497 }
498 }
499
John McCallac0350a2012-04-26 21:14:42 +0000500 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000501
John McCall351762c2011-02-07 10:33:21 +0000502 // At this point, we just have to add padding if the end align still
503 // isn't aligned right.
504 if (endAlign < maxFieldAlign) {
John McCallac0350a2012-04-26 21:14:42 +0000505 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
506 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000507
John McCall7f416cc2015-09-08 08:05:57 +0000508 // If we haven't yet added any fields, remember that there was an
509 // initial gap; this need to go into the block layout bit map.
510 if (blockSize == info.BlockHeaderForcedGapOffset) {
511 info.BlockHeaderForcedGapSize = padding;
512 }
513
John McCalle3dc1702011-02-15 09:22:45 +0000514 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
515 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000516 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000517 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000518 }
519
John McCall1db0a2f2012-05-01 20:28:00 +0000520 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000521 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000522 // Slam everything else on now. This works because they have
523 // strictly decreasing alignment and we expect that size is always a
524 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000525 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000526 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000527 if (endAlign < li->Alignment) {
528 // size may not be multiple of alignment. This can only happen with
529 // an over-aligned variable. We will be adding a padding field to
530 // make the size be multiple of alignment.
531 CharUnits padding = li->Alignment - endAlign;
532 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
533 padding.getQuantity()));
534 blockSize += padding;
535 endAlign = getLowBit(blockSize);
536 }
John McCall351762c2011-02-07 10:33:21 +0000537 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000538 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000539 elementTypes.push_back(li->Type);
540 blockSize += li->Size;
541 endAlign = getLowBit(blockSize);
542 }
543
544 info.StructureType =
545 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
546}
547
John McCall08ef4662011-11-10 08:15:53 +0000548/// Enter the scope of a block. This should be run at the entrance to
549/// a full-expression so that the block's cleanups are pushed at the
550/// right place in the stack.
551static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000552 assert(CGF.HaveInsertPoint());
553
John McCall08ef4662011-11-10 08:15:53 +0000554 // Allocate the block info and place it at the head of the list.
555 CGBlockInfo &blockInfo =
556 *new CGBlockInfo(block, CGF.CurFn->getName());
557 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
558 CGF.FirstBlockInfo = &blockInfo;
559
560 // Compute information about the layout, etc., of this block,
561 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000562 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000563
564 // Nothing else to do if it can be global.
565 if (blockInfo.CanBeGlobal) return;
566
567 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000568 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
569 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000570
571 // If there are cleanups to emit, enter them (but inactive).
572 if (!blockInfo.NeedsCopyDispose) return;
573
574 // Walk through the captures (in order) and find the ones not
575 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000576 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000577 // Ignore __block captures; there's nothing special in the
578 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000579 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000580
581 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000582 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000583 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
584 if (capture.isConstant()) continue;
585
586 // Ignore objects that aren't destructed.
587 QualType::DestructionKind dtorKind =
588 variable->getType().isDestructedType();
589 if (dtorKind == QualType::DK_none) continue;
590
591 CodeGenFunction::Destroyer *destroyer;
592
593 // Block captures count as local values and have imprecise semantics.
594 // They also can't be arrays, so need to worry about that.
595 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000596 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000597 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000598 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000599 }
600
601 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000602 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
603 capture.getIndex(),
604 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000605
John McCallf4beacd2011-11-10 10:43:54 +0000606 // We can use that GEP as the dominating IP.
607 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000608 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000609
John McCall08ef4662011-11-10 08:15:53 +0000610 CleanupKind cleanupKind = InactiveNormalCleanup;
611 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
612 if (useArrayEHCleanup)
613 cleanupKind = InactiveNormalAndEHCleanup;
614
615 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne1425b452012-01-26 03:33:36 +0000616 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000617
618 // Remember where that cleanup was.
619 capture.setCleanup(CGF.EHStack.stable_begin());
620 }
621}
622
623/// Enter a full-expression with a non-trivial number of objects to
624/// clean up. This is in this file because, at the moment, the only
625/// kind of cleanup object is a BlockDecl*.
626void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
627 assert(E->getNumObjects() != 0);
628 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
629 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
630 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
631 enterBlockScope(*this, *i);
632 }
633}
634
635/// Find the layout for the given block in a linked list and remove it.
636static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
637 const BlockDecl *block) {
638 while (true) {
639 assert(head && *head);
640 CGBlockInfo *cur = *head;
641
642 // If this is the block we're looking for, splice it out of the list.
643 if (cur->getBlockDecl() == block) {
644 *head = cur->NextBlockInfo;
645 return cur;
646 }
647
648 head = &cur->NextBlockInfo;
649 }
650}
651
652/// Destroy a chain of block layouts.
653void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
654 assert(head && "destroying an empty chain");
655 do {
656 CGBlockInfo *cur = head;
657 head = cur->NextBlockInfo;
658 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000659 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000660}
661
John McCall351762c2011-02-07 10:33:21 +0000662/// Emit a block literal expression in the current function.
663llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000664 // If the block has no captures, we won't have a pre-computed
665 // layout for it.
666 if (!blockExpr->getBlockDecl()->hasCaptures()) {
667 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000668 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000669 blockInfo.BlockExpression = blockExpr;
670 return EmitBlockLiteral(blockInfo);
671 }
John McCall351762c2011-02-07 10:33:21 +0000672
John McCall08ef4662011-11-10 08:15:53 +0000673 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000674 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000675 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
676 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000677
John McCall08ef4662011-11-10 08:15:53 +0000678 blockInfo->BlockExpression = blockExpr;
679 return EmitBlockLiteral(*blockInfo);
680}
681
682llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
683 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000684 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall351762c2011-02-07 10:33:21 +0000685 llvm::Constant *blockFn
Fariborz Jahanian63628032012-06-26 16:06:38 +0000686 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCalldec348f72013-05-03 07:33:41 +0000687 LocalDeclMap,
688 isLambdaConv);
John McCalle3dc1702011-02-15 09:22:45 +0000689 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000690
691 // If there is nothing to capture, we can emit this as a global block.
692 if (blockInfo.CanBeGlobal)
693 return buildGlobalBlock(CGM, blockInfo, blockFn);
694
695 // Otherwise, we have to emit this as a local block.
696
697 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCalle3dc1702011-02-15 09:22:45 +0000698 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000699
700 // Build the block descriptor.
701 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
702
John McCall7f416cc2015-09-08 08:05:57 +0000703 Address blockAddr = blockInfo.LocalAddress;
704 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000705
706 // Compute the initial on-stack block flags.
John McCallad7c5c12011-02-08 08:22:06 +0000707 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000708 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall351762c2011-02-07 10:33:21 +0000709 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
710 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall85915252011-03-09 08:39:33 +0000711 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +0000712
John McCall7f416cc2015-09-08 08:05:57 +0000713 auto projectField =
714 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
715 return Builder.CreateStructGEP(blockAddr, index, offset, name);
716 };
717 auto storeField =
718 [&](llvm::Value *value, unsigned index, CharUnits offset,
719 const Twine &name) {
720 Builder.CreateStore(value, projectField(index, offset, name));
721 };
722
723 // Initialize the block header.
724 {
725 // We assume all the header fields are densely packed.
726 unsigned index = 0;
727 CharUnits offset;
728 auto addHeaderField =
729 [&](llvm::Value *value, CharUnits size, const Twine &name) {
730 storeField(value, index, offset, name);
731 offset += size;
732 index++;
733 };
734
735 addHeaderField(isa, getPointerSize(), "block.isa");
736 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
737 getIntSize(), "block.flags");
738 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
739 getIntSize(), "block.reserved");
740 addHeaderField(blockFn, getPointerSize(), "block.invoke");
741 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
742 }
John McCall351762c2011-02-07 10:33:21 +0000743
744 // Finally, capture all the values into the block.
745 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
746
747 // First, 'this'.
748 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000749 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
750 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000751 Builder.CreateStore(LoadCXXThis(), addr);
752 }
753
754 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000755 for (const auto &CI : blockDecl->captures()) {
756 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000757 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
758
759 // Ignore constant captures.
760 if (capture.isConstant()) continue;
761
762 QualType type = variable->getType();
763
764 // This will be a [[type]]*, except that a byref entry will just be
765 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000766 Address blockField =
767 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000768
769 // Compute the address of the thing we're going to move into the
770 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000771 Address src = Address::invalid();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000772 if (BlockInfo && CI.isNested()) {
John McCall351762c2011-02-07 10:33:21 +0000773 // We need to use the capture from the enclosing block.
774 const CGBlockInfo::Capture &enclosingCapture =
775 BlockInfo->getCapture(variable);
776
777 // This is a [[type]]*, except that a byref entry wil just be an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000778 src = Builder.CreateStructGEP(LoadBlockStruct(),
John McCall351762c2011-02-07 10:33:21 +0000779 enclosingCapture.getIndex(),
John McCall7f416cc2015-09-08 08:05:57 +0000780 enclosingCapture.getOffset(),
John McCall351762c2011-02-07 10:33:21 +0000781 "block.capture.addr");
Eli Friedman98b01ed2012-03-01 04:01:32 +0000782 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000783 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000784 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000785 src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000786 } else {
John McCalla37c2fa2013-03-04 06:32:36 +0000787 // Just look it up in the locals map, which will give us back a
788 // [[type]]*. If that doesn't work, do the more elaborate DRE
789 // emission.
John McCall7f416cc2015-09-08 08:05:57 +0000790 auto it = LocalDeclMap.find(variable);
791 if (it != LocalDeclMap.end()) {
792 src = it->second;
793 } else {
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000794 DeclRefExpr declRef(
795 const_cast<VarDecl *>(variable),
796 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
797 VK_LValue, SourceLocation());
John McCalla37c2fa2013-03-04 06:32:36 +0000798 src = EmitDeclRefLValue(&declRef).getAddress();
799 }
John McCall351762c2011-02-07 10:33:21 +0000800 }
801
802 // For byrefs, we just write the pointer to the byref struct into
803 // the block field. There's no need to chase the forwarding
804 // pointer at this point, since we're building something that will
805 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000806 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000807 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000808 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000809 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000810 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000811 else
John McCall7f416cc2015-09-08 08:05:57 +0000812 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000813
John McCalle3dc1702011-02-15 09:22:45 +0000814 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000815 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000816
817 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000818 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000819 if (blockDecl->isConversionFromLambda()) {
820 // If we have a lambda conversion, emit the expression
821 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000822 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000823 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000824 AggValueSlot::IsDestructed,
825 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000826 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000827 EmitAggExpr(copyExpr, Slot);
828 } else {
829 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
830 }
John McCall351762c2011-02-07 10:33:21 +0000831
832 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000833 } else if (type->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +0000834 llvm::Value *ref = Builder.CreateLoad(src, "ref.val");
835 Builder.CreateStore(ref, blockField);
John McCall4d14a902013-04-08 23:27:49 +0000836
837 // If this is an ARC __strong block-pointer variable, don't do a
838 // block copy.
839 //
840 // TODO: this can be generalized into the normal initialization logic:
841 // we should never need to do a block-copy when initializing a local
842 // variable, because the local variable's lifetime should be strictly
843 // contained within the stack block's.
844 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
845 type->isBlockPointerType()) {
846 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000847 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000848 value = EmitARCRetainNonBlock(value);
849
850 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000851 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000852
853 // Otherwise, fake up a POD copy into the block field.
854 } else {
John McCall31168b02011-06-15 23:02:42 +0000855 // Fake up a new variable so that EmitScalarInit doesn't think
856 // we're referring to the variable in its own initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000857 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
858 SourceLocation(), /*name*/ nullptr,
859 type);
John McCall31168b02011-06-15 23:02:42 +0000860
John McCall93be3f72011-02-07 18:37:40 +0000861 // We use one of these or the other depending on whether the
862 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000863 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
864 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
865 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000866
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000867 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000868 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000869 // FIXME: Pass a specific location for the expr init so that the store is
870 // attributed to a reasonable location - otherwise it may be attributed to
871 // locations of subexpressions in the initialization.
John McCall1553b192011-06-16 04:16:24 +0000872 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall7f416cc2015-09-08 08:05:57 +0000873 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +0000874 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000875 }
876
John McCall08ef4662011-11-10 08:15:53 +0000877 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000878 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000879 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
880 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000881 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000882 }
John McCall351762c2011-02-07 10:33:21 +0000883 }
884
885 // Cast to the converted block-pointer type, which happens (somewhat
886 // unfortunately) to be a pointer to function type.
887 llvm::Value *result =
John McCall7f416cc2015-09-08 08:05:57 +0000888 Builder.CreateBitCast(blockAddr.getPointer(),
John McCall351762c2011-02-07 10:33:21 +0000889 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +0000890
John McCall351762c2011-02-07 10:33:21 +0000891 return result;
Mike Stump85284ba2009-02-13 16:19:19 +0000892}
893
894
Chris Lattnera5f58b02011-07-09 17:41:47 +0000895llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +0000896 if (BlockDescriptorType)
897 return BlockDescriptorType;
898
Chris Lattnera5f58b02011-07-09 17:41:47 +0000899 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000900 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000901
Mike Stump650c9322009-02-13 15:16:56 +0000902 // struct __block_descriptor {
903 // unsigned long reserved;
904 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +0000905 //
906 // // later, the following will be added
907 //
908 // struct {
909 // void (*copyHelper)();
910 // void (*copyHelper)();
911 // } helpers; // !!! optional
912 //
913 // const char *signature; // the block signature
914 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +0000915 // };
Chris Lattner845511f2011-06-18 22:49:11 +0000916 BlockDescriptorType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000917 llvm::StructType::create("struct.__block_descriptor",
Reid Kleckneree7cf842014-12-01 22:02:27 +0000918 UnsignedLongTy, UnsignedLongTy, nullptr);
Mike Stump650c9322009-02-13 15:16:56 +0000919
John McCall351762c2011-02-07 10:33:21 +0000920 // Now form a pointer to that.
921 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stump650c9322009-02-13 15:16:56 +0000922 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000923}
924
Chris Lattnera5f58b02011-07-09 17:41:47 +0000925llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +0000926 if (GenericBlockLiteralType)
927 return GenericBlockLiteralType;
928
Chris Lattnera5f58b02011-07-09 17:41:47 +0000929 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000930
Mike Stump005c9a62009-02-13 15:25:34 +0000931 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000932 // void *__isa;
933 // int __flags;
934 // int __reserved;
935 // void (*__invoke)(void *);
936 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000937 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000938 GenericBlockLiteralType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000939 llvm::StructType::create("struct.__block_literal_generic",
940 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +0000941 BlockDescPtrTy, nullptr);
Mike Stumpb7074c02009-02-13 15:32:32 +0000942
Mike Stump005c9a62009-02-13 15:25:34 +0000943 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000944}
945
Nick Lewycky2d84e842013-10-02 02:29:49 +0000946RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +0000947 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000948 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000949 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +0000950
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000951 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
952
953 // Get a pointer to the generic block literal.
Chris Lattner2192fe52011-07-18 04:24:23 +0000954 llvm::Type *BlockLiteralTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000955 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000956
957 // Bitcast the callee to a block literal.
Mike Stumpb7074c02009-02-13 15:32:32 +0000958 llvm::Value *BlockLiteral =
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000959 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
960
961 // Get the function pointer from the literal.
John McCall7f416cc2015-09-08 08:05:57 +0000962 llvm::Value *FuncPtr =
963 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000964
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000965 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000966
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000967 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000968 CallArgList Args;
John McCall9dc0db22011-05-15 01:53:33 +0000969 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000970
Anders Carlsson479e6fc2009-04-08 23:13:16 +0000971 QualType FnType = BPT->getPointeeType();
972
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000973 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +0000974 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +0000975
Anders Carlsson5f50c652009-04-07 22:10:22 +0000976 // Load the function.
John McCall7f416cc2015-09-08 08:05:57 +0000977 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +0000978
John McCall85915252011-03-09 08:39:33 +0000979 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +0000980 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +0000981 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +0000982
Anders Carlsson5f50c652009-04-07 22:10:22 +0000983 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +0000984 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattner2192fe52011-07-18 04:24:23 +0000986 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson5f50c652009-04-07 22:10:22 +0000987 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000988
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000989 // And call the block.
Anders Carlssonbfb36712009-12-24 21:13:40 +0000990 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000991}
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000992
John McCall7f416cc2015-09-08 08:05:57 +0000993Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
994 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +0000995 assert(BlockInfo && "evaluating block ref without block information?");
996 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +0000997
John McCall351762c2011-02-07 10:33:21 +0000998 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +0000999 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001000
John McCall7f416cc2015-09-08 08:05:57 +00001001 Address addr =
1002 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1003 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001004
John McCall351762c2011-02-07 10:33:21 +00001005 if (isByRef) {
1006 // addr should be a void** right now. Load, then cast the result
1007 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001008
John McCall7f416cc2015-09-08 08:05:57 +00001009 auto &byrefInfo = getBlockByrefInfo(variable);
1010 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001011
John McCall7f416cc2015-09-08 08:05:57 +00001012 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1013 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001014
John McCall7f416cc2015-09-08 08:05:57 +00001015 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1016 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001017 }
1018
John McCall7f416cc2015-09-08 08:05:57 +00001019 if (auto refType = variable->getType()->getAs<ReferenceType>()) {
1020 addr = EmitLoadOfReference(addr, refType);
1021 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00001022
John McCall351762c2011-02-07 10:33:21 +00001023 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001024}
1025
Mike Stump2d5a2872009-02-14 22:16:35 +00001026llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001027CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCalle3dc1702011-02-15 09:22:45 +00001028 const char *name) {
John McCall08ef4662011-11-10 08:15:53 +00001029 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1030 blockInfo.BlockExpression = blockExpr;
Mike Stumpb7074c02009-02-13 15:32:32 +00001031
John McCall351762c2011-02-07 10:33:21 +00001032 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001033 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001034
John McCall351762c2011-02-07 10:33:21 +00001035 // Using that metadata, generate the actual block function.
1036 llvm::Constant *blockFn;
1037 {
John McCall7f416cc2015-09-08 08:05:57 +00001038 CodeGenFunction::DeclMapTy LocalDeclMap;
John McCallad7c5c12011-02-08 08:22:06 +00001039 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1040 blockInfo,
John McCalldec348f72013-05-03 07:33:41 +00001041 LocalDeclMap,
Eli Friedman2495ab02012-02-25 02:48:22 +00001042 false);
John McCall351762c2011-02-07 10:33:21 +00001043 }
John McCalle3dc1702011-02-15 09:22:45 +00001044 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001045
John McCallad7c5c12011-02-08 08:22:06 +00001046 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001047}
1048
John McCall351762c2011-02-07 10:33:21 +00001049static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1050 const CGBlockInfo &blockInfo,
1051 llvm::Constant *blockFn) {
1052 assert(blockInfo.CanBeGlobal);
1053
1054 // Generate the constants for the block literal initializer.
1055 llvm::Constant *fields[BlockHeaderSize];
1056
1057 // isa
1058 fields[0] = CGM.getNSConcreteGlobalBlock();
1059
1060 // __flags
John McCall85915252011-03-09 08:39:33 +00001061 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1062 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1063
John McCalle3dc1702011-02-15 09:22:45 +00001064 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall351762c2011-02-07 10:33:21 +00001065
1066 // Reserved
John McCalle3dc1702011-02-15 09:22:45 +00001067 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall351762c2011-02-07 10:33:21 +00001068
1069 // Function
1070 fields[3] = blockFn;
1071
1072 // Descriptor
1073 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1074
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001075 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall351762c2011-02-07 10:33:21 +00001076
1077 llvm::GlobalVariable *literal =
1078 new llvm::GlobalVariable(CGM.getModule(),
1079 init->getType(),
1080 /*constant*/ true,
1081 llvm::GlobalVariable::InternalLinkage,
1082 init,
1083 "__block_literal_global");
1084 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1085
1086 // Return a constant of the appropriately-casted type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001087 llvm::Type *requiredType =
John McCall351762c2011-02-07 10:33:21 +00001088 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1089 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001090}
1091
John McCall7f416cc2015-09-08 08:05:57 +00001092void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1093 unsigned argNum,
1094 llvm::Value *arg) {
1095 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1096
1097 llvm::Value *localAddr = nullptr;
1098 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1099 // Allocate a stack slot to let the debug info survive the RA.
1100 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1101 Builder.CreateStore(arg, alloc);
1102 localAddr = Builder.CreateLoad(alloc);
1103 }
1104
1105 if (CGDebugInfo *DI = getDebugInfo()) {
1106 if (CGM.getCodeGenOpts().getDebugInfo()
1107 >= CodeGenOptions::LimitedDebugInfo) {
1108 DI->setLocation(D->getLocation());
1109 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1110 localAddr, Builder);
1111 }
1112 }
1113
1114 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1115 ApplyDebugLocation Scope(*this, StartLoc);
1116
1117 // Instead of messing around with LocalDeclMap, just set the value
1118 // directly as BlockPointer.
1119 BlockPointer = Builder.CreateBitCast(arg,
1120 BlockInfo->StructureType->getPointerTo(),
1121 "block");
1122}
1123
1124Address CodeGenFunction::LoadBlockStruct() {
1125 assert(BlockInfo && "not in a block invocation function!");
1126 assert(BlockPointer && "no block pointer set!");
1127 return Address(BlockPointer, BlockInfo->BlockAlign);
1128}
1129
Mike Stump4446dcf2009-03-05 08:32:30 +00001130llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001131CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1132 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001133 const DeclMapTy &ldm,
1134 bool IsLambdaConversionToBlock) {
John McCall351762c2011-02-07 10:33:21 +00001135 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001136
Fariborz Jahanian63628032012-06-26 16:06:38 +00001137 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001138
1139 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001140
John McCall351762c2011-02-07 10:33:21 +00001141 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001142
Mike Stump5469f292009-03-13 23:34:28 +00001143 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001144 // to be local to this function as well, in case they're directly
1145 // referenced in a block.
1146 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001147 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001148 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001149 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001150 }
1151
John McCall351762c2011-02-07 10:33:21 +00001152 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001153
John McCall351762c2011-02-07 10:33:21 +00001154 // Build the argument list.
1155 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001156
John McCall351762c2011-02-07 10:33:21 +00001157 // The first argument is the block pointer. Just take it as a void*
1158 // and cast it later.
1159 QualType selfTy = getContext().VoidPtrTy;
Mike Stump7fe9cc12009-10-21 03:49:08 +00001160 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001161
Richard Smith053f6c62014-05-16 23:01:30 +00001162 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
John McCall147d0212011-02-22 22:38:33 +00001163 SourceLocation(), II, selfTy);
John McCalla738c252011-03-09 04:27:21 +00001164 args.push_back(&selfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001165
John McCall351762c2011-02-07 10:33:21 +00001166 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001167 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001168
John McCall351762c2011-02-07 10:33:21 +00001169 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001170 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
Reid Kleckner4982b822014-01-31 22:54:50 +00001171 const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
Alp Toker314cc812014-01-25 16:55:45 +00001172 fnType->getReturnType(), args, fnType->getExtInfo(),
1173 fnType->isVariadic());
Tim Northovere77cc392014-03-29 13:28:05 +00001174 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001175 blockInfo.UsesStret = true;
1176
John McCalla729c622012-02-17 03:33:10 +00001177 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001178
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001179 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001180 llvm::Function *fn = llvm::Function::Create(
1181 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001182 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001183
John McCall351762c2011-02-07 10:33:21 +00001184 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001185 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001186 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001187 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001188
John McCall147d0212011-02-22 22:38:33 +00001189 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001190
Adrian Prantl0f6df002013-03-29 19:20:35 +00001191 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1192 // won't delete the dbg.declare intrinsics for captured variables.
1193 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1194 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1195 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001196 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1197 getPointerAlign(),
1198 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001199 // Set the DebugLocation to empty, so the store is recognized as a
1200 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001201 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001202 Builder.CreateStore(BlockPointer, Alloca);
1203 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001204 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001205
John McCall87fe5d52010-05-20 01:18:31 +00001206 // If we have a C++ 'this' reference, go ahead and force it into
1207 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001208 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001209 Address addr =
1210 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1211 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001212 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001213 }
1214
John McCall351762c2011-02-07 10:33:21 +00001215 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001216 for (const auto &CI : blockDecl->captures()) {
1217 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001218 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1219 if (!capture.isConstant()) continue;
1220
John McCall7f416cc2015-09-08 08:05:57 +00001221 CharUnits align = getContext().getDeclAlign(variable);
1222 Address alloca =
1223 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001224
John McCall7f416cc2015-09-08 08:05:57 +00001225 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001226
John McCall7f416cc2015-09-08 08:05:57 +00001227 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001228 }
1229
John McCall113bee02012-03-10 09:33:50 +00001230 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001231 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1232 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1233 --entry_ptr;
1234
Eli Friedman2495ab02012-02-25 02:48:22 +00001235 if (IsLambdaConversionToBlock)
1236 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001237 else {
1238 PGO.assignRegionCounters(blockDecl, fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001239 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001240 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001241 }
Mike Stump017460a2009-10-01 22:29:41 +00001242
Mike Stump7d699112009-10-01 00:27:30 +00001243 // Remember where we were...
1244 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001245
Mike Stump7d699112009-10-01 00:27:30 +00001246 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001247 ++entry_ptr;
1248 Builder.SetInsertPoint(entry, entry_ptr);
1249
John McCall113bee02012-03-10 09:33:50 +00001250 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001251 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001252 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001253 for (const auto &CI : blockDecl->captures()) {
1254 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001255 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001256
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001257 if (CGM.getCodeGenOpts().getDebugInfo()
1258 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001259 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1260 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001261 auto addr = LocalDeclMap.find(variable)->second;
1262 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Alexey Samsonov74a38682012-05-04 07:39:27 +00001263 Builder);
1264 continue;
1265 }
John McCall351762c2011-02-07 10:33:21 +00001266
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001267 DI->EmitDeclareOfBlockDeclRefVariable(
1268 variable, BlockPointerDbgLoc, Builder, blockInfo,
1269 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001270 }
Mike Stump2e722b92009-09-30 02:43:10 +00001271 }
Manman Renab08a9a2013-01-04 18:51:35 +00001272 // Recover location if it was changed in the above loop.
1273 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001274 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001275 }
John McCall351762c2011-02-07 10:33:21 +00001276
Mike Stump7d699112009-10-01 00:27:30 +00001277 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001278 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001279 Builder.ClearInsertionPoint();
1280 else
1281 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001282
John McCall351762c2011-02-07 10:33:21 +00001283 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001284
John McCall351762c2011-02-07 10:33:21 +00001285 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001286}
Mike Stump1db7d042009-02-28 09:07:16 +00001287
John McCall351762c2011-02-07 10:33:21 +00001288/*
1289 notes.push_back(HelperInfo());
1290 HelperInfo &note = notes.back();
1291 note.index = capture.getIndex();
1292 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1293 note.cxxbar_import = ci->getCopyExpr();
Mike Stump1db7d042009-02-28 09:07:16 +00001294
John McCall351762c2011-02-07 10:33:21 +00001295 if (ci->isByRef()) {
1296 note.flag = BLOCK_FIELD_IS_BYREF;
1297 if (type.isObjCGCWeak())
1298 note.flag |= BLOCK_FIELD_IS_WEAK;
1299 } else if (type->isBlockPointerType()) {
1300 note.flag = BLOCK_FIELD_IS_BLOCK;
1301 } else {
1302 note.flag = BLOCK_FIELD_IS_OBJECT;
1303 }
1304 */
Mike Stump1db7d042009-02-28 09:07:16 +00001305
John McCallf593b102013-01-22 03:56:22 +00001306/// Generate the copy-helper function for a block closure object:
1307/// static void block_copy_helper(block_t *dst, block_t *src);
1308/// The runtime will have previously initialized 'dst' by doing a
1309/// bit-copy of 'src'.
1310///
1311/// Note that this copies an entire block closure object to the heap;
1312/// it should not be confused with a 'byref copy helper', which moves
1313/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001314llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001315CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001316 ASTContext &C = getContext();
1317
1318 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001319 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1320 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001321 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001322 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1323 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001324 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001325
Reid Kleckner4982b822014-01-31 22:54:50 +00001326 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1327 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stump0c743272009-03-06 01:33:24 +00001328
John McCall351762c2011-02-07 10:33:21 +00001329 // FIXME: it would be nice if these were mergeable with things with
1330 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001331 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001332
1333 llvm::Function *Fn =
1334 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001335 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001336
1337 IdentifierInfo *II
1338 = &CGM.getContext().Idents.get("__copy_helper_block_");
1339
John McCall351762c2011-02-07 10:33:21 +00001340 FunctionDecl *FD = FunctionDecl::Create(C,
1341 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001342 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001343 SourceLocation(), II, C.VoidTy,
1344 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001345 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001346 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001347
1348 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1349
Adrian Prantl95b24e92015-02-03 20:00:54 +00001350 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001351 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001352 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001353 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001354 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001355
John McCall7f416cc2015-09-08 08:05:57 +00001356 Address src = GetAddrOfLocalVar(&srcDecl);
1357 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001358 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001359
John McCall7f416cc2015-09-08 08:05:57 +00001360 Address dst = GetAddrOfLocalVar(&dstDecl);
1361 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001362 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001363
John McCall351762c2011-02-07 10:33:21 +00001364 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001365
Aaron Ballman9371dd22014-03-14 18:34:04 +00001366 for (const auto &CI : blockDecl->captures()) {
1367 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001368 QualType type = variable->getType();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001369
John McCall351762c2011-02-07 10:33:21 +00001370 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1371 if (capture.isConstant()) continue;
1372
Aaron Ballman9371dd22014-03-14 18:34:04 +00001373 const Expr *copyExpr = CI.getCopyExpr();
John McCall31168b02011-06-15 23:02:42 +00001374 BlockFieldFlags flags;
1375
John McCalle68b8f42012-10-17 02:28:37 +00001376 bool useARCWeakCopy = false;
1377 bool useARCStrongCopy = false;
John McCall351762c2011-02-07 10:33:21 +00001378
1379 if (copyExpr) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001380 assert(!CI.isByRef());
John McCall351762c2011-02-07 10:33:21 +00001381 // don't bother computing flags
John McCall31168b02011-06-15 23:02:42 +00001382
Aaron Ballman9371dd22014-03-14 18:34:04 +00001383 } else if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001384 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001385 if (type.isObjCGCWeak())
1386 flags |= BLOCK_FIELD_IS_WEAK;
John McCall351762c2011-02-07 10:33:21 +00001387
John McCall31168b02011-06-15 23:02:42 +00001388 } else if (type->isObjCRetainableType()) {
1389 flags = BLOCK_FIELD_IS_OBJECT;
John McCalle68b8f42012-10-17 02:28:37 +00001390 bool isBlockPointer = type->isBlockPointerType();
1391 if (isBlockPointer)
John McCall31168b02011-06-15 23:02:42 +00001392 flags = BLOCK_FIELD_IS_BLOCK;
1393
1394 // Special rules for ARC captures:
John McCall460ce582015-10-22 18:38:17 +00001395 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001396
John McCall460ce582015-10-22 18:38:17 +00001397 // We need to register __weak direct captures with the runtime.
1398 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1399 useARCWeakCopy = true;
John McCall31168b02011-06-15 23:02:42 +00001400
John McCall460ce582015-10-22 18:38:17 +00001401 // We need to retain the copied value for __strong direct captures.
1402 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1403 // If it's a block pointer, we have to copy the block and
1404 // assign that to the destination pointer, so we might as
1405 // well use _Block_object_assign. Otherwise we can avoid that.
1406 if (!isBlockPointer)
1407 useARCStrongCopy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001408
1409 // Non-ARC captures of retainable pointers are strong and
1410 // therefore require a call to _Block_object_assign.
John McCall460ce582015-10-22 18:38:17 +00001411 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
John McCalle68b8f42012-10-17 02:28:37 +00001412 // fall through
John McCall460ce582015-10-22 18:38:17 +00001413
1414 // Otherwise the memcpy is fine.
1415 } else {
1416 continue;
John McCall31168b02011-06-15 23:02:42 +00001417 }
John McCall460ce582015-10-22 18:38:17 +00001418
1419 // For all other types, the memcpy is fine.
John McCall31168b02011-06-15 23:02:42 +00001420 } else {
1421 continue;
1422 }
John McCall351762c2011-02-07 10:33:21 +00001423
1424 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001425 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1426 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001427
1428 // If there's an explicit copy expression, we do that.
1429 if (copyExpr) {
John McCallad7c5c12011-02-08 08:22:06 +00001430 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCalle68b8f42012-10-17 02:28:37 +00001431 } else if (useARCWeakCopy) {
John McCall31168b02011-06-15 23:02:42 +00001432 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001433 } else {
1434 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCalle68b8f42012-10-17 02:28:37 +00001435 if (useARCStrongCopy) {
1436 // At -O0, store null into the destination field (so that the
1437 // storeStrong doesn't over-release) and then call storeStrong.
1438 // This is a workaround to not having an initStrong call.
1439 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001440 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001441 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1442 Builder.CreateStore(null, dstField);
1443 EmitARCStoreStrongCall(dstField, srcValue, true);
1444
1445 // With optimization enabled, take advantage of the fact that
1446 // the blocks runtime guarantees a memcpy of the block data, and
1447 // just emit a retain of the src field.
1448 } else {
1449 EmitARCRetainNonBlock(srcValue);
1450
1451 // We don't need this anymore, so kill it. It's not quite
1452 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001453 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001454 }
1455 } else {
1456 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001457 llvm::Value *dstAddr =
1458 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001459 llvm::Value *args[] = {
1460 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1461 };
1462
1463 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001464 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001465 const Expr *copyExpr =
1466 CGM.getContext().getBlockVarCopyInits(variable);
1467 if (copyExpr) {
1468 copyCanThrow = true; // FIXME: reuse the noexcept logic
1469 }
1470 }
1471
1472 if (copyCanThrow) {
1473 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1474 } else {
1475 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1476 }
John McCalle68b8f42012-10-17 02:28:37 +00001477 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001478 }
1479 }
1480
John McCallad7c5c12011-02-08 08:22:06 +00001481 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001482
John McCalle3dc1702011-02-15 09:22:45 +00001483 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001484}
1485
John McCallf593b102013-01-22 03:56:22 +00001486/// Generate the destroy-helper function for a block closure object:
1487/// static void block_destroy_helper(block_t *theBlock);
1488///
1489/// Note that this destroys a heap-allocated block closure object;
1490/// it should not be confused with a 'byref destroy helper', which
1491/// destroys the heap-allocated contents of an individual __block
1492/// variable.
John McCall351762c2011-02-07 10:33:21 +00001493llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001494CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001495 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001496
John McCall351762c2011-02-07 10:33:21 +00001497 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001498 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1499 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001500 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001501
Reid Kleckner4982b822014-01-31 22:54:50 +00001502 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1503 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stump0c743272009-03-06 01:33:24 +00001504
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001505 // FIXME: We'd like to put these into a mergable by content, with
1506 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001507 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001508
1509 llvm::Function *Fn =
1510 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001511 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001512
1513 IdentifierInfo *II
1514 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1515
John McCall351762c2011-02-07 10:33:21 +00001516 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001517 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001518 SourceLocation(), II, C.VoidTy,
1519 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001520 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001521
1522 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1523
Adrian Prantl49a78562013-07-24 20:34:39 +00001524 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001525 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001526 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001527 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001528
Chris Lattner2192fe52011-07-18 04:24:23 +00001529 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001530
John McCall7f416cc2015-09-08 08:05:57 +00001531 Address src = GetAddrOfLocalVar(&srcDecl);
1532 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001533 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001534
John McCall351762c2011-02-07 10:33:21 +00001535 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1536
John McCallad7c5c12011-02-08 08:22:06 +00001537 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001538
Aaron Ballman9371dd22014-03-14 18:34:04 +00001539 for (const auto &CI : blockDecl->captures()) {
1540 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001541 QualType type = variable->getType();
1542
1543 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1544 if (capture.isConstant()) continue;
1545
John McCallad7c5c12011-02-08 08:22:06 +00001546 BlockFieldFlags flags;
Craig Topper8a13c412014-05-21 05:09:00 +00001547 const CXXDestructorDecl *dtor = nullptr;
John McCall351762c2011-02-07 10:33:21 +00001548
John McCalle68b8f42012-10-17 02:28:37 +00001549 bool useARCWeakDestroy = false;
1550 bool useARCStrongDestroy = false;
John McCall31168b02011-06-15 23:02:42 +00001551
Aaron Ballman9371dd22014-03-14 18:34:04 +00001552 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001553 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001554 if (type.isObjCGCWeak())
1555 flags |= BLOCK_FIELD_IS_WEAK;
1556 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1557 if (record->hasTrivialDestructor())
1558 continue;
1559 dtor = record->getDestructor();
1560 } else if (type->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +00001561 flags = BLOCK_FIELD_IS_OBJECT;
John McCall31168b02011-06-15 23:02:42 +00001562 if (type->isBlockPointerType())
1563 flags = BLOCK_FIELD_IS_BLOCK;
John McCall351762c2011-02-07 10:33:21 +00001564
John McCall31168b02011-06-15 23:02:42 +00001565 // Special rules for ARC captures.
John McCall460ce582015-10-22 18:38:17 +00001566 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001567
John McCall460ce582015-10-22 18:38:17 +00001568 // Use objc_storeStrong for __strong direct captures; the
1569 // dynamic tools really like it when we do this.
1570 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1571 useARCStrongDestroy = true;
John McCall31168b02011-06-15 23:02:42 +00001572
John McCall460ce582015-10-22 18:38:17 +00001573 // Support __weak direct captures.
1574 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1575 useARCWeakDestroy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001576
John McCall460ce582015-10-22 18:38:17 +00001577 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1578 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1579 // fall through
1580
1581 // Otherwise, we have nothing to do.
1582 } else {
1583 continue;
John McCall31168b02011-06-15 23:02:42 +00001584 }
1585 } else {
1586 continue;
1587 }
John McCall351762c2011-02-07 10:33:21 +00001588
John McCall7f416cc2015-09-08 08:05:57 +00001589 Address srcField =
1590 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001591
1592 // If there's an explicit copy expression, we do that.
1593 if (dtor) {
John McCallad7c5c12011-02-08 08:22:06 +00001594 PushDestructorCleanup(dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001595
John McCall31168b02011-06-15 23:02:42 +00001596 // If this is a __weak capture, emit the release directly.
John McCalle68b8f42012-10-17 02:28:37 +00001597 } else if (useARCWeakDestroy) {
John McCall31168b02011-06-15 23:02:42 +00001598 EmitARCDestroyWeak(srcField);
1599
John McCalle68b8f42012-10-17 02:28:37 +00001600 // Destroy strong objects with a call if requested.
1601 } else if (useARCStrongDestroy) {
John McCallcdda29c2013-03-13 03:10:54 +00001602 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001603
John McCall351762c2011-02-07 10:33:21 +00001604 // Otherwise we call _Block_object_dispose. It wouldn't be too
1605 // hard to just emit this as a cleanup if we wanted to make sure
1606 // that things were done in reverse.
1607 } else {
1608 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001609 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001610 BuildBlockRelease(value, flags);
1611 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001612 }
1613
John McCall351762c2011-02-07 10:33:21 +00001614 cleanups.ForceCleanup();
1615
John McCallad7c5c12011-02-08 08:22:06 +00001616 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001617
John McCalle3dc1702011-02-15 09:22:45 +00001618 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001619}
1620
John McCallf9b056b2011-03-31 08:03:29 +00001621namespace {
1622
1623/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001624class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001625 BlockFieldFlags Flags;
1626
1627public:
1628 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001629 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001630
John McCall7f416cc2015-09-08 08:05:57 +00001631 void emitCopy(CodeGenFunction &CGF, Address destField,
1632 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001633 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1634
1635 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1636 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1637
1638 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1639
1640 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1641 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001642
John McCall7f416cc2015-09-08 08:05:57 +00001643 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001644 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001645 }
1646
John McCall7f416cc2015-09-08 08:05:57 +00001647 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001648 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1649 llvm::Value *value = CGF.Builder.CreateLoad(field);
1650
1651 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1652 }
1653
Craig Topper4f12f102014-03-12 06:41:41 +00001654 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001655 id.AddInteger(Flags.getBitMask());
1656 }
1657};
1658
John McCall31168b02011-06-15 23:02:42 +00001659/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001660class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001661public:
John McCall7f416cc2015-09-08 08:05:57 +00001662 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001663
John McCall7f416cc2015-09-08 08:05:57 +00001664 void emitCopy(CodeGenFunction &CGF, Address destField,
1665 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001666 CGF.EmitARCMoveWeak(destField, srcField);
1667 }
1668
John McCall7f416cc2015-09-08 08:05:57 +00001669 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001670 CGF.EmitARCDestroyWeak(field);
1671 }
1672
Craig Topper4f12f102014-03-12 06:41:41 +00001673 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001674 // 0 is distinguishable from all pointers and byref flags
1675 id.AddInteger(0);
1676 }
1677};
1678
1679/// Emits the copy/dispose helpers for an ARC __block __strong variable
1680/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001681class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001682public:
John McCall7f416cc2015-09-08 08:05:57 +00001683 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001684
John McCall7f416cc2015-09-08 08:05:57 +00001685 void emitCopy(CodeGenFunction &CGF, Address destField,
1686 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001687 // Do a "move" by copying the value and then zeroing out the old
1688 // variable.
1689
John McCall7f416cc2015-09-08 08:05:57 +00001690 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001691
John McCall31168b02011-06-15 23:02:42 +00001692 llvm::Value *null =
1693 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001694
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001695 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001696 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001697 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1698 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1699 return;
1700 }
John McCall7f416cc2015-09-08 08:05:57 +00001701 CGF.Builder.CreateStore(value, destField);
1702 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001703 }
1704
John McCall7f416cc2015-09-08 08:05:57 +00001705 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001706 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001707 }
1708
Craig Topper4f12f102014-03-12 06:41:41 +00001709 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001710 // 1 is distinguishable from all pointers and byref flags
1711 id.AddInteger(1);
1712 }
1713};
1714
John McCall3a237aa2011-11-09 03:17:26 +00001715/// Emits the copy/dispose helpers for an ARC __block __strong
1716/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001717class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001718public:
John McCall7f416cc2015-09-08 08:05:57 +00001719 ARCStrongBlockByrefHelpers(CharUnits alignment)
1720 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001721
John McCall7f416cc2015-09-08 08:05:57 +00001722 void emitCopy(CodeGenFunction &CGF, Address destField,
1723 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001724 // Do the copy with objc_retainBlock; that's all that
1725 // _Block_object_assign would do anyway, and we'd have to pass the
1726 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001727 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001728 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001729 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001730 }
1731
John McCall7f416cc2015-09-08 08:05:57 +00001732 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001733 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001734 }
1735
Craig Topper4f12f102014-03-12 06:41:41 +00001736 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001737 // 2 is distinguishable from all pointers and byref flags
1738 id.AddInteger(2);
1739 }
1740};
1741
John McCallf9b056b2011-03-31 08:03:29 +00001742/// Emits the copy/dispose helpers for a __block variable with a
1743/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00001744class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001745 QualType VarType;
1746 const Expr *CopyExpr;
1747
1748public:
1749 CXXByrefHelpers(CharUnits alignment, QualType type,
1750 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00001751 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00001752
Craig Topper8a13c412014-05-21 05:09:00 +00001753 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00001754 void emitCopy(CodeGenFunction &CGF, Address destField,
1755 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001756 if (!CopyExpr) return;
1757 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1758 }
1759
John McCall7f416cc2015-09-08 08:05:57 +00001760 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001761 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1762 CGF.PushDestructorCleanup(VarType, field);
1763 CGF.PopCleanupBlocks(cleanupDepth);
1764 }
1765
Craig Topper4f12f102014-03-12 06:41:41 +00001766 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001767 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1768 }
1769};
1770} // end anonymous namespace
1771
1772static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00001773generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1774 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001775 ASTContext &Context = CGF.getContext();
1776
1777 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001778
John McCalla738c252011-03-09 04:27:21 +00001779 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001780 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001781 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001782 args.push_back(&dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00001783
Craig Topper8a13c412014-05-21 05:09:00 +00001784 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001785 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001786 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001787
Reid Kleckner4982b822014-01-31 22:54:50 +00001788 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1789 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001790
John McCall7f416cc2015-09-08 08:05:57 +00001791 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001792
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001793 // FIXME: We'd like to put these into a mergable by content, with
1794 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001795 llvm::Function *Fn =
1796 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00001797 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001798
1799 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001800 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001801
John McCallf9b056b2011-03-31 08:03:29 +00001802 FunctionDecl *FD = FunctionDecl::Create(Context,
1803 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001804 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001805 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001806 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001807 false, false);
John McCall31168b02011-06-15 23:02:42 +00001808
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001809 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1810
Adrian Prantl22e66b42014-04-11 01:13:04 +00001811 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00001812
John McCall7f416cc2015-09-08 08:05:57 +00001813 if (generator.needsCopy()) {
1814 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00001815
John McCallf9b056b2011-03-31 08:03:29 +00001816 // dst->x
John McCall7f416cc2015-09-08 08:05:57 +00001817 Address destField = CGF.GetAddrOfLocalVar(&dst);
1818 destField = Address(CGF.Builder.CreateLoad(destField),
1819 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001820 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001821 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1822 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001823
John McCallf9b056b2011-03-31 08:03:29 +00001824 // src->x
John McCall7f416cc2015-09-08 08:05:57 +00001825 Address srcField = CGF.GetAddrOfLocalVar(&src);
1826 srcField = Address(CGF.Builder.CreateLoad(srcField),
1827 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001828 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001829 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1830 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00001831
John McCall7f416cc2015-09-08 08:05:57 +00001832 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00001833 }
1834
1835 CGF.FinishFunction();
1836
1837 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001838}
1839
John McCallf9b056b2011-03-31 08:03:29 +00001840/// Build the copy helper for a __block variable.
1841static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001842 const BlockByrefInfo &byrefInfo,
1843 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001844 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001845 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001846}
1847
1848/// Generate code for a __block variable's dispose helper.
1849static llvm::Constant *
1850generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001851 const BlockByrefInfo &byrefInfo,
1852 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001853 ASTContext &Context = CGF.getContext();
1854 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001855
John McCalla738c252011-03-09 04:27:21 +00001856 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001857 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001858 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001859 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001860
Reid Kleckner4982b822014-01-31 22:54:50 +00001861 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1862 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001863
John McCall7f416cc2015-09-08 08:05:57 +00001864 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001865
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001866 // FIXME: We'd like to put these into a mergable by content, with
1867 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001868 llvm::Function *Fn =
1869 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00001870 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00001871 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001872
1873 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001874 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001875
John McCallf9b056b2011-03-31 08:03:29 +00001876 FunctionDecl *FD = FunctionDecl::Create(Context,
1877 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001878 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001879 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001880 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001881 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001882
1883 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1884
Adrian Prantl22e66b42014-04-11 01:13:04 +00001885 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00001886
John McCall7f416cc2015-09-08 08:05:57 +00001887 if (generator.needsDispose()) {
1888 Address addr = CGF.GetAddrOfLocalVar(&src);
1889 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1890 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1891 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1892 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00001893
John McCall7f416cc2015-09-08 08:05:57 +00001894 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00001895 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001896
John McCallf9b056b2011-03-31 08:03:29 +00001897 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00001898
John McCallf9b056b2011-03-31 08:03:29 +00001899 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001900}
1901
John McCallf9b056b2011-03-31 08:03:29 +00001902/// Build the dispose helper for a __block variable.
1903static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001904 const BlockByrefInfo &byrefInfo,
1905 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001906 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001907 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001908}
1909
John McCallf593b102013-01-22 03:56:22 +00001910/// Lazily build the copy and dispose helpers for a __block variable
1911/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00001912template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00001913static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1914 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001915 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00001916 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00001917
1918 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00001919 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00001920 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1921 if (node) return static_cast<T*>(node);
1922
John McCall7f416cc2015-09-08 08:05:57 +00001923 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1924 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001925
John McCall7f416cc2015-09-08 08:05:57 +00001926 T *copy = new (CGM.getContext()) T(std::move(generator));
John McCallf9b056b2011-03-31 08:03:29 +00001927 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1928 return copy;
1929}
1930
John McCallf593b102013-01-22 03:56:22 +00001931/// Build the copy and dispose helpers for the given __block variable
1932/// emission. Places the helpers in the global cache. Returns null
1933/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00001934BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00001935CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00001936 const AutoVarEmission &emission) {
1937 const VarDecl &var = *emission.Variable;
1938 QualType type = var.getType();
1939
John McCall7f416cc2015-09-08 08:05:57 +00001940 auto &byrefInfo = getBlockByrefInfo(&var);
1941
1942 // The alignment we care about for the purposes of uniquing byref
1943 // helpers is the alignment of the actual byref value field.
1944 CharUnits valueAlignment =
1945 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00001946
John McCallf9b056b2011-03-31 08:03:29 +00001947 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1948 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00001949 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00001950
David Blaikie92551612015-08-13 23:53:09 +00001951 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00001952 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00001953 }
1954
John McCall31168b02011-06-15 23:02:42 +00001955 // Otherwise, if we don't have a retainable type, there's nothing to do.
1956 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00001957 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001958
1959 Qualifiers qs = type.getQualifiers();
1960
1961 // If we have lifetime, that dominates.
1962 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00001963 switch (lifetime) {
1964 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1965
1966 // These are just bits as far as the runtime is concerned.
1967 case Qualifiers::OCL_ExplicitNone:
1968 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00001969 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001970
1971 // Tell the runtime that this is ARC __weak, called by the
1972 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00001973 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00001974 return ::buildByrefHelpers(CGM, byrefInfo,
1975 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001976
1977 // ARC __strong __block variables need to be retained.
1978 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00001979 // Block pointers need to be copied, and there's no direct
1980 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00001981 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001982 return ::buildByrefHelpers(CGM, byrefInfo,
1983 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001984
1985 // Otherwise, we transfer ownership of the retain from the stack
1986 // to the heap.
1987 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001988 return ::buildByrefHelpers(CGM, byrefInfo,
1989 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001990 }
1991 }
1992 llvm_unreachable("fell out of lifetime switch!");
1993 }
1994
John McCallf9b056b2011-03-31 08:03:29 +00001995 BlockFieldFlags flags;
1996 if (type->isBlockPointerType()) {
1997 flags |= BLOCK_FIELD_IS_BLOCK;
1998 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1999 type->isObjCObjectPointerType()) {
2000 flags |= BLOCK_FIELD_IS_OBJECT;
2001 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002002 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002003 }
2004
2005 if (type.isObjCGCWeak())
2006 flags |= BLOCK_FIELD_IS_WEAK;
2007
John McCall7f416cc2015-09-08 08:05:57 +00002008 return ::buildByrefHelpers(CGM, byrefInfo,
2009 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002010}
2011
John McCall7f416cc2015-09-08 08:05:57 +00002012Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2013 const VarDecl *var,
2014 bool followForward) {
2015 auto &info = getBlockByrefInfo(var);
2016 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002017}
2018
John McCall7f416cc2015-09-08 08:05:57 +00002019Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2020 const BlockByrefInfo &info,
2021 bool followForward,
2022 const llvm::Twine &name) {
2023 // Chase the forwarding address if requested.
2024 if (followForward) {
2025 Address forwardingAddr =
2026 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2027 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2028 }
2029
2030 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2031 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002032}
2033
John McCall7f416cc2015-09-08 08:05:57 +00002034/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002035/// into:
2036///
2037/// struct {
2038/// void *__isa;
2039/// void *__forwarding;
2040/// int32_t __flags;
2041/// int32_t __size;
2042/// void *__copy_helper; // only if needed
2043/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002044/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002045/// char padding[X]; // only if needed
2046/// T x;
2047/// } x
2048///
John McCall7f416cc2015-09-08 08:05:57 +00002049const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2050 auto it = BlockByrefInfos.find(D);
2051 if (it != BlockByrefInfos.end())
2052 return it->second;
John McCall73064872011-03-31 01:59:53 +00002053
John McCall7f416cc2015-09-08 08:05:57 +00002054 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002055 llvm::StructType::create(getLLVMContext(),
2056 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002057
John McCall7f416cc2015-09-08 08:05:57 +00002058 QualType Ty = D->getType();
2059
2060 CharUnits size;
2061 SmallVector<llvm::Type *, 8> types;
2062
John McCall73064872011-03-31 01:59:53 +00002063 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002064 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002065 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002066
2067 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002068 types.push_back(llvm::PointerType::getUnqual(byrefType));
2069 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002070
2071 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002072 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002073 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002074
2075 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002076 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002077 size += CharUnits::fromQuantity(4);
2078
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002079 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002080 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2081 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002082 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002083 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002084 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002085
2086 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002087 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002088 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002089 }
John McCall7f416cc2015-09-08 08:05:57 +00002090
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002091 bool HasByrefExtendedLayout = false;
2092 Qualifiers::ObjCLifetime Lifetime;
2093 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002094 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002095 /// void *__byref_variable_layout;
2096 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002097 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002098 }
2099
2100 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002101 llvm::Type *varTy = ConvertTypeForMem(Ty);
2102
2103 bool packed = false;
2104 CharUnits varAlign = getContext().getDeclAlign(D);
2105 CharUnits varOffset = size.RoundUpToAlignment(varAlign);
2106
2107 // We may have to insert padding.
2108 if (varOffset != size) {
2109 llvm::Type *paddingTy =
2110 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2111
2112 types.push_back(paddingTy);
2113 size = varOffset;
2114
2115 // Conversely, we might have to prevent LLVM from inserting padding.
2116 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2117 > varAlign.getQuantity()) {
2118 packed = true;
2119 }
2120 types.push_back(varTy);
2121
2122 byrefType->setBody(types, packed);
2123
2124 BlockByrefInfo info;
2125 info.Type = byrefType;
2126 info.FieldIndex = types.size() - 1;
2127 info.FieldOffset = varOffset;
2128 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2129
2130 auto pair = BlockByrefInfos.insert({D, info});
2131 assert(pair.second && "info was inserted recursively?");
2132 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002133}
2134
2135/// Initialize the structural components of a __block variable, i.e.
2136/// everything but the actual object.
2137void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002138 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002139 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002140
John McCallf9b056b2011-03-31 08:03:29 +00002141 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002142 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002143 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2144
2145 unsigned nextHeaderIndex = 0;
2146 CharUnits nextHeaderOffset;
2147 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2148 const Twine &name) {
2149 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2150 nextHeaderOffset, name);
2151 Builder.CreateStore(value, fieldAddr);
2152
2153 nextHeaderIndex++;
2154 nextHeaderOffset += fieldSize;
2155 };
John McCallf9b056b2011-03-31 08:03:29 +00002156
2157 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002158 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002159
2160 const VarDecl &D = *emission.Variable;
2161 QualType type = D.getType();
2162
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002163 bool HasByrefExtendedLayout;
2164 Qualifiers::ObjCLifetime ByrefLifetime;
2165 bool ByRefHasLifetime =
2166 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002167
John McCallf9b056b2011-03-31 08:03:29 +00002168 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002169
2170 // Initialize the 'isa', which is just 0 or 1.
2171 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002172 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002173 isa = 1;
2174 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002175 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002176
2177 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002178 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002179
2180 // Blocks ABI:
2181 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002182 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002183 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002184 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2185 if (ByRefHasLifetime) {
2186 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2187 else switch (ByrefLifetime) {
2188 case Qualifiers::OCL_Strong:
2189 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2190 break;
2191 case Qualifiers::OCL_Weak:
2192 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2193 break;
2194 case Qualifiers::OCL_ExplicitNone:
2195 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2196 break;
2197 case Qualifiers::OCL_None:
2198 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2199 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2200 break;
2201 default:
2202 break;
2203 }
2204 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2205 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2206 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2207 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2208 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2209 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2210 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2211 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2212 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2213 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2214 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2215 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2216 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2217 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2218 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2219 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2220 }
2221 printf("\n");
2222 }
2223 }
John McCall7f416cc2015-09-08 08:05:57 +00002224 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2225 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002226
John McCallf9b056b2011-03-31 08:03:29 +00002227 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2228 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002229 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002230
John McCallf9b056b2011-03-31 08:03:29 +00002231 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002232 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2233 "byref.copyHelper");
2234 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2235 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002236 }
John McCall7f416cc2015-09-08 08:05:57 +00002237
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002238 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002239 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2240 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002241 }
John McCall73064872011-03-31 01:59:53 +00002242}
2243
John McCallad7c5c12011-02-08 08:22:06 +00002244void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002245 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002246 llvm::Value *args[] = {
2247 Builder.CreateBitCast(V, Int8PtrTy),
2248 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2249 };
2250 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002251}
John McCall73064872011-03-31 01:59:53 +00002252
2253namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002254 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002255 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002256 llvm::Value *Addr;
2257 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2258
Craig Topper4f12f102014-03-12 06:41:41 +00002259 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002260 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002261 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2262 }
2263 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002264} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002265
2266/// Enter a cleanup to destroy a __block variable. Note that this
2267/// cleanup should be a no-op if the variable hasn't left the stack
2268/// yet; if a cleanup is required for the variable itself, that needs
2269/// to be done externally.
2270void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2271 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002272 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002273 return;
2274
John McCall7f416cc2015-09-08 08:05:57 +00002275 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2276 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002277}
John McCall7959fee2011-09-09 20:41:01 +00002278
2279/// Adjust the declaration of something from the blocks API.
2280static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2281 llvm::Constant *C) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002282 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall7959fee2011-09-09 20:41:01 +00002283
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002284 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002285 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002286 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2287}
2288
2289llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2290 if (BlockObjectDispose)
2291 return BlockObjectDispose;
2292
2293 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2294 llvm::FunctionType *fty
2295 = llvm::FunctionType::get(VoidTy, args, false);
2296 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2297 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2298 return BlockObjectDispose;
2299}
2300
2301llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2302 if (BlockObjectAssign)
2303 return BlockObjectAssign;
2304
2305 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2306 llvm::FunctionType *fty
2307 = llvm::FunctionType::get(VoidTy, args, false);
2308 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2309 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2310 return BlockObjectAssign;
2311}
2312
2313llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2314 if (NSConcreteGlobalBlock)
2315 return NSConcreteGlobalBlock;
2316
2317 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002318 Int8PtrTy->getPointerTo(),
2319 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002320 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2321 return NSConcreteGlobalBlock;
2322}
2323
2324llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2325 if (NSConcreteStackBlock)
2326 return NSConcreteStackBlock;
2327
2328 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002329 Int8PtrTy->getPointerTo(),
2330 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002331 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2332 return NSConcreteStackBlock;
2333}