blob: 4e57e6cd9542b2f66a9888af481d5f38b134ce87 [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) {
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000310 // The header is basically 'struct { int; int;
Yaxun Liu10712d92017-10-04 20:32:17 +0000311 // custom_fields; }'. Assert that struct is packed.
Yaxun Liu10712d92017-10-04 20:32:17 +0000312 elementTypes.push_back(CGM.IntTy); /* total size */
313 elementTypes.push_back(CGM.IntTy); /* align */
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000314 unsigned Offset = 2 * CGM.getIntSize().getQuantity();
315 unsigned BlockAlign = CGM.getIntAlign().getQuantity();
Yaxun Liu10712d92017-10-04 20:32:17 +0000316 if (auto *Helper =
317 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
318 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
319 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
320 // If necessary, add padding fields to the custom fields.
321 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
322 if (BlockAlign < Align)
323 BlockAlign = Align;
324 assert(Offset % Align == 0);
325 Offset += CGM.getDataLayout().getTypeAllocSize(I);
326 elementTypes.push_back(I);
327 }
328 }
329 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
330 info.BlockSize = CharUnits::fromQuantity(Offset);
331 } else {
332 // The header is basically 'struct { void *; int; int; void *; void *; }'.
333 // Assert that that struct is packed.
334 assert(CGM.getIntSize() <= CGM.getPointerSize());
335 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
336 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
337 info.BlockAlign = CGM.getPointerAlign();
338 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
339 elementTypes.push_back(CGM.VoidPtrTy);
340 elementTypes.push_back(CGM.IntTy);
341 elementTypes.push_back(CGM.IntTy);
342 elementTypes.push_back(CGM.VoidPtrTy);
343 elementTypes.push_back(CGM.getBlockDescriptorType());
344 }
John McCall351762c2011-02-07 10:33:21 +0000345}
346
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000347static QualType getCaptureFieldType(const CodeGenFunction &CGF,
348 const BlockDecl::Capture &CI) {
349 const VarDecl *VD = CI.getVariable();
350
351 // If the variable is captured by an enclosing block or lambda expression,
352 // use the type of the capture field.
353 if (CGF.BlockInfo && CI.isNested())
354 return CGF.BlockInfo->getCapture(VD).fieldType();
355 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
356 return FD->getType();
357 return VD->getType();
358}
359
John McCall351762c2011-02-07 10:33:21 +0000360/// Compute the layout of the given block. Attempts to lay the block
361/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000362static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
363 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000364 ASTContext &C = CGM.getContext();
365 const BlockDecl *block = info.getBlockDecl();
366
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000367 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000368 initializeForBlockHeader(CGM, info, elementTypes);
Yaxun Liu10712d92017-10-04 20:32:17 +0000369 bool hasNonConstantCustomFields = false;
370 if (auto *OpenCLHelper =
371 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
372 hasNonConstantCustomFields =
373 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
374 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
John McCall351762c2011-02-07 10:33:21 +0000375 info.StructureType =
376 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
377 info.CanBeGlobal = true;
378 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000379 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000380 else if (C.getLangOpts().ObjC1 &&
381 CGM.getLangOpts().getGC() == LangOptions::NonGC)
382 info.HasCapturedVariableLayout = true;
383
John McCall351762c2011-02-07 10:33:21 +0000384 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000385 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000386 layout.reserve(block->capturesCXXThis() +
387 (block->capture_end() - block->capture_begin()));
388
389 CharUnits maxFieldAlign;
390
391 // First, 'this'.
392 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000393 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
394 "Can't capture 'this' outside a method");
395 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000396
John McCall7f416cc2015-09-08 08:05:57 +0000397 // Theoretically, this could be in a different address space, so
398 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000399 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000400 std::pair<CharUnits,CharUnits> tinfo
401 = CGM.getContext().getTypeInfoInChars(thisType);
402 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
403
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000404 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
405 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000406 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000407 }
408
409 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000410 for (const auto &CI : block->captures()) {
411 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000412
Aaron Ballman9371dd22014-03-14 18:34:04 +0000413 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000414 // We have to copy/dispose of the __block reference.
415 info.NeedsCopyDispose = true;
416
John McCall351762c2011-02-07 10:33:21 +0000417 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000418 CharUnits align = CGM.getPointerAlign();
419 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000420
John McCall7f416cc2015-09-08 08:05:57 +0000421 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
422 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000423 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000424 continue;
425 }
426
427 // Otherwise, build a layout chunk with the size and alignment of
428 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000429 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000430 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
431 continue;
432 }
433
John McCall31168b02011-06-15 23:02:42 +0000434 // If we have a lifetime qualifier, honor it for capture purposes.
435 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000436 Qualifiers::ObjCLifetime lifetime =
437 variable->getType().getObjCLifetime();
438 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000439 switch (lifetime) {
440 case Qualifiers::OCL_None: llvm_unreachable("impossible");
441 case Qualifiers::OCL_ExplicitNone:
442 case Qualifiers::OCL_Autoreleasing:
443 break;
John McCall351762c2011-02-07 10:33:21 +0000444
John McCall31168b02011-06-15 23:02:42 +0000445 case Qualifiers::OCL_Strong:
446 case Qualifiers::OCL_Weak:
447 info.NeedsCopyDispose = true;
448 }
449
450 // Block pointers require copy/dispose. So do Objective-C pointers.
451 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000452 // But honor the inert __unsafe_unretained qualifier, which doesn't
453 // actually make it into the type system.
454 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
455 lifetime = Qualifiers::OCL_ExplicitNone;
456 } else {
457 info.NeedsCopyDispose = true;
458 // used for mrr below.
459 lifetime = Qualifiers::OCL_Strong;
460 }
John McCall351762c2011-02-07 10:33:21 +0000461
462 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000463 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000464 info.NeedsCopyDispose = true;
465 info.HasCXXObject = true;
466
Akira Hatanaka7275da02018-02-28 07:15:55 +0000467 // So do C structs that require non-trivial copy construction or
468 // destruction.
469 } else if (variable->getType().isNonTrivialToPrimitiveCopy() ==
470 QualType::PCK_Struct ||
471 variable->getType().isDestructedType() ==
472 QualType::DK_nontrivial_c_struct) {
473 info.NeedsCopyDispose = true;
474
John McCall351762c2011-02-07 10:33:21 +0000475 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000476 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000477 if (const CXXRecordDecl *record =
478 variable->getType()->getAsCXXRecordDecl()) {
479 if (!record->hasTrivialDestructor()) {
480 info.HasCXXObject = true;
481 info.NeedsCopyDispose = true;
482 }
483 }
484 }
485
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000486 QualType VT = getCaptureFieldType(*CGF, CI);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000487 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000488 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000489
John McCall351762c2011-02-07 10:33:21 +0000490 maxFieldAlign = std::max(maxFieldAlign, align);
491
Jay Foad7c57be32011-07-11 09:56:20 +0000492 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000493 CGM.getTypes().ConvertTypeForMem(VT);
494
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000495 layout.push_back(
496 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000497 }
498
499 // If that was everything, we're done here.
500 if (layout.empty()) {
501 info.StructureType =
502 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
503 info.CanBeGlobal = true;
504 return;
505 }
506
507 // Sort the layout by alignment. We have to use a stable sort here
508 // to get reproducible results. There should probably be an
509 // llvm::array_pod_stable_sort.
510 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000511
512 // Needed for blocks layout info.
513 info.BlockHeaderForcedGapOffset = info.BlockSize;
514 info.BlockHeaderForcedGapSize = CharUnits::Zero();
515
John McCall351762c2011-02-07 10:33:21 +0000516 CharUnits &blockSize = info.BlockSize;
517 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
518
519 // Assuming that the first byte in the header is maximally aligned,
520 // get the alignment of the first byte following the header.
521 CharUnits endAlign = getLowBit(blockSize);
522
523 // If the end of the header isn't satisfactorily aligned for the
524 // maximum thing, look for things that are okay with the header-end
525 // alignment, and keep appending them until we get something that's
526 // aligned right. This algorithm is only guaranteed optimal if
527 // that condition is satisfied at some point; otherwise we can get
528 // things like:
529 // header // next byte has alignment 4
530 // something_with_size_5; // next byte has alignment 1
531 // something_with_alignment_8;
532 // which has 7 bytes of padding, as opposed to the naive solution
533 // which might have less (?).
534 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000535 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000536 li = layout.begin() + 1, le = layout.end();
537
538 // Look for something that the header end is already
539 // satisfactorily aligned for.
540 for (; li != le && endAlign < li->Alignment; ++li)
541 ;
542
543 // If we found something that's naturally aligned for the end of
544 // the header, keep adding things...
545 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000546 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000547 for (; li != le; ++li) {
548 assert(endAlign >= li->Alignment);
549
John McCall7f416cc2015-09-08 08:05:57 +0000550 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000551 elementTypes.push_back(li->Type);
552 blockSize += li->Size;
553 endAlign = getLowBit(blockSize);
554
555 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000556 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000557 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000558 }
John McCall351762c2011-02-07 10:33:21 +0000559 }
John McCall351762c2011-02-07 10:33:21 +0000560 // Don't re-append everything we just appended.
561 layout.erase(first, li);
562 }
563 }
564
John McCallac0350a2012-04-26 21:14:42 +0000565 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000566
John McCall351762c2011-02-07 10:33:21 +0000567 // At this point, we just have to add padding if the end align still
568 // isn't aligned right.
569 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000570 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000571 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000572
John McCall7f416cc2015-09-08 08:05:57 +0000573 // If we haven't yet added any fields, remember that there was an
574 // initial gap; this need to go into the block layout bit map.
575 if (blockSize == info.BlockHeaderForcedGapOffset) {
576 info.BlockHeaderForcedGapSize = padding;
577 }
578
John McCalle3dc1702011-02-15 09:22:45 +0000579 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
580 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000581 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000582 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000583 }
584
John McCall1db0a2f2012-05-01 20:28:00 +0000585 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000586 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000587 // Slam everything else on now. This works because they have
588 // strictly decreasing alignment and we expect that size is always a
589 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000590 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000591 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000592 if (endAlign < li->Alignment) {
593 // size may not be multiple of alignment. This can only happen with
594 // an over-aligned variable. We will be adding a padding field to
595 // make the size be multiple of alignment.
596 CharUnits padding = li->Alignment - endAlign;
597 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
598 padding.getQuantity()));
599 blockSize += padding;
600 endAlign = getLowBit(blockSize);
601 }
John McCall351762c2011-02-07 10:33:21 +0000602 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000603 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000604 elementTypes.push_back(li->Type);
605 blockSize += li->Size;
606 endAlign = getLowBit(blockSize);
607 }
608
609 info.StructureType =
610 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
611}
612
John McCall08ef4662011-11-10 08:15:53 +0000613/// Enter the scope of a block. This should be run at the entrance to
614/// a full-expression so that the block's cleanups are pushed at the
615/// right place in the stack.
616static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000617 assert(CGF.HaveInsertPoint());
618
John McCall08ef4662011-11-10 08:15:53 +0000619 // Allocate the block info and place it at the head of the list.
620 CGBlockInfo &blockInfo =
621 *new CGBlockInfo(block, CGF.CurFn->getName());
622 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
623 CGF.FirstBlockInfo = &blockInfo;
624
625 // Compute information about the layout, etc., of this block,
626 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000627 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000628
629 // Nothing else to do if it can be global.
630 if (blockInfo.CanBeGlobal) return;
631
632 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000633 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
634 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000635
636 // If there are cleanups to emit, enter them (but inactive).
637 if (!blockInfo.NeedsCopyDispose) return;
638
639 // Walk through the captures (in order) and find the ones not
640 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000641 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000642 // Ignore __block captures; there's nothing special in the
643 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000644 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000645
646 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000647 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000648 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
649 if (capture.isConstant()) continue;
650
651 // Ignore objects that aren't destructed.
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000652 QualType VT = getCaptureFieldType(CGF, CI);
653 QualType::DestructionKind dtorKind = VT.isDestructedType();
John McCall08ef4662011-11-10 08:15:53 +0000654 if (dtorKind == QualType::DK_none) continue;
655
656 CodeGenFunction::Destroyer *destroyer;
657
658 // Block captures count as local values and have imprecise semantics.
659 // They also can't be arrays, so need to worry about that.
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000660 //
661 // For const-qualified captures, emit clang.arc.use to ensure the captured
662 // object doesn't get released while we are still depending on its validity
663 // within the block.
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000664 if (VT.isConstQualified() &&
665 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
666 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
667 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
668 "expected ObjC ARC to be enabled");
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000669 destroyer = CodeGenFunction::emitARCIntrinsicUse;
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000670 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000671 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000672 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000673 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000674 }
675
676 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000677 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
678 capture.getIndex(),
679 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000680
John McCallf4beacd2011-11-10 10:43:54 +0000681 // We can use that GEP as the dominating IP.
682 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000683 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000684
John McCall08ef4662011-11-10 08:15:53 +0000685 CleanupKind cleanupKind = InactiveNormalCleanup;
686 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
687 if (useArrayEHCleanup)
688 cleanupKind = InactiveNormalAndEHCleanup;
689
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000690 CGF.pushDestroy(cleanupKind, addr, VT,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000691 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000692
693 // Remember where that cleanup was.
694 capture.setCleanup(CGF.EHStack.stable_begin());
695 }
696}
697
698/// Enter a full-expression with a non-trivial number of objects to
699/// clean up. This is in this file because, at the moment, the only
700/// kind of cleanup object is a BlockDecl*.
701void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
702 assert(E->getNumObjects() != 0);
George Burgess IV8b93a592018-03-02 20:10:38 +0000703 for (const ExprWithCleanups::CleanupObject &C : E->getObjects())
704 enterBlockScope(*this, C);
John McCall08ef4662011-11-10 08:15:53 +0000705}
706
707/// Find the layout for the given block in a linked list and remove it.
708static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
709 const BlockDecl *block) {
710 while (true) {
711 assert(head && *head);
712 CGBlockInfo *cur = *head;
713
714 // If this is the block we're looking for, splice it out of the list.
715 if (cur->getBlockDecl() == block) {
716 *head = cur->NextBlockInfo;
717 return cur;
718 }
719
720 head = &cur->NextBlockInfo;
721 }
722}
723
724/// Destroy a chain of block layouts.
725void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
726 assert(head && "destroying an empty chain");
727 do {
728 CGBlockInfo *cur = head;
729 head = cur->NextBlockInfo;
730 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000731 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000732}
733
John McCall351762c2011-02-07 10:33:21 +0000734/// Emit a block literal expression in the current function.
Yaxun Liufa13d012018-02-15 16:39:19 +0000735llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000736 // If the block has no captures, we won't have a pre-computed
737 // layout for it.
738 if (!blockExpr->getBlockDecl()->hasCaptures()) {
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000739 // The block literal is emitted as a global variable, and the block invoke
740 // function has to be extracted from its initializer.
741 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
George Burgess IVe3763372016-12-22 02:50:20 +0000742 return Block;
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000743 }
John McCall08ef4662011-11-10 08:15:53 +0000744 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000745 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000746 blockInfo.BlockExpression = blockExpr;
Yaxun Liufa13d012018-02-15 16:39:19 +0000747 return EmitBlockLiteral(blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000748 }
John McCall351762c2011-02-07 10:33:21 +0000749
John McCall08ef4662011-11-10 08:15:53 +0000750 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000751 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000752 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
753 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000754
John McCall08ef4662011-11-10 08:15:53 +0000755 blockInfo->BlockExpression = blockExpr;
Yaxun Liufa13d012018-02-15 16:39:19 +0000756 return EmitBlockLiteral(*blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000757}
758
Yaxun Liufa13d012018-02-15 16:39:19 +0000759llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000760 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
John McCall08ef4662011-11-10 08:15:53 +0000761 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000762 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
Vedant Kumar29477dc2017-12-08 02:47:58 +0000763 CodeGenFunction BlockCGF{CGM, true};
764 BlockCGF.SanOpts = SanOpts;
765 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
Yaxun Liu10712d92017-10-04 20:32:17 +0000766 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
John McCall351762c2011-02-07 10:33:21 +0000767
768 // If there is nothing to capture, we can emit this as a global block.
769 if (blockInfo.CanBeGlobal)
Akira Hatanakaba0367a2017-09-22 21:32:06 +0000770 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
John McCall351762c2011-02-07 10:33:21 +0000771
772 // Otherwise, we have to emit this as a local block.
773
John McCall7f416cc2015-09-08 08:05:57 +0000774 Address blockAddr = blockInfo.LocalAddress;
775 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000776
Yaxun Liu10712d92017-10-04 20:32:17 +0000777 llvm::Constant *isa;
778 llvm::Constant *descriptor;
779 BlockFlags flags;
780 if (!IsOpenCL) {
781 isa = llvm::ConstantExpr::getBitCast(CGM.getNSConcreteStackBlock(),
782 VoidPtrTy);
783
784 // Build the block descriptor.
785 descriptor = buildBlockDescriptor(CGM, blockInfo);
786
787 // Compute the initial on-stack block flags.
788 flags = BLOCK_HAS_SIGNATURE;
789 if (blockInfo.HasCapturedVariableLayout)
790 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
791 if (blockInfo.NeedsCopyDispose)
792 flags |= BLOCK_HAS_COPY_DISPOSE;
793 if (blockInfo.HasCXXObject)
794 flags |= BLOCK_HAS_CXX_OBJ;
795 if (blockInfo.UsesStret)
796 flags |= BLOCK_USE_STRET;
797 }
John McCall351762c2011-02-07 10:33:21 +0000798
John McCall7f416cc2015-09-08 08:05:57 +0000799 auto projectField =
800 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
801 return Builder.CreateStructGEP(blockAddr, index, offset, name);
802 };
803 auto storeField =
804 [&](llvm::Value *value, unsigned index, CharUnits offset,
805 const Twine &name) {
806 Builder.CreateStore(value, projectField(index, offset, name));
807 };
808
809 // Initialize the block header.
810 {
811 // We assume all the header fields are densely packed.
812 unsigned index = 0;
813 CharUnits offset;
814 auto addHeaderField =
815 [&](llvm::Value *value, CharUnits size, const Twine &name) {
816 storeField(value, index, offset, name);
817 offset += size;
818 index++;
819 };
820
Yaxun Liu10712d92017-10-04 20:32:17 +0000821 if (!IsOpenCL) {
822 addHeaderField(isa, getPointerSize(), "block.isa");
823 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
824 getIntSize(), "block.flags");
825 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
826 "block.reserved");
827 } else {
828 addHeaderField(
829 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
830 getIntSize(), "block.size");
831 addHeaderField(
832 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
833 getIntSize(), "block.align");
834 }
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000835 if (!IsOpenCL) {
836 addHeaderField(llvm::ConstantExpr::getBitCast(InvokeFn, VoidPtrTy),
837 getPointerSize(), "block.invoke");
Yaxun Liu10712d92017-10-04 20:32:17 +0000838 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
Yaxun Liucb35e9f2018-03-07 19:32:58 +0000839 } else if (auto *Helper =
840 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000841 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
842 addHeaderField(
843 I.first,
844 CharUnits::fromQuantity(
845 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
846 I.second);
847 }
848 }
John McCall7f416cc2015-09-08 08:05:57 +0000849 }
John McCall351762c2011-02-07 10:33:21 +0000850
851 // Finally, capture all the values into the block.
852 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
853
854 // First, 'this'.
855 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000856 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
857 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000858 Builder.CreateStore(LoadCXXThis(), addr);
859 }
860
861 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000862 for (const auto &CI : blockDecl->captures()) {
863 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000864 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
865
866 // Ignore constant captures.
867 if (capture.isConstant()) continue;
868
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000869 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000870
871 // This will be a [[type]]*, except that a byref entry will just be
872 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000873 Address blockField =
874 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000875
876 // Compute the address of the thing we're going to move into the
877 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000878 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000879
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000880 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000881 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000882 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000883 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000884 } else if (CI.isByRef()) {
885 if (BlockInfo && CI.isNested()) {
886 // We need to use the capture from the enclosing block.
887 const CGBlockInfo::Capture &enclosingCapture =
888 BlockInfo->getCapture(variable);
889
890 // This is a [[type]]*, except that a byref entry wil just be an i8**.
891 src = Builder.CreateStructGEP(LoadBlockStruct(),
892 enclosingCapture.getIndex(),
893 enclosingCapture.getOffset(),
894 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000895 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000896 auto I = LocalDeclMap.find(variable);
897 assert(I != LocalDeclMap.end());
898 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000899 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000900 } else {
901 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
902 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
903 type.getNonReferenceType(), VK_LValue,
904 SourceLocation());
905 src = EmitDeclRefLValue(&declRef).getAddress();
906 };
John McCall351762c2011-02-07 10:33:21 +0000907
908 // For byrefs, we just write the pointer to the byref struct into
909 // the block field. There's no need to chase the forwarding
910 // pointer at this point, since we're building something that will
911 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000912 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000913 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000914 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000915 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000916 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000917 else
John McCall7f416cc2015-09-08 08:05:57 +0000918 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000919
John McCalle3dc1702011-02-15 09:22:45 +0000920 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000921 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000922
923 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000924 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000925 if (blockDecl->isConversionFromLambda()) {
926 // If we have a lambda conversion, emit the expression
927 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000928 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000929 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000930 AggValueSlot::IsDestructed,
931 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +0000932 AggValueSlot::IsNotAliased,
933 AggValueSlot::DoesNotOverlap);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000934 EmitAggExpr(copyExpr, Slot);
935 } else {
936 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
937 }
John McCall351762c2011-02-07 10:33:21 +0000938
939 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000940 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000941 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000942
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000943 // If type is const-qualified, copy the value into the block field.
944 } else if (type.isConstQualified() &&
Akira Hatanaka855d70c2017-05-09 01:20:05 +0000945 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
946 CGM.getCodeGenOpts().OptimizationLevel != 0) {
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000947 llvm::Value *value = Builder.CreateLoad(src, "captured");
948 Builder.CreateStore(value, blockField);
949
John McCall4d14a902013-04-08 23:27:49 +0000950 // If this is an ARC __strong block-pointer variable, don't do a
951 // block copy.
952 //
953 // TODO: this can be generalized into the normal initialization logic:
954 // we should never need to do a block-copy when initializing a local
955 // variable, because the local variable's lifetime should be strictly
956 // contained within the stack block's.
957 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
958 type->isBlockPointerType()) {
959 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000960 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000961 value = EmitARCRetainNonBlock(value);
962
963 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000964 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000965
966 // Otherwise, fake up a POD copy into the block field.
967 } else {
John McCall31168b02011-06-15 23:02:42 +0000968 // Fake up a new variable so that EmitScalarInit doesn't think
969 // we're referring to the variable in its own initializer.
Alexey Bataev56223232017-06-09 13:40:18 +0000970 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
971 ImplicitParamDecl::Other);
John McCall31168b02011-06-15 23:02:42 +0000972
John McCall93be3f72011-02-07 18:37:40 +0000973 // We use one of these or the other depending on whether the
974 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000975 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
976 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
977 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000978
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000979 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000980 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000981 // FIXME: Pass a specific location for the expr init so that the store is
982 // attributed to a reasonable location - otherwise it may be attributed to
983 // locations of subexpressions in the initialization.
Alexey Bataev56223232017-06-09 13:40:18 +0000984 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000985 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +0000986 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000987 }
988
John McCall08ef4662011-11-10 08:15:53 +0000989 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000990 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000991 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
992 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000993 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000994 }
John McCall351762c2011-02-07 10:33:21 +0000995 }
996
997 // Cast to the converted block-pointer type, which happens (somewhat
998 // unfortunately) to be a pointer to function type.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +0000999 llvm::Value *result = Builder.CreatePointerCast(
1000 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +00001001
Yaxun Liufa13d012018-02-15 16:39:19 +00001002 if (IsOpenCL) {
1003 CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1004 result);
1005 }
1006
John McCall351762c2011-02-07 10:33:21 +00001007 return result;
Mike Stump85284ba2009-02-13 16:19:19 +00001008}
1009
1010
Chris Lattnera5f58b02011-07-09 17:41:47 +00001011llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +00001012 if (BlockDescriptorType)
1013 return BlockDescriptorType;
1014
Chris Lattnera5f58b02011-07-09 17:41:47 +00001015 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +00001016 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001017
Mike Stump650c9322009-02-13 15:16:56 +00001018 // struct __block_descriptor {
1019 // unsigned long reserved;
1020 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +00001021 //
1022 // // later, the following will be added
1023 //
1024 // struct {
1025 // void (*copyHelper)();
1026 // void (*copyHelper)();
1027 // } helpers; // !!! optional
1028 //
1029 // const char *signature; // the block signature
1030 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +00001031 // };
Serge Guelton1d993272017-05-09 19:31:30 +00001032 BlockDescriptorType = llvm::StructType::create(
1033 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
Mike Stump650c9322009-02-13 15:16:56 +00001034
John McCall351762c2011-02-07 10:33:21 +00001035 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +00001036 unsigned AddrSpace = 0;
1037 if (getLangOpts().OpenCL)
1038 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1039 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +00001040 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001041}
1042
Chris Lattnera5f58b02011-07-09 17:41:47 +00001043llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001044 assert(!getLangOpts().OpenCL && "OpenCL does not need this");
1045
Mike Stump005c9a62009-02-13 15:25:34 +00001046 if (GenericBlockLiteralType)
1047 return GenericBlockLiteralType;
1048
Chris Lattnera5f58b02011-07-09 17:41:47 +00001049 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +00001050
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001051 // struct __block_literal_generic {
1052 // void *__isa;
1053 // int __flags;
1054 // int __reserved;
1055 // void (*__invoke)(void *);
1056 // struct __block_descriptor *__descriptor;
1057 // };
1058 GenericBlockLiteralType =
1059 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1060 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001061
Mike Stump005c9a62009-02-13 15:25:34 +00001062 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001063}
1064
Yaxun Liu10712d92017-10-04 20:32:17 +00001065RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +00001066 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +00001067 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001068 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +00001069
John McCallb92ab1a2016-10-26 23:46:34 +00001070 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001071 llvm::Value *FuncPtr;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001072
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001073 if (!CGM.getLangOpts().OpenCL) {
1074 // Get a pointer to the generic block literal.
1075 llvm::Type *BlockLiteralTy =
1076 llvm::PointerType::get(CGM.getGenericBlockLiteralType(), 0);
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001077
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001078 // Bitcast the callee to a block literal.
1079 BlockPtr =
1080 Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001081
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001082 // Get the function pointer from the literal.
1083 FuncPtr =
1084 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
1085 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001086
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001087 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001088 CallArgList Args;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001089
1090 QualType VoidPtrQualTy = getContext().VoidPtrTy;
1091 llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1092 if (getLangOpts().OpenCL) {
Yaxun Liu10712d92017-10-04 20:32:17 +00001093 GenericVoidPtrTy = CGM.getOpenCLRuntime().getGenericVoidPointerType();
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001094 VoidPtrQualTy =
1095 getContext().getPointerType(getContext().getAddrSpaceQualType(
1096 getContext().VoidTy, LangAS::opencl_generic));
1097 }
1098
1099 BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1100 Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001101
Anders Carlsson479e6fc2009-04-08 23:13:16 +00001102 QualType FnType = BPT->getPointeeType();
1103
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001104 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +00001105 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +00001106
Anders Carlsson5f50c652009-04-07 22:10:22 +00001107 // Load the function.
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001108 llvm::Value *Func;
1109 if (CGM.getLangOpts().OpenCL)
1110 Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1111 else
1112 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001113
John McCall85915252011-03-09 08:39:33 +00001114 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001115 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001116 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001117
Anders Carlsson5f50c652009-04-07 22:10:22 +00001118 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001119 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001120
Chris Lattner2192fe52011-07-18 04:24:23 +00001121 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Yaxun Liu10712d92017-10-04 20:32:17 +00001122 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001123
John McCallb92ab1a2016-10-26 23:46:34 +00001124 // Prepare the callee.
1125 CGCallee Callee(CGCalleeInfo(), Func);
1126
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001127 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001128 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001129}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001130
John McCall7f416cc2015-09-08 08:05:57 +00001131Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1132 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001133 assert(BlockInfo && "evaluating block ref without block information?");
1134 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001135
John McCall351762c2011-02-07 10:33:21 +00001136 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001137 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001138
John McCall7f416cc2015-09-08 08:05:57 +00001139 Address addr =
1140 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1141 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001142
John McCall351762c2011-02-07 10:33:21 +00001143 if (isByRef) {
1144 // addr should be a void** right now. Load, then cast the result
1145 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001146
John McCall7f416cc2015-09-08 08:05:57 +00001147 auto &byrefInfo = getBlockByrefInfo(variable);
1148 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001149
John McCall7f416cc2015-09-08 08:05:57 +00001150 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1151 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001152
John McCall7f416cc2015-09-08 08:05:57 +00001153 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1154 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001155 }
1156
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001157 if (capture.fieldType()->isReferenceType())
1158 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
Mike Stump7fe9cc12009-10-21 03:49:08 +00001159
John McCall351762c2011-02-07 10:33:21 +00001160 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001161}
1162
George Burgess IVe3763372016-12-22 02:50:20 +00001163void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1164 llvm::Constant *Addr) {
1165 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1166 (void)Ok;
1167 assert(Ok && "Trying to replace an already-existing global block!");
1168}
1169
Mike Stump2d5a2872009-02-14 22:16:35 +00001170llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001171CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1172 StringRef Name) {
George Burgess IVe3763372016-12-22 02:50:20 +00001173 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1174 return Block;
1175
George Burgess IV70d15b32016-11-03 02:21:43 +00001176 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1177 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001178
John McCall351762c2011-02-07 10:33:21 +00001179 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001180 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001181
John McCall351762c2011-02-07 10:33:21 +00001182 // Using that metadata, generate the actual block function.
John McCall351762c2011-02-07 10:33:21 +00001183 {
John McCall7f416cc2015-09-08 08:05:57 +00001184 CodeGenFunction::DeclMapTy LocalDeclMap;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001185 CodeGenFunction(*this).GenerateBlockFunction(
1186 GlobalDecl(), blockInfo, LocalDeclMap,
1187 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
John McCall351762c2011-02-07 10:33:21 +00001188 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001189
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001190 return getAddrOfGlobalBlockIfEmitted(BE);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001191}
1192
John McCall351762c2011-02-07 10:33:21 +00001193static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1194 const CGBlockInfo &blockInfo,
1195 llvm::Constant *blockFn) {
1196 assert(blockInfo.CanBeGlobal);
George Burgess IVe3763372016-12-22 02:50:20 +00001197 // Callers should detect this case on their own: calling this function
1198 // generally requires computing layout information, which is a waste of time
1199 // if we've already emitted this block.
1200 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1201 "Refusing to re-emit a global block.");
John McCall351762c2011-02-07 10:33:21 +00001202
1203 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001204 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001205 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001206
Yaxun Liu10712d92017-10-04 20:32:17 +00001207 bool IsOpenCL = CGM.getLangOpts().OpenCL;
1208 if (!IsOpenCL) {
1209 // isa
1210 fields.add(CGM.getNSConcreteGlobalBlock());
John McCall351762c2011-02-07 10:33:21 +00001211
Yaxun Liu10712d92017-10-04 20:32:17 +00001212 // __flags
1213 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1214 if (blockInfo.UsesStret)
1215 flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +00001216
Yaxun Liu10712d92017-10-04 20:32:17 +00001217 fields.addInt(CGM.IntTy, flags.getBitMask());
1218
1219 // Reserved
1220 fields.addInt(CGM.IntTy, 0);
Yaxun Liucb35e9f2018-03-07 19:32:58 +00001221
1222 // Function
1223 fields.add(blockFn);
Yaxun Liu10712d92017-10-04 20:32:17 +00001224 } else {
1225 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1226 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1227 }
John McCall351762c2011-02-07 10:33:21 +00001228
Yaxun Liu10712d92017-10-04 20:32:17 +00001229 if (!IsOpenCL) {
1230 // Descriptor
1231 fields.add(buildBlockDescriptor(CGM, blockInfo));
1232 } else if (auto *Helper =
1233 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1234 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1235 fields.add(I);
1236 }
1237 }
John McCall351762c2011-02-07 10:33:21 +00001238
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001239 unsigned AddrSpace = 0;
1240 if (CGM.getContext().getLangOpts().OpenCL)
1241 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1242
1243 llvm::Constant *literal = fields.finishAndCreateGlobal(
1244 "__block_literal_global", blockInfo.BlockAlign,
1245 /*constant*/ true, llvm::GlobalVariable::InternalLinkage, AddrSpace);
John McCall351762c2011-02-07 10:33:21 +00001246
1247 // Return a constant of the appropriately-casted type.
George Burgess IVe3763372016-12-22 02:50:20 +00001248 llvm::Type *RequiredType =
John McCall351762c2011-02-07 10:33:21 +00001249 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
George Burgess IVe3763372016-12-22 02:50:20 +00001250 llvm::Constant *Result =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001251 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
George Burgess IVe3763372016-12-22 02:50:20 +00001252 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
Yaxun Liufa13d012018-02-15 16:39:19 +00001253 if (CGM.getContext().getLangOpts().OpenCL)
1254 CGM.getOpenCLRuntime().recordBlockInfo(
1255 blockInfo.BlockExpression,
1256 cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
George Burgess IVe3763372016-12-22 02:50:20 +00001257 return Result;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001258}
1259
John McCall7f416cc2015-09-08 08:05:57 +00001260void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1261 unsigned argNum,
1262 llvm::Value *arg) {
1263 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1264
Adrian Prantl356347b2017-10-26 20:08:52 +00001265 // Allocate a stack slot like for any local variable to guarantee optimal
1266 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1267 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1268 Builder.CreateStore(arg, alloc);
John McCall7f416cc2015-09-08 08:05:57 +00001269 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001270 if (CGM.getCodeGenOpts().getDebugInfo() >=
1271 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001272 DI->setLocation(D->getLocation());
Adrian Prantl356347b2017-10-26 20:08:52 +00001273 DI->EmitDeclareOfBlockLiteralArgVariable(
1274 *BlockInfo, D->getName(), argNum,
1275 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
John McCall7f416cc2015-09-08 08:05:57 +00001276 }
1277 }
1278
1279 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1280 ApplyDebugLocation Scope(*this, StartLoc);
1281
1282 // Instead of messing around with LocalDeclMap, just set the value
1283 // directly as BlockPointer.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001284 BlockPointer = Builder.CreatePointerCast(
1285 arg,
1286 BlockInfo->StructureType->getPointerTo(
1287 getContext().getLangOpts().OpenCL
1288 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1289 : 0),
1290 "block");
John McCall7f416cc2015-09-08 08:05:57 +00001291}
1292
1293Address CodeGenFunction::LoadBlockStruct() {
1294 assert(BlockInfo && "not in a block invocation function!");
1295 assert(BlockPointer && "no block pointer set!");
1296 return Address(BlockPointer, BlockInfo->BlockAlign);
1297}
1298
Mike Stump4446dcf2009-03-05 08:32:30 +00001299llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001300CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1301 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001302 const DeclMapTy &ldm,
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001303 bool IsLambdaConversionToBlock,
1304 bool BuildGlobalBlock) {
John McCall351762c2011-02-07 10:33:21 +00001305 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001306
Fariborz Jahanian63628032012-06-26 16:06:38 +00001307 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001308
1309 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001310
John McCall351762c2011-02-07 10:33:21 +00001311 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001312
Mike Stump5469f292009-03-13 23:34:28 +00001313 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001314 // to be local to this function as well, in case they're directly
1315 // referenced in a block.
1316 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001317 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001318 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001319 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001320 }
1321
John McCall351762c2011-02-07 10:33:21 +00001322 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001323
John McCall351762c2011-02-07 10:33:21 +00001324 // Build the argument list.
1325 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001326
John McCall351762c2011-02-07 10:33:21 +00001327 // The first argument is the block pointer. Just take it as a void*
1328 // and cast it later.
1329 QualType selfTy = getContext().VoidPtrTy;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001330
1331 // For OpenCL passed block pointer can be private AS local variable or
1332 // global AS program scope variable (for the case with and without captures).
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00001333 // Generic AS is used therefore to be able to accommodate both private and
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001334 // generic AS in one implementation.
1335 if (getLangOpts().OpenCL)
1336 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1337 getContext().VoidTy, LangAS::opencl_generic));
1338
Mike Stump7fe9cc12009-10-21 03:49:08 +00001339 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001340
Alexey Bataev56223232017-06-09 13:40:18 +00001341 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1342 SourceLocation(), II, selfTy,
1343 ImplicitParamDecl::ObjCSelf);
1344 args.push_back(&SelfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001345
John McCall351762c2011-02-07 10:33:21 +00001346 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001347 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001348
John McCall351762c2011-02-07 10:33:21 +00001349 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001350 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001351 const CGFunctionInfo &fnInfo =
1352 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001353 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001354 blockInfo.UsesStret = true;
1355
John McCalla729c622012-02-17 03:33:10 +00001356 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001357
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001358 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001359 llvm::Function *fn = llvm::Function::Create(
1360 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001361 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001362
Yaxun Liu10712d92017-10-04 20:32:17 +00001363 if (BuildGlobalBlock) {
1364 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1365 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1366 : VoidPtrTy;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001367 buildGlobalBlock(CGM, blockInfo,
Yaxun Liu10712d92017-10-04 20:32:17 +00001368 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1369 }
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001370
John McCall351762c2011-02-07 10:33:21 +00001371 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001372 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001373 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001374 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001375
John McCall147d0212011-02-22 22:38:33 +00001376 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001377
Adrian Prantl0f6df002013-03-29 19:20:35 +00001378 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1379 // won't delete the dbg.declare intrinsics for captured variables.
1380 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1381 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1382 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001383 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1384 getPointerAlign(),
1385 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001386 // Set the DebugLocation to empty, so the store is recognized as a
1387 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001388 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001389 Builder.CreateStore(BlockPointer, Alloca);
1390 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001391 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001392
John McCall87fe5d52010-05-20 01:18:31 +00001393 // If we have a C++ 'this' reference, go ahead and force it into
1394 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001395 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001396 Address addr =
1397 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1398 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001399 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001400 }
1401
John McCall351762c2011-02-07 10:33:21 +00001402 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001403 for (const auto &CI : blockDecl->captures()) {
1404 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001405 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1406 if (!capture.isConstant()) continue;
1407
John McCall7f416cc2015-09-08 08:05:57 +00001408 CharUnits align = getContext().getDeclAlign(variable);
1409 Address alloca =
1410 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001411
John McCall7f416cc2015-09-08 08:05:57 +00001412 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001413
John McCall7f416cc2015-09-08 08:05:57 +00001414 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001415 }
1416
John McCall113bee02012-03-10 09:33:50 +00001417 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001418 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1419 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1420 --entry_ptr;
1421
Eli Friedman2495ab02012-02-25 02:48:22 +00001422 if (IsLambdaConversionToBlock)
1423 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001424 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001425 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001426 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001427 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001428 }
Mike Stump017460a2009-10-01 22:29:41 +00001429
Mike Stump7d699112009-10-01 00:27:30 +00001430 // Remember where we were...
1431 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001432
Mike Stump7d699112009-10-01 00:27:30 +00001433 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001434 ++entry_ptr;
1435 Builder.SetInsertPoint(entry, entry_ptr);
1436
John McCall113bee02012-03-10 09:33:50 +00001437 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001438 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001439 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001440 for (const auto &CI : blockDecl->captures()) {
1441 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001442 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001443
Benjamin Kramer8c305922016-02-02 11:06:51 +00001444 if (CGM.getCodeGenOpts().getDebugInfo() >=
1445 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001446 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1447 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001448 auto addr = LocalDeclMap.find(variable)->second;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001449 (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1450 Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001451 continue;
1452 }
John McCall351762c2011-02-07 10:33:21 +00001453
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001454 DI->EmitDeclareOfBlockDeclRefVariable(
1455 variable, BlockPointerDbgLoc, Builder, blockInfo,
1456 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001457 }
Mike Stump2e722b92009-09-30 02:43:10 +00001458 }
Manman Renab08a9a2013-01-04 18:51:35 +00001459 // Recover location if it was changed in the above loop.
1460 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001461 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001462 }
John McCall351762c2011-02-07 10:33:21 +00001463
Mike Stump7d699112009-10-01 00:27:30 +00001464 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001465 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001466 Builder.ClearInsertionPoint();
1467 else
1468 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001469
John McCall351762c2011-02-07 10:33:21 +00001470 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001471
John McCall351762c2011-02-07 10:33:21 +00001472 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001473}
Mike Stump1db7d042009-02-28 09:07:16 +00001474
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001475namespace {
1476
1477/// Represents a type of copy/destroy operation that should be performed for an
1478/// entity that's captured by a block.
1479enum class BlockCaptureEntityKind {
1480 CXXRecord, // Copy or destroy
1481 ARCWeak,
1482 ARCStrong,
Akira Hatanaka7275da02018-02-28 07:15:55 +00001483 NonTrivialCStruct,
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001484 BlockObject, // Assign or release
1485 None
1486};
1487
1488/// Represents a captured entity that requires extra operations in order for
1489/// this entity to be copied or destroyed correctly.
1490struct BlockCaptureManagedEntity {
1491 BlockCaptureEntityKind Kind;
1492 BlockFieldFlags Flags;
1493 const BlockDecl::Capture &CI;
1494 const CGBlockInfo::Capture &Capture;
1495
1496 BlockCaptureManagedEntity(BlockCaptureEntityKind Type, BlockFieldFlags Flags,
1497 const BlockDecl::Capture &CI,
1498 const CGBlockInfo::Capture &Capture)
1499 : Kind(Type), Flags(Flags), CI(CI), Capture(Capture) {}
1500};
1501
1502} // end anonymous namespace
1503
1504static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1505computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1506 const LangOptions &LangOpts) {
1507 if (CI.getCopyExpr()) {
1508 assert(!CI.isByRef());
1509 // don't bother computing flags
1510 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1511 }
1512 BlockFieldFlags Flags;
1513 if (CI.isByRef()) {
1514 Flags = BLOCK_FIELD_IS_BYREF;
1515 if (T.isObjCGCWeak())
1516 Flags |= BLOCK_FIELD_IS_WEAK;
1517 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1518 }
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001519
1520 Flags = BLOCK_FIELD_IS_OBJECT;
1521 bool isBlockPointer = T->isBlockPointerType();
1522 if (isBlockPointer)
1523 Flags = BLOCK_FIELD_IS_BLOCK;
1524
Akira Hatanaka7275da02018-02-28 07:15:55 +00001525 switch (T.isNonTrivialToPrimitiveCopy()) {
1526 case QualType::PCK_Struct:
1527 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1528 BlockFieldFlags());
Akira Hatanakad791e922018-03-19 17:38:40 +00001529 case QualType::PCK_ARCWeak:
1530 // We need to register __weak direct captures with the runtime.
1531 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001532 case QualType::PCK_ARCStrong:
1533 // We need to retain the copied value for __strong direct captures.
1534 // If it's a block pointer, we have to copy the block and assign that to
1535 // the destination pointer, so we might as well use _Block_object_assign.
1536 // Otherwise we can avoid that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001537 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1538 : BlockCaptureEntityKind::BlockObject,
1539 Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001540 case QualType::PCK_Trivial:
1541 case QualType::PCK_VolatileTrivial: {
1542 if (!T->isObjCRetainableType())
1543 // For all other types, the memcpy is fine.
1544 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1545
1546 // Special rules for ARC captures:
1547 Qualifiers QS = T.getQualifiers();
1548
Akira Hatanaka7275da02018-02-28 07:15:55 +00001549 // Non-ARC captures of retainable pointers are strong and
1550 // therefore require a call to _Block_object_assign.
1551 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1552 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1553
1554 // Otherwise the memcpy is fine.
1555 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001556 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001557 }
Nico Weberb3897eb2018-02-28 19:28:47 +00001558 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001559}
1560
1561/// Find the set of block captures that need to be explicitly copied or destroy.
1562static void findBlockCapturedManagedEntities(
1563 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1564 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures,
1565 llvm::function_ref<std::pair<BlockCaptureEntityKind, BlockFieldFlags>(
1566 const BlockDecl::Capture &, QualType, const LangOptions &)>
1567 Predicate) {
1568 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1569 const VarDecl *Variable = CI.getVariable();
1570 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1571 if (Capture.isConstant())
1572 continue;
1573
1574 auto Info = Predicate(CI, Variable->getType(), LangOpts);
1575 if (Info.first != BlockCaptureEntityKind::None)
1576 ManagedCaptures.emplace_back(Info.first, Info.second, CI, Capture);
1577 }
1578}
1579
John McCallf593b102013-01-22 03:56:22 +00001580/// Generate the copy-helper function for a block closure object:
1581/// static void block_copy_helper(block_t *dst, block_t *src);
1582/// The runtime will have previously initialized 'dst' by doing a
1583/// bit-copy of 'src'.
1584///
1585/// Note that this copies an entire block closure object to the heap;
1586/// it should not be confused with a 'byref copy helper', which moves
1587/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001588llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001589CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001590 ASTContext &C = getContext();
1591
1592 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001593 ImplicitParamDecl DstDecl(getContext(), C.VoidPtrTy,
1594 ImplicitParamDecl::Other);
1595 args.push_back(&DstDecl);
1596 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1597 ImplicitParamDecl::Other);
1598 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001599
John McCallc56a8b32016-03-11 04:30:31 +00001600 const CGFunctionInfo &FI =
1601 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001602
John McCall351762c2011-02-07 10:33:21 +00001603 // FIXME: it would be nice if these were mergeable with things with
1604 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001605 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001606
1607 llvm::Function *Fn =
1608 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001609 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001610
1611 IdentifierInfo *II
1612 = &CGM.getContext().Idents.get("__copy_helper_block_");
1613
John McCall351762c2011-02-07 10:33:21 +00001614 FunctionDecl *FD = FunctionDecl::Create(C,
1615 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001616 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001617 SourceLocation(), II, C.VoidTy,
1618 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001619 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001620 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001621
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001622 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001623
Adrian Prantl22e66b42014-04-11 01:13:04 +00001624 StartFunction(FD, C.VoidTy, Fn, FI, args);
Vedant Kumar9c6b6822017-10-26 21:27:24 +00001625 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getLocStart()};
Chris Lattner2192fe52011-07-18 04:24:23 +00001626 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001627
Alexey Bataev56223232017-06-09 13:40:18 +00001628 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001629 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001630 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001631
Alexey Bataev56223232017-06-09 13:40:18 +00001632 Address dst = GetAddrOfLocalVar(&DstDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001633 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001634 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001635
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001636 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
1637 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures,
1638 computeCopyInfoForBlockCapture);
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001639
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001640 for (const auto &CopiedCapture : CopiedCaptures) {
1641 const BlockDecl::Capture &CI = CopiedCapture.CI;
1642 const CGBlockInfo::Capture &capture = CopiedCapture.Capture;
1643 BlockFieldFlags flags = CopiedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001644
1645 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001646 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1647 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001648
1649 // If there's an explicit copy expression, we do that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001650 if (CI.getCopyExpr()) {
1651 assert(CopiedCapture.Kind == BlockCaptureEntityKind::CXXRecord);
1652 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1653 } else if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
John McCall31168b02011-06-15 23:02:42 +00001654 EmitARCCopyWeak(dstField, srcField);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001655 // If this is a C struct that requires non-trivial copy construction, emit a
1656 // call to its copy constructor.
1657 } else if (CopiedCapture.Kind ==
1658 BlockCaptureEntityKind::NonTrivialCStruct) {
1659 QualType varType = CI.getVariable()->getType();
1660 callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
1661 MakeAddrLValue(srcField, varType));
John McCall351762c2011-02-07 10:33:21 +00001662 } else {
1663 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001664 if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
John McCalle68b8f42012-10-17 02:28:37 +00001665 // At -O0, store null into the destination field (so that the
1666 // storeStrong doesn't over-release) and then call storeStrong.
1667 // This is a workaround to not having an initStrong call.
1668 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001669 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001670 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1671 Builder.CreateStore(null, dstField);
1672 EmitARCStoreStrongCall(dstField, srcValue, true);
1673
1674 // With optimization enabled, take advantage of the fact that
1675 // the blocks runtime guarantees a memcpy of the block data, and
1676 // just emit a retain of the src field.
1677 } else {
1678 EmitARCRetainNonBlock(srcValue);
1679
1680 // We don't need this anymore, so kill it. It's not quite
1681 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001682 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001683 }
1684 } else {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001685 assert(CopiedCapture.Kind == BlockCaptureEntityKind::BlockObject);
John McCalle68b8f42012-10-17 02:28:37 +00001686 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001687 llvm::Value *dstAddr =
1688 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001689 llvm::Value *args[] = {
1690 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1691 };
1692
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001693 const VarDecl *variable = CI.getVariable();
John McCall882987f2013-02-28 19:01:20 +00001694 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001695 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001696 const Expr *copyExpr =
1697 CGM.getContext().getBlockVarCopyInits(variable);
1698 if (copyExpr) {
1699 copyCanThrow = true; // FIXME: reuse the noexcept logic
1700 }
1701 }
1702
1703 if (copyCanThrow) {
1704 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1705 } else {
1706 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1707 }
John McCalle68b8f42012-10-17 02:28:37 +00001708 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001709 }
1710 }
1711
John McCallad7c5c12011-02-08 08:22:06 +00001712 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001713
John McCalle3dc1702011-02-15 09:22:45 +00001714 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001715}
1716
Akira Hatanaka7275da02018-02-28 07:15:55 +00001717static BlockFieldFlags
1718getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
1719 QualType T) {
1720 BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
1721 if (T->isBlockPointerType())
1722 Flags = BLOCK_FIELD_IS_BLOCK;
1723 return Flags;
1724}
1725
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001726static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1727computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1728 const LangOptions &LangOpts) {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001729 if (CI.isByRef()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00001730 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001731 if (T.isObjCGCWeak())
1732 Flags |= BLOCK_FIELD_IS_WEAK;
1733 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1734 }
1735
Akira Hatanaka7275da02018-02-28 07:15:55 +00001736 switch (T.isDestructedType()) {
1737 case QualType::DK_cxx_destructor:
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001738 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
Akira Hatanaka7275da02018-02-28 07:15:55 +00001739 case QualType::DK_objc_strong_lifetime:
1740 // Use objc_storeStrong for __strong direct captures; the
1741 // dynamic tools really like it when we do this.
1742 return std::make_pair(BlockCaptureEntityKind::ARCStrong,
1743 getBlockFieldFlagsForObjCObjectPointer(CI, T));
1744 case QualType::DK_objc_weak_lifetime:
1745 // Support __weak direct captures.
1746 return std::make_pair(BlockCaptureEntityKind::ARCWeak,
1747 getBlockFieldFlagsForObjCObjectPointer(CI, T));
1748 case QualType::DK_nontrivial_c_struct:
1749 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1750 BlockFieldFlags());
1751 case QualType::DK_none: {
1752 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1753 if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
1754 !LangOpts.ObjCAutoRefCount)
1755 return std::make_pair(BlockCaptureEntityKind::BlockObject,
1756 getBlockFieldFlagsForObjCObjectPointer(CI, T));
1757 // Otherwise, we have nothing to do.
1758 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001759 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001760 }
Nico Weberb3897eb2018-02-28 19:28:47 +00001761 llvm_unreachable("after exhaustive DestructionKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001762}
1763
John McCallf593b102013-01-22 03:56:22 +00001764/// Generate the destroy-helper function for a block closure object:
1765/// static void block_destroy_helper(block_t *theBlock);
1766///
1767/// Note that this destroys a heap-allocated block closure object;
1768/// it should not be confused with a 'byref destroy helper', which
1769/// destroys the heap-allocated contents of an individual __block
1770/// variable.
John McCall351762c2011-02-07 10:33:21 +00001771llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001772CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001773 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001774
John McCall351762c2011-02-07 10:33:21 +00001775 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001776 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1777 ImplicitParamDecl::Other);
1778 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001779
John McCallc56a8b32016-03-11 04:30:31 +00001780 const CGFunctionInfo &FI =
1781 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001782
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001783 // FIXME: We'd like to put these into a mergable by content, with
1784 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001785 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001786
1787 llvm::Function *Fn =
1788 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001789 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001790
1791 IdentifierInfo *II
1792 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1793
John McCall351762c2011-02-07 10:33:21 +00001794 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001795 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001796 SourceLocation(), II, C.VoidTy,
1797 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001798 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001799
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001800 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001801
Adrian Prantl22e66b42014-04-11 01:13:04 +00001802 StartFunction(FD, C.VoidTy, Fn, FI, args);
Vedant Kumar9c6b6822017-10-26 21:27:24 +00001803 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getLocStart()};
Mike Stump6f7d9f82009-03-07 02:53:18 +00001804
Chris Lattner2192fe52011-07-18 04:24:23 +00001805 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001806
Alexey Bataev56223232017-06-09 13:40:18 +00001807 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001808 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001809 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001810
John McCallad7c5c12011-02-08 08:22:06 +00001811 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001812
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001813 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
1814 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures,
1815 computeDestroyInfoForBlockCapture);
John McCall351762c2011-02-07 10:33:21 +00001816
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001817 for (const auto &DestroyedCapture : DestroyedCaptures) {
1818 const BlockDecl::Capture &CI = DestroyedCapture.CI;
1819 const CGBlockInfo::Capture &capture = DestroyedCapture.Capture;
1820 BlockFieldFlags flags = DestroyedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001821
John McCall7f416cc2015-09-08 08:05:57 +00001822 Address srcField =
1823 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001824
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001825 // If the captured record has a destructor then call it.
1826 if (DestroyedCapture.Kind == BlockCaptureEntityKind::CXXRecord) {
1827 const auto *Dtor =
1828 CI.getVariable()->getType()->getAsCXXRecordDecl()->getDestructor();
1829 PushDestructorCleanup(Dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001830
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001831 // If this is a __weak capture, emit the release directly.
1832 } else if (DestroyedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
John McCall31168b02011-06-15 23:02:42 +00001833 EmitARCDestroyWeak(srcField);
1834
John McCalle68b8f42012-10-17 02:28:37 +00001835 // Destroy strong objects with a call if requested.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001836 } else if (DestroyedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
John McCallcdda29c2013-03-13 03:10:54 +00001837 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001838
Akira Hatanaka7275da02018-02-28 07:15:55 +00001839 // If this is a C struct that requires non-trivial destruction, emit a call
1840 // to its destructor.
1841 } else if (DestroyedCapture.Kind ==
1842 BlockCaptureEntityKind::NonTrivialCStruct) {
1843 QualType varType = CI.getVariable()->getType();
1844 pushDestroy(varType.isDestructedType(), srcField, varType);
1845
John McCall351762c2011-02-07 10:33:21 +00001846 // Otherwise we call _Block_object_dispose. It wouldn't be too
1847 // hard to just emit this as a cleanup if we wanted to make sure
1848 // that things were done in reverse.
1849 } else {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001850 assert(DestroyedCapture.Kind == BlockCaptureEntityKind::BlockObject);
John McCall351762c2011-02-07 10:33:21 +00001851 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001852 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001853 BuildBlockRelease(value, flags);
1854 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001855 }
1856
John McCall351762c2011-02-07 10:33:21 +00001857 cleanups.ForceCleanup();
1858
John McCallad7c5c12011-02-08 08:22:06 +00001859 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001860
John McCalle3dc1702011-02-15 09:22:45 +00001861 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001862}
1863
John McCallf9b056b2011-03-31 08:03:29 +00001864namespace {
1865
1866/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001867class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001868 BlockFieldFlags Flags;
1869
1870public:
1871 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001872 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001873
John McCall7f416cc2015-09-08 08:05:57 +00001874 void emitCopy(CodeGenFunction &CGF, Address destField,
1875 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001876 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1877
1878 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1879 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1880
1881 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1882
1883 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1884 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001885
John McCall7f416cc2015-09-08 08:05:57 +00001886 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001887 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001888 }
1889
John McCall7f416cc2015-09-08 08:05:57 +00001890 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001891 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1892 llvm::Value *value = CGF.Builder.CreateLoad(field);
1893
1894 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1895 }
1896
Craig Topper4f12f102014-03-12 06:41:41 +00001897 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001898 id.AddInteger(Flags.getBitMask());
1899 }
1900};
1901
John McCall31168b02011-06-15 23:02:42 +00001902/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001903class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001904public:
John McCall7f416cc2015-09-08 08:05:57 +00001905 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001906
John McCall7f416cc2015-09-08 08:05:57 +00001907 void emitCopy(CodeGenFunction &CGF, Address destField,
1908 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001909 CGF.EmitARCMoveWeak(destField, srcField);
1910 }
1911
John McCall7f416cc2015-09-08 08:05:57 +00001912 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001913 CGF.EmitARCDestroyWeak(field);
1914 }
1915
Craig Topper4f12f102014-03-12 06:41:41 +00001916 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001917 // 0 is distinguishable from all pointers and byref flags
1918 id.AddInteger(0);
1919 }
1920};
1921
1922/// Emits the copy/dispose helpers for an ARC __block __strong variable
1923/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001924class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001925public:
John McCall7f416cc2015-09-08 08:05:57 +00001926 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001927
John McCall7f416cc2015-09-08 08:05:57 +00001928 void emitCopy(CodeGenFunction &CGF, Address destField,
1929 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001930 // Do a "move" by copying the value and then zeroing out the old
1931 // variable.
1932
John McCall7f416cc2015-09-08 08:05:57 +00001933 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001934
John McCall31168b02011-06-15 23:02:42 +00001935 llvm::Value *null =
1936 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001937
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001938 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001939 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001940 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1941 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1942 return;
1943 }
John McCall7f416cc2015-09-08 08:05:57 +00001944 CGF.Builder.CreateStore(value, destField);
1945 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001946 }
1947
John McCall7f416cc2015-09-08 08:05:57 +00001948 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001949 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001950 }
1951
Craig Topper4f12f102014-03-12 06:41:41 +00001952 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001953 // 1 is distinguishable from all pointers and byref flags
1954 id.AddInteger(1);
1955 }
1956};
1957
John McCall3a237aa2011-11-09 03:17:26 +00001958/// Emits the copy/dispose helpers for an ARC __block __strong
1959/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001960class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001961public:
John McCall7f416cc2015-09-08 08:05:57 +00001962 ARCStrongBlockByrefHelpers(CharUnits alignment)
1963 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001964
John McCall7f416cc2015-09-08 08:05:57 +00001965 void emitCopy(CodeGenFunction &CGF, Address destField,
1966 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001967 // Do the copy with objc_retainBlock; that's all that
1968 // _Block_object_assign would do anyway, and we'd have to pass the
1969 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001970 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001971 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001972 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001973 }
1974
John McCall7f416cc2015-09-08 08:05:57 +00001975 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001976 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001977 }
1978
Craig Topper4f12f102014-03-12 06:41:41 +00001979 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001980 // 2 is distinguishable from all pointers and byref flags
1981 id.AddInteger(2);
1982 }
1983};
1984
John McCallf9b056b2011-03-31 08:03:29 +00001985/// Emits the copy/dispose helpers for a __block variable with a
1986/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00001987class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001988 QualType VarType;
1989 const Expr *CopyExpr;
1990
1991public:
1992 CXXByrefHelpers(CharUnits alignment, QualType type,
1993 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00001994 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00001995
Craig Topper8a13c412014-05-21 05:09:00 +00001996 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00001997 void emitCopy(CodeGenFunction &CGF, Address destField,
1998 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001999 if (!CopyExpr) return;
2000 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2001 }
2002
John McCall7f416cc2015-09-08 08:05:57 +00002003 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002004 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2005 CGF.PushDestructorCleanup(VarType, field);
2006 CGF.PopCleanupBlocks(cleanupDepth);
2007 }
2008
Craig Topper4f12f102014-03-12 06:41:41 +00002009 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002010 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2011 }
2012};
Akira Hatanaka7275da02018-02-28 07:15:55 +00002013
2014/// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2015/// C struct.
2016class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2017 QualType VarType;
2018
2019public:
2020 NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2021 : BlockByrefHelpers(alignment), VarType(type) {}
2022
2023 void emitCopy(CodeGenFunction &CGF, Address destField,
2024 Address srcField) override {
2025 CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2026 CGF.MakeAddrLValue(srcField, VarType));
2027 }
2028
2029 bool needsDispose() const override {
2030 return VarType.isDestructedType();
2031 }
2032
2033 void emitDispose(CodeGenFunction &CGF, Address field) override {
2034 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2035 CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2036 CGF.PopCleanupBlocks(cleanupDepth);
2037 }
2038
2039 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2040 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2041 }
2042};
John McCallf9b056b2011-03-31 08:03:29 +00002043} // end anonymous namespace
2044
2045static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00002046generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2047 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002048 ASTContext &Context = CGF.getContext();
2049
2050 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002051
John McCalla738c252011-03-09 04:27:21 +00002052 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002053 ImplicitParamDecl Dst(CGF.getContext(), Context.VoidPtrTy,
2054 ImplicitParamDecl::Other);
2055 args.push_back(&Dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00002056
Alexey Bataev56223232017-06-09 13:40:18 +00002057 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2058 ImplicitParamDecl::Other);
2059 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002060
John McCallc56a8b32016-03-11 04:30:31 +00002061 const CGFunctionInfo &FI =
2062 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002063
John McCall7f416cc2015-09-08 08:05:57 +00002064 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002065
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002066 // FIXME: We'd like to put these into a mergable by content, with
2067 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002068 llvm::Function *Fn =
2069 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00002070 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002071
2072 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002073 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002074
John McCallf9b056b2011-03-31 08:03:29 +00002075 FunctionDecl *FD = FunctionDecl::Create(Context,
2076 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002077 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002078 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002079 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002080 false, false);
John McCall31168b02011-06-15 23:02:42 +00002081
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002082 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002083
Adrian Prantl22e66b42014-04-11 01:13:04 +00002084 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00002085
John McCall7f416cc2015-09-08 08:05:57 +00002086 if (generator.needsCopy()) {
2087 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00002088
John McCallf9b056b2011-03-31 08:03:29 +00002089 // dst->x
Alexey Bataev56223232017-06-09 13:40:18 +00002090 Address destField = CGF.GetAddrOfLocalVar(&Dst);
John McCall7f416cc2015-09-08 08:05:57 +00002091 destField = Address(CGF.Builder.CreateLoad(destField),
2092 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002093 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002094 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2095 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002096
John McCallf9b056b2011-03-31 08:03:29 +00002097 // src->x
Alexey Bataev56223232017-06-09 13:40:18 +00002098 Address srcField = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002099 srcField = Address(CGF.Builder.CreateLoad(srcField),
2100 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002101 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002102 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2103 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00002104
John McCall7f416cc2015-09-08 08:05:57 +00002105 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00002106 }
2107
2108 CGF.FinishFunction();
2109
2110 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002111}
2112
John McCallf9b056b2011-03-31 08:03:29 +00002113/// Build the copy helper for a __block variable.
2114static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002115 const BlockByrefInfo &byrefInfo,
2116 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002117 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002118 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002119}
2120
2121/// Generate code for a __block variable's dispose helper.
2122static llvm::Constant *
2123generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002124 const BlockByrefInfo &byrefInfo,
2125 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002126 ASTContext &Context = CGF.getContext();
2127 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002128
John McCalla738c252011-03-09 04:27:21 +00002129 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002130 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2131 ImplicitParamDecl::Other);
2132 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002133
John McCallc56a8b32016-03-11 04:30:31 +00002134 const CGFunctionInfo &FI =
2135 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002136
John McCall7f416cc2015-09-08 08:05:57 +00002137 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002138
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002139 // FIXME: We'd like to put these into a mergable by content, with
2140 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002141 llvm::Function *Fn =
2142 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00002143 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00002144 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002145
2146 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002147 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002148
John McCallf9b056b2011-03-31 08:03:29 +00002149 FunctionDecl *FD = FunctionDecl::Create(Context,
2150 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002151 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002152 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002153 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002154 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002155
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002156 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002157
Adrian Prantl22e66b42014-04-11 01:13:04 +00002158 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00002159
John McCall7f416cc2015-09-08 08:05:57 +00002160 if (generator.needsDispose()) {
Alexey Bataev56223232017-06-09 13:40:18 +00002161 Address addr = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002162 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2163 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2164 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2165 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00002166
John McCall7f416cc2015-09-08 08:05:57 +00002167 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00002168 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002169
John McCallf9b056b2011-03-31 08:03:29 +00002170 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00002171
John McCallf9b056b2011-03-31 08:03:29 +00002172 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002173}
2174
John McCallf9b056b2011-03-31 08:03:29 +00002175/// Build the dispose helper for a __block variable.
2176static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002177 const BlockByrefInfo &byrefInfo,
2178 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002179 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002180 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002181}
2182
John McCallf593b102013-01-22 03:56:22 +00002183/// Lazily build the copy and dispose helpers for a __block variable
2184/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00002185template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00002186static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2187 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002188 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00002189 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00002190
2191 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00002192 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00002193 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2194 if (node) return static_cast<T*>(node);
2195
John McCall7f416cc2015-09-08 08:05:57 +00002196 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2197 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002198
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00002199 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00002200 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2201 return copy;
2202}
2203
John McCallf593b102013-01-22 03:56:22 +00002204/// Build the copy and dispose helpers for the given __block variable
2205/// emission. Places the helpers in the global cache. Returns null
2206/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00002207BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00002208CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00002209 const AutoVarEmission &emission) {
2210 const VarDecl &var = *emission.Variable;
2211 QualType type = var.getType();
2212
John McCall7f416cc2015-09-08 08:05:57 +00002213 auto &byrefInfo = getBlockByrefInfo(&var);
2214
2215 // The alignment we care about for the purposes of uniquing byref
2216 // helpers is the alignment of the actual byref value field.
2217 CharUnits valueAlignment =
2218 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00002219
John McCallf9b056b2011-03-31 08:03:29 +00002220 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2221 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00002222 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002223
David Blaikie92551612015-08-13 23:53:09 +00002224 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00002225 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00002226 }
2227
Akira Hatanaka7275da02018-02-28 07:15:55 +00002228 // If type is a non-trivial C struct type that is non-trivial to
2229 // destructly move or destroy, build the copy and dispose helpers.
2230 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2231 type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2232 return ::buildByrefHelpers(
2233 CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2234
John McCall31168b02011-06-15 23:02:42 +00002235 // Otherwise, if we don't have a retainable type, there's nothing to do.
2236 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00002237 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002238
2239 Qualifiers qs = type.getQualifiers();
2240
2241 // If we have lifetime, that dominates.
2242 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00002243 switch (lifetime) {
2244 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2245
2246 // These are just bits as far as the runtime is concerned.
2247 case Qualifiers::OCL_ExplicitNone:
2248 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00002249 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002250
2251 // Tell the runtime that this is ARC __weak, called by the
2252 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002253 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002254 return ::buildByrefHelpers(CGM, byrefInfo,
2255 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002256
2257 // ARC __strong __block variables need to be retained.
2258 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002259 // Block pointers need to be copied, and there's no direct
2260 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002261 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002262 return ::buildByrefHelpers(CGM, byrefInfo,
2263 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002264
2265 // Otherwise, we transfer ownership of the retain from the stack
2266 // to the heap.
2267 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002268 return ::buildByrefHelpers(CGM, byrefInfo,
2269 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002270 }
2271 }
2272 llvm_unreachable("fell out of lifetime switch!");
2273 }
2274
John McCallf9b056b2011-03-31 08:03:29 +00002275 BlockFieldFlags flags;
2276 if (type->isBlockPointerType()) {
2277 flags |= BLOCK_FIELD_IS_BLOCK;
2278 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2279 type->isObjCObjectPointerType()) {
2280 flags |= BLOCK_FIELD_IS_OBJECT;
2281 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002282 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002283 }
2284
2285 if (type.isObjCGCWeak())
2286 flags |= BLOCK_FIELD_IS_WEAK;
2287
John McCall7f416cc2015-09-08 08:05:57 +00002288 return ::buildByrefHelpers(CGM, byrefInfo,
2289 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002290}
2291
John McCall7f416cc2015-09-08 08:05:57 +00002292Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2293 const VarDecl *var,
2294 bool followForward) {
2295 auto &info = getBlockByrefInfo(var);
2296 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002297}
2298
John McCall7f416cc2015-09-08 08:05:57 +00002299Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2300 const BlockByrefInfo &info,
2301 bool followForward,
2302 const llvm::Twine &name) {
2303 // Chase the forwarding address if requested.
2304 if (followForward) {
2305 Address forwardingAddr =
2306 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2307 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2308 }
2309
2310 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2311 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002312}
2313
John McCall7f416cc2015-09-08 08:05:57 +00002314/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002315/// into:
2316///
2317/// struct {
2318/// void *__isa;
2319/// void *__forwarding;
2320/// int32_t __flags;
2321/// int32_t __size;
2322/// void *__copy_helper; // only if needed
2323/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002324/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002325/// char padding[X]; // only if needed
2326/// T x;
2327/// } x
2328///
John McCall7f416cc2015-09-08 08:05:57 +00002329const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2330 auto it = BlockByrefInfos.find(D);
2331 if (it != BlockByrefInfos.end())
2332 return it->second;
John McCall73064872011-03-31 01:59:53 +00002333
John McCall7f416cc2015-09-08 08:05:57 +00002334 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002335 llvm::StructType::create(getLLVMContext(),
2336 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002337
John McCall7f416cc2015-09-08 08:05:57 +00002338 QualType Ty = D->getType();
2339
2340 CharUnits size;
2341 SmallVector<llvm::Type *, 8> types;
2342
John McCall73064872011-03-31 01:59:53 +00002343 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002344 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002345 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002346
2347 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002348 types.push_back(llvm::PointerType::getUnqual(byrefType));
2349 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002350
2351 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002352 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002353 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002354
2355 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002356 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002357 size += CharUnits::fromQuantity(4);
2358
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002359 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002360 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2361 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002362 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002363 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002364 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002365
2366 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002367 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002368 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002369 }
John McCall7f416cc2015-09-08 08:05:57 +00002370
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002371 bool HasByrefExtendedLayout = false;
2372 Qualifiers::ObjCLifetime Lifetime;
2373 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002374 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002375 /// void *__byref_variable_layout;
2376 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002377 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002378 }
2379
2380 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002381 llvm::Type *varTy = ConvertTypeForMem(Ty);
2382
2383 bool packed = false;
2384 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002385 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002386
2387 // We may have to insert padding.
2388 if (varOffset != size) {
2389 llvm::Type *paddingTy =
2390 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2391
2392 types.push_back(paddingTy);
2393 size = varOffset;
2394
2395 // Conversely, we might have to prevent LLVM from inserting padding.
2396 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2397 > varAlign.getQuantity()) {
2398 packed = true;
2399 }
2400 types.push_back(varTy);
2401
2402 byrefType->setBody(types, packed);
2403
2404 BlockByrefInfo info;
2405 info.Type = byrefType;
2406 info.FieldIndex = types.size() - 1;
2407 info.FieldOffset = varOffset;
2408 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2409
2410 auto pair = BlockByrefInfos.insert({D, info});
2411 assert(pair.second && "info was inserted recursively?");
2412 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002413}
2414
2415/// Initialize the structural components of a __block variable, i.e.
2416/// everything but the actual object.
2417void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002418 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002419 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002420
John McCallf9b056b2011-03-31 08:03:29 +00002421 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002422 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002423 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2424
2425 unsigned nextHeaderIndex = 0;
2426 CharUnits nextHeaderOffset;
2427 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2428 const Twine &name) {
2429 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2430 nextHeaderOffset, name);
2431 Builder.CreateStore(value, fieldAddr);
2432
2433 nextHeaderIndex++;
2434 nextHeaderOffset += fieldSize;
2435 };
John McCallf9b056b2011-03-31 08:03:29 +00002436
2437 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002438 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002439
2440 const VarDecl &D = *emission.Variable;
2441 QualType type = D.getType();
2442
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002443 bool HasByrefExtendedLayout;
2444 Qualifiers::ObjCLifetime ByrefLifetime;
2445 bool ByRefHasLifetime =
2446 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002447
John McCallf9b056b2011-03-31 08:03:29 +00002448 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002449
2450 // Initialize the 'isa', which is just 0 or 1.
2451 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002452 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002453 isa = 1;
2454 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002455 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002456
2457 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002458 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002459
2460 // Blocks ABI:
2461 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002462 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002463 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002464 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2465 if (ByRefHasLifetime) {
2466 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2467 else switch (ByrefLifetime) {
2468 case Qualifiers::OCL_Strong:
2469 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2470 break;
2471 case Qualifiers::OCL_Weak:
2472 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2473 break;
2474 case Qualifiers::OCL_ExplicitNone:
2475 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2476 break;
2477 case Qualifiers::OCL_None:
2478 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2479 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2480 break;
2481 default:
2482 break;
2483 }
2484 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2485 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2486 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2487 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2488 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2489 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2490 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2491 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2492 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2493 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2494 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2495 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2496 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2497 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2498 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2499 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2500 }
2501 printf("\n");
2502 }
2503 }
John McCall7f416cc2015-09-08 08:05:57 +00002504 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2505 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002506
John McCallf9b056b2011-03-31 08:03:29 +00002507 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2508 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002509 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002510
John McCallf9b056b2011-03-31 08:03:29 +00002511 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002512 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2513 "byref.copyHelper");
2514 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2515 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002516 }
John McCall7f416cc2015-09-08 08:05:57 +00002517
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002518 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002519 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2520 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002521 }
John McCall73064872011-03-31 01:59:53 +00002522}
2523
John McCallad7c5c12011-02-08 08:22:06 +00002524void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002525 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002526 llvm::Value *args[] = {
2527 Builder.CreateBitCast(V, Int8PtrTy),
2528 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2529 };
2530 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002531}
John McCall73064872011-03-31 01:59:53 +00002532
2533namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002534 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002535 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002536 llvm::Value *Addr;
2537 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2538
Craig Topper4f12f102014-03-12 06:41:41 +00002539 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002540 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002541 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2542 }
2543 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002544} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002545
2546/// Enter a cleanup to destroy a __block variable. Note that this
2547/// cleanup should be a no-op if the variable hasn't left the stack
2548/// yet; if a cleanup is required for the variable itself, that needs
2549/// to be done externally.
2550void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2551 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002552 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002553 return;
2554
John McCall7f416cc2015-09-08 08:05:57 +00002555 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2556 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002557}
John McCall7959fee2011-09-09 20:41:01 +00002558
2559/// Adjust the declaration of something from the blocks API.
2560static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2561 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002562 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002563
2564 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2565 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2566 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2567 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2568
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002569 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2570 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2571 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002572
2573 const NamedDecl *ND = nullptr;
2574 for (const auto &Result : DC->lookup(&II))
2575 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2576 (ND = dyn_cast<VarDecl>(Result)))
2577 break;
2578
2579 // TODO: support static blocks runtime
2580 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2581 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2582 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2583 } else {
2584 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2585 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2586 }
2587 }
2588
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002589 if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2590 GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002591 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002592
2593 CGM.setDSOLocal(GV);
John McCall7959fee2011-09-09 20:41:01 +00002594}
2595
2596llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2597 if (BlockObjectDispose)
2598 return BlockObjectDispose;
2599
2600 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2601 llvm::FunctionType *fty
2602 = llvm::FunctionType::get(VoidTy, args, false);
2603 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2604 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2605 return BlockObjectDispose;
2606}
2607
2608llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2609 if (BlockObjectAssign)
2610 return BlockObjectAssign;
2611
2612 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2613 llvm::FunctionType *fty
2614 = llvm::FunctionType::get(VoidTy, args, false);
2615 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2616 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2617 return BlockObjectAssign;
2618}
2619
2620llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2621 if (NSConcreteGlobalBlock)
2622 return NSConcreteGlobalBlock;
2623
2624 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002625 Int8PtrTy->getPointerTo(),
2626 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002627 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2628 return NSConcreteGlobalBlock;
2629}
2630
2631llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2632 if (NSConcreteStackBlock)
2633 return NSConcreteStackBlock;
2634
2635 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002636 Int8PtrTy->getPointerTo(),
2637 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002638 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002639 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002640}