blob: 615b7823504142f4713f1f6e394bb6d6742aad07 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson2437cbf2009-02-12 00:39:25 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit blocks.
10//
11//===----------------------------------------------------------------------===//
12
John McCallad7c5c12011-02-08 08:22:06 +000013#include "CGBlocks.h"
Akira Hatanaka9978da32018-08-10 15:09:24 +000014#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000017#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000020#include "ConstantEmitter.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000021#include "TargetInfo.h"
Reid Kleckner98031782019-12-09 16:11:56 -080022#include "clang/AST/Attr.h"
Mike Stump692c6e32009-03-20 21:53:12 +000023#include "clang/AST/DeclObjC.h"
Yaxun Liu10712d92017-10-04 20:32:17 +000024#include "clang/CodeGen/ConstantInitBuilder.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000025#include "llvm/ADT/SmallSet.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Module.h"
Akira Hatanaka9978da32018-08-10 15:09:24 +000028#include "llvm/Support/ScopedPrinter.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000029#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000030#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000031
Anders Carlsson2437cbf2009-02-12 00:39:25 +000032using namespace clang;
33using namespace CodeGen;
34
John McCall08ef4662011-11-10 08:15:53 +000035CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
36 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000037 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
Akira Hatanaka9978da32018-08-10 15:09:24 +000038 CapturesNonExternalType(false), LocalAddress(Address::invalid()),
Akira Hatanakac9a52de2020-06-03 16:41:50 -070039 StructureType(nullptr), Block(block) {
Craig Topper8a13c412014-05-21 05:09:00 +000040
John McCall08ef4662011-11-10 08:15:53 +000041 // Skip asm prefix, if any. 'name' is usually taken directly from
42 // the mangled name of the enclosing function.
43 if (!name.empty() && name[0] == '\01')
44 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000045}
46
John McCallf9b056b2011-03-31 08:03:29 +000047// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000048BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000049
John McCall351762c2011-02-07 10:33:21 +000050/// Build the given block as a global block.
51static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
52 const CGBlockInfo &blockInfo,
53 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000054
John McCall351762c2011-02-07 10:33:21 +000055/// Build the helper function to copy a block.
56static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
57 const CGBlockInfo &blockInfo) {
58 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
59}
60
Alp Tokerf6a24ce2013-12-05 16:25:25 +000061/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000062static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
63 const CGBlockInfo &blockInfo) {
64 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
65}
66
Akira Hatanaka2ec36f02018-08-17 15:46:07 +000067namespace {
68
69/// Represents a type of copy/destroy operation that should be performed for an
70/// entity that's captured by a block.
71enum class BlockCaptureEntityKind {
72 CXXRecord, // Copy or destroy
73 ARCWeak,
74 ARCStrong,
75 NonTrivialCStruct,
76 BlockObject, // Assign or release
77 None
78};
79
80/// Represents a captured entity that requires extra operations in order for
81/// this entity to be copied or destroyed correctly.
82struct BlockCaptureManagedEntity {
83 BlockCaptureEntityKind CopyKind, DisposeKind;
84 BlockFieldFlags CopyFlags, DisposeFlags;
85 const BlockDecl::Capture *CI;
86 const CGBlockInfo::Capture *Capture;
87
88 BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
89 BlockCaptureEntityKind DisposeType,
90 BlockFieldFlags CopyFlags,
91 BlockFieldFlags DisposeFlags,
92 const BlockDecl::Capture &CI,
93 const CGBlockInfo::Capture &Capture)
94 : CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
95 DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
96
97 bool operator<(const BlockCaptureManagedEntity &Other) const {
98 return Capture->getOffset() < Other.Capture->getOffset();
99 }
100};
101
102enum class CaptureStrKind {
103 // String for the copy helper.
104 CopyHelper,
105 // String for the dispose helper.
106 DisposeHelper,
107 // Merge the strings for the copy helper and dispose helper.
108 Merged
109};
110
111} // end anonymous namespace
112
113static void findBlockCapturedManagedEntities(
114 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
115 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures);
116
117static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
118 CaptureStrKind StrKind,
119 CharUnits BlockAlignment,
120 CodeGenModule &CGM);
121
122static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
123 CodeGenModule &CGM) {
124 std::string Name = "__block_descriptor_";
125 Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
126
127 if (BlockInfo.needsCopyDisposeHelpers()) {
128 if (CGM.getLangOpts().Exceptions)
129 Name += "e";
130 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
131 Name += "a";
132 Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
133
134 SmallVector<BlockCaptureManagedEntity, 4> ManagedCaptures;
135 findBlockCapturedManagedEntities(BlockInfo, CGM.getContext().getLangOpts(),
136 ManagedCaptures);
137
138 for (const BlockCaptureManagedEntity &E : ManagedCaptures) {
139 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
140
141 if (E.CopyKind == E.DisposeKind) {
142 // If CopyKind and DisposeKind are the same, merge the capture
143 // information.
144 assert(E.CopyKind != BlockCaptureEntityKind::None &&
145 "shouldn't see BlockCaptureManagedEntity that is None");
146 Name += getBlockCaptureStr(E, CaptureStrKind::Merged,
147 BlockInfo.BlockAlign, CGM);
148 } else {
149 // If CopyKind and DisposeKind are not the same, which can happen when
150 // either Kind is None or the captured object is a __strong block,
151 // concatenate the copy and dispose strings.
152 Name += getBlockCaptureStr(E, CaptureStrKind::CopyHelper,
153 BlockInfo.BlockAlign, CGM);
154 Name += getBlockCaptureStr(E, CaptureStrKind::DisposeHelper,
155 BlockInfo.BlockAlign, CGM);
156 }
157 }
158 Name += "_";
159 }
160
161 std::string TypeAtEncoding =
162 CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
Akira Hatanakac7c75742018-12-29 17:28:30 +0000163 /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
164 /// a separator between symbol name and symbol version.
165 std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000166 Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
167 Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
168 return Name;
169}
170
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +0000171/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
172/// buildBlockDescriptor is accessed from 5th field of the Block_literal
173/// meta-data and contains stationary information about the block literal.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000174/// Its definition will have 4 (or optionally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +0000175/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +0000176/// struct Block_descriptor {
177/// unsigned long reserved;
178/// unsigned long size; // size of Block_literal metadata in bytes.
179/// void *copy_func_helper_decl; // optional copy helper.
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000180/// void *destroy_func_decl; // optional destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +0000181/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +0000182/// void *block_layout_info; // encoding of captured block variables.
183/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +0000184/// \endcode
John McCall351762c2011-02-07 10:33:21 +0000185static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
186 const CGBlockInfo &blockInfo) {
187 ASTContext &C = CGM.getContext();
188
John McCall6c9f1fdb2016-11-19 08:17:24 +0000189 llvm::IntegerType *ulong =
190 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
191 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +0000192 if (CGM.getLangOpts().OpenCL)
Fangrui Song6907ce22018-07-30 19:24:48 +0000193 i8p =
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +0000194 llvm::Type::getInt8PtrTy(
195 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
196 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000197 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +0000198
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000199 std::string descName;
200
201 // If an equivalent block descriptor global variable exists, return it.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000202 if (C.getLangOpts().ObjC &&
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000203 CGM.getLangOpts().getGC() == LangOptions::NonGC) {
204 descName = getBlockDescriptorName(blockInfo, CGM);
205 if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
206 return llvm::ConstantExpr::getBitCast(desc,
207 CGM.getBlockDescriptorType());
208 }
209
210 // If there isn't an equivalent block descriptor global variable, create a new
211 // one.
John McCall23c9dc62016-11-28 22:18:27 +0000212 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000213 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +0000214
215 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +0000216 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +0000217
218 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +0000219 // FIXME: What is the right way to say this doesn't fit? We should give
220 // a user diagnostic in that case. Better fix would be to change the
221 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000222 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000223
John McCall351762c2011-02-07 10:33:21 +0000224 // Optional copy/dispose helpers.
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000225 bool hasInternalHelper = false;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000226 if (blockInfo.needsCopyDisposeHelpers()) {
Mike Stump85284ba2009-02-13 16:19:19 +0000227 // copy_func_helper_decl
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000228 llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
229 elements.add(copyHelper);
Mike Stump85284ba2009-02-13 16:19:19 +0000230
231 // destroy_func_decl
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000232 llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
233 elements.add(disposeHelper);
234
235 if (cast<llvm::Function>(copyHelper->getOperand(0))->hasInternalLinkage() ||
236 cast<llvm::Function>(disposeHelper->getOperand(0))
237 ->hasInternalLinkage())
238 hasInternalHelper = true;
Mike Stump85284ba2009-02-13 16:19:19 +0000239 }
240
John McCall351762c2011-02-07 10:33:21 +0000241 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
242 std::string typeAtEncoding =
243 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000244 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000245 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Fangrui Song6907ce22018-07-30 19:24:48 +0000246
John McCall351762c2011-02-07 10:33:21 +0000247 // GC layout.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000248 if (C.getLangOpts().ObjC) {
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000249 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000250 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000251 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000252 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000253 }
John McCall351762c2011-02-07 10:33:21 +0000254 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000255 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000256
Joey Goulyddbda402016-08-10 15:57:02 +0000257 unsigned AddrSpace = 0;
258 if (C.getLangOpts().OpenCL)
259 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000260
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000261 llvm::GlobalValue::LinkageTypes linkage;
262 if (descName.empty()) {
263 linkage = llvm::GlobalValue::InternalLinkage;
264 descName = "__block_descriptor_tmp";
265 } else if (hasInternalHelper) {
266 // If either the copy helper or the dispose helper has internal linkage,
267 // the block descriptor must have internal linkage too.
268 linkage = llvm::GlobalValue::InternalLinkage;
269 } else {
270 linkage = llvm::GlobalValue::LinkOnceODRLinkage;
271 }
272
John McCall351762c2011-02-07 10:33:21 +0000273 llvm::GlobalVariable *global =
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000274 elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
275 /*constant*/ true, linkage, AddrSpace);
276
277 if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
David Chisnall17d42952019-03-31 11:22:26 +0000278 if (CGM.supportsCOMDAT())
279 global->setComdat(CGM.getModule().getOrInsertComdat(descName));
Akira Hatanaka2ec36f02018-08-17 15:46:07 +0000280 global->setVisibility(llvm::GlobalValue::HiddenVisibility);
281 global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
282 }
Mike Stump85284ba2009-02-13 16:19:19 +0000283
John McCall351762c2011-02-07 10:33:21 +0000284 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000285}
286
John McCall351762c2011-02-07 10:33:21 +0000287/*
288 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000289
John McCall351762c2011-02-07 10:33:21 +0000290 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
291 struct Block_literal {
292 /// Initialized to one of:
293 /// extern void *_NSConcreteStackBlock[];
294 /// extern void *_NSConcreteGlobalBlock[];
295 ///
296 /// In theory, we could start one off malloc'ed by setting
297 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
298 /// this isa:
299 /// extern void *_NSConcreteMallocBlock[];
300 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000301
John McCall351762c2011-02-07 10:33:21 +0000302 /// These are the flags (with corresponding bit number) that the
303 /// compiler is actually supposed to know about.
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000304 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
John McCall351762c2011-02-07 10:33:21 +0000305 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
306 /// descriptor provides copy and dispose helper functions
307 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
308 /// object with a nontrivial destructor or copy constructor
309 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
310 /// as global memory
311 /// 29. BLOCK_USE_STRET - indicates that the block function
312 /// uses stret, which objc_msgSend needs to know about
313 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
314 /// @encoded signature string
315 /// And we're not supposed to manipulate these:
316 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
317 /// to malloc'ed memory
318 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
319 /// to GC-allocated memory
320 /// Additionally, the bottom 16 bits are a reference count which
321 /// should be zero on the stack.
322 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000323
John McCall351762c2011-02-07 10:33:21 +0000324 /// Reserved; should be zero-initialized.
325 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000326
John McCall351762c2011-02-07 10:33:21 +0000327 /// Function pointer generated from block literal.
328 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000329
John McCall351762c2011-02-07 10:33:21 +0000330 /// Block description metadata generated from block literal.
331 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000332
John McCall351762c2011-02-07 10:33:21 +0000333 /// Captured values follow.
334 _CapturesTypes captures...;
335 };
336 */
David Chisnall950a9512009-11-17 19:33:30 +0000337
John McCall351762c2011-02-07 10:33:21 +0000338namespace {
339 /// A chunk of data that we actually have to capture in the block.
340 struct BlockLayoutChunk {
341 CharUnits Alignment;
342 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000343 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000344 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000345 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000346 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000347
John McCall351762c2011-02-07 10:33:21 +0000348 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000349 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000350 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000351 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000352 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000353 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000354
John McCall351762c2011-02-07 10:33:21 +0000355 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000356 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
357 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000358 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000359 info.CXXThisOffset = offset;
360 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000361 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
362 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000363 }
John McCall87fe5d52010-05-20 01:18:31 +0000364 }
John McCall351762c2011-02-07 10:33:21 +0000365 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000366
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000367 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
368 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000369 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000370 if (left.Alignment != right.Alignment)
371 return left.Alignment > right.Alignment;
372
373 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000374 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000375 return 1;
376 if (chunk.Lifetime == Qualifiers::OCL_Strong)
377 return 0;
378 if (chunk.Lifetime == Qualifiers::OCL_Weak)
379 return 2;
380 return 3;
381 };
382
383 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000384 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000385} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000386
John McCallb0a3ecb2011-02-08 03:07:00 +0000387/// Determines if the given type is safe for constant capture in C++.
388static bool isSafeForCXXConstantCapture(QualType type) {
389 const RecordType *recordType =
390 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
391
392 // Only records can be unsafe.
393 if (!recordType) return true;
394
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000395 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000396
397 // Maintain semantics for classes with non-trivial dtors or copy ctors.
398 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000399 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000400
401 // Otherwise, we just have to make sure there aren't any mutable
402 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000403 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000404}
405
John McCall351762c2011-02-07 10:33:21 +0000406/// It is illegal to modify a const object after initialization.
407/// Therefore, if a const object has a constant initializer, we don't
408/// actually need to keep storage for it in the block; we'll just
409/// rematerialize it at the start of the block function. This is
410/// acceptable because we make no promises about address stability of
411/// captured variables.
412static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000413 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000414 const VarDecl *var) {
Simon Pilgrim2c518802017-03-30 14:13:19 +0000415 // Return if this is a function parameter. We shouldn't try to
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000416 // rematerialize default arguments of function parameters.
417 if (isa<ParmVarDecl>(var))
418 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000419
John McCall351762c2011-02-07 10:33:21 +0000420 QualType type = var->getType();
421
422 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000423 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000424
John McCallb0a3ecb2011-02-08 03:07:00 +0000425 // Furthermore, in C++ we have to worry about mutable fields:
426 // C++ [dcl.type.cv]p4:
427 // Except that any class member declared mutable can be
428 // modified, any attempt to modify a const object during its
429 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000430 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000431 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000432
433 // If the variable doesn't have any initializer (shouldn't this be
434 // invalid?), it's not clear what we should do. Maybe capture as
435 // zero?
436 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000437 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000438
John McCallde0fe072017-08-15 21:42:52 +0000439 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
John McCall351762c2011-02-07 10:33:21 +0000440}
441
442/// Get the low bit of a nonzero character count. This is the
443/// alignment of the nth byte if the 0th byte is universally aligned.
444static CharUnits getLowBit(CharUnits v) {
445 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
446}
447
448static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000449 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall351762c2011-02-07 10:33:21 +0000450
451 assert(elementTypes.empty());
Yaxun Liu10712d92017-10-04 20:32:17 +0000452 if (CGM.getLangOpts().OpenCL) {
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000453 // The header is basically 'struct { int; int; generic void *;
Yaxun Liu10712d92017-10-04 20:32:17 +0000454 // custom_fields; }'. Assert that struct is packed.
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000455 auto GenericAS =
456 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
457 auto GenPtrAlign =
458 CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
459 auto GenPtrSize =
460 CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
461 assert(CGM.getIntSize() <= GenPtrSize);
462 assert(CGM.getIntAlign() <= GenPtrAlign);
463 assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
Yaxun Liu10712d92017-10-04 20:32:17 +0000464 elementTypes.push_back(CGM.IntTy); /* total size */
465 elementTypes.push_back(CGM.IntTy); /* align */
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000466 elementTypes.push_back(
467 CGM.getOpenCLRuntime()
468 .getGenericVoidPointerType()); /* invoke function */
469 unsigned Offset =
470 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
471 unsigned BlockAlign = GenPtrAlign.getQuantity();
Yaxun Liu10712d92017-10-04 20:32:17 +0000472 if (auto *Helper =
473 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
474 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
475 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
476 // If necessary, add padding fields to the custom fields.
477 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
478 if (BlockAlign < Align)
479 BlockAlign = Align;
480 assert(Offset % Align == 0);
481 Offset += CGM.getDataLayout().getTypeAllocSize(I);
482 elementTypes.push_back(I);
483 }
484 }
485 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
486 info.BlockSize = CharUnits::fromQuantity(Offset);
487 } else {
488 // The header is basically 'struct { void *; int; int; void *; void *; }'.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000489 // Assert that the struct is packed.
Yaxun Liu10712d92017-10-04 20:32:17 +0000490 assert(CGM.getIntSize() <= CGM.getPointerSize());
491 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
492 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
493 info.BlockAlign = CGM.getPointerAlign();
494 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
495 elementTypes.push_back(CGM.VoidPtrTy);
496 elementTypes.push_back(CGM.IntTy);
497 elementTypes.push_back(CGM.IntTy);
498 elementTypes.push_back(CGM.VoidPtrTy);
499 elementTypes.push_back(CGM.getBlockDescriptorType());
500 }
John McCall351762c2011-02-07 10:33:21 +0000501}
502
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000503static QualType getCaptureFieldType(const CodeGenFunction &CGF,
504 const BlockDecl::Capture &CI) {
505 const VarDecl *VD = CI.getVariable();
506
507 // If the variable is captured by an enclosing block or lambda expression,
508 // use the type of the capture field.
509 if (CGF.BlockInfo && CI.isNested())
510 return CGF.BlockInfo->getCapture(VD).fieldType();
511 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
512 return FD->getType();
Akira Hatanaka8e57b072018-10-01 21:51:28 +0000513 // If the captured variable is a non-escaping __block variable, the field
514 // type is the reference type. If the variable is a __block variable that
515 // already has a reference type, the field type is the variable's type.
516 return VD->isNonEscapingByref() ?
517 CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000518}
519
John McCall351762c2011-02-07 10:33:21 +0000520/// Compute the layout of the given block. Attempts to lay the block
521/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000522static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
523 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000524 ASTContext &C = CGM.getContext();
525 const BlockDecl *block = info.getBlockDecl();
526
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000527 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000528 initializeForBlockHeader(CGM, info, elementTypes);
Yaxun Liu10712d92017-10-04 20:32:17 +0000529 bool hasNonConstantCustomFields = false;
530 if (auto *OpenCLHelper =
531 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
532 hasNonConstantCustomFields =
533 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
534 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
John McCall351762c2011-02-07 10:33:21 +0000535 info.StructureType =
536 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
537 info.CanBeGlobal = true;
538 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000539 }
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000540 else if (C.getLangOpts().ObjC &&
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000541 CGM.getLangOpts().getGC() == LangOptions::NonGC)
542 info.HasCapturedVariableLayout = true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000543
John McCall351762c2011-02-07 10:33:21 +0000544 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000545 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000546 layout.reserve(block->capturesCXXThis() +
547 (block->capture_end() - block->capture_begin()));
548
549 CharUnits maxFieldAlign;
550
551 // First, 'this'.
552 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000553 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
554 "Can't capture 'this' outside a method");
Brian Gesiak5488ab42019-01-11 01:54:53 +0000555 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
John McCall351762c2011-02-07 10:33:21 +0000556
John McCall7f416cc2015-09-08 08:05:57 +0000557 // Theoretically, this could be in a different address space, so
558 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000559 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000560 std::pair<CharUnits,CharUnits> tinfo
561 = CGM.getContext().getTypeInfoInChars(thisType);
562 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
563
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000564 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
565 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000566 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000567 }
568
569 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000570 for (const auto &CI : block->captures()) {
571 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000572
Akira Hatanaka8e57b072018-10-01 21:51:28 +0000573 if (CI.isEscapingByref()) {
John McCall351762c2011-02-07 10:33:21 +0000574 // We have to copy/dispose of the __block reference.
575 info.NeedsCopyDispose = true;
576
John McCall351762c2011-02-07 10:33:21 +0000577 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000578 CharUnits align = CGM.getPointerAlign();
579 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000580
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000581 // Since a __block variable cannot be captured by lambdas, its type and
582 // the capture field type should always match.
583 assert(getCaptureFieldType(*CGF, CI) == variable->getType() &&
584 "capture type differs from the variable type");
John McCall7f416cc2015-09-08 08:05:57 +0000585 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
586 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000587 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000588 continue;
589 }
590
591 // Otherwise, build a layout chunk with the size and alignment of
592 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000593 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000594 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
595 continue;
596 }
597
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000598 QualType VT = getCaptureFieldType(*CGF, CI);
599
John McCall31168b02011-06-15 23:02:42 +0000600 // If we have a lifetime qualifier, honor it for capture purposes.
601 // That includes *not* copying it if it's __unsafe_unretained.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000602 Qualifiers::ObjCLifetime lifetime = VT.getObjCLifetime();
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000603 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000604 switch (lifetime) {
605 case Qualifiers::OCL_None: llvm_unreachable("impossible");
606 case Qualifiers::OCL_ExplicitNone:
607 case Qualifiers::OCL_Autoreleasing:
608 break;
John McCall351762c2011-02-07 10:33:21 +0000609
John McCall31168b02011-06-15 23:02:42 +0000610 case Qualifiers::OCL_Strong:
611 case Qualifiers::OCL_Weak:
612 info.NeedsCopyDispose = true;
613 }
614
615 // Block pointers require copy/dispose. So do Objective-C pointers.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000616 } else if (VT->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000617 // But honor the inert __unsafe_unretained qualifier, which doesn't
618 // actually make it into the type system.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000619 if (VT->isObjCInertUnsafeUnretainedType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000620 lifetime = Qualifiers::OCL_ExplicitNone;
621 } else {
622 info.NeedsCopyDispose = true;
623 // used for mrr below.
624 lifetime = Qualifiers::OCL_Strong;
625 }
John McCall351762c2011-02-07 10:33:21 +0000626
627 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000628 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000629 info.NeedsCopyDispose = true;
630 info.HasCXXObject = true;
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000631 if (!VT->getAsCXXRecordDecl()->isExternallyVisible())
Akira Hatanaka9978da32018-08-10 15:09:24 +0000632 info.CapturesNonExternalType = true;
John McCall351762c2011-02-07 10:33:21 +0000633
Akira Hatanaka7275da02018-02-28 07:15:55 +0000634 // So do C structs that require non-trivial copy construction or
635 // destruction.
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000636 } else if (VT.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct ||
637 VT.isDestructedType() == QualType::DK_nontrivial_c_struct) {
Akira Hatanaka7275da02018-02-28 07:15:55 +0000638 info.NeedsCopyDispose = true;
639
John McCall351762c2011-02-07 10:33:21 +0000640 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000641 } else if (CGM.getLangOpts().CPlusPlus) {
Akira Hatanaka2a5e4632018-08-22 13:41:19 +0000642 if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) {
John McCall351762c2011-02-07 10:33:21 +0000643 if (!record->hasTrivialDestructor()) {
644 info.HasCXXObject = true;
645 info.NeedsCopyDispose = true;
Akira Hatanaka9978da32018-08-10 15:09:24 +0000646 if (!record->isExternallyVisible())
647 info.CapturesNonExternalType = true;
John McCall351762c2011-02-07 10:33:21 +0000648 }
649 }
650 }
651
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000652 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000653 CharUnits align = C.getDeclAlign(variable);
Fangrui Song6907ce22018-07-30 19:24:48 +0000654
John McCall351762c2011-02-07 10:33:21 +0000655 maxFieldAlign = std::max(maxFieldAlign, align);
656
Jay Foad7c57be32011-07-11 09:56:20 +0000657 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000658 CGM.getTypes().ConvertTypeForMem(VT);
Fangrui Song6907ce22018-07-30 19:24:48 +0000659
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000660 layout.push_back(
661 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000662 }
663
664 // If that was everything, we're done here.
665 if (layout.empty()) {
666 info.StructureType =
667 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
668 info.CanBeGlobal = true;
669 return;
670 }
671
672 // Sort the layout by alignment. We have to use a stable sort here
673 // to get reproducible results. There should probably be an
674 // llvm::array_pod_stable_sort.
Fangrui Song899d1392019-04-24 14:43:05 +0000675 llvm::stable_sort(layout);
Fangrui Song6907ce22018-07-30 19:24:48 +0000676
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000677 // Needed for blocks layout info.
678 info.BlockHeaderForcedGapOffset = info.BlockSize;
679 info.BlockHeaderForcedGapSize = CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +0000680
John McCall351762c2011-02-07 10:33:21 +0000681 CharUnits &blockSize = info.BlockSize;
682 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
683
684 // Assuming that the first byte in the header is maximally aligned,
685 // get the alignment of the first byte following the header.
686 CharUnits endAlign = getLowBit(blockSize);
687
688 // If the end of the header isn't satisfactorily aligned for the
689 // maximum thing, look for things that are okay with the header-end
690 // alignment, and keep appending them until we get something that's
691 // aligned right. This algorithm is only guaranteed optimal if
692 // that condition is satisfied at some point; otherwise we can get
693 // things like:
694 // header // next byte has alignment 4
695 // something_with_size_5; // next byte has alignment 1
696 // something_with_alignment_8;
697 // which has 7 bytes of padding, as opposed to the naive solution
698 // which might have less (?).
699 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000700 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000701 li = layout.begin() + 1, le = layout.end();
702
703 // Look for something that the header end is already
704 // satisfactorily aligned for.
705 for (; li != le && endAlign < li->Alignment; ++li)
706 ;
707
708 // If we found something that's naturally aligned for the end of
709 // the header, keep adding things...
710 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000711 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000712 for (; li != le; ++li) {
713 assert(endAlign >= li->Alignment);
714
John McCall7f416cc2015-09-08 08:05:57 +0000715 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000716 elementTypes.push_back(li->Type);
717 blockSize += li->Size;
718 endAlign = getLowBit(blockSize);
719
720 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000721 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000722 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000723 }
John McCall351762c2011-02-07 10:33:21 +0000724 }
John McCall351762c2011-02-07 10:33:21 +0000725 // Don't re-append everything we just appended.
726 layout.erase(first, li);
727 }
728 }
729
John McCallac0350a2012-04-26 21:14:42 +0000730 assert(endAlign == getLowBit(blockSize));
Fangrui Song6907ce22018-07-30 19:24:48 +0000731
John McCall351762c2011-02-07 10:33:21 +0000732 // At this point, we just have to add padding if the end align still
733 // isn't aligned right.
734 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000735 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000736 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000737
John McCall7f416cc2015-09-08 08:05:57 +0000738 // If we haven't yet added any fields, remember that there was an
739 // initial gap; this need to go into the block layout bit map.
740 if (blockSize == info.BlockHeaderForcedGapOffset) {
741 info.BlockHeaderForcedGapSize = padding;
742 }
743
John McCalle3dc1702011-02-15 09:22:45 +0000744 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
745 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000746 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000747 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000748 }
749
John McCall1db0a2f2012-05-01 20:28:00 +0000750 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000751 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000752 // Slam everything else on now. This works because they have
753 // strictly decreasing alignment and we expect that size is always a
754 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000755 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000756 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000757 if (endAlign < li->Alignment) {
758 // size may not be multiple of alignment. This can only happen with
759 // an over-aligned variable. We will be adding a padding field to
760 // make the size be multiple of alignment.
761 CharUnits padding = li->Alignment - endAlign;
762 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
763 padding.getQuantity()));
764 blockSize += padding;
765 endAlign = getLowBit(blockSize);
766 }
John McCall351762c2011-02-07 10:33:21 +0000767 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000768 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000769 elementTypes.push_back(li->Type);
770 blockSize += li->Size;
771 endAlign = getLowBit(blockSize);
772 }
773
774 info.StructureType =
775 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
776}
777
778/// Emit a block literal expression in the current function.
Yaxun Liufa13d012018-02-15 16:39:19 +0000779llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000780 // If the block has no captures, we won't have a pre-computed
781 // layout for it.
Akira Hatanakac9a52de2020-06-03 16:41:50 -0700782 if (!blockExpr->getBlockDecl()->hasCaptures())
Yaxun Liuc2a87a02017-10-14 12:23:50 +0000783 // The block literal is emitted as a global variable, and the block invoke
784 // function has to be extracted from its initializer.
Akira Hatanakac9a52de2020-06-03 16:41:50 -0700785 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
George Burgess IVe3763372016-12-22 02:50:20 +0000786 return Block;
John McCall351762c2011-02-07 10:33:21 +0000787
Akira Hatanakac9a52de2020-06-03 16:41:50 -0700788 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
789 computeBlockInfo(CGM, this, blockInfo);
790 blockInfo.BlockExpression = blockExpr;
791 if (!blockInfo.CanBeGlobal)
792 blockInfo.LocalAddress = CreateTempAlloca(blockInfo.StructureType,
793 blockInfo.BlockAlign, "block");
794 return EmitBlockLiteral(blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000795}
796
Yaxun Liufa13d012018-02-15 16:39:19 +0000797llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000798 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000799 auto GenVoidPtrTy =
800 IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
801 LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
802 auto GenVoidPtrSize = CharUnits::fromQuantity(
803 CGM.getTarget().getPointerWidth(
804 CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
805 8);
John McCall08ef4662011-11-10 08:15:53 +0000806 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000807 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
Vedant Kumar29477dc2017-12-08 02:47:58 +0000808 CodeGenFunction BlockCGF{CGM, true};
809 BlockCGF.SanOpts = SanOpts;
810 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
Yaxun Liu10712d92017-10-04 20:32:17 +0000811 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000812 auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000813
814 // If there is nothing to capture, we can emit this as a global block.
815 if (blockInfo.CanBeGlobal)
Akira Hatanakaba0367a2017-09-22 21:32:06 +0000816 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
John McCall351762c2011-02-07 10:33:21 +0000817
818 // Otherwise, we have to emit this as a local block.
819
John McCall7f416cc2015-09-08 08:05:57 +0000820 Address blockAddr = blockInfo.LocalAddress;
821 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000822
Yaxun Liu10712d92017-10-04 20:32:17 +0000823 llvm::Constant *isa;
824 llvm::Constant *descriptor;
825 BlockFlags flags;
826 if (!IsOpenCL) {
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000827 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
828 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
829 // block just returns the original block and releasing it is a no-op.
830 llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
831 ? CGM.getNSConcreteGlobalBlock()
832 : CGM.getNSConcreteStackBlock();
833 isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
Yaxun Liu10712d92017-10-04 20:32:17 +0000834
835 // Build the block descriptor.
836 descriptor = buildBlockDescriptor(CGM, blockInfo);
837
838 // Compute the initial on-stack block flags.
839 flags = BLOCK_HAS_SIGNATURE;
840 if (blockInfo.HasCapturedVariableLayout)
841 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000842 if (blockInfo.needsCopyDisposeHelpers())
Yaxun Liu10712d92017-10-04 20:32:17 +0000843 flags |= BLOCK_HAS_COPY_DISPOSE;
844 if (blockInfo.HasCXXObject)
845 flags |= BLOCK_HAS_CXX_OBJ;
846 if (blockInfo.UsesStret)
847 flags |= BLOCK_USE_STRET;
Akira Hatanakadbfa4532018-07-20 17:10:32 +0000848 if (blockInfo.getBlockDecl()->doesNotEscape())
849 flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
Yaxun Liu10712d92017-10-04 20:32:17 +0000850 }
John McCall351762c2011-02-07 10:33:21 +0000851
James Y Knight751fe282019-02-09 22:22:28 +0000852 auto projectField = [&](unsigned index, const Twine &name) -> Address {
853 return Builder.CreateStructGEP(blockAddr, index, name);
854 };
855 auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) {
856 Builder.CreateStore(value, projectField(index, name));
857 };
John McCall7f416cc2015-09-08 08:05:57 +0000858
859 // Initialize the block header.
860 {
861 // We assume all the header fields are densely packed.
862 unsigned index = 0;
863 CharUnits offset;
James Y Knight751fe282019-02-09 22:22:28 +0000864 auto addHeaderField = [&](llvm::Value *value, CharUnits size,
865 const Twine &name) {
866 storeField(value, index, name);
867 offset += size;
868 index++;
869 };
John McCall7f416cc2015-09-08 08:05:57 +0000870
Yaxun Liu10712d92017-10-04 20:32:17 +0000871 if (!IsOpenCL) {
872 addHeaderField(isa, getPointerSize(), "block.isa");
873 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
874 getIntSize(), "block.flags");
875 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
876 "block.reserved");
877 } else {
878 addHeaderField(
879 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
880 getIntSize(), "block.size");
881 addHeaderField(
882 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
883 getIntSize(), "block.align");
884 }
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000885 addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
886 if (!IsOpenCL)
Yaxun Liu10712d92017-10-04 20:32:17 +0000887 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
Sven van Haastregtda3b6322018-10-02 13:02:24 +0000888 else if (auto *Helper =
889 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
Yaxun Liu10712d92017-10-04 20:32:17 +0000890 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
891 addHeaderField(
892 I.first,
893 CharUnits::fromQuantity(
894 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
895 I.second);
896 }
897 }
John McCall7f416cc2015-09-08 08:05:57 +0000898 }
John McCall351762c2011-02-07 10:33:21 +0000899
900 // Finally, capture all the values into the block.
901 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
902
903 // First, 'this'.
904 if (blockDecl->capturesCXXThis()) {
James Y Knight751fe282019-02-09 22:22:28 +0000905 Address addr =
906 projectField(blockInfo.CXXThisIndex, "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000907 Builder.CreateStore(LoadCXXThis(), addr);
908 }
909
910 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000911 for (const auto &CI : blockDecl->captures()) {
912 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000913 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
914
915 // Ignore constant captures.
916 if (capture.isConstant()) continue;
917
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000918 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000919
920 // This will be a [[type]]*, except that a byref entry will just be
921 // an i8**.
James Y Knight751fe282019-02-09 22:22:28 +0000922 Address blockField = projectField(capture.getIndex(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000923
924 // Compute the address of the thing we're going to move into the
925 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000926 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000927
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000928 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000929 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000930 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000931 src = Address::invalid();
Akira Hatanaka8e57b072018-10-01 21:51:28 +0000932 } else if (CI.isEscapingByref()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000933 if (BlockInfo && CI.isNested()) {
934 // We need to use the capture from the enclosing block.
935 const CGBlockInfo::Capture &enclosingCapture =
936 BlockInfo->getCapture(variable);
937
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000938 // This is a [[type]]*, except that a byref entry will just be an i8**.
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000939 src = Builder.CreateStructGEP(LoadBlockStruct(),
940 enclosingCapture.getIndex(),
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000941 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000942 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000943 auto I = LocalDeclMap.find(variable);
944 assert(I != LocalDeclMap.end());
945 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000946 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000947 } else {
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000948 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000949 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
950 type.getNonReferenceType(), VK_LValue,
951 SourceLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800952 src = EmitDeclRefLValue(&declRef).getAddress(*this);
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000953 };
John McCall351762c2011-02-07 10:33:21 +0000954
955 // For byrefs, we just write the pointer to the byref struct into
956 // the block field. There's no need to chase the forwarding
957 // pointer at this point, since we're building something that will
958 // live a shorter life than the stack byref anyway.
Akira Hatanaka8e57b072018-10-01 21:51:28 +0000959 if (CI.isEscapingByref()) {
John McCalle3dc1702011-02-15 09:22:45 +0000960 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000961 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000962 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000963 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000964 else
John McCall7f416cc2015-09-08 08:05:57 +0000965 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000966
John McCalle3dc1702011-02-15 09:22:45 +0000967 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000968 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000969
970 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000971 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000972 if (blockDecl->isConversionFromLambda()) {
973 // If we have a lambda conversion, emit the expression
974 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000975 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000976 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000977 AggValueSlot::IsDestructed,
978 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +0000979 AggValueSlot::IsNotAliased,
980 AggValueSlot::DoesNotOverlap);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000981 EmitAggExpr(copyExpr, Slot);
982 } else {
983 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
984 }
John McCall351762c2011-02-07 10:33:21 +0000985
986 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000987 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000988 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000989
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000990 // If type is const-qualified, copy the value into the block field.
991 } else if (type.isConstQualified() &&
Akira Hatanaka855d70c2017-05-09 01:20:05 +0000992 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
993 CGM.getCodeGenOpts().OptimizationLevel != 0) {
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000994 llvm::Value *value = Builder.CreateLoad(src, "captured");
995 Builder.CreateStore(value, blockField);
996
John McCall4d14a902013-04-08 23:27:49 +0000997 // If this is an ARC __strong block-pointer variable, don't do a
998 // block copy.
999 //
1000 // TODO: this can be generalized into the normal initialization logic:
1001 // we should never need to do a block-copy when initializing a local
1002 // variable, because the local variable's lifetime should be strictly
1003 // contained within the stack block's.
1004 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1005 type->isBlockPointerType()) {
1006 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +00001007 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +00001008 value = EmitARCRetainNonBlock(value);
1009
1010 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +00001011 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +00001012
1013 // Otherwise, fake up a POD copy into the block field.
1014 } else {
John McCall31168b02011-06-15 23:02:42 +00001015 // Fake up a new variable so that EmitScalarInit doesn't think
1016 // we're referring to the variable in its own initializer.
Alexey Bataev56223232017-06-09 13:40:18 +00001017 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1018 ImplicitParamDecl::Other);
John McCall31168b02011-06-15 23:02:42 +00001019
John McCall93be3f72011-02-07 18:37:40 +00001020 // We use one of these or the other depending on whether the
1021 // reference is nested.
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001022 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
Alexey Bataev19acc3d2015-01-12 10:17:46 +00001023 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1024 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +00001025
Fariborz Jahanian10317ea2011-11-02 22:53:43 +00001026 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
Serge Pavlovde044f72020-09-12 17:05:26 +07001027 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +00001028 // FIXME: Pass a specific location for the expr init so that the store is
1029 // attributed to a reasonable location - otherwise it may be attributed to
1030 // locations of subexpressions in the initialization.
Alexey Bataev56223232017-06-09 13:40:18 +00001031 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001032 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +00001033 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +00001034 }
1035
Akira Hatanakac9a52de2020-06-03 16:41:50 -07001036 // Push a cleanup for the capture if necessary.
1037 if (!blockInfo.NeedsCopyDispose)
1038 continue;
1039
1040 // Ignore __block captures; there's nothing special in the on-stack block
1041 // that we need to do for them.
1042 if (CI.isByRef())
1043 continue;
1044
1045 // Ignore objects that aren't destructed.
1046 QualType::DestructionKind dtorKind = type.isDestructedType();
1047 if (dtorKind == QualType::DK_none)
1048 continue;
1049
1050 CodeGenFunction::Destroyer *destroyer;
1051
1052 // Block captures count as local values and have imprecise semantics.
1053 // They also can't be arrays, so need to worry about that.
1054 //
1055 // For const-qualified captures, emit clang.arc.use to ensure the captured
1056 // object doesn't get released while we are still depending on its validity
1057 // within the block.
1058 if (type.isConstQualified() &&
1059 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1060 CGM.getCodeGenOpts().OptimizationLevel != 0) {
1061 assert(CGM.getLangOpts().ObjCAutoRefCount &&
1062 "expected ObjC ARC to be enabled");
1063 destroyer = emitARCIntrinsicUse;
1064 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
1065 destroyer = destroyARCStrongImprecise;
1066 } else {
1067 destroyer = getDestroyer(dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001068 }
Akira Hatanakac9a52de2020-06-03 16:41:50 -07001069
1070 CleanupKind cleanupKind = NormalCleanup;
1071 bool useArrayEHCleanup = needsEHCleanup(dtorKind);
1072 if (useArrayEHCleanup)
1073 cleanupKind = NormalAndEHCleanup;
1074
1075 // Extend the lifetime of the capture to the end of the scope enclosing the
1076 // block expression except when the block decl is in the list of RetExpr's
1077 // cleanup objects, in which case its lifetime ends after the full
1078 // expression.
1079 auto IsBlockDeclInRetExpr = [&]() {
1080 auto *EWC = llvm::dyn_cast_or_null<ExprWithCleanups>(RetExpr);
1081 if (EWC)
1082 for (auto &C : EWC->getObjects())
1083 if (auto *BD = C.dyn_cast<BlockDecl *>())
1084 if (BD == blockDecl)
1085 return true;
1086 return false;
1087 };
1088
1089 if (IsBlockDeclInRetExpr())
1090 pushDestroy(cleanupKind, blockField, type, destroyer, useArrayEHCleanup);
1091 else
1092 pushLifetimeExtendedDestroy(cleanupKind, blockField, type, destroyer,
1093 useArrayEHCleanup);
John McCall351762c2011-02-07 10:33:21 +00001094 }
1095
1096 // Cast to the converted block-pointer type, which happens (somewhat
1097 // unfortunately) to be a pointer to function type.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001098 llvm::Value *result = Builder.CreatePointerCast(
1099 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +00001100
Yaxun Liufa13d012018-02-15 16:39:19 +00001101 if (IsOpenCL) {
1102 CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1103 result);
1104 }
1105
John McCall351762c2011-02-07 10:33:21 +00001106 return result;
Mike Stump85284ba2009-02-13 16:19:19 +00001107}
1108
1109
Chris Lattnera5f58b02011-07-09 17:41:47 +00001110llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +00001111 if (BlockDescriptorType)
1112 return BlockDescriptorType;
1113
Chris Lattnera5f58b02011-07-09 17:41:47 +00001114 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +00001115 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001116
Mike Stump650c9322009-02-13 15:16:56 +00001117 // struct __block_descriptor {
1118 // unsigned long reserved;
1119 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +00001120 //
1121 // // later, the following will be added
1122 //
1123 // struct {
1124 // void (*copyHelper)();
1125 // void (*copyHelper)();
1126 // } helpers; // !!! optional
1127 //
1128 // const char *signature; // the block signature
1129 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +00001130 // };
Serge Guelton1d993272017-05-09 19:31:30 +00001131 BlockDescriptorType = llvm::StructType::create(
1132 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
Mike Stump650c9322009-02-13 15:16:56 +00001133
John McCall351762c2011-02-07 10:33:21 +00001134 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +00001135 unsigned AddrSpace = 0;
1136 if (getLangOpts().OpenCL)
1137 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1138 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +00001139 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001140}
1141
Chris Lattnera5f58b02011-07-09 17:41:47 +00001142llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +00001143 if (GenericBlockLiteralType)
1144 return GenericBlockLiteralType;
1145
Chris Lattnera5f58b02011-07-09 17:41:47 +00001146 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +00001147
Sven van Haastregtda3b6322018-10-02 13:02:24 +00001148 if (getLangOpts().OpenCL) {
1149 // struct __opencl_block_literal_generic {
1150 // int __size;
1151 // int __align;
1152 // __generic void *__invoke;
1153 // /* custom fields */
1154 // };
1155 SmallVector<llvm::Type *, 8> StructFields(
1156 {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1157 if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1158 for (auto I : Helper->getCustomFieldTypes())
1159 StructFields.push_back(I);
1160 }
1161 GenericBlockLiteralType = llvm::StructType::create(
1162 StructFields, "struct.__opencl_block_literal_generic");
1163 } else {
1164 // struct __block_literal_generic {
1165 // void *__isa;
1166 // int __flags;
1167 // int __reserved;
1168 // void (*__invoke)(void *);
1169 // struct __block_descriptor *__descriptor;
1170 // };
1171 GenericBlockLiteralType =
1172 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1173 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1174 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001175
Mike Stump005c9a62009-02-13 15:25:34 +00001176 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001177}
1178
Yaxun Liu10712d92017-10-04 20:32:17 +00001179RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +00001180 ReturnValueSlot ReturnValue) {
Simon Pilgrim0abbb152019-10-04 15:01:54 +00001181 const auto *BPT = E->getCallee()->getType()->castAs<BlockPointerType>();
John McCallb92ab1a2016-10-26 23:46:34 +00001182 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Andrew Savonichev43fceb22019-02-21 11:02:10 +00001183 llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType();
1184 llvm::Value *Func = nullptr;
1185 QualType FnType = BPT->getPointeeType();
1186 ASTContext &Ctx = getContext();
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001187 CallArgList Args;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001188
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001189 if (getLangOpts().OpenCL) {
Andrew Savonichev43fceb22019-02-21 11:02:10 +00001190 // For OpenCL, BlockPtr is already casted to generic block literal.
1191
1192 // First argument of a block call is a generic block literal casted to
1193 // generic void pointer, i.e. i8 addrspace(4)*
1194 llvm::Value *BlockDescriptor = Builder.CreatePointerCast(
1195 BlockPtr, CGM.getOpenCLRuntime().getGenericVoidPointerType());
1196 QualType VoidPtrQualTy = Ctx.getPointerType(
1197 Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic));
1198 Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy);
1199 // And the rest of the arguments.
1200 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1201
1202 // We *can* call the block directly unless it is a function argument.
1203 if (!isa<ParmVarDecl>(E->getCalleeDecl()))
1204 Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1205 else {
1206 llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
1207 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1208 }
1209 } else {
1210 // Bitcast the block literal to a generic block literal.
1211 BlockPtr = Builder.CreatePointerCast(
1212 BlockPtr, llvm::PointerType::get(GenBlockTy, 0), "block.literal");
1213 // Get pointer to the block invoke function
1214 llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
1215
1216 // First argument is a block literal casted to a void pointer
1217 BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
1218 Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy);
1219 // And the rest of the arguments.
1220 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1221
1222 // Load the function.
1223 Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001224 }
1225
John McCall85915252011-03-09 08:39:33 +00001226 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001227 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001228 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001229
Anders Carlsson5f50c652009-04-07 22:10:22 +00001230 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001231 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001232
Chris Lattner2192fe52011-07-18 04:24:23 +00001233 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Yaxun Liu10712d92017-10-04 20:32:17 +00001234 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001235
John McCallb92ab1a2016-10-26 23:46:34 +00001236 // Prepare the callee.
1237 CGCallee Callee(CGCalleeInfo(), Func);
1238
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001239 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001240 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001241}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001242
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001243Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
John McCall351762c2011-02-07 10:33:21 +00001244 assert(BlockInfo && "evaluating block ref without block information?");
1245 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001246
John McCall351762c2011-02-07 10:33:21 +00001247 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001248 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001249
James Y Knight751fe282019-02-09 22:22:28 +00001250 Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1251 "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001252
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001253 if (variable->isEscapingByref()) {
John McCall351762c2011-02-07 10:33:21 +00001254 // addr should be a void** right now. Load, then cast the result
1255 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001256
John McCall7f416cc2015-09-08 08:05:57 +00001257 auto &byrefInfo = getBlockByrefInfo(variable);
1258 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001259
John McCall7f416cc2015-09-08 08:05:57 +00001260 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1261 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001262
John McCall7f416cc2015-09-08 08:05:57 +00001263 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1264 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001265 }
1266
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001267 assert((!variable->isNonEscapingByref() ||
1268 capture.fieldType()->isReferenceType()) &&
1269 "the capture field of a non-escaping variable should have a "
1270 "reference type");
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001271 if (capture.fieldType()->isReferenceType())
1272 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
Mike Stump7fe9cc12009-10-21 03:49:08 +00001273
John McCall351762c2011-02-07 10:33:21 +00001274 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001275}
1276
George Burgess IVe3763372016-12-22 02:50:20 +00001277void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1278 llvm::Constant *Addr) {
1279 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1280 (void)Ok;
1281 assert(Ok && "Trying to replace an already-existing global block!");
1282}
1283
Mike Stump2d5a2872009-02-14 22:16:35 +00001284llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001285CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1286 StringRef Name) {
George Burgess IVe3763372016-12-22 02:50:20 +00001287 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1288 return Block;
1289
George Burgess IV70d15b32016-11-03 02:21:43 +00001290 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1291 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001292
John McCall351762c2011-02-07 10:33:21 +00001293 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001294 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001295
John McCall351762c2011-02-07 10:33:21 +00001296 // Using that metadata, generate the actual block function.
John McCall351762c2011-02-07 10:33:21 +00001297 {
John McCall7f416cc2015-09-08 08:05:57 +00001298 CodeGenFunction::DeclMapTy LocalDeclMap;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001299 CodeGenFunction(*this).GenerateBlockFunction(
1300 GlobalDecl(), blockInfo, LocalDeclMap,
1301 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
John McCall351762c2011-02-07 10:33:21 +00001302 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001303
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001304 return getAddrOfGlobalBlockIfEmitted(BE);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001305}
1306
John McCall351762c2011-02-07 10:33:21 +00001307static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1308 const CGBlockInfo &blockInfo,
1309 llvm::Constant *blockFn) {
1310 assert(blockInfo.CanBeGlobal);
George Burgess IVe3763372016-12-22 02:50:20 +00001311 // Callers should detect this case on their own: calling this function
1312 // generally requires computing layout information, which is a waste of time
1313 // if we've already emitted this block.
1314 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1315 "Refusing to re-emit a global block.");
John McCall351762c2011-02-07 10:33:21 +00001316
1317 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001318 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001319 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001320
Yaxun Liu10712d92017-10-04 20:32:17 +00001321 bool IsOpenCL = CGM.getLangOpts().OpenCL;
David Chisnallc5a458c2018-08-09 08:02:42 +00001322 bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
Yaxun Liu10712d92017-10-04 20:32:17 +00001323 if (!IsOpenCL) {
1324 // isa
David Chisnallc5a458c2018-08-09 08:02:42 +00001325 if (IsWindows)
1326 fields.addNullPointer(CGM.Int8PtrPtrTy);
1327 else
1328 fields.add(CGM.getNSConcreteGlobalBlock());
John McCall351762c2011-02-07 10:33:21 +00001329
Yaxun Liu10712d92017-10-04 20:32:17 +00001330 // __flags
1331 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1332 if (blockInfo.UsesStret)
1333 flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +00001334
Yaxun Liu10712d92017-10-04 20:32:17 +00001335 fields.addInt(CGM.IntTy, flags.getBitMask());
1336
1337 // Reserved
1338 fields.addInt(CGM.IntTy, 0);
1339 } else {
1340 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1341 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1342 }
John McCall351762c2011-02-07 10:33:21 +00001343
Sven van Haastregtda3b6322018-10-02 13:02:24 +00001344 // Function
1345 fields.add(blockFn);
1346
Yaxun Liu10712d92017-10-04 20:32:17 +00001347 if (!IsOpenCL) {
1348 // Descriptor
1349 fields.add(buildBlockDescriptor(CGM, blockInfo));
1350 } else if (auto *Helper =
1351 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1352 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1353 fields.add(I);
1354 }
1355 }
John McCall351762c2011-02-07 10:33:21 +00001356
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001357 unsigned AddrSpace = 0;
1358 if (CGM.getContext().getLangOpts().OpenCL)
1359 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1360
Akira Hatanaka6cb2d9d2019-06-14 22:06:28 +00001361 llvm::GlobalVariable *literal = fields.finishAndCreateGlobal(
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001362 "__block_literal_global", blockInfo.BlockAlign,
David Chisnallc5a458c2018-08-09 08:02:42 +00001363 /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1364
Akira Hatanaka6cb2d9d2019-06-14 22:06:28 +00001365 literal->addAttribute("objc_arc_inert");
1366
David Chisnallc5a458c2018-08-09 08:02:42 +00001367 // Windows does not allow globals to be initialised to point to globals in
1368 // different DLLs. Any such variables must run code to initialise them.
1369 if (IsWindows) {
1370 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1371 {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1372 &CGM.getModule());
1373 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1374 Init));
1375 b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
Guillaume Chatelet59f95222020-01-23 16:18:34 +01001376 b.CreateStructGEP(literal, 0),
1377 CGM.getPointerAlign().getAsAlign());
David Chisnallc5a458c2018-08-09 08:02:42 +00001378 b.CreateRetVoid();
1379 // We can't use the normal LLVM global initialisation array, because we
1380 // need to specify that this runs early in library initialisation.
1381 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1382 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1383 Init, ".block_isa_init_ptr");
1384 InitVar->setSection(".CRT$XCLa");
1385 CGM.addUsedGlobal(InitVar);
1386 }
John McCall351762c2011-02-07 10:33:21 +00001387
1388 // Return a constant of the appropriately-casted type.
George Burgess IVe3763372016-12-22 02:50:20 +00001389 llvm::Type *RequiredType =
John McCall351762c2011-02-07 10:33:21 +00001390 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
George Burgess IVe3763372016-12-22 02:50:20 +00001391 llvm::Constant *Result =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001392 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
George Burgess IVe3763372016-12-22 02:50:20 +00001393 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
Yaxun Liufa13d012018-02-15 16:39:19 +00001394 if (CGM.getContext().getLangOpts().OpenCL)
1395 CGM.getOpenCLRuntime().recordBlockInfo(
1396 blockInfo.BlockExpression,
1397 cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
George Burgess IVe3763372016-12-22 02:50:20 +00001398 return Result;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001399}
1400
John McCall7f416cc2015-09-08 08:05:57 +00001401void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1402 unsigned argNum,
1403 llvm::Value *arg) {
1404 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1405
Adrian Prantl356347b2017-10-26 20:08:52 +00001406 // Allocate a stack slot like for any local variable to guarantee optimal
1407 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1408 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1409 Builder.CreateStore(arg, alloc);
John McCall7f416cc2015-09-08 08:05:57 +00001410 if (CGDebugInfo *DI = getDebugInfo()) {
Amy Huang53539bb2020-01-13 15:54:54 -08001411 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
John McCall7f416cc2015-09-08 08:05:57 +00001412 DI->setLocation(D->getLocation());
Adrian Prantl356347b2017-10-26 20:08:52 +00001413 DI->EmitDeclareOfBlockLiteralArgVariable(
1414 *BlockInfo, D->getName(), argNum,
1415 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
John McCall7f416cc2015-09-08 08:05:57 +00001416 }
1417 }
1418
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001419 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
John McCall7f416cc2015-09-08 08:05:57 +00001420 ApplyDebugLocation Scope(*this, StartLoc);
1421
1422 // Instead of messing around with LocalDeclMap, just set the value
1423 // directly as BlockPointer.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001424 BlockPointer = Builder.CreatePointerCast(
1425 arg,
1426 BlockInfo->StructureType->getPointerTo(
1427 getContext().getLangOpts().OpenCL
1428 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1429 : 0),
1430 "block");
John McCall7f416cc2015-09-08 08:05:57 +00001431}
1432
1433Address CodeGenFunction::LoadBlockStruct() {
1434 assert(BlockInfo && "not in a block invocation function!");
1435 assert(BlockPointer && "no block pointer set!");
1436 return Address(BlockPointer, BlockInfo->BlockAlign);
1437}
1438
Mike Stump4446dcf2009-03-05 08:32:30 +00001439llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001440CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1441 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001442 const DeclMapTy &ldm,
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001443 bool IsLambdaConversionToBlock,
1444 bool BuildGlobalBlock) {
John McCall351762c2011-02-07 10:33:21 +00001445 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001446
Fariborz Jahanian63628032012-06-26 16:06:38 +00001447 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001448
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001449 CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00001450
John McCall351762c2011-02-07 10:33:21 +00001451 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001452
Mike Stump5469f292009-03-13 23:34:28 +00001453 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001454 // to be local to this function as well, in case they're directly
1455 // referenced in a block.
1456 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001457 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001458 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001459 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001460 }
1461
John McCall351762c2011-02-07 10:33:21 +00001462 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001463
John McCall351762c2011-02-07 10:33:21 +00001464 // Build the argument list.
1465 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001466
John McCall351762c2011-02-07 10:33:21 +00001467 // The first argument is the block pointer. Just take it as a void*
1468 // and cast it later.
1469 QualType selfTy = getContext().VoidPtrTy;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001470
1471 // For OpenCL passed block pointer can be private AS local variable or
1472 // global AS program scope variable (for the case with and without captures).
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00001473 // Generic AS is used therefore to be able to accommodate both private and
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001474 // generic AS in one implementation.
1475 if (getLangOpts().OpenCL)
1476 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1477 getContext().VoidTy, LangAS::opencl_generic));
1478
Mike Stump7fe9cc12009-10-21 03:49:08 +00001479 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001480
Alexey Bataev56223232017-06-09 13:40:18 +00001481 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1482 SourceLocation(), II, selfTy,
1483 ImplicitParamDecl::ObjCSelf);
1484 args.push_back(&SelfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001485
John McCall351762c2011-02-07 10:33:21 +00001486 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001487 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001488
John McCall351762c2011-02-07 10:33:21 +00001489 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001490 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001491 const CGFunctionInfo &fnInfo =
1492 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001493 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001494 blockInfo.UsesStret = true;
1495
John McCalla729c622012-02-17 03:33:10 +00001496 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001497
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001498 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001499 llvm::Function *fn = llvm::Function::Create(
1500 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001501 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001502
Yaxun Liu10712d92017-10-04 20:32:17 +00001503 if (BuildGlobalBlock) {
1504 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1505 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1506 : VoidPtrTy;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001507 buildGlobalBlock(CGM, blockInfo,
Yaxun Liu10712d92017-10-04 20:32:17 +00001508 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1509 }
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001510
John McCall351762c2011-02-07 10:33:21 +00001511 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001512 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001513 blockDecl->getLocation(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001514 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
Mike Stumpb7074c02009-02-13 15:32:32 +00001515
John McCall147d0212011-02-22 22:38:33 +00001516 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001517
Adrian Prantl0f6df002013-03-29 19:20:35 +00001518 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1519 // won't delete the dbg.declare intrinsics for captured variables.
1520 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1521 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1522 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001523 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1524 getPointerAlign(),
1525 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001526 // Set the DebugLocation to empty, so the store is recognized as a
1527 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001528 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001529 Builder.CreateStore(BlockPointer, Alloca);
1530 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001531 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001532
John McCall87fe5d52010-05-20 01:18:31 +00001533 // If we have a C++ 'this' reference, go ahead and force it into
1534 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001535 if (blockDecl->capturesCXXThis()) {
James Y Knight751fe282019-02-09 22:22:28 +00001536 Address addr = Builder.CreateStructGEP(
1537 LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001538 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001539 }
1540
John McCall351762c2011-02-07 10:33:21 +00001541 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001542 for (const auto &CI : blockDecl->captures()) {
1543 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001544 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1545 if (!capture.isConstant()) continue;
1546
John McCall7f416cc2015-09-08 08:05:57 +00001547 CharUnits align = getContext().getDeclAlign(variable);
1548 Address alloca =
1549 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001550
John McCall7f416cc2015-09-08 08:05:57 +00001551 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001552
John McCall7f416cc2015-09-08 08:05:57 +00001553 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001554 }
1555
John McCall113bee02012-03-10 09:33:50 +00001556 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001557 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1558 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1559 --entry_ptr;
1560
Eli Friedman2495ab02012-02-25 02:48:22 +00001561 if (IsLambdaConversionToBlock)
1562 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001563 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001564 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001565 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001566 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001567 }
Mike Stump017460a2009-10-01 22:29:41 +00001568
Mike Stump7d699112009-10-01 00:27:30 +00001569 // Remember where we were...
1570 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001571
Mike Stump7d699112009-10-01 00:27:30 +00001572 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001573 ++entry_ptr;
1574 Builder.SetInsertPoint(entry, entry_ptr);
1575
John McCall113bee02012-03-10 09:33:50 +00001576 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001577 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001578 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001579 for (const auto &CI : blockDecl->captures()) {
1580 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001581 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001582
Amy Huang53539bb2020-01-13 15:54:54 -08001583 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001584 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1585 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001586 auto addr = LocalDeclMap.find(variable)->second;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001587 (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1588 Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001589 continue;
1590 }
John McCall351762c2011-02-07 10:33:21 +00001591
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001592 DI->EmitDeclareOfBlockDeclRefVariable(
1593 variable, BlockPointerDbgLoc, Builder, blockInfo,
1594 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001595 }
Mike Stump2e722b92009-09-30 02:43:10 +00001596 }
Manman Renab08a9a2013-01-04 18:51:35 +00001597 // Recover location if it was changed in the above loop.
1598 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001599 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001600 }
John McCall351762c2011-02-07 10:33:21 +00001601
Mike Stump7d699112009-10-01 00:27:30 +00001602 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001603 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001604 Builder.ClearInsertionPoint();
1605 else
1606 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001607
John McCall351762c2011-02-07 10:33:21 +00001608 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001609
John McCall351762c2011-02-07 10:33:21 +00001610 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001611}
Mike Stump1db7d042009-02-28 09:07:16 +00001612
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001613static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1614computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1615 const LangOptions &LangOpts) {
1616 if (CI.getCopyExpr()) {
1617 assert(!CI.isByRef());
1618 // don't bother computing flags
1619 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1620 }
1621 BlockFieldFlags Flags;
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001622 if (CI.isEscapingByref()) {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001623 Flags = BLOCK_FIELD_IS_BYREF;
1624 if (T.isObjCGCWeak())
1625 Flags |= BLOCK_FIELD_IS_WEAK;
1626 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1627 }
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001628
1629 Flags = BLOCK_FIELD_IS_OBJECT;
1630 bool isBlockPointer = T->isBlockPointerType();
1631 if (isBlockPointer)
1632 Flags = BLOCK_FIELD_IS_BLOCK;
1633
Akira Hatanaka7275da02018-02-28 07:15:55 +00001634 switch (T.isNonTrivialToPrimitiveCopy()) {
1635 case QualType::PCK_Struct:
1636 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1637 BlockFieldFlags());
Akira Hatanakad791e922018-03-19 17:38:40 +00001638 case QualType::PCK_ARCWeak:
1639 // We need to register __weak direct captures with the runtime.
1640 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001641 case QualType::PCK_ARCStrong:
1642 // We need to retain the copied value for __strong direct captures.
1643 // If it's a block pointer, we have to copy the block and assign that to
1644 // the destination pointer, so we might as well use _Block_object_assign.
1645 // Otherwise we can avoid that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001646 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1647 : BlockCaptureEntityKind::BlockObject,
1648 Flags);
Akira Hatanaka7275da02018-02-28 07:15:55 +00001649 case QualType::PCK_Trivial:
1650 case QualType::PCK_VolatileTrivial: {
1651 if (!T->isObjCRetainableType())
1652 // For all other types, the memcpy is fine.
1653 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1654
1655 // Special rules for ARC captures:
1656 Qualifiers QS = T.getQualifiers();
1657
Akira Hatanaka7275da02018-02-28 07:15:55 +00001658 // Non-ARC captures of retainable pointers are strong and
1659 // therefore require a call to _Block_object_assign.
1660 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1661 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1662
1663 // Otherwise the memcpy is fine.
1664 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001665 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001666 }
Nico Weberb3897eb2018-02-28 19:28:47 +00001667 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001668}
1669
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001670static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1671computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1672 const LangOptions &LangOpts);
1673
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001674/// Find the set of block captures that need to be explicitly copied or destroy.
1675static void findBlockCapturedManagedEntities(
1676 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001677 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures) {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001678 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1679 const VarDecl *Variable = CI.getVariable();
1680 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1681 if (Capture.isConstant())
1682 continue;
1683
Akira Hatanaka2a5e4632018-08-22 13:41:19 +00001684 QualType VT = Capture.fieldType();
1685 auto CopyInfo = computeCopyInfoForBlockCapture(CI, VT, LangOpts);
1686 auto DisposeInfo = computeDestroyInfoForBlockCapture(CI, VT, LangOpts);
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001687 if (CopyInfo.first != BlockCaptureEntityKind::None ||
1688 DisposeInfo.first != BlockCaptureEntityKind::None)
1689 ManagedCaptures.emplace_back(CopyInfo.first, DisposeInfo.first,
1690 CopyInfo.second, DisposeInfo.second, CI,
1691 Capture);
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001692 }
Akira Hatanaka9978da32018-08-10 15:09:24 +00001693
1694 // Sort the captures by offset.
Fangrui Song55fab262018-09-26 22:16:28 +00001695 llvm::sort(ManagedCaptures);
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001696}
1697
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001698namespace {
1699/// Release a __block variable.
1700struct CallBlockRelease final : EHScopeStack::Cleanup {
1701 Address Addr;
1702 BlockFieldFlags FieldFlags;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001703 bool LoadBlockVarAddr, CanThrow;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001704
Akira Hatanaka9978da32018-08-10 15:09:24 +00001705 CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1706 bool CT)
1707 : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1708 CanThrow(CT) {}
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001709
1710 void Emit(CodeGenFunction &CGF, Flags flags) override {
1711 llvm::Value *BlockVarAddr;
1712 if (LoadBlockVarAddr) {
1713 BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1714 BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1715 } else {
1716 BlockVarAddr = Addr.getPointer();
1717 }
1718
Akira Hatanaka9978da32018-08-10 15:09:24 +00001719 CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001720 }
1721};
1722} // end anonymous namespace
1723
Akira Hatanaka9978da32018-08-10 15:09:24 +00001724/// Check if \p T is a C++ class that has a destructor that can throw.
1725bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1726 if (const auto *RD = T->getAsCXXRecordDecl())
1727 if (const CXXDestructorDecl *DD = RD->getDestructor())
Simon Pilgrim0abbb152019-10-04 15:01:54 +00001728 return DD->getType()->castAs<FunctionProtoType>()->canThrow();
Akira Hatanaka9978da32018-08-10 15:09:24 +00001729 return false;
1730}
1731
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001732// Return a string that has the information about a capture.
1733static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
1734 CaptureStrKind StrKind,
1735 CharUnits BlockAlignment,
1736 CodeGenModule &CGM) {
1737 std::string Str;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001738 ASTContext &Ctx = CGM.getContext();
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001739 const BlockDecl::Capture &CI = *E.CI;
1740 QualType CaptureTy = CI.getVariable()->getType();
Akira Hatanaka9978da32018-08-10 15:09:24 +00001741
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001742 BlockCaptureEntityKind Kind;
1743 BlockFieldFlags Flags;
1744
1745 // CaptureStrKind::Merged should be passed only when the operations and the
1746 // flags are the same for copy and dispose.
1747 assert((StrKind != CaptureStrKind::Merged ||
1748 (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) &&
1749 "different operations and flags");
1750
1751 if (StrKind == CaptureStrKind::DisposeHelper) {
1752 Kind = E.DisposeKind;
1753 Flags = E.DisposeFlags;
1754 } else {
1755 Kind = E.CopyKind;
1756 Flags = E.CopyFlags;
1757 }
1758
1759 switch (Kind) {
1760 case BlockCaptureEntityKind::CXXRecord: {
1761 Str += "c";
1762 SmallString<256> TyStr;
1763 llvm::raw_svector_ostream Out(TyStr);
Akira Hatanaka32e0a582018-10-20 05:45:01 +00001764 CGM.getCXXABI().getMangleContext().mangleTypeName(CaptureTy, Out);
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001765 Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
1766 break;
1767 }
1768 case BlockCaptureEntityKind::ARCWeak:
1769 Str += "w";
1770 break;
1771 case BlockCaptureEntityKind::ARCStrong:
1772 Str += "s";
1773 break;
1774 case BlockCaptureEntityKind::BlockObject: {
1775 const VarDecl *Var = CI.getVariable();
1776 unsigned F = Flags.getBitMask();
1777 if (F & BLOCK_FIELD_IS_BYREF) {
1778 Str += "r";
1779 if (F & BLOCK_FIELD_IS_WEAK)
1780 Str += "w";
1781 else {
1782 // If CaptureStrKind::Merged is passed, check both the copy expression
1783 // and the destructor.
1784 if (StrKind != CaptureStrKind::DisposeHelper) {
1785 if (Ctx.getBlockVarCopyInit(Var).canThrow())
1786 Str += "c";
1787 }
1788 if (StrKind != CaptureStrKind::CopyHelper) {
1789 if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1790 Str += "d";
1791 }
1792 }
1793 } else {
1794 assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
1795 if (F == BLOCK_FIELD_IS_BLOCK)
1796 Str += "b";
1797 else
1798 Str += "o";
1799 }
1800 break;
1801 }
1802 case BlockCaptureEntityKind::NonTrivialCStruct: {
1803 bool IsVolatile = CaptureTy.isVolatileQualified();
1804 CharUnits Alignment =
1805 BlockAlignment.alignmentAtOffset(E.Capture->getOffset());
1806
1807 Str += "n";
1808 std::string FuncStr;
1809 if (StrKind == CaptureStrKind::DisposeHelper)
1810 FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
1811 CaptureTy, Alignment, IsVolatile, Ctx);
1812 else
1813 // If CaptureStrKind::Merged is passed, use the copy constructor string.
1814 // It has all the information that the destructor string has.
1815 FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
1816 CaptureTy, Alignment, IsVolatile, Ctx);
1817 // The underscore is necessary here because non-trivial copy constructor
1818 // and destructor strings can start with a number.
1819 Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
1820 break;
1821 }
1822 case BlockCaptureEntityKind::None:
1823 break;
1824 }
1825
1826 return Str;
1827}
1828
1829static std::string getCopyDestroyHelperFuncName(
1830 const SmallVectorImpl<BlockCaptureManagedEntity> &Captures,
1831 CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
1832 assert((StrKind == CaptureStrKind::CopyHelper ||
1833 StrKind == CaptureStrKind::DisposeHelper) &&
1834 "unexpected CaptureStrKind");
1835 std::string Name = StrKind == CaptureStrKind::CopyHelper
1836 ? "__copy_helper_block_"
1837 : "__destroy_helper_block_";
Akira Hatanaka9978da32018-08-10 15:09:24 +00001838 if (CGM.getLangOpts().Exceptions)
1839 Name += "e";
1840 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1841 Name += "a";
1842 Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1843
1844 for (const BlockCaptureManagedEntity &E : Captures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00001845 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001846 Name += getBlockCaptureStr(E, StrKind, BlockAlignment, CGM);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001847 }
1848
1849 return Name;
1850}
1851
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001852static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1853 Address Field, QualType CaptureType,
Akira Hatanaka9978da32018-08-10 15:09:24 +00001854 BlockFieldFlags Flags, bool ForCopyHelper,
1855 VarDecl *Var, CodeGenFunction &CGF) {
1856 bool EHOnly = ForCopyHelper;
1857
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001858 switch (CaptureKind) {
1859 case BlockCaptureEntityKind::CXXRecord:
1860 case BlockCaptureEntityKind::ARCWeak:
1861 case BlockCaptureEntityKind::NonTrivialCStruct:
1862 case BlockCaptureEntityKind::ARCStrong: {
1863 if (CaptureType.isDestructedType() &&
1864 (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1865 CodeGenFunction::Destroyer *Destroyer =
1866 CaptureKind == BlockCaptureEntityKind::ARCStrong
1867 ? CodeGenFunction::destroyARCStrongImprecise
1868 : CGF.getDestroyer(CaptureType.isDestructedType());
1869 CleanupKind Kind =
1870 EHOnly ? EHCleanup
1871 : CGF.getCleanupKind(CaptureType.isDestructedType());
1872 CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1873 }
1874 break;
1875 }
1876 case BlockCaptureEntityKind::BlockObject: {
1877 if (!EHOnly || CGF.getLangOpts().Exceptions) {
1878 CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
Akira Hatanaka9978da32018-08-10 15:09:24 +00001879 // Calls to _Block_object_dispose along the EH path in the copy helper
1880 // function don't throw as newly-copied __block variables always have a
1881 // reference count of 2.
1882 bool CanThrow =
1883 !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
1884 CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1885 CanThrow);
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001886 }
1887 break;
1888 }
1889 case BlockCaptureEntityKind::None:
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001890 break;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001891 }
1892}
1893
Akira Hatanaka9978da32018-08-10 15:09:24 +00001894static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1895 llvm::Function *Fn,
1896 const CGFunctionInfo &FI,
1897 CodeGenModule &CGM) {
1898 if (CapturesNonExternalType) {
1899 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1900 } else {
1901 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1902 Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Erich Keanede6480a32018-11-13 15:48:08 +00001903 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001904 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1905 }
1906}
John McCallf593b102013-01-22 03:56:22 +00001907/// Generate the copy-helper function for a block closure object:
1908/// static void block_copy_helper(block_t *dst, block_t *src);
1909/// The runtime will have previously initialized 'dst' by doing a
1910/// bit-copy of 'src'.
1911///
1912/// Note that this copies an entire block closure object to the heap;
1913/// it should not be confused with a 'byref copy helper', which moves
1914/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001915llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001916CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00001917 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001918 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001919 std::string FuncName =
1920 getCopyDestroyHelperFuncName(CopiedCaptures, blockInfo.BlockAlign,
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001921 CaptureStrKind::CopyHelper, CGM);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001922
1923 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
Akira Hatanaka936240c2018-08-14 00:15:42 +00001924 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001925
John McCall351762c2011-02-07 10:33:21 +00001926 ASTContext &C = getContext();
1927
Jonas Devlieghere64a26302018-11-11 00:56:15 +00001928 QualType ReturnTy = C.VoidTy;
1929
John McCall351762c2011-02-07 10:33:21 +00001930 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00001931 ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00001932 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00001933 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00001934 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001935
John McCallc56a8b32016-03-11 04:30:31 +00001936 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00001937 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001938
John McCall351762c2011-02-07 10:33:21 +00001939 // FIXME: it would be nice if these were mergeable with things with
1940 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001941 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001942
1943 llvm::Function *Fn =
Akira Hatanaka9978da32018-08-10 15:09:24 +00001944 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
1945 FuncName, &CGM.getModule());
Saleem Abdulrasool89628922019-02-22 16:29:50 +00001946 if (CGM.supportsCOMDAT())
1947 Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
Mike Stump0c743272009-03-06 01:33:24 +00001948
Jonas Devlieghere64a26302018-11-11 00:56:15 +00001949 IdentifierInfo *II = &C.Idents.get(FuncName);
Mike Stump0c743272009-03-06 01:33:24 +00001950
Jonas Devlieghere64a26302018-11-11 00:56:15 +00001951 SmallVector<QualType, 2> ArgTys;
1952 ArgTys.push_back(C.VoidPtrTy);
1953 ArgTys.push_back(C.VoidPtrTy);
1954 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
1955
1956 FunctionDecl *FD = FunctionDecl::Create(
1957 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
1958 FunctionTy, nullptr, SC_Static, false, false);
Akira Hatanaka9978da32018-08-10 15:09:24 +00001959 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
1960 CGM);
Adrian Prantl314b9272020-03-04 08:34:20 -08001961 // This is necessary to avoid inheriting the previous line number.
1962 FD->setImplicit();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00001963 StartFunction(FD, ReturnTy, Fn, FI, args);
Adrian Prantl314b9272020-03-04 08:34:20 -08001964 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1965
Chris Lattner2192fe52011-07-18 04:24:23 +00001966 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001967
Alexey Bataev56223232017-06-09 13:40:18 +00001968 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001969 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001970 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001971
Alexey Bataev56223232017-06-09 13:40:18 +00001972 Address dst = GetAddrOfLocalVar(&DstDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001973 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001974 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001975
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001976 for (const auto &CopiedCapture : CopiedCaptures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00001977 const BlockDecl::Capture &CI = *CopiedCapture.CI;
1978 const CGBlockInfo::Capture &capture = *CopiedCapture.Capture;
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001979 QualType captureType = CI.getVariable()->getType();
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001980 BlockFieldFlags flags = CopiedCapture.CopyFlags;
John McCall351762c2011-02-07 10:33:21 +00001981
1982 unsigned index = capture.getIndex();
James Y Knight751fe282019-02-09 22:22:28 +00001983 Address srcField = Builder.CreateStructGEP(src, index);
1984 Address dstField = Builder.CreateStructGEP(dst, index);
John McCall351762c2011-02-07 10:33:21 +00001985
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00001986 switch (CopiedCapture.CopyKind) {
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00001987 case BlockCaptureEntityKind::CXXRecord:
1988 // If there's an explicit copy expression, we do that.
1989 assert(CI.getCopyExpr() && "copy expression for variable is missing");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001990 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00001991 break;
1992 case BlockCaptureEntityKind::ARCWeak:
John McCall31168b02011-06-15 23:02:42 +00001993 EmitARCCopyWeak(dstField, srcField);
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00001994 break;
1995 case BlockCaptureEntityKind::NonTrivialCStruct: {
1996 // If this is a C struct that requires non-trivial copy construction,
1997 // emit a call to its copy constructor.
Akira Hatanaka7275da02018-02-28 07:15:55 +00001998 QualType varType = CI.getVariable()->getType();
1999 callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
2000 MakeAddrLValue(srcField, varType));
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002001 break;
2002 }
2003 case BlockCaptureEntityKind::ARCStrong: {
John McCall351762c2011-02-07 10:33:21 +00002004 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002005 // At -O0, store null into the destination field (so that the
2006 // storeStrong doesn't over-release) and then call storeStrong.
2007 // This is a workaround to not having an initStrong call.
2008 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2009 auto *ty = cast<llvm::PointerType>(srcValue->getType());
2010 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
2011 Builder.CreateStore(null, dstField);
2012 EmitARCStoreStrongCall(dstField, srcValue, true);
John McCalle68b8f42012-10-17 02:28:37 +00002013
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002014 // With optimization enabled, take advantage of the fact that
2015 // the blocks runtime guarantees a memcpy of the block data, and
2016 // just emit a retain of the src field.
John McCalle68b8f42012-10-17 02:28:37 +00002017 } else {
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002018 EmitARCRetainNonBlock(srcValue);
John McCall882987f2013-02-28 19:01:20 +00002019
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002020 // Unless EH cleanup is required, we don't need this anymore, so kill
2021 // it. It's not quite worth the annoyance to avoid creating it in the
2022 // first place.
2023 if (!needsEHCleanup(captureType.isDestructedType()))
2024 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00002025 }
Akira Hatanaka4a6f1902018-08-13 20:59:57 +00002026 break;
2027 }
2028 case BlockCaptureEntityKind::BlockObject: {
2029 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2030 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
2031 llvm::Value *dstAddr =
2032 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
2033 llvm::Value *args[] = {
2034 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2035 };
2036
2037 if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
2038 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
2039 else
2040 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
2041 break;
2042 }
2043 case BlockCaptureEntityKind::None:
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002044 continue;
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002045 }
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002046
2047 // Ensure that we destroy the copied object if an exception is thrown later
2048 // in the helper function.
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002049 pushCaptureCleanup(CopiedCapture.CopyKind, dstField, captureType, flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002050 /*ForCopyHelper*/ true, CI.getVariable(), *this);
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00002051 }
2052
John McCallad7c5c12011-02-08 08:22:06 +00002053 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00002054
John McCalle3dc1702011-02-15 09:22:45 +00002055 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00002056}
2057
Akira Hatanaka7275da02018-02-28 07:15:55 +00002058static BlockFieldFlags
2059getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
2060 QualType T) {
2061 BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
2062 if (T->isBlockPointerType())
2063 Flags = BLOCK_FIELD_IS_BLOCK;
2064 return Flags;
2065}
2066
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002067static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
2068computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
2069 const LangOptions &LangOpts) {
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002070 if (CI.isEscapingByref()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00002071 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002072 if (T.isObjCGCWeak())
2073 Flags |= BLOCK_FIELD_IS_WEAK;
2074 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
2075 }
2076
Akira Hatanaka7275da02018-02-28 07:15:55 +00002077 switch (T.isDestructedType()) {
2078 case QualType::DK_cxx_destructor:
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002079 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
Akira Hatanaka7275da02018-02-28 07:15:55 +00002080 case QualType::DK_objc_strong_lifetime:
2081 // Use objc_storeStrong for __strong direct captures; the
2082 // dynamic tools really like it when we do this.
2083 return std::make_pair(BlockCaptureEntityKind::ARCStrong,
2084 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2085 case QualType::DK_objc_weak_lifetime:
2086 // Support __weak direct captures.
2087 return std::make_pair(BlockCaptureEntityKind::ARCWeak,
2088 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2089 case QualType::DK_nontrivial_c_struct:
2090 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
2091 BlockFieldFlags());
2092 case QualType::DK_none: {
2093 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2094 if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
2095 !LangOpts.ObjCAutoRefCount)
2096 return std::make_pair(BlockCaptureEntityKind::BlockObject,
2097 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2098 // Otherwise, we have nothing to do.
2099 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002100 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00002101 }
Nico Weberb3897eb2018-02-28 19:28:47 +00002102 llvm_unreachable("after exhaustive DestructionKind switch");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002103}
2104
John McCallf593b102013-01-22 03:56:22 +00002105/// Generate the destroy-helper function for a block closure object:
2106/// static void block_destroy_helper(block_t *theBlock);
2107///
2108/// Note that this destroys a heap-allocated block closure object;
2109/// it should not be confused with a 'byref destroy helper', which
2110/// destroys the heap-allocated contents of an individual __block
2111/// variable.
John McCall351762c2011-02-07 10:33:21 +00002112llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00002113CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002114 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002115 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002116 std::string FuncName =
2117 getCopyDestroyHelperFuncName(DestroyedCaptures, blockInfo.BlockAlign,
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002118 CaptureStrKind::DisposeHelper, CGM);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002119
2120 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
Akira Hatanaka936240c2018-08-14 00:15:42 +00002121 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002122
John McCall351762c2011-02-07 10:33:21 +00002123 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00002124
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002125 QualType ReturnTy = C.VoidTy;
2126
John McCall351762c2011-02-07 10:33:21 +00002127 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002128 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00002129 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002130
John McCallc56a8b32016-03-11 04:30:31 +00002131 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002132 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00002133
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002134 // FIXME: We'd like to put these into a mergable by content, with
2135 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00002136 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00002137
2138 llvm::Function *Fn =
Akira Hatanaka9978da32018-08-10 15:09:24 +00002139 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2140 FuncName, &CGM.getModule());
Saleem Abdulrasool89628922019-02-22 16:29:50 +00002141 if (CGM.supportsCOMDAT())
2142 Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
Mike Stump0c743272009-03-06 01:33:24 +00002143
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002144 IdentifierInfo *II = &C.Idents.get(FuncName);
Mike Stump0c743272009-03-06 01:33:24 +00002145
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002146 SmallVector<QualType, 1> ArgTys;
2147 ArgTys.push_back(C.VoidPtrTy);
2148 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
2149
2150 FunctionDecl *FD = FunctionDecl::Create(
2151 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
2152 FunctionTy, nullptr, SC_Static, false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002153
Akira Hatanaka9978da32018-08-10 15:09:24 +00002154 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2155 CGM);
Adrian Prantl314b9272020-03-04 08:34:20 -08002156 // This is necessary to avoid inheriting the previous line number.
2157 FD->setImplicit();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002158 StartFunction(FD, ReturnTy, Fn, FI, args);
Akira Hatanaka9978da32018-08-10 15:09:24 +00002159 markAsIgnoreThreadCheckingAtRuntime(Fn);
2160
Adrian Prantl314b9272020-03-04 08:34:20 -08002161 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00002162
Chris Lattner2192fe52011-07-18 04:24:23 +00002163 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00002164
Alexey Bataev56223232017-06-09 13:40:18 +00002165 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00002166 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00002167 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00002168
John McCallad7c5c12011-02-08 08:22:06 +00002169 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00002170
Alex Lorenze08e5bc2017-03-06 16:23:04 +00002171 for (const auto &DestroyedCapture : DestroyedCaptures) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002172 const BlockDecl::Capture &CI = *DestroyedCapture.CI;
2173 const CGBlockInfo::Capture &capture = *DestroyedCapture.Capture;
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002174 BlockFieldFlags flags = DestroyedCapture.DisposeFlags;
John McCall351762c2011-02-07 10:33:21 +00002175
James Y Knight751fe282019-02-09 22:22:28 +00002176 Address srcField = Builder.CreateStructGEP(src, capture.getIndex());
John McCall351762c2011-02-07 10:33:21 +00002177
Akira Hatanaka2ec36f02018-08-17 15:46:07 +00002178 pushCaptureCleanup(DestroyedCapture.DisposeKind, srcField,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002179 CI.getVariable()->getType(), flags,
2180 /*ForCopyHelper*/ false, CI.getVariable(), *this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00002181 }
2182
John McCall351762c2011-02-07 10:33:21 +00002183 cleanups.ForceCleanup();
2184
John McCallad7c5c12011-02-08 08:22:06 +00002185 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00002186
John McCalle3dc1702011-02-15 09:22:45 +00002187 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00002188}
2189
John McCallf9b056b2011-03-31 08:03:29 +00002190namespace {
2191
2192/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00002193class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00002194 BlockFieldFlags Flags;
2195
2196public:
2197 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00002198 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00002199
John McCall7f416cc2015-09-08 08:05:57 +00002200 void emitCopy(CodeGenFunction &CGF, Address destField,
2201 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00002202 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
2203
2204 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
2205 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2206
2207 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2208
2209 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
James Y Knight9871db02019-02-05 16:42:33 +00002210 llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00002211
John McCall7f416cc2015-09-08 08:05:57 +00002212 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00002213 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00002214 }
2215
John McCall7f416cc2015-09-08 08:05:57 +00002216 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002217 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
2218 llvm::Value *value = CGF.Builder.CreateLoad(field);
2219
Akira Hatanaka9978da32018-08-10 15:09:24 +00002220 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
John McCallf9b056b2011-03-31 08:03:29 +00002221 }
2222
Craig Topper4f12f102014-03-12 06:41:41 +00002223 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002224 id.AddInteger(Flags.getBitMask());
2225 }
2226};
2227
John McCall31168b02011-06-15 23:02:42 +00002228/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00002229class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00002230public:
John McCall7f416cc2015-09-08 08:05:57 +00002231 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00002232
John McCall7f416cc2015-09-08 08:05:57 +00002233 void emitCopy(CodeGenFunction &CGF, Address destField,
2234 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00002235 CGF.EmitARCMoveWeak(destField, srcField);
2236 }
2237
John McCall7f416cc2015-09-08 08:05:57 +00002238 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00002239 CGF.EmitARCDestroyWeak(field);
2240 }
2241
Craig Topper4f12f102014-03-12 06:41:41 +00002242 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00002243 // 0 is distinguishable from all pointers and byref flags
2244 id.AddInteger(0);
2245 }
2246};
2247
2248/// Emits the copy/dispose helpers for an ARC __block __strong variable
2249/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00002250class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00002251public:
John McCall7f416cc2015-09-08 08:05:57 +00002252 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00002253
John McCall7f416cc2015-09-08 08:05:57 +00002254 void emitCopy(CodeGenFunction &CGF, Address destField,
2255 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00002256 // Do a "move" by copying the value and then zeroing out the old
2257 // variable.
2258
John McCall7f416cc2015-09-08 08:05:57 +00002259 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
Fangrui Song6907ce22018-07-30 19:24:48 +00002260
John McCall31168b02011-06-15 23:02:42 +00002261 llvm::Value *null =
2262 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00002263
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00002264 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002265 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00002266 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2267 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2268 return;
2269 }
John McCall7f416cc2015-09-08 08:05:57 +00002270 CGF.Builder.CreateStore(value, destField);
2271 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00002272 }
2273
John McCall7f416cc2015-09-08 08:05:57 +00002274 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00002275 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00002276 }
2277
Craig Topper4f12f102014-03-12 06:41:41 +00002278 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00002279 // 1 is distinguishable from all pointers and byref flags
2280 id.AddInteger(1);
2281 }
2282};
2283
John McCall3a237aa2011-11-09 03:17:26 +00002284/// Emits the copy/dispose helpers for an ARC __block __strong
2285/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00002286class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00002287public:
John McCall7f416cc2015-09-08 08:05:57 +00002288 ARCStrongBlockByrefHelpers(CharUnits alignment)
2289 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00002290
John McCall7f416cc2015-09-08 08:05:57 +00002291 void emitCopy(CodeGenFunction &CGF, Address destField,
2292 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00002293 // Do the copy with objc_retainBlock; that's all that
2294 // _Block_object_assign would do anyway, and we'd have to pass the
2295 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00002296 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00002297 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00002298 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00002299 }
2300
John McCall7f416cc2015-09-08 08:05:57 +00002301 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00002302 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00002303 }
2304
Craig Topper4f12f102014-03-12 06:41:41 +00002305 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00002306 // 2 is distinguishable from all pointers and byref flags
2307 id.AddInteger(2);
2308 }
2309};
2310
John McCallf9b056b2011-03-31 08:03:29 +00002311/// Emits the copy/dispose helpers for a __block variable with a
2312/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00002313class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00002314 QualType VarType;
2315 const Expr *CopyExpr;
2316
2317public:
2318 CXXByrefHelpers(CharUnits alignment, QualType type,
2319 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00002320 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00002321
Craig Topper8a13c412014-05-21 05:09:00 +00002322 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00002323 void emitCopy(CodeGenFunction &CGF, Address destField,
2324 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00002325 if (!CopyExpr) return;
2326 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2327 }
2328
John McCall7f416cc2015-09-08 08:05:57 +00002329 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00002330 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2331 CGF.PushDestructorCleanup(VarType, field);
2332 CGF.PopCleanupBlocks(cleanupDepth);
2333 }
2334
Craig Topper4f12f102014-03-12 06:41:41 +00002335 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00002336 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2337 }
2338};
Akira Hatanaka7275da02018-02-28 07:15:55 +00002339
2340/// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2341/// C struct.
2342class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2343 QualType VarType;
2344
2345public:
2346 NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2347 : BlockByrefHelpers(alignment), VarType(type) {}
2348
2349 void emitCopy(CodeGenFunction &CGF, Address destField,
2350 Address srcField) override {
2351 CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2352 CGF.MakeAddrLValue(srcField, VarType));
2353 }
2354
2355 bool needsDispose() const override {
2356 return VarType.isDestructedType();
2357 }
2358
2359 void emitDispose(CodeGenFunction &CGF, Address field) override {
2360 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2361 CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2362 CGF.PopCleanupBlocks(cleanupDepth);
2363 }
2364
2365 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2366 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2367 }
2368};
John McCallf9b056b2011-03-31 08:03:29 +00002369} // end anonymous namespace
2370
2371static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00002372generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2373 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002374 ASTContext &Context = CGF.getContext();
2375
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002376 QualType ReturnTy = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002377
John McCalla738c252011-03-09 04:27:21 +00002378 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002379 ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00002380 args.push_back(&Dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00002381
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002382 ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00002383 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002384
John McCallc56a8b32016-03-11 04:30:31 +00002385 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002386 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002387
John McCall7f416cc2015-09-08 08:05:57 +00002388 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002389
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002390 // FIXME: We'd like to put these into a mergable by content, with
2391 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002392 llvm::Function *Fn =
2393 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00002394 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002395
2396 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002397 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002398
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002399 SmallVector<QualType, 2> ArgTys;
2400 ArgTys.push_back(Context.VoidPtrTy);
2401 ArgTys.push_back(Context.VoidPtrTy);
2402 QualType FunctionTy = Context.getFunctionType(ReturnTy, ArgTys, {});
2403
2404 FunctionDecl *FD = FunctionDecl::Create(
2405 Context, Context.getTranslationUnitDecl(), SourceLocation(),
2406 SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
John McCall31168b02011-06-15 23:02:42 +00002407
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002408 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002409
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002410 CGF.StartFunction(FD, ReturnTy, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00002411
John McCall7f416cc2015-09-08 08:05:57 +00002412 if (generator.needsCopy()) {
2413 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00002414
John McCallf9b056b2011-03-31 08:03:29 +00002415 // dst->x
Alexey Bataev56223232017-06-09 13:40:18 +00002416 Address destField = CGF.GetAddrOfLocalVar(&Dst);
John McCall7f416cc2015-09-08 08:05:57 +00002417 destField = Address(CGF.Builder.CreateLoad(destField),
2418 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002419 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002420 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2421 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002422
John McCallf9b056b2011-03-31 08:03:29 +00002423 // src->x
Alexey Bataev56223232017-06-09 13:40:18 +00002424 Address srcField = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002425 srcField = Address(CGF.Builder.CreateLoad(srcField),
2426 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00002427 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00002428 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2429 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00002430
John McCall7f416cc2015-09-08 08:05:57 +00002431 generator.emitCopy(CGF, destField, srcField);
Fangrui Song6907ce22018-07-30 19:24:48 +00002432 }
John McCallf9b056b2011-03-31 08:03:29 +00002433
2434 CGF.FinishFunction();
2435
2436 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002437}
2438
John McCallf9b056b2011-03-31 08:03:29 +00002439/// Build the copy helper for a __block variable.
2440static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002441 const BlockByrefInfo &byrefInfo,
2442 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002443 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002444 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002445}
2446
2447/// Generate code for a __block variable's dispose helper.
2448static llvm::Constant *
2449generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002450 const BlockByrefInfo &byrefInfo,
2451 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002452 ASTContext &Context = CGF.getContext();
2453 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002454
John McCalla738c252011-03-09 04:27:21 +00002455 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002456 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2457 ImplicitParamDecl::Other);
2458 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002459
John McCallc56a8b32016-03-11 04:30:31 +00002460 const CGFunctionInfo &FI =
2461 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002462
John McCall7f416cc2015-09-08 08:05:57 +00002463 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002464
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002465 // FIXME: We'd like to put these into a mergable by content, with
2466 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002467 llvm::Function *Fn =
2468 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00002469 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00002470 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002471
2472 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002473 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002474
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002475 SmallVector<QualType, 1> ArgTys;
2476 ArgTys.push_back(Context.VoidPtrTy);
2477 QualType FunctionTy = Context.getFunctionType(R, ArgTys, {});
2478
2479 FunctionDecl *FD = FunctionDecl::Create(
2480 Context, Context.getTranslationUnitDecl(), SourceLocation(),
2481 SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002482
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002483 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002484
Adrian Prantl22e66b42014-04-11 01:13:04 +00002485 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00002486
John McCall7f416cc2015-09-08 08:05:57 +00002487 if (generator.needsDispose()) {
Alexey Bataev56223232017-06-09 13:40:18 +00002488 Address addr = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002489 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2490 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2491 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2492 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00002493
John McCall7f416cc2015-09-08 08:05:57 +00002494 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00002495 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002496
John McCallf9b056b2011-03-31 08:03:29 +00002497 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00002498
John McCallf9b056b2011-03-31 08:03:29 +00002499 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002500}
2501
John McCallf9b056b2011-03-31 08:03:29 +00002502/// Build the dispose helper for a __block variable.
2503static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002504 const BlockByrefInfo &byrefInfo,
2505 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002506 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002507 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002508}
2509
John McCallf593b102013-01-22 03:56:22 +00002510/// Lazily build the copy and dispose helpers for a __block variable
2511/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00002512template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00002513static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2514 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002515 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00002516 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00002517
2518 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00002519 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00002520 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2521 if (node) return static_cast<T*>(node);
2522
John McCall7f416cc2015-09-08 08:05:57 +00002523 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2524 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002525
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00002526 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00002527 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2528 return copy;
2529}
2530
John McCallf593b102013-01-22 03:56:22 +00002531/// Build the copy and dispose helpers for the given __block variable
2532/// emission. Places the helpers in the global cache. Returns null
2533/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00002534BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00002535CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00002536 const AutoVarEmission &emission) {
2537 const VarDecl &var = *emission.Variable;
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002538 assert(var.isEscapingByref() &&
2539 "only escaping __block variables need byref helpers");
2540
John McCallf9b056b2011-03-31 08:03:29 +00002541 QualType type = var.getType();
2542
John McCall7f416cc2015-09-08 08:05:57 +00002543 auto &byrefInfo = getBlockByrefInfo(&var);
2544
2545 // The alignment we care about for the purposes of uniquing byref
2546 // helpers is the alignment of the actual byref value field.
2547 CharUnits valueAlignment =
2548 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00002549
John McCallf9b056b2011-03-31 08:03:29 +00002550 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00002551 const Expr *copyExpr =
2552 CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
Craig Topper8a13c412014-05-21 05:09:00 +00002553 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002554
David Blaikie92551612015-08-13 23:53:09 +00002555 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00002556 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00002557 }
2558
Akira Hatanaka7275da02018-02-28 07:15:55 +00002559 // If type is a non-trivial C struct type that is non-trivial to
2560 // destructly move or destroy, build the copy and dispose helpers.
2561 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2562 type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2563 return ::buildByrefHelpers(
2564 CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2565
John McCall31168b02011-06-15 23:02:42 +00002566 // Otherwise, if we don't have a retainable type, there's nothing to do.
2567 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00002568 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002569
2570 Qualifiers qs = type.getQualifiers();
2571
2572 // If we have lifetime, that dominates.
2573 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00002574 switch (lifetime) {
2575 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2576
2577 // These are just bits as far as the runtime is concerned.
2578 case Qualifiers::OCL_ExplicitNone:
2579 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00002580 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002581
2582 // Tell the runtime that this is ARC __weak, called by the
2583 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002584 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002585 return ::buildByrefHelpers(CGM, byrefInfo,
2586 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002587
2588 // ARC __strong __block variables need to be retained.
2589 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002590 // Block pointers need to be copied, and there's no direct
2591 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002592 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002593 return ::buildByrefHelpers(CGM, byrefInfo,
2594 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002595
2596 // Otherwise, we transfer ownership of the retain from the stack
2597 // to the heap.
2598 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002599 return ::buildByrefHelpers(CGM, byrefInfo,
2600 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002601 }
2602 }
2603 llvm_unreachable("fell out of lifetime switch!");
2604 }
2605
John McCallf9b056b2011-03-31 08:03:29 +00002606 BlockFieldFlags flags;
2607 if (type->isBlockPointerType()) {
2608 flags |= BLOCK_FIELD_IS_BLOCK;
Fangrui Song6907ce22018-07-30 19:24:48 +00002609 } else if (CGM.getContext().isObjCNSObjectType(type) ||
John McCallf9b056b2011-03-31 08:03:29 +00002610 type->isObjCObjectPointerType()) {
2611 flags |= BLOCK_FIELD_IS_OBJECT;
2612 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002613 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002614 }
2615
2616 if (type.isObjCGCWeak())
2617 flags |= BLOCK_FIELD_IS_WEAK;
2618
John McCall7f416cc2015-09-08 08:05:57 +00002619 return ::buildByrefHelpers(CGM, byrefInfo,
2620 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002621}
2622
John McCall7f416cc2015-09-08 08:05:57 +00002623Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2624 const VarDecl *var,
2625 bool followForward) {
2626 auto &info = getBlockByrefInfo(var);
2627 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002628}
2629
John McCall7f416cc2015-09-08 08:05:57 +00002630Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2631 const BlockByrefInfo &info,
2632 bool followForward,
2633 const llvm::Twine &name) {
2634 // Chase the forwarding address if requested.
2635 if (followForward) {
James Y Knight751fe282019-02-09 22:22:28 +00002636 Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding");
John McCall7f416cc2015-09-08 08:05:57 +00002637 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2638 }
2639
James Y Knight751fe282019-02-09 22:22:28 +00002640 return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name);
John McCall73064872011-03-31 01:59:53 +00002641}
2642
John McCall7f416cc2015-09-08 08:05:57 +00002643/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002644/// into:
2645///
2646/// struct {
2647/// void *__isa;
2648/// void *__forwarding;
2649/// int32_t __flags;
2650/// int32_t __size;
2651/// void *__copy_helper; // only if needed
2652/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002653/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002654/// char padding[X]; // only if needed
2655/// T x;
2656/// } x
2657///
John McCall7f416cc2015-09-08 08:05:57 +00002658const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2659 auto it = BlockByrefInfos.find(D);
2660 if (it != BlockByrefInfos.end())
2661 return it->second;
John McCall73064872011-03-31 01:59:53 +00002662
John McCall7f416cc2015-09-08 08:05:57 +00002663 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002664 llvm::StructType::create(getLLVMContext(),
2665 "struct.__block_byref_" + D->getNameAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00002666
John McCall7f416cc2015-09-08 08:05:57 +00002667 QualType Ty = D->getType();
2668
2669 CharUnits size;
2670 SmallVector<llvm::Type *, 8> types;
Fangrui Song6907ce22018-07-30 19:24:48 +00002671
John McCall73064872011-03-31 01:59:53 +00002672 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002673 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002674 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002675
John McCall73064872011-03-31 01:59:53 +00002676 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002677 types.push_back(llvm::PointerType::getUnqual(byrefType));
2678 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002679
John McCall73064872011-03-31 01:59:53 +00002680 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002681 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002682 size += CharUnits::fromQuantity(4);
Fangrui Song6907ce22018-07-30 19:24:48 +00002683
John McCall73064872011-03-31 01:59:53 +00002684 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002685 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002686 size += CharUnits::fromQuantity(4);
2687
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002688 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002689 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2690 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002691 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002692 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002693 size += getPointerSize();
Fangrui Song6907ce22018-07-30 19:24:48 +00002694
John McCall73064872011-03-31 01:59:53 +00002695 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002696 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002697 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002698 }
John McCall7f416cc2015-09-08 08:05:57 +00002699
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002700 bool HasByrefExtendedLayout = false;
2701 Qualifiers::ObjCLifetime Lifetime;
2702 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002703 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002704 /// void *__byref_variable_layout;
2705 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002706 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002707 }
2708
2709 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002710 llvm::Type *varTy = ConvertTypeForMem(Ty);
2711
2712 bool packed = false;
2713 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002714 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002715
2716 // We may have to insert padding.
2717 if (varOffset != size) {
2718 llvm::Type *paddingTy =
2719 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2720
2721 types.push_back(paddingTy);
2722 size = varOffset;
2723
2724 // Conversely, we might have to prevent LLVM from inserting padding.
2725 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2726 > varAlign.getQuantity()) {
2727 packed = true;
2728 }
2729 types.push_back(varTy);
2730
2731 byrefType->setBody(types, packed);
2732
2733 BlockByrefInfo info;
2734 info.Type = byrefType;
2735 info.FieldIndex = types.size() - 1;
2736 info.FieldOffset = varOffset;
2737 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2738
2739 auto pair = BlockByrefInfos.insert({D, info});
2740 assert(pair.second && "info was inserted recursively?");
2741 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002742}
2743
2744/// Initialize the structural components of a __block variable, i.e.
2745/// everything but the actual object.
2746void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002747 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002748 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002749
John McCallf9b056b2011-03-31 08:03:29 +00002750 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002751 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002752 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2753
2754 unsigned nextHeaderIndex = 0;
2755 CharUnits nextHeaderOffset;
2756 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2757 const Twine &name) {
James Y Knight751fe282019-02-09 22:22:28 +00002758 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
John McCall7f416cc2015-09-08 08:05:57 +00002759 Builder.CreateStore(value, fieldAddr);
2760
2761 nextHeaderIndex++;
2762 nextHeaderOffset += fieldSize;
2763 };
John McCallf9b056b2011-03-31 08:03:29 +00002764
2765 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002766 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002767
2768 const VarDecl &D = *emission.Variable;
2769 QualType type = D.getType();
2770
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002771 bool HasByrefExtendedLayout;
2772 Qualifiers::ObjCLifetime ByrefLifetime;
2773 bool ByRefHasLifetime =
2774 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002775
John McCallf9b056b2011-03-31 08:03:29 +00002776 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002777
2778 // Initialize the 'isa', which is just 0 or 1.
2779 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002780 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002781 isa = 1;
2782 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002783 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002784
2785 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002786 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002787
2788 // Blocks ABI:
2789 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002790 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002791 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002792 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2793 if (ByRefHasLifetime) {
2794 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2795 else switch (ByrefLifetime) {
2796 case Qualifiers::OCL_Strong:
2797 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2798 break;
2799 case Qualifiers::OCL_Weak:
2800 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2801 break;
2802 case Qualifiers::OCL_ExplicitNone:
2803 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2804 break;
2805 case Qualifiers::OCL_None:
2806 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2807 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2808 break;
2809 default:
2810 break;
2811 }
2812 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2813 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2814 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2815 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2816 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2817 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2818 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2819 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2820 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2821 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2822 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2823 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2824 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2825 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2826 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2827 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2828 }
2829 printf("\n");
2830 }
2831 }
John McCall7f416cc2015-09-08 08:05:57 +00002832 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2833 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002834
John McCallf9b056b2011-03-31 08:03:29 +00002835 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2836 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002837 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002838
John McCallf9b056b2011-03-31 08:03:29 +00002839 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002840 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2841 "byref.copyHelper");
2842 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2843 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002844 }
John McCall7f416cc2015-09-08 08:05:57 +00002845
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002846 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002847 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2848 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002849 }
John McCall73064872011-03-31 01:59:53 +00002850}
2851
Akira Hatanaka9978da32018-08-10 15:09:24 +00002852void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2853 bool CanThrow) {
James Y Knight9871db02019-02-05 16:42:33 +00002854 llvm::FunctionCallee F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002855 llvm::Value *args[] = {
2856 Builder.CreateBitCast(V, Int8PtrTy),
2857 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2858 };
Akira Hatanaka9978da32018-08-10 15:09:24 +00002859
2860 if (CanThrow)
2861 EmitRuntimeCallOrInvoke(F, args);
2862 else
2863 EmitNounwindRuntimeCall(F, args);
Mike Stump626aecc2009-03-05 01:23:13 +00002864}
John McCall73064872011-03-31 01:59:53 +00002865
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002866void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2867 BlockFieldFlags Flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002868 bool LoadBlockVarAddr, bool CanThrow) {
2869 EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2870 CanThrow);
John McCall73064872011-03-31 01:59:53 +00002871}
John McCall7959fee2011-09-09 20:41:01 +00002872
2873/// Adjust the declaration of something from the blocks API.
2874static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2875 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002876 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002877
2878 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2879 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2880 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2881 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2882
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002883 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2884 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2885 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002886
2887 const NamedDecl *ND = nullptr;
2888 for (const auto &Result : DC->lookup(&II))
2889 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2890 (ND = dyn_cast<VarDecl>(Result)))
2891 break;
2892
2893 // TODO: support static blocks runtime
2894 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2895 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2896 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2897 } else {
2898 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2899 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2900 }
2901 }
2902
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002903 if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2904 GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002905 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Rafael Espindola3c8a39c2018-03-14 18:19:26 +00002906
2907 CGM.setDSOLocal(GV);
John McCall7959fee2011-09-09 20:41:01 +00002908}
2909
James Y Knight9871db02019-02-05 16:42:33 +00002910llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
John McCall7959fee2011-09-09 20:41:01 +00002911 if (BlockObjectDispose)
2912 return BlockObjectDispose;
2913
2914 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2915 llvm::FunctionType *fty
2916 = llvm::FunctionType::get(VoidTy, args, false);
2917 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
James Y Knight9871db02019-02-05 16:42:33 +00002918 configureBlocksRuntimeObject(
2919 *this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
John McCall7959fee2011-09-09 20:41:01 +00002920 return BlockObjectDispose;
2921}
2922
James Y Knight9871db02019-02-05 16:42:33 +00002923llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
John McCall7959fee2011-09-09 20:41:01 +00002924 if (BlockObjectAssign)
2925 return BlockObjectAssign;
2926
2927 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2928 llvm::FunctionType *fty
2929 = llvm::FunctionType::get(VoidTy, args, false);
2930 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
James Y Knight9871db02019-02-05 16:42:33 +00002931 configureBlocksRuntimeObject(
2932 *this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
John McCall7959fee2011-09-09 20:41:01 +00002933 return BlockObjectAssign;
2934}
2935
2936llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2937 if (NSConcreteGlobalBlock)
2938 return NSConcreteGlobalBlock;
2939
2940 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002941 Int8PtrTy->getPointerTo(),
2942 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002943 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2944 return NSConcreteGlobalBlock;
2945}
2946
2947llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2948 if (NSConcreteStackBlock)
2949 return NSConcreteStackBlock;
2950
2951 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002952 Int8PtrTy->getPointerTo(),
2953 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002954 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002955 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002956}