Coverage Report

Created: 2020-02-15 09:57

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