xref: /openbsd-src/gnu/llvm/clang/lib/CodeGen/CGBlocks.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This contains code to emit blocks.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "CGBlocks.h"
14e5dd7070Spatrick #include "CGCXXABI.h"
15e5dd7070Spatrick #include "CGDebugInfo.h"
16e5dd7070Spatrick #include "CGObjCRuntime.h"
17e5dd7070Spatrick #include "CGOpenCLRuntime.h"
18e5dd7070Spatrick #include "CodeGenFunction.h"
19e5dd7070Spatrick #include "CodeGenModule.h"
20e5dd7070Spatrick #include "ConstantEmitter.h"
21e5dd7070Spatrick #include "TargetInfo.h"
22e5dd7070Spatrick #include "clang/AST/Attr.h"
23e5dd7070Spatrick #include "clang/AST/DeclObjC.h"
24e5dd7070Spatrick #include "clang/CodeGen/ConstantInitBuilder.h"
25e5dd7070Spatrick #include "llvm/ADT/SmallSet.h"
26e5dd7070Spatrick #include "llvm/IR/DataLayout.h"
27e5dd7070Spatrick #include "llvm/IR/Module.h"
28e5dd7070Spatrick #include "llvm/Support/ScopedPrinter.h"
29e5dd7070Spatrick #include <algorithm>
30e5dd7070Spatrick #include <cstdio>
31e5dd7070Spatrick 
32e5dd7070Spatrick using namespace clang;
33e5dd7070Spatrick using namespace CodeGen;
34e5dd7070Spatrick 
CGBlockInfo(const BlockDecl * block,StringRef name)35e5dd7070Spatrick CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
36e5dd7070Spatrick     : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
37*12c85518Srobert       NoEscape(false), HasCXXObject(false), UsesStret(false),
38*12c85518Srobert       HasCapturedVariableLayout(false), CapturesNonExternalType(false),
39*12c85518Srobert       LocalAddress(Address::invalid()), StructureType(nullptr), Block(block) {
40e5dd7070Spatrick 
41e5dd7070Spatrick   // Skip asm prefix, if any.  'name' is usually taken directly from
42e5dd7070Spatrick   // the mangled name of the enclosing function.
43e5dd7070Spatrick   if (!name.empty() && name[0] == '\01')
44e5dd7070Spatrick     name = name.substr(1);
45e5dd7070Spatrick }
46e5dd7070Spatrick 
47e5dd7070Spatrick // Anchor the vtable to this translation unit.
~BlockByrefHelpers()48e5dd7070Spatrick BlockByrefHelpers::~BlockByrefHelpers() {}
49e5dd7070Spatrick 
50e5dd7070Spatrick /// Build the given block as a global block.
51e5dd7070Spatrick static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
52e5dd7070Spatrick                                         const CGBlockInfo &blockInfo,
53e5dd7070Spatrick                                         llvm::Constant *blockFn);
54e5dd7070Spatrick 
55e5dd7070Spatrick /// Build the helper function to copy a block.
buildCopyHelper(CodeGenModule & CGM,const CGBlockInfo & blockInfo)56e5dd7070Spatrick static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
57e5dd7070Spatrick                                        const CGBlockInfo &blockInfo) {
58e5dd7070Spatrick   return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
59e5dd7070Spatrick }
60e5dd7070Spatrick 
61e5dd7070Spatrick /// Build the helper function to dispose of a block.
buildDisposeHelper(CodeGenModule & CGM,const CGBlockInfo & blockInfo)62e5dd7070Spatrick static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
63e5dd7070Spatrick                                           const CGBlockInfo &blockInfo) {
64e5dd7070Spatrick   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
65e5dd7070Spatrick }
66e5dd7070Spatrick 
67e5dd7070Spatrick namespace {
68e5dd7070Spatrick 
69e5dd7070Spatrick /// Represents a captured entity that requires extra operations in order for
70e5dd7070Spatrick /// this entity to be copied or destroyed correctly.
71e5dd7070Spatrick struct BlockCaptureManagedEntity {
72e5dd7070Spatrick   BlockCaptureEntityKind CopyKind, DisposeKind;
73e5dd7070Spatrick   BlockFieldFlags CopyFlags, DisposeFlags;
74e5dd7070Spatrick   const BlockDecl::Capture *CI;
75e5dd7070Spatrick   const CGBlockInfo::Capture *Capture;
76e5dd7070Spatrick 
BlockCaptureManagedEntity__anon3298161d0111::BlockCaptureManagedEntity77e5dd7070Spatrick   BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
78e5dd7070Spatrick                             BlockCaptureEntityKind DisposeType,
79e5dd7070Spatrick                             BlockFieldFlags CopyFlags,
80e5dd7070Spatrick                             BlockFieldFlags DisposeFlags,
81e5dd7070Spatrick                             const BlockDecl::Capture &CI,
82e5dd7070Spatrick                             const CGBlockInfo::Capture &Capture)
83e5dd7070Spatrick       : CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
84e5dd7070Spatrick         DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
85e5dd7070Spatrick 
operator <__anon3298161d0111::BlockCaptureManagedEntity86e5dd7070Spatrick   bool operator<(const BlockCaptureManagedEntity &Other) const {
87e5dd7070Spatrick     return Capture->getOffset() < Other.Capture->getOffset();
88e5dd7070Spatrick   }
89e5dd7070Spatrick };
90e5dd7070Spatrick 
91e5dd7070Spatrick enum class CaptureStrKind {
92e5dd7070Spatrick   // String for the copy helper.
93e5dd7070Spatrick   CopyHelper,
94e5dd7070Spatrick   // String for the dispose helper.
95e5dd7070Spatrick   DisposeHelper,
96e5dd7070Spatrick   // Merge the strings for the copy helper and dispose helper.
97e5dd7070Spatrick   Merged
98e5dd7070Spatrick };
99e5dd7070Spatrick 
100e5dd7070Spatrick } // end anonymous namespace
101e5dd7070Spatrick 
102*12c85518Srobert static std::string getBlockCaptureStr(const CGBlockInfo::Capture &Cap,
103e5dd7070Spatrick                                       CaptureStrKind StrKind,
104e5dd7070Spatrick                                       CharUnits BlockAlignment,
105e5dd7070Spatrick                                       CodeGenModule &CGM);
106e5dd7070Spatrick 
getBlockDescriptorName(const CGBlockInfo & BlockInfo,CodeGenModule & CGM)107e5dd7070Spatrick static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
108e5dd7070Spatrick                                           CodeGenModule &CGM) {
109e5dd7070Spatrick   std::string Name = "__block_descriptor_";
110e5dd7070Spatrick   Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
111e5dd7070Spatrick 
112*12c85518Srobert   if (BlockInfo.NeedsCopyDispose) {
113e5dd7070Spatrick     if (CGM.getLangOpts().Exceptions)
114e5dd7070Spatrick       Name += "e";
115e5dd7070Spatrick     if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
116e5dd7070Spatrick       Name += "a";
117e5dd7070Spatrick     Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
118e5dd7070Spatrick 
119*12c85518Srobert     for (auto &Cap : BlockInfo.SortedCaptures) {
120*12c85518Srobert       if (Cap.isConstantOrTrivial())
121*12c85518Srobert         continue;
122e5dd7070Spatrick 
123*12c85518Srobert       Name += llvm::to_string(Cap.getOffset().getQuantity());
124e5dd7070Spatrick 
125*12c85518Srobert       if (Cap.CopyKind == Cap.DisposeKind) {
126e5dd7070Spatrick         // If CopyKind and DisposeKind are the same, merge the capture
127e5dd7070Spatrick         // information.
128*12c85518Srobert         assert(Cap.CopyKind != BlockCaptureEntityKind::None &&
129e5dd7070Spatrick                "shouldn't see BlockCaptureManagedEntity that is None");
130*12c85518Srobert         Name += getBlockCaptureStr(Cap, CaptureStrKind::Merged,
131e5dd7070Spatrick                                    BlockInfo.BlockAlign, CGM);
132e5dd7070Spatrick       } else {
133e5dd7070Spatrick         // If CopyKind and DisposeKind are not the same, which can happen when
134e5dd7070Spatrick         // either Kind is None or the captured object is a __strong block,
135e5dd7070Spatrick         // concatenate the copy and dispose strings.
136*12c85518Srobert         Name += getBlockCaptureStr(Cap, CaptureStrKind::CopyHelper,
137e5dd7070Spatrick                                    BlockInfo.BlockAlign, CGM);
138*12c85518Srobert         Name += getBlockCaptureStr(Cap, CaptureStrKind::DisposeHelper,
139e5dd7070Spatrick                                    BlockInfo.BlockAlign, CGM);
140e5dd7070Spatrick       }
141e5dd7070Spatrick     }
142e5dd7070Spatrick     Name += "_";
143e5dd7070Spatrick   }
144e5dd7070Spatrick 
145e5dd7070Spatrick   std::string TypeAtEncoding =
146e5dd7070Spatrick       CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
147e5dd7070Spatrick   /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
148e5dd7070Spatrick   /// a separator between symbol name and symbol version.
149e5dd7070Spatrick   std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
150e5dd7070Spatrick   Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
151e5dd7070Spatrick   Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
152e5dd7070Spatrick   return Name;
153e5dd7070Spatrick }
154e5dd7070Spatrick 
155e5dd7070Spatrick /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
156e5dd7070Spatrick /// buildBlockDescriptor is accessed from 5th field of the Block_literal
157e5dd7070Spatrick /// meta-data and contains stationary information about the block literal.
158e5dd7070Spatrick /// Its definition will have 4 (or optionally 6) words.
159e5dd7070Spatrick /// \code
160e5dd7070Spatrick /// struct Block_descriptor {
161e5dd7070Spatrick ///   unsigned long reserved;
162e5dd7070Spatrick ///   unsigned long size;  // size of Block_literal metadata in bytes.
163e5dd7070Spatrick ///   void *copy_func_helper_decl;  // optional copy helper.
164e5dd7070Spatrick ///   void *destroy_func_decl; // optional destructor helper.
165e5dd7070Spatrick ///   void *block_method_encoding_address; // @encode for block literal signature.
166e5dd7070Spatrick ///   void *block_layout_info; // encoding of captured block variables.
167e5dd7070Spatrick /// };
168e5dd7070Spatrick /// \endcode
buildBlockDescriptor(CodeGenModule & CGM,const CGBlockInfo & blockInfo)169e5dd7070Spatrick static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
170e5dd7070Spatrick                                             const CGBlockInfo &blockInfo) {
171e5dd7070Spatrick   ASTContext &C = CGM.getContext();
172e5dd7070Spatrick 
173e5dd7070Spatrick   llvm::IntegerType *ulong =
174e5dd7070Spatrick     cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
175e5dd7070Spatrick   llvm::PointerType *i8p = nullptr;
176e5dd7070Spatrick   if (CGM.getLangOpts().OpenCL)
177e5dd7070Spatrick     i8p =
178e5dd7070Spatrick       llvm::Type::getInt8PtrTy(
179e5dd7070Spatrick            CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
180e5dd7070Spatrick   else
181e5dd7070Spatrick     i8p = CGM.VoidPtrTy;
182e5dd7070Spatrick 
183e5dd7070Spatrick   std::string descName;
184e5dd7070Spatrick 
185e5dd7070Spatrick   // If an equivalent block descriptor global variable exists, return it.
186e5dd7070Spatrick   if (C.getLangOpts().ObjC &&
187e5dd7070Spatrick       CGM.getLangOpts().getGC() == LangOptions::NonGC) {
188e5dd7070Spatrick     descName = getBlockDescriptorName(blockInfo, CGM);
189e5dd7070Spatrick     if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
190e5dd7070Spatrick       return llvm::ConstantExpr::getBitCast(desc,
191e5dd7070Spatrick                                             CGM.getBlockDescriptorType());
192e5dd7070Spatrick   }
193e5dd7070Spatrick 
194e5dd7070Spatrick   // If there isn't an equivalent block descriptor global variable, create a new
195e5dd7070Spatrick   // one.
196e5dd7070Spatrick   ConstantInitBuilder builder(CGM);
197e5dd7070Spatrick   auto elements = builder.beginStruct();
198e5dd7070Spatrick 
199e5dd7070Spatrick   // reserved
200e5dd7070Spatrick   elements.addInt(ulong, 0);
201e5dd7070Spatrick 
202e5dd7070Spatrick   // Size
203e5dd7070Spatrick   // FIXME: What is the right way to say this doesn't fit?  We should give
204e5dd7070Spatrick   // a user diagnostic in that case.  Better fix would be to change the
205e5dd7070Spatrick   // API to size_t.
206e5dd7070Spatrick   elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
207e5dd7070Spatrick 
208e5dd7070Spatrick   // Optional copy/dispose helpers.
209e5dd7070Spatrick   bool hasInternalHelper = false;
210*12c85518Srobert   if (blockInfo.NeedsCopyDispose) {
211e5dd7070Spatrick     // copy_func_helper_decl
212e5dd7070Spatrick     llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
213e5dd7070Spatrick     elements.add(copyHelper);
214e5dd7070Spatrick 
215e5dd7070Spatrick     // destroy_func_decl
216e5dd7070Spatrick     llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
217e5dd7070Spatrick     elements.add(disposeHelper);
218e5dd7070Spatrick 
219*12c85518Srobert     if (cast<llvm::Function>(copyHelper->stripPointerCasts())
220*12c85518Srobert             ->hasInternalLinkage() ||
221*12c85518Srobert         cast<llvm::Function>(disposeHelper->stripPointerCasts())
222e5dd7070Spatrick             ->hasInternalLinkage())
223e5dd7070Spatrick       hasInternalHelper = true;
224e5dd7070Spatrick   }
225e5dd7070Spatrick 
226e5dd7070Spatrick   // Signature.  Mandatory ObjC-style method descriptor @encode sequence.
227e5dd7070Spatrick   std::string typeAtEncoding =
228e5dd7070Spatrick     CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
229e5dd7070Spatrick   elements.add(llvm::ConstantExpr::getBitCast(
230e5dd7070Spatrick     CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
231e5dd7070Spatrick 
232e5dd7070Spatrick   // GC layout.
233e5dd7070Spatrick   if (C.getLangOpts().ObjC) {
234e5dd7070Spatrick     if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
235e5dd7070Spatrick       elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
236e5dd7070Spatrick     else
237e5dd7070Spatrick       elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
238e5dd7070Spatrick   }
239e5dd7070Spatrick   else
240e5dd7070Spatrick     elements.addNullPointer(i8p);
241e5dd7070Spatrick 
242e5dd7070Spatrick   unsigned AddrSpace = 0;
243e5dd7070Spatrick   if (C.getLangOpts().OpenCL)
244e5dd7070Spatrick     AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
245e5dd7070Spatrick 
246e5dd7070Spatrick   llvm::GlobalValue::LinkageTypes linkage;
247e5dd7070Spatrick   if (descName.empty()) {
248e5dd7070Spatrick     linkage = llvm::GlobalValue::InternalLinkage;
249e5dd7070Spatrick     descName = "__block_descriptor_tmp";
250e5dd7070Spatrick   } else if (hasInternalHelper) {
251e5dd7070Spatrick     // If either the copy helper or the dispose helper has internal linkage,
252e5dd7070Spatrick     // the block descriptor must have internal linkage too.
253e5dd7070Spatrick     linkage = llvm::GlobalValue::InternalLinkage;
254e5dd7070Spatrick   } else {
255e5dd7070Spatrick     linkage = llvm::GlobalValue::LinkOnceODRLinkage;
256e5dd7070Spatrick   }
257e5dd7070Spatrick 
258e5dd7070Spatrick   llvm::GlobalVariable *global =
259e5dd7070Spatrick       elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
260e5dd7070Spatrick                                      /*constant*/ true, linkage, AddrSpace);
261e5dd7070Spatrick 
262e5dd7070Spatrick   if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
263e5dd7070Spatrick     if (CGM.supportsCOMDAT())
264e5dd7070Spatrick       global->setComdat(CGM.getModule().getOrInsertComdat(descName));
265e5dd7070Spatrick     global->setVisibility(llvm::GlobalValue::HiddenVisibility);
266e5dd7070Spatrick     global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
267e5dd7070Spatrick   }
268e5dd7070Spatrick 
269e5dd7070Spatrick   return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
270e5dd7070Spatrick }
271e5dd7070Spatrick 
272e5dd7070Spatrick /*
273e5dd7070Spatrick   Purely notional variadic template describing the layout of a block.
274e5dd7070Spatrick 
275e5dd7070Spatrick   template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
276e5dd7070Spatrick   struct Block_literal {
277e5dd7070Spatrick     /// Initialized to one of:
278e5dd7070Spatrick     ///   extern void *_NSConcreteStackBlock[];
279e5dd7070Spatrick     ///   extern void *_NSConcreteGlobalBlock[];
280e5dd7070Spatrick     ///
281e5dd7070Spatrick     /// In theory, we could start one off malloc'ed by setting
282e5dd7070Spatrick     /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
283e5dd7070Spatrick     /// this isa:
284e5dd7070Spatrick     ///   extern void *_NSConcreteMallocBlock[];
285e5dd7070Spatrick     struct objc_class *isa;
286e5dd7070Spatrick 
287e5dd7070Spatrick     /// These are the flags (with corresponding bit number) that the
288e5dd7070Spatrick     /// compiler is actually supposed to know about.
289e5dd7070Spatrick     ///  23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
290e5dd7070Spatrick     ///  25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
291e5dd7070Spatrick     ///   descriptor provides copy and dispose helper functions
292e5dd7070Spatrick     ///  26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
293e5dd7070Spatrick     ///   object with a nontrivial destructor or copy constructor
294e5dd7070Spatrick     ///  28. BLOCK_IS_GLOBAL - indicates that the block is allocated
295e5dd7070Spatrick     ///   as global memory
296e5dd7070Spatrick     ///  29. BLOCK_USE_STRET - indicates that the block function
297e5dd7070Spatrick     ///   uses stret, which objc_msgSend needs to know about
298e5dd7070Spatrick     ///  30. BLOCK_HAS_SIGNATURE - indicates that the block has an
299e5dd7070Spatrick     ///   @encoded signature string
300e5dd7070Spatrick     /// And we're not supposed to manipulate these:
301e5dd7070Spatrick     ///  24. BLOCK_NEEDS_FREE - indicates that the block has been moved
302e5dd7070Spatrick     ///   to malloc'ed memory
303e5dd7070Spatrick     ///  27. BLOCK_IS_GC - indicates that the block has been moved to
304e5dd7070Spatrick     ///   to GC-allocated memory
305e5dd7070Spatrick     /// Additionally, the bottom 16 bits are a reference count which
306e5dd7070Spatrick     /// should be zero on the stack.
307e5dd7070Spatrick     int flags;
308e5dd7070Spatrick 
309e5dd7070Spatrick     /// Reserved;  should be zero-initialized.
310e5dd7070Spatrick     int reserved;
311e5dd7070Spatrick 
312e5dd7070Spatrick     /// Function pointer generated from block literal.
313e5dd7070Spatrick     _ResultType (*invoke)(Block_literal *, _ParamTypes...);
314e5dd7070Spatrick 
315e5dd7070Spatrick     /// Block description metadata generated from block literal.
316e5dd7070Spatrick     struct Block_descriptor *block_descriptor;
317e5dd7070Spatrick 
318e5dd7070Spatrick     /// Captured values follow.
319e5dd7070Spatrick     _CapturesTypes captures...;
320e5dd7070Spatrick   };
321e5dd7070Spatrick  */
322e5dd7070Spatrick 
323e5dd7070Spatrick namespace {
324e5dd7070Spatrick   /// A chunk of data that we actually have to capture in the block.
325e5dd7070Spatrick   struct BlockLayoutChunk {
326e5dd7070Spatrick     CharUnits Alignment;
327e5dd7070Spatrick     CharUnits Size;
328e5dd7070Spatrick     const BlockDecl::Capture *Capture; // null for 'this'
329e5dd7070Spatrick     llvm::Type *Type;
330e5dd7070Spatrick     QualType FieldType;
331*12c85518Srobert     BlockCaptureEntityKind CopyKind, DisposeKind;
332*12c85518Srobert     BlockFieldFlags CopyFlags, DisposeFlags;
333e5dd7070Spatrick 
BlockLayoutChunk__anon3298161d0211::BlockLayoutChunk334e5dd7070Spatrick     BlockLayoutChunk(CharUnits align, CharUnits size,
335*12c85518Srobert                      const BlockDecl::Capture *capture, llvm::Type *type,
336*12c85518Srobert                      QualType fieldType, BlockCaptureEntityKind CopyKind,
337*12c85518Srobert                      BlockFieldFlags CopyFlags,
338*12c85518Srobert                      BlockCaptureEntityKind DisposeKind,
339*12c85518Srobert                      BlockFieldFlags DisposeFlags)
340*12c85518Srobert         : Alignment(align), Size(size), Capture(capture), Type(type),
341*12c85518Srobert           FieldType(fieldType), CopyKind(CopyKind), DisposeKind(DisposeKind),
342*12c85518Srobert           CopyFlags(CopyFlags), DisposeFlags(DisposeFlags) {}
343e5dd7070Spatrick 
344e5dd7070Spatrick     /// Tell the block info that this chunk has the given field index.
setIndex__anon3298161d0211::BlockLayoutChunk345e5dd7070Spatrick     void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
346e5dd7070Spatrick       if (!Capture) {
347e5dd7070Spatrick         info.CXXThisIndex = index;
348e5dd7070Spatrick         info.CXXThisOffset = offset;
349e5dd7070Spatrick       } else {
350*12c85518Srobert         info.SortedCaptures.push_back(CGBlockInfo::Capture::makeIndex(
351*12c85518Srobert             index, offset, FieldType, CopyKind, CopyFlags, DisposeKind,
352*12c85518Srobert             DisposeFlags, Capture));
353e5dd7070Spatrick       }
354e5dd7070Spatrick     }
355*12c85518Srobert 
isTrivial__anon3298161d0211::BlockLayoutChunk356*12c85518Srobert     bool isTrivial() const {
357*12c85518Srobert       return CopyKind == BlockCaptureEntityKind::None &&
358*12c85518Srobert              DisposeKind == BlockCaptureEntityKind::None;
359*12c85518Srobert     }
360e5dd7070Spatrick   };
361e5dd7070Spatrick 
362*12c85518Srobert   /// Order by 1) all __strong together 2) next, all block together 3) next,
363*12c85518Srobert   /// all byref together 4) next, all __weak together. Preserve descending
364*12c85518Srobert   /// alignment in all situations.
operator <(const BlockLayoutChunk & left,const BlockLayoutChunk & right)365e5dd7070Spatrick   bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
366e5dd7070Spatrick     if (left.Alignment != right.Alignment)
367e5dd7070Spatrick       return left.Alignment > right.Alignment;
368e5dd7070Spatrick 
369e5dd7070Spatrick     auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
370*12c85518Srobert       switch (chunk.CopyKind) {
371*12c85518Srobert       case BlockCaptureEntityKind::ARCStrong:
372e5dd7070Spatrick         return 0;
373*12c85518Srobert       case BlockCaptureEntityKind::BlockObject:
374*12c85518Srobert         switch (chunk.CopyFlags.getBitMask()) {
375*12c85518Srobert         case BLOCK_FIELD_IS_OBJECT:
376*12c85518Srobert           return 0;
377*12c85518Srobert         case BLOCK_FIELD_IS_BLOCK:
378*12c85518Srobert           return 1;
379*12c85518Srobert         case BLOCK_FIELD_IS_BYREF:
380e5dd7070Spatrick           return 2;
381*12c85518Srobert         default:
382*12c85518Srobert           break;
383*12c85518Srobert         }
384*12c85518Srobert         break;
385*12c85518Srobert       case BlockCaptureEntityKind::ARCWeak:
386e5dd7070Spatrick         return 3;
387*12c85518Srobert       default:
388*12c85518Srobert         break;
389*12c85518Srobert       }
390*12c85518Srobert       return 4;
391e5dd7070Spatrick     };
392e5dd7070Spatrick 
393e5dd7070Spatrick     return getPrefOrder(left) < getPrefOrder(right);
394e5dd7070Spatrick   }
395e5dd7070Spatrick } // end anonymous namespace
396e5dd7070Spatrick 
397*12c85518Srobert static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
398*12c85518Srobert computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
399*12c85518Srobert                                const LangOptions &LangOpts);
400*12c85518Srobert 
401*12c85518Srobert static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
402*12c85518Srobert computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
403*12c85518Srobert                                   const LangOptions &LangOpts);
404*12c85518Srobert 
addBlockLayout(CharUnits align,CharUnits size,const BlockDecl::Capture * capture,llvm::Type * type,QualType fieldType,SmallVectorImpl<BlockLayoutChunk> & Layout,CGBlockInfo & Info,CodeGenModule & CGM)405*12c85518Srobert static void addBlockLayout(CharUnits align, CharUnits size,
406*12c85518Srobert                            const BlockDecl::Capture *capture, llvm::Type *type,
407*12c85518Srobert                            QualType fieldType,
408*12c85518Srobert                            SmallVectorImpl<BlockLayoutChunk> &Layout,
409*12c85518Srobert                            CGBlockInfo &Info, CodeGenModule &CGM) {
410*12c85518Srobert   if (!capture) {
411*12c85518Srobert     // 'this' capture.
412*12c85518Srobert     Layout.push_back(BlockLayoutChunk(
413*12c85518Srobert         align, size, capture, type, fieldType, BlockCaptureEntityKind::None,
414*12c85518Srobert         BlockFieldFlags(), BlockCaptureEntityKind::None, BlockFieldFlags()));
415*12c85518Srobert     return;
416*12c85518Srobert   }
417*12c85518Srobert 
418*12c85518Srobert   const LangOptions &LangOpts = CGM.getLangOpts();
419*12c85518Srobert   BlockCaptureEntityKind CopyKind, DisposeKind;
420*12c85518Srobert   BlockFieldFlags CopyFlags, DisposeFlags;
421*12c85518Srobert 
422*12c85518Srobert   std::tie(CopyKind, CopyFlags) =
423*12c85518Srobert       computeCopyInfoForBlockCapture(*capture, fieldType, LangOpts);
424*12c85518Srobert   std::tie(DisposeKind, DisposeFlags) =
425*12c85518Srobert       computeDestroyInfoForBlockCapture(*capture, fieldType, LangOpts);
426*12c85518Srobert   Layout.push_back(BlockLayoutChunk(align, size, capture, type, fieldType,
427*12c85518Srobert                                     CopyKind, CopyFlags, DisposeKind,
428*12c85518Srobert                                     DisposeFlags));
429*12c85518Srobert 
430*12c85518Srobert   if (Info.NoEscape)
431*12c85518Srobert     return;
432*12c85518Srobert 
433*12c85518Srobert   if (!Layout.back().isTrivial())
434*12c85518Srobert     Info.NeedsCopyDispose = true;
435*12c85518Srobert }
436*12c85518Srobert 
437e5dd7070Spatrick /// Determines if the given type is safe for constant capture in C++.
isSafeForCXXConstantCapture(QualType type)438e5dd7070Spatrick static bool isSafeForCXXConstantCapture(QualType type) {
439e5dd7070Spatrick   const RecordType *recordType =
440e5dd7070Spatrick     type->getBaseElementTypeUnsafe()->getAs<RecordType>();
441e5dd7070Spatrick 
442e5dd7070Spatrick   // Only records can be unsafe.
443e5dd7070Spatrick   if (!recordType) return true;
444e5dd7070Spatrick 
445e5dd7070Spatrick   const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
446e5dd7070Spatrick 
447e5dd7070Spatrick   // Maintain semantics for classes with non-trivial dtors or copy ctors.
448e5dd7070Spatrick   if (!record->hasTrivialDestructor()) return false;
449e5dd7070Spatrick   if (record->hasNonTrivialCopyConstructor()) return false;
450e5dd7070Spatrick 
451e5dd7070Spatrick   // Otherwise, we just have to make sure there aren't any mutable
452e5dd7070Spatrick   // fields that might have changed since initialization.
453e5dd7070Spatrick   return !record->hasMutableFields();
454e5dd7070Spatrick }
455e5dd7070Spatrick 
456e5dd7070Spatrick /// It is illegal to modify a const object after initialization.
457e5dd7070Spatrick /// Therefore, if a const object has a constant initializer, we don't
458e5dd7070Spatrick /// actually need to keep storage for it in the block; we'll just
459e5dd7070Spatrick /// rematerialize it at the start of the block function.  This is
460e5dd7070Spatrick /// acceptable because we make no promises about address stability of
461e5dd7070Spatrick /// captured variables.
tryCaptureAsConstant(CodeGenModule & CGM,CodeGenFunction * CGF,const VarDecl * var)462e5dd7070Spatrick static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
463e5dd7070Spatrick                                             CodeGenFunction *CGF,
464e5dd7070Spatrick                                             const VarDecl *var) {
465e5dd7070Spatrick   // Return if this is a function parameter. We shouldn't try to
466e5dd7070Spatrick   // rematerialize default arguments of function parameters.
467e5dd7070Spatrick   if (isa<ParmVarDecl>(var))
468e5dd7070Spatrick     return nullptr;
469e5dd7070Spatrick 
470e5dd7070Spatrick   QualType type = var->getType();
471e5dd7070Spatrick 
472e5dd7070Spatrick   // We can only do this if the variable is const.
473e5dd7070Spatrick   if (!type.isConstQualified()) return nullptr;
474e5dd7070Spatrick 
475e5dd7070Spatrick   // Furthermore, in C++ we have to worry about mutable fields:
476e5dd7070Spatrick   // C++ [dcl.type.cv]p4:
477e5dd7070Spatrick   //   Except that any class member declared mutable can be
478e5dd7070Spatrick   //   modified, any attempt to modify a const object during its
479e5dd7070Spatrick   //   lifetime results in undefined behavior.
480e5dd7070Spatrick   if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
481e5dd7070Spatrick     return nullptr;
482e5dd7070Spatrick 
483e5dd7070Spatrick   // If the variable doesn't have any initializer (shouldn't this be
484e5dd7070Spatrick   // invalid?), it's not clear what we should do.  Maybe capture as
485e5dd7070Spatrick   // zero?
486e5dd7070Spatrick   const Expr *init = var->getInit();
487e5dd7070Spatrick   if (!init) return nullptr;
488e5dd7070Spatrick 
489e5dd7070Spatrick   return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
490e5dd7070Spatrick }
491e5dd7070Spatrick 
492e5dd7070Spatrick /// Get the low bit of a nonzero character count.  This is the
493e5dd7070Spatrick /// alignment of the nth byte if the 0th byte is universally aligned.
getLowBit(CharUnits v)494e5dd7070Spatrick static CharUnits getLowBit(CharUnits v) {
495e5dd7070Spatrick   return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
496e5dd7070Spatrick }
497e5dd7070Spatrick 
initializeForBlockHeader(CodeGenModule & CGM,CGBlockInfo & info,SmallVectorImpl<llvm::Type * > & elementTypes)498e5dd7070Spatrick static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
499e5dd7070Spatrick                              SmallVectorImpl<llvm::Type*> &elementTypes) {
500e5dd7070Spatrick 
501e5dd7070Spatrick   assert(elementTypes.empty());
502e5dd7070Spatrick   if (CGM.getLangOpts().OpenCL) {
503e5dd7070Spatrick     // The header is basically 'struct { int; int; generic void *;
504e5dd7070Spatrick     // custom_fields; }'. Assert that struct is packed.
505*12c85518Srobert     auto GenPtrAlign = CharUnits::fromQuantity(
506*12c85518Srobert         CGM.getTarget().getPointerAlign(LangAS::opencl_generic) / 8);
507*12c85518Srobert     auto GenPtrSize = CharUnits::fromQuantity(
508*12c85518Srobert         CGM.getTarget().getPointerWidth(LangAS::opencl_generic) / 8);
509e5dd7070Spatrick     assert(CGM.getIntSize() <= GenPtrSize);
510e5dd7070Spatrick     assert(CGM.getIntAlign() <= GenPtrAlign);
511e5dd7070Spatrick     assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
512e5dd7070Spatrick     elementTypes.push_back(CGM.IntTy); /* total size */
513e5dd7070Spatrick     elementTypes.push_back(CGM.IntTy); /* align */
514e5dd7070Spatrick     elementTypes.push_back(
515e5dd7070Spatrick         CGM.getOpenCLRuntime()
516e5dd7070Spatrick             .getGenericVoidPointerType()); /* invoke function */
517e5dd7070Spatrick     unsigned Offset =
518e5dd7070Spatrick         2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
519e5dd7070Spatrick     unsigned BlockAlign = GenPtrAlign.getQuantity();
520e5dd7070Spatrick     if (auto *Helper =
521e5dd7070Spatrick             CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
522*12c85518Srobert       for (auto *I : Helper->getCustomFieldTypes()) /* custom fields */ {
523e5dd7070Spatrick         // TargetOpenCLBlockHelp needs to make sure the struct is packed.
524e5dd7070Spatrick         // If necessary, add padding fields to the custom fields.
525*12c85518Srobert         unsigned Align = CGM.getDataLayout().getABITypeAlign(I).value();
526e5dd7070Spatrick         if (BlockAlign < Align)
527e5dd7070Spatrick           BlockAlign = Align;
528e5dd7070Spatrick         assert(Offset % Align == 0);
529e5dd7070Spatrick         Offset += CGM.getDataLayout().getTypeAllocSize(I);
530e5dd7070Spatrick         elementTypes.push_back(I);
531e5dd7070Spatrick       }
532e5dd7070Spatrick     }
533e5dd7070Spatrick     info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
534e5dd7070Spatrick     info.BlockSize = CharUnits::fromQuantity(Offset);
535e5dd7070Spatrick   } else {
536e5dd7070Spatrick     // The header is basically 'struct { void *; int; int; void *; void *; }'.
537e5dd7070Spatrick     // Assert that the struct is packed.
538e5dd7070Spatrick     assert(CGM.getIntSize() <= CGM.getPointerSize());
539e5dd7070Spatrick     assert(CGM.getIntAlign() <= CGM.getPointerAlign());
540e5dd7070Spatrick     assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
541e5dd7070Spatrick     info.BlockAlign = CGM.getPointerAlign();
542e5dd7070Spatrick     info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
543e5dd7070Spatrick     elementTypes.push_back(CGM.VoidPtrTy);
544e5dd7070Spatrick     elementTypes.push_back(CGM.IntTy);
545e5dd7070Spatrick     elementTypes.push_back(CGM.IntTy);
546e5dd7070Spatrick     elementTypes.push_back(CGM.VoidPtrTy);
547e5dd7070Spatrick     elementTypes.push_back(CGM.getBlockDescriptorType());
548e5dd7070Spatrick   }
549e5dd7070Spatrick }
550e5dd7070Spatrick 
getCaptureFieldType(const CodeGenFunction & CGF,const BlockDecl::Capture & CI)551e5dd7070Spatrick static QualType getCaptureFieldType(const CodeGenFunction &CGF,
552e5dd7070Spatrick                                     const BlockDecl::Capture &CI) {
553e5dd7070Spatrick   const VarDecl *VD = CI.getVariable();
554e5dd7070Spatrick 
555e5dd7070Spatrick   // If the variable is captured by an enclosing block or lambda expression,
556e5dd7070Spatrick   // use the type of the capture field.
557e5dd7070Spatrick   if (CGF.BlockInfo && CI.isNested())
558e5dd7070Spatrick     return CGF.BlockInfo->getCapture(VD).fieldType();
559e5dd7070Spatrick   if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
560e5dd7070Spatrick     return FD->getType();
561e5dd7070Spatrick   // If the captured variable is a non-escaping __block variable, the field
562e5dd7070Spatrick   // type is the reference type. If the variable is a __block variable that
563e5dd7070Spatrick   // already has a reference type, the field type is the variable's type.
564e5dd7070Spatrick   return VD->isNonEscapingByref() ?
565e5dd7070Spatrick          CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
566e5dd7070Spatrick }
567e5dd7070Spatrick 
568e5dd7070Spatrick /// Compute the layout of the given block.  Attempts to lay the block
569e5dd7070Spatrick /// out with minimal space requirements.
computeBlockInfo(CodeGenModule & CGM,CodeGenFunction * CGF,CGBlockInfo & info)570e5dd7070Spatrick static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
571e5dd7070Spatrick                              CGBlockInfo &info) {
572e5dd7070Spatrick   ASTContext &C = CGM.getContext();
573e5dd7070Spatrick   const BlockDecl *block = info.getBlockDecl();
574e5dd7070Spatrick 
575e5dd7070Spatrick   SmallVector<llvm::Type*, 8> elementTypes;
576e5dd7070Spatrick   initializeForBlockHeader(CGM, info, elementTypes);
577e5dd7070Spatrick   bool hasNonConstantCustomFields = false;
578e5dd7070Spatrick   if (auto *OpenCLHelper =
579e5dd7070Spatrick           CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
580e5dd7070Spatrick     hasNonConstantCustomFields =
581e5dd7070Spatrick         !OpenCLHelper->areAllCustomFieldValuesConstant(info);
582e5dd7070Spatrick   if (!block->hasCaptures() && !hasNonConstantCustomFields) {
583e5dd7070Spatrick     info.StructureType =
584e5dd7070Spatrick       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
585e5dd7070Spatrick     info.CanBeGlobal = true;
586e5dd7070Spatrick     return;
587e5dd7070Spatrick   }
588e5dd7070Spatrick   else if (C.getLangOpts().ObjC &&
589e5dd7070Spatrick            CGM.getLangOpts().getGC() == LangOptions::NonGC)
590e5dd7070Spatrick     info.HasCapturedVariableLayout = true;
591e5dd7070Spatrick 
592*12c85518Srobert   if (block->doesNotEscape())
593*12c85518Srobert     info.NoEscape = true;
594*12c85518Srobert 
595e5dd7070Spatrick   // Collect the layout chunks.
596e5dd7070Spatrick   SmallVector<BlockLayoutChunk, 16> layout;
597e5dd7070Spatrick   layout.reserve(block->capturesCXXThis() +
598e5dd7070Spatrick                  (block->capture_end() - block->capture_begin()));
599e5dd7070Spatrick 
600e5dd7070Spatrick   CharUnits maxFieldAlign;
601e5dd7070Spatrick 
602e5dd7070Spatrick   // First, 'this'.
603e5dd7070Spatrick   if (block->capturesCXXThis()) {
604e5dd7070Spatrick     assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
605e5dd7070Spatrick            "Can't capture 'this' outside a method");
606e5dd7070Spatrick     QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
607e5dd7070Spatrick 
608e5dd7070Spatrick     // Theoretically, this could be in a different address space, so
609e5dd7070Spatrick     // don't assume standard pointer size/align.
610e5dd7070Spatrick     llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
611a9ac8606Spatrick     auto TInfo = CGM.getContext().getTypeInfoInChars(thisType);
612a9ac8606Spatrick     maxFieldAlign = std::max(maxFieldAlign, TInfo.Align);
613e5dd7070Spatrick 
614*12c85518Srobert     addBlockLayout(TInfo.Align, TInfo.Width, nullptr, llvmType, thisType,
615*12c85518Srobert                    layout, info, CGM);
616e5dd7070Spatrick   }
617e5dd7070Spatrick 
618e5dd7070Spatrick   // Next, all the block captures.
619e5dd7070Spatrick   for (const auto &CI : block->captures()) {
620e5dd7070Spatrick     const VarDecl *variable = CI.getVariable();
621e5dd7070Spatrick 
622e5dd7070Spatrick     if (CI.isEscapingByref()) {
623e5dd7070Spatrick       // Just use void* instead of a pointer to the byref type.
624e5dd7070Spatrick       CharUnits align = CGM.getPointerAlign();
625e5dd7070Spatrick       maxFieldAlign = std::max(maxFieldAlign, align);
626e5dd7070Spatrick 
627e5dd7070Spatrick       // Since a __block variable cannot be captured by lambdas, its type and
628e5dd7070Spatrick       // the capture field type should always match.
629a9ac8606Spatrick       assert(CGF && getCaptureFieldType(*CGF, CI) == variable->getType() &&
630e5dd7070Spatrick              "capture type differs from the variable type");
631*12c85518Srobert       addBlockLayout(align, CGM.getPointerSize(), &CI, CGM.VoidPtrTy,
632*12c85518Srobert                      variable->getType(), layout, info, CGM);
633e5dd7070Spatrick       continue;
634e5dd7070Spatrick     }
635e5dd7070Spatrick 
636e5dd7070Spatrick     // Otherwise, build a layout chunk with the size and alignment of
637e5dd7070Spatrick     // the declaration.
638e5dd7070Spatrick     if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
639*12c85518Srobert       info.SortedCaptures.push_back(
640*12c85518Srobert           CGBlockInfo::Capture::makeConstant(constant, &CI));
641e5dd7070Spatrick       continue;
642e5dd7070Spatrick     }
643e5dd7070Spatrick 
644e5dd7070Spatrick     QualType VT = getCaptureFieldType(*CGF, CI);
645e5dd7070Spatrick 
646*12c85518Srobert     if (CGM.getLangOpts().CPlusPlus)
647*12c85518Srobert       if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl())
648*12c85518Srobert         if (CI.hasCopyExpr() || !record->hasTrivialDestructor()) {
649e5dd7070Spatrick           info.HasCXXObject = true;
650e5dd7070Spatrick           if (!record->isExternallyVisible())
651e5dd7070Spatrick             info.CapturesNonExternalType = true;
652e5dd7070Spatrick         }
653e5dd7070Spatrick 
654e5dd7070Spatrick     CharUnits size = C.getTypeSizeInChars(VT);
655e5dd7070Spatrick     CharUnits align = C.getDeclAlign(variable);
656e5dd7070Spatrick 
657e5dd7070Spatrick     maxFieldAlign = std::max(maxFieldAlign, align);
658e5dd7070Spatrick 
659e5dd7070Spatrick     llvm::Type *llvmType =
660e5dd7070Spatrick       CGM.getTypes().ConvertTypeForMem(VT);
661e5dd7070Spatrick 
662*12c85518Srobert     addBlockLayout(align, size, &CI, llvmType, VT, layout, info, CGM);
663e5dd7070Spatrick   }
664e5dd7070Spatrick 
665e5dd7070Spatrick   // If that was everything, we're done here.
666e5dd7070Spatrick   if (layout.empty()) {
667e5dd7070Spatrick     info.StructureType =
668e5dd7070Spatrick       llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
669e5dd7070Spatrick     info.CanBeGlobal = true;
670*12c85518Srobert     info.buildCaptureMap();
671e5dd7070Spatrick     return;
672e5dd7070Spatrick   }
673e5dd7070Spatrick 
674e5dd7070Spatrick   // Sort the layout by alignment.  We have to use a stable sort here
675e5dd7070Spatrick   // to get reproducible results.  There should probably be an
676e5dd7070Spatrick   // llvm::array_pod_stable_sort.
677e5dd7070Spatrick   llvm::stable_sort(layout);
678e5dd7070Spatrick 
679e5dd7070Spatrick   // Needed for blocks layout info.
680e5dd7070Spatrick   info.BlockHeaderForcedGapOffset = info.BlockSize;
681e5dd7070Spatrick   info.BlockHeaderForcedGapSize = CharUnits::Zero();
682e5dd7070Spatrick 
683e5dd7070Spatrick   CharUnits &blockSize = info.BlockSize;
684e5dd7070Spatrick   info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
685e5dd7070Spatrick 
686e5dd7070Spatrick   // Assuming that the first byte in the header is maximally aligned,
687e5dd7070Spatrick   // get the alignment of the first byte following the header.
688e5dd7070Spatrick   CharUnits endAlign = getLowBit(blockSize);
689e5dd7070Spatrick 
690e5dd7070Spatrick   // If the end of the header isn't satisfactorily aligned for the
691e5dd7070Spatrick   // maximum thing, look for things that are okay with the header-end
692e5dd7070Spatrick   // alignment, and keep appending them until we get something that's
693e5dd7070Spatrick   // aligned right.  This algorithm is only guaranteed optimal if
694e5dd7070Spatrick   // that condition is satisfied at some point; otherwise we can get
695e5dd7070Spatrick   // things like:
696e5dd7070Spatrick   //   header                 // next byte has alignment 4
697e5dd7070Spatrick   //   something_with_size_5; // next byte has alignment 1
698e5dd7070Spatrick   //   something_with_alignment_8;
699e5dd7070Spatrick   // which has 7 bytes of padding, as opposed to the naive solution
700e5dd7070Spatrick   // which might have less (?).
701e5dd7070Spatrick   if (endAlign < maxFieldAlign) {
702e5dd7070Spatrick     SmallVectorImpl<BlockLayoutChunk>::iterator
703e5dd7070Spatrick       li = layout.begin() + 1, le = layout.end();
704e5dd7070Spatrick 
705e5dd7070Spatrick     // Look for something that the header end is already
706e5dd7070Spatrick     // satisfactorily aligned for.
707e5dd7070Spatrick     for (; li != le && endAlign < li->Alignment; ++li)
708e5dd7070Spatrick       ;
709e5dd7070Spatrick 
710e5dd7070Spatrick     // If we found something that's naturally aligned for the end of
711e5dd7070Spatrick     // the header, keep adding things...
712e5dd7070Spatrick     if (li != le) {
713e5dd7070Spatrick       SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
714e5dd7070Spatrick       for (; li != le; ++li) {
715e5dd7070Spatrick         assert(endAlign >= li->Alignment);
716e5dd7070Spatrick 
717e5dd7070Spatrick         li->setIndex(info, elementTypes.size(), blockSize);
718e5dd7070Spatrick         elementTypes.push_back(li->Type);
719e5dd7070Spatrick         blockSize += li->Size;
720e5dd7070Spatrick         endAlign = getLowBit(blockSize);
721e5dd7070Spatrick 
722e5dd7070Spatrick         // ...until we get to the alignment of the maximum field.
723e5dd7070Spatrick         if (endAlign >= maxFieldAlign) {
724*12c85518Srobert           ++li;
725e5dd7070Spatrick           break;
726e5dd7070Spatrick         }
727e5dd7070Spatrick       }
728e5dd7070Spatrick       // Don't re-append everything we just appended.
729e5dd7070Spatrick       layout.erase(first, li);
730e5dd7070Spatrick     }
731e5dd7070Spatrick   }
732e5dd7070Spatrick 
733e5dd7070Spatrick   assert(endAlign == getLowBit(blockSize));
734e5dd7070Spatrick 
735e5dd7070Spatrick   // At this point, we just have to add padding if the end align still
736e5dd7070Spatrick   // isn't aligned right.
737e5dd7070Spatrick   if (endAlign < maxFieldAlign) {
738e5dd7070Spatrick     CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
739e5dd7070Spatrick     CharUnits padding = newBlockSize - blockSize;
740e5dd7070Spatrick 
741e5dd7070Spatrick     // If we haven't yet added any fields, remember that there was an
742e5dd7070Spatrick     // initial gap; this need to go into the block layout bit map.
743e5dd7070Spatrick     if (blockSize == info.BlockHeaderForcedGapOffset) {
744e5dd7070Spatrick       info.BlockHeaderForcedGapSize = padding;
745e5dd7070Spatrick     }
746e5dd7070Spatrick 
747e5dd7070Spatrick     elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
748e5dd7070Spatrick                                                 padding.getQuantity()));
749e5dd7070Spatrick     blockSize = newBlockSize;
750e5dd7070Spatrick     endAlign = getLowBit(blockSize); // might be > maxFieldAlign
751e5dd7070Spatrick   }
752e5dd7070Spatrick 
753e5dd7070Spatrick   assert(endAlign >= maxFieldAlign);
754e5dd7070Spatrick   assert(endAlign == getLowBit(blockSize));
755e5dd7070Spatrick   // Slam everything else on now.  This works because they have
756e5dd7070Spatrick   // strictly decreasing alignment and we expect that size is always a
757e5dd7070Spatrick   // multiple of alignment.
758e5dd7070Spatrick   for (SmallVectorImpl<BlockLayoutChunk>::iterator
759e5dd7070Spatrick          li = layout.begin(), le = layout.end(); li != le; ++li) {
760e5dd7070Spatrick     if (endAlign < li->Alignment) {
761e5dd7070Spatrick       // size may not be multiple of alignment. This can only happen with
762e5dd7070Spatrick       // an over-aligned variable. We will be adding a padding field to
763e5dd7070Spatrick       // make the size be multiple of alignment.
764e5dd7070Spatrick       CharUnits padding = li->Alignment - endAlign;
765e5dd7070Spatrick       elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
766e5dd7070Spatrick                                                   padding.getQuantity()));
767e5dd7070Spatrick       blockSize += padding;
768e5dd7070Spatrick       endAlign = getLowBit(blockSize);
769e5dd7070Spatrick     }
770e5dd7070Spatrick     assert(endAlign >= li->Alignment);
771e5dd7070Spatrick     li->setIndex(info, elementTypes.size(), blockSize);
772e5dd7070Spatrick     elementTypes.push_back(li->Type);
773e5dd7070Spatrick     blockSize += li->Size;
774e5dd7070Spatrick     endAlign = getLowBit(blockSize);
775e5dd7070Spatrick   }
776e5dd7070Spatrick 
777*12c85518Srobert   info.buildCaptureMap();
778e5dd7070Spatrick   info.StructureType =
779e5dd7070Spatrick     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
780e5dd7070Spatrick }
781e5dd7070Spatrick 
782e5dd7070Spatrick /// Emit a block literal expression in the current function.
EmitBlockLiteral(const BlockExpr * blockExpr)783e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
784e5dd7070Spatrick   // If the block has no captures, we won't have a pre-computed
785e5dd7070Spatrick   // layout for it.
786ec727ea7Spatrick   if (!blockExpr->getBlockDecl()->hasCaptures())
787e5dd7070Spatrick     // The block literal is emitted as a global variable, and the block invoke
788e5dd7070Spatrick     // function has to be extracted from its initializer.
789ec727ea7Spatrick     if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
790e5dd7070Spatrick       return Block;
791ec727ea7Spatrick 
792e5dd7070Spatrick   CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
793e5dd7070Spatrick   computeBlockInfo(CGM, this, blockInfo);
794e5dd7070Spatrick   blockInfo.BlockExpression = blockExpr;
795ec727ea7Spatrick   if (!blockInfo.CanBeGlobal)
796ec727ea7Spatrick     blockInfo.LocalAddress = CreateTempAlloca(blockInfo.StructureType,
797ec727ea7Spatrick                                               blockInfo.BlockAlign, "block");
798e5dd7070Spatrick   return EmitBlockLiteral(blockInfo);
799e5dd7070Spatrick }
800e5dd7070Spatrick 
EmitBlockLiteral(const CGBlockInfo & blockInfo)801e5dd7070Spatrick llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
802e5dd7070Spatrick   bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
803e5dd7070Spatrick   auto GenVoidPtrTy =
804e5dd7070Spatrick       IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
805e5dd7070Spatrick   LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
806e5dd7070Spatrick   auto GenVoidPtrSize = CharUnits::fromQuantity(
807*12c85518Srobert       CGM.getTarget().getPointerWidth(GenVoidPtrAddr) / 8);
808e5dd7070Spatrick   // Using the computed layout, generate the actual block function.
809e5dd7070Spatrick   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
810e5dd7070Spatrick   CodeGenFunction BlockCGF{CGM, true};
811e5dd7070Spatrick   BlockCGF.SanOpts = SanOpts;
812e5dd7070Spatrick   auto *InvokeFn = BlockCGF.GenerateBlockFunction(
813e5dd7070Spatrick       CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
814e5dd7070Spatrick   auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
815e5dd7070Spatrick 
816e5dd7070Spatrick   // If there is nothing to capture, we can emit this as a global block.
817e5dd7070Spatrick   if (blockInfo.CanBeGlobal)
818e5dd7070Spatrick     return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
819e5dd7070Spatrick 
820e5dd7070Spatrick   // Otherwise, we have to emit this as a local block.
821e5dd7070Spatrick 
822e5dd7070Spatrick   Address blockAddr = blockInfo.LocalAddress;
823e5dd7070Spatrick   assert(blockAddr.isValid() && "block has no address!");
824e5dd7070Spatrick 
825e5dd7070Spatrick   llvm::Constant *isa;
826e5dd7070Spatrick   llvm::Constant *descriptor;
827e5dd7070Spatrick   BlockFlags flags;
828e5dd7070Spatrick   if (!IsOpenCL) {
829e5dd7070Spatrick     // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
830e5dd7070Spatrick     // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
831e5dd7070Spatrick     // block just returns the original block and releasing it is a no-op.
832*12c85518Srobert     llvm::Constant *blockISA = blockInfo.NoEscape
833e5dd7070Spatrick                                    ? CGM.getNSConcreteGlobalBlock()
834e5dd7070Spatrick                                    : CGM.getNSConcreteStackBlock();
835e5dd7070Spatrick     isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
836e5dd7070Spatrick 
837e5dd7070Spatrick     // Build the block descriptor.
838e5dd7070Spatrick     descriptor = buildBlockDescriptor(CGM, blockInfo);
839e5dd7070Spatrick 
840e5dd7070Spatrick     // Compute the initial on-stack block flags.
841e5dd7070Spatrick     flags = BLOCK_HAS_SIGNATURE;
842e5dd7070Spatrick     if (blockInfo.HasCapturedVariableLayout)
843e5dd7070Spatrick       flags |= BLOCK_HAS_EXTENDED_LAYOUT;
844*12c85518Srobert     if (blockInfo.NeedsCopyDispose)
845e5dd7070Spatrick       flags |= BLOCK_HAS_COPY_DISPOSE;
846e5dd7070Spatrick     if (blockInfo.HasCXXObject)
847e5dd7070Spatrick       flags |= BLOCK_HAS_CXX_OBJ;
848e5dd7070Spatrick     if (blockInfo.UsesStret)
849e5dd7070Spatrick       flags |= BLOCK_USE_STRET;
850*12c85518Srobert     if (blockInfo.NoEscape)
851e5dd7070Spatrick       flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
852e5dd7070Spatrick   }
853e5dd7070Spatrick 
854e5dd7070Spatrick   auto projectField = [&](unsigned index, const Twine &name) -> Address {
855e5dd7070Spatrick     return Builder.CreateStructGEP(blockAddr, index, name);
856e5dd7070Spatrick   };
857e5dd7070Spatrick   auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) {
858e5dd7070Spatrick     Builder.CreateStore(value, projectField(index, name));
859e5dd7070Spatrick   };
860e5dd7070Spatrick 
861e5dd7070Spatrick   // Initialize the block header.
862e5dd7070Spatrick   {
863e5dd7070Spatrick     // We assume all the header fields are densely packed.
864e5dd7070Spatrick     unsigned index = 0;
865e5dd7070Spatrick     CharUnits offset;
866e5dd7070Spatrick     auto addHeaderField = [&](llvm::Value *value, CharUnits size,
867e5dd7070Spatrick                               const Twine &name) {
868e5dd7070Spatrick       storeField(value, index, name);
869e5dd7070Spatrick       offset += size;
870e5dd7070Spatrick       index++;
871e5dd7070Spatrick     };
872e5dd7070Spatrick 
873e5dd7070Spatrick     if (!IsOpenCL) {
874e5dd7070Spatrick       addHeaderField(isa, getPointerSize(), "block.isa");
875e5dd7070Spatrick       addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
876e5dd7070Spatrick                      getIntSize(), "block.flags");
877e5dd7070Spatrick       addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
878e5dd7070Spatrick                      "block.reserved");
879e5dd7070Spatrick     } else {
880e5dd7070Spatrick       addHeaderField(
881e5dd7070Spatrick           llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
882e5dd7070Spatrick           getIntSize(), "block.size");
883e5dd7070Spatrick       addHeaderField(
884e5dd7070Spatrick           llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
885e5dd7070Spatrick           getIntSize(), "block.align");
886e5dd7070Spatrick     }
887e5dd7070Spatrick     addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
888e5dd7070Spatrick     if (!IsOpenCL)
889e5dd7070Spatrick       addHeaderField(descriptor, getPointerSize(), "block.descriptor");
890e5dd7070Spatrick     else if (auto *Helper =
891e5dd7070Spatrick                  CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
892e5dd7070Spatrick       for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
893e5dd7070Spatrick         addHeaderField(
894e5dd7070Spatrick             I.first,
895e5dd7070Spatrick             CharUnits::fromQuantity(
896e5dd7070Spatrick                 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
897e5dd7070Spatrick             I.second);
898e5dd7070Spatrick       }
899e5dd7070Spatrick     }
900e5dd7070Spatrick   }
901e5dd7070Spatrick 
902e5dd7070Spatrick   // Finally, capture all the values into the block.
903e5dd7070Spatrick   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
904e5dd7070Spatrick 
905e5dd7070Spatrick   // First, 'this'.
906e5dd7070Spatrick   if (blockDecl->capturesCXXThis()) {
907e5dd7070Spatrick     Address addr =
908e5dd7070Spatrick         projectField(blockInfo.CXXThisIndex, "block.captured-this.addr");
909e5dd7070Spatrick     Builder.CreateStore(LoadCXXThis(), addr);
910e5dd7070Spatrick   }
911e5dd7070Spatrick 
912e5dd7070Spatrick   // Next, captured variables.
913e5dd7070Spatrick   for (const auto &CI : blockDecl->captures()) {
914e5dd7070Spatrick     const VarDecl *variable = CI.getVariable();
915e5dd7070Spatrick     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
916e5dd7070Spatrick 
917e5dd7070Spatrick     // Ignore constant captures.
918e5dd7070Spatrick     if (capture.isConstant()) continue;
919e5dd7070Spatrick 
920e5dd7070Spatrick     QualType type = capture.fieldType();
921e5dd7070Spatrick 
922e5dd7070Spatrick     // This will be a [[type]]*, except that a byref entry will just be
923e5dd7070Spatrick     // an i8**.
924e5dd7070Spatrick     Address blockField = projectField(capture.getIndex(), "block.captured");
925e5dd7070Spatrick 
926e5dd7070Spatrick     // Compute the address of the thing we're going to move into the
927e5dd7070Spatrick     // block literal.
928e5dd7070Spatrick     Address src = Address::invalid();
929e5dd7070Spatrick 
930e5dd7070Spatrick     if (blockDecl->isConversionFromLambda()) {
931e5dd7070Spatrick       // The lambda capture in a lambda's conversion-to-block-pointer is
932e5dd7070Spatrick       // special; we'll simply emit it directly.
933e5dd7070Spatrick       src = Address::invalid();
934e5dd7070Spatrick     } else if (CI.isEscapingByref()) {
935e5dd7070Spatrick       if (BlockInfo && CI.isNested()) {
936e5dd7070Spatrick         // We need to use the capture from the enclosing block.
937e5dd7070Spatrick         const CGBlockInfo::Capture &enclosingCapture =
938e5dd7070Spatrick             BlockInfo->getCapture(variable);
939e5dd7070Spatrick 
940e5dd7070Spatrick         // This is a [[type]]*, except that a byref entry will just be an i8**.
941e5dd7070Spatrick         src = Builder.CreateStructGEP(LoadBlockStruct(),
942e5dd7070Spatrick                                       enclosingCapture.getIndex(),
943e5dd7070Spatrick                                       "block.capture.addr");
944e5dd7070Spatrick       } else {
945e5dd7070Spatrick         auto I = LocalDeclMap.find(variable);
946e5dd7070Spatrick         assert(I != LocalDeclMap.end());
947e5dd7070Spatrick         src = I->second;
948e5dd7070Spatrick       }
949e5dd7070Spatrick     } else {
950e5dd7070Spatrick       DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
951e5dd7070Spatrick                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
952e5dd7070Spatrick                           type.getNonReferenceType(), VK_LValue,
953e5dd7070Spatrick                           SourceLocation());
954e5dd7070Spatrick       src = EmitDeclRefLValue(&declRef).getAddress(*this);
955e5dd7070Spatrick     };
956e5dd7070Spatrick 
957e5dd7070Spatrick     // For byrefs, we just write the pointer to the byref struct into
958e5dd7070Spatrick     // the block field.  There's no need to chase the forwarding
959e5dd7070Spatrick     // pointer at this point, since we're building something that will
960e5dd7070Spatrick     // live a shorter life than the stack byref anyway.
961e5dd7070Spatrick     if (CI.isEscapingByref()) {
962e5dd7070Spatrick       // Get a void* that points to the byref struct.
963e5dd7070Spatrick       llvm::Value *byrefPointer;
964e5dd7070Spatrick       if (CI.isNested())
965e5dd7070Spatrick         byrefPointer = Builder.CreateLoad(src, "byref.capture");
966e5dd7070Spatrick       else
967e5dd7070Spatrick         byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
968e5dd7070Spatrick 
969e5dd7070Spatrick       // Write that void* into the capture field.
970e5dd7070Spatrick       Builder.CreateStore(byrefPointer, blockField);
971e5dd7070Spatrick 
972e5dd7070Spatrick     // If we have a copy constructor, evaluate that into the block field.
973e5dd7070Spatrick     } else if (const Expr *copyExpr = CI.getCopyExpr()) {
974e5dd7070Spatrick       if (blockDecl->isConversionFromLambda()) {
975e5dd7070Spatrick         // If we have a lambda conversion, emit the expression
976e5dd7070Spatrick         // directly into the block instead.
977e5dd7070Spatrick         AggValueSlot Slot =
978e5dd7070Spatrick             AggValueSlot::forAddr(blockField, Qualifiers(),
979e5dd7070Spatrick                                   AggValueSlot::IsDestructed,
980e5dd7070Spatrick                                   AggValueSlot::DoesNotNeedGCBarriers,
981e5dd7070Spatrick                                   AggValueSlot::IsNotAliased,
982e5dd7070Spatrick                                   AggValueSlot::DoesNotOverlap);
983e5dd7070Spatrick         EmitAggExpr(copyExpr, Slot);
984e5dd7070Spatrick       } else {
985e5dd7070Spatrick         EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
986e5dd7070Spatrick       }
987e5dd7070Spatrick 
988e5dd7070Spatrick     // If it's a reference variable, copy the reference into the block field.
989e5dd7070Spatrick     } else if (type->isReferenceType()) {
990e5dd7070Spatrick       Builder.CreateStore(src.getPointer(), blockField);
991e5dd7070Spatrick 
992e5dd7070Spatrick     // If type is const-qualified, copy the value into the block field.
993e5dd7070Spatrick     } else if (type.isConstQualified() &&
994e5dd7070Spatrick                type.getObjCLifetime() == Qualifiers::OCL_Strong &&
995e5dd7070Spatrick                CGM.getCodeGenOpts().OptimizationLevel != 0) {
996e5dd7070Spatrick       llvm::Value *value = Builder.CreateLoad(src, "captured");
997e5dd7070Spatrick       Builder.CreateStore(value, blockField);
998e5dd7070Spatrick 
999e5dd7070Spatrick     // If this is an ARC __strong block-pointer variable, don't do a
1000e5dd7070Spatrick     // block copy.
1001e5dd7070Spatrick     //
1002e5dd7070Spatrick     // TODO: this can be generalized into the normal initialization logic:
1003e5dd7070Spatrick     // we should never need to do a block-copy when initializing a local
1004e5dd7070Spatrick     // variable, because the local variable's lifetime should be strictly
1005e5dd7070Spatrick     // contained within the stack block's.
1006e5dd7070Spatrick     } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1007e5dd7070Spatrick                type->isBlockPointerType()) {
1008e5dd7070Spatrick       // Load the block and do a simple retain.
1009e5dd7070Spatrick       llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
1010e5dd7070Spatrick       value = EmitARCRetainNonBlock(value);
1011e5dd7070Spatrick 
1012e5dd7070Spatrick       // Do a primitive store to the block field.
1013e5dd7070Spatrick       Builder.CreateStore(value, blockField);
1014e5dd7070Spatrick 
1015e5dd7070Spatrick     // Otherwise, fake up a POD copy into the block field.
1016e5dd7070Spatrick     } else {
1017e5dd7070Spatrick       // Fake up a new variable so that EmitScalarInit doesn't think
1018e5dd7070Spatrick       // we're referring to the variable in its own initializer.
1019e5dd7070Spatrick       ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1020e5dd7070Spatrick                                             ImplicitParamDecl::Other);
1021e5dd7070Spatrick 
1022e5dd7070Spatrick       // We use one of these or the other depending on whether the
1023e5dd7070Spatrick       // reference is nested.
1024e5dd7070Spatrick       DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
1025e5dd7070Spatrick                           /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1026e5dd7070Spatrick                           type, VK_LValue, SourceLocation());
1027e5dd7070Spatrick 
1028e5dd7070Spatrick       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
1029a9ac8606Spatrick                            &declRef, VK_PRValue, FPOptionsOverride());
1030e5dd7070Spatrick       // FIXME: Pass a specific location for the expr init so that the store is
1031e5dd7070Spatrick       // attributed to a reasonable location - otherwise it may be attributed to
1032e5dd7070Spatrick       // locations of subexpressions in the initialization.
1033e5dd7070Spatrick       EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
1034e5dd7070Spatrick                      MakeAddrLValue(blockField, type, AlignmentSource::Decl),
1035e5dd7070Spatrick                      /*captured by init*/ false);
1036e5dd7070Spatrick     }
1037e5dd7070Spatrick 
1038ec727ea7Spatrick     // Push a cleanup for the capture if necessary.
1039*12c85518Srobert     if (!blockInfo.NoEscape && !blockInfo.NeedsCopyDispose)
1040ec727ea7Spatrick       continue;
1041ec727ea7Spatrick 
1042ec727ea7Spatrick     // Ignore __block captures; there's nothing special in the on-stack block
1043ec727ea7Spatrick     // that we need to do for them.
1044ec727ea7Spatrick     if (CI.isByRef())
1045ec727ea7Spatrick       continue;
1046ec727ea7Spatrick 
1047ec727ea7Spatrick     // Ignore objects that aren't destructed.
1048ec727ea7Spatrick     QualType::DestructionKind dtorKind = type.isDestructedType();
1049ec727ea7Spatrick     if (dtorKind == QualType::DK_none)
1050ec727ea7Spatrick       continue;
1051ec727ea7Spatrick 
1052ec727ea7Spatrick     CodeGenFunction::Destroyer *destroyer;
1053ec727ea7Spatrick 
1054ec727ea7Spatrick     // Block captures count as local values and have imprecise semantics.
1055ec727ea7Spatrick     // They also can't be arrays, so need to worry about that.
1056ec727ea7Spatrick     //
1057ec727ea7Spatrick     // For const-qualified captures, emit clang.arc.use to ensure the captured
1058ec727ea7Spatrick     // object doesn't get released while we are still depending on its validity
1059ec727ea7Spatrick     // within the block.
1060ec727ea7Spatrick     if (type.isConstQualified() &&
1061ec727ea7Spatrick         type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1062ec727ea7Spatrick         CGM.getCodeGenOpts().OptimizationLevel != 0) {
1063ec727ea7Spatrick       assert(CGM.getLangOpts().ObjCAutoRefCount &&
1064ec727ea7Spatrick              "expected ObjC ARC to be enabled");
1065ec727ea7Spatrick       destroyer = emitARCIntrinsicUse;
1066ec727ea7Spatrick     } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
1067ec727ea7Spatrick       destroyer = destroyARCStrongImprecise;
1068ec727ea7Spatrick     } else {
1069ec727ea7Spatrick       destroyer = getDestroyer(dtorKind);
1070e5dd7070Spatrick     }
1071ec727ea7Spatrick 
1072ec727ea7Spatrick     CleanupKind cleanupKind = NormalCleanup;
1073ec727ea7Spatrick     bool useArrayEHCleanup = needsEHCleanup(dtorKind);
1074ec727ea7Spatrick     if (useArrayEHCleanup)
1075ec727ea7Spatrick       cleanupKind = NormalAndEHCleanup;
1076ec727ea7Spatrick 
1077ec727ea7Spatrick     // Extend the lifetime of the capture to the end of the scope enclosing the
1078ec727ea7Spatrick     // block expression except when the block decl is in the list of RetExpr's
1079ec727ea7Spatrick     // cleanup objects, in which case its lifetime ends after the full
1080ec727ea7Spatrick     // expression.
1081ec727ea7Spatrick     auto IsBlockDeclInRetExpr = [&]() {
1082ec727ea7Spatrick       auto *EWC = llvm::dyn_cast_or_null<ExprWithCleanups>(RetExpr);
1083ec727ea7Spatrick       if (EWC)
1084ec727ea7Spatrick         for (auto &C : EWC->getObjects())
1085ec727ea7Spatrick           if (auto *BD = C.dyn_cast<BlockDecl *>())
1086ec727ea7Spatrick             if (BD == blockDecl)
1087ec727ea7Spatrick               return true;
1088ec727ea7Spatrick       return false;
1089ec727ea7Spatrick     };
1090ec727ea7Spatrick 
1091ec727ea7Spatrick     if (IsBlockDeclInRetExpr())
1092ec727ea7Spatrick       pushDestroy(cleanupKind, blockField, type, destroyer, useArrayEHCleanup);
1093ec727ea7Spatrick     else
1094ec727ea7Spatrick       pushLifetimeExtendedDestroy(cleanupKind, blockField, type, destroyer,
1095ec727ea7Spatrick                                   useArrayEHCleanup);
1096e5dd7070Spatrick   }
1097e5dd7070Spatrick 
1098e5dd7070Spatrick   // Cast to the converted block-pointer type, which happens (somewhat
1099e5dd7070Spatrick   // unfortunately) to be a pointer to function type.
1100e5dd7070Spatrick   llvm::Value *result = Builder.CreatePointerCast(
1101e5dd7070Spatrick       blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
1102e5dd7070Spatrick 
1103e5dd7070Spatrick   if (IsOpenCL) {
1104e5dd7070Spatrick     CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1105*12c85518Srobert                                            result, blockInfo.StructureType);
1106e5dd7070Spatrick   }
1107e5dd7070Spatrick 
1108e5dd7070Spatrick   return result;
1109e5dd7070Spatrick }
1110e5dd7070Spatrick 
1111e5dd7070Spatrick 
getBlockDescriptorType()1112e5dd7070Spatrick llvm::Type *CodeGenModule::getBlockDescriptorType() {
1113e5dd7070Spatrick   if (BlockDescriptorType)
1114e5dd7070Spatrick     return BlockDescriptorType;
1115e5dd7070Spatrick 
1116e5dd7070Spatrick   llvm::Type *UnsignedLongTy =
1117e5dd7070Spatrick     getTypes().ConvertType(getContext().UnsignedLongTy);
1118e5dd7070Spatrick 
1119e5dd7070Spatrick   // struct __block_descriptor {
1120e5dd7070Spatrick   //   unsigned long reserved;
1121e5dd7070Spatrick   //   unsigned long block_size;
1122e5dd7070Spatrick   //
1123e5dd7070Spatrick   //   // later, the following will be added
1124e5dd7070Spatrick   //
1125e5dd7070Spatrick   //   struct {
1126e5dd7070Spatrick   //     void (*copyHelper)();
1127e5dd7070Spatrick   //     void (*copyHelper)();
1128e5dd7070Spatrick   //   } helpers;                // !!! optional
1129e5dd7070Spatrick   //
1130e5dd7070Spatrick   //   const char *signature;   // the block signature
1131e5dd7070Spatrick   //   const char *layout;      // reserved
1132e5dd7070Spatrick   // };
1133e5dd7070Spatrick   BlockDescriptorType = llvm::StructType::create(
1134e5dd7070Spatrick       "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
1135e5dd7070Spatrick 
1136e5dd7070Spatrick   // Now form a pointer to that.
1137e5dd7070Spatrick   unsigned AddrSpace = 0;
1138e5dd7070Spatrick   if (getLangOpts().OpenCL)
1139e5dd7070Spatrick     AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1140e5dd7070Spatrick   BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
1141e5dd7070Spatrick   return BlockDescriptorType;
1142e5dd7070Spatrick }
1143e5dd7070Spatrick 
getGenericBlockLiteralType()1144e5dd7070Spatrick llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
1145e5dd7070Spatrick   if (GenericBlockLiteralType)
1146e5dd7070Spatrick     return GenericBlockLiteralType;
1147e5dd7070Spatrick 
1148e5dd7070Spatrick   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
1149e5dd7070Spatrick 
1150e5dd7070Spatrick   if (getLangOpts().OpenCL) {
1151e5dd7070Spatrick     // struct __opencl_block_literal_generic {
1152e5dd7070Spatrick     //   int __size;
1153e5dd7070Spatrick     //   int __align;
1154e5dd7070Spatrick     //   __generic void *__invoke;
1155e5dd7070Spatrick     //   /* custom fields */
1156e5dd7070Spatrick     // };
1157e5dd7070Spatrick     SmallVector<llvm::Type *, 8> StructFields(
1158e5dd7070Spatrick         {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1159e5dd7070Spatrick     if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1160*12c85518Srobert       llvm::append_range(StructFields, Helper->getCustomFieldTypes());
1161e5dd7070Spatrick     }
1162e5dd7070Spatrick     GenericBlockLiteralType = llvm::StructType::create(
1163e5dd7070Spatrick         StructFields, "struct.__opencl_block_literal_generic");
1164e5dd7070Spatrick   } else {
1165e5dd7070Spatrick     // struct __block_literal_generic {
1166e5dd7070Spatrick     //   void *__isa;
1167e5dd7070Spatrick     //   int __flags;
1168e5dd7070Spatrick     //   int __reserved;
1169e5dd7070Spatrick     //   void (*__invoke)(void *);
1170e5dd7070Spatrick     //   struct __block_descriptor *__descriptor;
1171e5dd7070Spatrick     // };
1172e5dd7070Spatrick     GenericBlockLiteralType =
1173e5dd7070Spatrick         llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1174e5dd7070Spatrick                                  IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1175e5dd7070Spatrick   }
1176e5dd7070Spatrick 
1177e5dd7070Spatrick   return GenericBlockLiteralType;
1178e5dd7070Spatrick }
1179e5dd7070Spatrick 
EmitBlockCallExpr(const CallExpr * E,ReturnValueSlot ReturnValue)1180e5dd7070Spatrick RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
1181e5dd7070Spatrick                                           ReturnValueSlot ReturnValue) {
1182e5dd7070Spatrick   const auto *BPT = E->getCallee()->getType()->castAs<BlockPointerType>();
1183e5dd7070Spatrick   llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
1184e5dd7070Spatrick   llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType();
1185e5dd7070Spatrick   llvm::Value *Func = nullptr;
1186e5dd7070Spatrick   QualType FnType = BPT->getPointeeType();
1187e5dd7070Spatrick   ASTContext &Ctx = getContext();
1188e5dd7070Spatrick   CallArgList Args;
1189e5dd7070Spatrick 
1190e5dd7070Spatrick   if (getLangOpts().OpenCL) {
1191e5dd7070Spatrick     // For OpenCL, BlockPtr is already casted to generic block literal.
1192e5dd7070Spatrick 
1193e5dd7070Spatrick     // First argument of a block call is a generic block literal casted to
1194e5dd7070Spatrick     // generic void pointer, i.e. i8 addrspace(4)*
1195a9ac8606Spatrick     llvm::Type *GenericVoidPtrTy =
1196a9ac8606Spatrick         CGM.getOpenCLRuntime().getGenericVoidPointerType();
1197e5dd7070Spatrick     llvm::Value *BlockDescriptor = Builder.CreatePointerCast(
1198a9ac8606Spatrick         BlockPtr, GenericVoidPtrTy);
1199e5dd7070Spatrick     QualType VoidPtrQualTy = Ctx.getPointerType(
1200e5dd7070Spatrick         Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic));
1201e5dd7070Spatrick     Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy);
1202e5dd7070Spatrick     // And the rest of the arguments.
1203e5dd7070Spatrick     EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1204e5dd7070Spatrick 
1205e5dd7070Spatrick     // We *can* call the block directly unless it is a function argument.
1206e5dd7070Spatrick     if (!isa<ParmVarDecl>(E->getCalleeDecl()))
1207e5dd7070Spatrick       Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1208e5dd7070Spatrick     else {
1209e5dd7070Spatrick       llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
1210a9ac8606Spatrick       Func = Builder.CreateAlignedLoad(GenericVoidPtrTy, FuncPtr,
1211a9ac8606Spatrick                                        getPointerAlign());
1212e5dd7070Spatrick     }
1213e5dd7070Spatrick   } else {
1214e5dd7070Spatrick     // Bitcast the block literal to a generic block literal.
1215e5dd7070Spatrick     BlockPtr = Builder.CreatePointerCast(
1216e5dd7070Spatrick         BlockPtr, llvm::PointerType::get(GenBlockTy, 0), "block.literal");
1217e5dd7070Spatrick     // Get pointer to the block invoke function
1218e5dd7070Spatrick     llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
1219e5dd7070Spatrick 
1220e5dd7070Spatrick     // First argument is a block literal casted to a void pointer
1221e5dd7070Spatrick     BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
1222e5dd7070Spatrick     Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy);
1223e5dd7070Spatrick     // And the rest of the arguments.
1224e5dd7070Spatrick     EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1225e5dd7070Spatrick 
1226e5dd7070Spatrick     // Load the function.
1227a9ac8606Spatrick     Func = Builder.CreateAlignedLoad(VoidPtrTy, FuncPtr, getPointerAlign());
1228e5dd7070Spatrick   }
1229e5dd7070Spatrick 
1230e5dd7070Spatrick   const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1231e5dd7070Spatrick   const CGFunctionInfo &FnInfo =
1232e5dd7070Spatrick     CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1233e5dd7070Spatrick 
1234e5dd7070Spatrick   // Cast the function pointer to the right type.
1235e5dd7070Spatrick   llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1236e5dd7070Spatrick 
1237e5dd7070Spatrick   llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1238e5dd7070Spatrick   Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
1239e5dd7070Spatrick 
1240e5dd7070Spatrick   // Prepare the callee.
1241e5dd7070Spatrick   CGCallee Callee(CGCalleeInfo(), Func);
1242e5dd7070Spatrick 
1243e5dd7070Spatrick   // And call the block.
1244e5dd7070Spatrick   return EmitCall(FnInfo, Callee, ReturnValue, Args);
1245e5dd7070Spatrick }
1246e5dd7070Spatrick 
GetAddrOfBlockDecl(const VarDecl * variable)1247e5dd7070Spatrick Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
1248e5dd7070Spatrick   assert(BlockInfo && "evaluating block ref without block information?");
1249e5dd7070Spatrick   const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1250e5dd7070Spatrick 
1251e5dd7070Spatrick   // Handle constant captures.
1252e5dd7070Spatrick   if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1253e5dd7070Spatrick 
1254e5dd7070Spatrick   Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1255e5dd7070Spatrick                                          "block.capture.addr");
1256e5dd7070Spatrick 
1257e5dd7070Spatrick   if (variable->isEscapingByref()) {
1258e5dd7070Spatrick     // addr should be a void** right now.  Load, then cast the result
1259e5dd7070Spatrick     // to byref*.
1260e5dd7070Spatrick 
1261e5dd7070Spatrick     auto &byrefInfo = getBlockByrefInfo(variable);
1262*12c85518Srobert     addr = Address(Builder.CreateLoad(addr), Int8Ty, byrefInfo.ByrefAlignment);
1263e5dd7070Spatrick 
1264*12c85518Srobert     addr = Builder.CreateElementBitCast(addr, byrefInfo.Type, "byref.addr");
1265e5dd7070Spatrick 
1266e5dd7070Spatrick     addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1267e5dd7070Spatrick                                  variable->getName());
1268e5dd7070Spatrick   }
1269e5dd7070Spatrick 
1270e5dd7070Spatrick   assert((!variable->isNonEscapingByref() ||
1271e5dd7070Spatrick           capture.fieldType()->isReferenceType()) &&
1272e5dd7070Spatrick          "the capture field of a non-escaping variable should have a "
1273e5dd7070Spatrick          "reference type");
1274e5dd7070Spatrick   if (capture.fieldType()->isReferenceType())
1275e5dd7070Spatrick     addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
1276e5dd7070Spatrick 
1277e5dd7070Spatrick   return addr;
1278e5dd7070Spatrick }
1279e5dd7070Spatrick 
setAddrOfGlobalBlock(const BlockExpr * BE,llvm::Constant * Addr)1280e5dd7070Spatrick void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1281e5dd7070Spatrick                                          llvm::Constant *Addr) {
1282e5dd7070Spatrick   bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1283e5dd7070Spatrick   (void)Ok;
1284e5dd7070Spatrick   assert(Ok && "Trying to replace an already-existing global block!");
1285e5dd7070Spatrick }
1286e5dd7070Spatrick 
1287e5dd7070Spatrick llvm::Constant *
GetAddrOfGlobalBlock(const BlockExpr * BE,StringRef Name)1288e5dd7070Spatrick CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1289e5dd7070Spatrick                                     StringRef Name) {
1290e5dd7070Spatrick   if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1291e5dd7070Spatrick     return Block;
1292e5dd7070Spatrick 
1293e5dd7070Spatrick   CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1294e5dd7070Spatrick   blockInfo.BlockExpression = BE;
1295e5dd7070Spatrick 
1296e5dd7070Spatrick   // Compute information about the layout, etc., of this block.
1297e5dd7070Spatrick   computeBlockInfo(*this, nullptr, blockInfo);
1298e5dd7070Spatrick 
1299e5dd7070Spatrick   // Using that metadata, generate the actual block function.
1300e5dd7070Spatrick   {
1301e5dd7070Spatrick     CodeGenFunction::DeclMapTy LocalDeclMap;
1302e5dd7070Spatrick     CodeGenFunction(*this).GenerateBlockFunction(
1303e5dd7070Spatrick         GlobalDecl(), blockInfo, LocalDeclMap,
1304e5dd7070Spatrick         /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1305e5dd7070Spatrick   }
1306e5dd7070Spatrick 
1307e5dd7070Spatrick   return getAddrOfGlobalBlockIfEmitted(BE);
1308e5dd7070Spatrick }
1309e5dd7070Spatrick 
buildGlobalBlock(CodeGenModule & CGM,const CGBlockInfo & blockInfo,llvm::Constant * blockFn)1310e5dd7070Spatrick static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1311e5dd7070Spatrick                                         const CGBlockInfo &blockInfo,
1312e5dd7070Spatrick                                         llvm::Constant *blockFn) {
1313e5dd7070Spatrick   assert(blockInfo.CanBeGlobal);
1314e5dd7070Spatrick   // Callers should detect this case on their own: calling this function
1315e5dd7070Spatrick   // generally requires computing layout information, which is a waste of time
1316e5dd7070Spatrick   // if we've already emitted this block.
1317e5dd7070Spatrick   assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1318e5dd7070Spatrick          "Refusing to re-emit a global block.");
1319e5dd7070Spatrick 
1320e5dd7070Spatrick   // Generate the constants for the block literal initializer.
1321e5dd7070Spatrick   ConstantInitBuilder builder(CGM);
1322e5dd7070Spatrick   auto fields = builder.beginStruct();
1323e5dd7070Spatrick 
1324e5dd7070Spatrick   bool IsOpenCL = CGM.getLangOpts().OpenCL;
1325e5dd7070Spatrick   bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
1326e5dd7070Spatrick   if (!IsOpenCL) {
1327e5dd7070Spatrick     // isa
1328e5dd7070Spatrick     if (IsWindows)
1329e5dd7070Spatrick       fields.addNullPointer(CGM.Int8PtrPtrTy);
1330e5dd7070Spatrick     else
1331e5dd7070Spatrick       fields.add(CGM.getNSConcreteGlobalBlock());
1332e5dd7070Spatrick 
1333e5dd7070Spatrick     // __flags
1334e5dd7070Spatrick     BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1335e5dd7070Spatrick     if (blockInfo.UsesStret)
1336e5dd7070Spatrick       flags |= BLOCK_USE_STRET;
1337e5dd7070Spatrick 
1338e5dd7070Spatrick     fields.addInt(CGM.IntTy, flags.getBitMask());
1339e5dd7070Spatrick 
1340e5dd7070Spatrick     // Reserved
1341e5dd7070Spatrick     fields.addInt(CGM.IntTy, 0);
1342e5dd7070Spatrick   } else {
1343e5dd7070Spatrick     fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1344e5dd7070Spatrick     fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1345e5dd7070Spatrick   }
1346e5dd7070Spatrick 
1347e5dd7070Spatrick   // Function
1348e5dd7070Spatrick   fields.add(blockFn);
1349e5dd7070Spatrick 
1350e5dd7070Spatrick   if (!IsOpenCL) {
1351e5dd7070Spatrick     // Descriptor
1352e5dd7070Spatrick     fields.add(buildBlockDescriptor(CGM, blockInfo));
1353e5dd7070Spatrick   } else if (auto *Helper =
1354e5dd7070Spatrick                  CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1355*12c85518Srobert     for (auto *I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1356e5dd7070Spatrick       fields.add(I);
1357e5dd7070Spatrick     }
1358e5dd7070Spatrick   }
1359e5dd7070Spatrick 
1360e5dd7070Spatrick   unsigned AddrSpace = 0;
1361e5dd7070Spatrick   if (CGM.getContext().getLangOpts().OpenCL)
1362e5dd7070Spatrick     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1363e5dd7070Spatrick 
1364e5dd7070Spatrick   llvm::GlobalVariable *literal = fields.finishAndCreateGlobal(
1365e5dd7070Spatrick       "__block_literal_global", blockInfo.BlockAlign,
1366e5dd7070Spatrick       /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1367e5dd7070Spatrick 
1368e5dd7070Spatrick   literal->addAttribute("objc_arc_inert");
1369e5dd7070Spatrick 
1370e5dd7070Spatrick   // Windows does not allow globals to be initialised to point to globals in
1371e5dd7070Spatrick   // different DLLs.  Any such variables must run code to initialise them.
1372e5dd7070Spatrick   if (IsWindows) {
1373e5dd7070Spatrick     auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1374e5dd7070Spatrick           {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1375e5dd7070Spatrick         &CGM.getModule());
1376e5dd7070Spatrick     llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1377e5dd7070Spatrick           Init));
1378e5dd7070Spatrick     b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1379a9ac8606Spatrick                          b.CreateStructGEP(literal->getValueType(), literal, 0),
1380ec727ea7Spatrick                          CGM.getPointerAlign().getAsAlign());
1381e5dd7070Spatrick     b.CreateRetVoid();
1382e5dd7070Spatrick     // We can't use the normal LLVM global initialisation array, because we
1383e5dd7070Spatrick     // need to specify that this runs early in library initialisation.
1384e5dd7070Spatrick     auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1385e5dd7070Spatrick         /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1386e5dd7070Spatrick         Init, ".block_isa_init_ptr");
1387e5dd7070Spatrick     InitVar->setSection(".CRT$XCLa");
1388e5dd7070Spatrick     CGM.addUsedGlobal(InitVar);
1389e5dd7070Spatrick   }
1390e5dd7070Spatrick 
1391e5dd7070Spatrick   // Return a constant of the appropriately-casted type.
1392e5dd7070Spatrick   llvm::Type *RequiredType =
1393e5dd7070Spatrick     CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1394e5dd7070Spatrick   llvm::Constant *Result =
1395e5dd7070Spatrick       llvm::ConstantExpr::getPointerCast(literal, RequiredType);
1396e5dd7070Spatrick   CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1397e5dd7070Spatrick   if (CGM.getContext().getLangOpts().OpenCL)
1398e5dd7070Spatrick     CGM.getOpenCLRuntime().recordBlockInfo(
1399e5dd7070Spatrick         blockInfo.BlockExpression,
1400*12c85518Srobert         cast<llvm::Function>(blockFn->stripPointerCasts()), Result,
1401*12c85518Srobert         literal->getValueType());
1402e5dd7070Spatrick   return Result;
1403e5dd7070Spatrick }
1404e5dd7070Spatrick 
setBlockContextParameter(const ImplicitParamDecl * D,unsigned argNum,llvm::Value * arg)1405e5dd7070Spatrick void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1406e5dd7070Spatrick                                                unsigned argNum,
1407e5dd7070Spatrick                                                llvm::Value *arg) {
1408e5dd7070Spatrick   assert(BlockInfo && "not emitting prologue of block invocation function?!");
1409e5dd7070Spatrick 
1410e5dd7070Spatrick   // Allocate a stack slot like for any local variable to guarantee optimal
1411e5dd7070Spatrick   // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1412e5dd7070Spatrick   Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1413e5dd7070Spatrick   Builder.CreateStore(arg, alloc);
1414e5dd7070Spatrick   if (CGDebugInfo *DI = getDebugInfo()) {
1415e5dd7070Spatrick     if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
1416e5dd7070Spatrick       DI->setLocation(D->getLocation());
1417e5dd7070Spatrick       DI->EmitDeclareOfBlockLiteralArgVariable(
1418e5dd7070Spatrick           *BlockInfo, D->getName(), argNum,
1419e5dd7070Spatrick           cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
1420e5dd7070Spatrick     }
1421e5dd7070Spatrick   }
1422e5dd7070Spatrick 
1423e5dd7070Spatrick   SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
1424e5dd7070Spatrick   ApplyDebugLocation Scope(*this, StartLoc);
1425e5dd7070Spatrick 
1426e5dd7070Spatrick   // Instead of messing around with LocalDeclMap, just set the value
1427e5dd7070Spatrick   // directly as BlockPointer.
1428e5dd7070Spatrick   BlockPointer = Builder.CreatePointerCast(
1429e5dd7070Spatrick       arg,
1430e5dd7070Spatrick       BlockInfo->StructureType->getPointerTo(
1431e5dd7070Spatrick           getContext().getLangOpts().OpenCL
1432e5dd7070Spatrick               ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1433e5dd7070Spatrick               : 0),
1434e5dd7070Spatrick       "block");
1435e5dd7070Spatrick }
1436e5dd7070Spatrick 
LoadBlockStruct()1437e5dd7070Spatrick Address CodeGenFunction::LoadBlockStruct() {
1438e5dd7070Spatrick   assert(BlockInfo && "not in a block invocation function!");
1439e5dd7070Spatrick   assert(BlockPointer && "no block pointer set!");
1440*12c85518Srobert   return Address(BlockPointer, BlockInfo->StructureType, BlockInfo->BlockAlign);
1441e5dd7070Spatrick }
1442e5dd7070Spatrick 
GenerateBlockFunction(GlobalDecl GD,const CGBlockInfo & blockInfo,const DeclMapTy & ldm,bool IsLambdaConversionToBlock,bool BuildGlobalBlock)1443*12c85518Srobert llvm::Function *CodeGenFunction::GenerateBlockFunction(
1444*12c85518Srobert     GlobalDecl GD, const CGBlockInfo &blockInfo, const DeclMapTy &ldm,
1445*12c85518Srobert     bool IsLambdaConversionToBlock, bool BuildGlobalBlock) {
1446e5dd7070Spatrick   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1447e5dd7070Spatrick 
1448e5dd7070Spatrick   CurGD = GD;
1449e5dd7070Spatrick 
1450e5dd7070Spatrick   CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
1451e5dd7070Spatrick 
1452e5dd7070Spatrick   BlockInfo = &blockInfo;
1453e5dd7070Spatrick 
1454e5dd7070Spatrick   // Arrange for local static and local extern declarations to appear
1455e5dd7070Spatrick   // to be local to this function as well, in case they're directly
1456e5dd7070Spatrick   // referenced in a block.
1457e5dd7070Spatrick   for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1458e5dd7070Spatrick     const auto *var = dyn_cast<VarDecl>(i->first);
1459e5dd7070Spatrick     if (var && !var->hasLocalStorage())
1460e5dd7070Spatrick       setAddrOfLocalVar(var, i->second);
1461e5dd7070Spatrick   }
1462e5dd7070Spatrick 
1463e5dd7070Spatrick   // Begin building the function declaration.
1464e5dd7070Spatrick 
1465e5dd7070Spatrick   // Build the argument list.
1466e5dd7070Spatrick   FunctionArgList args;
1467e5dd7070Spatrick 
1468e5dd7070Spatrick   // The first argument is the block pointer.  Just take it as a void*
1469e5dd7070Spatrick   // and cast it later.
1470e5dd7070Spatrick   QualType selfTy = getContext().VoidPtrTy;
1471e5dd7070Spatrick 
1472e5dd7070Spatrick   // For OpenCL passed block pointer can be private AS local variable or
1473e5dd7070Spatrick   // global AS program scope variable (for the case with and without captures).
1474e5dd7070Spatrick   // Generic AS is used therefore to be able to accommodate both private and
1475e5dd7070Spatrick   // generic AS in one implementation.
1476e5dd7070Spatrick   if (getLangOpts().OpenCL)
1477e5dd7070Spatrick     selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1478e5dd7070Spatrick         getContext().VoidTy, LangAS::opencl_generic));
1479e5dd7070Spatrick 
1480e5dd7070Spatrick   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1481e5dd7070Spatrick 
1482e5dd7070Spatrick   ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1483e5dd7070Spatrick                              SourceLocation(), II, selfTy,
1484e5dd7070Spatrick                              ImplicitParamDecl::ObjCSelf);
1485e5dd7070Spatrick   args.push_back(&SelfDecl);
1486e5dd7070Spatrick 
1487e5dd7070Spatrick   // Now add the rest of the parameters.
1488e5dd7070Spatrick   args.append(blockDecl->param_begin(), blockDecl->param_end());
1489e5dd7070Spatrick 
1490e5dd7070Spatrick   // Create the function declaration.
1491e5dd7070Spatrick   const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1492e5dd7070Spatrick   const CGFunctionInfo &fnInfo =
1493e5dd7070Spatrick     CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1494e5dd7070Spatrick   if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1495e5dd7070Spatrick     blockInfo.UsesStret = true;
1496e5dd7070Spatrick 
1497e5dd7070Spatrick   llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1498e5dd7070Spatrick 
1499e5dd7070Spatrick   StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1500e5dd7070Spatrick   llvm::Function *fn = llvm::Function::Create(
1501e5dd7070Spatrick       fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1502e5dd7070Spatrick   CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1503e5dd7070Spatrick 
1504e5dd7070Spatrick   if (BuildGlobalBlock) {
1505e5dd7070Spatrick     auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1506e5dd7070Spatrick                             ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1507e5dd7070Spatrick                             : VoidPtrTy;
1508e5dd7070Spatrick     buildGlobalBlock(CGM, blockInfo,
1509e5dd7070Spatrick                      llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1510e5dd7070Spatrick   }
1511e5dd7070Spatrick 
1512e5dd7070Spatrick   // Begin generating the function.
1513e5dd7070Spatrick   StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1514e5dd7070Spatrick                 blockDecl->getLocation(),
1515e5dd7070Spatrick                 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
1516e5dd7070Spatrick 
1517e5dd7070Spatrick   // Okay.  Undo some of what StartFunction did.
1518e5dd7070Spatrick 
1519e5dd7070Spatrick   // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1520e5dd7070Spatrick   // won't delete the dbg.declare intrinsics for captured variables.
1521e5dd7070Spatrick   llvm::Value *BlockPointerDbgLoc = BlockPointer;
1522e5dd7070Spatrick   if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1523e5dd7070Spatrick     // Allocate a stack slot for it, so we can point the debugger to it
1524e5dd7070Spatrick     Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1525e5dd7070Spatrick                                       getPointerAlign(),
1526e5dd7070Spatrick                                       "block.addr");
1527e5dd7070Spatrick     // Set the DebugLocation to empty, so the store is recognized as a
1528e5dd7070Spatrick     // frame setup instruction by llvm::DwarfDebug::beginFunction().
1529e5dd7070Spatrick     auto NL = ApplyDebugLocation::CreateEmpty(*this);
1530e5dd7070Spatrick     Builder.CreateStore(BlockPointer, Alloca);
1531e5dd7070Spatrick     BlockPointerDbgLoc = Alloca.getPointer();
1532e5dd7070Spatrick   }
1533e5dd7070Spatrick 
1534e5dd7070Spatrick   // If we have a C++ 'this' reference, go ahead and force it into
1535e5dd7070Spatrick   // existence now.
1536e5dd7070Spatrick   if (blockDecl->capturesCXXThis()) {
1537e5dd7070Spatrick     Address addr = Builder.CreateStructGEP(
1538e5dd7070Spatrick         LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this");
1539e5dd7070Spatrick     CXXThisValue = Builder.CreateLoad(addr, "this");
1540e5dd7070Spatrick   }
1541e5dd7070Spatrick 
1542e5dd7070Spatrick   // Also force all the constant captures.
1543e5dd7070Spatrick   for (const auto &CI : blockDecl->captures()) {
1544e5dd7070Spatrick     const VarDecl *variable = CI.getVariable();
1545e5dd7070Spatrick     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1546e5dd7070Spatrick     if (!capture.isConstant()) continue;
1547e5dd7070Spatrick 
1548e5dd7070Spatrick     CharUnits align = getContext().getDeclAlign(variable);
1549e5dd7070Spatrick     Address alloca =
1550e5dd7070Spatrick       CreateMemTemp(variable->getType(), align, "block.captured-const");
1551e5dd7070Spatrick 
1552e5dd7070Spatrick     Builder.CreateStore(capture.getConstant(), alloca);
1553e5dd7070Spatrick 
1554e5dd7070Spatrick     setAddrOfLocalVar(variable, alloca);
1555e5dd7070Spatrick   }
1556e5dd7070Spatrick 
1557e5dd7070Spatrick   // Save a spot to insert the debug information for all the DeclRefExprs.
1558e5dd7070Spatrick   llvm::BasicBlock *entry = Builder.GetInsertBlock();
1559e5dd7070Spatrick   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1560e5dd7070Spatrick   --entry_ptr;
1561e5dd7070Spatrick 
1562e5dd7070Spatrick   if (IsLambdaConversionToBlock)
1563e5dd7070Spatrick     EmitLambdaBlockInvokeBody();
1564e5dd7070Spatrick   else {
1565e5dd7070Spatrick     PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1566e5dd7070Spatrick     incrementProfileCounter(blockDecl->getBody());
1567e5dd7070Spatrick     EmitStmt(blockDecl->getBody());
1568e5dd7070Spatrick   }
1569e5dd7070Spatrick 
1570e5dd7070Spatrick   // Remember where we were...
1571e5dd7070Spatrick   llvm::BasicBlock *resume = Builder.GetInsertBlock();
1572e5dd7070Spatrick 
1573e5dd7070Spatrick   // Go back to the entry.
1574e5dd7070Spatrick   ++entry_ptr;
1575e5dd7070Spatrick   Builder.SetInsertPoint(entry, entry_ptr);
1576e5dd7070Spatrick 
1577e5dd7070Spatrick   // Emit debug information for all the DeclRefExprs.
1578e5dd7070Spatrick   // FIXME: also for 'this'
1579e5dd7070Spatrick   if (CGDebugInfo *DI = getDebugInfo()) {
1580e5dd7070Spatrick     for (const auto &CI : blockDecl->captures()) {
1581e5dd7070Spatrick       const VarDecl *variable = CI.getVariable();
1582e5dd7070Spatrick       DI->EmitLocation(Builder, variable->getLocation());
1583e5dd7070Spatrick 
1584e5dd7070Spatrick       if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
1585e5dd7070Spatrick         const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1586e5dd7070Spatrick         if (capture.isConstant()) {
1587e5dd7070Spatrick           auto addr = LocalDeclMap.find(variable)->second;
1588e5dd7070Spatrick           (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1589e5dd7070Spatrick                                               Builder);
1590e5dd7070Spatrick           continue;
1591e5dd7070Spatrick         }
1592e5dd7070Spatrick 
1593e5dd7070Spatrick         DI->EmitDeclareOfBlockDeclRefVariable(
1594e5dd7070Spatrick             variable, BlockPointerDbgLoc, Builder, blockInfo,
1595e5dd7070Spatrick             entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1596e5dd7070Spatrick       }
1597e5dd7070Spatrick     }
1598e5dd7070Spatrick     // Recover location if it was changed in the above loop.
1599e5dd7070Spatrick     DI->EmitLocation(Builder,
1600e5dd7070Spatrick                      cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1601e5dd7070Spatrick   }
1602e5dd7070Spatrick 
1603e5dd7070Spatrick   // And resume where we left off.
1604e5dd7070Spatrick   if (resume == nullptr)
1605e5dd7070Spatrick     Builder.ClearInsertionPoint();
1606e5dd7070Spatrick   else
1607e5dd7070Spatrick     Builder.SetInsertPoint(resume);
1608e5dd7070Spatrick 
1609e5dd7070Spatrick   FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1610e5dd7070Spatrick 
1611e5dd7070Spatrick   return fn;
1612e5dd7070Spatrick }
1613e5dd7070Spatrick 
1614e5dd7070Spatrick static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
computeCopyInfoForBlockCapture(const BlockDecl::Capture & CI,QualType T,const LangOptions & LangOpts)1615e5dd7070Spatrick computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1616e5dd7070Spatrick                                const LangOptions &LangOpts) {
1617e5dd7070Spatrick   if (CI.getCopyExpr()) {
1618e5dd7070Spatrick     assert(!CI.isByRef());
1619e5dd7070Spatrick     // don't bother computing flags
1620e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1621e5dd7070Spatrick   }
1622e5dd7070Spatrick   BlockFieldFlags Flags;
1623e5dd7070Spatrick   if (CI.isEscapingByref()) {
1624e5dd7070Spatrick     Flags = BLOCK_FIELD_IS_BYREF;
1625e5dd7070Spatrick     if (T.isObjCGCWeak())
1626e5dd7070Spatrick       Flags |= BLOCK_FIELD_IS_WEAK;
1627e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1628e5dd7070Spatrick   }
1629e5dd7070Spatrick 
1630e5dd7070Spatrick   Flags = BLOCK_FIELD_IS_OBJECT;
1631e5dd7070Spatrick   bool isBlockPointer = T->isBlockPointerType();
1632e5dd7070Spatrick   if (isBlockPointer)
1633e5dd7070Spatrick     Flags = BLOCK_FIELD_IS_BLOCK;
1634e5dd7070Spatrick 
1635e5dd7070Spatrick   switch (T.isNonTrivialToPrimitiveCopy()) {
1636e5dd7070Spatrick   case QualType::PCK_Struct:
1637e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1638e5dd7070Spatrick                           BlockFieldFlags());
1639e5dd7070Spatrick   case QualType::PCK_ARCWeak:
1640e5dd7070Spatrick     // We need to register __weak direct captures with the runtime.
1641e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1642e5dd7070Spatrick   case QualType::PCK_ARCStrong:
1643e5dd7070Spatrick     // We need to retain the copied value for __strong direct captures.
1644e5dd7070Spatrick     // If it's a block pointer, we have to copy the block and assign that to
1645e5dd7070Spatrick     // the destination pointer, so we might as well use _Block_object_assign.
1646e5dd7070Spatrick     // Otherwise we can avoid that.
1647e5dd7070Spatrick     return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1648e5dd7070Spatrick                                           : BlockCaptureEntityKind::BlockObject,
1649e5dd7070Spatrick                           Flags);
1650e5dd7070Spatrick   case QualType::PCK_Trivial:
1651e5dd7070Spatrick   case QualType::PCK_VolatileTrivial: {
1652e5dd7070Spatrick     if (!T->isObjCRetainableType())
1653e5dd7070Spatrick       // For all other types, the memcpy is fine.
1654e5dd7070Spatrick       return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1655e5dd7070Spatrick 
1656*12c85518Srobert     // Honor the inert __unsafe_unretained qualifier, which doesn't actually
1657*12c85518Srobert     // make it into the type system.
1658*12c85518Srobert     if (T->isObjCInertUnsafeUnretainedType())
1659*12c85518Srobert       return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1660*12c85518Srobert 
1661e5dd7070Spatrick     // Special rules for ARC captures:
1662e5dd7070Spatrick     Qualifiers QS = T.getQualifiers();
1663e5dd7070Spatrick 
1664e5dd7070Spatrick     // Non-ARC captures of retainable pointers are strong and
1665e5dd7070Spatrick     // therefore require a call to _Block_object_assign.
1666e5dd7070Spatrick     if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1667e5dd7070Spatrick       return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1668e5dd7070Spatrick 
1669e5dd7070Spatrick     // Otherwise the memcpy is fine.
1670e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1671e5dd7070Spatrick   }
1672e5dd7070Spatrick   }
1673e5dd7070Spatrick   llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
1674e5dd7070Spatrick }
1675e5dd7070Spatrick 
1676e5dd7070Spatrick namespace {
1677e5dd7070Spatrick /// Release a __block variable.
1678e5dd7070Spatrick struct CallBlockRelease final : EHScopeStack::Cleanup {
1679e5dd7070Spatrick   Address Addr;
1680e5dd7070Spatrick   BlockFieldFlags FieldFlags;
1681e5dd7070Spatrick   bool LoadBlockVarAddr, CanThrow;
1682e5dd7070Spatrick 
CallBlockRelease__anon3298161d0811::CallBlockRelease1683e5dd7070Spatrick   CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1684e5dd7070Spatrick                    bool CT)
1685e5dd7070Spatrick       : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1686e5dd7070Spatrick         CanThrow(CT) {}
1687e5dd7070Spatrick 
Emit__anon3298161d0811::CallBlockRelease1688e5dd7070Spatrick   void Emit(CodeGenFunction &CGF, Flags flags) override {
1689e5dd7070Spatrick     llvm::Value *BlockVarAddr;
1690e5dd7070Spatrick     if (LoadBlockVarAddr) {
1691e5dd7070Spatrick       BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1692e5dd7070Spatrick       BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1693e5dd7070Spatrick     } else {
1694e5dd7070Spatrick       BlockVarAddr = Addr.getPointer();
1695e5dd7070Spatrick     }
1696e5dd7070Spatrick 
1697e5dd7070Spatrick     CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
1698e5dd7070Spatrick   }
1699e5dd7070Spatrick };
1700e5dd7070Spatrick } // end anonymous namespace
1701e5dd7070Spatrick 
1702e5dd7070Spatrick /// Check if \p T is a C++ class that has a destructor that can throw.
cxxDestructorCanThrow(QualType T)1703e5dd7070Spatrick bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1704e5dd7070Spatrick   if (const auto *RD = T->getAsCXXRecordDecl())
1705e5dd7070Spatrick     if (const CXXDestructorDecl *DD = RD->getDestructor())
1706e5dd7070Spatrick       return DD->getType()->castAs<FunctionProtoType>()->canThrow();
1707e5dd7070Spatrick   return false;
1708e5dd7070Spatrick }
1709e5dd7070Spatrick 
1710e5dd7070Spatrick // Return a string that has the information about a capture.
getBlockCaptureStr(const CGBlockInfo::Capture & Cap,CaptureStrKind StrKind,CharUnits BlockAlignment,CodeGenModule & CGM)1711*12c85518Srobert static std::string getBlockCaptureStr(const CGBlockInfo::Capture &Cap,
1712e5dd7070Spatrick                                       CaptureStrKind StrKind,
1713e5dd7070Spatrick                                       CharUnits BlockAlignment,
1714e5dd7070Spatrick                                       CodeGenModule &CGM) {
1715e5dd7070Spatrick   std::string Str;
1716e5dd7070Spatrick   ASTContext &Ctx = CGM.getContext();
1717*12c85518Srobert   const BlockDecl::Capture &CI = *Cap.Cap;
1718e5dd7070Spatrick   QualType CaptureTy = CI.getVariable()->getType();
1719e5dd7070Spatrick 
1720e5dd7070Spatrick   BlockCaptureEntityKind Kind;
1721e5dd7070Spatrick   BlockFieldFlags Flags;
1722e5dd7070Spatrick 
1723e5dd7070Spatrick   // CaptureStrKind::Merged should be passed only when the operations and the
1724e5dd7070Spatrick   // flags are the same for copy and dispose.
1725e5dd7070Spatrick   assert((StrKind != CaptureStrKind::Merged ||
1726*12c85518Srobert           (Cap.CopyKind == Cap.DisposeKind &&
1727*12c85518Srobert            Cap.CopyFlags == Cap.DisposeFlags)) &&
1728e5dd7070Spatrick          "different operations and flags");
1729e5dd7070Spatrick 
1730e5dd7070Spatrick   if (StrKind == CaptureStrKind::DisposeHelper) {
1731*12c85518Srobert     Kind = Cap.DisposeKind;
1732*12c85518Srobert     Flags = Cap.DisposeFlags;
1733e5dd7070Spatrick   } else {
1734*12c85518Srobert     Kind = Cap.CopyKind;
1735*12c85518Srobert     Flags = Cap.CopyFlags;
1736e5dd7070Spatrick   }
1737e5dd7070Spatrick 
1738e5dd7070Spatrick   switch (Kind) {
1739e5dd7070Spatrick   case BlockCaptureEntityKind::CXXRecord: {
1740e5dd7070Spatrick     Str += "c";
1741e5dd7070Spatrick     SmallString<256> TyStr;
1742e5dd7070Spatrick     llvm::raw_svector_ostream Out(TyStr);
1743e5dd7070Spatrick     CGM.getCXXABI().getMangleContext().mangleTypeName(CaptureTy, Out);
1744e5dd7070Spatrick     Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
1745e5dd7070Spatrick     break;
1746e5dd7070Spatrick   }
1747e5dd7070Spatrick   case BlockCaptureEntityKind::ARCWeak:
1748e5dd7070Spatrick     Str += "w";
1749e5dd7070Spatrick     break;
1750e5dd7070Spatrick   case BlockCaptureEntityKind::ARCStrong:
1751e5dd7070Spatrick     Str += "s";
1752e5dd7070Spatrick     break;
1753e5dd7070Spatrick   case BlockCaptureEntityKind::BlockObject: {
1754e5dd7070Spatrick     const VarDecl *Var = CI.getVariable();
1755e5dd7070Spatrick     unsigned F = Flags.getBitMask();
1756e5dd7070Spatrick     if (F & BLOCK_FIELD_IS_BYREF) {
1757e5dd7070Spatrick       Str += "r";
1758e5dd7070Spatrick       if (F & BLOCK_FIELD_IS_WEAK)
1759e5dd7070Spatrick         Str += "w";
1760e5dd7070Spatrick       else {
1761e5dd7070Spatrick         // If CaptureStrKind::Merged is passed, check both the copy expression
1762e5dd7070Spatrick         // and the destructor.
1763e5dd7070Spatrick         if (StrKind != CaptureStrKind::DisposeHelper) {
1764e5dd7070Spatrick           if (Ctx.getBlockVarCopyInit(Var).canThrow())
1765e5dd7070Spatrick             Str += "c";
1766e5dd7070Spatrick         }
1767e5dd7070Spatrick         if (StrKind != CaptureStrKind::CopyHelper) {
1768e5dd7070Spatrick           if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1769e5dd7070Spatrick             Str += "d";
1770e5dd7070Spatrick         }
1771e5dd7070Spatrick       }
1772e5dd7070Spatrick     } else {
1773e5dd7070Spatrick       assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
1774e5dd7070Spatrick       if (F == BLOCK_FIELD_IS_BLOCK)
1775e5dd7070Spatrick         Str += "b";
1776e5dd7070Spatrick       else
1777e5dd7070Spatrick         Str += "o";
1778e5dd7070Spatrick     }
1779e5dd7070Spatrick     break;
1780e5dd7070Spatrick   }
1781e5dd7070Spatrick   case BlockCaptureEntityKind::NonTrivialCStruct: {
1782e5dd7070Spatrick     bool IsVolatile = CaptureTy.isVolatileQualified();
1783*12c85518Srobert     CharUnits Alignment = BlockAlignment.alignmentAtOffset(Cap.getOffset());
1784e5dd7070Spatrick 
1785e5dd7070Spatrick     Str += "n";
1786e5dd7070Spatrick     std::string FuncStr;
1787e5dd7070Spatrick     if (StrKind == CaptureStrKind::DisposeHelper)
1788e5dd7070Spatrick       FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
1789e5dd7070Spatrick           CaptureTy, Alignment, IsVolatile, Ctx);
1790e5dd7070Spatrick     else
1791e5dd7070Spatrick       // If CaptureStrKind::Merged is passed, use the copy constructor string.
1792e5dd7070Spatrick       // It has all the information that the destructor string has.
1793e5dd7070Spatrick       FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
1794e5dd7070Spatrick           CaptureTy, Alignment, IsVolatile, Ctx);
1795e5dd7070Spatrick     // The underscore is necessary here because non-trivial copy constructor
1796e5dd7070Spatrick     // and destructor strings can start with a number.
1797e5dd7070Spatrick     Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
1798e5dd7070Spatrick     break;
1799e5dd7070Spatrick   }
1800e5dd7070Spatrick   case BlockCaptureEntityKind::None:
1801e5dd7070Spatrick     break;
1802e5dd7070Spatrick   }
1803e5dd7070Spatrick 
1804e5dd7070Spatrick   return Str;
1805e5dd7070Spatrick }
1806e5dd7070Spatrick 
getCopyDestroyHelperFuncName(const SmallVectorImpl<CGBlockInfo::Capture> & Captures,CharUnits BlockAlignment,CaptureStrKind StrKind,CodeGenModule & CGM)1807e5dd7070Spatrick static std::string getCopyDestroyHelperFuncName(
1808*12c85518Srobert     const SmallVectorImpl<CGBlockInfo::Capture> &Captures,
1809e5dd7070Spatrick     CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
1810e5dd7070Spatrick   assert((StrKind == CaptureStrKind::CopyHelper ||
1811e5dd7070Spatrick           StrKind == CaptureStrKind::DisposeHelper) &&
1812e5dd7070Spatrick          "unexpected CaptureStrKind");
1813e5dd7070Spatrick   std::string Name = StrKind == CaptureStrKind::CopyHelper
1814e5dd7070Spatrick                          ? "__copy_helper_block_"
1815e5dd7070Spatrick                          : "__destroy_helper_block_";
1816e5dd7070Spatrick   if (CGM.getLangOpts().Exceptions)
1817e5dd7070Spatrick     Name += "e";
1818e5dd7070Spatrick   if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1819e5dd7070Spatrick     Name += "a";
1820e5dd7070Spatrick   Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1821e5dd7070Spatrick 
1822*12c85518Srobert   for (auto &Cap : Captures) {
1823*12c85518Srobert     if (Cap.isConstantOrTrivial())
1824*12c85518Srobert       continue;
1825*12c85518Srobert     Name += llvm::to_string(Cap.getOffset().getQuantity());
1826*12c85518Srobert     Name += getBlockCaptureStr(Cap, StrKind, BlockAlignment, CGM);
1827e5dd7070Spatrick   }
1828e5dd7070Spatrick 
1829e5dd7070Spatrick   return Name;
1830e5dd7070Spatrick }
1831e5dd7070Spatrick 
pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,Address Field,QualType CaptureType,BlockFieldFlags Flags,bool ForCopyHelper,VarDecl * Var,CodeGenFunction & CGF)1832e5dd7070Spatrick static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1833e5dd7070Spatrick                                Address Field, QualType CaptureType,
1834e5dd7070Spatrick                                BlockFieldFlags Flags, bool ForCopyHelper,
1835e5dd7070Spatrick                                VarDecl *Var, CodeGenFunction &CGF) {
1836e5dd7070Spatrick   bool EHOnly = ForCopyHelper;
1837e5dd7070Spatrick 
1838e5dd7070Spatrick   switch (CaptureKind) {
1839e5dd7070Spatrick   case BlockCaptureEntityKind::CXXRecord:
1840e5dd7070Spatrick   case BlockCaptureEntityKind::ARCWeak:
1841e5dd7070Spatrick   case BlockCaptureEntityKind::NonTrivialCStruct:
1842e5dd7070Spatrick   case BlockCaptureEntityKind::ARCStrong: {
1843e5dd7070Spatrick     if (CaptureType.isDestructedType() &&
1844e5dd7070Spatrick         (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1845e5dd7070Spatrick       CodeGenFunction::Destroyer *Destroyer =
1846e5dd7070Spatrick           CaptureKind == BlockCaptureEntityKind::ARCStrong
1847e5dd7070Spatrick               ? CodeGenFunction::destroyARCStrongImprecise
1848e5dd7070Spatrick               : CGF.getDestroyer(CaptureType.isDestructedType());
1849e5dd7070Spatrick       CleanupKind Kind =
1850e5dd7070Spatrick           EHOnly ? EHCleanup
1851e5dd7070Spatrick                  : CGF.getCleanupKind(CaptureType.isDestructedType());
1852e5dd7070Spatrick       CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1853e5dd7070Spatrick     }
1854e5dd7070Spatrick     break;
1855e5dd7070Spatrick   }
1856e5dd7070Spatrick   case BlockCaptureEntityKind::BlockObject: {
1857e5dd7070Spatrick     if (!EHOnly || CGF.getLangOpts().Exceptions) {
1858e5dd7070Spatrick       CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
1859e5dd7070Spatrick       // Calls to _Block_object_dispose along the EH path in the copy helper
1860e5dd7070Spatrick       // function don't throw as newly-copied __block variables always have a
1861e5dd7070Spatrick       // reference count of 2.
1862e5dd7070Spatrick       bool CanThrow =
1863e5dd7070Spatrick           !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
1864e5dd7070Spatrick       CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1865e5dd7070Spatrick                             CanThrow);
1866e5dd7070Spatrick     }
1867e5dd7070Spatrick     break;
1868e5dd7070Spatrick   }
1869e5dd7070Spatrick   case BlockCaptureEntityKind::None:
1870e5dd7070Spatrick     break;
1871e5dd7070Spatrick   }
1872e5dd7070Spatrick }
1873e5dd7070Spatrick 
setBlockHelperAttributesVisibility(bool CapturesNonExternalType,llvm::Function * Fn,const CGFunctionInfo & FI,CodeGenModule & CGM)1874e5dd7070Spatrick static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1875e5dd7070Spatrick                                                llvm::Function *Fn,
1876e5dd7070Spatrick                                                const CGFunctionInfo &FI,
1877e5dd7070Spatrick                                                CodeGenModule &CGM) {
1878e5dd7070Spatrick   if (CapturesNonExternalType) {
1879e5dd7070Spatrick     CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1880e5dd7070Spatrick   } else {
1881e5dd7070Spatrick     Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1882e5dd7070Spatrick     Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1883a9ac8606Spatrick     CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, /*IsThunk=*/false);
1884e5dd7070Spatrick     CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1885e5dd7070Spatrick   }
1886e5dd7070Spatrick }
1887e5dd7070Spatrick /// Generate the copy-helper function for a block closure object:
1888e5dd7070Spatrick ///   static void block_copy_helper(block_t *dst, block_t *src);
1889e5dd7070Spatrick /// The runtime will have previously initialized 'dst' by doing a
1890e5dd7070Spatrick /// bit-copy of 'src'.
1891e5dd7070Spatrick ///
1892e5dd7070Spatrick /// Note that this copies an entire block closure object to the heap;
1893e5dd7070Spatrick /// it should not be confused with a 'byref copy helper', which moves
1894e5dd7070Spatrick /// the contents of an individual __block variable to the heap.
1895e5dd7070Spatrick llvm::Constant *
GenerateCopyHelperFunction(const CGBlockInfo & blockInfo)1896e5dd7070Spatrick CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1897*12c85518Srobert   std::string FuncName = getCopyDestroyHelperFuncName(
1898*12c85518Srobert       blockInfo.SortedCaptures, blockInfo.BlockAlign,
1899e5dd7070Spatrick       CaptureStrKind::CopyHelper, CGM);
1900e5dd7070Spatrick 
1901e5dd7070Spatrick   if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
1902e5dd7070Spatrick     return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
1903e5dd7070Spatrick 
1904e5dd7070Spatrick   ASTContext &C = getContext();
1905e5dd7070Spatrick 
1906e5dd7070Spatrick   QualType ReturnTy = C.VoidTy;
1907e5dd7070Spatrick 
1908e5dd7070Spatrick   FunctionArgList args;
1909e5dd7070Spatrick   ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
1910e5dd7070Spatrick   args.push_back(&DstDecl);
1911e5dd7070Spatrick   ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
1912e5dd7070Spatrick   args.push_back(&SrcDecl);
1913e5dd7070Spatrick 
1914e5dd7070Spatrick   const CGFunctionInfo &FI =
1915e5dd7070Spatrick       CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
1916e5dd7070Spatrick 
1917e5dd7070Spatrick   // FIXME: it would be nice if these were mergeable with things with
1918e5dd7070Spatrick   // identical semantics.
1919e5dd7070Spatrick   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1920e5dd7070Spatrick 
1921e5dd7070Spatrick   llvm::Function *Fn =
1922e5dd7070Spatrick     llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
1923e5dd7070Spatrick                            FuncName, &CGM.getModule());
1924e5dd7070Spatrick   if (CGM.supportsCOMDAT())
1925e5dd7070Spatrick     Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
1926e5dd7070Spatrick 
1927e5dd7070Spatrick   SmallVector<QualType, 2> ArgTys;
1928e5dd7070Spatrick   ArgTys.push_back(C.VoidPtrTy);
1929e5dd7070Spatrick   ArgTys.push_back(C.VoidPtrTy);
1930e5dd7070Spatrick 
1931e5dd7070Spatrick   setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
1932e5dd7070Spatrick                                      CGM);
1933a9ac8606Spatrick   StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
1934ec727ea7Spatrick   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1935ec727ea7Spatrick 
1936e5dd7070Spatrick   Address src = GetAddrOfLocalVar(&SrcDecl);
1937*12c85518Srobert   src = Address(Builder.CreateLoad(src), Int8Ty, blockInfo.BlockAlign);
1938*12c85518Srobert   src = Builder.CreateElementBitCast(src, blockInfo.StructureType,
1939*12c85518Srobert                                      "block.source");
1940e5dd7070Spatrick 
1941e5dd7070Spatrick   Address dst = GetAddrOfLocalVar(&DstDecl);
1942*12c85518Srobert   dst = Address(Builder.CreateLoad(dst), Int8Ty, blockInfo.BlockAlign);
1943*12c85518Srobert   dst =
1944*12c85518Srobert       Builder.CreateElementBitCast(dst, blockInfo.StructureType, "block.dest");
1945e5dd7070Spatrick 
1946*12c85518Srobert   for (auto &capture : blockInfo.SortedCaptures) {
1947*12c85518Srobert     if (capture.isConstantOrTrivial())
1948*12c85518Srobert       continue;
1949*12c85518Srobert 
1950*12c85518Srobert     const BlockDecl::Capture &CI = *capture.Cap;
1951e5dd7070Spatrick     QualType captureType = CI.getVariable()->getType();
1952*12c85518Srobert     BlockFieldFlags flags = capture.CopyFlags;
1953e5dd7070Spatrick 
1954e5dd7070Spatrick     unsigned index = capture.getIndex();
1955e5dd7070Spatrick     Address srcField = Builder.CreateStructGEP(src, index);
1956e5dd7070Spatrick     Address dstField = Builder.CreateStructGEP(dst, index);
1957e5dd7070Spatrick 
1958*12c85518Srobert     switch (capture.CopyKind) {
1959e5dd7070Spatrick     case BlockCaptureEntityKind::CXXRecord:
1960e5dd7070Spatrick       // If there's an explicit copy expression, we do that.
1961e5dd7070Spatrick       assert(CI.getCopyExpr() && "copy expression for variable is missing");
1962e5dd7070Spatrick       EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1963e5dd7070Spatrick       break;
1964e5dd7070Spatrick     case BlockCaptureEntityKind::ARCWeak:
1965e5dd7070Spatrick       EmitARCCopyWeak(dstField, srcField);
1966e5dd7070Spatrick       break;
1967e5dd7070Spatrick     case BlockCaptureEntityKind::NonTrivialCStruct: {
1968e5dd7070Spatrick       // If this is a C struct that requires non-trivial copy construction,
1969e5dd7070Spatrick       // emit a call to its copy constructor.
1970e5dd7070Spatrick       QualType varType = CI.getVariable()->getType();
1971e5dd7070Spatrick       callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
1972e5dd7070Spatrick                                  MakeAddrLValue(srcField, varType));
1973e5dd7070Spatrick       break;
1974e5dd7070Spatrick     }
1975e5dd7070Spatrick     case BlockCaptureEntityKind::ARCStrong: {
1976e5dd7070Spatrick       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1977e5dd7070Spatrick       // At -O0, store null into the destination field (so that the
1978e5dd7070Spatrick       // storeStrong doesn't over-release) and then call storeStrong.
1979e5dd7070Spatrick       // This is a workaround to not having an initStrong call.
1980e5dd7070Spatrick       if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1981e5dd7070Spatrick         auto *ty = cast<llvm::PointerType>(srcValue->getType());
1982e5dd7070Spatrick         llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1983e5dd7070Spatrick         Builder.CreateStore(null, dstField);
1984e5dd7070Spatrick         EmitARCStoreStrongCall(dstField, srcValue, true);
1985e5dd7070Spatrick 
1986e5dd7070Spatrick       // With optimization enabled, take advantage of the fact that
1987e5dd7070Spatrick       // the blocks runtime guarantees a memcpy of the block data, and
1988e5dd7070Spatrick       // just emit a retain of the src field.
1989e5dd7070Spatrick       } else {
1990e5dd7070Spatrick         EmitARCRetainNonBlock(srcValue);
1991e5dd7070Spatrick 
1992e5dd7070Spatrick         // Unless EH cleanup is required, we don't need this anymore, so kill
1993e5dd7070Spatrick         // it. It's not quite worth the annoyance to avoid creating it in the
1994e5dd7070Spatrick         // first place.
1995e5dd7070Spatrick         if (!needsEHCleanup(captureType.isDestructedType()))
1996e5dd7070Spatrick           cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
1997e5dd7070Spatrick       }
1998e5dd7070Spatrick       break;
1999e5dd7070Spatrick     }
2000e5dd7070Spatrick     case BlockCaptureEntityKind::BlockObject: {
2001e5dd7070Spatrick       llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2002e5dd7070Spatrick       srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
2003e5dd7070Spatrick       llvm::Value *dstAddr =
2004e5dd7070Spatrick           Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
2005e5dd7070Spatrick       llvm::Value *args[] = {
2006e5dd7070Spatrick         dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2007e5dd7070Spatrick       };
2008e5dd7070Spatrick 
2009e5dd7070Spatrick       if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
2010e5dd7070Spatrick         EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
2011e5dd7070Spatrick       else
2012e5dd7070Spatrick         EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
2013e5dd7070Spatrick       break;
2014e5dd7070Spatrick     }
2015e5dd7070Spatrick     case BlockCaptureEntityKind::None:
2016e5dd7070Spatrick       continue;
2017e5dd7070Spatrick     }
2018e5dd7070Spatrick 
2019e5dd7070Spatrick     // Ensure that we destroy the copied object if an exception is thrown later
2020e5dd7070Spatrick     // in the helper function.
2021*12c85518Srobert     pushCaptureCleanup(capture.CopyKind, dstField, captureType, flags,
2022e5dd7070Spatrick                        /*ForCopyHelper*/ true, CI.getVariable(), *this);
2023e5dd7070Spatrick   }
2024e5dd7070Spatrick 
2025e5dd7070Spatrick   FinishFunction();
2026e5dd7070Spatrick 
2027e5dd7070Spatrick   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2028e5dd7070Spatrick }
2029e5dd7070Spatrick 
2030e5dd7070Spatrick static BlockFieldFlags
getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture & CI,QualType T)2031e5dd7070Spatrick getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
2032e5dd7070Spatrick                                        QualType T) {
2033e5dd7070Spatrick   BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
2034e5dd7070Spatrick   if (T->isBlockPointerType())
2035e5dd7070Spatrick     Flags = BLOCK_FIELD_IS_BLOCK;
2036e5dd7070Spatrick   return Flags;
2037e5dd7070Spatrick }
2038e5dd7070Spatrick 
2039e5dd7070Spatrick static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
computeDestroyInfoForBlockCapture(const BlockDecl::Capture & CI,QualType T,const LangOptions & LangOpts)2040e5dd7070Spatrick computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
2041e5dd7070Spatrick                                   const LangOptions &LangOpts) {
2042e5dd7070Spatrick   if (CI.isEscapingByref()) {
2043e5dd7070Spatrick     BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2044e5dd7070Spatrick     if (T.isObjCGCWeak())
2045e5dd7070Spatrick       Flags |= BLOCK_FIELD_IS_WEAK;
2046e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
2047e5dd7070Spatrick   }
2048e5dd7070Spatrick 
2049e5dd7070Spatrick   switch (T.isDestructedType()) {
2050e5dd7070Spatrick   case QualType::DK_cxx_destructor:
2051e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
2052e5dd7070Spatrick   case QualType::DK_objc_strong_lifetime:
2053e5dd7070Spatrick     // Use objc_storeStrong for __strong direct captures; the
2054e5dd7070Spatrick     // dynamic tools really like it when we do this.
2055e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::ARCStrong,
2056e5dd7070Spatrick                           getBlockFieldFlagsForObjCObjectPointer(CI, T));
2057e5dd7070Spatrick   case QualType::DK_objc_weak_lifetime:
2058e5dd7070Spatrick     // Support __weak direct captures.
2059e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::ARCWeak,
2060e5dd7070Spatrick                           getBlockFieldFlagsForObjCObjectPointer(CI, T));
2061e5dd7070Spatrick   case QualType::DK_nontrivial_c_struct:
2062e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
2063e5dd7070Spatrick                           BlockFieldFlags());
2064e5dd7070Spatrick   case QualType::DK_none: {
2065e5dd7070Spatrick     // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2066*12c85518Srobert     // But honor the inert __unsafe_unretained qualifier, which doesn't actually
2067*12c85518Srobert     // make it into the type system.
2068e5dd7070Spatrick     if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
2069*12c85518Srobert         !LangOpts.ObjCAutoRefCount && !T->isObjCInertUnsafeUnretainedType())
2070e5dd7070Spatrick       return std::make_pair(BlockCaptureEntityKind::BlockObject,
2071e5dd7070Spatrick                             getBlockFieldFlagsForObjCObjectPointer(CI, T));
2072e5dd7070Spatrick     // Otherwise, we have nothing to do.
2073e5dd7070Spatrick     return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
2074e5dd7070Spatrick   }
2075e5dd7070Spatrick   }
2076e5dd7070Spatrick   llvm_unreachable("after exhaustive DestructionKind switch");
2077e5dd7070Spatrick }
2078e5dd7070Spatrick 
2079e5dd7070Spatrick /// Generate the destroy-helper function for a block closure object:
2080e5dd7070Spatrick ///   static void block_destroy_helper(block_t *theBlock);
2081e5dd7070Spatrick ///
2082e5dd7070Spatrick /// Note that this destroys a heap-allocated block closure object;
2083e5dd7070Spatrick /// it should not be confused with a 'byref destroy helper', which
2084e5dd7070Spatrick /// destroys the heap-allocated contents of an individual __block
2085e5dd7070Spatrick /// variable.
2086e5dd7070Spatrick llvm::Constant *
GenerateDestroyHelperFunction(const CGBlockInfo & blockInfo)2087e5dd7070Spatrick CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
2088*12c85518Srobert   std::string FuncName = getCopyDestroyHelperFuncName(
2089*12c85518Srobert       blockInfo.SortedCaptures, blockInfo.BlockAlign,
2090e5dd7070Spatrick       CaptureStrKind::DisposeHelper, CGM);
2091e5dd7070Spatrick 
2092e5dd7070Spatrick   if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
2093e5dd7070Spatrick     return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
2094e5dd7070Spatrick 
2095e5dd7070Spatrick   ASTContext &C = getContext();
2096e5dd7070Spatrick 
2097e5dd7070Spatrick   QualType ReturnTy = C.VoidTy;
2098e5dd7070Spatrick 
2099e5dd7070Spatrick   FunctionArgList args;
2100e5dd7070Spatrick   ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2101e5dd7070Spatrick   args.push_back(&SrcDecl);
2102e5dd7070Spatrick 
2103e5dd7070Spatrick   const CGFunctionInfo &FI =
2104e5dd7070Spatrick       CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2105e5dd7070Spatrick 
2106e5dd7070Spatrick   // FIXME: We'd like to put these into a mergable by content, with
2107e5dd7070Spatrick   // internal linkage.
2108e5dd7070Spatrick   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2109e5dd7070Spatrick 
2110e5dd7070Spatrick   llvm::Function *Fn =
2111e5dd7070Spatrick     llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2112e5dd7070Spatrick                            FuncName, &CGM.getModule());
2113e5dd7070Spatrick   if (CGM.supportsCOMDAT())
2114e5dd7070Spatrick     Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
2115e5dd7070Spatrick 
2116e5dd7070Spatrick   SmallVector<QualType, 1> ArgTys;
2117e5dd7070Spatrick   ArgTys.push_back(C.VoidPtrTy);
2118e5dd7070Spatrick 
2119e5dd7070Spatrick   setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2120e5dd7070Spatrick                                      CGM);
2121a9ac8606Spatrick   StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
2122e5dd7070Spatrick   markAsIgnoreThreadCheckingAtRuntime(Fn);
2123e5dd7070Spatrick 
2124ec727ea7Spatrick   auto AL = ApplyDebugLocation::CreateArtificial(*this);
2125e5dd7070Spatrick 
2126e5dd7070Spatrick   Address src = GetAddrOfLocalVar(&SrcDecl);
2127*12c85518Srobert   src = Address(Builder.CreateLoad(src), Int8Ty, blockInfo.BlockAlign);
2128*12c85518Srobert   src = Builder.CreateElementBitCast(src, blockInfo.StructureType, "block");
2129e5dd7070Spatrick 
2130e5dd7070Spatrick   CodeGenFunction::RunCleanupsScope cleanups(*this);
2131e5dd7070Spatrick 
2132*12c85518Srobert   for (auto &capture : blockInfo.SortedCaptures) {
2133*12c85518Srobert     if (capture.isConstantOrTrivial())
2134*12c85518Srobert       continue;
2135*12c85518Srobert 
2136*12c85518Srobert     const BlockDecl::Capture &CI = *capture.Cap;
2137*12c85518Srobert     BlockFieldFlags flags = capture.DisposeFlags;
2138e5dd7070Spatrick 
2139e5dd7070Spatrick     Address srcField = Builder.CreateStructGEP(src, capture.getIndex());
2140e5dd7070Spatrick 
2141*12c85518Srobert     pushCaptureCleanup(capture.DisposeKind, srcField,
2142e5dd7070Spatrick                        CI.getVariable()->getType(), flags,
2143e5dd7070Spatrick                        /*ForCopyHelper*/ false, CI.getVariable(), *this);
2144e5dd7070Spatrick   }
2145e5dd7070Spatrick 
2146e5dd7070Spatrick   cleanups.ForceCleanup();
2147e5dd7070Spatrick 
2148e5dd7070Spatrick   FinishFunction();
2149e5dd7070Spatrick 
2150e5dd7070Spatrick   return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2151e5dd7070Spatrick }
2152e5dd7070Spatrick 
2153e5dd7070Spatrick namespace {
2154e5dd7070Spatrick 
2155e5dd7070Spatrick /// Emits the copy/dispose helper functions for a __block object of id type.
2156e5dd7070Spatrick class ObjectByrefHelpers final : public BlockByrefHelpers {
2157e5dd7070Spatrick   BlockFieldFlags Flags;
2158e5dd7070Spatrick 
2159e5dd7070Spatrick public:
ObjectByrefHelpers(CharUnits alignment,BlockFieldFlags flags)2160e5dd7070Spatrick   ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
2161e5dd7070Spatrick     : BlockByrefHelpers(alignment), Flags(flags) {}
2162e5dd7070Spatrick 
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)2163e5dd7070Spatrick   void emitCopy(CodeGenFunction &CGF, Address destField,
2164e5dd7070Spatrick                 Address srcField) override {
2165*12c85518Srobert     destField = CGF.Builder.CreateElementBitCast(destField, CGF.Int8Ty);
2166e5dd7070Spatrick 
2167*12c85518Srobert     srcField = CGF.Builder.CreateElementBitCast(srcField, CGF.Int8PtrTy);
2168e5dd7070Spatrick     llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2169e5dd7070Spatrick 
2170e5dd7070Spatrick     unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2171e5dd7070Spatrick 
2172e5dd7070Spatrick     llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
2173e5dd7070Spatrick     llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign();
2174e5dd7070Spatrick 
2175e5dd7070Spatrick     llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
2176e5dd7070Spatrick     CGF.EmitNounwindRuntimeCall(fn, args);
2177e5dd7070Spatrick   }
2178e5dd7070Spatrick 
emitDispose(CodeGenFunction & CGF,Address field)2179e5dd7070Spatrick   void emitDispose(CodeGenFunction &CGF, Address field) override {
2180*12c85518Srobert     field = CGF.Builder.CreateElementBitCast(field, CGF.Int8PtrTy);
2181e5dd7070Spatrick     llvm::Value *value = CGF.Builder.CreateLoad(field);
2182e5dd7070Spatrick 
2183e5dd7070Spatrick     CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
2184e5dd7070Spatrick   }
2185e5dd7070Spatrick 
profileImpl(llvm::FoldingSetNodeID & id) const2186e5dd7070Spatrick   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2187e5dd7070Spatrick     id.AddInteger(Flags.getBitMask());
2188e5dd7070Spatrick   }
2189e5dd7070Spatrick };
2190e5dd7070Spatrick 
2191e5dd7070Spatrick /// Emits the copy/dispose helpers for an ARC __block __weak variable.
2192e5dd7070Spatrick class ARCWeakByrefHelpers final : public BlockByrefHelpers {
2193e5dd7070Spatrick public:
ARCWeakByrefHelpers(CharUnits alignment)2194e5dd7070Spatrick   ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2195e5dd7070Spatrick 
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)2196e5dd7070Spatrick   void emitCopy(CodeGenFunction &CGF, Address destField,
2197e5dd7070Spatrick                 Address srcField) override {
2198e5dd7070Spatrick     CGF.EmitARCMoveWeak(destField, srcField);
2199e5dd7070Spatrick   }
2200e5dd7070Spatrick 
emitDispose(CodeGenFunction & CGF,Address field)2201e5dd7070Spatrick   void emitDispose(CodeGenFunction &CGF, Address field) override {
2202e5dd7070Spatrick     CGF.EmitARCDestroyWeak(field);
2203e5dd7070Spatrick   }
2204e5dd7070Spatrick 
profileImpl(llvm::FoldingSetNodeID & id) const2205e5dd7070Spatrick   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2206e5dd7070Spatrick     // 0 is distinguishable from all pointers and byref flags
2207e5dd7070Spatrick     id.AddInteger(0);
2208e5dd7070Spatrick   }
2209e5dd7070Spatrick };
2210e5dd7070Spatrick 
2211e5dd7070Spatrick /// Emits the copy/dispose helpers for an ARC __block __strong variable
2212e5dd7070Spatrick /// that's not of block-pointer type.
2213e5dd7070Spatrick class ARCStrongByrefHelpers final : public BlockByrefHelpers {
2214e5dd7070Spatrick public:
ARCStrongByrefHelpers(CharUnits alignment)2215e5dd7070Spatrick   ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2216e5dd7070Spatrick 
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)2217e5dd7070Spatrick   void emitCopy(CodeGenFunction &CGF, Address destField,
2218e5dd7070Spatrick                 Address srcField) override {
2219e5dd7070Spatrick     // Do a "move" by copying the value and then zeroing out the old
2220e5dd7070Spatrick     // variable.
2221e5dd7070Spatrick 
2222e5dd7070Spatrick     llvm::Value *value = CGF.Builder.CreateLoad(srcField);
2223e5dd7070Spatrick 
2224e5dd7070Spatrick     llvm::Value *null =
2225e5dd7070Spatrick       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
2226e5dd7070Spatrick 
2227e5dd7070Spatrick     if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2228e5dd7070Spatrick       CGF.Builder.CreateStore(null, destField);
2229e5dd7070Spatrick       CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2230e5dd7070Spatrick       CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2231e5dd7070Spatrick       return;
2232e5dd7070Spatrick     }
2233e5dd7070Spatrick     CGF.Builder.CreateStore(value, destField);
2234e5dd7070Spatrick     CGF.Builder.CreateStore(null, srcField);
2235e5dd7070Spatrick   }
2236e5dd7070Spatrick 
emitDispose(CodeGenFunction & CGF,Address field)2237e5dd7070Spatrick   void emitDispose(CodeGenFunction &CGF, Address field) override {
2238e5dd7070Spatrick     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2239e5dd7070Spatrick   }
2240e5dd7070Spatrick 
profileImpl(llvm::FoldingSetNodeID & id) const2241e5dd7070Spatrick   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2242e5dd7070Spatrick     // 1 is distinguishable from all pointers and byref flags
2243e5dd7070Spatrick     id.AddInteger(1);
2244e5dd7070Spatrick   }
2245e5dd7070Spatrick };
2246e5dd7070Spatrick 
2247e5dd7070Spatrick /// Emits the copy/dispose helpers for an ARC __block __strong
2248e5dd7070Spatrick /// variable that's of block-pointer type.
2249e5dd7070Spatrick class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
2250e5dd7070Spatrick public:
ARCStrongBlockByrefHelpers(CharUnits alignment)2251e5dd7070Spatrick   ARCStrongBlockByrefHelpers(CharUnits alignment)
2252e5dd7070Spatrick     : BlockByrefHelpers(alignment) {}
2253e5dd7070Spatrick 
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)2254e5dd7070Spatrick   void emitCopy(CodeGenFunction &CGF, Address destField,
2255e5dd7070Spatrick                 Address srcField) override {
2256e5dd7070Spatrick     // Do the copy with objc_retainBlock; that's all that
2257e5dd7070Spatrick     // _Block_object_assign would do anyway, and we'd have to pass the
2258e5dd7070Spatrick     // right arguments to make sure it doesn't get no-op'ed.
2259e5dd7070Spatrick     llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
2260e5dd7070Spatrick     llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
2261e5dd7070Spatrick     CGF.Builder.CreateStore(copy, destField);
2262e5dd7070Spatrick   }
2263e5dd7070Spatrick 
emitDispose(CodeGenFunction & CGF,Address field)2264e5dd7070Spatrick   void emitDispose(CodeGenFunction &CGF, Address field) override {
2265e5dd7070Spatrick     CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2266e5dd7070Spatrick   }
2267e5dd7070Spatrick 
profileImpl(llvm::FoldingSetNodeID & id) const2268e5dd7070Spatrick   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2269e5dd7070Spatrick     // 2 is distinguishable from all pointers and byref flags
2270e5dd7070Spatrick     id.AddInteger(2);
2271e5dd7070Spatrick   }
2272e5dd7070Spatrick };
2273e5dd7070Spatrick 
2274e5dd7070Spatrick /// Emits the copy/dispose helpers for a __block variable with a
2275e5dd7070Spatrick /// nontrivial copy constructor or destructor.
2276e5dd7070Spatrick class CXXByrefHelpers final : public BlockByrefHelpers {
2277e5dd7070Spatrick   QualType VarType;
2278e5dd7070Spatrick   const Expr *CopyExpr;
2279e5dd7070Spatrick 
2280e5dd7070Spatrick public:
CXXByrefHelpers(CharUnits alignment,QualType type,const Expr * copyExpr)2281e5dd7070Spatrick   CXXByrefHelpers(CharUnits alignment, QualType type,
2282e5dd7070Spatrick                   const Expr *copyExpr)
2283e5dd7070Spatrick     : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
2284e5dd7070Spatrick 
needsCopy() const2285e5dd7070Spatrick   bool needsCopy() const override { return CopyExpr != nullptr; }
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)2286e5dd7070Spatrick   void emitCopy(CodeGenFunction &CGF, Address destField,
2287e5dd7070Spatrick                 Address srcField) override {
2288e5dd7070Spatrick     if (!CopyExpr) return;
2289e5dd7070Spatrick     CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2290e5dd7070Spatrick   }
2291e5dd7070Spatrick 
emitDispose(CodeGenFunction & CGF,Address field)2292e5dd7070Spatrick   void emitDispose(CodeGenFunction &CGF, Address field) override {
2293e5dd7070Spatrick     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2294e5dd7070Spatrick     CGF.PushDestructorCleanup(VarType, field);
2295e5dd7070Spatrick     CGF.PopCleanupBlocks(cleanupDepth);
2296e5dd7070Spatrick   }
2297e5dd7070Spatrick 
profileImpl(llvm::FoldingSetNodeID & id) const2298e5dd7070Spatrick   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2299e5dd7070Spatrick     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2300e5dd7070Spatrick   }
2301e5dd7070Spatrick };
2302e5dd7070Spatrick 
2303e5dd7070Spatrick /// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2304e5dd7070Spatrick /// C struct.
2305e5dd7070Spatrick class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2306e5dd7070Spatrick   QualType VarType;
2307e5dd7070Spatrick 
2308e5dd7070Spatrick public:
NonTrivialCStructByrefHelpers(CharUnits alignment,QualType type)2309e5dd7070Spatrick   NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2310e5dd7070Spatrick     : BlockByrefHelpers(alignment), VarType(type) {}
2311e5dd7070Spatrick 
emitCopy(CodeGenFunction & CGF,Address destField,Address srcField)2312e5dd7070Spatrick   void emitCopy(CodeGenFunction &CGF, Address destField,
2313e5dd7070Spatrick                 Address srcField) override {
2314e5dd7070Spatrick     CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2315e5dd7070Spatrick                                    CGF.MakeAddrLValue(srcField, VarType));
2316e5dd7070Spatrick   }
2317e5dd7070Spatrick 
needsDispose() const2318e5dd7070Spatrick   bool needsDispose() const override {
2319e5dd7070Spatrick     return VarType.isDestructedType();
2320e5dd7070Spatrick   }
2321e5dd7070Spatrick 
emitDispose(CodeGenFunction & CGF,Address field)2322e5dd7070Spatrick   void emitDispose(CodeGenFunction &CGF, Address field) override {
2323e5dd7070Spatrick     EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2324e5dd7070Spatrick     CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2325e5dd7070Spatrick     CGF.PopCleanupBlocks(cleanupDepth);
2326e5dd7070Spatrick   }
2327e5dd7070Spatrick 
profileImpl(llvm::FoldingSetNodeID & id) const2328e5dd7070Spatrick   void profileImpl(llvm::FoldingSetNodeID &id) const override {
2329e5dd7070Spatrick     id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2330e5dd7070Spatrick   }
2331e5dd7070Spatrick };
2332e5dd7070Spatrick } // end anonymous namespace
2333e5dd7070Spatrick 
2334e5dd7070Spatrick static llvm::Constant *
generateByrefCopyHelper(CodeGenFunction & CGF,const BlockByrefInfo & byrefInfo,BlockByrefHelpers & generator)2335e5dd7070Spatrick generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2336e5dd7070Spatrick                         BlockByrefHelpers &generator) {
2337e5dd7070Spatrick   ASTContext &Context = CGF.getContext();
2338e5dd7070Spatrick 
2339e5dd7070Spatrick   QualType ReturnTy = Context.VoidTy;
2340e5dd7070Spatrick 
2341e5dd7070Spatrick   FunctionArgList args;
2342e5dd7070Spatrick   ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2343e5dd7070Spatrick   args.push_back(&Dst);
2344e5dd7070Spatrick 
2345e5dd7070Spatrick   ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2346e5dd7070Spatrick   args.push_back(&Src);
2347e5dd7070Spatrick 
2348e5dd7070Spatrick   const CGFunctionInfo &FI =
2349e5dd7070Spatrick       CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2350e5dd7070Spatrick 
2351e5dd7070Spatrick   llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2352e5dd7070Spatrick 
2353e5dd7070Spatrick   // FIXME: We'd like to put these into a mergable by content, with
2354e5dd7070Spatrick   // internal linkage.
2355e5dd7070Spatrick   llvm::Function *Fn =
2356e5dd7070Spatrick     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2357e5dd7070Spatrick                            "__Block_byref_object_copy_", &CGF.CGM.getModule());
2358e5dd7070Spatrick 
2359e5dd7070Spatrick   SmallVector<QualType, 2> ArgTys;
2360e5dd7070Spatrick   ArgTys.push_back(Context.VoidPtrTy);
2361e5dd7070Spatrick   ArgTys.push_back(Context.VoidPtrTy);
2362e5dd7070Spatrick 
2363e5dd7070Spatrick   CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2364e5dd7070Spatrick 
2365a9ac8606Spatrick   CGF.StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
2366a9ac8606Spatrick     // Create a scope with an artificial location for the body of this function.
2367a9ac8606Spatrick   auto AL = ApplyDebugLocation::CreateArtificial(CGF);
2368e5dd7070Spatrick 
2369e5dd7070Spatrick   if (generator.needsCopy()) {
2370e5dd7070Spatrick     // dst->x
2371e5dd7070Spatrick     Address destField = CGF.GetAddrOfLocalVar(&Dst);
2372*12c85518Srobert     destField = Address(CGF.Builder.CreateLoad(destField), CGF.Int8Ty,
2373e5dd7070Spatrick                         byrefInfo.ByrefAlignment);
2374*12c85518Srobert     destField = CGF.Builder.CreateElementBitCast(destField, byrefInfo.Type);
2375*12c85518Srobert     destField =
2376*12c85518Srobert         CGF.emitBlockByrefAddress(destField, byrefInfo, false, "dest-object");
2377e5dd7070Spatrick 
2378e5dd7070Spatrick     // src->x
2379e5dd7070Spatrick     Address srcField = CGF.GetAddrOfLocalVar(&Src);
2380*12c85518Srobert     srcField = Address(CGF.Builder.CreateLoad(srcField), CGF.Int8Ty,
2381e5dd7070Spatrick                        byrefInfo.ByrefAlignment);
2382*12c85518Srobert     srcField = CGF.Builder.CreateElementBitCast(srcField, byrefInfo.Type);
2383*12c85518Srobert     srcField =
2384*12c85518Srobert         CGF.emitBlockByrefAddress(srcField, byrefInfo, false, "src-object");
2385e5dd7070Spatrick 
2386e5dd7070Spatrick     generator.emitCopy(CGF, destField, srcField);
2387e5dd7070Spatrick   }
2388e5dd7070Spatrick 
2389e5dd7070Spatrick   CGF.FinishFunction();
2390e5dd7070Spatrick 
2391e5dd7070Spatrick   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2392e5dd7070Spatrick }
2393e5dd7070Spatrick 
2394e5dd7070Spatrick /// Build the copy helper for a __block variable.
buildByrefCopyHelper(CodeGenModule & CGM,const BlockByrefInfo & byrefInfo,BlockByrefHelpers & generator)2395e5dd7070Spatrick static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
2396e5dd7070Spatrick                                             const BlockByrefInfo &byrefInfo,
2397e5dd7070Spatrick                                             BlockByrefHelpers &generator) {
2398e5dd7070Spatrick   CodeGenFunction CGF(CGM);
2399e5dd7070Spatrick   return generateByrefCopyHelper(CGF, byrefInfo, generator);
2400e5dd7070Spatrick }
2401e5dd7070Spatrick 
2402e5dd7070Spatrick /// Generate code for a __block variable's dispose helper.
2403e5dd7070Spatrick static llvm::Constant *
generateByrefDisposeHelper(CodeGenFunction & CGF,const BlockByrefInfo & byrefInfo,BlockByrefHelpers & generator)2404e5dd7070Spatrick generateByrefDisposeHelper(CodeGenFunction &CGF,
2405e5dd7070Spatrick                            const BlockByrefInfo &byrefInfo,
2406e5dd7070Spatrick                            BlockByrefHelpers &generator) {
2407e5dd7070Spatrick   ASTContext &Context = CGF.getContext();
2408e5dd7070Spatrick   QualType R = Context.VoidTy;
2409e5dd7070Spatrick 
2410e5dd7070Spatrick   FunctionArgList args;
2411e5dd7070Spatrick   ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2412e5dd7070Spatrick                         ImplicitParamDecl::Other);
2413e5dd7070Spatrick   args.push_back(&Src);
2414e5dd7070Spatrick 
2415e5dd7070Spatrick   const CGFunctionInfo &FI =
2416e5dd7070Spatrick     CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
2417e5dd7070Spatrick 
2418e5dd7070Spatrick   llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2419e5dd7070Spatrick 
2420e5dd7070Spatrick   // FIXME: We'd like to put these into a mergable by content, with
2421e5dd7070Spatrick   // internal linkage.
2422e5dd7070Spatrick   llvm::Function *Fn =
2423e5dd7070Spatrick     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2424e5dd7070Spatrick                            "__Block_byref_object_dispose_",
2425e5dd7070Spatrick                            &CGF.CGM.getModule());
2426e5dd7070Spatrick 
2427e5dd7070Spatrick   SmallVector<QualType, 1> ArgTys;
2428e5dd7070Spatrick   ArgTys.push_back(Context.VoidPtrTy);
2429e5dd7070Spatrick 
2430e5dd7070Spatrick   CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2431e5dd7070Spatrick 
2432a9ac8606Spatrick   CGF.StartFunction(GlobalDecl(), R, Fn, FI, args);
2433a9ac8606Spatrick     // Create a scope with an artificial location for the body of this function.
2434a9ac8606Spatrick   auto AL = ApplyDebugLocation::CreateArtificial(CGF);
2435e5dd7070Spatrick 
2436e5dd7070Spatrick   if (generator.needsDispose()) {
2437e5dd7070Spatrick     Address addr = CGF.GetAddrOfLocalVar(&Src);
2438*12c85518Srobert     addr = Address(CGF.Builder.CreateLoad(addr), CGF.Int8Ty,
2439*12c85518Srobert                    byrefInfo.ByrefAlignment);
2440*12c85518Srobert     addr = CGF.Builder.CreateElementBitCast(addr, byrefInfo.Type);
2441e5dd7070Spatrick     addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
2442e5dd7070Spatrick 
2443e5dd7070Spatrick     generator.emitDispose(CGF, addr);
2444e5dd7070Spatrick   }
2445e5dd7070Spatrick 
2446e5dd7070Spatrick   CGF.FinishFunction();
2447e5dd7070Spatrick 
2448e5dd7070Spatrick   return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2449e5dd7070Spatrick }
2450e5dd7070Spatrick 
2451e5dd7070Spatrick /// Build the dispose helper for a __block variable.
buildByrefDisposeHelper(CodeGenModule & CGM,const BlockByrefInfo & byrefInfo,BlockByrefHelpers & generator)2452e5dd7070Spatrick static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
2453e5dd7070Spatrick                                                const BlockByrefInfo &byrefInfo,
2454e5dd7070Spatrick                                                BlockByrefHelpers &generator) {
2455e5dd7070Spatrick   CodeGenFunction CGF(CGM);
2456e5dd7070Spatrick   return generateByrefDisposeHelper(CGF, byrefInfo, generator);
2457e5dd7070Spatrick }
2458e5dd7070Spatrick 
2459e5dd7070Spatrick /// Lazily build the copy and dispose helpers for a __block variable
2460e5dd7070Spatrick /// with the given information.
2461e5dd7070Spatrick template <class T>
buildByrefHelpers(CodeGenModule & CGM,const BlockByrefInfo & byrefInfo,T && generator)2462e5dd7070Spatrick static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2463e5dd7070Spatrick                             T &&generator) {
2464e5dd7070Spatrick   llvm::FoldingSetNodeID id;
2465e5dd7070Spatrick   generator.Profile(id);
2466e5dd7070Spatrick 
2467e5dd7070Spatrick   void *insertPos;
2468e5dd7070Spatrick   BlockByrefHelpers *node
2469e5dd7070Spatrick     = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2470e5dd7070Spatrick   if (node) return static_cast<T*>(node);
2471e5dd7070Spatrick 
2472e5dd7070Spatrick   generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2473e5dd7070Spatrick   generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2474e5dd7070Spatrick 
2475e5dd7070Spatrick   T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2476e5dd7070Spatrick   CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2477e5dd7070Spatrick   return copy;
2478e5dd7070Spatrick }
2479e5dd7070Spatrick 
2480e5dd7070Spatrick /// Build the copy and dispose helpers for the given __block variable
2481e5dd7070Spatrick /// emission.  Places the helpers in the global cache.  Returns null
2482e5dd7070Spatrick /// if no helpers are required.
2483e5dd7070Spatrick BlockByrefHelpers *
buildByrefHelpers(llvm::StructType & byrefType,const AutoVarEmission & emission)2484e5dd7070Spatrick CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
2485e5dd7070Spatrick                                    const AutoVarEmission &emission) {
2486e5dd7070Spatrick   const VarDecl &var = *emission.Variable;
2487e5dd7070Spatrick   assert(var.isEscapingByref() &&
2488e5dd7070Spatrick          "only escaping __block variables need byref helpers");
2489e5dd7070Spatrick 
2490e5dd7070Spatrick   QualType type = var.getType();
2491e5dd7070Spatrick 
2492e5dd7070Spatrick   auto &byrefInfo = getBlockByrefInfo(&var);
2493e5dd7070Spatrick 
2494e5dd7070Spatrick   // The alignment we care about for the purposes of uniquing byref
2495e5dd7070Spatrick   // helpers is the alignment of the actual byref value field.
2496e5dd7070Spatrick   CharUnits valueAlignment =
2497e5dd7070Spatrick     byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
2498e5dd7070Spatrick 
2499e5dd7070Spatrick   if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2500e5dd7070Spatrick     const Expr *copyExpr =
2501e5dd7070Spatrick         CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
2502e5dd7070Spatrick     if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
2503e5dd7070Spatrick 
2504e5dd7070Spatrick     return ::buildByrefHelpers(
2505e5dd7070Spatrick         CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
2506e5dd7070Spatrick   }
2507e5dd7070Spatrick 
2508e5dd7070Spatrick   // If type is a non-trivial C struct type that is non-trivial to
2509e5dd7070Spatrick   // destructly move or destroy, build the copy and dispose helpers.
2510e5dd7070Spatrick   if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2511e5dd7070Spatrick       type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2512e5dd7070Spatrick     return ::buildByrefHelpers(
2513e5dd7070Spatrick         CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2514e5dd7070Spatrick 
2515e5dd7070Spatrick   // Otherwise, if we don't have a retainable type, there's nothing to do.
2516e5dd7070Spatrick   // that the runtime does extra copies.
2517e5dd7070Spatrick   if (!type->isObjCRetainableType()) return nullptr;
2518e5dd7070Spatrick 
2519e5dd7070Spatrick   Qualifiers qs = type.getQualifiers();
2520e5dd7070Spatrick 
2521e5dd7070Spatrick   // If we have lifetime, that dominates.
2522e5dd7070Spatrick   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
2523e5dd7070Spatrick     switch (lifetime) {
2524e5dd7070Spatrick     case Qualifiers::OCL_None: llvm_unreachable("impossible");
2525e5dd7070Spatrick 
2526e5dd7070Spatrick     // These are just bits as far as the runtime is concerned.
2527e5dd7070Spatrick     case Qualifiers::OCL_ExplicitNone:
2528e5dd7070Spatrick     case Qualifiers::OCL_Autoreleasing:
2529e5dd7070Spatrick       return nullptr;
2530e5dd7070Spatrick 
2531e5dd7070Spatrick     // Tell the runtime that this is ARC __weak, called by the
2532e5dd7070Spatrick     // byref routines.
2533e5dd7070Spatrick     case Qualifiers::OCL_Weak:
2534e5dd7070Spatrick       return ::buildByrefHelpers(CGM, byrefInfo,
2535e5dd7070Spatrick                                  ARCWeakByrefHelpers(valueAlignment));
2536e5dd7070Spatrick 
2537e5dd7070Spatrick     // ARC __strong __block variables need to be retained.
2538e5dd7070Spatrick     case Qualifiers::OCL_Strong:
2539e5dd7070Spatrick       // Block pointers need to be copied, and there's no direct
2540e5dd7070Spatrick       // transfer possible.
2541e5dd7070Spatrick       if (type->isBlockPointerType()) {
2542e5dd7070Spatrick         return ::buildByrefHelpers(CGM, byrefInfo,
2543e5dd7070Spatrick                                    ARCStrongBlockByrefHelpers(valueAlignment));
2544e5dd7070Spatrick 
2545e5dd7070Spatrick       // Otherwise, we transfer ownership of the retain from the stack
2546e5dd7070Spatrick       // to the heap.
2547e5dd7070Spatrick       } else {
2548e5dd7070Spatrick         return ::buildByrefHelpers(CGM, byrefInfo,
2549e5dd7070Spatrick                                    ARCStrongByrefHelpers(valueAlignment));
2550e5dd7070Spatrick       }
2551e5dd7070Spatrick     }
2552e5dd7070Spatrick     llvm_unreachable("fell out of lifetime switch!");
2553e5dd7070Spatrick   }
2554e5dd7070Spatrick 
2555e5dd7070Spatrick   BlockFieldFlags flags;
2556e5dd7070Spatrick   if (type->isBlockPointerType()) {
2557e5dd7070Spatrick     flags |= BLOCK_FIELD_IS_BLOCK;
2558e5dd7070Spatrick   } else if (CGM.getContext().isObjCNSObjectType(type) ||
2559e5dd7070Spatrick              type->isObjCObjectPointerType()) {
2560e5dd7070Spatrick     flags |= BLOCK_FIELD_IS_OBJECT;
2561e5dd7070Spatrick   } else {
2562e5dd7070Spatrick     return nullptr;
2563e5dd7070Spatrick   }
2564e5dd7070Spatrick 
2565e5dd7070Spatrick   if (type.isObjCGCWeak())
2566e5dd7070Spatrick     flags |= BLOCK_FIELD_IS_WEAK;
2567e5dd7070Spatrick 
2568e5dd7070Spatrick   return ::buildByrefHelpers(CGM, byrefInfo,
2569e5dd7070Spatrick                              ObjectByrefHelpers(valueAlignment, flags));
2570e5dd7070Spatrick }
2571e5dd7070Spatrick 
emitBlockByrefAddress(Address baseAddr,const VarDecl * var,bool followForward)2572e5dd7070Spatrick Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2573e5dd7070Spatrick                                                const VarDecl *var,
2574e5dd7070Spatrick                                                bool followForward) {
2575e5dd7070Spatrick   auto &info = getBlockByrefInfo(var);
2576e5dd7070Spatrick   return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2577e5dd7070Spatrick }
2578e5dd7070Spatrick 
emitBlockByrefAddress(Address baseAddr,const BlockByrefInfo & info,bool followForward,const llvm::Twine & name)2579e5dd7070Spatrick Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2580e5dd7070Spatrick                                                const BlockByrefInfo &info,
2581e5dd7070Spatrick                                                bool followForward,
2582e5dd7070Spatrick                                                const llvm::Twine &name) {
2583e5dd7070Spatrick   // Chase the forwarding address if requested.
2584e5dd7070Spatrick   if (followForward) {
2585e5dd7070Spatrick     Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding");
2586*12c85518Srobert     baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.Type,
2587*12c85518Srobert                        info.ByrefAlignment);
2588e5dd7070Spatrick   }
2589e5dd7070Spatrick 
2590e5dd7070Spatrick   return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name);
2591e5dd7070Spatrick }
2592e5dd7070Spatrick 
2593e5dd7070Spatrick /// BuildByrefInfo - This routine changes a __block variable declared as T x
2594e5dd7070Spatrick ///   into:
2595e5dd7070Spatrick ///
2596e5dd7070Spatrick ///      struct {
2597e5dd7070Spatrick ///        void *__isa;
2598e5dd7070Spatrick ///        void *__forwarding;
2599e5dd7070Spatrick ///        int32_t __flags;
2600e5dd7070Spatrick ///        int32_t __size;
2601e5dd7070Spatrick ///        void *__copy_helper;       // only if needed
2602e5dd7070Spatrick ///        void *__destroy_helper;    // only if needed
2603e5dd7070Spatrick ///        void *__byref_variable_layout;// only if needed
2604e5dd7070Spatrick ///        char padding[X];           // only if needed
2605e5dd7070Spatrick ///        T x;
2606e5dd7070Spatrick ///      } x
2607e5dd7070Spatrick ///
getBlockByrefInfo(const VarDecl * D)2608e5dd7070Spatrick const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2609e5dd7070Spatrick   auto it = BlockByrefInfos.find(D);
2610e5dd7070Spatrick   if (it != BlockByrefInfos.end())
2611e5dd7070Spatrick     return it->second;
2612e5dd7070Spatrick 
2613e5dd7070Spatrick   llvm::StructType *byrefType =
2614e5dd7070Spatrick     llvm::StructType::create(getLLVMContext(),
2615e5dd7070Spatrick                              "struct.__block_byref_" + D->getNameAsString());
2616e5dd7070Spatrick 
2617e5dd7070Spatrick   QualType Ty = D->getType();
2618e5dd7070Spatrick 
2619e5dd7070Spatrick   CharUnits size;
2620e5dd7070Spatrick   SmallVector<llvm::Type *, 8> types;
2621e5dd7070Spatrick 
2622e5dd7070Spatrick   // void *__isa;
2623e5dd7070Spatrick   types.push_back(Int8PtrTy);
2624e5dd7070Spatrick   size += getPointerSize();
2625e5dd7070Spatrick 
2626e5dd7070Spatrick   // void *__forwarding;
2627e5dd7070Spatrick   types.push_back(llvm::PointerType::getUnqual(byrefType));
2628e5dd7070Spatrick   size += getPointerSize();
2629e5dd7070Spatrick 
2630e5dd7070Spatrick   // int32_t __flags;
2631e5dd7070Spatrick   types.push_back(Int32Ty);
2632e5dd7070Spatrick   size += CharUnits::fromQuantity(4);
2633e5dd7070Spatrick 
2634e5dd7070Spatrick   // int32_t __size;
2635e5dd7070Spatrick   types.push_back(Int32Ty);
2636e5dd7070Spatrick   size += CharUnits::fromQuantity(4);
2637e5dd7070Spatrick 
2638e5dd7070Spatrick   // Note that this must match *exactly* the logic in buildByrefHelpers.
2639e5dd7070Spatrick   bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2640e5dd7070Spatrick   if (hasCopyAndDispose) {
2641e5dd7070Spatrick     /// void *__copy_helper;
2642e5dd7070Spatrick     types.push_back(Int8PtrTy);
2643e5dd7070Spatrick     size += getPointerSize();
2644e5dd7070Spatrick 
2645e5dd7070Spatrick     /// void *__destroy_helper;
2646e5dd7070Spatrick     types.push_back(Int8PtrTy);
2647e5dd7070Spatrick     size += getPointerSize();
2648e5dd7070Spatrick   }
2649e5dd7070Spatrick 
2650e5dd7070Spatrick   bool HasByrefExtendedLayout = false;
2651a9ac8606Spatrick   Qualifiers::ObjCLifetime Lifetime = Qualifiers::OCL_None;
2652e5dd7070Spatrick   if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2653e5dd7070Spatrick       HasByrefExtendedLayout) {
2654e5dd7070Spatrick     /// void *__byref_variable_layout;
2655e5dd7070Spatrick     types.push_back(Int8PtrTy);
2656e5dd7070Spatrick     size += CharUnits::fromQuantity(PointerSizeInBytes);
2657e5dd7070Spatrick   }
2658e5dd7070Spatrick 
2659e5dd7070Spatrick   // T x;
2660e5dd7070Spatrick   llvm::Type *varTy = ConvertTypeForMem(Ty);
2661e5dd7070Spatrick 
2662e5dd7070Spatrick   bool packed = false;
2663e5dd7070Spatrick   CharUnits varAlign = getContext().getDeclAlign(D);
2664e5dd7070Spatrick   CharUnits varOffset = size.alignTo(varAlign);
2665e5dd7070Spatrick 
2666e5dd7070Spatrick   // We may have to insert padding.
2667e5dd7070Spatrick   if (varOffset != size) {
2668e5dd7070Spatrick     llvm::Type *paddingTy =
2669e5dd7070Spatrick       llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2670e5dd7070Spatrick 
2671e5dd7070Spatrick     types.push_back(paddingTy);
2672e5dd7070Spatrick     size = varOffset;
2673e5dd7070Spatrick 
2674e5dd7070Spatrick   // Conversely, we might have to prevent LLVM from inserting padding.
2675*12c85518Srobert   } else if (CGM.getDataLayout().getABITypeAlign(varTy) >
2676*12c85518Srobert              uint64_t(varAlign.getQuantity())) {
2677e5dd7070Spatrick     packed = true;
2678e5dd7070Spatrick   }
2679e5dd7070Spatrick   types.push_back(varTy);
2680e5dd7070Spatrick 
2681e5dd7070Spatrick   byrefType->setBody(types, packed);
2682e5dd7070Spatrick 
2683e5dd7070Spatrick   BlockByrefInfo info;
2684e5dd7070Spatrick   info.Type = byrefType;
2685e5dd7070Spatrick   info.FieldIndex = types.size() - 1;
2686e5dd7070Spatrick   info.FieldOffset = varOffset;
2687e5dd7070Spatrick   info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2688e5dd7070Spatrick 
2689e5dd7070Spatrick   auto pair = BlockByrefInfos.insert({D, info});
2690e5dd7070Spatrick   assert(pair.second && "info was inserted recursively?");
2691e5dd7070Spatrick   return pair.first->second;
2692e5dd7070Spatrick }
2693e5dd7070Spatrick 
2694e5dd7070Spatrick /// Initialize the structural components of a __block variable, i.e.
2695e5dd7070Spatrick /// everything but the actual object.
emitByrefStructureInit(const AutoVarEmission & emission)2696e5dd7070Spatrick void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2697e5dd7070Spatrick   // Find the address of the local.
2698e5dd7070Spatrick   Address addr = emission.Addr;
2699e5dd7070Spatrick 
2700e5dd7070Spatrick   // That's an alloca of the byref structure type.
2701*12c85518Srobert   llvm::StructType *byrefType = cast<llvm::StructType>(addr.getElementType());
2702e5dd7070Spatrick 
2703e5dd7070Spatrick   unsigned nextHeaderIndex = 0;
2704e5dd7070Spatrick   CharUnits nextHeaderOffset;
2705e5dd7070Spatrick   auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2706e5dd7070Spatrick                               const Twine &name) {
2707e5dd7070Spatrick     auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
2708e5dd7070Spatrick     Builder.CreateStore(value, fieldAddr);
2709e5dd7070Spatrick 
2710e5dd7070Spatrick     nextHeaderIndex++;
2711e5dd7070Spatrick     nextHeaderOffset += fieldSize;
2712e5dd7070Spatrick   };
2713e5dd7070Spatrick 
2714e5dd7070Spatrick   // Build the byref helpers if necessary.  This is null if we don't need any.
2715e5dd7070Spatrick   BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2716e5dd7070Spatrick 
2717e5dd7070Spatrick   const VarDecl &D = *emission.Variable;
2718e5dd7070Spatrick   QualType type = D.getType();
2719e5dd7070Spatrick 
2720a9ac8606Spatrick   bool HasByrefExtendedLayout = false;
2721a9ac8606Spatrick   Qualifiers::ObjCLifetime ByrefLifetime = Qualifiers::OCL_None;
2722e5dd7070Spatrick   bool ByRefHasLifetime =
2723e5dd7070Spatrick     getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2724e5dd7070Spatrick 
2725e5dd7070Spatrick   llvm::Value *V;
2726e5dd7070Spatrick 
2727e5dd7070Spatrick   // Initialize the 'isa', which is just 0 or 1.
2728e5dd7070Spatrick   int isa = 0;
2729e5dd7070Spatrick   if (type.isObjCGCWeak())
2730e5dd7070Spatrick     isa = 1;
2731e5dd7070Spatrick   V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2732e5dd7070Spatrick   storeHeaderField(V, getPointerSize(), "byref.isa");
2733e5dd7070Spatrick 
2734e5dd7070Spatrick   // Store the address of the variable into its own forwarding pointer.
2735e5dd7070Spatrick   storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2736e5dd7070Spatrick 
2737e5dd7070Spatrick   // Blocks ABI:
2738e5dd7070Spatrick   //   c) the flags field is set to either 0 if no helper functions are
2739e5dd7070Spatrick   //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2740e5dd7070Spatrick   BlockFlags flags;
2741e5dd7070Spatrick   if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2742e5dd7070Spatrick   if (ByRefHasLifetime) {
2743e5dd7070Spatrick     if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2744e5dd7070Spatrick       else switch (ByrefLifetime) {
2745e5dd7070Spatrick         case Qualifiers::OCL_Strong:
2746e5dd7070Spatrick           flags |= BLOCK_BYREF_LAYOUT_STRONG;
2747e5dd7070Spatrick           break;
2748e5dd7070Spatrick         case Qualifiers::OCL_Weak:
2749e5dd7070Spatrick           flags |= BLOCK_BYREF_LAYOUT_WEAK;
2750e5dd7070Spatrick           break;
2751e5dd7070Spatrick         case Qualifiers::OCL_ExplicitNone:
2752e5dd7070Spatrick           flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2753e5dd7070Spatrick           break;
2754e5dd7070Spatrick         case Qualifiers::OCL_None:
2755e5dd7070Spatrick           if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2756e5dd7070Spatrick             flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2757e5dd7070Spatrick           break;
2758e5dd7070Spatrick         default:
2759e5dd7070Spatrick           break;
2760e5dd7070Spatrick       }
2761e5dd7070Spatrick     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2762e5dd7070Spatrick       printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2763e5dd7070Spatrick       if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2764e5dd7070Spatrick         printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2765e5dd7070Spatrick       if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2766e5dd7070Spatrick         BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2767e5dd7070Spatrick         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
2768e5dd7070Spatrick           printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2769e5dd7070Spatrick         if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
2770e5dd7070Spatrick           printf(" BLOCK_BYREF_LAYOUT_STRONG");
2771e5dd7070Spatrick         if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2772e5dd7070Spatrick           printf(" BLOCK_BYREF_LAYOUT_WEAK");
2773e5dd7070Spatrick         if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2774e5dd7070Spatrick           printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2775e5dd7070Spatrick         if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2776e5dd7070Spatrick           printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2777e5dd7070Spatrick       }
2778e5dd7070Spatrick       printf("\n");
2779e5dd7070Spatrick     }
2780e5dd7070Spatrick   }
2781e5dd7070Spatrick   storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2782e5dd7070Spatrick                    getIntSize(), "byref.flags");
2783e5dd7070Spatrick 
2784e5dd7070Spatrick   CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2785e5dd7070Spatrick   V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2786e5dd7070Spatrick   storeHeaderField(V, getIntSize(), "byref.size");
2787e5dd7070Spatrick 
2788e5dd7070Spatrick   if (helpers) {
2789e5dd7070Spatrick     storeHeaderField(helpers->CopyHelper, getPointerSize(),
2790e5dd7070Spatrick                      "byref.copyHelper");
2791e5dd7070Spatrick     storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2792e5dd7070Spatrick                      "byref.disposeHelper");
2793e5dd7070Spatrick   }
2794e5dd7070Spatrick 
2795e5dd7070Spatrick   if (ByRefHasLifetime && HasByrefExtendedLayout) {
2796e5dd7070Spatrick     auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2797e5dd7070Spatrick     storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2798e5dd7070Spatrick   }
2799e5dd7070Spatrick }
2800e5dd7070Spatrick 
BuildBlockRelease(llvm::Value * V,BlockFieldFlags flags,bool CanThrow)2801e5dd7070Spatrick void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2802e5dd7070Spatrick                                         bool CanThrow) {
2803e5dd7070Spatrick   llvm::FunctionCallee F = CGM.getBlockObjectDispose();
2804e5dd7070Spatrick   llvm::Value *args[] = {
2805e5dd7070Spatrick     Builder.CreateBitCast(V, Int8PtrTy),
2806e5dd7070Spatrick     llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2807e5dd7070Spatrick   };
2808e5dd7070Spatrick 
2809e5dd7070Spatrick   if (CanThrow)
2810e5dd7070Spatrick     EmitRuntimeCallOrInvoke(F, args);
2811e5dd7070Spatrick   else
2812e5dd7070Spatrick     EmitNounwindRuntimeCall(F, args);
2813e5dd7070Spatrick }
2814e5dd7070Spatrick 
enterByrefCleanup(CleanupKind Kind,Address Addr,BlockFieldFlags Flags,bool LoadBlockVarAddr,bool CanThrow)2815e5dd7070Spatrick void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2816e5dd7070Spatrick                                         BlockFieldFlags Flags,
2817e5dd7070Spatrick                                         bool LoadBlockVarAddr, bool CanThrow) {
2818e5dd7070Spatrick   EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2819e5dd7070Spatrick                                         CanThrow);
2820e5dd7070Spatrick }
2821e5dd7070Spatrick 
2822e5dd7070Spatrick /// Adjust the declaration of something from the blocks API.
configureBlocksRuntimeObject(CodeGenModule & CGM,llvm::Constant * C)2823e5dd7070Spatrick static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2824e5dd7070Spatrick                                          llvm::Constant *C) {
2825e5dd7070Spatrick   auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2826e5dd7070Spatrick 
2827e5dd7070Spatrick   if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2828e5dd7070Spatrick     IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2829e5dd7070Spatrick     TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2830e5dd7070Spatrick     DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2831e5dd7070Spatrick 
2832e5dd7070Spatrick     assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2833e5dd7070Spatrick             isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2834e5dd7070Spatrick            "expected Function or GlobalVariable");
2835e5dd7070Spatrick 
2836e5dd7070Spatrick     const NamedDecl *ND = nullptr;
2837a9ac8606Spatrick     for (const auto *Result : DC->lookup(&II))
2838e5dd7070Spatrick       if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2839e5dd7070Spatrick           (ND = dyn_cast<VarDecl>(Result)))
2840e5dd7070Spatrick         break;
2841e5dd7070Spatrick 
2842e5dd7070Spatrick     // TODO: support static blocks runtime
2843e5dd7070Spatrick     if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2844e5dd7070Spatrick       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2845e5dd7070Spatrick       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2846e5dd7070Spatrick     } else {
2847e5dd7070Spatrick       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2848e5dd7070Spatrick       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2849e5dd7070Spatrick     }
2850e5dd7070Spatrick   }
2851e5dd7070Spatrick 
2852e5dd7070Spatrick   if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2853e5dd7070Spatrick       GV->hasExternalLinkage())
2854e5dd7070Spatrick     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2855e5dd7070Spatrick 
2856e5dd7070Spatrick   CGM.setDSOLocal(GV);
2857e5dd7070Spatrick }
2858e5dd7070Spatrick 
getBlockObjectDispose()2859e5dd7070Spatrick llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
2860e5dd7070Spatrick   if (BlockObjectDispose)
2861e5dd7070Spatrick     return BlockObjectDispose;
2862e5dd7070Spatrick 
2863e5dd7070Spatrick   llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2864e5dd7070Spatrick   llvm::FunctionType *fty
2865e5dd7070Spatrick     = llvm::FunctionType::get(VoidTy, args, false);
2866e5dd7070Spatrick   BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2867e5dd7070Spatrick   configureBlocksRuntimeObject(
2868e5dd7070Spatrick       *this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
2869e5dd7070Spatrick   return BlockObjectDispose;
2870e5dd7070Spatrick }
2871e5dd7070Spatrick 
getBlockObjectAssign()2872e5dd7070Spatrick llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
2873e5dd7070Spatrick   if (BlockObjectAssign)
2874e5dd7070Spatrick     return BlockObjectAssign;
2875e5dd7070Spatrick 
2876e5dd7070Spatrick   llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2877e5dd7070Spatrick   llvm::FunctionType *fty
2878e5dd7070Spatrick     = llvm::FunctionType::get(VoidTy, args, false);
2879e5dd7070Spatrick   BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2880e5dd7070Spatrick   configureBlocksRuntimeObject(
2881e5dd7070Spatrick       *this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
2882e5dd7070Spatrick   return BlockObjectAssign;
2883e5dd7070Spatrick }
2884e5dd7070Spatrick 
getNSConcreteGlobalBlock()2885e5dd7070Spatrick llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2886e5dd7070Spatrick   if (NSConcreteGlobalBlock)
2887e5dd7070Spatrick     return NSConcreteGlobalBlock;
2888e5dd7070Spatrick 
2889*12c85518Srobert   NSConcreteGlobalBlock = GetOrCreateLLVMGlobal(
2890*12c85518Srobert       "_NSConcreteGlobalBlock", Int8PtrTy, LangAS::Default, nullptr);
2891e5dd7070Spatrick   configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2892e5dd7070Spatrick   return NSConcreteGlobalBlock;
2893e5dd7070Spatrick }
2894e5dd7070Spatrick 
getNSConcreteStackBlock()2895e5dd7070Spatrick llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2896e5dd7070Spatrick   if (NSConcreteStackBlock)
2897e5dd7070Spatrick     return NSConcreteStackBlock;
2898e5dd7070Spatrick 
2899*12c85518Srobert   NSConcreteStackBlock = GetOrCreateLLVMGlobal(
2900*12c85518Srobert       "_NSConcreteStackBlock", Int8PtrTy, LangAS::Default, nullptr);
2901e5dd7070Spatrick   configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2902e5dd7070Spatrick   return NSConcreteStackBlock;
2903e5dd7070Spatrick }
2904