blob: 2915dabe54148fc53ebeca17f0bf453ac4d7e1aa [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
Anders Carlsson2437cbf2009-02-12 00:39:25 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
John McCallad7c5c12011-02-08 08:22:06 +000014#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000017#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000020#include "ConstantEmitter.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000021#include "TargetInfo.h"
Mike Stump692c6e32009-03-20 21:53:12 +000022#include "clang/AST/DeclObjC.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000023#include "clang/CodeGen/ConstantInitBuilder.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000024#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Module.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000028#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000029#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000030
Anders Carlsson2437cbf2009-02-12 00:39:25 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall08ef4662011-11-10 08:15:53 +000034CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
35 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000036 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
John McCall7f416cc2015-09-08 08:05:57 +000037 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
Craig Topper8a13c412014-05-21 05:09:00 +000038 DominatingIP(nullptr) {
39
John McCall08ef4662011-11-10 08:15:53 +000040 // Skip asm prefix, if any. 'name' is usually taken directly from
41 // the mangled name of the enclosing function.
42 if (!name.empty() && name[0] == '\01')
43 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000044}
45
John McCallf9b056b2011-03-31 08:03:29 +000046// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000047BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000048
John McCall351762c2011-02-07 10:33:21 +000049/// Build the given block as a global block.
50static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
51 const CGBlockInfo &blockInfo,
52 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000053
John McCall351762c2011-02-07 10:33:21 +000054/// Build the helper function to copy a block.
55static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
56 const CGBlockInfo &blockInfo) {
57 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
58}
59
Alp Tokerf6a24ce2013-12-05 16:25:25 +000060/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000061static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
62 const CGBlockInfo &blockInfo) {
63 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
64}
65
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000066/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
67/// buildBlockDescriptor is accessed from 5th field of the Block_literal
68/// meta-data and contains stationary information about the block literal.
69/// Its definition will have 4 (or optinally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000070/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000071/// struct Block_descriptor {
72/// unsigned long reserved;
73/// unsigned long size; // size of Block_literal metadata in bytes.
74/// void *copy_func_helper_decl; // optional copy helper.
75/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000076/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000077/// void *block_layout_info; // encoding of captured block variables.
78/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000079/// \endcode
John McCall351762c2011-02-07 10:33:21 +000080static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
81 const CGBlockInfo &blockInfo) {
82 ASTContext &C = CGM.getContext();
83
John McCall6c9f1fdb2016-11-19 08:17:24 +000084 llvm::IntegerType *ulong =
85 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
86 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000087 if (CGM.getLangOpts().OpenCL)
88 i8p =
89 llvm::Type::getInt8PtrTy(
90 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
91 else
John McCall6c9f1fdb2016-11-19 08:17:24 +000092 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +000093
John McCall23c9dc62016-11-28 22:18:27 +000094 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +000095 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +000096
97 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +000098 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +000099
100 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +0000101 // FIXME: What is the right way to say this doesn't fit? We should give
102 // a user diagnostic in that case. Better fix would be to change the
103 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000104 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000105
John McCall351762c2011-02-07 10:33:21 +0000106 // Optional copy/dispose helpers.
107 if (blockInfo.NeedsCopyDispose) {
Mike Stump85284ba2009-02-13 16:19:19 +0000108 // copy_func_helper_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000109 elements.add(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000110
111 // destroy_func_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000112 elements.add(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000113 }
114
John McCall351762c2011-02-07 10:33:21 +0000115 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
116 std::string typeAtEncoding =
117 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000118 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000119 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000120
John McCall351762c2011-02-07 10:33:21 +0000121 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000122 if (C.getLangOpts().ObjC1) {
123 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000124 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000125 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000126 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000127 }
John McCall351762c2011-02-07 10:33:21 +0000128 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000129 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000130
Joey Goulyddbda402016-08-10 15:57:02 +0000131 unsigned AddrSpace = 0;
132 if (C.getLangOpts().OpenCL)
133 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000134
John McCall351762c2011-02-07 10:33:21 +0000135 llvm::GlobalVariable *global =
John McCall6c9f1fdb2016-11-19 08:17:24 +0000136 elements.finishAndCreateGlobal("__block_descriptor_tmp",
137 CGM.getPointerAlign(),
138 /*constant*/ true,
139 llvm::GlobalValue::InternalLinkage,
140 AddrSpace);
Mike Stump85284ba2009-02-13 16:19:19 +0000141
John McCall351762c2011-02-07 10:33:21 +0000142 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000143}
144
John McCall351762c2011-02-07 10:33:21 +0000145/*
146 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000147
John McCall351762c2011-02-07 10:33:21 +0000148 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
149 struct Block_literal {
150 /// Initialized to one of:
151 /// extern void *_NSConcreteStackBlock[];
152 /// extern void *_NSConcreteGlobalBlock[];
153 ///
154 /// In theory, we could start one off malloc'ed by setting
155 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
156 /// this isa:
157 /// extern void *_NSConcreteMallocBlock[];
158 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000159
John McCall351762c2011-02-07 10:33:21 +0000160 /// These are the flags (with corresponding bit number) that the
161 /// compiler is actually supposed to know about.
162 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
163 /// descriptor provides copy and dispose helper functions
164 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
165 /// object with a nontrivial destructor or copy constructor
166 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
167 /// as global memory
168 /// 29. BLOCK_USE_STRET - indicates that the block function
169 /// uses stret, which objc_msgSend needs to know about
170 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
171 /// @encoded signature string
172 /// And we're not supposed to manipulate these:
173 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
174 /// to malloc'ed memory
175 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
176 /// to GC-allocated memory
177 /// Additionally, the bottom 16 bits are a reference count which
178 /// should be zero on the stack.
179 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000180
John McCall351762c2011-02-07 10:33:21 +0000181 /// Reserved; should be zero-initialized.
182 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000183
John McCall351762c2011-02-07 10:33:21 +0000184 /// Function pointer generated from block literal.
185 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000186
John McCall351762c2011-02-07 10:33:21 +0000187 /// Block description metadata generated from block literal.
188 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000189
John McCall351762c2011-02-07 10:33:21 +0000190 /// Captured values follow.
191 _CapturesTypes captures...;
192 };
193 */
David Chisnall950a9512009-11-17 19:33:30 +0000194
John McCall351762c2011-02-07 10:33:21 +0000195namespace {
196 /// A chunk of data that we actually have to capture in the block.
197 struct BlockLayoutChunk {
198 CharUnits Alignment;
199 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000200 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000201 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000202 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000203 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000204
John McCall351762c2011-02-07 10:33:21 +0000205 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000206 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000207 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000208 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000209 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000210 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000211
John McCall351762c2011-02-07 10:33:21 +0000212 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000213 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
214 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000215 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000216 info.CXXThisOffset = offset;
217 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000218 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
219 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000220 }
John McCall87fe5d52010-05-20 01:18:31 +0000221 }
John McCall351762c2011-02-07 10:33:21 +0000222 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000223
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000224 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
225 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000226 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000227 if (left.Alignment != right.Alignment)
228 return left.Alignment > right.Alignment;
229
230 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000231 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000232 return 1;
233 if (chunk.Lifetime == Qualifiers::OCL_Strong)
234 return 0;
235 if (chunk.Lifetime == Qualifiers::OCL_Weak)
236 return 2;
237 return 3;
238 };
239
240 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000241 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000242} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000243
John McCallb0a3ecb2011-02-08 03:07:00 +0000244/// Determines if the given type is safe for constant capture in C++.
245static bool isSafeForCXXConstantCapture(QualType type) {
246 const RecordType *recordType =
247 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
248
249 // Only records can be unsafe.
250 if (!recordType) return true;
251
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000252 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000253
254 // Maintain semantics for classes with non-trivial dtors or copy ctors.
255 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000256 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000257
258 // Otherwise, we just have to make sure there aren't any mutable
259 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000260 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000261}
262
John McCall351762c2011-02-07 10:33:21 +0000263/// It is illegal to modify a const object after initialization.
264/// Therefore, if a const object has a constant initializer, we don't
265/// actually need to keep storage for it in the block; we'll just
266/// rematerialize it at the start of the block function. This is
267/// acceptable because we make no promises about address stability of
268/// captured variables.
269static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000270 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000271 const VarDecl *var) {
Simon Pilgrim2c518802017-03-30 14:13:19 +0000272 // Return if this is a function parameter. We shouldn't try to
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000273 // rematerialize default arguments of function parameters.
274 if (isa<ParmVarDecl>(var))
275 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000276
John McCall351762c2011-02-07 10:33:21 +0000277 QualType type = var->getType();
278
279 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000280 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000281
John McCallb0a3ecb2011-02-08 03:07:00 +0000282 // Furthermore, in C++ we have to worry about mutable fields:
283 // C++ [dcl.type.cv]p4:
284 // Except that any class member declared mutable can be
285 // modified, any attempt to modify a const object during its
286 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000287 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000288 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000289
290 // If the variable doesn't have any initializer (shouldn't this be
291 // invalid?), it's not clear what we should do. Maybe capture as
292 // zero?
293 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000294 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000295
John McCallde0fe072017-08-15 21:42:52 +0000296 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
John McCall351762c2011-02-07 10:33:21 +0000297}
298
299/// Get the low bit of a nonzero character count. This is the
300/// alignment of the nth byte if the 0th byte is universally aligned.
301static CharUnits getLowBit(CharUnits v) {
302 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
303}
304
305static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000306 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall351762c2011-02-07 10:33:21 +0000307
308 assert(elementTypes.empty());
Yaxun Liu10712d92017-10-04 20:32:17 +0000309 if (CGM.getLangOpts().OpenCL) {
310 // The header is basically 'struct { int; int; generic void *;
311 // custom_fields; }'. Assert that struct is packed.
Alexander Richardson6d989432017-10-15 18:48:14 +0000312 auto GenericAS =
313 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
314 auto GenPtrAlign =
315 CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
316 auto GenPtrSize =
317 CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
Yaxun Liu10712d92017-10-04 20:32:17 +0000318 assert(CGM.getIntSize() <= GenPtrSize);
319 assert(CGM.getIntAlign() <= GenPtrAlign);
320 assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
321 elementTypes.push_back(CGM.IntTy); /* total size */
322 elementTypes.push_back(CGM.IntTy); /* align */
323 elementTypes.push_back(
324 CGM.getOpenCLRuntime()
325 .getGenericVoidPointerType()); /* invoke function */
326 unsigned Offset =
327 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
328 unsigned BlockAlign = GenPtrAlign.getQuantity();
329 if (auto *Helper =
330 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
331 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
332 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
333 // If necessary, add padding fields to the custom fields.
334 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
335 if (BlockAlign < Align)
336 BlockAlign = Align;
337 assert(Offset % Align == 0);
338 Offset += CGM.getDataLayout().getTypeAllocSize(I);
339 elementTypes.push_back(I);
340 }
341 }
342 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
343 info.BlockSize = CharUnits::fromQuantity(Offset);
344 } else {
345 // The header is basically 'struct { void *; int; int; void *; void *; }'.
346 // Assert that that struct is packed.
347 assert(CGM.getIntSize() <= CGM.getPointerSize());
348 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
349 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
350 info.BlockAlign = CGM.getPointerAlign();
351 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
352 elementTypes.push_back(CGM.VoidPtrTy);
353 elementTypes.push_back(CGM.IntTy);
354 elementTypes.push_back(CGM.IntTy);
355 elementTypes.push_back(CGM.VoidPtrTy);
356 elementTypes.push_back(CGM.getBlockDescriptorType());
357 }
John McCall351762c2011-02-07 10:33:21 +0000358}
359
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000360static QualType getCaptureFieldType(const CodeGenFunction &CGF,
361 const BlockDecl::Capture &CI) {
362 const VarDecl *VD = CI.getVariable();
363
364 // If the variable is captured by an enclosing block or lambda expression,
365 // use the type of the capture field.
366 if (CGF.BlockInfo && CI.isNested())
367 return CGF.BlockInfo->getCapture(VD).fieldType();
368 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
369 return FD->getType();
370 return VD->getType();
371}
372
John McCall351762c2011-02-07 10:33:21 +0000373/// Compute the layout of the given block. Attempts to lay the block
374/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000375static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
376 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000377 ASTContext &C = CGM.getContext();
378 const BlockDecl *block = info.getBlockDecl();
379
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000380 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000381 initializeForBlockHeader(CGM, info, elementTypes);
Yaxun Liu10712d92017-10-04 20:32:17 +0000382 bool hasNonConstantCustomFields = false;
383 if (auto *OpenCLHelper =
384 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
385 hasNonConstantCustomFields =
386 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
387 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
John McCall351762c2011-02-07 10:33:21 +0000388 info.StructureType =
389 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
390 info.CanBeGlobal = true;
391 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000392 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000393 else if (C.getLangOpts().ObjC1 &&
394 CGM.getLangOpts().getGC() == LangOptions::NonGC)
395 info.HasCapturedVariableLayout = true;
396
John McCall351762c2011-02-07 10:33:21 +0000397 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000398 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000399 layout.reserve(block->capturesCXXThis() +
400 (block->capture_end() - block->capture_begin()));
401
402 CharUnits maxFieldAlign;
403
404 // First, 'this'.
405 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000406 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
407 "Can't capture 'this' outside a method");
408 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000409
John McCall7f416cc2015-09-08 08:05:57 +0000410 // Theoretically, this could be in a different address space, so
411 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000412 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000413 std::pair<CharUnits,CharUnits> tinfo
414 = CGM.getContext().getTypeInfoInChars(thisType);
415 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
416
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000417 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
418 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000419 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000420 }
421
422 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000423 for (const auto &CI : block->captures()) {
424 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000425
Aaron Ballman9371dd22014-03-14 18:34:04 +0000426 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000427 // We have to copy/dispose of the __block reference.
428 info.NeedsCopyDispose = true;
429
John McCall351762c2011-02-07 10:33:21 +0000430 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000431 CharUnits align = CGM.getPointerAlign();
432 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000433
John McCall7f416cc2015-09-08 08:05:57 +0000434 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
435 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000436 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000437 continue;
438 }
439
440 // Otherwise, build a layout chunk with the size and alignment of
441 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000442 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000443 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
444 continue;
445 }
446
John McCall31168b02011-06-15 23:02:42 +0000447 // If we have a lifetime qualifier, honor it for capture purposes.
448 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000449 Qualifiers::ObjCLifetime lifetime =
450 variable->getType().getObjCLifetime();
451 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000452 switch (lifetime) {
453 case Qualifiers::OCL_None: llvm_unreachable("impossible");
454 case Qualifiers::OCL_ExplicitNone:
455 case Qualifiers::OCL_Autoreleasing:
456 break;
John McCall351762c2011-02-07 10:33:21 +0000457
John McCall31168b02011-06-15 23:02:42 +0000458 case Qualifiers::OCL_Strong:
459 case Qualifiers::OCL_Weak:
460 info.NeedsCopyDispose = true;
461 }
462
463 // Block pointers require copy/dispose. So do Objective-C pointers.
464 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000465 // But honor the inert __unsafe_unretained qualifier, which doesn't
466 // actually make it into the type system.
467 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
468 lifetime = Qualifiers::OCL_ExplicitNone;
469 } else {
470 info.NeedsCopyDispose = true;
471 // used for mrr below.
472 lifetime = Qualifiers::OCL_Strong;
473 }
John McCall351762c2011-02-07 10:33:21 +0000474
475 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000476 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000477 info.NeedsCopyDispose = true;
478 info.HasCXXObject = true;
479
480 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000481 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000482 if (const CXXRecordDecl *record =
483 variable->getType()->getAsCXXRecordDecl()) {
484 if (!record->hasTrivialDestructor()) {
485 info.HasCXXObject = true;
486 info.NeedsCopyDispose = true;
487 }
488 }
489 }
490
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000491 QualType VT = getCaptureFieldType(*CGF, CI);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000492 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000493 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000494
John McCall351762c2011-02-07 10:33:21 +0000495 maxFieldAlign = std::max(maxFieldAlign, align);
496
Jay Foad7c57be32011-07-11 09:56:20 +0000497 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000498 CGM.getTypes().ConvertTypeForMem(VT);
499
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000500 layout.push_back(
501 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000502 }
503
504 // If that was everything, we're done here.
505 if (layout.empty()) {
506 info.StructureType =
507 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
508 info.CanBeGlobal = true;
509 return;
510 }
511
512 // Sort the layout by alignment. We have to use a stable sort here
513 // to get reproducible results. There should probably be an
514 // llvm::array_pod_stable_sort.
515 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000516
517 // Needed for blocks layout info.
518 info.BlockHeaderForcedGapOffset = info.BlockSize;
519 info.BlockHeaderForcedGapSize = CharUnits::Zero();
520
John McCall351762c2011-02-07 10:33:21 +0000521 CharUnits &blockSize = info.BlockSize;
522 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
523
524 // Assuming that the first byte in the header is maximally aligned,
525 // get the alignment of the first byte following the header.
526 CharUnits endAlign = getLowBit(blockSize);
527
528 // If the end of the header isn't satisfactorily aligned for the
529 // maximum thing, look for things that are okay with the header-end
530 // alignment, and keep appending them until we get something that's
531 // aligned right. This algorithm is only guaranteed optimal if
532 // that condition is satisfied at some point; otherwise we can get
533 // things like:
534 // header // next byte has alignment 4
535 // something_with_size_5; // next byte has alignment 1
536 // something_with_alignment_8;
537 // which has 7 bytes of padding, as opposed to the naive solution
538 // which might have less (?).
539 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000540 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000541 li = layout.begin() + 1, le = layout.end();
542
543 // Look for something that the header end is already
544 // satisfactorily aligned for.
545 for (; li != le && endAlign < li->Alignment; ++li)
546 ;
547
548 // If we found something that's naturally aligned for the end of
549 // the header, keep adding things...
550 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000551 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000552 for (; li != le; ++li) {
553 assert(endAlign >= li->Alignment);
554
John McCall7f416cc2015-09-08 08:05:57 +0000555 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000556 elementTypes.push_back(li->Type);
557 blockSize += li->Size;
558 endAlign = getLowBit(blockSize);
559
560 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000561 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000562 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000563 }
John McCall351762c2011-02-07 10:33:21 +0000564 }
John McCall351762c2011-02-07 10:33:21 +0000565 // Don't re-append everything we just appended.
566 layout.erase(first, li);
567 }
568 }
569
John McCallac0350a2012-04-26 21:14:42 +0000570 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000571
John McCall351762c2011-02-07 10:33:21 +0000572 // At this point, we just have to add padding if the end align still
573 // isn't aligned right.
574 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000575 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000576 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000577
John McCall7f416cc2015-09-08 08:05:57 +0000578 // If we haven't yet added any fields, remember that there was an
579 // initial gap; this need to go into the block layout bit map.
580 if (blockSize == info.BlockHeaderForcedGapOffset) {
581 info.BlockHeaderForcedGapSize = padding;
582 }
583
John McCalle3dc1702011-02-15 09:22:45 +0000584 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
585 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000586 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000587 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000588 }
589
John McCall1db0a2f2012-05-01 20:28:00 +0000590 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000591 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000592 // Slam everything else on now. This works because they have
593 // strictly decreasing alignment and we expect that size is always a
594 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000595 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000596 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000597 if (endAlign < li->Alignment) {
598 // size may not be multiple of alignment. This can only happen with
599 // an over-aligned variable. We will be adding a padding field to
600 // make the size be multiple of alignment.
601 CharUnits padding = li->Alignment - endAlign;
602 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
603 padding.getQuantity()));
604 blockSize += padding;
605 endAlign = getLowBit(blockSize);
606 }
John McCall351762c2011-02-07 10:33:21 +0000607 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000608 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000609 elementTypes.push_back(li->Type);
610 blockSize += li->Size;
611 endAlign = getLowBit(blockSize);
612 }
613
614 info.StructureType =
615 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
616}
617
John McCall08ef4662011-11-10 08:15:53 +0000618/// Enter the scope of a block. This should be run at the entrance to
619/// a full-expression so that the block's cleanups are pushed at the
620/// right place in the stack.
621static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000622 assert(CGF.HaveInsertPoint());
623
John McCall08ef4662011-11-10 08:15:53 +0000624 // Allocate the block info and place it at the head of the list.
625 CGBlockInfo &blockInfo =
626 *new CGBlockInfo(block, CGF.CurFn->getName());
627 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
628 CGF.FirstBlockInfo = &blockInfo;
629
630 // Compute information about the layout, etc., of this block,
631 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000632 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000633
634 // Nothing else to do if it can be global.
635 if (blockInfo.CanBeGlobal) return;
636
637 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000638 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
639 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000640
641 // If there are cleanups to emit, enter them (but inactive).
642 if (!blockInfo.NeedsCopyDispose) return;
643
644 // Walk through the captures (in order) and find the ones not
645 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000646 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000647 // Ignore __block captures; there's nothing special in the
648 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000649 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000650
651 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000652 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000653 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
654 if (capture.isConstant()) continue;
655
656 // Ignore objects that aren't destructed.
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000657 QualType VT = getCaptureFieldType(CGF, CI);
658 QualType::DestructionKind dtorKind = VT.isDestructedType();
John McCall08ef4662011-11-10 08:15:53 +0000659 if (dtorKind == QualType::DK_none) continue;
660
661 CodeGenFunction::Destroyer *destroyer;
662
663 // Block captures count as local values and have imprecise semantics.
664 // They also can't be arrays, so need to worry about that.
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000665 //
666 // For const-qualified captures, emit clang.arc.use to ensure the captured
667 // object doesn't get released while we are still depending on its validity
668 // within the block.
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000669 if (VT.isConstQualified() &&
670 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
671 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
672 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
673 "expected ObjC ARC to be enabled");
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000674 destroyer = CodeGenFunction::emitARCIntrinsicUse;
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000675 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000676 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000677 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000678 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000679 }
680
681 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000682 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
683 capture.getIndex(),
684 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000685
John McCallf4beacd2011-11-10 10:43:54 +0000686 // We can use that GEP as the dominating IP.
687 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000688 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000689
John McCall08ef4662011-11-10 08:15:53 +0000690 CleanupKind cleanupKind = InactiveNormalCleanup;
691 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
692 if (useArrayEHCleanup)
693 cleanupKind = InactiveNormalAndEHCleanup;
694
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000695 CGF.pushDestroy(cleanupKind, addr, VT,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000696 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000697
698 // Remember where that cleanup was.
699 capture.setCleanup(CGF.EHStack.stable_begin());
700 }
701}
702
703/// Enter a full-expression with a non-trivial number of objects to
704/// clean up. This is in this file because, at the moment, the only
705/// kind of cleanup object is a BlockDecl*.
706void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
707 assert(E->getNumObjects() != 0);
708 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
709 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
710 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
711 enterBlockScope(*this, *i);
712 }
713}
714
715/// Find the layout for the given block in a linked list and remove it.
716static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
717 const BlockDecl *block) {
718 while (true) {
719 assert(head && *head);
720 CGBlockInfo *cur = *head;
721
722 // If this is the block we're looking for, splice it out of the list.
723 if (cur->getBlockDecl() == block) {
724 *head = cur->NextBlockInfo;
725 return cur;
726 }
727
728 head = &cur->NextBlockInfo;
729 }
730}
731
732/// Destroy a chain of block layouts.
733void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
734 assert(head && "destroying an empty chain");
735 do {
736 CGBlockInfo *cur = head;
737 head = cur->NextBlockInfo;
738 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000739 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000740}
741
John McCall351762c2011-02-07 10:33:21 +0000742/// Emit a block literal expression in the current function.
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000743llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr,
744 llvm::Function **InvokeF) {
John McCall08ef4662011-11-10 08:15:53 +0000745 // If the block has no captures, we won't have a pre-computed
746 // layout for it.
747 if (!blockExpr->getBlockDecl()->hasCaptures()) {
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000748 // The block literal is emitted as a global variable, and the block invoke
749 // function has to be extracted from its initializer.
750 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
751 if (InvokeF) {
752 auto *GV = cast<llvm::GlobalVariable>(
753 cast<llvm::Constant>(Block)->stripPointerCasts());
754 auto *BlockInit = cast<llvm::ConstantStruct>(GV->getInitializer());
755 *InvokeF = cast<llvm::Function>(
756 BlockInit->getAggregateElement(2)->stripPointerCasts());
757 }
George Burgess IVe3763372016-12-22 02:50:20 +0000758 return Block;
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000759 }
John McCall08ef4662011-11-10 08:15:53 +0000760 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000761 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000762 blockInfo.BlockExpression = blockExpr;
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000763 return EmitBlockLiteral(blockInfo, InvokeF);
John McCall08ef4662011-11-10 08:15:53 +0000764 }
John McCall351762c2011-02-07 10:33:21 +0000765
John McCall08ef4662011-11-10 08:15:53 +0000766 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000767 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000768 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
769 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000770
John McCall08ef4662011-11-10 08:15:53 +0000771 blockInfo->BlockExpression = blockExpr;
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000772 return EmitBlockLiteral(*blockInfo, InvokeF);
John McCall08ef4662011-11-10 08:15:53 +0000773}
774
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000775llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo,
776 llvm::Function **InvokeF) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000777 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
778 auto GenVoidPtrTy =
779 IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
Alexander Richardson6d989432017-10-15 18:48:14 +0000780 LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
Yaxun Liu10712d92017-10-04 20:32:17 +0000781 auto GenVoidPtrSize = CharUnits::fromQuantity(
Alexander Richardson6d989432017-10-15 18:48:14 +0000782 CGM.getTarget().getPointerWidth(
783 CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
784 8);
John McCall08ef4662011-11-10 08:15:53 +0000785 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000786 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000787 auto *InvokeFn = CodeGenFunction(CGM, true).GenerateBlockFunction(
Yaxun Liu10712d92017-10-04 20:32:17 +0000788 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000789 if (InvokeF)
790 *InvokeF = InvokeFn;
791 auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000792
793 // If there is nothing to capture, we can emit this as a global block.
794 if (blockInfo.CanBeGlobal)
Akira Hatanakaba0367a2017-09-22 21:32:06 +0000795 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
John McCall351762c2011-02-07 10:33:21 +0000796
797 // Otherwise, we have to emit this as a local block.
798
John McCall7f416cc2015-09-08 08:05:57 +0000799 Address blockAddr = blockInfo.LocalAddress;
800 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000801
Yaxun Liu10712d92017-10-04 20:32:17 +0000802 llvm::Constant *isa;
803 llvm::Constant *descriptor;
804 BlockFlags flags;
805 if (!IsOpenCL) {
806 isa = llvm::ConstantExpr::getBitCast(CGM.getNSConcreteStackBlock(),
807 VoidPtrTy);
808
809 // Build the block descriptor.
810 descriptor = buildBlockDescriptor(CGM, blockInfo);
811
812 // Compute the initial on-stack block flags.
813 flags = BLOCK_HAS_SIGNATURE;
814 if (blockInfo.HasCapturedVariableLayout)
815 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
816 if (blockInfo.NeedsCopyDispose)
817 flags |= BLOCK_HAS_COPY_DISPOSE;
818 if (blockInfo.HasCXXObject)
819 flags |= BLOCK_HAS_CXX_OBJ;
820 if (blockInfo.UsesStret)
821 flags |= BLOCK_USE_STRET;
822 }
John McCall351762c2011-02-07 10:33:21 +0000823
John McCall7f416cc2015-09-08 08:05:57 +0000824 auto projectField =
825 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
826 return Builder.CreateStructGEP(blockAddr, index, offset, name);
827 };
828 auto storeField =
829 [&](llvm::Value *value, unsigned index, CharUnits offset,
830 const Twine &name) {
831 Builder.CreateStore(value, projectField(index, offset, name));
832 };
833
834 // Initialize the block header.
835 {
836 // We assume all the header fields are densely packed.
837 unsigned index = 0;
838 CharUnits offset;
839 auto addHeaderField =
840 [&](llvm::Value *value, CharUnits size, const Twine &name) {
841 storeField(value, index, offset, name);
842 offset += size;
843 index++;
844 };
845
Yaxun Liu10712d92017-10-04 20:32:17 +0000846 if (!IsOpenCL) {
847 addHeaderField(isa, getPointerSize(), "block.isa");
848 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
849 getIntSize(), "block.flags");
850 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
851 "block.reserved");
852 } else {
853 addHeaderField(
854 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
855 getIntSize(), "block.size");
856 addHeaderField(
857 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
858 getIntSize(), "block.align");
859 }
860 addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
861 if (!IsOpenCL)
862 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
863 else if (auto *Helper =
864 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
865 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
866 addHeaderField(
867 I.first,
868 CharUnits::fromQuantity(
869 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
870 I.second);
871 }
872 }
John McCall7f416cc2015-09-08 08:05:57 +0000873 }
John McCall351762c2011-02-07 10:33:21 +0000874
875 // Finally, capture all the values into the block.
876 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
877
878 // First, 'this'.
879 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000880 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
881 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000882 Builder.CreateStore(LoadCXXThis(), addr);
883 }
884
885 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000886 for (const auto &CI : blockDecl->captures()) {
887 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000888 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
889
890 // Ignore constant captures.
891 if (capture.isConstant()) continue;
892
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000893 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000894
895 // This will be a [[type]]*, except that a byref entry will just be
896 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000897 Address blockField =
898 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000899
900 // Compute the address of the thing we're going to move into the
901 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000902 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000903
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000904 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000905 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000906 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000907 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000908 } else if (CI.isByRef()) {
909 if (BlockInfo && CI.isNested()) {
910 // We need to use the capture from the enclosing block.
911 const CGBlockInfo::Capture &enclosingCapture =
912 BlockInfo->getCapture(variable);
913
914 // This is a [[type]]*, except that a byref entry wil just be an i8**.
915 src = Builder.CreateStructGEP(LoadBlockStruct(),
916 enclosingCapture.getIndex(),
917 enclosingCapture.getOffset(),
918 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000919 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000920 auto I = LocalDeclMap.find(variable);
921 assert(I != LocalDeclMap.end());
922 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000923 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000924 } else {
925 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
926 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
927 type.getNonReferenceType(), VK_LValue,
928 SourceLocation());
929 src = EmitDeclRefLValue(&declRef).getAddress();
930 };
John McCall351762c2011-02-07 10:33:21 +0000931
932 // For byrefs, we just write the pointer to the byref struct into
933 // the block field. There's no need to chase the forwarding
934 // pointer at this point, since we're building something that will
935 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000936 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000937 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000938 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000939 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000940 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000941 else
John McCall7f416cc2015-09-08 08:05:57 +0000942 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000943
John McCalle3dc1702011-02-15 09:22:45 +0000944 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000945 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000946
947 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000948 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000949 if (blockDecl->isConversionFromLambda()) {
950 // If we have a lambda conversion, emit the expression
951 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000952 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000953 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000954 AggValueSlot::IsDestructed,
955 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000956 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000957 EmitAggExpr(copyExpr, Slot);
958 } else {
959 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
960 }
John McCall351762c2011-02-07 10:33:21 +0000961
962 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000963 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000964 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000965
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000966 // If type is const-qualified, copy the value into the block field.
967 } else if (type.isConstQualified() &&
Akira Hatanaka855d70c2017-05-09 01:20:05 +0000968 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
969 CGM.getCodeGenOpts().OptimizationLevel != 0) {
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000970 llvm::Value *value = Builder.CreateLoad(src, "captured");
971 Builder.CreateStore(value, blockField);
972
John McCall4d14a902013-04-08 23:27:49 +0000973 // If this is an ARC __strong block-pointer variable, don't do a
974 // block copy.
975 //
976 // TODO: this can be generalized into the normal initialization logic:
977 // we should never need to do a block-copy when initializing a local
978 // variable, because the local variable's lifetime should be strictly
979 // contained within the stack block's.
980 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
981 type->isBlockPointerType()) {
982 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000983 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000984 value = EmitARCRetainNonBlock(value);
985
986 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000987 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000988
989 // Otherwise, fake up a POD copy into the block field.
990 } else {
John McCall31168b02011-06-15 23:02:42 +0000991 // Fake up a new variable so that EmitScalarInit doesn't think
992 // we're referring to the variable in its own initializer.
Alexey Bataev56223232017-06-09 13:40:18 +0000993 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
994 ImplicitParamDecl::Other);
John McCall31168b02011-06-15 23:02:42 +0000995
John McCall93be3f72011-02-07 18:37:40 +0000996 // We use one of these or the other depending on whether the
997 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000998 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
999 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1000 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +00001001
Fariborz Jahanian10317ea2011-11-02 22:53:43 +00001002 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +00001003 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +00001004 // FIXME: Pass a specific location for the expr init so that the store is
1005 // attributed to a reasonable location - otherwise it may be attributed to
1006 // locations of subexpressions in the initialization.
Alexey Bataev56223232017-06-09 13:40:18 +00001007 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001008 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +00001009 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +00001010 }
1011
John McCall08ef4662011-11-10 08:15:53 +00001012 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001013 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +00001014 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
1015 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +00001016 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +00001017 }
John McCall351762c2011-02-07 10:33:21 +00001018 }
1019
1020 // Cast to the converted block-pointer type, which happens (somewhat
1021 // unfortunately) to be a pointer to function type.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001022 llvm::Value *result = Builder.CreatePointerCast(
1023 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +00001024
John McCall351762c2011-02-07 10:33:21 +00001025 return result;
Mike Stump85284ba2009-02-13 16:19:19 +00001026}
1027
1028
Chris Lattnera5f58b02011-07-09 17:41:47 +00001029llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +00001030 if (BlockDescriptorType)
1031 return BlockDescriptorType;
1032
Chris Lattnera5f58b02011-07-09 17:41:47 +00001033 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +00001034 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001035
Mike Stump650c9322009-02-13 15:16:56 +00001036 // struct __block_descriptor {
1037 // unsigned long reserved;
1038 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +00001039 //
1040 // // later, the following will be added
1041 //
1042 // struct {
1043 // void (*copyHelper)();
1044 // void (*copyHelper)();
1045 // } helpers; // !!! optional
1046 //
1047 // const char *signature; // the block signature
1048 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +00001049 // };
Serge Guelton1d993272017-05-09 19:31:30 +00001050 BlockDescriptorType = llvm::StructType::create(
1051 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
Mike Stump650c9322009-02-13 15:16:56 +00001052
John McCall351762c2011-02-07 10:33:21 +00001053 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +00001054 unsigned AddrSpace = 0;
1055 if (getLangOpts().OpenCL)
1056 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1057 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +00001058 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001059}
1060
Chris Lattnera5f58b02011-07-09 17:41:47 +00001061llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +00001062 if (GenericBlockLiteralType)
1063 return GenericBlockLiteralType;
1064
Chris Lattnera5f58b02011-07-09 17:41:47 +00001065 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +00001066
Yaxun Liu10712d92017-10-04 20:32:17 +00001067 if (getLangOpts().OpenCL) {
1068 // struct __opencl_block_literal_generic {
1069 // int __size;
1070 // int __align;
1071 // __generic void *__invoke;
1072 // /* custom fields */
1073 // };
1074 SmallVector<llvm::Type *, 8> StructFields(
1075 {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1076 if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1077 for (auto I : Helper->getCustomFieldTypes())
1078 StructFields.push_back(I);
1079 }
1080 GenericBlockLiteralType = llvm::StructType::create(
1081 StructFields, "struct.__opencl_block_literal_generic");
1082 } else {
1083 // struct __block_literal_generic {
1084 // void *__isa;
1085 // int __flags;
1086 // int __reserved;
1087 // void (*__invoke)(void *);
1088 // struct __block_descriptor *__descriptor;
1089 // };
1090 GenericBlockLiteralType =
1091 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1092 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1093 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001094
Mike Stump005c9a62009-02-13 15:25:34 +00001095 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001096}
1097
Yaxun Liu10712d92017-10-04 20:32:17 +00001098RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +00001099 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +00001100 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001101 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +00001102
John McCallb92ab1a2016-10-26 23:46:34 +00001103 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001104
1105 // Get a pointer to the generic block literal.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001106 // For OpenCL we generate generic AS void ptr to be able to reuse the same
1107 // block definition for blocks with captures generated as private AS local
1108 // variables and without captures generated as global AS program scope
1109 // variables.
1110 unsigned AddrSpace = 0;
1111 if (getLangOpts().OpenCL)
1112 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1113
Chris Lattner2192fe52011-07-18 04:24:23 +00001114 llvm::Type *BlockLiteralTy =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001115 llvm::PointerType::get(CGM.getGenericBlockLiteralType(), AddrSpace);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001116
1117 // Bitcast the callee to a block literal.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001118 BlockPtr =
1119 Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001120
1121 // Get the function pointer from the literal.
John McCall7f416cc2015-09-08 08:05:57 +00001122 llvm::Value *FuncPtr =
Yaxun Liu10712d92017-10-04 20:32:17 +00001123 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr,
1124 CGM.getLangOpts().OpenCL ? 2 : 3);
Mike Stumpb7074c02009-02-13 15:32:32 +00001125
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001126 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001127 CallArgList Args;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001128
1129 QualType VoidPtrQualTy = getContext().VoidPtrTy;
1130 llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1131 if (getLangOpts().OpenCL) {
Yaxun Liu10712d92017-10-04 20:32:17 +00001132 GenericVoidPtrTy = CGM.getOpenCLRuntime().getGenericVoidPointerType();
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001133 VoidPtrQualTy =
1134 getContext().getPointerType(getContext().getAddrSpaceQualType(
1135 getContext().VoidTy, LangAS::opencl_generic));
1136 }
1137
1138 BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1139 Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001140
Anders Carlsson479e6fc2009-04-08 23:13:16 +00001141 QualType FnType = BPT->getPointeeType();
1142
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001143 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +00001144 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +00001145
Anders Carlsson5f50c652009-04-07 22:10:22 +00001146 // Load the function.
John McCall7f416cc2015-09-08 08:05:57 +00001147 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001148
John McCall85915252011-03-09 08:39:33 +00001149 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001150 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001151 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001152
Anders Carlsson5f50c652009-04-07 22:10:22 +00001153 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001154 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001155
Chris Lattner2192fe52011-07-18 04:24:23 +00001156 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Yaxun Liu10712d92017-10-04 20:32:17 +00001157 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001158
John McCallb92ab1a2016-10-26 23:46:34 +00001159 // Prepare the callee.
1160 CGCallee Callee(CGCalleeInfo(), Func);
1161
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001162 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001163 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001164}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001165
John McCall7f416cc2015-09-08 08:05:57 +00001166Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1167 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001168 assert(BlockInfo && "evaluating block ref without block information?");
1169 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001170
John McCall351762c2011-02-07 10:33:21 +00001171 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001172 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001173
John McCall7f416cc2015-09-08 08:05:57 +00001174 Address addr =
1175 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1176 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001177
John McCall351762c2011-02-07 10:33:21 +00001178 if (isByRef) {
1179 // addr should be a void** right now. Load, then cast the result
1180 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001181
John McCall7f416cc2015-09-08 08:05:57 +00001182 auto &byrefInfo = getBlockByrefInfo(variable);
1183 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001184
John McCall7f416cc2015-09-08 08:05:57 +00001185 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1186 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001187
John McCall7f416cc2015-09-08 08:05:57 +00001188 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1189 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001190 }
1191
Akira Hatanakad542ccf2016-09-16 00:02:06 +00001192 if (auto refType = capture.fieldType()->getAs<ReferenceType>())
John McCall7f416cc2015-09-08 08:05:57 +00001193 addr = EmitLoadOfReference(addr, refType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001194
John McCall351762c2011-02-07 10:33:21 +00001195 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001196}
1197
George Burgess IVe3763372016-12-22 02:50:20 +00001198void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1199 llvm::Constant *Addr) {
1200 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1201 (void)Ok;
1202 assert(Ok && "Trying to replace an already-existing global block!");
1203}
1204
Mike Stump2d5a2872009-02-14 22:16:35 +00001205llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001206CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1207 StringRef Name) {
George Burgess IVe3763372016-12-22 02:50:20 +00001208 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1209 return Block;
1210
George Burgess IV70d15b32016-11-03 02:21:43 +00001211 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1212 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001213
John McCall351762c2011-02-07 10:33:21 +00001214 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001215 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001216
John McCall351762c2011-02-07 10:33:21 +00001217 // Using that metadata, generate the actual block function.
John McCall351762c2011-02-07 10:33:21 +00001218 {
John McCall7f416cc2015-09-08 08:05:57 +00001219 CodeGenFunction::DeclMapTy LocalDeclMap;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001220 CodeGenFunction(*this).GenerateBlockFunction(
1221 GlobalDecl(), blockInfo, LocalDeclMap,
1222 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
John McCall351762c2011-02-07 10:33:21 +00001223 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001224
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001225 return getAddrOfGlobalBlockIfEmitted(BE);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001226}
1227
John McCall351762c2011-02-07 10:33:21 +00001228static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1229 const CGBlockInfo &blockInfo,
1230 llvm::Constant *blockFn) {
1231 assert(blockInfo.CanBeGlobal);
George Burgess IVe3763372016-12-22 02:50:20 +00001232 // Callers should detect this case on their own: calling this function
1233 // generally requires computing layout information, which is a waste of time
1234 // if we've already emitted this block.
1235 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1236 "Refusing to re-emit a global block.");
John McCall351762c2011-02-07 10:33:21 +00001237
1238 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001239 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001240 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001241
Yaxun Liu10712d92017-10-04 20:32:17 +00001242 bool IsOpenCL = CGM.getLangOpts().OpenCL;
1243 if (!IsOpenCL) {
1244 // isa
1245 fields.add(CGM.getNSConcreteGlobalBlock());
John McCall351762c2011-02-07 10:33:21 +00001246
Yaxun Liu10712d92017-10-04 20:32:17 +00001247 // __flags
1248 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1249 if (blockInfo.UsesStret)
1250 flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +00001251
Yaxun Liu10712d92017-10-04 20:32:17 +00001252 fields.addInt(CGM.IntTy, flags.getBitMask());
1253
1254 // Reserved
1255 fields.addInt(CGM.IntTy, 0);
1256 } else {
1257 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1258 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1259 }
John McCall351762c2011-02-07 10:33:21 +00001260
1261 // Function
John McCall6c9f1fdb2016-11-19 08:17:24 +00001262 fields.add(blockFn);
John McCall351762c2011-02-07 10:33:21 +00001263
Yaxun Liu10712d92017-10-04 20:32:17 +00001264 if (!IsOpenCL) {
1265 // Descriptor
1266 fields.add(buildBlockDescriptor(CGM, blockInfo));
1267 } else if (auto *Helper =
1268 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1269 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1270 fields.add(I);
1271 }
1272 }
John McCall351762c2011-02-07 10:33:21 +00001273
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001274 unsigned AddrSpace = 0;
1275 if (CGM.getContext().getLangOpts().OpenCL)
1276 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1277
1278 llvm::Constant *literal = fields.finishAndCreateGlobal(
1279 "__block_literal_global", blockInfo.BlockAlign,
1280 /*constant*/ true, llvm::GlobalVariable::InternalLinkage, AddrSpace);
John McCall351762c2011-02-07 10:33:21 +00001281
1282 // Return a constant of the appropriately-casted type.
George Burgess IVe3763372016-12-22 02:50:20 +00001283 llvm::Type *RequiredType =
John McCall351762c2011-02-07 10:33:21 +00001284 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
George Burgess IVe3763372016-12-22 02:50:20 +00001285 llvm::Constant *Result =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001286 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
George Burgess IVe3763372016-12-22 02:50:20 +00001287 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1288 return Result;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001289}
1290
John McCall7f416cc2015-09-08 08:05:57 +00001291void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1292 unsigned argNum,
1293 llvm::Value *arg) {
1294 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1295
1296 llvm::Value *localAddr = nullptr;
Adrian Prantle78a6222017-10-26 18:32:16 +00001297 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1298 // Allocate a stack slot to let the debug info survive the RA.
1299 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1300 Builder.CreateStore(arg, alloc);
1301 localAddr = Builder.CreateLoad(alloc);
1302 }
John McCall7f416cc2015-09-08 08:05:57 +00001303
1304 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001305 if (CGM.getCodeGenOpts().getDebugInfo() >=
1306 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001307 DI->setLocation(D->getLocation());
Adrian Prantle78a6222017-10-26 18:32:16 +00001308 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1309 localAddr, Builder);
John McCall7f416cc2015-09-08 08:05:57 +00001310 }
1311 }
1312
1313 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1314 ApplyDebugLocation Scope(*this, StartLoc);
1315
1316 // Instead of messing around with LocalDeclMap, just set the value
1317 // directly as BlockPointer.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001318 BlockPointer = Builder.CreatePointerCast(
1319 arg,
1320 BlockInfo->StructureType->getPointerTo(
1321 getContext().getLangOpts().OpenCL
1322 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1323 : 0),
1324 "block");
John McCall7f416cc2015-09-08 08:05:57 +00001325}
1326
1327Address CodeGenFunction::LoadBlockStruct() {
1328 assert(BlockInfo && "not in a block invocation function!");
1329 assert(BlockPointer && "no block pointer set!");
1330 return Address(BlockPointer, BlockInfo->BlockAlign);
1331}
1332
Mike Stump4446dcf2009-03-05 08:32:30 +00001333llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001334CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1335 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001336 const DeclMapTy &ldm,
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001337 bool IsLambdaConversionToBlock,
1338 bool BuildGlobalBlock) {
John McCall351762c2011-02-07 10:33:21 +00001339 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001340
Fariborz Jahanian63628032012-06-26 16:06:38 +00001341 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001342
1343 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001344
John McCall351762c2011-02-07 10:33:21 +00001345 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001346
Mike Stump5469f292009-03-13 23:34:28 +00001347 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001348 // to be local to this function as well, in case they're directly
1349 // referenced in a block.
1350 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001351 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001352 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001353 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001354 }
1355
John McCall351762c2011-02-07 10:33:21 +00001356 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001357
John McCall351762c2011-02-07 10:33:21 +00001358 // Build the argument list.
1359 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001360
John McCall351762c2011-02-07 10:33:21 +00001361 // The first argument is the block pointer. Just take it as a void*
1362 // and cast it later.
1363 QualType selfTy = getContext().VoidPtrTy;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001364
1365 // For OpenCL passed block pointer can be private AS local variable or
1366 // global AS program scope variable (for the case with and without captures).
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00001367 // Generic AS is used therefore to be able to accommodate both private and
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001368 // generic AS in one implementation.
1369 if (getLangOpts().OpenCL)
1370 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1371 getContext().VoidTy, LangAS::opencl_generic));
1372
Mike Stump7fe9cc12009-10-21 03:49:08 +00001373 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001374
Alexey Bataev56223232017-06-09 13:40:18 +00001375 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1376 SourceLocation(), II, selfTy,
1377 ImplicitParamDecl::ObjCSelf);
1378 args.push_back(&SelfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001379
John McCall351762c2011-02-07 10:33:21 +00001380 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001381 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001382
John McCall351762c2011-02-07 10:33:21 +00001383 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001384 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001385 const CGFunctionInfo &fnInfo =
1386 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001387 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001388 blockInfo.UsesStret = true;
1389
John McCalla729c622012-02-17 03:33:10 +00001390 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001391
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001392 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001393 llvm::Function *fn = llvm::Function::Create(
1394 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001395 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001396
Yaxun Liu10712d92017-10-04 20:32:17 +00001397 if (BuildGlobalBlock) {
1398 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1399 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1400 : VoidPtrTy;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001401 buildGlobalBlock(CGM, blockInfo,
Yaxun Liu10712d92017-10-04 20:32:17 +00001402 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1403 }
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001404
John McCall351762c2011-02-07 10:33:21 +00001405 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001406 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001407 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001408 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001409
John McCall147d0212011-02-22 22:38:33 +00001410 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001411
Adrian Prantl0f6df002013-03-29 19:20:35 +00001412 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1413 // won't delete the dbg.declare intrinsics for captured variables.
1414 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1415 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1416 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001417 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1418 getPointerAlign(),
1419 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001420 // Set the DebugLocation to empty, so the store is recognized as a
1421 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001422 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001423 Builder.CreateStore(BlockPointer, Alloca);
1424 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001425 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001426
John McCall87fe5d52010-05-20 01:18:31 +00001427 // If we have a C++ 'this' reference, go ahead and force it into
1428 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001429 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001430 Address addr =
1431 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1432 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001433 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001434 }
1435
John McCall351762c2011-02-07 10:33:21 +00001436 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001437 for (const auto &CI : blockDecl->captures()) {
1438 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001439 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1440 if (!capture.isConstant()) continue;
1441
John McCall7f416cc2015-09-08 08:05:57 +00001442 CharUnits align = getContext().getDeclAlign(variable);
1443 Address alloca =
1444 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001445
John McCall7f416cc2015-09-08 08:05:57 +00001446 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001447
John McCall7f416cc2015-09-08 08:05:57 +00001448 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001449 }
1450
John McCall113bee02012-03-10 09:33:50 +00001451 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001452 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1453 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1454 --entry_ptr;
1455
Eli Friedman2495ab02012-02-25 02:48:22 +00001456 if (IsLambdaConversionToBlock)
1457 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001458 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001459 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001460 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001461 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001462 }
Mike Stump017460a2009-10-01 22:29:41 +00001463
Mike Stump7d699112009-10-01 00:27:30 +00001464 // Remember where we were...
1465 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001466
Mike Stump7d699112009-10-01 00:27:30 +00001467 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001468 ++entry_ptr;
1469 Builder.SetInsertPoint(entry, entry_ptr);
1470
John McCall113bee02012-03-10 09:33:50 +00001471 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001472 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001473 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001474 for (const auto &CI : blockDecl->captures()) {
1475 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001476 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001477
Benjamin Kramer8c305922016-02-02 11:06:51 +00001478 if (CGM.getCodeGenOpts().getDebugInfo() >=
1479 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001480 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1481 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001482 auto addr = LocalDeclMap.find(variable)->second;
1483 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Alexey Samsonov74a38682012-05-04 07:39:27 +00001484 Builder);
1485 continue;
1486 }
John McCall351762c2011-02-07 10:33:21 +00001487
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001488 DI->EmitDeclareOfBlockDeclRefVariable(
1489 variable, BlockPointerDbgLoc, Builder, blockInfo,
1490 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001491 }
Mike Stump2e722b92009-09-30 02:43:10 +00001492 }
Manman Renab08a9a2013-01-04 18:51:35 +00001493 // Recover location if it was changed in the above loop.
1494 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001495 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001496 }
John McCall351762c2011-02-07 10:33:21 +00001497
Mike Stump7d699112009-10-01 00:27:30 +00001498 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001499 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001500 Builder.ClearInsertionPoint();
1501 else
1502 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001503
John McCall351762c2011-02-07 10:33:21 +00001504 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001505
John McCall351762c2011-02-07 10:33:21 +00001506 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001507}
Mike Stump1db7d042009-02-28 09:07:16 +00001508
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001509namespace {
1510
1511/// Represents a type of copy/destroy operation that should be performed for an
1512/// entity that's captured by a block.
1513enum class BlockCaptureEntityKind {
1514 CXXRecord, // Copy or destroy
1515 ARCWeak,
1516 ARCStrong,
1517 BlockObject, // Assign or release
1518 None
1519};
1520
1521/// Represents a captured entity that requires extra operations in order for
1522/// this entity to be copied or destroyed correctly.
1523struct BlockCaptureManagedEntity {
1524 BlockCaptureEntityKind Kind;
1525 BlockFieldFlags Flags;
1526 const BlockDecl::Capture &CI;
1527 const CGBlockInfo::Capture &Capture;
1528
1529 BlockCaptureManagedEntity(BlockCaptureEntityKind Type, BlockFieldFlags Flags,
1530 const BlockDecl::Capture &CI,
1531 const CGBlockInfo::Capture &Capture)
1532 : Kind(Type), Flags(Flags), CI(CI), Capture(Capture) {}
1533};
1534
1535} // end anonymous namespace
1536
1537static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1538computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1539 const LangOptions &LangOpts) {
1540 if (CI.getCopyExpr()) {
1541 assert(!CI.isByRef());
1542 // don't bother computing flags
1543 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1544 }
1545 BlockFieldFlags Flags;
1546 if (CI.isByRef()) {
1547 Flags = BLOCK_FIELD_IS_BYREF;
1548 if (T.isObjCGCWeak())
1549 Flags |= BLOCK_FIELD_IS_WEAK;
1550 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1551 }
1552 if (!T->isObjCRetainableType())
1553 // For all other types, the memcpy is fine.
1554 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1555
1556 Flags = BLOCK_FIELD_IS_OBJECT;
1557 bool isBlockPointer = T->isBlockPointerType();
1558 if (isBlockPointer)
1559 Flags = BLOCK_FIELD_IS_BLOCK;
1560
1561 // Special rules for ARC captures:
1562 Qualifiers QS = T.getQualifiers();
1563
1564 // We need to register __weak direct captures with the runtime.
1565 if (QS.getObjCLifetime() == Qualifiers::OCL_Weak)
1566 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1567
1568 // We need to retain the copied value for __strong direct captures.
1569 if (QS.getObjCLifetime() == Qualifiers::OCL_Strong) {
1570 // If it's a block pointer, we have to copy the block and
1571 // assign that to the destination pointer, so we might as
1572 // well use _Block_object_assign. Otherwise we can avoid that.
1573 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1574 : BlockCaptureEntityKind::BlockObject,
1575 Flags);
1576 }
1577
1578 // Non-ARC captures of retainable pointers are strong and
1579 // therefore require a call to _Block_object_assign.
1580 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1581 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1582
1583 // Otherwise the memcpy is fine.
1584 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1585}
1586
1587/// Find the set of block captures that need to be explicitly copied or destroy.
1588static void findBlockCapturedManagedEntities(
1589 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1590 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures,
1591 llvm::function_ref<std::pair<BlockCaptureEntityKind, BlockFieldFlags>(
1592 const BlockDecl::Capture &, QualType, const LangOptions &)>
1593 Predicate) {
1594 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1595 const VarDecl *Variable = CI.getVariable();
1596 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1597 if (Capture.isConstant())
1598 continue;
1599
1600 auto Info = Predicate(CI, Variable->getType(), LangOpts);
1601 if (Info.first != BlockCaptureEntityKind::None)
1602 ManagedCaptures.emplace_back(Info.first, Info.second, CI, Capture);
1603 }
1604}
1605
John McCallf593b102013-01-22 03:56:22 +00001606/// Generate the copy-helper function for a block closure object:
1607/// static void block_copy_helper(block_t *dst, block_t *src);
1608/// The runtime will have previously initialized 'dst' by doing a
1609/// bit-copy of 'src'.
1610///
1611/// Note that this copies an entire block closure object to the heap;
1612/// it should not be confused with a 'byref copy helper', which moves
1613/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001614llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001615CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001616 ASTContext &C = getContext();
1617
1618 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001619 ImplicitParamDecl DstDecl(getContext(), C.VoidPtrTy,
1620 ImplicitParamDecl::Other);
1621 args.push_back(&DstDecl);
1622 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1623 ImplicitParamDecl::Other);
1624 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001625
John McCallc56a8b32016-03-11 04:30:31 +00001626 const CGFunctionInfo &FI =
1627 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001628
John McCall351762c2011-02-07 10:33:21 +00001629 // FIXME: it would be nice if these were mergeable with things with
1630 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001631 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001632
1633 llvm::Function *Fn =
1634 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001635 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001636
1637 IdentifierInfo *II
1638 = &CGM.getContext().Idents.get("__copy_helper_block_");
1639
John McCall351762c2011-02-07 10:33:21 +00001640 FunctionDecl *FD = FunctionDecl::Create(C,
1641 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001642 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001643 SourceLocation(), II, C.VoidTy,
1644 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001645 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001646 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001647
1648 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1649
Adrian Prantl95b24e92015-02-03 20:00:54 +00001650 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001651 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001652 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001653 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001654 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001655
Alexey Bataev56223232017-06-09 13:40:18 +00001656 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001657 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001658 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001659
Alexey Bataev56223232017-06-09 13:40:18 +00001660 Address dst = GetAddrOfLocalVar(&DstDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001661 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001662 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001663
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001664 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
1665 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures,
1666 computeCopyInfoForBlockCapture);
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001667
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001668 for (const auto &CopiedCapture : CopiedCaptures) {
1669 const BlockDecl::Capture &CI = CopiedCapture.CI;
1670 const CGBlockInfo::Capture &capture = CopiedCapture.Capture;
1671 BlockFieldFlags flags = CopiedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001672
1673 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001674 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1675 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001676
1677 // If there's an explicit copy expression, we do that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001678 if (CI.getCopyExpr()) {
1679 assert(CopiedCapture.Kind == BlockCaptureEntityKind::CXXRecord);
1680 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1681 } else if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
John McCall31168b02011-06-15 23:02:42 +00001682 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001683 } else {
1684 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001685 if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
John McCalle68b8f42012-10-17 02:28:37 +00001686 // At -O0, store null into the destination field (so that the
1687 // storeStrong doesn't over-release) and then call storeStrong.
1688 // This is a workaround to not having an initStrong call.
1689 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001690 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001691 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1692 Builder.CreateStore(null, dstField);
1693 EmitARCStoreStrongCall(dstField, srcValue, true);
1694
1695 // With optimization enabled, take advantage of the fact that
1696 // the blocks runtime guarantees a memcpy of the block data, and
1697 // just emit a retain of the src field.
1698 } else {
1699 EmitARCRetainNonBlock(srcValue);
1700
1701 // We don't need this anymore, so kill it. It's not quite
1702 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001703 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001704 }
1705 } else {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001706 assert(CopiedCapture.Kind == BlockCaptureEntityKind::BlockObject);
John McCalle68b8f42012-10-17 02:28:37 +00001707 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001708 llvm::Value *dstAddr =
1709 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001710 llvm::Value *args[] = {
1711 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1712 };
1713
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001714 const VarDecl *variable = CI.getVariable();
John McCall882987f2013-02-28 19:01:20 +00001715 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001716 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001717 const Expr *copyExpr =
1718 CGM.getContext().getBlockVarCopyInits(variable);
1719 if (copyExpr) {
1720 copyCanThrow = true; // FIXME: reuse the noexcept logic
1721 }
1722 }
1723
1724 if (copyCanThrow) {
1725 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1726 } else {
1727 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1728 }
John McCalle68b8f42012-10-17 02:28:37 +00001729 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001730 }
1731 }
1732
John McCallad7c5c12011-02-08 08:22:06 +00001733 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001734
John McCalle3dc1702011-02-15 09:22:45 +00001735 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001736}
1737
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001738static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1739computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1740 const LangOptions &LangOpts) {
1741 BlockFieldFlags Flags;
1742 if (CI.isByRef()) {
1743 Flags = BLOCK_FIELD_IS_BYREF;
1744 if (T.isObjCGCWeak())
1745 Flags |= BLOCK_FIELD_IS_WEAK;
1746 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1747 }
1748
1749 if (const CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1750 if (Record->hasTrivialDestructor())
1751 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1752 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1753 }
1754
1755 // Other types don't need to be destroy explicitly.
1756 if (!T->isObjCRetainableType())
1757 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1758
1759 Flags = BLOCK_FIELD_IS_OBJECT;
1760 if (T->isBlockPointerType())
1761 Flags = BLOCK_FIELD_IS_BLOCK;
1762
1763 // Special rules for ARC captures.
1764 Qualifiers QS = T.getQualifiers();
1765
1766 // Use objc_storeStrong for __strong direct captures; the
1767 // dynamic tools really like it when we do this.
1768 if (QS.getObjCLifetime() == Qualifiers::OCL_Strong)
1769 return std::make_pair(BlockCaptureEntityKind::ARCStrong, Flags);
1770
1771 // Support __weak direct captures.
1772 if (QS.getObjCLifetime() == Qualifiers::OCL_Weak)
1773 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1774
1775 // Non-ARC captures are strong, and we need to use
1776 // _Block_object_dispose.
1777 if (!QS.hasObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1778 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1779
1780 // Otherwise, we have nothing to do.
1781 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1782}
1783
John McCallf593b102013-01-22 03:56:22 +00001784/// Generate the destroy-helper function for a block closure object:
1785/// static void block_destroy_helper(block_t *theBlock);
1786///
1787/// Note that this destroys a heap-allocated block closure object;
1788/// it should not be confused with a 'byref destroy helper', which
1789/// destroys the heap-allocated contents of an individual __block
1790/// variable.
John McCall351762c2011-02-07 10:33:21 +00001791llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001792CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001793 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001794
John McCall351762c2011-02-07 10:33:21 +00001795 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001796 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1797 ImplicitParamDecl::Other);
1798 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001799
John McCallc56a8b32016-03-11 04:30:31 +00001800 const CGFunctionInfo &FI =
1801 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001802
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001803 // FIXME: We'd like to put these into a mergable by content, with
1804 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001805 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001806
1807 llvm::Function *Fn =
1808 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001809 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001810
1811 IdentifierInfo *II
1812 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1813
John McCall351762c2011-02-07 10:33:21 +00001814 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001815 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001816 SourceLocation(), II, C.VoidTy,
1817 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001818 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001819
1820 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1821
Adrian Prantl49a78562013-07-24 20:34:39 +00001822 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001823 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001824 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001825 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001826
Chris Lattner2192fe52011-07-18 04:24:23 +00001827 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001828
Alexey Bataev56223232017-06-09 13:40:18 +00001829 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001830 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001831 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001832
John McCallad7c5c12011-02-08 08:22:06 +00001833 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001834
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001835 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
1836 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures,
1837 computeDestroyInfoForBlockCapture);
John McCall351762c2011-02-07 10:33:21 +00001838
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001839 for (const auto &DestroyedCapture : DestroyedCaptures) {
1840 const BlockDecl::Capture &CI = DestroyedCapture.CI;
1841 const CGBlockInfo::Capture &capture = DestroyedCapture.Capture;
1842 BlockFieldFlags flags = DestroyedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001843
John McCall7f416cc2015-09-08 08:05:57 +00001844 Address srcField =
1845 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001846
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001847 // If the captured record has a destructor then call it.
1848 if (DestroyedCapture.Kind == BlockCaptureEntityKind::CXXRecord) {
1849 const auto *Dtor =
1850 CI.getVariable()->getType()->getAsCXXRecordDecl()->getDestructor();
1851 PushDestructorCleanup(Dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001852
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001853 // If this is a __weak capture, emit the release directly.
1854 } else if (DestroyedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
John McCall31168b02011-06-15 23:02:42 +00001855 EmitARCDestroyWeak(srcField);
1856
John McCalle68b8f42012-10-17 02:28:37 +00001857 // Destroy strong objects with a call if requested.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001858 } else if (DestroyedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
John McCallcdda29c2013-03-13 03:10:54 +00001859 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001860
John McCall351762c2011-02-07 10:33:21 +00001861 // Otherwise we call _Block_object_dispose. It wouldn't be too
1862 // hard to just emit this as a cleanup if we wanted to make sure
1863 // that things were done in reverse.
1864 } else {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001865 assert(DestroyedCapture.Kind == BlockCaptureEntityKind::BlockObject);
John McCall351762c2011-02-07 10:33:21 +00001866 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001867 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001868 BuildBlockRelease(value, flags);
1869 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001870 }
1871
John McCall351762c2011-02-07 10:33:21 +00001872 cleanups.ForceCleanup();
1873
John McCallad7c5c12011-02-08 08:22:06 +00001874 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001875
John McCalle3dc1702011-02-15 09:22:45 +00001876 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001877}
1878
John McCallf9b056b2011-03-31 08:03:29 +00001879namespace {
1880
1881/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001882class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001883 BlockFieldFlags Flags;
1884
1885public:
1886 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001887 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001888
John McCall7f416cc2015-09-08 08:05:57 +00001889 void emitCopy(CodeGenFunction &CGF, Address destField,
1890 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001891 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1892
1893 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1894 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1895
1896 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1897
1898 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1899 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001900
John McCall7f416cc2015-09-08 08:05:57 +00001901 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001902 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001903 }
1904
John McCall7f416cc2015-09-08 08:05:57 +00001905 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001906 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1907 llvm::Value *value = CGF.Builder.CreateLoad(field);
1908
1909 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1910 }
1911
Craig Topper4f12f102014-03-12 06:41:41 +00001912 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001913 id.AddInteger(Flags.getBitMask());
1914 }
1915};
1916
John McCall31168b02011-06-15 23:02:42 +00001917/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001918class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001919public:
John McCall7f416cc2015-09-08 08:05:57 +00001920 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001921
John McCall7f416cc2015-09-08 08:05:57 +00001922 void emitCopy(CodeGenFunction &CGF, Address destField,
1923 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001924 CGF.EmitARCMoveWeak(destField, srcField);
1925 }
1926
John McCall7f416cc2015-09-08 08:05:57 +00001927 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001928 CGF.EmitARCDestroyWeak(field);
1929 }
1930
Craig Topper4f12f102014-03-12 06:41:41 +00001931 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001932 // 0 is distinguishable from all pointers and byref flags
1933 id.AddInteger(0);
1934 }
1935};
1936
1937/// Emits the copy/dispose helpers for an ARC __block __strong variable
1938/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001939class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001940public:
John McCall7f416cc2015-09-08 08:05:57 +00001941 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001942
John McCall7f416cc2015-09-08 08:05:57 +00001943 void emitCopy(CodeGenFunction &CGF, Address destField,
1944 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001945 // Do a "move" by copying the value and then zeroing out the old
1946 // variable.
1947
John McCall7f416cc2015-09-08 08:05:57 +00001948 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001949
John McCall31168b02011-06-15 23:02:42 +00001950 llvm::Value *null =
1951 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001952
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001953 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001954 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001955 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1956 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1957 return;
1958 }
John McCall7f416cc2015-09-08 08:05:57 +00001959 CGF.Builder.CreateStore(value, destField);
1960 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001961 }
1962
John McCall7f416cc2015-09-08 08:05:57 +00001963 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001964 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001965 }
1966
Craig Topper4f12f102014-03-12 06:41:41 +00001967 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001968 // 1 is distinguishable from all pointers and byref flags
1969 id.AddInteger(1);
1970 }
1971};
1972
John McCall3a237aa2011-11-09 03:17:26 +00001973/// Emits the copy/dispose helpers for an ARC __block __strong
1974/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001975class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001976public:
John McCall7f416cc2015-09-08 08:05:57 +00001977 ARCStrongBlockByrefHelpers(CharUnits alignment)
1978 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001979
John McCall7f416cc2015-09-08 08:05:57 +00001980 void emitCopy(CodeGenFunction &CGF, Address destField,
1981 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001982 // Do the copy with objc_retainBlock; that's all that
1983 // _Block_object_assign would do anyway, and we'd have to pass the
1984 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001985 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001986 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001987 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001988 }
1989
John McCall7f416cc2015-09-08 08:05:57 +00001990 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001991 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001992 }
1993
Craig Topper4f12f102014-03-12 06:41:41 +00001994 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001995 // 2 is distinguishable from all pointers and byref flags
1996 id.AddInteger(2);
1997 }
1998};
1999
John McCallf9b056b2011-03-31 08:03:29 +00002000/// Emits the copy/dispose helpers for a __block variable with a
2001/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00002002class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00002003 QualType VarType;
2004 const Expr *CopyExpr;
2005
2006public:
2007 CXXByrefHelpers(CharUnits alignment, QualType type,
2008 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00002009 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00002010
Craig Topper8a13c412014-05-21 05:09:00 +00002011 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00002012 void emitCopy(CodeGenFunction &CGF, Address destField,
2013 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00002014 if (!CopyExpr) return;
2015 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2016 }
2017
John McCall7f416cc2015-09-08 08:05:57 +00002018 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002019 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2020 CGF.PushDestructorCleanup(VarType, field);
2021 CGF.PopCleanupBlocks(cleanupDepth);
2022 }
2023
Craig Topper4f12f102014-03-12 06:41:41 +00002024 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002025 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2026 }
2027};
2028} // end anonymous namespace
2029
2030static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00002031generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2032 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002033 ASTContext &Context = CGF.getContext();
2034
2035 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002036
John McCalla738c252011-03-09 04:27:21 +00002037 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002038 ImplicitParamDecl Dst(CGF.getContext(), Context.VoidPtrTy,
2039 ImplicitParamDecl::Other);
2040 args.push_back(&Dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00002041
Alexey Bataev56223232017-06-09 13:40:18 +00002042 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2043 ImplicitParamDecl::Other);
2044 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002045
John McCallc56a8b32016-03-11 04:30:31 +00002046 const CGFunctionInfo &FI =
2047 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002048
John McCall7f416cc2015-09-08 08:05:57 +00002049 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002050
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002051 // FIXME: We'd like to put these into a mergable by content, with
2052 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002053 llvm::Function *Fn =
2054 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00002055 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002056
2057 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002058 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002059
John McCallf9b056b2011-03-31 08:03:29 +00002060 FunctionDecl *FD = FunctionDecl::Create(Context,
2061 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002062 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002063 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002064 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002065 false, false);
John McCall31168b02011-06-15 23:02:42 +00002066
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002067 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
2068
Adrian Prantl22e66b42014-04-11 01:13:04 +00002069 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00002070
John McCall7f416cc2015-09-08 08:05:57 +00002071 if (generator.needsCopy()) {
2072 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00002073
John McCallf9b056b2011-03-31 08:03:29 +00002074 // dst->x
Alexey Bataev56223232017-06-09 13:40:18 +00002075 Address destField = CGF.GetAddrOfLocalVar(&Dst);
John McCall7f416cc2015-09-08 08:05:57 +00002076 destField = Address(CGF.Builder.CreateLoad(destField),
2077 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002078 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002079 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2080 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002081
John McCallf9b056b2011-03-31 08:03:29 +00002082 // src->x
Alexey Bataev56223232017-06-09 13:40:18 +00002083 Address srcField = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002084 srcField = Address(CGF.Builder.CreateLoad(srcField),
2085 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002086 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002087 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2088 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00002089
John McCall7f416cc2015-09-08 08:05:57 +00002090 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00002091 }
2092
2093 CGF.FinishFunction();
2094
2095 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002096}
2097
John McCallf9b056b2011-03-31 08:03:29 +00002098/// Build the copy helper for a __block variable.
2099static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002100 const BlockByrefInfo &byrefInfo,
2101 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002102 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002103 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002104}
2105
2106/// Generate code for a __block variable's dispose helper.
2107static llvm::Constant *
2108generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002109 const BlockByrefInfo &byrefInfo,
2110 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002111 ASTContext &Context = CGF.getContext();
2112 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002113
John McCalla738c252011-03-09 04:27:21 +00002114 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002115 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2116 ImplicitParamDecl::Other);
2117 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002118
John McCallc56a8b32016-03-11 04:30:31 +00002119 const CGFunctionInfo &FI =
2120 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002121
John McCall7f416cc2015-09-08 08:05:57 +00002122 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002123
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002124 // FIXME: We'd like to put these into a mergable by content, with
2125 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002126 llvm::Function *Fn =
2127 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00002128 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00002129 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002130
2131 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002132 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002133
John McCallf9b056b2011-03-31 08:03:29 +00002134 FunctionDecl *FD = FunctionDecl::Create(Context,
2135 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002136 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002137 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002138 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002139 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002140
2141 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
2142
Adrian Prantl22e66b42014-04-11 01:13:04 +00002143 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00002144
John McCall7f416cc2015-09-08 08:05:57 +00002145 if (generator.needsDispose()) {
Alexey Bataev56223232017-06-09 13:40:18 +00002146 Address addr = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002147 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2148 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2149 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2150 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00002151
John McCall7f416cc2015-09-08 08:05:57 +00002152 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00002153 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002154
John McCallf9b056b2011-03-31 08:03:29 +00002155 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00002156
John McCallf9b056b2011-03-31 08:03:29 +00002157 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002158}
2159
John McCallf9b056b2011-03-31 08:03:29 +00002160/// Build the dispose helper for a __block variable.
2161static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002162 const BlockByrefInfo &byrefInfo,
2163 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002164 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002165 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002166}
2167
John McCallf593b102013-01-22 03:56:22 +00002168/// Lazily build the copy and dispose helpers for a __block variable
2169/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00002170template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00002171static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2172 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002173 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00002174 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00002175
2176 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00002177 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00002178 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2179 if (node) return static_cast<T*>(node);
2180
John McCall7f416cc2015-09-08 08:05:57 +00002181 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2182 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002183
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00002184 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00002185 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2186 return copy;
2187}
2188
John McCallf593b102013-01-22 03:56:22 +00002189/// Build the copy and dispose helpers for the given __block variable
2190/// emission. Places the helpers in the global cache. Returns null
2191/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00002192BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00002193CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00002194 const AutoVarEmission &emission) {
2195 const VarDecl &var = *emission.Variable;
2196 QualType type = var.getType();
2197
John McCall7f416cc2015-09-08 08:05:57 +00002198 auto &byrefInfo = getBlockByrefInfo(&var);
2199
2200 // The alignment we care about for the purposes of uniquing byref
2201 // helpers is the alignment of the actual byref value field.
2202 CharUnits valueAlignment =
2203 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00002204
John McCallf9b056b2011-03-31 08:03:29 +00002205 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2206 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00002207 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002208
David Blaikie92551612015-08-13 23:53:09 +00002209 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00002210 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00002211 }
2212
John McCall31168b02011-06-15 23:02:42 +00002213 // Otherwise, if we don't have a retainable type, there's nothing to do.
2214 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00002215 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002216
2217 Qualifiers qs = type.getQualifiers();
2218
2219 // If we have lifetime, that dominates.
2220 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00002221 switch (lifetime) {
2222 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2223
2224 // These are just bits as far as the runtime is concerned.
2225 case Qualifiers::OCL_ExplicitNone:
2226 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00002227 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002228
2229 // Tell the runtime that this is ARC __weak, called by the
2230 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002231 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002232 return ::buildByrefHelpers(CGM, byrefInfo,
2233 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002234
2235 // ARC __strong __block variables need to be retained.
2236 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002237 // Block pointers need to be copied, and there's no direct
2238 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002239 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002240 return ::buildByrefHelpers(CGM, byrefInfo,
2241 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002242
2243 // Otherwise, we transfer ownership of the retain from the stack
2244 // to the heap.
2245 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002246 return ::buildByrefHelpers(CGM, byrefInfo,
2247 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002248 }
2249 }
2250 llvm_unreachable("fell out of lifetime switch!");
2251 }
2252
John McCallf9b056b2011-03-31 08:03:29 +00002253 BlockFieldFlags flags;
2254 if (type->isBlockPointerType()) {
2255 flags |= BLOCK_FIELD_IS_BLOCK;
2256 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2257 type->isObjCObjectPointerType()) {
2258 flags |= BLOCK_FIELD_IS_OBJECT;
2259 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002260 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002261 }
2262
2263 if (type.isObjCGCWeak())
2264 flags |= BLOCK_FIELD_IS_WEAK;
2265
John McCall7f416cc2015-09-08 08:05:57 +00002266 return ::buildByrefHelpers(CGM, byrefInfo,
2267 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002268}
2269
John McCall7f416cc2015-09-08 08:05:57 +00002270Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2271 const VarDecl *var,
2272 bool followForward) {
2273 auto &info = getBlockByrefInfo(var);
2274 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002275}
2276
John McCall7f416cc2015-09-08 08:05:57 +00002277Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2278 const BlockByrefInfo &info,
2279 bool followForward,
2280 const llvm::Twine &name) {
2281 // Chase the forwarding address if requested.
2282 if (followForward) {
2283 Address forwardingAddr =
2284 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2285 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2286 }
2287
2288 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2289 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002290}
2291
John McCall7f416cc2015-09-08 08:05:57 +00002292/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002293/// into:
2294///
2295/// struct {
2296/// void *__isa;
2297/// void *__forwarding;
2298/// int32_t __flags;
2299/// int32_t __size;
2300/// void *__copy_helper; // only if needed
2301/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002302/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002303/// char padding[X]; // only if needed
2304/// T x;
2305/// } x
2306///
John McCall7f416cc2015-09-08 08:05:57 +00002307const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2308 auto it = BlockByrefInfos.find(D);
2309 if (it != BlockByrefInfos.end())
2310 return it->second;
John McCall73064872011-03-31 01:59:53 +00002311
John McCall7f416cc2015-09-08 08:05:57 +00002312 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002313 llvm::StructType::create(getLLVMContext(),
2314 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002315
John McCall7f416cc2015-09-08 08:05:57 +00002316 QualType Ty = D->getType();
2317
2318 CharUnits size;
2319 SmallVector<llvm::Type *, 8> types;
2320
John McCall73064872011-03-31 01:59:53 +00002321 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002322 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002323 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002324
2325 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002326 types.push_back(llvm::PointerType::getUnqual(byrefType));
2327 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002328
2329 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002330 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002331 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002332
2333 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002334 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002335 size += CharUnits::fromQuantity(4);
2336
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002337 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002338 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2339 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002340 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002341 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002342 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002343
2344 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002345 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002346 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002347 }
John McCall7f416cc2015-09-08 08:05:57 +00002348
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002349 bool HasByrefExtendedLayout = false;
2350 Qualifiers::ObjCLifetime Lifetime;
2351 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002352 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002353 /// void *__byref_variable_layout;
2354 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002355 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002356 }
2357
2358 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002359 llvm::Type *varTy = ConvertTypeForMem(Ty);
2360
2361 bool packed = false;
2362 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002363 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002364
2365 // We may have to insert padding.
2366 if (varOffset != size) {
2367 llvm::Type *paddingTy =
2368 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2369
2370 types.push_back(paddingTy);
2371 size = varOffset;
2372
2373 // Conversely, we might have to prevent LLVM from inserting padding.
2374 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2375 > varAlign.getQuantity()) {
2376 packed = true;
2377 }
2378 types.push_back(varTy);
2379
2380 byrefType->setBody(types, packed);
2381
2382 BlockByrefInfo info;
2383 info.Type = byrefType;
2384 info.FieldIndex = types.size() - 1;
2385 info.FieldOffset = varOffset;
2386 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2387
2388 auto pair = BlockByrefInfos.insert({D, info});
2389 assert(pair.second && "info was inserted recursively?");
2390 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002391}
2392
2393/// Initialize the structural components of a __block variable, i.e.
2394/// everything but the actual object.
2395void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002396 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002397 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002398
John McCallf9b056b2011-03-31 08:03:29 +00002399 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002400 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002401 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2402
2403 unsigned nextHeaderIndex = 0;
2404 CharUnits nextHeaderOffset;
2405 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2406 const Twine &name) {
2407 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2408 nextHeaderOffset, name);
2409 Builder.CreateStore(value, fieldAddr);
2410
2411 nextHeaderIndex++;
2412 nextHeaderOffset += fieldSize;
2413 };
John McCallf9b056b2011-03-31 08:03:29 +00002414
2415 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002416 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002417
2418 const VarDecl &D = *emission.Variable;
2419 QualType type = D.getType();
2420
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002421 bool HasByrefExtendedLayout;
2422 Qualifiers::ObjCLifetime ByrefLifetime;
2423 bool ByRefHasLifetime =
2424 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002425
John McCallf9b056b2011-03-31 08:03:29 +00002426 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002427
2428 // Initialize the 'isa', which is just 0 or 1.
2429 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002430 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002431 isa = 1;
2432 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002433 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002434
2435 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002436 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002437
2438 // Blocks ABI:
2439 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002440 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002441 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002442 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2443 if (ByRefHasLifetime) {
2444 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2445 else switch (ByrefLifetime) {
2446 case Qualifiers::OCL_Strong:
2447 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2448 break;
2449 case Qualifiers::OCL_Weak:
2450 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2451 break;
2452 case Qualifiers::OCL_ExplicitNone:
2453 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2454 break;
2455 case Qualifiers::OCL_None:
2456 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2457 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2458 break;
2459 default:
2460 break;
2461 }
2462 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2463 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2464 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2465 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2466 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2467 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2468 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2469 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2470 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2471 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2472 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2473 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2474 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2475 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2476 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2477 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2478 }
2479 printf("\n");
2480 }
2481 }
John McCall7f416cc2015-09-08 08:05:57 +00002482 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2483 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002484
John McCallf9b056b2011-03-31 08:03:29 +00002485 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2486 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002487 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002488
John McCallf9b056b2011-03-31 08:03:29 +00002489 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002490 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2491 "byref.copyHelper");
2492 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2493 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002494 }
John McCall7f416cc2015-09-08 08:05:57 +00002495
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002496 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002497 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2498 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002499 }
John McCall73064872011-03-31 01:59:53 +00002500}
2501
John McCallad7c5c12011-02-08 08:22:06 +00002502void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002503 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002504 llvm::Value *args[] = {
2505 Builder.CreateBitCast(V, Int8PtrTy),
2506 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2507 };
2508 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002509}
John McCall73064872011-03-31 01:59:53 +00002510
2511namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002512 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002513 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002514 llvm::Value *Addr;
2515 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2516
Craig Topper4f12f102014-03-12 06:41:41 +00002517 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002518 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002519 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2520 }
2521 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002522} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002523
2524/// Enter a cleanup to destroy a __block variable. Note that this
2525/// cleanup should be a no-op if the variable hasn't left the stack
2526/// yet; if a cleanup is required for the variable itself, that needs
2527/// to be done externally.
2528void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2529 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002530 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002531 return;
2532
John McCall7f416cc2015-09-08 08:05:57 +00002533 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2534 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002535}
John McCall7959fee2011-09-09 20:41:01 +00002536
2537/// Adjust the declaration of something from the blocks API.
2538static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2539 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002540 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002541
2542 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2543 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2544 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2545 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2546
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002547 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2548 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2549 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002550
2551 const NamedDecl *ND = nullptr;
2552 for (const auto &Result : DC->lookup(&II))
2553 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2554 (ND = dyn_cast<VarDecl>(Result)))
2555 break;
2556
2557 // TODO: support static blocks runtime
2558 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2559 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2560 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2561 } else {
2562 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2563 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2564 }
2565 }
2566
2567 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2568 return;
2569
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002570 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002571 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2572}
2573
2574llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2575 if (BlockObjectDispose)
2576 return BlockObjectDispose;
2577
2578 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2579 llvm::FunctionType *fty
2580 = llvm::FunctionType::get(VoidTy, args, false);
2581 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2582 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2583 return BlockObjectDispose;
2584}
2585
2586llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2587 if (BlockObjectAssign)
2588 return BlockObjectAssign;
2589
2590 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2591 llvm::FunctionType *fty
2592 = llvm::FunctionType::get(VoidTy, args, false);
2593 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2594 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2595 return BlockObjectAssign;
2596}
2597
2598llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2599 if (NSConcreteGlobalBlock)
2600 return NSConcreteGlobalBlock;
2601
2602 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002603 Int8PtrTy->getPointerTo(),
2604 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002605 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2606 return NSConcreteGlobalBlock;
2607}
2608
2609llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2610 if (NSConcreteStackBlock)
2611 return NSConcreteStackBlock;
2612
2613 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002614 Int8PtrTy->getPointerTo(),
2615 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002616 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002617 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002618}