blob: a4848d1f69ad63dcaf9cfbe0e4ac51af90a8e54f [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
Anders Carlsson2437cbf2009-02-12 00:39:25 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
John McCallad7c5c12011-02-08 08:22:06 +000014#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
John McCall5ad74072017-03-02 20:04:19 +000019#include "clang/CodeGen/ConstantInitBuilder.h"
Mike Stump692c6e32009-03-20 21:53:12 +000020#include "clang/AST/DeclObjC.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000022#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Module.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000025#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000026#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000027
Anders Carlsson2437cbf2009-02-12 00:39:25 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall08ef4662011-11-10 08:15:53 +000031CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
32 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000033 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
John McCall7f416cc2015-09-08 08:05:57 +000034 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
Craig Topper8a13c412014-05-21 05:09:00 +000035 DominatingIP(nullptr) {
36
John McCall08ef4662011-11-10 08:15:53 +000037 // Skip asm prefix, if any. 'name' is usually taken directly from
38 // the mangled name of the enclosing function.
39 if (!name.empty() && name[0] == '\01')
40 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000041}
42
John McCallf9b056b2011-03-31 08:03:29 +000043// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000044BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000045
John McCall351762c2011-02-07 10:33:21 +000046/// Build the given block as a global block.
47static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
48 const CGBlockInfo &blockInfo,
49 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000050
John McCall351762c2011-02-07 10:33:21 +000051/// Build the helper function to copy a block.
52static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo) {
54 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
55}
56
Alp Tokerf6a24ce2013-12-05 16:25:25 +000057/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000058static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
59 const CGBlockInfo &blockInfo) {
60 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
61}
62
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000063/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
64/// buildBlockDescriptor is accessed from 5th field of the Block_literal
65/// meta-data and contains stationary information about the block literal.
66/// Its definition will have 4 (or optinally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000067/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000068/// struct Block_descriptor {
69/// unsigned long reserved;
70/// unsigned long size; // size of Block_literal metadata in bytes.
71/// void *copy_func_helper_decl; // optional copy helper.
72/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000073/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000074/// void *block_layout_info; // encoding of captured block variables.
75/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000076/// \endcode
John McCall351762c2011-02-07 10:33:21 +000077static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
78 const CGBlockInfo &blockInfo) {
79 ASTContext &C = CGM.getContext();
80
John McCall6c9f1fdb2016-11-19 08:17:24 +000081 llvm::IntegerType *ulong =
82 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
83 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000084 if (CGM.getLangOpts().OpenCL)
85 i8p =
86 llvm::Type::getInt8PtrTy(
87 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
88 else
John McCall6c9f1fdb2016-11-19 08:17:24 +000089 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +000090
John McCall23c9dc62016-11-28 22:18:27 +000091 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +000092 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +000093
94 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +000095 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +000096
97 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +000098 // FIXME: What is the right way to say this doesn't fit? We should give
99 // a user diagnostic in that case. Better fix would be to change the
100 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000101 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000102
John McCall351762c2011-02-07 10:33:21 +0000103 // Optional copy/dispose helpers.
104 if (blockInfo.NeedsCopyDispose) {
Mike Stump85284ba2009-02-13 16:19:19 +0000105 // copy_func_helper_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000106 elements.add(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000107
108 // destroy_func_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000109 elements.add(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000110 }
111
John McCall351762c2011-02-07 10:33:21 +0000112 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
113 std::string typeAtEncoding =
114 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000115 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000116 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000117
John McCall351762c2011-02-07 10:33:21 +0000118 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000119 if (C.getLangOpts().ObjC1) {
120 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000121 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000122 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000123 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000124 }
John McCall351762c2011-02-07 10:33:21 +0000125 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000126 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000127
Joey Goulyddbda402016-08-10 15:57:02 +0000128 unsigned AddrSpace = 0;
129 if (C.getLangOpts().OpenCL)
130 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000131
John McCall351762c2011-02-07 10:33:21 +0000132 llvm::GlobalVariable *global =
John McCall6c9f1fdb2016-11-19 08:17:24 +0000133 elements.finishAndCreateGlobal("__block_descriptor_tmp",
134 CGM.getPointerAlign(),
135 /*constant*/ true,
136 llvm::GlobalValue::InternalLinkage,
137 AddrSpace);
Mike Stump85284ba2009-02-13 16:19:19 +0000138
John McCall351762c2011-02-07 10:33:21 +0000139 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000140}
141
John McCall351762c2011-02-07 10:33:21 +0000142/*
143 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000144
John McCall351762c2011-02-07 10:33:21 +0000145 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
146 struct Block_literal {
147 /// Initialized to one of:
148 /// extern void *_NSConcreteStackBlock[];
149 /// extern void *_NSConcreteGlobalBlock[];
150 ///
151 /// In theory, we could start one off malloc'ed by setting
152 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
153 /// this isa:
154 /// extern void *_NSConcreteMallocBlock[];
155 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000156
John McCall351762c2011-02-07 10:33:21 +0000157 /// These are the flags (with corresponding bit number) that the
158 /// compiler is actually supposed to know about.
159 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
160 /// descriptor provides copy and dispose helper functions
161 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
162 /// object with a nontrivial destructor or copy constructor
163 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
164 /// as global memory
165 /// 29. BLOCK_USE_STRET - indicates that the block function
166 /// uses stret, which objc_msgSend needs to know about
167 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
168 /// @encoded signature string
169 /// And we're not supposed to manipulate these:
170 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
171 /// to malloc'ed memory
172 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
173 /// to GC-allocated memory
174 /// Additionally, the bottom 16 bits are a reference count which
175 /// should be zero on the stack.
176 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000177
John McCall351762c2011-02-07 10:33:21 +0000178 /// Reserved; should be zero-initialized.
179 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000180
John McCall351762c2011-02-07 10:33:21 +0000181 /// Function pointer generated from block literal.
182 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000183
John McCall351762c2011-02-07 10:33:21 +0000184 /// Block description metadata generated from block literal.
185 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000186
John McCall351762c2011-02-07 10:33:21 +0000187 /// Captured values follow.
188 _CapturesTypes captures...;
189 };
190 */
David Chisnall950a9512009-11-17 19:33:30 +0000191
John McCall351762c2011-02-07 10:33:21 +0000192namespace {
193 /// A chunk of data that we actually have to capture in the block.
194 struct BlockLayoutChunk {
195 CharUnits Alignment;
196 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000197 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000198 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000199 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000200 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000201
John McCall351762c2011-02-07 10:33:21 +0000202 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000203 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000204 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000205 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000206 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000207 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000208
John McCall351762c2011-02-07 10:33:21 +0000209 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000210 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
211 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000212 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000213 info.CXXThisOffset = offset;
214 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000215 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
216 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000217 }
John McCall87fe5d52010-05-20 01:18:31 +0000218 }
John McCall351762c2011-02-07 10:33:21 +0000219 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000220
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000221 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
222 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000223 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000224 if (left.Alignment != right.Alignment)
225 return left.Alignment > right.Alignment;
226
227 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000228 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000229 return 1;
230 if (chunk.Lifetime == Qualifiers::OCL_Strong)
231 return 0;
232 if (chunk.Lifetime == Qualifiers::OCL_Weak)
233 return 2;
234 return 3;
235 };
236
237 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000238 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000239} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000240
John McCallb0a3ecb2011-02-08 03:07:00 +0000241/// Determines if the given type is safe for constant capture in C++.
242static bool isSafeForCXXConstantCapture(QualType type) {
243 const RecordType *recordType =
244 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
245
246 // Only records can be unsafe.
247 if (!recordType) return true;
248
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000249 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000250
251 // Maintain semantics for classes with non-trivial dtors or copy ctors.
252 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000253 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000254
255 // Otherwise, we just have to make sure there aren't any mutable
256 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000257 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000258}
259
John McCall351762c2011-02-07 10:33:21 +0000260/// It is illegal to modify a const object after initialization.
261/// Therefore, if a const object has a constant initializer, we don't
262/// actually need to keep storage for it in the block; we'll just
263/// rematerialize it at the start of the block function. This is
264/// acceptable because we make no promises about address stability of
265/// captured variables.
266static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000267 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000268 const VarDecl *var) {
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000269 // Return if this is a function paramter. We shouldn't try to
270 // rematerialize default arguments of function parameters.
271 if (isa<ParmVarDecl>(var))
272 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000273
John McCall351762c2011-02-07 10:33:21 +0000274 QualType type = var->getType();
275
276 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000277 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000278
John McCallb0a3ecb2011-02-08 03:07:00 +0000279 // Furthermore, in C++ we have to worry about mutable fields:
280 // C++ [dcl.type.cv]p4:
281 // Except that any class member declared mutable can be
282 // modified, any attempt to modify a const object during its
283 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000284 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000285 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000286
287 // If the variable doesn't have any initializer (shouldn't this be
288 // invalid?), it's not clear what we should do. Maybe capture as
289 // zero?
290 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000291 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000292
Richard Smithdafff942012-01-14 04:30:29 +0000293 return CGM.EmitConstantInit(*var, CGF);
John McCall351762c2011-02-07 10:33:21 +0000294}
295
296/// Get the low bit of a nonzero character count. This is the
297/// alignment of the nth byte if the 0th byte is universally aligned.
298static CharUnits getLowBit(CharUnits v) {
299 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
300}
301
302static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000303 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall7f416cc2015-09-08 08:05:57 +0000304 // The header is basically 'struct { void *; int; int; void *; void *; }'.
305 // Assert that that struct is packed.
306 assert(CGM.getIntSize() <= CGM.getPointerSize());
307 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
308 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
John McCall351762c2011-02-07 10:33:21 +0000309
John McCall7f416cc2015-09-08 08:05:57 +0000310 info.BlockAlign = CGM.getPointerAlign();
311 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
John McCall351762c2011-02-07 10:33:21 +0000312
313 assert(elementTypes.empty());
John McCall7f416cc2015-09-08 08:05:57 +0000314 elementTypes.push_back(CGM.VoidPtrTy);
315 elementTypes.push_back(CGM.IntTy);
316 elementTypes.push_back(CGM.IntTy);
317 elementTypes.push_back(CGM.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000318 elementTypes.push_back(CGM.getBlockDescriptorType());
John McCall351762c2011-02-07 10:33:21 +0000319}
320
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000321static QualType getCaptureFieldType(const CodeGenFunction &CGF,
322 const BlockDecl::Capture &CI) {
323 const VarDecl *VD = CI.getVariable();
324
325 // If the variable is captured by an enclosing block or lambda expression,
326 // use the type of the capture field.
327 if (CGF.BlockInfo && CI.isNested())
328 return CGF.BlockInfo->getCapture(VD).fieldType();
329 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
330 return FD->getType();
331 return VD->getType();
332}
333
John McCall351762c2011-02-07 10:33:21 +0000334/// Compute the layout of the given block. Attempts to lay the block
335/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000336static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
337 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000338 ASTContext &C = CGM.getContext();
339 const BlockDecl *block = info.getBlockDecl();
340
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000341 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000342 initializeForBlockHeader(CGM, info, elementTypes);
343
344 if (!block->hasCaptures()) {
345 info.StructureType =
346 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
347 info.CanBeGlobal = true;
348 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000349 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000350 else if (C.getLangOpts().ObjC1 &&
351 CGM.getLangOpts().getGC() == LangOptions::NonGC)
352 info.HasCapturedVariableLayout = true;
353
John McCall351762c2011-02-07 10:33:21 +0000354 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000355 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000356 layout.reserve(block->capturesCXXThis() +
357 (block->capture_end() - block->capture_begin()));
358
359 CharUnits maxFieldAlign;
360
361 // First, 'this'.
362 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000363 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
364 "Can't capture 'this' outside a method");
365 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000366
John McCall7f416cc2015-09-08 08:05:57 +0000367 // Theoretically, this could be in a different address space, so
368 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000369 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000370 std::pair<CharUnits,CharUnits> tinfo
371 = CGM.getContext().getTypeInfoInChars(thisType);
372 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
373
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000374 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
375 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000376 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000377 }
378
379 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000380 for (const auto &CI : block->captures()) {
381 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000382
Aaron Ballman9371dd22014-03-14 18:34:04 +0000383 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000384 // We have to copy/dispose of the __block reference.
385 info.NeedsCopyDispose = true;
386
John McCall351762c2011-02-07 10:33:21 +0000387 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000388 CharUnits align = CGM.getPointerAlign();
389 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000390
John McCall7f416cc2015-09-08 08:05:57 +0000391 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
392 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000393 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000394 continue;
395 }
396
397 // Otherwise, build a layout chunk with the size and alignment of
398 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000399 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000400 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
401 continue;
402 }
403
John McCall31168b02011-06-15 23:02:42 +0000404 // If we have a lifetime qualifier, honor it for capture purposes.
405 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000406 Qualifiers::ObjCLifetime lifetime =
407 variable->getType().getObjCLifetime();
408 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000409 switch (lifetime) {
410 case Qualifiers::OCL_None: llvm_unreachable("impossible");
411 case Qualifiers::OCL_ExplicitNone:
412 case Qualifiers::OCL_Autoreleasing:
413 break;
John McCall351762c2011-02-07 10:33:21 +0000414
John McCall31168b02011-06-15 23:02:42 +0000415 case Qualifiers::OCL_Strong:
416 case Qualifiers::OCL_Weak:
417 info.NeedsCopyDispose = true;
418 }
419
420 // Block pointers require copy/dispose. So do Objective-C pointers.
421 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000422 // But honor the inert __unsafe_unretained qualifier, which doesn't
423 // actually make it into the type system.
424 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
425 lifetime = Qualifiers::OCL_ExplicitNone;
426 } else {
427 info.NeedsCopyDispose = true;
428 // used for mrr below.
429 lifetime = Qualifiers::OCL_Strong;
430 }
John McCall351762c2011-02-07 10:33:21 +0000431
432 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000433 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000434 info.NeedsCopyDispose = true;
435 info.HasCXXObject = true;
436
437 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000438 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000439 if (const CXXRecordDecl *record =
440 variable->getType()->getAsCXXRecordDecl()) {
441 if (!record->hasTrivialDestructor()) {
442 info.HasCXXObject = true;
443 info.NeedsCopyDispose = true;
444 }
445 }
446 }
447
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000448 QualType VT = getCaptureFieldType(*CGF, CI);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000449 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000450 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000451
John McCall351762c2011-02-07 10:33:21 +0000452 maxFieldAlign = std::max(maxFieldAlign, align);
453
Jay Foad7c57be32011-07-11 09:56:20 +0000454 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000455 CGM.getTypes().ConvertTypeForMem(VT);
456
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000457 layout.push_back(
458 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000459 }
460
461 // If that was everything, we're done here.
462 if (layout.empty()) {
463 info.StructureType =
464 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
465 info.CanBeGlobal = true;
466 return;
467 }
468
469 // Sort the layout by alignment. We have to use a stable sort here
470 // to get reproducible results. There should probably be an
471 // llvm::array_pod_stable_sort.
472 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000473
474 // Needed for blocks layout info.
475 info.BlockHeaderForcedGapOffset = info.BlockSize;
476 info.BlockHeaderForcedGapSize = CharUnits::Zero();
477
John McCall351762c2011-02-07 10:33:21 +0000478 CharUnits &blockSize = info.BlockSize;
479 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
480
481 // Assuming that the first byte in the header is maximally aligned,
482 // get the alignment of the first byte following the header.
483 CharUnits endAlign = getLowBit(blockSize);
484
485 // If the end of the header isn't satisfactorily aligned for the
486 // maximum thing, look for things that are okay with the header-end
487 // alignment, and keep appending them until we get something that's
488 // aligned right. This algorithm is only guaranteed optimal if
489 // that condition is satisfied at some point; otherwise we can get
490 // things like:
491 // header // next byte has alignment 4
492 // something_with_size_5; // next byte has alignment 1
493 // something_with_alignment_8;
494 // which has 7 bytes of padding, as opposed to the naive solution
495 // which might have less (?).
496 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000497 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000498 li = layout.begin() + 1, le = layout.end();
499
500 // Look for something that the header end is already
501 // satisfactorily aligned for.
502 for (; li != le && endAlign < li->Alignment; ++li)
503 ;
504
505 // If we found something that's naturally aligned for the end of
506 // the header, keep adding things...
507 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000508 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000509 for (; li != le; ++li) {
510 assert(endAlign >= li->Alignment);
511
John McCall7f416cc2015-09-08 08:05:57 +0000512 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000513 elementTypes.push_back(li->Type);
514 blockSize += li->Size;
515 endAlign = getLowBit(blockSize);
516
517 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000518 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000519 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000520 }
John McCall351762c2011-02-07 10:33:21 +0000521 }
John McCall351762c2011-02-07 10:33:21 +0000522 // Don't re-append everything we just appended.
523 layout.erase(first, li);
524 }
525 }
526
John McCallac0350a2012-04-26 21:14:42 +0000527 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000528
John McCall351762c2011-02-07 10:33:21 +0000529 // At this point, we just have to add padding if the end align still
530 // isn't aligned right.
531 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000532 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000533 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000534
John McCall7f416cc2015-09-08 08:05:57 +0000535 // If we haven't yet added any fields, remember that there was an
536 // initial gap; this need to go into the block layout bit map.
537 if (blockSize == info.BlockHeaderForcedGapOffset) {
538 info.BlockHeaderForcedGapSize = padding;
539 }
540
John McCalle3dc1702011-02-15 09:22:45 +0000541 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
542 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000543 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000544 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000545 }
546
John McCall1db0a2f2012-05-01 20:28:00 +0000547 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000548 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000549 // Slam everything else on now. This works because they have
550 // strictly decreasing alignment and we expect that size is always a
551 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000552 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000553 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000554 if (endAlign < li->Alignment) {
555 // size may not be multiple of alignment. This can only happen with
556 // an over-aligned variable. We will be adding a padding field to
557 // make the size be multiple of alignment.
558 CharUnits padding = li->Alignment - endAlign;
559 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
560 padding.getQuantity()));
561 blockSize += padding;
562 endAlign = getLowBit(blockSize);
563 }
John McCall351762c2011-02-07 10:33:21 +0000564 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000565 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000566 elementTypes.push_back(li->Type);
567 blockSize += li->Size;
568 endAlign = getLowBit(blockSize);
569 }
570
571 info.StructureType =
572 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
573}
574
John McCall08ef4662011-11-10 08:15:53 +0000575/// Enter the scope of a block. This should be run at the entrance to
576/// a full-expression so that the block's cleanups are pushed at the
577/// right place in the stack.
578static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000579 assert(CGF.HaveInsertPoint());
580
John McCall08ef4662011-11-10 08:15:53 +0000581 // Allocate the block info and place it at the head of the list.
582 CGBlockInfo &blockInfo =
583 *new CGBlockInfo(block, CGF.CurFn->getName());
584 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
585 CGF.FirstBlockInfo = &blockInfo;
586
587 // Compute information about the layout, etc., of this block,
588 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000589 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000590
591 // Nothing else to do if it can be global.
592 if (blockInfo.CanBeGlobal) return;
593
594 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000595 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
596 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000597
598 // If there are cleanups to emit, enter them (but inactive).
599 if (!blockInfo.NeedsCopyDispose) return;
600
601 // Walk through the captures (in order) and find the ones not
602 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000603 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000604 // Ignore __block captures; there's nothing special in the
605 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000606 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000607
608 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000609 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000610 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
611 if (capture.isConstant()) continue;
612
613 // Ignore objects that aren't destructed.
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000614 QualType VT = getCaptureFieldType(CGF, CI);
615 QualType::DestructionKind dtorKind = VT.isDestructedType();
John McCall08ef4662011-11-10 08:15:53 +0000616 if (dtorKind == QualType::DK_none) continue;
617
618 CodeGenFunction::Destroyer *destroyer;
619
620 // Block captures count as local values and have imprecise semantics.
621 // They also can't be arrays, so need to worry about that.
622 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000623 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000624 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000625 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000626 }
627
628 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000629 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
630 capture.getIndex(),
631 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000632
John McCallf4beacd2011-11-10 10:43:54 +0000633 // We can use that GEP as the dominating IP.
634 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000635 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000636
John McCall08ef4662011-11-10 08:15:53 +0000637 CleanupKind cleanupKind = InactiveNormalCleanup;
638 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
639 if (useArrayEHCleanup)
640 cleanupKind = InactiveNormalAndEHCleanup;
641
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000642 CGF.pushDestroy(cleanupKind, addr, VT,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000643 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000644
645 // Remember where that cleanup was.
646 capture.setCleanup(CGF.EHStack.stable_begin());
647 }
648}
649
650/// Enter a full-expression with a non-trivial number of objects to
651/// clean up. This is in this file because, at the moment, the only
652/// kind of cleanup object is a BlockDecl*.
653void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
654 assert(E->getNumObjects() != 0);
655 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
656 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
657 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
658 enterBlockScope(*this, *i);
659 }
660}
661
662/// Find the layout for the given block in a linked list and remove it.
663static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
664 const BlockDecl *block) {
665 while (true) {
666 assert(head && *head);
667 CGBlockInfo *cur = *head;
668
669 // If this is the block we're looking for, splice it out of the list.
670 if (cur->getBlockDecl() == block) {
671 *head = cur->NextBlockInfo;
672 return cur;
673 }
674
675 head = &cur->NextBlockInfo;
676 }
677}
678
679/// Destroy a chain of block layouts.
680void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
681 assert(head && "destroying an empty chain");
682 do {
683 CGBlockInfo *cur = head;
684 head = cur->NextBlockInfo;
685 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000686 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000687}
688
John McCall351762c2011-02-07 10:33:21 +0000689/// Emit a block literal expression in the current function.
690llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000691 // If the block has no captures, we won't have a pre-computed
692 // layout for it.
693 if (!blockExpr->getBlockDecl()->hasCaptures()) {
George Burgess IVe3763372016-12-22 02:50:20 +0000694 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
695 return Block;
John McCall08ef4662011-11-10 08:15:53 +0000696 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000697 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000698 blockInfo.BlockExpression = blockExpr;
699 return EmitBlockLiteral(blockInfo);
700 }
John McCall351762c2011-02-07 10:33:21 +0000701
John McCall08ef4662011-11-10 08:15:53 +0000702 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000703 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000704 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
705 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000706
John McCall08ef4662011-11-10 08:15:53 +0000707 blockInfo->BlockExpression = blockExpr;
708 return EmitBlockLiteral(*blockInfo);
709}
710
711llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
712 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000713 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall351762c2011-02-07 10:33:21 +0000714 llvm::Constant *blockFn
Fariborz Jahanian63628032012-06-26 16:06:38 +0000715 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCalldec348f72013-05-03 07:33:41 +0000716 LocalDeclMap,
717 isLambdaConv);
John McCalle3dc1702011-02-15 09:22:45 +0000718 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000719
720 // If there is nothing to capture, we can emit this as a global block.
721 if (blockInfo.CanBeGlobal)
722 return buildGlobalBlock(CGM, blockInfo, blockFn);
723
724 // Otherwise, we have to emit this as a local block.
725
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +0000726 llvm::Constant *isa =
727 (!CGM.getContext().getLangOpts().OpenCL)
728 ? CGM.getNSConcreteStackBlock()
729 : CGM.getNullPointer(cast<llvm::PointerType>(
730 CGM.getNSConcreteStackBlock()->getType()),
731 QualType(getContext().VoidPtrTy));
John McCalle3dc1702011-02-15 09:22:45 +0000732 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000733
734 // Build the block descriptor.
735 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
736
John McCall7f416cc2015-09-08 08:05:57 +0000737 Address blockAddr = blockInfo.LocalAddress;
738 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000739
740 // Compute the initial on-stack block flags.
John McCallad7c5c12011-02-08 08:22:06 +0000741 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000742 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall351762c2011-02-07 10:33:21 +0000743 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
744 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall85915252011-03-09 08:39:33 +0000745 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +0000746
John McCall7f416cc2015-09-08 08:05:57 +0000747 auto projectField =
748 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
749 return Builder.CreateStructGEP(blockAddr, index, offset, name);
750 };
751 auto storeField =
752 [&](llvm::Value *value, unsigned index, CharUnits offset,
753 const Twine &name) {
754 Builder.CreateStore(value, projectField(index, offset, name));
755 };
756
757 // Initialize the block header.
758 {
759 // We assume all the header fields are densely packed.
760 unsigned index = 0;
761 CharUnits offset;
762 auto addHeaderField =
763 [&](llvm::Value *value, CharUnits size, const Twine &name) {
764 storeField(value, index, offset, name);
765 offset += size;
766 index++;
767 };
768
769 addHeaderField(isa, getPointerSize(), "block.isa");
770 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
771 getIntSize(), "block.flags");
772 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
773 getIntSize(), "block.reserved");
774 addHeaderField(blockFn, getPointerSize(), "block.invoke");
775 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
776 }
John McCall351762c2011-02-07 10:33:21 +0000777
778 // Finally, capture all the values into the block.
779 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
780
781 // First, 'this'.
782 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000783 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
784 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000785 Builder.CreateStore(LoadCXXThis(), addr);
786 }
787
788 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000789 for (const auto &CI : blockDecl->captures()) {
790 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000791 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
792
793 // Ignore constant captures.
794 if (capture.isConstant()) continue;
795
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000796 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000797
798 // This will be a [[type]]*, except that a byref entry will just be
799 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000800 Address blockField =
801 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000802
803 // Compute the address of the thing we're going to move into the
804 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000805 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000806
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000807 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000808 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000809 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000810 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000811 } else if (CI.isByRef()) {
812 if (BlockInfo && CI.isNested()) {
813 // We need to use the capture from the enclosing block.
814 const CGBlockInfo::Capture &enclosingCapture =
815 BlockInfo->getCapture(variable);
816
817 // This is a [[type]]*, except that a byref entry wil just be an i8**.
818 src = Builder.CreateStructGEP(LoadBlockStruct(),
819 enclosingCapture.getIndex(),
820 enclosingCapture.getOffset(),
821 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000822 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000823 auto I = LocalDeclMap.find(variable);
824 assert(I != LocalDeclMap.end());
825 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000826 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000827 } else {
828 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
829 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
830 type.getNonReferenceType(), VK_LValue,
831 SourceLocation());
832 src = EmitDeclRefLValue(&declRef).getAddress();
833 };
John McCall351762c2011-02-07 10:33:21 +0000834
835 // For byrefs, we just write the pointer to the byref struct into
836 // the block field. There's no need to chase the forwarding
837 // pointer at this point, since we're building something that will
838 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000839 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000840 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000841 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000842 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000843 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000844 else
John McCall7f416cc2015-09-08 08:05:57 +0000845 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000846
John McCalle3dc1702011-02-15 09:22:45 +0000847 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000848 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000849
850 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000851 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000852 if (blockDecl->isConversionFromLambda()) {
853 // If we have a lambda conversion, emit the expression
854 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000855 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000856 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000857 AggValueSlot::IsDestructed,
858 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000859 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000860 EmitAggExpr(copyExpr, Slot);
861 } else {
862 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
863 }
John McCall351762c2011-02-07 10:33:21 +0000864
865 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000866 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000867 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000868
869 // If this is an ARC __strong block-pointer variable, don't do a
870 // block copy.
871 //
872 // TODO: this can be generalized into the normal initialization logic:
873 // we should never need to do a block-copy when initializing a local
874 // variable, because the local variable's lifetime should be strictly
875 // contained within the stack block's.
876 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
877 type->isBlockPointerType()) {
878 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000879 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000880 value = EmitARCRetainNonBlock(value);
881
882 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000883 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000884
885 // Otherwise, fake up a POD copy into the block field.
886 } else {
John McCall31168b02011-06-15 23:02:42 +0000887 // Fake up a new variable so that EmitScalarInit doesn't think
888 // we're referring to the variable in its own initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000889 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
890 SourceLocation(), /*name*/ nullptr,
891 type);
John McCall31168b02011-06-15 23:02:42 +0000892
John McCall93be3f72011-02-07 18:37:40 +0000893 // We use one of these or the other depending on whether the
894 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000895 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
896 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
897 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000898
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000899 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000900 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000901 // FIXME: Pass a specific location for the expr init so that the store is
902 // attributed to a reasonable location - otherwise it may be attributed to
903 // locations of subexpressions in the initialization.
John McCall1553b192011-06-16 04:16:24 +0000904 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall7f416cc2015-09-08 08:05:57 +0000905 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +0000906 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000907 }
908
John McCall08ef4662011-11-10 08:15:53 +0000909 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000910 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000911 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
912 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000913 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000914 }
John McCall351762c2011-02-07 10:33:21 +0000915 }
916
917 // Cast to the converted block-pointer type, which happens (somewhat
918 // unfortunately) to be a pointer to function type.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +0000919 llvm::Value *result = Builder.CreatePointerCast(
920 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +0000921
John McCall351762c2011-02-07 10:33:21 +0000922 return result;
Mike Stump85284ba2009-02-13 16:19:19 +0000923}
924
925
Chris Lattnera5f58b02011-07-09 17:41:47 +0000926llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +0000927 if (BlockDescriptorType)
928 return BlockDescriptorType;
929
Chris Lattnera5f58b02011-07-09 17:41:47 +0000930 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000931 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000932
Mike Stump650c9322009-02-13 15:16:56 +0000933 // struct __block_descriptor {
934 // unsigned long reserved;
935 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +0000936 //
937 // // later, the following will be added
938 //
939 // struct {
940 // void (*copyHelper)();
941 // void (*copyHelper)();
942 // } helpers; // !!! optional
943 //
944 // const char *signature; // the block signature
945 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +0000946 // };
Chris Lattner845511f2011-06-18 22:49:11 +0000947 BlockDescriptorType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000948 llvm::StructType::create("struct.__block_descriptor",
Reid Kleckneree7cf842014-12-01 22:02:27 +0000949 UnsignedLongTy, UnsignedLongTy, nullptr);
Mike Stump650c9322009-02-13 15:16:56 +0000950
John McCall351762c2011-02-07 10:33:21 +0000951 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +0000952 unsigned AddrSpace = 0;
953 if (getLangOpts().OpenCL)
954 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
955 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +0000956 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000957}
958
Chris Lattnera5f58b02011-07-09 17:41:47 +0000959llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +0000960 if (GenericBlockLiteralType)
961 return GenericBlockLiteralType;
962
Chris Lattnera5f58b02011-07-09 17:41:47 +0000963 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000964
Mike Stump005c9a62009-02-13 15:25:34 +0000965 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000966 // void *__isa;
967 // int __flags;
968 // int __reserved;
969 // void (*__invoke)(void *);
970 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000971 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000972 GenericBlockLiteralType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000973 llvm::StructType::create("struct.__block_literal_generic",
974 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +0000975 BlockDescPtrTy, nullptr);
Mike Stumpb7074c02009-02-13 15:32:32 +0000976
Mike Stump005c9a62009-02-13 15:25:34 +0000977 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000978}
979
Nick Lewycky2d84e842013-10-02 02:29:49 +0000980RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +0000981 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000982 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000983 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +0000984
John McCallb92ab1a2016-10-26 23:46:34 +0000985 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000986
987 // Get a pointer to the generic block literal.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +0000988 // For OpenCL we generate generic AS void ptr to be able to reuse the same
989 // block definition for blocks with captures generated as private AS local
990 // variables and without captures generated as global AS program scope
991 // variables.
992 unsigned AddrSpace = 0;
993 if (getLangOpts().OpenCL)
994 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_generic);
995
Chris Lattner2192fe52011-07-18 04:24:23 +0000996 llvm::Type *BlockLiteralTy =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +0000997 llvm::PointerType::get(CGM.getGenericBlockLiteralType(), AddrSpace);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000998
999 // Bitcast the callee to a block literal.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001000 BlockPtr =
1001 Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001002
1003 // Get the function pointer from the literal.
John McCall7f416cc2015-09-08 08:05:57 +00001004 llvm::Value *FuncPtr =
John McCallb92ab1a2016-10-26 23:46:34 +00001005 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001006
Mike Stumpb7074c02009-02-13 15:32:32 +00001007
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001008 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001009 CallArgList Args;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001010
1011 QualType VoidPtrQualTy = getContext().VoidPtrTy;
1012 llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1013 if (getLangOpts().OpenCL) {
1014 GenericVoidPtrTy = Builder.getInt8PtrTy(
1015 getContext().getTargetAddressSpace(LangAS::opencl_generic));
1016 VoidPtrQualTy =
1017 getContext().getPointerType(getContext().getAddrSpaceQualType(
1018 getContext().VoidTy, LangAS::opencl_generic));
1019 }
1020
1021 BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1022 Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001023
Anders Carlsson479e6fc2009-04-08 23:13:16 +00001024 QualType FnType = BPT->getPointeeType();
1025
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001026 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +00001027 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +00001028
Anders Carlsson5f50c652009-04-07 22:10:22 +00001029 // Load the function.
John McCall7f416cc2015-09-08 08:05:57 +00001030 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001031
John McCall85915252011-03-09 08:39:33 +00001032 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001033 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001034 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001035
Anders Carlsson5f50c652009-04-07 22:10:22 +00001036 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001037 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001038
Chris Lattner2192fe52011-07-18 04:24:23 +00001039 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson5f50c652009-04-07 22:10:22 +00001040 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001041
John McCallb92ab1a2016-10-26 23:46:34 +00001042 // Prepare the callee.
1043 CGCallee Callee(CGCalleeInfo(), Func);
1044
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001045 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001046 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001047}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001048
John McCall7f416cc2015-09-08 08:05:57 +00001049Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1050 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001051 assert(BlockInfo && "evaluating block ref without block information?");
1052 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001053
John McCall351762c2011-02-07 10:33:21 +00001054 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001055 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001056
John McCall7f416cc2015-09-08 08:05:57 +00001057 Address addr =
1058 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1059 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001060
John McCall351762c2011-02-07 10:33:21 +00001061 if (isByRef) {
1062 // addr should be a void** right now. Load, then cast the result
1063 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001064
John McCall7f416cc2015-09-08 08:05:57 +00001065 auto &byrefInfo = getBlockByrefInfo(variable);
1066 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001067
John McCall7f416cc2015-09-08 08:05:57 +00001068 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1069 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001070
John McCall7f416cc2015-09-08 08:05:57 +00001071 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1072 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001073 }
1074
Akira Hatanakad542ccf2016-09-16 00:02:06 +00001075 if (auto refType = capture.fieldType()->getAs<ReferenceType>())
John McCall7f416cc2015-09-08 08:05:57 +00001076 addr = EmitLoadOfReference(addr, refType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001077
John McCall351762c2011-02-07 10:33:21 +00001078 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001079}
1080
George Burgess IVe3763372016-12-22 02:50:20 +00001081void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1082 llvm::Constant *Addr) {
1083 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1084 (void)Ok;
1085 assert(Ok && "Trying to replace an already-existing global block!");
1086}
1087
Mike Stump2d5a2872009-02-14 22:16:35 +00001088llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001089CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1090 StringRef Name) {
George Burgess IVe3763372016-12-22 02:50:20 +00001091 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1092 return Block;
1093
George Burgess IV70d15b32016-11-03 02:21:43 +00001094 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1095 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001096
John McCall351762c2011-02-07 10:33:21 +00001097 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001098 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001099
John McCall351762c2011-02-07 10:33:21 +00001100 // Using that metadata, generate the actual block function.
1101 llvm::Constant *blockFn;
1102 {
John McCall7f416cc2015-09-08 08:05:57 +00001103 CodeGenFunction::DeclMapTy LocalDeclMap;
John McCallad7c5c12011-02-08 08:22:06 +00001104 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1105 blockInfo,
John McCalldec348f72013-05-03 07:33:41 +00001106 LocalDeclMap,
Eli Friedman2495ab02012-02-25 02:48:22 +00001107 false);
John McCall351762c2011-02-07 10:33:21 +00001108 }
John McCalle3dc1702011-02-15 09:22:45 +00001109 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001110
John McCallad7c5c12011-02-08 08:22:06 +00001111 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001112}
1113
John McCall351762c2011-02-07 10:33:21 +00001114static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1115 const CGBlockInfo &blockInfo,
1116 llvm::Constant *blockFn) {
1117 assert(blockInfo.CanBeGlobal);
George Burgess IVe3763372016-12-22 02:50:20 +00001118 // Callers should detect this case on their own: calling this function
1119 // generally requires computing layout information, which is a waste of time
1120 // if we've already emitted this block.
1121 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1122 "Refusing to re-emit a global block.");
John McCall351762c2011-02-07 10:33:21 +00001123
1124 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001125 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001126 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001127
1128 // isa
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001129 fields.add(
1130 (!CGM.getContext().getLangOpts().OpenCL)
1131 ? CGM.getNSConcreteGlobalBlock()
1132 : CGM.getNullPointer(cast<llvm::PointerType>(
1133 CGM.getNSConcreteGlobalBlock()->getType()),
1134 QualType(CGM.getContext().VoidPtrTy)));
John McCall351762c2011-02-07 10:33:21 +00001135
1136 // __flags
John McCall85915252011-03-09 08:39:33 +00001137 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1138 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1139
John McCall6c9f1fdb2016-11-19 08:17:24 +00001140 fields.addInt(CGM.IntTy, flags.getBitMask());
John McCall351762c2011-02-07 10:33:21 +00001141
1142 // Reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +00001143 fields.addInt(CGM.IntTy, 0);
John McCall351762c2011-02-07 10:33:21 +00001144
1145 // Function
John McCall6c9f1fdb2016-11-19 08:17:24 +00001146 fields.add(blockFn);
John McCall351762c2011-02-07 10:33:21 +00001147
1148 // Descriptor
John McCall6c9f1fdb2016-11-19 08:17:24 +00001149 fields.add(buildBlockDescriptor(CGM, blockInfo));
John McCall351762c2011-02-07 10:33:21 +00001150
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001151 unsigned AddrSpace = 0;
1152 if (CGM.getContext().getLangOpts().OpenCL)
1153 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1154
1155 llvm::Constant *literal = fields.finishAndCreateGlobal(
1156 "__block_literal_global", blockInfo.BlockAlign,
1157 /*constant*/ true, llvm::GlobalVariable::InternalLinkage, AddrSpace);
John McCall351762c2011-02-07 10:33:21 +00001158
1159 // Return a constant of the appropriately-casted type.
George Burgess IVe3763372016-12-22 02:50:20 +00001160 llvm::Type *RequiredType =
John McCall351762c2011-02-07 10:33:21 +00001161 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
George Burgess IVe3763372016-12-22 02:50:20 +00001162 llvm::Constant *Result =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001163 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
George Burgess IVe3763372016-12-22 02:50:20 +00001164 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1165 return Result;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001166}
1167
John McCall7f416cc2015-09-08 08:05:57 +00001168void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1169 unsigned argNum,
1170 llvm::Value *arg) {
1171 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1172
1173 llvm::Value *localAddr = nullptr;
1174 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1175 // Allocate a stack slot to let the debug info survive the RA.
1176 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1177 Builder.CreateStore(arg, alloc);
1178 localAddr = Builder.CreateLoad(alloc);
1179 }
1180
1181 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001182 if (CGM.getCodeGenOpts().getDebugInfo() >=
1183 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001184 DI->setLocation(D->getLocation());
1185 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1186 localAddr, Builder);
1187 }
1188 }
1189
1190 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1191 ApplyDebugLocation Scope(*this, StartLoc);
1192
1193 // Instead of messing around with LocalDeclMap, just set the value
1194 // directly as BlockPointer.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001195 BlockPointer = Builder.CreatePointerCast(
1196 arg,
1197 BlockInfo->StructureType->getPointerTo(
1198 getContext().getLangOpts().OpenCL
1199 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1200 : 0),
1201 "block");
John McCall7f416cc2015-09-08 08:05:57 +00001202}
1203
1204Address CodeGenFunction::LoadBlockStruct() {
1205 assert(BlockInfo && "not in a block invocation function!");
1206 assert(BlockPointer && "no block pointer set!");
1207 return Address(BlockPointer, BlockInfo->BlockAlign);
1208}
1209
Mike Stump4446dcf2009-03-05 08:32:30 +00001210llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001211CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1212 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001213 const DeclMapTy &ldm,
1214 bool IsLambdaConversionToBlock) {
John McCall351762c2011-02-07 10:33:21 +00001215 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001216
Fariborz Jahanian63628032012-06-26 16:06:38 +00001217 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001218
1219 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001220
John McCall351762c2011-02-07 10:33:21 +00001221 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001222
Mike Stump5469f292009-03-13 23:34:28 +00001223 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001224 // to be local to this function as well, in case they're directly
1225 // referenced in a block.
1226 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001227 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001228 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001229 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001230 }
1231
John McCall351762c2011-02-07 10:33:21 +00001232 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001233
John McCall351762c2011-02-07 10:33:21 +00001234 // Build the argument list.
1235 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001236
John McCall351762c2011-02-07 10:33:21 +00001237 // The first argument is the block pointer. Just take it as a void*
1238 // and cast it later.
1239 QualType selfTy = getContext().VoidPtrTy;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001240
1241 // For OpenCL passed block pointer can be private AS local variable or
1242 // global AS program scope variable (for the case with and without captures).
1243 // Generic AS is used therefore to be able to accomodate both private and
1244 // generic AS in one implementation.
1245 if (getLangOpts().OpenCL)
1246 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1247 getContext().VoidTy, LangAS::opencl_generic));
1248
Mike Stump7fe9cc12009-10-21 03:49:08 +00001249 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001250
Richard Smith053f6c62014-05-16 23:01:30 +00001251 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
John McCall147d0212011-02-22 22:38:33 +00001252 SourceLocation(), II, selfTy);
John McCalla738c252011-03-09 04:27:21 +00001253 args.push_back(&selfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001254
John McCall351762c2011-02-07 10:33:21 +00001255 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001256 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001257
John McCall351762c2011-02-07 10:33:21 +00001258 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001259 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001260 const CGFunctionInfo &fnInfo =
1261 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001262 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001263 blockInfo.UsesStret = true;
1264
John McCalla729c622012-02-17 03:33:10 +00001265 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001266
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001267 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001268 llvm::Function *fn = llvm::Function::Create(
1269 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001270 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001271
John McCall351762c2011-02-07 10:33:21 +00001272 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001273 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001274 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001275 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001276
John McCall147d0212011-02-22 22:38:33 +00001277 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001278
Adrian Prantl0f6df002013-03-29 19:20:35 +00001279 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1280 // won't delete the dbg.declare intrinsics for captured variables.
1281 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1282 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1283 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001284 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1285 getPointerAlign(),
1286 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001287 // Set the DebugLocation to empty, so the store is recognized as a
1288 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001289 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001290 Builder.CreateStore(BlockPointer, Alloca);
1291 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001292 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001293
John McCall87fe5d52010-05-20 01:18:31 +00001294 // If we have a C++ 'this' reference, go ahead and force it into
1295 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001296 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001297 Address addr =
1298 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1299 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001300 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001301 }
1302
John McCall351762c2011-02-07 10:33:21 +00001303 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001304 for (const auto &CI : blockDecl->captures()) {
1305 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001306 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1307 if (!capture.isConstant()) continue;
1308
John McCall7f416cc2015-09-08 08:05:57 +00001309 CharUnits align = getContext().getDeclAlign(variable);
1310 Address alloca =
1311 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001312
John McCall7f416cc2015-09-08 08:05:57 +00001313 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001314
John McCall7f416cc2015-09-08 08:05:57 +00001315 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001316 }
1317
John McCall113bee02012-03-10 09:33:50 +00001318 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001319 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1320 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1321 --entry_ptr;
1322
Eli Friedman2495ab02012-02-25 02:48:22 +00001323 if (IsLambdaConversionToBlock)
1324 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001325 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001326 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001327 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001328 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001329 }
Mike Stump017460a2009-10-01 22:29:41 +00001330
Mike Stump7d699112009-10-01 00:27:30 +00001331 // Remember where we were...
1332 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001333
Mike Stump7d699112009-10-01 00:27:30 +00001334 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001335 ++entry_ptr;
1336 Builder.SetInsertPoint(entry, entry_ptr);
1337
John McCall113bee02012-03-10 09:33:50 +00001338 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001339 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001340 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001341 for (const auto &CI : blockDecl->captures()) {
1342 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001343 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001344
Benjamin Kramer8c305922016-02-02 11:06:51 +00001345 if (CGM.getCodeGenOpts().getDebugInfo() >=
1346 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001347 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1348 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001349 auto addr = LocalDeclMap.find(variable)->second;
1350 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Alexey Samsonov74a38682012-05-04 07:39:27 +00001351 Builder);
1352 continue;
1353 }
John McCall351762c2011-02-07 10:33:21 +00001354
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001355 DI->EmitDeclareOfBlockDeclRefVariable(
1356 variable, BlockPointerDbgLoc, Builder, blockInfo,
1357 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001358 }
Mike Stump2e722b92009-09-30 02:43:10 +00001359 }
Manman Renab08a9a2013-01-04 18:51:35 +00001360 // Recover location if it was changed in the above loop.
1361 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001362 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001363 }
John McCall351762c2011-02-07 10:33:21 +00001364
Mike Stump7d699112009-10-01 00:27:30 +00001365 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001366 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001367 Builder.ClearInsertionPoint();
1368 else
1369 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001370
John McCall351762c2011-02-07 10:33:21 +00001371 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001372
John McCall351762c2011-02-07 10:33:21 +00001373 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001374}
Mike Stump1db7d042009-02-28 09:07:16 +00001375
John McCallf593b102013-01-22 03:56:22 +00001376/// Generate the copy-helper function for a block closure object:
1377/// static void block_copy_helper(block_t *dst, block_t *src);
1378/// The runtime will have previously initialized 'dst' by doing a
1379/// bit-copy of 'src'.
1380///
1381/// Note that this copies an entire block closure object to the heap;
1382/// it should not be confused with a 'byref copy helper', which moves
1383/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001384llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001385CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001386 ASTContext &C = getContext();
1387
1388 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001389 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1390 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001391 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001392 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1393 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001394 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001395
John McCallc56a8b32016-03-11 04:30:31 +00001396 const CGFunctionInfo &FI =
1397 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001398
John McCall351762c2011-02-07 10:33:21 +00001399 // FIXME: it would be nice if these were mergeable with things with
1400 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001401 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001402
1403 llvm::Function *Fn =
1404 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001405 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001406
1407 IdentifierInfo *II
1408 = &CGM.getContext().Idents.get("__copy_helper_block_");
1409
John McCall351762c2011-02-07 10:33:21 +00001410 FunctionDecl *FD = FunctionDecl::Create(C,
1411 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001412 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001413 SourceLocation(), II, C.VoidTy,
1414 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001415 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001416 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001417
1418 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1419
Adrian Prantl95b24e92015-02-03 20:00:54 +00001420 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001421 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001422 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001423 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001424 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001425
John McCall7f416cc2015-09-08 08:05:57 +00001426 Address src = GetAddrOfLocalVar(&srcDecl);
1427 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001428 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001429
John McCall7f416cc2015-09-08 08:05:57 +00001430 Address dst = GetAddrOfLocalVar(&dstDecl);
1431 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001432 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001433
John McCall351762c2011-02-07 10:33:21 +00001434 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001435
Aaron Ballman9371dd22014-03-14 18:34:04 +00001436 for (const auto &CI : blockDecl->captures()) {
1437 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001438 QualType type = variable->getType();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001439
John McCall351762c2011-02-07 10:33:21 +00001440 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1441 if (capture.isConstant()) continue;
1442
Aaron Ballman9371dd22014-03-14 18:34:04 +00001443 const Expr *copyExpr = CI.getCopyExpr();
John McCall31168b02011-06-15 23:02:42 +00001444 BlockFieldFlags flags;
1445
John McCalle68b8f42012-10-17 02:28:37 +00001446 bool useARCWeakCopy = false;
1447 bool useARCStrongCopy = false;
John McCall351762c2011-02-07 10:33:21 +00001448
1449 if (copyExpr) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001450 assert(!CI.isByRef());
John McCall351762c2011-02-07 10:33:21 +00001451 // don't bother computing flags
John McCall31168b02011-06-15 23:02:42 +00001452
Aaron Ballman9371dd22014-03-14 18:34:04 +00001453 } else if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001454 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001455 if (type.isObjCGCWeak())
1456 flags |= BLOCK_FIELD_IS_WEAK;
John McCall351762c2011-02-07 10:33:21 +00001457
John McCall31168b02011-06-15 23:02:42 +00001458 } else if (type->isObjCRetainableType()) {
1459 flags = BLOCK_FIELD_IS_OBJECT;
John McCalle68b8f42012-10-17 02:28:37 +00001460 bool isBlockPointer = type->isBlockPointerType();
1461 if (isBlockPointer)
John McCall31168b02011-06-15 23:02:42 +00001462 flags = BLOCK_FIELD_IS_BLOCK;
1463
1464 // Special rules for ARC captures:
John McCall460ce582015-10-22 18:38:17 +00001465 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001466
John McCall460ce582015-10-22 18:38:17 +00001467 // We need to register __weak direct captures with the runtime.
1468 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1469 useARCWeakCopy = true;
John McCall31168b02011-06-15 23:02:42 +00001470
John McCall460ce582015-10-22 18:38:17 +00001471 // We need to retain the copied value for __strong direct captures.
1472 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1473 // If it's a block pointer, we have to copy the block and
1474 // assign that to the destination pointer, so we might as
1475 // well use _Block_object_assign. Otherwise we can avoid that.
1476 if (!isBlockPointer)
1477 useARCStrongCopy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001478
1479 // Non-ARC captures of retainable pointers are strong and
1480 // therefore require a call to _Block_object_assign.
John McCall460ce582015-10-22 18:38:17 +00001481 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
John McCalle68b8f42012-10-17 02:28:37 +00001482 // fall through
John McCall460ce582015-10-22 18:38:17 +00001483
1484 // Otherwise the memcpy is fine.
1485 } else {
1486 continue;
John McCall31168b02011-06-15 23:02:42 +00001487 }
John McCall460ce582015-10-22 18:38:17 +00001488
1489 // For all other types, the memcpy is fine.
John McCall31168b02011-06-15 23:02:42 +00001490 } else {
1491 continue;
1492 }
John McCall351762c2011-02-07 10:33:21 +00001493
1494 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001495 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1496 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001497
1498 // If there's an explicit copy expression, we do that.
1499 if (copyExpr) {
John McCallad7c5c12011-02-08 08:22:06 +00001500 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCalle68b8f42012-10-17 02:28:37 +00001501 } else if (useARCWeakCopy) {
John McCall31168b02011-06-15 23:02:42 +00001502 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001503 } else {
1504 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCalle68b8f42012-10-17 02:28:37 +00001505 if (useARCStrongCopy) {
1506 // At -O0, store null into the destination field (so that the
1507 // storeStrong doesn't over-release) and then call storeStrong.
1508 // This is a workaround to not having an initStrong call.
1509 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001510 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001511 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1512 Builder.CreateStore(null, dstField);
1513 EmitARCStoreStrongCall(dstField, srcValue, true);
1514
1515 // With optimization enabled, take advantage of the fact that
1516 // the blocks runtime guarantees a memcpy of the block data, and
1517 // just emit a retain of the src field.
1518 } else {
1519 EmitARCRetainNonBlock(srcValue);
1520
1521 // We don't need this anymore, so kill it. It's not quite
1522 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001523 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001524 }
1525 } else {
1526 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001527 llvm::Value *dstAddr =
1528 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001529 llvm::Value *args[] = {
1530 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1531 };
1532
1533 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001534 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001535 const Expr *copyExpr =
1536 CGM.getContext().getBlockVarCopyInits(variable);
1537 if (copyExpr) {
1538 copyCanThrow = true; // FIXME: reuse the noexcept logic
1539 }
1540 }
1541
1542 if (copyCanThrow) {
1543 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1544 } else {
1545 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1546 }
John McCalle68b8f42012-10-17 02:28:37 +00001547 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001548 }
1549 }
1550
John McCallad7c5c12011-02-08 08:22:06 +00001551 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001552
John McCalle3dc1702011-02-15 09:22:45 +00001553 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001554}
1555
John McCallf593b102013-01-22 03:56:22 +00001556/// Generate the destroy-helper function for a block closure object:
1557/// static void block_destroy_helper(block_t *theBlock);
1558///
1559/// Note that this destroys a heap-allocated block closure object;
1560/// it should not be confused with a 'byref destroy helper', which
1561/// destroys the heap-allocated contents of an individual __block
1562/// variable.
John McCall351762c2011-02-07 10:33:21 +00001563llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001564CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001565 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001566
John McCall351762c2011-02-07 10:33:21 +00001567 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001568 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1569 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001570 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001571
John McCallc56a8b32016-03-11 04:30:31 +00001572 const CGFunctionInfo &FI =
1573 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001574
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001575 // FIXME: We'd like to put these into a mergable by content, with
1576 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001577 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001578
1579 llvm::Function *Fn =
1580 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001581 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001582
1583 IdentifierInfo *II
1584 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1585
John McCall351762c2011-02-07 10:33:21 +00001586 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001587 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001588 SourceLocation(), II, C.VoidTy,
1589 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001590 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001591
1592 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1593
Adrian Prantl49a78562013-07-24 20:34:39 +00001594 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001595 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001596 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001597 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001598
Chris Lattner2192fe52011-07-18 04:24:23 +00001599 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001600
John McCall7f416cc2015-09-08 08:05:57 +00001601 Address src = GetAddrOfLocalVar(&srcDecl);
1602 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001603 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001604
John McCall351762c2011-02-07 10:33:21 +00001605 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1606
John McCallad7c5c12011-02-08 08:22:06 +00001607 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001608
Aaron Ballman9371dd22014-03-14 18:34:04 +00001609 for (const auto &CI : blockDecl->captures()) {
1610 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001611 QualType type = variable->getType();
1612
1613 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1614 if (capture.isConstant()) continue;
1615
John McCallad7c5c12011-02-08 08:22:06 +00001616 BlockFieldFlags flags;
Craig Topper8a13c412014-05-21 05:09:00 +00001617 const CXXDestructorDecl *dtor = nullptr;
John McCall351762c2011-02-07 10:33:21 +00001618
John McCalle68b8f42012-10-17 02:28:37 +00001619 bool useARCWeakDestroy = false;
1620 bool useARCStrongDestroy = false;
John McCall31168b02011-06-15 23:02:42 +00001621
Aaron Ballman9371dd22014-03-14 18:34:04 +00001622 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001623 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001624 if (type.isObjCGCWeak())
1625 flags |= BLOCK_FIELD_IS_WEAK;
1626 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1627 if (record->hasTrivialDestructor())
1628 continue;
1629 dtor = record->getDestructor();
1630 } else if (type->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +00001631 flags = BLOCK_FIELD_IS_OBJECT;
John McCall31168b02011-06-15 23:02:42 +00001632 if (type->isBlockPointerType())
1633 flags = BLOCK_FIELD_IS_BLOCK;
John McCall351762c2011-02-07 10:33:21 +00001634
John McCall31168b02011-06-15 23:02:42 +00001635 // Special rules for ARC captures.
John McCall460ce582015-10-22 18:38:17 +00001636 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001637
John McCall460ce582015-10-22 18:38:17 +00001638 // Use objc_storeStrong for __strong direct captures; the
1639 // dynamic tools really like it when we do this.
1640 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1641 useARCStrongDestroy = true;
John McCall31168b02011-06-15 23:02:42 +00001642
John McCall460ce582015-10-22 18:38:17 +00001643 // Support __weak direct captures.
1644 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1645 useARCWeakDestroy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001646
John McCall460ce582015-10-22 18:38:17 +00001647 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1648 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1649 // fall through
1650
1651 // Otherwise, we have nothing to do.
1652 } else {
1653 continue;
John McCall31168b02011-06-15 23:02:42 +00001654 }
1655 } else {
1656 continue;
1657 }
John McCall351762c2011-02-07 10:33:21 +00001658
John McCall7f416cc2015-09-08 08:05:57 +00001659 Address srcField =
1660 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001661
1662 // If there's an explicit copy expression, we do that.
1663 if (dtor) {
John McCallad7c5c12011-02-08 08:22:06 +00001664 PushDestructorCleanup(dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001665
John McCall31168b02011-06-15 23:02:42 +00001666 // If this is a __weak capture, emit the release directly.
John McCalle68b8f42012-10-17 02:28:37 +00001667 } else if (useARCWeakDestroy) {
John McCall31168b02011-06-15 23:02:42 +00001668 EmitARCDestroyWeak(srcField);
1669
John McCalle68b8f42012-10-17 02:28:37 +00001670 // Destroy strong objects with a call if requested.
1671 } else if (useARCStrongDestroy) {
John McCallcdda29c2013-03-13 03:10:54 +00001672 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001673
John McCall351762c2011-02-07 10:33:21 +00001674 // Otherwise we call _Block_object_dispose. It wouldn't be too
1675 // hard to just emit this as a cleanup if we wanted to make sure
1676 // that things were done in reverse.
1677 } else {
1678 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001679 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001680 BuildBlockRelease(value, flags);
1681 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001682 }
1683
John McCall351762c2011-02-07 10:33:21 +00001684 cleanups.ForceCleanup();
1685
John McCallad7c5c12011-02-08 08:22:06 +00001686 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001687
John McCalle3dc1702011-02-15 09:22:45 +00001688 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001689}
1690
John McCallf9b056b2011-03-31 08:03:29 +00001691namespace {
1692
1693/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001694class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001695 BlockFieldFlags Flags;
1696
1697public:
1698 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001699 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001700
John McCall7f416cc2015-09-08 08:05:57 +00001701 void emitCopy(CodeGenFunction &CGF, Address destField,
1702 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001703 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1704
1705 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1706 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1707
1708 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1709
1710 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1711 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001712
John McCall7f416cc2015-09-08 08:05:57 +00001713 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001714 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001715 }
1716
John McCall7f416cc2015-09-08 08:05:57 +00001717 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001718 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1719 llvm::Value *value = CGF.Builder.CreateLoad(field);
1720
1721 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1722 }
1723
Craig Topper4f12f102014-03-12 06:41:41 +00001724 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001725 id.AddInteger(Flags.getBitMask());
1726 }
1727};
1728
John McCall31168b02011-06-15 23:02:42 +00001729/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001730class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001731public:
John McCall7f416cc2015-09-08 08:05:57 +00001732 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001733
John McCall7f416cc2015-09-08 08:05:57 +00001734 void emitCopy(CodeGenFunction &CGF, Address destField,
1735 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001736 CGF.EmitARCMoveWeak(destField, srcField);
1737 }
1738
John McCall7f416cc2015-09-08 08:05:57 +00001739 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001740 CGF.EmitARCDestroyWeak(field);
1741 }
1742
Craig Topper4f12f102014-03-12 06:41:41 +00001743 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001744 // 0 is distinguishable from all pointers and byref flags
1745 id.AddInteger(0);
1746 }
1747};
1748
1749/// Emits the copy/dispose helpers for an ARC __block __strong variable
1750/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001751class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001752public:
John McCall7f416cc2015-09-08 08:05:57 +00001753 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001754
John McCall7f416cc2015-09-08 08:05:57 +00001755 void emitCopy(CodeGenFunction &CGF, Address destField,
1756 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001757 // Do a "move" by copying the value and then zeroing out the old
1758 // variable.
1759
John McCall7f416cc2015-09-08 08:05:57 +00001760 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001761
John McCall31168b02011-06-15 23:02:42 +00001762 llvm::Value *null =
1763 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001764
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001765 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001766 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001767 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1768 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1769 return;
1770 }
John McCall7f416cc2015-09-08 08:05:57 +00001771 CGF.Builder.CreateStore(value, destField);
1772 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001773 }
1774
John McCall7f416cc2015-09-08 08:05:57 +00001775 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001776 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001777 }
1778
Craig Topper4f12f102014-03-12 06:41:41 +00001779 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001780 // 1 is distinguishable from all pointers and byref flags
1781 id.AddInteger(1);
1782 }
1783};
1784
John McCall3a237aa2011-11-09 03:17:26 +00001785/// Emits the copy/dispose helpers for an ARC __block __strong
1786/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001787class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001788public:
John McCall7f416cc2015-09-08 08:05:57 +00001789 ARCStrongBlockByrefHelpers(CharUnits alignment)
1790 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001791
John McCall7f416cc2015-09-08 08:05:57 +00001792 void emitCopy(CodeGenFunction &CGF, Address destField,
1793 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001794 // Do the copy with objc_retainBlock; that's all that
1795 // _Block_object_assign would do anyway, and we'd have to pass the
1796 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001797 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001798 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001799 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001800 }
1801
John McCall7f416cc2015-09-08 08:05:57 +00001802 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001803 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001804 }
1805
Craig Topper4f12f102014-03-12 06:41:41 +00001806 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001807 // 2 is distinguishable from all pointers and byref flags
1808 id.AddInteger(2);
1809 }
1810};
1811
John McCallf9b056b2011-03-31 08:03:29 +00001812/// Emits the copy/dispose helpers for a __block variable with a
1813/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00001814class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001815 QualType VarType;
1816 const Expr *CopyExpr;
1817
1818public:
1819 CXXByrefHelpers(CharUnits alignment, QualType type,
1820 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00001821 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00001822
Craig Topper8a13c412014-05-21 05:09:00 +00001823 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00001824 void emitCopy(CodeGenFunction &CGF, Address destField,
1825 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001826 if (!CopyExpr) return;
1827 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1828 }
1829
John McCall7f416cc2015-09-08 08:05:57 +00001830 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001831 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1832 CGF.PushDestructorCleanup(VarType, field);
1833 CGF.PopCleanupBlocks(cleanupDepth);
1834 }
1835
Craig Topper4f12f102014-03-12 06:41:41 +00001836 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001837 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1838 }
1839};
1840} // end anonymous namespace
1841
1842static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00001843generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1844 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001845 ASTContext &Context = CGF.getContext();
1846
1847 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001848
John McCalla738c252011-03-09 04:27:21 +00001849 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001850 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001851 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001852 args.push_back(&dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00001853
Craig Topper8a13c412014-05-21 05:09:00 +00001854 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001855 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001856 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001857
John McCallc56a8b32016-03-11 04:30:31 +00001858 const CGFunctionInfo &FI =
1859 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001860
John McCall7f416cc2015-09-08 08:05:57 +00001861 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001862
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001863 // FIXME: We'd like to put these into a mergable by content, with
1864 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001865 llvm::Function *Fn =
1866 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00001867 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001868
1869 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001870 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001871
John McCallf9b056b2011-03-31 08:03:29 +00001872 FunctionDecl *FD = FunctionDecl::Create(Context,
1873 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001874 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001875 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001876 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001877 false, false);
John McCall31168b02011-06-15 23:02:42 +00001878
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001879 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1880
Adrian Prantl22e66b42014-04-11 01:13:04 +00001881 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00001882
John McCall7f416cc2015-09-08 08:05:57 +00001883 if (generator.needsCopy()) {
1884 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00001885
John McCallf9b056b2011-03-31 08:03:29 +00001886 // dst->x
John McCall7f416cc2015-09-08 08:05:57 +00001887 Address destField = CGF.GetAddrOfLocalVar(&dst);
1888 destField = Address(CGF.Builder.CreateLoad(destField),
1889 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001890 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001891 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1892 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001893
John McCallf9b056b2011-03-31 08:03:29 +00001894 // src->x
John McCall7f416cc2015-09-08 08:05:57 +00001895 Address srcField = CGF.GetAddrOfLocalVar(&src);
1896 srcField = Address(CGF.Builder.CreateLoad(srcField),
1897 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001898 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001899 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1900 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00001901
John McCall7f416cc2015-09-08 08:05:57 +00001902 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00001903 }
1904
1905 CGF.FinishFunction();
1906
1907 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001908}
1909
John McCallf9b056b2011-03-31 08:03:29 +00001910/// Build the copy helper for a __block variable.
1911static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001912 const BlockByrefInfo &byrefInfo,
1913 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001914 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001915 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001916}
1917
1918/// Generate code for a __block variable's dispose helper.
1919static llvm::Constant *
1920generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001921 const BlockByrefInfo &byrefInfo,
1922 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001923 ASTContext &Context = CGF.getContext();
1924 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001925
John McCalla738c252011-03-09 04:27:21 +00001926 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001927 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001928 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001929 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001930
John McCallc56a8b32016-03-11 04:30:31 +00001931 const CGFunctionInfo &FI =
1932 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001933
John McCall7f416cc2015-09-08 08:05:57 +00001934 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001935
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001936 // FIXME: We'd like to put these into a mergable by content, with
1937 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001938 llvm::Function *Fn =
1939 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00001940 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00001941 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001942
1943 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001944 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001945
John McCallf9b056b2011-03-31 08:03:29 +00001946 FunctionDecl *FD = FunctionDecl::Create(Context,
1947 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001948 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001949 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001950 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001951 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001952
1953 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1954
Adrian Prantl22e66b42014-04-11 01:13:04 +00001955 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00001956
John McCall7f416cc2015-09-08 08:05:57 +00001957 if (generator.needsDispose()) {
1958 Address addr = CGF.GetAddrOfLocalVar(&src);
1959 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1960 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1961 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1962 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00001963
John McCall7f416cc2015-09-08 08:05:57 +00001964 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00001965 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001966
John McCallf9b056b2011-03-31 08:03:29 +00001967 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00001968
John McCallf9b056b2011-03-31 08:03:29 +00001969 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001970}
1971
John McCallf9b056b2011-03-31 08:03:29 +00001972/// Build the dispose helper for a __block variable.
1973static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001974 const BlockByrefInfo &byrefInfo,
1975 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001976 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001977 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001978}
1979
John McCallf593b102013-01-22 03:56:22 +00001980/// Lazily build the copy and dispose helpers for a __block variable
1981/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00001982template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00001983static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1984 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001985 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00001986 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00001987
1988 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00001989 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00001990 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1991 if (node) return static_cast<T*>(node);
1992
John McCall7f416cc2015-09-08 08:05:57 +00001993 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1994 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001995
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00001996 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00001997 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1998 return copy;
1999}
2000
John McCallf593b102013-01-22 03:56:22 +00002001/// Build the copy and dispose helpers for the given __block variable
2002/// emission. Places the helpers in the global cache. Returns null
2003/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00002004BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00002005CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00002006 const AutoVarEmission &emission) {
2007 const VarDecl &var = *emission.Variable;
2008 QualType type = var.getType();
2009
John McCall7f416cc2015-09-08 08:05:57 +00002010 auto &byrefInfo = getBlockByrefInfo(&var);
2011
2012 // The alignment we care about for the purposes of uniquing byref
2013 // helpers is the alignment of the actual byref value field.
2014 CharUnits valueAlignment =
2015 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00002016
John McCallf9b056b2011-03-31 08:03:29 +00002017 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2018 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00002019 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002020
David Blaikie92551612015-08-13 23:53:09 +00002021 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00002022 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00002023 }
2024
John McCall31168b02011-06-15 23:02:42 +00002025 // Otherwise, if we don't have a retainable type, there's nothing to do.
2026 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00002027 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002028
2029 Qualifiers qs = type.getQualifiers();
2030
2031 // If we have lifetime, that dominates.
2032 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00002033 switch (lifetime) {
2034 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2035
2036 // These are just bits as far as the runtime is concerned.
2037 case Qualifiers::OCL_ExplicitNone:
2038 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00002039 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002040
2041 // Tell the runtime that this is ARC __weak, called by the
2042 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002043 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002044 return ::buildByrefHelpers(CGM, byrefInfo,
2045 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002046
2047 // ARC __strong __block variables need to be retained.
2048 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002049 // Block pointers need to be copied, and there's no direct
2050 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002051 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002052 return ::buildByrefHelpers(CGM, byrefInfo,
2053 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002054
2055 // Otherwise, we transfer ownership of the retain from the stack
2056 // to the heap.
2057 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002058 return ::buildByrefHelpers(CGM, byrefInfo,
2059 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002060 }
2061 }
2062 llvm_unreachable("fell out of lifetime switch!");
2063 }
2064
John McCallf9b056b2011-03-31 08:03:29 +00002065 BlockFieldFlags flags;
2066 if (type->isBlockPointerType()) {
2067 flags |= BLOCK_FIELD_IS_BLOCK;
2068 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2069 type->isObjCObjectPointerType()) {
2070 flags |= BLOCK_FIELD_IS_OBJECT;
2071 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002072 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002073 }
2074
2075 if (type.isObjCGCWeak())
2076 flags |= BLOCK_FIELD_IS_WEAK;
2077
John McCall7f416cc2015-09-08 08:05:57 +00002078 return ::buildByrefHelpers(CGM, byrefInfo,
2079 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002080}
2081
John McCall7f416cc2015-09-08 08:05:57 +00002082Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2083 const VarDecl *var,
2084 bool followForward) {
2085 auto &info = getBlockByrefInfo(var);
2086 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002087}
2088
John McCall7f416cc2015-09-08 08:05:57 +00002089Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2090 const BlockByrefInfo &info,
2091 bool followForward,
2092 const llvm::Twine &name) {
2093 // Chase the forwarding address if requested.
2094 if (followForward) {
2095 Address forwardingAddr =
2096 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2097 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2098 }
2099
2100 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2101 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002102}
2103
John McCall7f416cc2015-09-08 08:05:57 +00002104/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002105/// into:
2106///
2107/// struct {
2108/// void *__isa;
2109/// void *__forwarding;
2110/// int32_t __flags;
2111/// int32_t __size;
2112/// void *__copy_helper; // only if needed
2113/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002114/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002115/// char padding[X]; // only if needed
2116/// T x;
2117/// } x
2118///
John McCall7f416cc2015-09-08 08:05:57 +00002119const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2120 auto it = BlockByrefInfos.find(D);
2121 if (it != BlockByrefInfos.end())
2122 return it->second;
John McCall73064872011-03-31 01:59:53 +00002123
John McCall7f416cc2015-09-08 08:05:57 +00002124 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002125 llvm::StructType::create(getLLVMContext(),
2126 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002127
John McCall7f416cc2015-09-08 08:05:57 +00002128 QualType Ty = D->getType();
2129
2130 CharUnits size;
2131 SmallVector<llvm::Type *, 8> types;
2132
John McCall73064872011-03-31 01:59:53 +00002133 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002134 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002135 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002136
2137 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002138 types.push_back(llvm::PointerType::getUnqual(byrefType));
2139 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002140
2141 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002142 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002143 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002144
2145 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002146 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002147 size += CharUnits::fromQuantity(4);
2148
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002149 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002150 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2151 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002152 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002153 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002154 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002155
2156 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002157 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002158 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002159 }
John McCall7f416cc2015-09-08 08:05:57 +00002160
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002161 bool HasByrefExtendedLayout = false;
2162 Qualifiers::ObjCLifetime Lifetime;
2163 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002164 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002165 /// void *__byref_variable_layout;
2166 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002167 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002168 }
2169
2170 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002171 llvm::Type *varTy = ConvertTypeForMem(Ty);
2172
2173 bool packed = false;
2174 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002175 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002176
2177 // We may have to insert padding.
2178 if (varOffset != size) {
2179 llvm::Type *paddingTy =
2180 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2181
2182 types.push_back(paddingTy);
2183 size = varOffset;
2184
2185 // Conversely, we might have to prevent LLVM from inserting padding.
2186 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2187 > varAlign.getQuantity()) {
2188 packed = true;
2189 }
2190 types.push_back(varTy);
2191
2192 byrefType->setBody(types, packed);
2193
2194 BlockByrefInfo info;
2195 info.Type = byrefType;
2196 info.FieldIndex = types.size() - 1;
2197 info.FieldOffset = varOffset;
2198 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2199
2200 auto pair = BlockByrefInfos.insert({D, info});
2201 assert(pair.second && "info was inserted recursively?");
2202 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002203}
2204
2205/// Initialize the structural components of a __block variable, i.e.
2206/// everything but the actual object.
2207void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002208 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002209 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002210
John McCallf9b056b2011-03-31 08:03:29 +00002211 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002212 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002213 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2214
2215 unsigned nextHeaderIndex = 0;
2216 CharUnits nextHeaderOffset;
2217 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2218 const Twine &name) {
2219 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2220 nextHeaderOffset, name);
2221 Builder.CreateStore(value, fieldAddr);
2222
2223 nextHeaderIndex++;
2224 nextHeaderOffset += fieldSize;
2225 };
John McCallf9b056b2011-03-31 08:03:29 +00002226
2227 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002228 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002229
2230 const VarDecl &D = *emission.Variable;
2231 QualType type = D.getType();
2232
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002233 bool HasByrefExtendedLayout;
2234 Qualifiers::ObjCLifetime ByrefLifetime;
2235 bool ByRefHasLifetime =
2236 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002237
John McCallf9b056b2011-03-31 08:03:29 +00002238 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002239
2240 // Initialize the 'isa', which is just 0 or 1.
2241 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002242 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002243 isa = 1;
2244 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002245 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002246
2247 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002248 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002249
2250 // Blocks ABI:
2251 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002252 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002253 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002254 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2255 if (ByRefHasLifetime) {
2256 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2257 else switch (ByrefLifetime) {
2258 case Qualifiers::OCL_Strong:
2259 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2260 break;
2261 case Qualifiers::OCL_Weak:
2262 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2263 break;
2264 case Qualifiers::OCL_ExplicitNone:
2265 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2266 break;
2267 case Qualifiers::OCL_None:
2268 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2269 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2270 break;
2271 default:
2272 break;
2273 }
2274 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2275 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2276 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2277 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2278 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2279 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2280 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2281 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2282 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2283 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2284 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2285 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2286 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2287 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2288 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2289 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2290 }
2291 printf("\n");
2292 }
2293 }
John McCall7f416cc2015-09-08 08:05:57 +00002294 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2295 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002296
John McCallf9b056b2011-03-31 08:03:29 +00002297 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2298 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002299 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002300
John McCallf9b056b2011-03-31 08:03:29 +00002301 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002302 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2303 "byref.copyHelper");
2304 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2305 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002306 }
John McCall7f416cc2015-09-08 08:05:57 +00002307
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002308 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002309 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2310 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002311 }
John McCall73064872011-03-31 01:59:53 +00002312}
2313
John McCallad7c5c12011-02-08 08:22:06 +00002314void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002315 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002316 llvm::Value *args[] = {
2317 Builder.CreateBitCast(V, Int8PtrTy),
2318 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2319 };
2320 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002321}
John McCall73064872011-03-31 01:59:53 +00002322
2323namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002324 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002325 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002326 llvm::Value *Addr;
2327 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2328
Craig Topper4f12f102014-03-12 06:41:41 +00002329 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002330 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002331 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2332 }
2333 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002334} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002335
2336/// Enter a cleanup to destroy a __block variable. Note that this
2337/// cleanup should be a no-op if the variable hasn't left the stack
2338/// yet; if a cleanup is required for the variable itself, that needs
2339/// to be done externally.
2340void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2341 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002342 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002343 return;
2344
John McCall7f416cc2015-09-08 08:05:57 +00002345 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2346 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002347}
John McCall7959fee2011-09-09 20:41:01 +00002348
2349/// Adjust the declaration of something from the blocks API.
2350static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2351 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002352 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002353
2354 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2355 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2356 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2357 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2358
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002359 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2360 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2361 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002362
2363 const NamedDecl *ND = nullptr;
2364 for (const auto &Result : DC->lookup(&II))
2365 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2366 (ND = dyn_cast<VarDecl>(Result)))
2367 break;
2368
2369 // TODO: support static blocks runtime
2370 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2371 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2372 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2373 } else {
2374 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2375 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2376 }
2377 }
2378
2379 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2380 return;
2381
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002382 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002383 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2384}
2385
2386llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2387 if (BlockObjectDispose)
2388 return BlockObjectDispose;
2389
2390 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2391 llvm::FunctionType *fty
2392 = llvm::FunctionType::get(VoidTy, args, false);
2393 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2394 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2395 return BlockObjectDispose;
2396}
2397
2398llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2399 if (BlockObjectAssign)
2400 return BlockObjectAssign;
2401
2402 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2403 llvm::FunctionType *fty
2404 = llvm::FunctionType::get(VoidTy, args, false);
2405 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2406 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2407 return BlockObjectAssign;
2408}
2409
2410llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2411 if (NSConcreteGlobalBlock)
2412 return NSConcreteGlobalBlock;
2413
2414 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002415 Int8PtrTy->getPointerTo(),
2416 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002417 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2418 return NSConcreteGlobalBlock;
2419}
2420
2421llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2422 if (NSConcreteStackBlock)
2423 return NSConcreteStackBlock;
2424
2425 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002426 Int8PtrTy->getPointerTo(),
2427 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002428 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002429 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002430}