blob: 71a2447cb5dc471c036f1f0c8a7b108862e9e0e0 [file] [log] [blame]
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
John 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),
Craig Topper8a13c412014-05-21 05:09:00 +000033 StructureType(nullptr), Block(block),
34 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.
43CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
44
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);
81 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +000082
Chris Lattner0e62c1c2011-07-23 10:55:15 +000083 SmallVector<llvm::Constant*, 6> elements;
Mike Stump85284ba2009-02-13 16:19:19 +000084
85 // reserved
John McCall351762c2011-02-07 10:33:21 +000086 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stump85284ba2009-02-13 16:19:19 +000087
88 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +000089 // FIXME: What is the right way to say this doesn't fit? We should give
90 // a user diagnostic in that case. Better fix would be to change the
91 // API to size_t.
John McCall351762c2011-02-07 10:33:21 +000092 elements.push_back(llvm::ConstantInt::get(ulong,
93 blockInfo.BlockSize.getQuantity()));
Mike Stump85284ba2009-02-13 16:19:19 +000094
John McCall351762c2011-02-07 10:33:21 +000095 // Optional copy/dispose helpers.
96 if (blockInfo.NeedsCopyDispose) {
Mike Stump85284ba2009-02-13 16:19:19 +000097 // copy_func_helper_decl
John McCall351762c2011-02-07 10:33:21 +000098 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +000099
100 // destroy_func_decl
John McCall351762c2011-02-07 10:33:21 +0000101 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000102 }
103
John McCall351762c2011-02-07 10:33:21 +0000104 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
105 std::string typeAtEncoding =
106 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
107 elements.push_back(llvm::ConstantExpr::getBitCast(
108 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000109
John McCall351762c2011-02-07 10:33:21 +0000110 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000111 if (C.getLangOpts().ObjC1) {
112 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
113 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
114 else
115 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
116 }
John McCall351762c2011-02-07 10:33:21 +0000117 else
118 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000119
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000120 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stump85284ba2009-02-13 16:19:19 +0000121
John McCall351762c2011-02-07 10:33:21 +0000122 llvm::GlobalVariable *global =
123 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
124 llvm::GlobalValue::InternalLinkage,
125 init, "__block_descriptor_tmp");
Mike Stump85284ba2009-02-13 16:19:19 +0000126
John McCall351762c2011-02-07 10:33:21 +0000127 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000128}
129
John McCall351762c2011-02-07 10:33:21 +0000130/*
131 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000132
John McCall351762c2011-02-07 10:33:21 +0000133 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
134 struct Block_literal {
135 /// Initialized to one of:
136 /// extern void *_NSConcreteStackBlock[];
137 /// extern void *_NSConcreteGlobalBlock[];
138 ///
139 /// In theory, we could start one off malloc'ed by setting
140 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
141 /// this isa:
142 /// extern void *_NSConcreteMallocBlock[];
143 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000144
John McCall351762c2011-02-07 10:33:21 +0000145 /// These are the flags (with corresponding bit number) that the
146 /// compiler is actually supposed to know about.
147 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
148 /// descriptor provides copy and dispose helper functions
149 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
150 /// object with a nontrivial destructor or copy constructor
151 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
152 /// as global memory
153 /// 29. BLOCK_USE_STRET - indicates that the block function
154 /// uses stret, which objc_msgSend needs to know about
155 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
156 /// @encoded signature string
157 /// And we're not supposed to manipulate these:
158 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
159 /// to malloc'ed memory
160 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
161 /// to GC-allocated memory
162 /// Additionally, the bottom 16 bits are a reference count which
163 /// should be zero on the stack.
164 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000165
John McCall351762c2011-02-07 10:33:21 +0000166 /// Reserved; should be zero-initialized.
167 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000168
John McCall351762c2011-02-07 10:33:21 +0000169 /// Function pointer generated from block literal.
170 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000171
John McCall351762c2011-02-07 10:33:21 +0000172 /// Block description metadata generated from block literal.
173 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000174
John McCall351762c2011-02-07 10:33:21 +0000175 /// Captured values follow.
176 _CapturesTypes captures...;
177 };
178 */
David Chisnall950a9512009-11-17 19:33:30 +0000179
John McCall351762c2011-02-07 10:33:21 +0000180/// The number of fields in a block header.
181const unsigned BlockHeaderSize = 5;
Mike Stump4446dcf2009-03-05 08:32:30 +0000182
John McCall351762c2011-02-07 10:33:21 +0000183namespace {
184 /// A chunk of data that we actually have to capture in the block.
185 struct BlockLayoutChunk {
186 CharUnits Alignment;
187 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000188 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000189 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000190 llvm::Type *Type;
Mike Stump85284ba2009-02-13 16:19:19 +0000191
John McCall351762c2011-02-07 10:33:21 +0000192 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000193 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000194 const BlockDecl::Capture *capture,
Jay Foad7c57be32011-07-11 09:56:20 +0000195 llvm::Type *type)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000196 : Alignment(align), Size(size), Lifetime(lifetime),
197 Capture(capture), Type(type) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000198
John McCall351762c2011-02-07 10:33:21 +0000199 /// Tell the block info that this chunk has the given field index.
200 void setIndex(CGBlockInfo &info, unsigned index) {
201 if (!Capture)
202 info.CXXThisIndex = index;
John McCall87fe5d52010-05-20 01:18:31 +0000203 else
John McCall351762c2011-02-07 10:33:21 +0000204 info.Captures[Capture->getVariable()]
205 = CGBlockInfo::Capture::makeIndex(index);
John McCall87fe5d52010-05-20 01:18:31 +0000206 }
John McCall351762c2011-02-07 10:33:21 +0000207 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000208
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000209 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
210 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000211 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000212 CharUnits LeftValue, RightValue;
213 bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
214 bool RightByref = right.Capture ? right.Capture->isByRef() : false;
215
216 if (left.Lifetime == Qualifiers::OCL_Strong &&
217 left.Alignment >= right.Alignment)
218 LeftValue = CharUnits::fromQuantity(64);
219 else if (LeftByref && left.Alignment >= right.Alignment)
220 LeftValue = CharUnits::fromQuantity(32);
221 else if (left.Lifetime == Qualifiers::OCL_Weak &&
222 left.Alignment >= right.Alignment)
223 LeftValue = CharUnits::fromQuantity(16);
224 else
225 LeftValue = left.Alignment;
226 if (right.Lifetime == Qualifiers::OCL_Strong &&
227 right.Alignment >= left.Alignment)
228 RightValue = CharUnits::fromQuantity(64);
229 else if (RightByref && right.Alignment >= left.Alignment)
230 RightValue = CharUnits::fromQuantity(32);
231 else if (right.Lifetime == Qualifiers::OCL_Weak &&
232 right.Alignment >= left.Alignment)
233 RightValue = CharUnits::fromQuantity(16);
234 else
235 RightValue = right.Alignment;
236
237 return LeftValue > RightValue;
John McCall351762c2011-02-07 10:33:21 +0000238 }
239}
240
John McCallb0a3ecb2011-02-08 03:07:00 +0000241/// Determines if the given type is safe for constant capture in C++.
242static bool isSafeForCXXConstantCapture(QualType type) {
243 const RecordType *recordType =
244 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
245
246 // Only records can be unsafe.
247 if (!recordType) return true;
248
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000249 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000250
251 // Maintain semantics for classes with non-trivial dtors or copy ctors.
252 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000253 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000254
255 // Otherwise, we just have to make sure there aren't any mutable
256 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000257 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000258}
259
John McCall351762c2011-02-07 10:33:21 +0000260/// It is illegal to modify a const object after initialization.
261/// Therefore, if a const object has a constant initializer, we don't
262/// actually need to keep storage for it in the block; we'll just
263/// rematerialize it at the start of the block function. This is
264/// acceptable because we make no promises about address stability of
265/// captured variables.
266static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000267 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000268 const VarDecl *var) {
269 QualType type = var->getType();
270
271 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000272 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000273
John McCallb0a3ecb2011-02-08 03:07:00 +0000274 // Furthermore, in C++ we have to worry about mutable fields:
275 // C++ [dcl.type.cv]p4:
276 // Except that any class member declared mutable can be
277 // modified, any attempt to modify a const object during its
278 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000279 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000280 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000281
282 // If the variable doesn't have any initializer (shouldn't this be
283 // invalid?), it's not clear what we should do. Maybe capture as
284 // zero?
285 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000286 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000287
Richard Smithdafff942012-01-14 04:30:29 +0000288 return CGM.EmitConstantInit(*var, CGF);
John McCall351762c2011-02-07 10:33:21 +0000289}
290
291/// Get the low bit of a nonzero character count. This is the
292/// alignment of the nth byte if the 0th byte is universally aligned.
293static CharUnits getLowBit(CharUnits v) {
294 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
295}
296
297static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000298 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall351762c2011-02-07 10:33:21 +0000299 ASTContext &C = CGM.getContext();
300
301 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
302 CharUnits ptrSize, ptrAlign, intSize, intAlign;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000303 std::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
304 std::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
John McCall351762c2011-02-07 10:33:21 +0000305
306 // Are there crazy embedded platforms where this isn't true?
307 assert(intSize <= ptrSize && "layout assumptions horribly violated");
308
309 CharUnits headerSize = ptrSize;
310 if (2 * intSize < ptrAlign) headerSize += ptrSize;
311 else headerSize += 2 * intSize;
312 headerSize += 2 * ptrSize;
313
314 info.BlockAlign = ptrAlign;
315 info.BlockSize = headerSize;
316
317 assert(elementTypes.empty());
Jay Foad7c57be32011-07-11 09:56:20 +0000318 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
319 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall351762c2011-02-07 10:33:21 +0000320 elementTypes.push_back(i8p);
321 elementTypes.push_back(intTy);
322 elementTypes.push_back(intTy);
323 elementTypes.push_back(i8p);
324 elementTypes.push_back(CGM.getBlockDescriptorType());
325
326 assert(elementTypes.size() == BlockHeaderSize);
327}
328
329/// Compute the layout of the given block. Attempts to lay the block
330/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000331static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
332 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000333 ASTContext &C = CGM.getContext();
334 const BlockDecl *block = info.getBlockDecl();
335
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000336 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000337 initializeForBlockHeader(CGM, info, elementTypes);
338
339 if (!block->hasCaptures()) {
340 info.StructureType =
341 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
342 info.CanBeGlobal = true;
343 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000344 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000345 else if (C.getLangOpts().ObjC1 &&
346 CGM.getLangOpts().getGC() == LangOptions::NonGC)
347 info.HasCapturedVariableLayout = true;
348
John McCall351762c2011-02-07 10:33:21 +0000349 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000350 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000351 layout.reserve(block->capturesCXXThis() +
352 (block->capture_end() - block->capture_begin()));
353
354 CharUnits maxFieldAlign;
355
356 // First, 'this'.
357 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000358 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
359 "Can't capture 'this' outside a method");
360 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000361
Jay Foad7c57be32011-07-11 09:56:20 +0000362 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000363 std::pair<CharUnits,CharUnits> tinfo
364 = CGM.getContext().getTypeInfoInChars(thisType);
365 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
366
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000367 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
368 Qualifiers::OCL_None,
Craig Topper8a13c412014-05-21 05:09:00 +0000369 nullptr, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000370 }
371
372 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000373 for (const auto &CI : block->captures()) {
374 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000375
Aaron Ballman9371dd22014-03-14 18:34:04 +0000376 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000377 // We have to copy/dispose of the __block reference.
378 info.NeedsCopyDispose = true;
379
John McCall351762c2011-02-07 10:33:21 +0000380 // Just use void* instead of a pointer to the byref type.
381 QualType byRefPtrTy = C.VoidPtrTy;
382
Jay Foad7c57be32011-07-11 09:56:20 +0000383 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000384 std::pair<CharUnits,CharUnits> tinfo
385 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
386 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
387
388 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
Aaron Ballman9371dd22014-03-14 18:34:04 +0000389 Qualifiers::OCL_None, &CI, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000390 continue;
391 }
392
393 // Otherwise, build a layout chunk with the size and alignment of
394 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000395 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000396 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
397 continue;
398 }
399
John McCall31168b02011-06-15 23:02:42 +0000400 // If we have a lifetime qualifier, honor it for capture purposes.
401 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000402 Qualifiers::ObjCLifetime lifetime =
403 variable->getType().getObjCLifetime();
404 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000405 switch (lifetime) {
406 case Qualifiers::OCL_None: llvm_unreachable("impossible");
407 case Qualifiers::OCL_ExplicitNone:
408 case Qualifiers::OCL_Autoreleasing:
409 break;
John McCall351762c2011-02-07 10:33:21 +0000410
John McCall31168b02011-06-15 23:02:42 +0000411 case Qualifiers::OCL_Strong:
412 case Qualifiers::OCL_Weak:
413 info.NeedsCopyDispose = true;
414 }
415
416 // Block pointers require copy/dispose. So do Objective-C pointers.
417 } else if (variable->getType()->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +0000418 info.NeedsCopyDispose = true;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000419 // used for mrr below.
420 lifetime = Qualifiers::OCL_Strong;
John McCall351762c2011-02-07 10:33:21 +0000421
422 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000423 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000424 info.NeedsCopyDispose = true;
425 info.HasCXXObject = true;
426
427 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000428 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000429 if (const CXXRecordDecl *record =
430 variable->getType()->getAsCXXRecordDecl()) {
431 if (!record->hasTrivialDestructor()) {
432 info.HasCXXObject = true;
433 info.NeedsCopyDispose = true;
434 }
435 }
436 }
437
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000438 QualType VT = variable->getType();
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000439 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000440 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000441
John McCall351762c2011-02-07 10:33:21 +0000442 maxFieldAlign = std::max(maxFieldAlign, align);
443
Jay Foad7c57be32011-07-11 09:56:20 +0000444 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000445 CGM.getTypes().ConvertTypeForMem(VT);
446
Aaron Ballman9371dd22014-03-14 18:34:04 +0000447 layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000448 }
449
450 // If that was everything, we're done here.
451 if (layout.empty()) {
452 info.StructureType =
453 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
454 info.CanBeGlobal = true;
455 return;
456 }
457
458 // Sort the layout by alignment. We have to use a stable sort here
459 // to get reproducible results. There should probably be an
460 // llvm::array_pod_stable_sort.
461 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000462
463 // Needed for blocks layout info.
464 info.BlockHeaderForcedGapOffset = info.BlockSize;
465 info.BlockHeaderForcedGapSize = CharUnits::Zero();
466
John McCall351762c2011-02-07 10:33:21 +0000467 CharUnits &blockSize = info.BlockSize;
468 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
469
470 // Assuming that the first byte in the header is maximally aligned,
471 // get the alignment of the first byte following the header.
472 CharUnits endAlign = getLowBit(blockSize);
473
474 // If the end of the header isn't satisfactorily aligned for the
475 // maximum thing, look for things that are okay with the header-end
476 // alignment, and keep appending them until we get something that's
477 // aligned right. This algorithm is only guaranteed optimal if
478 // that condition is satisfied at some point; otherwise we can get
479 // things like:
480 // header // next byte has alignment 4
481 // something_with_size_5; // next byte has alignment 1
482 // something_with_alignment_8;
483 // which has 7 bytes of padding, as opposed to the naive solution
484 // which might have less (?).
485 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000486 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000487 li = layout.begin() + 1, le = layout.end();
488
489 // Look for something that the header end is already
490 // satisfactorily aligned for.
491 for (; li != le && endAlign < li->Alignment; ++li)
492 ;
493
494 // If we found something that's naturally aligned for the end of
495 // the header, keep adding things...
496 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000497 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000498 for (; li != le; ++li) {
499 assert(endAlign >= li->Alignment);
500
501 li->setIndex(info, elementTypes.size());
502 elementTypes.push_back(li->Type);
503 blockSize += li->Size;
504 endAlign = getLowBit(blockSize);
505
506 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000507 if (endAlign >= maxFieldAlign) {
508 if (li == first) {
509 // No user field was appended. So, a gap was added.
510 // Save total gap size for use in block layout bit map.
511 info.BlockHeaderForcedGapSize = li->Size;
512 }
John McCall351762c2011-02-07 10:33:21 +0000513 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000514 }
John McCall351762c2011-02-07 10:33:21 +0000515 }
John McCall351762c2011-02-07 10:33:21 +0000516 // Don't re-append everything we just appended.
517 layout.erase(first, li);
518 }
519 }
520
John McCallac0350a2012-04-26 21:14:42 +0000521 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000522
John McCall351762c2011-02-07 10:33:21 +0000523 // At this point, we just have to add padding if the end align still
524 // isn't aligned right.
525 if (endAlign < maxFieldAlign) {
John McCallac0350a2012-04-26 21:14:42 +0000526 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
527 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000528
John McCalle3dc1702011-02-15 09:22:45 +0000529 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
530 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000531 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000532 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000533 }
534
John McCall1db0a2f2012-05-01 20:28:00 +0000535 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000536 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000537 // Slam everything else on now. This works because they have
538 // strictly decreasing alignment and we expect that size is always a
539 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000540 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000541 li = layout.begin(), le = layout.end(); li != le; ++li) {
542 assert(endAlign >= li->Alignment);
543 li->setIndex(info, elementTypes.size());
544 elementTypes.push_back(li->Type);
545 blockSize += li->Size;
546 endAlign = getLowBit(blockSize);
547 }
548
549 info.StructureType =
550 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
551}
552
John McCall08ef4662011-11-10 08:15:53 +0000553/// Enter the scope of a block. This should be run at the entrance to
554/// a full-expression so that the block's cleanups are pushed at the
555/// right place in the stack.
556static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000557 assert(CGF.HaveInsertPoint());
558
John McCall08ef4662011-11-10 08:15:53 +0000559 // Allocate the block info and place it at the head of the list.
560 CGBlockInfo &blockInfo =
561 *new CGBlockInfo(block, CGF.CurFn->getName());
562 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
563 CGF.FirstBlockInfo = &blockInfo;
564
565 // Compute information about the layout, etc., of this block,
566 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000567 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000568
569 // Nothing else to do if it can be global.
570 if (blockInfo.CanBeGlobal) return;
571
572 // Make the allocation for the block.
573 blockInfo.Address =
574 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
575 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
576
577 // If there are cleanups to emit, enter them (but inactive).
578 if (!blockInfo.NeedsCopyDispose) return;
579
580 // Walk through the captures (in order) and find the ones not
581 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000582 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000583 // Ignore __block captures; there's nothing special in the
584 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000585 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000586
587 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000588 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000589 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
590 if (capture.isConstant()) continue;
591
592 // Ignore objects that aren't destructed.
593 QualType::DestructionKind dtorKind =
594 variable->getType().isDestructedType();
595 if (dtorKind == QualType::DK_none) continue;
596
597 CodeGenFunction::Destroyer *destroyer;
598
599 // Block captures count as local values and have imprecise semantics.
600 // They also can't be arrays, so need to worry about that.
601 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000602 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000603 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000604 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000605 }
606
607 // GEP down to the address.
608 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
609 capture.getIndex());
610
John McCallf4beacd2011-11-10 10:43:54 +0000611 // We can use that GEP as the dominating IP.
612 if (!blockInfo.DominatingIP)
613 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
614
John McCall08ef4662011-11-10 08:15:53 +0000615 CleanupKind cleanupKind = InactiveNormalCleanup;
616 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
617 if (useArrayEHCleanup)
618 cleanupKind = InactiveNormalAndEHCleanup;
619
620 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne1425b452012-01-26 03:33:36 +0000621 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000622
623 // Remember where that cleanup was.
624 capture.setCleanup(CGF.EHStack.stable_begin());
625 }
626}
627
628/// Enter a full-expression with a non-trivial number of objects to
629/// clean up. This is in this file because, at the moment, the only
630/// kind of cleanup object is a BlockDecl*.
631void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
632 assert(E->getNumObjects() != 0);
633 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
634 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
635 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
636 enterBlockScope(*this, *i);
637 }
638}
639
640/// Find the layout for the given block in a linked list and remove it.
641static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
642 const BlockDecl *block) {
643 while (true) {
644 assert(head && *head);
645 CGBlockInfo *cur = *head;
646
647 // If this is the block we're looking for, splice it out of the list.
648 if (cur->getBlockDecl() == block) {
649 *head = cur->NextBlockInfo;
650 return cur;
651 }
652
653 head = &cur->NextBlockInfo;
654 }
655}
656
657/// Destroy a chain of block layouts.
658void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
659 assert(head && "destroying an empty chain");
660 do {
661 CGBlockInfo *cur = head;
662 head = cur->NextBlockInfo;
663 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000664 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000665}
666
John McCall351762c2011-02-07 10:33:21 +0000667/// Emit a block literal expression in the current function.
668llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000669 // If the block has no captures, we won't have a pre-computed
670 // layout for it.
671 if (!blockExpr->getBlockDecl()->hasCaptures()) {
672 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000673 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000674 blockInfo.BlockExpression = blockExpr;
675 return EmitBlockLiteral(blockInfo);
676 }
John McCall351762c2011-02-07 10:33:21 +0000677
John McCall08ef4662011-11-10 08:15:53 +0000678 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000679 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000680 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
681 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000682
John McCall08ef4662011-11-10 08:15:53 +0000683 blockInfo->BlockExpression = blockExpr;
684 return EmitBlockLiteral(*blockInfo);
685}
686
687llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
688 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000689 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall351762c2011-02-07 10:33:21 +0000690 llvm::Constant *blockFn
Fariborz Jahanian63628032012-06-26 16:06:38 +0000691 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCalldec348f72013-05-03 07:33:41 +0000692 LocalDeclMap,
693 isLambdaConv);
John McCalle3dc1702011-02-15 09:22:45 +0000694 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000695
696 // If there is nothing to capture, we can emit this as a global block.
697 if (blockInfo.CanBeGlobal)
698 return buildGlobalBlock(CGM, blockInfo, blockFn);
699
700 // Otherwise, we have to emit this as a local block.
701
702 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCalle3dc1702011-02-15 09:22:45 +0000703 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000704
705 // Build the block descriptor.
706 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
707
John McCall08ef4662011-11-10 08:15:53 +0000708 llvm::AllocaInst *blockAddr = blockInfo.Address;
709 assert(blockAddr && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000710
711 // Compute the initial on-stack block flags.
John McCallad7c5c12011-02-08 08:22:06 +0000712 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000713 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall351762c2011-02-07 10:33:21 +0000714 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
715 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall85915252011-03-09 08:39:33 +0000716 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +0000717
718 // Initialize the block literal.
719 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall08ef4662011-11-10 08:15:53 +0000720 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall351762c2011-02-07 10:33:21 +0000721 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall08ef4662011-11-10 08:15:53 +0000722 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall351762c2011-02-07 10:33:21 +0000723 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
724 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
725 "block.invoke"));
726 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
727 "block.descriptor"));
728
729 // Finally, capture all the values into the block.
730 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
731
732 // First, 'this'.
733 if (blockDecl->capturesCXXThis()) {
734 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
735 blockInfo.CXXThisIndex,
736 "block.captured-this.addr");
737 Builder.CreateStore(LoadCXXThis(), addr);
738 }
739
740 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000741 for (const auto &CI : blockDecl->captures()) {
742 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000743 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
744
745 // Ignore constant captures.
746 if (capture.isConstant()) continue;
747
748 QualType type = variable->getType();
John McCall4d14a902013-04-08 23:27:49 +0000749 CharUnits align = getContext().getDeclAlign(variable);
John McCall351762c2011-02-07 10:33:21 +0000750
751 // This will be a [[type]]*, except that a byref entry will just be
752 // an i8**.
753 llvm::Value *blockField =
754 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
755 "block.captured");
756
757 // Compute the address of the thing we're going to move into the
758 // block literal.
759 llvm::Value *src;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000760 if (BlockInfo && CI.isNested()) {
John McCall351762c2011-02-07 10:33:21 +0000761 // We need to use the capture from the enclosing block.
762 const CGBlockInfo::Capture &enclosingCapture =
763 BlockInfo->getCapture(variable);
764
765 // This is a [[type]]*, except that a byref entry wil just be an i8**.
766 src = Builder.CreateStructGEP(LoadBlockStruct(),
767 enclosingCapture.getIndex(),
768 "block.capture.addr");
Eli Friedman98b01ed2012-03-01 04:01:32 +0000769 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000770 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000771 // special; we'll simply emit it directly.
Craig Topper8a13c412014-05-21 05:09:00 +0000772 src = nullptr;
John McCall351762c2011-02-07 10:33:21 +0000773 } else {
John McCalla37c2fa2013-03-04 06:32:36 +0000774 // Just look it up in the locals map, which will give us back a
775 // [[type]]*. If that doesn't work, do the more elaborate DRE
776 // emission.
777 src = LocalDeclMap.lookup(variable);
778 if (!src) {
Aaron Ballman9371dd22014-03-14 18:34:04 +0000779 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
780 /*refersToEnclosing*/ CI.isNested(), type,
John McCalla37c2fa2013-03-04 06:32:36 +0000781 VK_LValue, SourceLocation());
782 src = EmitDeclRefLValue(&declRef).getAddress();
783 }
John McCall351762c2011-02-07 10:33:21 +0000784 }
785
786 // For byrefs, we just write the pointer to the byref struct into
787 // the block field. There's no need to chase the forwarding
788 // pointer at this point, since we're building something that will
789 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000790 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000791 // Get a void* that points to the byref struct.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000792 if (CI.isNested())
John McCall4d14a902013-04-08 23:27:49 +0000793 src = Builder.CreateAlignedLoad(src, align.getQuantity(),
794 "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000795 else
John McCalle3dc1702011-02-15 09:22:45 +0000796 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000797
John McCalle3dc1702011-02-15 09:22:45 +0000798 // Write that void* into the capture field.
John McCall4d14a902013-04-08 23:27:49 +0000799 Builder.CreateAlignedStore(src, blockField, align.getQuantity());
John McCall351762c2011-02-07 10:33:21 +0000800
801 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000802 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000803 if (blockDecl->isConversionFromLambda()) {
804 // If we have a lambda conversion, emit the expression
805 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000806 AggValueSlot Slot =
John McCall4d14a902013-04-08 23:27:49 +0000807 AggValueSlot::forAddr(blockField, align, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000808 AggValueSlot::IsDestructed,
809 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000810 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000811 EmitAggExpr(copyExpr, Slot);
812 } else {
813 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
814 }
John McCall351762c2011-02-07 10:33:21 +0000815
816 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000817 } else if (type->isReferenceType()) {
John McCall4d14a902013-04-08 23:27:49 +0000818 llvm::Value *ref =
819 Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
820 Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
821
822 // If this is an ARC __strong block-pointer variable, don't do a
823 // block copy.
824 //
825 // TODO: this can be generalized into the normal initialization logic:
826 // we should never need to do a block-copy when initializing a local
827 // variable, because the local variable's lifetime should be strictly
828 // contained within the stack block's.
829 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
830 type->isBlockPointerType()) {
831 // Load the block and do a simple retain.
832 LValue srcLV = MakeAddrLValue(src, type, align);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000833 llvm::Value *value = EmitLoadOfScalar(srcLV, SourceLocation());
John McCall4d14a902013-04-08 23:27:49 +0000834 value = EmitARCRetainNonBlock(value);
835
836 // Do a primitive store to the block field.
837 LValue destLV = MakeAddrLValue(blockField, type, align);
838 EmitStoreOfScalar(value, destLV, /*init*/ true);
John McCall351762c2011-02-07 10:33:21 +0000839
840 // Otherwise, fake up a POD copy into the block field.
841 } else {
John McCall31168b02011-06-15 23:02:42 +0000842 // Fake up a new variable so that EmitScalarInit doesn't think
843 // we're referring to the variable in its own initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000844 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
845 SourceLocation(), /*name*/ nullptr,
846 type);
John McCall31168b02011-06-15 23:02:42 +0000847
John McCall93be3f72011-02-07 18:37:40 +0000848 // We use one of these or the other depending on whether the
849 // reference is nested.
John McCall113bee02012-03-10 09:33:50 +0000850 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
Aaron Ballman9371dd22014-03-14 18:34:04 +0000851 /*refersToEnclosing*/ CI.isNested(), type,
John McCall113bee02012-03-10 09:33:50 +0000852 VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000853
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000854 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000855 &declRef, VK_RValue);
John McCall1553b192011-06-16 04:16:24 +0000856 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall4d14a902013-04-08 23:27:49 +0000857 MakeAddrLValue(blockField, type, align),
John McCall5c8f6c42011-03-08 09:38:48 +0000858 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000859 }
860
John McCall08ef4662011-11-10 08:15:53 +0000861 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000862 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000863 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
864 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000865 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000866 }
John McCall351762c2011-02-07 10:33:21 +0000867 }
868
869 // Cast to the converted block-pointer type, which happens (somewhat
870 // unfortunately) to be a pointer to function type.
871 llvm::Value *result =
872 Builder.CreateBitCast(blockAddr,
873 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +0000874
John McCall351762c2011-02-07 10:33:21 +0000875 return result;
Mike Stump85284ba2009-02-13 16:19:19 +0000876}
877
878
Chris Lattnera5f58b02011-07-09 17:41:47 +0000879llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +0000880 if (BlockDescriptorType)
881 return BlockDescriptorType;
882
Chris Lattnera5f58b02011-07-09 17:41:47 +0000883 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000884 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000885
Mike Stump650c9322009-02-13 15:16:56 +0000886 // struct __block_descriptor {
887 // unsigned long reserved;
888 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +0000889 //
890 // // later, the following will be added
891 //
892 // struct {
893 // void (*copyHelper)();
894 // void (*copyHelper)();
895 // } helpers; // !!! optional
896 //
897 // const char *signature; // the block signature
898 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +0000899 // };
Chris Lattner845511f2011-06-18 22:49:11 +0000900 BlockDescriptorType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000901 llvm::StructType::create("struct.__block_descriptor",
902 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stump650c9322009-02-13 15:16:56 +0000903
John McCall351762c2011-02-07 10:33:21 +0000904 // Now form a pointer to that.
905 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stump650c9322009-02-13 15:16:56 +0000906 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000907}
908
Chris Lattnera5f58b02011-07-09 17:41:47 +0000909llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +0000910 if (GenericBlockLiteralType)
911 return GenericBlockLiteralType;
912
Chris Lattnera5f58b02011-07-09 17:41:47 +0000913 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000914
Mike Stump005c9a62009-02-13 15:25:34 +0000915 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000916 // void *__isa;
917 // int __flags;
918 // int __reserved;
919 // void (*__invoke)(void *);
920 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000921 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000922 GenericBlockLiteralType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000923 llvm::StructType::create("struct.__block_literal_generic",
924 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
925 BlockDescPtrTy, NULL);
Mike Stumpb7074c02009-02-13 15:32:32 +0000926
Mike Stump005c9a62009-02-13 15:25:34 +0000927 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000928}
929
Mike Stump5d2534ad2009-02-19 01:01:04 +0000930
Nick Lewycky2d84e842013-10-02 02:29:49 +0000931RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +0000932 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000933 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000934 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +0000935
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000936 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
937
938 // Get a pointer to the generic block literal.
Chris Lattner2192fe52011-07-18 04:24:23 +0000939 llvm::Type *BlockLiteralTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000940 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000941
942 // Bitcast the callee to a block literal.
Mike Stumpb7074c02009-02-13 15:32:32 +0000943 llvm::Value *BlockLiteral =
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000944 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
945
946 // Get the function pointer from the literal.
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000947 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000948
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000949 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000950
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000951 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000952 CallArgList Args;
John McCall9dc0db22011-05-15 01:53:33 +0000953 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000954
Anders Carlsson479e6fc2009-04-08 23:13:16 +0000955 QualType FnType = BPT->getPointeeType();
956
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000957 // And the rest of the arguments.
John McCall9dd450b2009-09-21 23:43:11 +0000958 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson479e6fc2009-04-08 23:13:16 +0000959 E->arg_begin(), E->arg_end());
Mike Stumpb7074c02009-02-13 15:32:32 +0000960
Anders Carlsson5f50c652009-04-07 22:10:22 +0000961 // Load the function.
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000962 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson5f50c652009-04-07 22:10:22 +0000963
John McCall85915252011-03-09 08:39:33 +0000964 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +0000965 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +0000966 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Anders Carlsson5f50c652009-04-07 22:10:22 +0000968 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +0000969 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +0000970
Chris Lattner2192fe52011-07-18 04:24:23 +0000971 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson5f50c652009-04-07 22:10:22 +0000972 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000973
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000974 // And call the block.
Anders Carlssonbfb36712009-12-24 21:13:40 +0000975 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000976}
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000977
John McCall351762c2011-02-07 10:33:21 +0000978llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
979 bool isByRef) {
980 assert(BlockInfo && "evaluating block ref without block information?");
981 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +0000982
John McCall351762c2011-02-07 10:33:21 +0000983 // Handle constant captures.
984 if (capture.isConstant()) return LocalDeclMap[variable];
John McCall87fe5d52010-05-20 01:18:31 +0000985
John McCall351762c2011-02-07 10:33:21 +0000986 llvm::Value *addr =
987 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
988 "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +0000989
John McCall351762c2011-02-07 10:33:21 +0000990 if (isByRef) {
991 // addr should be a void** right now. Load, then cast the result
992 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +0000993
John McCall351762c2011-02-07 10:33:21 +0000994 addr = Builder.CreateLoad(addr);
Chris Lattner2192fe52011-07-18 04:24:23 +0000995 llvm::PointerType *byrefPointerType
John McCall351762c2011-02-07 10:33:21 +0000996 = llvm::PointerType::get(BuildByRefType(variable), 0);
997 addr = Builder.CreateBitCast(addr, byrefPointerType,
998 "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +0000999
John McCall351762c2011-02-07 10:33:21 +00001000 // Follow the forwarding pointer.
1001 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
1002 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001003
John McCall351762c2011-02-07 10:33:21 +00001004 // Cast back to byref* and GEP over to the actual object.
1005 addr = Builder.CreateBitCast(addr, byrefPointerType);
1006 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
1007 variable->getNameAsString());
John McCall87fe5d52010-05-20 01:18:31 +00001008 }
1009
Fariborz Jahanian10317ea2011-11-02 22:53:43 +00001010 if (variable->getType()->isReferenceType())
John McCall351762c2011-02-07 10:33:21 +00001011 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001012
John McCall351762c2011-02-07 10:33:21 +00001013 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001014}
1015
Mike Stump2d5a2872009-02-14 22:16:35 +00001016llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001017CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCalle3dc1702011-02-15 09:22:45 +00001018 const char *name) {
John McCall08ef4662011-11-10 08:15:53 +00001019 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1020 blockInfo.BlockExpression = blockExpr;
Mike Stumpb7074c02009-02-13 15:32:32 +00001021
John McCall351762c2011-02-07 10:33:21 +00001022 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001023 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001024
John McCall351762c2011-02-07 10:33:21 +00001025 // Using that metadata, generate the actual block function.
1026 llvm::Constant *blockFn;
1027 {
1028 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCallad7c5c12011-02-08 08:22:06 +00001029 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1030 blockInfo,
John McCalldec348f72013-05-03 07:33:41 +00001031 LocalDeclMap,
Eli Friedman2495ab02012-02-25 02:48:22 +00001032 false);
John McCall351762c2011-02-07 10:33:21 +00001033 }
John McCalle3dc1702011-02-15 09:22:45 +00001034 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001035
John McCallad7c5c12011-02-08 08:22:06 +00001036 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001037}
1038
John McCall351762c2011-02-07 10:33:21 +00001039static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1040 const CGBlockInfo &blockInfo,
1041 llvm::Constant *blockFn) {
1042 assert(blockInfo.CanBeGlobal);
1043
1044 // Generate the constants for the block literal initializer.
1045 llvm::Constant *fields[BlockHeaderSize];
1046
1047 // isa
1048 fields[0] = CGM.getNSConcreteGlobalBlock();
1049
1050 // __flags
John McCall85915252011-03-09 08:39:33 +00001051 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1052 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1053
John McCalle3dc1702011-02-15 09:22:45 +00001054 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall351762c2011-02-07 10:33:21 +00001055
1056 // Reserved
John McCalle3dc1702011-02-15 09:22:45 +00001057 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall351762c2011-02-07 10:33:21 +00001058
1059 // Function
1060 fields[3] = blockFn;
1061
1062 // Descriptor
1063 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1064
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001065 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall351762c2011-02-07 10:33:21 +00001066
1067 llvm::GlobalVariable *literal =
1068 new llvm::GlobalVariable(CGM.getModule(),
1069 init->getType(),
1070 /*constant*/ true,
1071 llvm::GlobalVariable::InternalLinkage,
1072 init,
1073 "__block_literal_global");
1074 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1075
1076 // Return a constant of the appropriately-casted type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001077 llvm::Type *requiredType =
John McCall351762c2011-02-07 10:33:21 +00001078 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1079 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001080}
1081
Mike Stump4446dcf2009-03-05 08:32:30 +00001082llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001083CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1084 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001085 const DeclMapTy &ldm,
1086 bool IsLambdaConversionToBlock) {
John McCall351762c2011-02-07 10:33:21 +00001087 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001088
Fariborz Jahanian63628032012-06-26 16:06:38 +00001089 CurGD = GD;
1090
John McCall351762c2011-02-07 10:33:21 +00001091 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001092
Mike Stump5469f292009-03-13 23:34:28 +00001093 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001094 // to be local to this function as well, in case they're directly
1095 // referenced in a block.
1096 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001097 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001098 if (var && !var->hasLocalStorage())
1099 LocalDeclMap[var] = i->second;
Mike Stump5469f292009-03-13 23:34:28 +00001100 }
1101
John McCall351762c2011-02-07 10:33:21 +00001102 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001103
John McCall351762c2011-02-07 10:33:21 +00001104 // Build the argument list.
1105 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001106
John McCall351762c2011-02-07 10:33:21 +00001107 // The first argument is the block pointer. Just take it as a void*
1108 // and cast it later.
1109 QualType selfTy = getContext().VoidPtrTy;
Mike Stump7fe9cc12009-10-21 03:49:08 +00001110 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001111
Richard Smith053f6c62014-05-16 23:01:30 +00001112 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
John McCall147d0212011-02-22 22:38:33 +00001113 SourceLocation(), II, selfTy);
John McCalla738c252011-03-09 04:27:21 +00001114 args.push_back(&selfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001115
John McCall351762c2011-02-07 10:33:21 +00001116 // Now add the rest of the parameters.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00001117 for (auto i : blockDecl->params())
1118 args.push_back(i);
John McCall87fe5d52010-05-20 01:18:31 +00001119
John McCall351762c2011-02-07 10:33:21 +00001120 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001121 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
Reid Kleckner4982b822014-01-31 22:54:50 +00001122 const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
Alp Toker314cc812014-01-25 16:55:45 +00001123 fnType->getReturnType(), args, fnType->getExtInfo(),
1124 fnType->isVariadic());
Tim Northovere77cc392014-03-29 13:28:05 +00001125 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001126 blockInfo.UsesStret = true;
1127
John McCalla729c622012-02-17 03:33:10 +00001128 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001129
Alp Toker0e64e0d2014-06-03 02:13:57 +00001130 std::string name = CGM.getBlockMangledName(GD, blockDecl);
1131 llvm::Function *fn = llvm::Function::Create(
1132 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001133 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001134
John McCall351762c2011-02-07 10:33:21 +00001135 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001136 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001137 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001138 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001139
John McCall147d0212011-02-22 22:38:33 +00001140 // Okay. Undo some of what StartFunction did.
1141
1142 // Pull the 'self' reference out of the local decl map.
1143 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1144 LocalDeclMap.erase(&selfDecl);
John McCall351762c2011-02-07 10:33:21 +00001145 BlockPointer = Builder.CreateBitCast(blockAddr,
1146 blockInfo.StructureType->getPointerTo(),
1147 "block");
Adrian Prantl0f6df002013-03-29 19:20:35 +00001148 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1149 // won't delete the dbg.declare intrinsics for captured variables.
1150 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1151 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1152 // Allocate a stack slot for it, so we can point the debugger to it
1153 llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
1154 "block.addr");
1155 unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
1156 Alloca->setAlignment(Align);
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001157 // Set the DebugLocation to empty, so the store is recognized as a
1158 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl2e0637f2013-07-18 00:28:02 +00001159 NoLocation NL(*this, Builder);
Adrian Prantl0f6df002013-03-29 19:20:35 +00001160 Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
1161 BlockPointerDbgLoc = Alloca;
1162 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001163
John McCall87fe5d52010-05-20 01:18:31 +00001164 // If we have a C++ 'this' reference, go ahead and force it into
1165 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001166 if (blockDecl->capturesCXXThis()) {
1167 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1168 blockInfo.CXXThisIndex,
1169 "block.captured-this");
1170 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001171 }
1172
John McCall351762c2011-02-07 10:33:21 +00001173 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001174 for (const auto &CI : blockDecl->captures()) {
1175 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001176 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1177 if (!capture.isConstant()) continue;
1178
1179 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1180
1181 llvm::AllocaInst *alloca =
1182 CreateMemTemp(variable->getType(), "block.captured-const");
1183 alloca->setAlignment(align);
1184
Adrian Prantl51936dd2013-03-14 17:53:33 +00001185 Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
John McCall351762c2011-02-07 10:33:21 +00001186
1187 LocalDeclMap[variable] = alloca;
John McCall9d42f0f2010-05-21 04:11:14 +00001188 }
1189
John McCall113bee02012-03-10 09:33:50 +00001190 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001191 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1192 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1193 --entry_ptr;
1194
Eli Friedman2495ab02012-02-25 02:48:22 +00001195 if (IsLambdaConversionToBlock)
1196 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001197 else {
1198 PGO.assignRegionCounters(blockDecl, fn);
1199 RegionCounter Cnt = getPGORegionCounter(blockDecl->getBody());
1200 Cnt.beginRegion(Builder);
Eli Friedman2495ab02012-02-25 02:48:22 +00001201 EmitStmt(blockDecl->getBody());
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +00001202 PGO.emitInstrumentationData();
Bob Wilsonc845c002014-03-06 20:24:27 +00001203 PGO.destroyRegionCounters();
1204 }
Mike Stump017460a2009-10-01 22:29:41 +00001205
Mike Stump7d699112009-10-01 00:27:30 +00001206 // Remember where we were...
1207 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001208
Mike Stump7d699112009-10-01 00:27:30 +00001209 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001210 ++entry_ptr;
1211 Builder.SetInsertPoint(entry, entry_ptr);
1212
John McCall113bee02012-03-10 09:33:50 +00001213 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001214 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001215 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001216 for (const auto &CI : blockDecl->captures()) {
1217 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001218 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001219
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001220 if (CGM.getCodeGenOpts().getDebugInfo()
1221 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001222 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1223 if (capture.isConstant()) {
1224 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1225 Builder);
1226 continue;
1227 }
John McCall351762c2011-02-07 10:33:21 +00001228
Adrian Prantl0f6df002013-03-29 19:20:35 +00001229 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
Alexey Samsonov74a38682012-05-04 07:39:27 +00001230 Builder, blockInfo);
1231 }
Mike Stump2e722b92009-09-30 02:43:10 +00001232 }
Manman Renab08a9a2013-01-04 18:51:35 +00001233 // Recover location if it was changed in the above loop.
1234 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001235 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001236 }
John McCall351762c2011-02-07 10:33:21 +00001237
Mike Stump7d699112009-10-01 00:27:30 +00001238 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001239 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001240 Builder.ClearInsertionPoint();
1241 else
1242 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001243
John McCall351762c2011-02-07 10:33:21 +00001244 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001245
John McCall351762c2011-02-07 10:33:21 +00001246 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001247}
Mike Stump1db7d042009-02-28 09:07:16 +00001248
John McCall351762c2011-02-07 10:33:21 +00001249/*
1250 notes.push_back(HelperInfo());
1251 HelperInfo &note = notes.back();
1252 note.index = capture.getIndex();
1253 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1254 note.cxxbar_import = ci->getCopyExpr();
Mike Stump1db7d042009-02-28 09:07:16 +00001255
John McCall351762c2011-02-07 10:33:21 +00001256 if (ci->isByRef()) {
1257 note.flag = BLOCK_FIELD_IS_BYREF;
1258 if (type.isObjCGCWeak())
1259 note.flag |= BLOCK_FIELD_IS_WEAK;
1260 } else if (type->isBlockPointerType()) {
1261 note.flag = BLOCK_FIELD_IS_BLOCK;
1262 } else {
1263 note.flag = BLOCK_FIELD_IS_OBJECT;
1264 }
1265 */
Mike Stump1db7d042009-02-28 09:07:16 +00001266
Mike Stump4446dcf2009-03-05 08:32:30 +00001267
John McCallf593b102013-01-22 03:56:22 +00001268/// Generate the copy-helper function for a block closure object:
1269/// static void block_copy_helper(block_t *dst, block_t *src);
1270/// The runtime will have previously initialized 'dst' by doing a
1271/// bit-copy of 'src'.
1272///
1273/// Note that this copies an entire block closure object to the heap;
1274/// it should not be confused with a 'byref copy helper', which moves
1275/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001276llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001277CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001278 ASTContext &C = getContext();
1279
1280 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001281 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1282 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001283 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001284 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1285 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001286 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001287
Reid Kleckner4982b822014-01-31 22:54:50 +00001288 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1289 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stump0c743272009-03-06 01:33:24 +00001290
John McCall351762c2011-02-07 10:33:21 +00001291 // FIXME: it would be nice if these were mergeable with things with
1292 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001293 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001294
1295 llvm::Function *Fn =
1296 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001297 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001298
1299 IdentifierInfo *II
1300 = &CGM.getContext().Idents.get("__copy_helper_block_");
1301
John McCall351762c2011-02-07 10:33:21 +00001302 FunctionDecl *FD = FunctionDecl::Create(C,
1303 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001304 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001305 SourceLocation(), II, C.VoidTy,
1306 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001307 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001308 false);
Adrian Prantl49a78562013-07-24 20:34:39 +00001309 // Create a scope with an artificial location for the body of this function.
Adrian Prantlb75016d2013-07-18 01:36:04 +00001310 ArtificialLocation AL(*this, Builder);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001311 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl49a78562013-07-24 20:34:39 +00001312 AL.Emit();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001313
Chris Lattner2192fe52011-07-18 04:24:23 +00001314 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001315
John McCalla738c252011-03-09 04:27:21 +00001316 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCallad7c5c12011-02-08 08:22:06 +00001317 src = Builder.CreateLoad(src);
1318 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001319
John McCalla738c252011-03-09 04:27:21 +00001320 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCallad7c5c12011-02-08 08:22:06 +00001321 dst = Builder.CreateLoad(dst);
1322 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001323
John McCall351762c2011-02-07 10:33:21 +00001324 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001325
Aaron Ballman9371dd22014-03-14 18:34:04 +00001326 for (const auto &CI : blockDecl->captures()) {
1327 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001328 QualType type = variable->getType();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001329
John McCall351762c2011-02-07 10:33:21 +00001330 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1331 if (capture.isConstant()) continue;
1332
Aaron Ballman9371dd22014-03-14 18:34:04 +00001333 const Expr *copyExpr = CI.getCopyExpr();
John McCall31168b02011-06-15 23:02:42 +00001334 BlockFieldFlags flags;
1335
John McCalle68b8f42012-10-17 02:28:37 +00001336 bool useARCWeakCopy = false;
1337 bool useARCStrongCopy = false;
John McCall351762c2011-02-07 10:33:21 +00001338
1339 if (copyExpr) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001340 assert(!CI.isByRef());
John McCall351762c2011-02-07 10:33:21 +00001341 // don't bother computing flags
John McCall31168b02011-06-15 23:02:42 +00001342
Aaron Ballman9371dd22014-03-14 18:34:04 +00001343 } else if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001344 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001345 if (type.isObjCGCWeak())
1346 flags |= BLOCK_FIELD_IS_WEAK;
John McCall351762c2011-02-07 10:33:21 +00001347
John McCall31168b02011-06-15 23:02:42 +00001348 } else if (type->isObjCRetainableType()) {
1349 flags = BLOCK_FIELD_IS_OBJECT;
John McCalle68b8f42012-10-17 02:28:37 +00001350 bool isBlockPointer = type->isBlockPointerType();
1351 if (isBlockPointer)
John McCall31168b02011-06-15 23:02:42 +00001352 flags = BLOCK_FIELD_IS_BLOCK;
1353
1354 // Special rules for ARC captures:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001355 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001356 Qualifiers qs = type.getQualifiers();
1357
John McCalle68b8f42012-10-17 02:28:37 +00001358 // We need to register __weak direct captures with the runtime.
1359 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1360 useARCWeakCopy = true;
John McCall31168b02011-06-15 23:02:42 +00001361
John McCalle68b8f42012-10-17 02:28:37 +00001362 // We need to retain the copied value for __strong direct captures.
1363 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1364 // If it's a block pointer, we have to copy the block and
1365 // assign that to the destination pointer, so we might as
1366 // well use _Block_object_assign. Otherwise we can avoid that.
1367 if (!isBlockPointer)
1368 useARCStrongCopy = true;
1369
1370 // Otherwise the memcpy is fine.
1371 } else {
1372 continue;
1373 }
1374
1375 // Non-ARC captures of retainable pointers are strong and
1376 // therefore require a call to _Block_object_assign.
1377 } else {
1378 // fall through
John McCall31168b02011-06-15 23:02:42 +00001379 }
1380 } else {
1381 continue;
1382 }
John McCall351762c2011-02-07 10:33:21 +00001383
1384 unsigned index = capture.getIndex();
John McCallad7c5c12011-02-08 08:22:06 +00001385 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1386 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall351762c2011-02-07 10:33:21 +00001387
1388 // If there's an explicit copy expression, we do that.
1389 if (copyExpr) {
John McCallad7c5c12011-02-08 08:22:06 +00001390 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCalle68b8f42012-10-17 02:28:37 +00001391 } else if (useARCWeakCopy) {
John McCall31168b02011-06-15 23:02:42 +00001392 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001393 } else {
1394 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCalle68b8f42012-10-17 02:28:37 +00001395 if (useARCStrongCopy) {
1396 // At -O0, store null into the destination field (so that the
1397 // storeStrong doesn't over-release) and then call storeStrong.
1398 // This is a workaround to not having an initStrong call.
1399 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001400 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001401 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1402 Builder.CreateStore(null, dstField);
1403 EmitARCStoreStrongCall(dstField, srcValue, true);
1404
1405 // With optimization enabled, take advantage of the fact that
1406 // the blocks runtime guarantees a memcpy of the block data, and
1407 // just emit a retain of the src field.
1408 } else {
1409 EmitARCRetainNonBlock(srcValue);
1410
1411 // We don't need this anymore, so kill it. It's not quite
1412 // worth the annoyance to avoid creating it in the first place.
1413 cast<llvm::Instruction>(dstField)->eraseFromParent();
1414 }
1415 } else {
1416 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1417 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001418 llvm::Value *args[] = {
1419 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1420 };
1421
1422 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001423 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001424 const Expr *copyExpr =
1425 CGM.getContext().getBlockVarCopyInits(variable);
1426 if (copyExpr) {
1427 copyCanThrow = true; // FIXME: reuse the noexcept logic
1428 }
1429 }
1430
1431 if (copyCanThrow) {
1432 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1433 } else {
1434 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1435 }
John McCalle68b8f42012-10-17 02:28:37 +00001436 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001437 }
1438 }
1439
John McCallad7c5c12011-02-08 08:22:06 +00001440 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001441
John McCalle3dc1702011-02-15 09:22:45 +00001442 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001443}
1444
John McCallf593b102013-01-22 03:56:22 +00001445/// Generate the destroy-helper function for a block closure object:
1446/// static void block_destroy_helper(block_t *theBlock);
1447///
1448/// Note that this destroys a heap-allocated block closure object;
1449/// it should not be confused with a 'byref destroy helper', which
1450/// destroys the heap-allocated contents of an individual __block
1451/// variable.
John McCall351762c2011-02-07 10:33:21 +00001452llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001453CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001454 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001455
John McCall351762c2011-02-07 10:33:21 +00001456 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001457 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1458 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001459 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001460
Reid Kleckner4982b822014-01-31 22:54:50 +00001461 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1462 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stump0c743272009-03-06 01:33:24 +00001463
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001464 // FIXME: We'd like to put these into a mergable by content, with
1465 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001466 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001467
1468 llvm::Function *Fn =
1469 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001470 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001471
1472 IdentifierInfo *II
1473 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1474
John McCall351762c2011-02-07 10:33:21 +00001475 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001476 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001477 SourceLocation(), II, C.VoidTy,
1478 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001479 false, false);
Adrian Prantl49a78562013-07-24 20:34:39 +00001480 // Create a scope with an artificial location for the body of this function.
Adrian Prantlb75016d2013-07-18 01:36:04 +00001481 ArtificialLocation AL(*this, Builder);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001482 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl49a78562013-07-24 20:34:39 +00001483 AL.Emit();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001484
Chris Lattner2192fe52011-07-18 04:24:23 +00001485 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001486
John McCalla738c252011-03-09 04:27:21 +00001487 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCallad7c5c12011-02-08 08:22:06 +00001488 src = Builder.CreateLoad(src);
1489 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001490
John McCall351762c2011-02-07 10:33:21 +00001491 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1492
John McCallad7c5c12011-02-08 08:22:06 +00001493 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001494
Aaron Ballman9371dd22014-03-14 18:34:04 +00001495 for (const auto &CI : blockDecl->captures()) {
1496 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001497 QualType type = variable->getType();
1498
1499 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1500 if (capture.isConstant()) continue;
1501
John McCallad7c5c12011-02-08 08:22:06 +00001502 BlockFieldFlags flags;
Craig Topper8a13c412014-05-21 05:09:00 +00001503 const CXXDestructorDecl *dtor = nullptr;
John McCall351762c2011-02-07 10:33:21 +00001504
John McCalle68b8f42012-10-17 02:28:37 +00001505 bool useARCWeakDestroy = false;
1506 bool useARCStrongDestroy = false;
John McCall31168b02011-06-15 23:02:42 +00001507
Aaron Ballman9371dd22014-03-14 18:34:04 +00001508 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001509 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001510 if (type.isObjCGCWeak())
1511 flags |= BLOCK_FIELD_IS_WEAK;
1512 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1513 if (record->hasTrivialDestructor())
1514 continue;
1515 dtor = record->getDestructor();
1516 } else if (type->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +00001517 flags = BLOCK_FIELD_IS_OBJECT;
John McCall31168b02011-06-15 23:02:42 +00001518 if (type->isBlockPointerType())
1519 flags = BLOCK_FIELD_IS_BLOCK;
John McCall351762c2011-02-07 10:33:21 +00001520
John McCall31168b02011-06-15 23:02:42 +00001521 // Special rules for ARC captures.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001522 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001523 Qualifiers qs = type.getQualifiers();
1524
1525 // Don't generate special dispose logic for a captured object
1526 // unless it's __strong or __weak.
1527 if (!qs.hasStrongOrWeakObjCLifetime())
1528 continue;
1529
1530 // Support __weak direct captures.
1531 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCalle68b8f42012-10-17 02:28:37 +00001532 useARCWeakDestroy = true;
1533
1534 // Tools really want us to use objc_storeStrong here.
1535 else
1536 useARCStrongDestroy = true;
John McCall31168b02011-06-15 23:02:42 +00001537 }
1538 } else {
1539 continue;
1540 }
John McCall351762c2011-02-07 10:33:21 +00001541
1542 unsigned index = capture.getIndex();
John McCallad7c5c12011-02-08 08:22:06 +00001543 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall351762c2011-02-07 10:33:21 +00001544
1545 // If there's an explicit copy expression, we do that.
1546 if (dtor) {
John McCallad7c5c12011-02-08 08:22:06 +00001547 PushDestructorCleanup(dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001548
John McCall31168b02011-06-15 23:02:42 +00001549 // If this is a __weak capture, emit the release directly.
John McCalle68b8f42012-10-17 02:28:37 +00001550 } else if (useARCWeakDestroy) {
John McCall31168b02011-06-15 23:02:42 +00001551 EmitARCDestroyWeak(srcField);
1552
John McCalle68b8f42012-10-17 02:28:37 +00001553 // Destroy strong objects with a call if requested.
1554 } else if (useARCStrongDestroy) {
John McCallcdda29c2013-03-13 03:10:54 +00001555 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001556
John McCall351762c2011-02-07 10:33:21 +00001557 // Otherwise we call _Block_object_dispose. It wouldn't be too
1558 // hard to just emit this as a cleanup if we wanted to make sure
1559 // that things were done in reverse.
1560 } else {
1561 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001562 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001563 BuildBlockRelease(value, flags);
1564 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001565 }
1566
John McCall351762c2011-02-07 10:33:21 +00001567 cleanups.ForceCleanup();
1568
John McCallad7c5c12011-02-08 08:22:06 +00001569 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001570
John McCalle3dc1702011-02-15 09:22:45 +00001571 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001572}
1573
John McCallf9b056b2011-03-31 08:03:29 +00001574namespace {
1575
1576/// Emits the copy/dispose helper functions for a __block object of id type.
1577class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1578 BlockFieldFlags Flags;
1579
1580public:
1581 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1582 : ByrefHelpers(alignment), Flags(flags) {}
1583
John McCall7c623642011-03-31 09:19:20 +00001584 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Craig Topper4f12f102014-03-12 06:41:41 +00001585 llvm::Value *srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001586 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1587
1588 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1589 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1590
1591 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1592
1593 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1594 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001595
1596 llvm::Value *args[] = { destField, srcValue, flagsVal };
1597 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001598 }
1599
Craig Topper4f12f102014-03-12 06:41:41 +00001600 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001601 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1602 llvm::Value *value = CGF.Builder.CreateLoad(field);
1603
1604 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1605 }
1606
Craig Topper4f12f102014-03-12 06:41:41 +00001607 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001608 id.AddInteger(Flags.getBitMask());
1609 }
1610};
1611
John McCall31168b02011-06-15 23:02:42 +00001612/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1613class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1614public:
1615 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1616
1617 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Craig Topper4f12f102014-03-12 06:41:41 +00001618 llvm::Value *srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001619 CGF.EmitARCMoveWeak(destField, srcField);
1620 }
1621
Craig Topper4f12f102014-03-12 06:41:41 +00001622 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCall31168b02011-06-15 23:02:42 +00001623 CGF.EmitARCDestroyWeak(field);
1624 }
1625
Craig Topper4f12f102014-03-12 06:41:41 +00001626 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001627 // 0 is distinguishable from all pointers and byref flags
1628 id.AddInteger(0);
1629 }
1630};
1631
1632/// Emits the copy/dispose helpers for an ARC __block __strong variable
1633/// that's not of block-pointer type.
1634class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1635public:
1636 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1637
1638 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Craig Topper4f12f102014-03-12 06:41:41 +00001639 llvm::Value *srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001640 // Do a "move" by copying the value and then zeroing out the old
1641 // variable.
1642
John McCall3a237aa2011-11-09 03:17:26 +00001643 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1644 value->setAlignment(Alignment.getQuantity());
1645
John McCall31168b02011-06-15 23:02:42 +00001646 llvm::Value *null =
1647 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001648
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001649 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
Fariborz Jahaniancc2ae882013-01-05 00:32:13 +00001650 llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1651 store->setAlignment(Alignment.getQuantity());
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001652 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1653 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1654 return;
1655 }
John McCall3a237aa2011-11-09 03:17:26 +00001656 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1657 store->setAlignment(Alignment.getQuantity());
1658
1659 store = CGF.Builder.CreateStore(null, srcField);
1660 store->setAlignment(Alignment.getQuantity());
John McCall31168b02011-06-15 23:02:42 +00001661 }
1662
Craig Topper4f12f102014-03-12 06:41:41 +00001663 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001664 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001665 }
1666
Craig Topper4f12f102014-03-12 06:41:41 +00001667 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001668 // 1 is distinguishable from all pointers and byref flags
1669 id.AddInteger(1);
1670 }
1671};
1672
John McCall3a237aa2011-11-09 03:17:26 +00001673/// Emits the copy/dispose helpers for an ARC __block __strong
1674/// variable that's of block-pointer type.
1675class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1676public:
1677 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1678
1679 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Craig Topper4f12f102014-03-12 06:41:41 +00001680 llvm::Value *srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001681 // Do the copy with objc_retainBlock; that's all that
1682 // _Block_object_assign would do anyway, and we'd have to pass the
1683 // right arguments to make sure it doesn't get no-op'ed.
1684 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1685 oldValue->setAlignment(Alignment.getQuantity());
1686
1687 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1688
1689 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1690 store->setAlignment(Alignment.getQuantity());
1691 }
1692
Craig Topper4f12f102014-03-12 06:41:41 +00001693 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001694 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001695 }
1696
Craig Topper4f12f102014-03-12 06:41:41 +00001697 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001698 // 2 is distinguishable from all pointers and byref flags
1699 id.AddInteger(2);
1700 }
1701};
1702
John McCallf9b056b2011-03-31 08:03:29 +00001703/// Emits the copy/dispose helpers for a __block variable with a
1704/// nontrivial copy constructor or destructor.
1705class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1706 QualType VarType;
1707 const Expr *CopyExpr;
1708
1709public:
1710 CXXByrefHelpers(CharUnits alignment, QualType type,
1711 const Expr *copyExpr)
1712 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1713
Craig Topper8a13c412014-05-21 05:09:00 +00001714 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCallf9b056b2011-03-31 08:03:29 +00001715 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Craig Topper4f12f102014-03-12 06:41:41 +00001716 llvm::Value *srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001717 if (!CopyExpr) return;
1718 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1719 }
1720
Craig Topper4f12f102014-03-12 06:41:41 +00001721 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001722 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1723 CGF.PushDestructorCleanup(VarType, field);
1724 CGF.PopCleanupBlocks(cleanupDepth);
1725 }
1726
Craig Topper4f12f102014-03-12 06:41:41 +00001727 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001728 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1729 }
1730};
1731} // end anonymous namespace
1732
1733static llvm::Constant *
1734generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2192fe52011-07-18 04:24:23 +00001735 llvm::StructType &byrefType,
John McCallf593b102013-01-22 03:56:22 +00001736 unsigned valueFieldIndex,
John McCallf9b056b2011-03-31 08:03:29 +00001737 CodeGenModule::ByrefHelpers &byrefInfo) {
1738 ASTContext &Context = CGF.getContext();
1739
1740 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001741
John McCalla738c252011-03-09 04:27:21 +00001742 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001743 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001744 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001745 args.push_back(&dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00001746
Craig Topper8a13c412014-05-21 05:09:00 +00001747 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001748 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001749 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001750
Reid Kleckner4982b822014-01-31 22:54:50 +00001751 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1752 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001753
John McCallf9b056b2011-03-31 08:03:29 +00001754 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCalla729c622012-02-17 03:33:10 +00001755 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001756
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001757 // FIXME: We'd like to put these into a mergable by content, with
1758 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001759 llvm::Function *Fn =
1760 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00001761 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001762
1763 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001764 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001765
John McCallf9b056b2011-03-31 08:03:29 +00001766 FunctionDecl *FD = FunctionDecl::Create(Context,
1767 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001768 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001769 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001770 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001771 false, false);
John McCall31168b02011-06-15 23:02:42 +00001772
Adrian Prantl22e66b42014-04-11 01:13:04 +00001773 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00001774
John McCallf9b056b2011-03-31 08:03:29 +00001775 if (byrefInfo.needsCopy()) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001776 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00001777
John McCallf9b056b2011-03-31 08:03:29 +00001778 // dst->x
1779 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1780 destField = CGF.Builder.CreateLoad(destField);
1781 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCallf593b102013-01-22 03:56:22 +00001782 destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001783
John McCallf9b056b2011-03-31 08:03:29 +00001784 // src->x
1785 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1786 srcField = CGF.Builder.CreateLoad(srcField);
1787 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCallf593b102013-01-22 03:56:22 +00001788 srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
John McCallf9b056b2011-03-31 08:03:29 +00001789
1790 byrefInfo.emitCopy(CGF, destField, srcField);
1791 }
1792
1793 CGF.FinishFunction();
1794
1795 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001796}
1797
John McCallf9b056b2011-03-31 08:03:29 +00001798/// Build the copy helper for a __block variable.
1799static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001800 llvm::StructType &byrefType,
John McCallf593b102013-01-22 03:56:22 +00001801 unsigned byrefValueIndex,
John McCallf9b056b2011-03-31 08:03:29 +00001802 CodeGenModule::ByrefHelpers &info) {
1803 CodeGenFunction CGF(CGM);
John McCallf593b102013-01-22 03:56:22 +00001804 return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
John McCallf9b056b2011-03-31 08:03:29 +00001805}
1806
1807/// Generate code for a __block variable's dispose helper.
1808static llvm::Constant *
1809generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2192fe52011-07-18 04:24:23 +00001810 llvm::StructType &byrefType,
John McCallf593b102013-01-22 03:56:22 +00001811 unsigned byrefValueIndex,
John McCallf9b056b2011-03-31 08:03:29 +00001812 CodeGenModule::ByrefHelpers &byrefInfo) {
1813 ASTContext &Context = CGF.getContext();
1814 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001815
John McCalla738c252011-03-09 04:27:21 +00001816 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001817 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001818 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001819 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001820
Reid Kleckner4982b822014-01-31 22:54:50 +00001821 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1822 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001823
John McCallf9b056b2011-03-31 08:03:29 +00001824 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCalla729c622012-02-17 03:33:10 +00001825 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001826
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001827 // FIXME: We'd like to put these into a mergable by content, with
1828 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001829 llvm::Function *Fn =
1830 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00001831 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00001832 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001833
1834 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001835 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001836
John McCallf9b056b2011-03-31 08:03:29 +00001837 FunctionDecl *FD = FunctionDecl::Create(Context,
1838 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001839 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001840 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001841 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001842 false, false);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001843 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00001844
John McCallf9b056b2011-03-31 08:03:29 +00001845 if (byrefInfo.needsDispose()) {
1846 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1847 V = CGF.Builder.CreateLoad(V);
1848 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
John McCallf593b102013-01-22 03:56:22 +00001849 V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
John McCallad7c5c12011-02-08 08:22:06 +00001850
John McCallf9b056b2011-03-31 08:03:29 +00001851 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian50198092010-12-02 17:02:11 +00001852 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001853
John McCallf9b056b2011-03-31 08:03:29 +00001854 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00001855
John McCallf9b056b2011-03-31 08:03:29 +00001856 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001857}
1858
John McCallf9b056b2011-03-31 08:03:29 +00001859/// Build the dispose helper for a __block variable.
1860static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001861 llvm::StructType &byrefType,
John McCallf593b102013-01-22 03:56:22 +00001862 unsigned byrefValueIndex,
John McCallf9b056b2011-03-31 08:03:29 +00001863 CodeGenModule::ByrefHelpers &info) {
1864 CodeGenFunction CGF(CGM);
John McCallf593b102013-01-22 03:56:22 +00001865 return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001866}
1867
John McCallf593b102013-01-22 03:56:22 +00001868/// Lazily build the copy and dispose helpers for a __block variable
1869/// with the given information.
John McCallf9b056b2011-03-31 08:03:29 +00001870template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001871 llvm::StructType &byrefTy,
John McCallf593b102013-01-22 03:56:22 +00001872 unsigned byrefValueIndex,
John McCallf9b056b2011-03-31 08:03:29 +00001873 T &byrefInfo) {
1874 // Increase the field's alignment to be at least pointer alignment,
1875 // since the layout of the byref struct will guarantee at least that.
1876 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1877 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1878
1879 llvm::FoldingSetNodeID id;
1880 byrefInfo.Profile(id);
1881
1882 void *insertPos;
1883 CodeGenModule::ByrefHelpers *node
1884 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1885 if (node) return static_cast<T*>(node);
1886
John McCallf593b102013-01-22 03:56:22 +00001887 byrefInfo.CopyHelper =
1888 buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1889 byrefInfo.DisposeHelper =
1890 buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
John McCallf9b056b2011-03-31 08:03:29 +00001891
1892 T *copy = new (CGM.getContext()) T(byrefInfo);
1893 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1894 return copy;
1895}
1896
John McCallf593b102013-01-22 03:56:22 +00001897/// Build the copy and dispose helpers for the given __block variable
1898/// emission. Places the helpers in the global cache. Returns null
1899/// if no helpers are required.
John McCallf9b056b2011-03-31 08:03:29 +00001900CodeGenModule::ByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00001901CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00001902 const AutoVarEmission &emission) {
1903 const VarDecl &var = *emission.Variable;
1904 QualType type = var.getType();
1905
John McCallf593b102013-01-22 03:56:22 +00001906 unsigned byrefValueIndex = getByRefValueLLVMField(&var);
1907
John McCallf9b056b2011-03-31 08:03:29 +00001908 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1909 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00001910 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00001911
1912 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
John McCallf593b102013-01-22 03:56:22 +00001913 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf9b056b2011-03-31 08:03:29 +00001914 }
1915
John McCall31168b02011-06-15 23:02:42 +00001916 // Otherwise, if we don't have a retainable type, there's nothing to do.
1917 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00001918 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001919
1920 Qualifiers qs = type.getQualifiers();
1921
1922 // If we have lifetime, that dominates.
1923 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001924 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00001925
1926 switch (lifetime) {
1927 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1928
1929 // These are just bits as far as the runtime is concerned.
1930 case Qualifiers::OCL_ExplicitNone:
1931 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00001932 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001933
1934 // Tell the runtime that this is ARC __weak, called by the
1935 // byref routines.
1936 case Qualifiers::OCL_Weak: {
1937 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
John McCallf593b102013-01-22 03:56:22 +00001938 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCall31168b02011-06-15 23:02:42 +00001939 }
1940
1941 // ARC __strong __block variables need to be retained.
1942 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00001943 // Block pointers need to be copied, and there's no direct
1944 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00001945 if (type->isBlockPointerType()) {
John McCall3a237aa2011-11-09 03:17:26 +00001946 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf593b102013-01-22 03:56:22 +00001947 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCall31168b02011-06-15 23:02:42 +00001948
1949 // Otherwise, we transfer ownership of the retain from the stack
1950 // to the heap.
1951 } else {
1952 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
John McCallf593b102013-01-22 03:56:22 +00001953 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCall31168b02011-06-15 23:02:42 +00001954 }
1955 }
1956 llvm_unreachable("fell out of lifetime switch!");
1957 }
1958
John McCallf9b056b2011-03-31 08:03:29 +00001959 BlockFieldFlags flags;
1960 if (type->isBlockPointerType()) {
1961 flags |= BLOCK_FIELD_IS_BLOCK;
1962 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1963 type->isObjCObjectPointerType()) {
1964 flags |= BLOCK_FIELD_IS_OBJECT;
1965 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001966 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00001967 }
1968
1969 if (type.isObjCGCWeak())
1970 flags |= BLOCK_FIELD_IS_WEAK;
1971
1972 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
John McCallf593b102013-01-22 03:56:22 +00001973 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001974}
1975
John McCall73064872011-03-31 01:59:53 +00001976unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1977 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1978
1979 return ByRefValueInfo.find(VD)->second.second;
1980}
1981
1982llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1983 const VarDecl *V) {
1984 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1985 Loc = Builder.CreateLoad(Loc);
1986 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1987 V->getNameAsString());
1988 return Loc;
1989}
1990
1991/// BuildByRefType - This routine changes a __block variable declared as T x
1992/// into:
1993///
1994/// struct {
1995/// void *__isa;
1996/// void *__forwarding;
1997/// int32_t __flags;
1998/// int32_t __size;
1999/// void *__copy_helper; // only if needed
2000/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002001/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002002/// char padding[X]; // only if needed
2003/// T x;
2004/// } x
2005///
Chris Lattner2192fe52011-07-18 04:24:23 +00002006llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
2007 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall73064872011-03-31 01:59:53 +00002008 if (Info.first)
2009 return Info.first;
2010
2011 QualType Ty = D->getType();
2012
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002013 SmallVector<llvm::Type *, 8> types;
John McCall73064872011-03-31 01:59:53 +00002014
Chris Lattnera5f58b02011-07-09 17:41:47 +00002015 llvm::StructType *ByRefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002016 llvm::StructType::create(getLLVMContext(),
2017 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002018
2019 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002020 types.push_back(Int8PtrTy);
John McCall73064872011-03-31 01:59:53 +00002021
2022 // void *__forwarding;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002023 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall73064872011-03-31 01:59:53 +00002024
2025 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002026 types.push_back(Int32Ty);
John McCall73064872011-03-31 01:59:53 +00002027
2028 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002029 types.push_back(Int32Ty);
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002030 // Note that this must match *exactly* the logic in buildByrefHelpers.
2031 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
John McCall73064872011-03-31 01:59:53 +00002032 if (HasCopyAndDispose) {
2033 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002034 types.push_back(Int8PtrTy);
John McCall73064872011-03-31 01:59:53 +00002035
2036 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002037 types.push_back(Int8PtrTy);
John McCall73064872011-03-31 01:59:53 +00002038 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002039 bool HasByrefExtendedLayout = false;
2040 Qualifiers::ObjCLifetime Lifetime;
2041 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2042 HasByrefExtendedLayout)
2043 /// void *__byref_variable_layout;
2044 types.push_back(Int8PtrTy);
John McCall73064872011-03-31 01:59:53 +00002045
2046 bool Packed = false;
2047 CharUnits Align = getContext().getDeclAlign(D);
John McCallc8e01702013-04-16 22:48:15 +00002048 if (Align >
2049 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
John McCall73064872011-03-31 01:59:53 +00002050 // We have to insert padding.
2051
2052 // The struct above has 2 32-bit integers.
2053 unsigned CurrentOffsetInBytes = 4 * 2;
2054
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002055 // And either 2, 3, 4 or 5 pointers.
2056 unsigned noPointers = 2;
2057 if (HasCopyAndDispose)
2058 noPointers += 2;
2059 if (HasByrefExtendedLayout)
2060 noPointers += 1;
2061
2062 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall73064872011-03-31 01:59:53 +00002063
2064 // Align the offset.
2065 unsigned AlignedOffsetInBytes =
2066 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2067
2068 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2069 if (NumPaddingBytes > 0) {
Chris Lattnerece04092012-02-07 00:39:47 +00002070 llvm::Type *Ty = Int8Ty;
John McCall73064872011-03-31 01:59:53 +00002071 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall9dc0db22011-05-15 01:53:33 +00002072 // the maximal stack alignment and the alignment of malloc on the system.
John McCall73064872011-03-31 01:59:53 +00002073 if (NumPaddingBytes > 1)
2074 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2075
John McCall9dc0db22011-05-15 01:53:33 +00002076 types.push_back(Ty);
John McCall73064872011-03-31 01:59:53 +00002077
2078 // We want a packed struct.
2079 Packed = true;
2080 }
2081 }
2082
2083 // T x;
John McCall9dc0db22011-05-15 01:53:33 +00002084 types.push_back(ConvertTypeForMem(Ty));
John McCall73064872011-03-31 01:59:53 +00002085
Chris Lattnera5f58b02011-07-09 17:41:47 +00002086 ByRefType->setBody(types, Packed);
John McCall73064872011-03-31 01:59:53 +00002087
Chris Lattnera5f58b02011-07-09 17:41:47 +00002088 Info.first = ByRefType;
John McCall73064872011-03-31 01:59:53 +00002089
John McCall9dc0db22011-05-15 01:53:33 +00002090 Info.second = types.size() - 1;
John McCall73064872011-03-31 01:59:53 +00002091
2092 return Info.first;
2093}
2094
2095/// Initialize the structural components of a __block variable, i.e.
2096/// everything but the actual object.
2097void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002098 // Find the address of the local.
2099 llvm::Value *addr = emission.Address;
John McCall73064872011-03-31 01:59:53 +00002100
John McCallf9b056b2011-03-31 08:03:29 +00002101 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002102 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf9b056b2011-03-31 08:03:29 +00002103 cast<llvm::PointerType>(addr->getType())->getElementType());
2104
2105 // Build the byref helpers if necessary. This is null if we don't need any.
2106 CodeGenModule::ByrefHelpers *helpers =
2107 buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002108
2109 const VarDecl &D = *emission.Variable;
2110 QualType type = D.getType();
2111
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002112 bool HasByrefExtendedLayout;
2113 Qualifiers::ObjCLifetime ByrefLifetime;
2114 bool ByRefHasLifetime =
2115 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2116
John McCallf9b056b2011-03-31 08:03:29 +00002117 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002118
2119 // Initialize the 'isa', which is just 0 or 1.
2120 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002121 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002122 isa = 1;
2123 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2124 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2125
2126 // Store the address of the variable into its own forwarding pointer.
2127 Builder.CreateStore(addr,
2128 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2129
2130 // Blocks ABI:
2131 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002132 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002133 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002134 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2135 if (ByRefHasLifetime) {
2136 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2137 else switch (ByrefLifetime) {
2138 case Qualifiers::OCL_Strong:
2139 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2140 break;
2141 case Qualifiers::OCL_Weak:
2142 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2143 break;
2144 case Qualifiers::OCL_ExplicitNone:
2145 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2146 break;
2147 case Qualifiers::OCL_None:
2148 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2149 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2150 break;
2151 default:
2152 break;
2153 }
2154 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2155 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2156 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2157 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2158 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2159 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2160 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2161 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2162 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2163 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2164 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2165 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2166 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2167 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2168 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2169 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2170 }
2171 printf("\n");
2172 }
2173 }
2174
John McCall73064872011-03-31 01:59:53 +00002175 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2176 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2177
John McCallf9b056b2011-03-31 08:03:29 +00002178 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2179 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall73064872011-03-31 01:59:53 +00002180 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2181
John McCallf9b056b2011-03-31 08:03:29 +00002182 if (helpers) {
John McCall73064872011-03-31 01:59:53 +00002183 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf9b056b2011-03-31 08:03:29 +00002184 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall73064872011-03-31 01:59:53 +00002185
2186 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf9b056b2011-03-31 08:03:29 +00002187 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall73064872011-03-31 01:59:53 +00002188 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002189 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2190 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2191 llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2192 "byref.layout");
2193 // cast destination to pointer to source type.
2194 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2195 DesTy = DesTy->getPointerTo();
2196 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2197 Builder.CreateStore(ByrefLayoutInfo, BC);
2198 }
John McCall73064872011-03-31 01:59:53 +00002199}
2200
John McCallad7c5c12011-02-08 08:22:06 +00002201void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002202 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002203 llvm::Value *args[] = {
2204 Builder.CreateBitCast(V, Int8PtrTy),
2205 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2206 };
2207 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002208}
John McCall73064872011-03-31 01:59:53 +00002209
2210namespace {
2211 struct CallBlockRelease : EHScopeStack::Cleanup {
2212 llvm::Value *Addr;
2213 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2214
Craig Topper4f12f102014-03-12 06:41:41 +00002215 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002216 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002217 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2218 }
2219 };
2220}
2221
2222/// Enter a cleanup to destroy a __block variable. Note that this
2223/// cleanup should be a no-op if the variable hasn't left the stack
2224/// yet; if a cleanup is required for the variable itself, that needs
2225/// to be done externally.
2226void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2227 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002228 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002229 return;
2230
2231 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2232}
John McCall7959fee2011-09-09 20:41:01 +00002233
2234/// Adjust the declaration of something from the blocks API.
2235static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2236 llvm::Constant *C) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002237 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall7959fee2011-09-09 20:41:01 +00002238
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002239 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002240 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002241 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2242}
2243
2244llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2245 if (BlockObjectDispose)
2246 return BlockObjectDispose;
2247
2248 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2249 llvm::FunctionType *fty
2250 = llvm::FunctionType::get(VoidTy, args, false);
2251 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2252 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2253 return BlockObjectDispose;
2254}
2255
2256llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2257 if (BlockObjectAssign)
2258 return BlockObjectAssign;
2259
2260 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2261 llvm::FunctionType *fty
2262 = llvm::FunctionType::get(VoidTy, args, false);
2263 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2264 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2265 return BlockObjectAssign;
2266}
2267
2268llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2269 if (NSConcreteGlobalBlock)
2270 return NSConcreteGlobalBlock;
2271
2272 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002273 Int8PtrTy->getPointerTo(),
2274 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002275 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2276 return NSConcreteGlobalBlock;
2277}
2278
2279llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2280 if (NSConcreteStackBlock)
2281 return NSConcreteStackBlock;
2282
2283 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002284 Int8PtrTy->getPointerTo(),
2285 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002286 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2287 return NSConcreteStackBlock;
2288}