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