clang  3.9.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 "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Module.h"
24 #include <algorithm>
25 #include <cstdio>
26 
27 using namespace clang;
28 using namespace CodeGen;
29 
30 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
31  : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
32  HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
33  LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
34  DominatingIP(nullptr) {
35 
36  // Skip asm prefix, if any. 'name' is usually taken directly from
37  // the mangled name of the enclosing function.
38  if (!name.empty() && name[0] == '\01')
39  name = name.substr(1);
40 }
41 
42 // Anchor the vtable to this translation unit.
44 
45 /// Build the given block as a global block.
46 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
47  const CGBlockInfo &blockInfo,
48  llvm::Constant *blockFn);
49 
50 /// Build the helper function to copy a block.
51 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
52  const CGBlockInfo &blockInfo) {
53  return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
54 }
55 
56 /// Build the helper function to dispose of a block.
57 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
58  const CGBlockInfo &blockInfo) {
59  return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
60 }
61 
62 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
63 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
64 /// meta-data and contains stationary information about the block literal.
65 /// Its definition will have 4 (or optinally 6) words.
66 /// \code
67 /// struct Block_descriptor {
68 /// unsigned long reserved;
69 /// unsigned long size; // size of Block_literal metadata in bytes.
70 /// void *copy_func_helper_decl; // optional copy helper.
71 /// void *destroy_func_decl; // optioanl destructor helper.
72 /// void *block_method_encoding_address; // @encode for block literal signature.
73 /// void *block_layout_info; // encoding of captured block variables.
74 /// };
75 /// \endcode
76 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
77  const CGBlockInfo &blockInfo) {
78  ASTContext &C = CGM.getContext();
79 
81  llvm::Type *i8p = nullptr;
82  if (CGM.getLangOpts().OpenCL)
83  i8p =
84  llvm::Type::getInt8PtrTy(
86  else
87  i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
88 
90 
91  // reserved
92  elements.push_back(llvm::ConstantInt::get(ulong, 0));
93 
94  // Size
95  // FIXME: What is the right way to say this doesn't fit? We should give
96  // a user diagnostic in that case. Better fix would be to change the
97  // API to size_t.
98  elements.push_back(llvm::ConstantInt::get(ulong,
99  blockInfo.BlockSize.getQuantity()));
100 
101  // Optional copy/dispose helpers.
102  if (blockInfo.NeedsCopyDispose) {
103  // copy_func_helper_decl
104  elements.push_back(buildCopyHelper(CGM, blockInfo));
105 
106  // destroy_func_decl
107  elements.push_back(buildDisposeHelper(CGM, blockInfo));
108  }
109 
110  // Signature. Mandatory ObjC-style method descriptor @encode sequence.
111  std::string typeAtEncoding =
113  elements.push_back(llvm::ConstantExpr::getBitCast(
114  CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
115 
116  // GC layout.
117  if (C.getLangOpts().ObjC1) {
118  if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
119  elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
120  else
121  elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
122  }
123  else
124  elements.push_back(llvm::Constant::getNullValue(i8p));
125 
126  llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
127 
128  llvm::GlobalVariable *global =
129  new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
131  init, "__block_descriptor_tmp");
132 
133  return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
134 }
135 
136 /*
137  Purely notional variadic template describing the layout of a block.
138 
139  template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
140  struct Block_literal {
141  /// Initialized to one of:
142  /// extern void *_NSConcreteStackBlock[];
143  /// extern void *_NSConcreteGlobalBlock[];
144  ///
145  /// In theory, we could start one off malloc'ed by setting
146  /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
147  /// this isa:
148  /// extern void *_NSConcreteMallocBlock[];
149  struct objc_class *isa;
150 
151  /// These are the flags (with corresponding bit number) that the
152  /// compiler is actually supposed to know about.
153  /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
154  /// descriptor provides copy and dispose helper functions
155  /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
156  /// object with a nontrivial destructor or copy constructor
157  /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
158  /// as global memory
159  /// 29. BLOCK_USE_STRET - indicates that the block function
160  /// uses stret, which objc_msgSend needs to know about
161  /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
162  /// @encoded signature string
163  /// And we're not supposed to manipulate these:
164  /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
165  /// to malloc'ed memory
166  /// 27. BLOCK_IS_GC - indicates that the block has been moved to
167  /// to GC-allocated memory
168  /// Additionally, the bottom 16 bits are a reference count which
169  /// should be zero on the stack.
170  int flags;
171 
172  /// Reserved; should be zero-initialized.
173  int reserved;
174 
175  /// Function pointer generated from block literal.
176  _ResultType (*invoke)(Block_literal *, _ParamTypes...);
177 
178  /// Block description metadata generated from block literal.
179  struct Block_descriptor *block_descriptor;
180 
181  /// Captured values follow.
182  _CapturesTypes captures...;
183  };
184  */
185 
186 /// The number of fields in a block header.
187 const unsigned BlockHeaderSize = 5;
188 
189 namespace {
190  /// A chunk of data that we actually have to capture in the block.
191  struct BlockLayoutChunk {
192  CharUnits Alignment;
193  CharUnits Size;
194  Qualifiers::ObjCLifetime Lifetime;
195  const BlockDecl::Capture *Capture; // null for 'this'
196  llvm::Type *Type;
197 
198  BlockLayoutChunk(CharUnits align, CharUnits size,
199  Qualifiers::ObjCLifetime lifetime,
200  const BlockDecl::Capture *capture,
201  llvm::Type *type)
202  : Alignment(align), Size(size), Lifetime(lifetime),
203  Capture(capture), Type(type) {}
204 
205  /// Tell the block info that this chunk has the given field index.
206  void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
207  if (!Capture) {
208  info.CXXThisIndex = index;
209  info.CXXThisOffset = offset;
210  } else {
211  info.Captures.insert({Capture->getVariable(),
212  CGBlockInfo::Capture::makeIndex(index, offset)});
213  }
214  }
215  };
216 
217  /// Order by 1) all __strong together 2) next, all byfref together 3) next,
218  /// all __weak together. Preserve descending alignment in all situations.
219  bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
220  if (left.Alignment != right.Alignment)
221  return left.Alignment > right.Alignment;
222 
223  auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
224  if (chunk.Capture && chunk.Capture->isByRef())
225  return 1;
226  if (chunk.Lifetime == Qualifiers::OCL_Strong)
227  return 0;
228  if (chunk.Lifetime == Qualifiers::OCL_Weak)
229  return 2;
230  return 3;
231  };
232 
233  return getPrefOrder(left) < getPrefOrder(right);
234  }
235 } // end anonymous namespace
236 
237 /// Determines if the given type is safe for constant capture in C++.
239  const RecordType *recordType =
241 
242  // Only records can be unsafe.
243  if (!recordType) return true;
244 
245  const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
246 
247  // Maintain semantics for classes with non-trivial dtors or copy ctors.
248  if (!record->hasTrivialDestructor()) return false;
249  if (record->hasNonTrivialCopyConstructor()) return false;
250 
251  // Otherwise, we just have to make sure there aren't any mutable
252  // fields that might have changed since initialization.
253  return !record->hasMutableFields();
254 }
255 
256 /// It is illegal to modify a const object after initialization.
257 /// Therefore, if a const object has a constant initializer, we don't
258 /// actually need to keep storage for it in the block; we'll just
259 /// rematerialize it at the start of the block function. This is
260 /// acceptable because we make no promises about address stability of
261 /// captured variables.
262 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
263  CodeGenFunction *CGF,
264  const VarDecl *var) {
265  // Return if this is a function paramter. We shouldn't try to
266  // rematerialize default arguments of function parameters.
267  if (isa<ParmVarDecl>(var))
268  return nullptr;
269 
270  QualType type = var->getType();
271 
272  // We can only do this if the variable is const.
273  if (!type.isConstQualified()) return nullptr;
274 
275  // Furthermore, in C++ we have to worry about mutable fields:
276  // C++ [dcl.type.cv]p4:
277  // Except that any class member declared mutable can be
278  // modified, any attempt to modify a const object during its
279  // lifetime results in undefined behavior.
280  if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
281  return nullptr;
282 
283  // If the variable doesn't have any initializer (shouldn't this be
284  // invalid?), it's not clear what we should do. Maybe capture as
285  // zero?
286  const Expr *init = var->getInit();
287  if (!init) return nullptr;
288 
289  return CGM.EmitConstantInit(*var, CGF);
290 }
291 
292 /// Get the low bit of a nonzero character count. This is the
293 /// alignment of the nth byte if the 0th byte is universally aligned.
295  return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
296 }
297 
299  SmallVectorImpl<llvm::Type*> &elementTypes) {
300  // The header is basically 'struct { void *; int; int; void *; void *; }'.
301  // Assert that that struct is packed.
302  assert(CGM.getIntSize() <= CGM.getPointerSize());
303  assert(CGM.getIntAlign() <= CGM.getPointerAlign());
304  assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
305 
306  info.BlockAlign = CGM.getPointerAlign();
307  info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
308 
309  assert(elementTypes.empty());
310  elementTypes.push_back(CGM.VoidPtrTy);
311  elementTypes.push_back(CGM.IntTy);
312  elementTypes.push_back(CGM.IntTy);
313  elementTypes.push_back(CGM.VoidPtrTy);
314  elementTypes.push_back(CGM.getBlockDescriptorType());
315 
316  assert(elementTypes.size() == BlockHeaderSize);
317 }
318 
319 /// Compute the layout of the given block. Attempts to lay the block
320 /// out with minimal space requirements.
322  CGBlockInfo &info) {
323  ASTContext &C = CGM.getContext();
324  const BlockDecl *block = info.getBlockDecl();
325 
326  SmallVector<llvm::Type*, 8> elementTypes;
327  initializeForBlockHeader(CGM, info, elementTypes);
328 
329  if (!block->hasCaptures()) {
330  info.StructureType =
331  llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
332  info.CanBeGlobal = true;
333  return;
334  }
335  else if (C.getLangOpts().ObjC1 &&
336  CGM.getLangOpts().getGC() == LangOptions::NonGC)
337  info.HasCapturedVariableLayout = true;
338 
339  // Collect the layout chunks.
341  layout.reserve(block->capturesCXXThis() +
342  (block->capture_end() - block->capture_begin()));
343 
344  CharUnits maxFieldAlign;
345 
346  // First, 'this'.
347  if (block->capturesCXXThis()) {
348  assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
349  "Can't capture 'this' outside a method");
350  QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
351 
352  // Theoretically, this could be in a different address space, so
353  // don't assume standard pointer size/align.
354  llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
355  std::pair<CharUnits,CharUnits> tinfo
356  = CGM.getContext().getTypeInfoInChars(thisType);
357  maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
358 
359  layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
361  nullptr, llvmType));
362  }
363 
364  // Next, all the block captures.
365  for (const auto &CI : block->captures()) {
366  const VarDecl *variable = CI.getVariable();
367 
368  if (CI.isByRef()) {
369  // We have to copy/dispose of the __block reference.
370  info.NeedsCopyDispose = true;
371 
372  // Just use void* instead of a pointer to the byref type.
373  CharUnits align = CGM.getPointerAlign();
374  maxFieldAlign = std::max(maxFieldAlign, align);
375 
376  layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
378  CGM.VoidPtrTy));
379  continue;
380  }
381 
382  // Otherwise, build a layout chunk with the size and alignment of
383  // the declaration.
384  if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
385  info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
386  continue;
387  }
388 
389  // If we have a lifetime qualifier, honor it for capture purposes.
390  // That includes *not* copying it if it's __unsafe_unretained.
391  Qualifiers::ObjCLifetime lifetime =
392  variable->getType().getObjCLifetime();
393  if (lifetime) {
394  switch (lifetime) {
395  case Qualifiers::OCL_None: llvm_unreachable("impossible");
398  break;
399 
402  info.NeedsCopyDispose = true;
403  }
404 
405  // Block pointers require copy/dispose. So do Objective-C pointers.
406  } else if (variable->getType()->isObjCRetainableType()) {
407  // But honor the inert __unsafe_unretained qualifier, which doesn't
408  // actually make it into the type system.
409  if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
410  lifetime = Qualifiers::OCL_ExplicitNone;
411  } else {
412  info.NeedsCopyDispose = true;
413  // used for mrr below.
414  lifetime = Qualifiers::OCL_Strong;
415  }
416 
417  // So do types that require non-trivial copy construction.
418  } else if (CI.hasCopyExpr()) {
419  info.NeedsCopyDispose = true;
420  info.HasCXXObject = true;
421 
422  // And so do types with destructors.
423  } else if (CGM.getLangOpts().CPlusPlus) {
424  if (const CXXRecordDecl *record =
425  variable->getType()->getAsCXXRecordDecl()) {
426  if (!record->hasTrivialDestructor()) {
427  info.HasCXXObject = true;
428  info.NeedsCopyDispose = true;
429  }
430  }
431  }
432 
433  QualType VT = variable->getType();
434  CharUnits size = C.getTypeSizeInChars(VT);
435  CharUnits align = C.getDeclAlign(variable);
436 
437  maxFieldAlign = std::max(maxFieldAlign, align);
438 
439  llvm::Type *llvmType =
440  CGM.getTypes().ConvertTypeForMem(VT);
441 
442  layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
443  }
444 
445  // If that was everything, we're done here.
446  if (layout.empty()) {
447  info.StructureType =
448  llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
449  info.CanBeGlobal = true;
450  return;
451  }
452 
453  // Sort the layout by alignment. We have to use a stable sort here
454  // to get reproducible results. There should probably be an
455  // llvm::array_pod_stable_sort.
456  std::stable_sort(layout.begin(), layout.end());
457 
458  // Needed for blocks layout info.
461 
462  CharUnits &blockSize = info.BlockSize;
463  info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
464 
465  // Assuming that the first byte in the header is maximally aligned,
466  // get the alignment of the first byte following the header.
467  CharUnits endAlign = getLowBit(blockSize);
468 
469  // If the end of the header isn't satisfactorily aligned for the
470  // maximum thing, look for things that are okay with the header-end
471  // alignment, and keep appending them until we get something that's
472  // aligned right. This algorithm is only guaranteed optimal if
473  // that condition is satisfied at some point; otherwise we can get
474  // things like:
475  // header // next byte has alignment 4
476  // something_with_size_5; // next byte has alignment 1
477  // something_with_alignment_8;
478  // which has 7 bytes of padding, as opposed to the naive solution
479  // which might have less (?).
480  if (endAlign < maxFieldAlign) {
482  li = layout.begin() + 1, le = layout.end();
483 
484  // Look for something that the header end is already
485  // satisfactorily aligned for.
486  for (; li != le && endAlign < li->Alignment; ++li)
487  ;
488 
489  // If we found something that's naturally aligned for the end of
490  // the header, keep adding things...
491  if (li != le) {
493  for (; li != le; ++li) {
494  assert(endAlign >= li->Alignment);
495 
496  li->setIndex(info, elementTypes.size(), blockSize);
497  elementTypes.push_back(li->Type);
498  blockSize += li->Size;
499  endAlign = getLowBit(blockSize);
500 
501  // ...until we get to the alignment of the maximum field.
502  if (endAlign >= maxFieldAlign) {
503  break;
504  }
505  }
506  // Don't re-append everything we just appended.
507  layout.erase(first, li);
508  }
509  }
510 
511  assert(endAlign == getLowBit(blockSize));
512 
513  // At this point, we just have to add padding if the end align still
514  // isn't aligned right.
515  if (endAlign < maxFieldAlign) {
516  CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
517  CharUnits padding = newBlockSize - blockSize;
518 
519  // If we haven't yet added any fields, remember that there was an
520  // initial gap; this need to go into the block layout bit map.
521  if (blockSize == info.BlockHeaderForcedGapOffset) {
522  info.BlockHeaderForcedGapSize = padding;
523  }
524 
525  elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
526  padding.getQuantity()));
527  blockSize = newBlockSize;
528  endAlign = getLowBit(blockSize); // might be > maxFieldAlign
529  }
530 
531  assert(endAlign >= maxFieldAlign);
532  assert(endAlign == getLowBit(blockSize));
533  // Slam everything else on now. This works because they have
534  // strictly decreasing alignment and we expect that size is always a
535  // multiple of alignment.
537  li = layout.begin(), le = layout.end(); li != le; ++li) {
538  if (endAlign < li->Alignment) {
539  // size may not be multiple of alignment. This can only happen with
540  // an over-aligned variable. We will be adding a padding field to
541  // make the size be multiple of alignment.
542  CharUnits padding = li->Alignment - endAlign;
543  elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
544  padding.getQuantity()));
545  blockSize += padding;
546  endAlign = getLowBit(blockSize);
547  }
548  assert(endAlign >= li->Alignment);
549  li->setIndex(info, elementTypes.size(), blockSize);
550  elementTypes.push_back(li->Type);
551  blockSize += li->Size;
552  endAlign = getLowBit(blockSize);
553  }
554 
555  info.StructureType =
556  llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
557 }
558 
559 /// Enter the scope of a block. This should be run at the entrance to
560 /// a full-expression so that the block's cleanups are pushed at the
561 /// right place in the stack.
562 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
563  assert(CGF.HaveInsertPoint());
564 
565  // Allocate the block info and place it at the head of the list.
566  CGBlockInfo &blockInfo =
567  *new CGBlockInfo(block, CGF.CurFn->getName());
568  blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
569  CGF.FirstBlockInfo = &blockInfo;
570 
571  // Compute information about the layout, etc., of this block,
572  // pushing cleanups as necessary.
573  computeBlockInfo(CGF.CGM, &CGF, blockInfo);
574 
575  // Nothing else to do if it can be global.
576  if (blockInfo.CanBeGlobal) return;
577 
578  // Make the allocation for the block.
579  blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
580  blockInfo.BlockAlign, "block");
581 
582  // If there are cleanups to emit, enter them (but inactive).
583  if (!blockInfo.NeedsCopyDispose) return;
584 
585  // Walk through the captures (in order) and find the ones not
586  // captured by constant.
587  for (const auto &CI : block->captures()) {
588  // Ignore __block captures; there's nothing special in the
589  // on-stack block that we need to do for them.
590  if (CI.isByRef()) continue;
591 
592  // Ignore variables that are constant-captured.
593  const VarDecl *variable = CI.getVariable();
594  CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
595  if (capture.isConstant()) continue;
596 
597  // Ignore objects that aren't destructed.
598  QualType::DestructionKind dtorKind =
599  variable->getType().isDestructedType();
600  if (dtorKind == QualType::DK_none) continue;
601 
602  CodeGenFunction::Destroyer *destroyer;
603 
604  // Block captures count as local values and have imprecise semantics.
605  // They also can't be arrays, so need to worry about that.
606  if (dtorKind == QualType::DK_objc_strong_lifetime) {
608  } else {
609  destroyer = CGF.getDestroyer(dtorKind);
610  }
611 
612  // GEP down to the address.
613  Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
614  capture.getIndex(),
615  capture.getOffset());
616 
617  // We can use that GEP as the dominating IP.
618  if (!blockInfo.DominatingIP)
619  blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
620 
621  CleanupKind cleanupKind = InactiveNormalCleanup;
622  bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
623  if (useArrayEHCleanup)
624  cleanupKind = InactiveNormalAndEHCleanup;
625 
626  CGF.pushDestroy(cleanupKind, addr, variable->getType(),
627  destroyer, useArrayEHCleanup);
628 
629  // Remember where that cleanup was.
630  capture.setCleanup(CGF.EHStack.stable_begin());
631  }
632 }
633 
634 /// Enter a full-expression with a non-trivial number of objects to
635 /// clean up. This is in this file because, at the moment, the only
636 /// kind of cleanup object is a BlockDecl*.
638  assert(E->getNumObjects() != 0);
641  i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
642  enterBlockScope(*this, *i);
643  }
644 }
645 
646 /// Find the layout for the given block in a linked list and remove it.
648  const BlockDecl *block) {
649  while (true) {
650  assert(head && *head);
651  CGBlockInfo *cur = *head;
652 
653  // If this is the block we're looking for, splice it out of the list.
654  if (cur->getBlockDecl() == block) {
655  *head = cur->NextBlockInfo;
656  return cur;
657  }
658 
659  head = &cur->NextBlockInfo;
660  }
661 }
662 
663 /// Destroy a chain of block layouts.
665  assert(head && "destroying an empty chain");
666  do {
667  CGBlockInfo *cur = head;
668  head = cur->NextBlockInfo;
669  delete cur;
670  } while (head != nullptr);
671 }
672 
673 /// Emit a block literal expression in the current function.
675  // If the block has no captures, we won't have a pre-computed
676  // layout for it.
677  if (!blockExpr->getBlockDecl()->hasCaptures()) {
678  CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
679  computeBlockInfo(CGM, this, blockInfo);
680  blockInfo.BlockExpression = blockExpr;
681  return EmitBlockLiteral(blockInfo);
682  }
683 
684  // Find the block info for this block and take ownership of it.
685  std::unique_ptr<CGBlockInfo> blockInfo;
686  blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
687  blockExpr->getBlockDecl()));
688 
689  blockInfo->BlockExpression = blockExpr;
690  return EmitBlockLiteral(*blockInfo);
691 }
692 
694  // Using the computed layout, generate the actual block function.
695  bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
696  llvm::Constant *blockFn
697  = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
698  LocalDeclMap,
699  isLambdaConv);
700  blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
701 
702  // If there is nothing to capture, we can emit this as a global block.
703  if (blockInfo.CanBeGlobal)
704  return buildGlobalBlock(CGM, blockInfo, blockFn);
705 
706  // Otherwise, we have to emit this as a local block.
707 
708  llvm::Constant *isa = CGM.getNSConcreteStackBlock();
709  isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
710 
711  // Build the block descriptor.
712  llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
713 
714  Address blockAddr = blockInfo.LocalAddress;
715  assert(blockAddr.isValid() && "block has no address!");
716 
717  // Compute the initial on-stack block flags.
720  if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
721  if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
722  if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
723 
724  auto projectField =
725  [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
726  return Builder.CreateStructGEP(blockAddr, index, offset, name);
727  };
728  auto storeField =
729  [&](llvm::Value *value, unsigned index, CharUnits offset,
730  const Twine &name) {
731  Builder.CreateStore(value, projectField(index, offset, name));
732  };
733 
734  // Initialize the block header.
735  {
736  // We assume all the header fields are densely packed.
737  unsigned index = 0;
738  CharUnits offset;
739  auto addHeaderField =
740  [&](llvm::Value *value, CharUnits size, const Twine &name) {
741  storeField(value, index, offset, name);
742  offset += size;
743  index++;
744  };
745 
746  addHeaderField(isa, getPointerSize(), "block.isa");
747  addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
748  getIntSize(), "block.flags");
749  addHeaderField(llvm::ConstantInt::get(IntTy, 0),
750  getIntSize(), "block.reserved");
751  addHeaderField(blockFn, getPointerSize(), "block.invoke");
752  addHeaderField(descriptor, getPointerSize(), "block.descriptor");
753  }
754 
755  // Finally, capture all the values into the block.
756  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
757 
758  // First, 'this'.
759  if (blockDecl->capturesCXXThis()) {
760  Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
761  "block.captured-this.addr");
762  Builder.CreateStore(LoadCXXThis(), addr);
763  }
764 
765  // Next, captured variables.
766  for (const auto &CI : blockDecl->captures()) {
767  const VarDecl *variable = CI.getVariable();
768  const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
769 
770  // Ignore constant captures.
771  if (capture.isConstant()) continue;
772 
773  QualType type = variable->getType();
774 
775  // This will be a [[type]]*, except that a byref entry will just be
776  // an i8**.
777  Address blockField =
778  projectField(capture.getIndex(), capture.getOffset(), "block.captured");
779 
780  // Compute the address of the thing we're going to move into the
781  // block literal.
782  Address src = Address::invalid();
783  if (BlockInfo && CI.isNested()) {
784  // We need to use the capture from the enclosing block.
785  const CGBlockInfo::Capture &enclosingCapture =
786  BlockInfo->getCapture(variable);
787 
788  // This is a [[type]]*, except that a byref entry wil just be an i8**.
789  src = Builder.CreateStructGEP(LoadBlockStruct(),
790  enclosingCapture.getIndex(),
791  enclosingCapture.getOffset(),
792  "block.capture.addr");
793  } else if (blockDecl->isConversionFromLambda()) {
794  // The lambda capture in a lambda's conversion-to-block-pointer is
795  // special; we'll simply emit it directly.
796  src = Address::invalid();
797  } else {
798  // Just look it up in the locals map, which will give us back a
799  // [[type]]*. If that doesn't work, do the more elaborate DRE
800  // emission.
801  auto it = LocalDeclMap.find(variable);
802  if (it != LocalDeclMap.end()) {
803  src = it->second;
804  } else {
805  DeclRefExpr declRef(
806  const_cast<VarDecl *>(variable),
807  /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
809  src = EmitDeclRefLValue(&declRef).getAddress();
810  }
811  }
812 
813  // For byrefs, we just write the pointer to the byref struct into
814  // the block field. There's no need to chase the forwarding
815  // pointer at this point, since we're building something that will
816  // live a shorter life than the stack byref anyway.
817  if (CI.isByRef()) {
818  // Get a void* that points to the byref struct.
819  llvm::Value *byrefPointer;
820  if (CI.isNested())
821  byrefPointer = Builder.CreateLoad(src, "byref.capture");
822  else
823  byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
824 
825  // Write that void* into the capture field.
826  Builder.CreateStore(byrefPointer, blockField);
827 
828  // If we have a copy constructor, evaluate that into the block field.
829  } else if (const Expr *copyExpr = CI.getCopyExpr()) {
830  if (blockDecl->isConversionFromLambda()) {
831  // If we have a lambda conversion, emit the expression
832  // directly into the block instead.
833  AggValueSlot Slot =
834  AggValueSlot::forAddr(blockField, Qualifiers(),
838  EmitAggExpr(copyExpr, Slot);
839  } else {
840  EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
841  }
842 
843  // If it's a reference variable, copy the reference into the block field.
844  } else if (type->isReferenceType()) {
845  llvm::Value *ref = Builder.CreateLoad(src, "ref.val");
846  Builder.CreateStore(ref, blockField);
847 
848  // If this is an ARC __strong block-pointer variable, don't do a
849  // block copy.
850  //
851  // TODO: this can be generalized into the normal initialization logic:
852  // we should never need to do a block-copy when initializing a local
853  // variable, because the local variable's lifetime should be strictly
854  // contained within the stack block's.
855  } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
856  type->isBlockPointerType()) {
857  // Load the block and do a simple retain.
858  llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
859  value = EmitARCRetainNonBlock(value);
860 
861  // Do a primitive store to the block field.
862  Builder.CreateStore(value, blockField);
863 
864  // Otherwise, fake up a POD copy into the block field.
865  } else {
866  // Fake up a new variable so that EmitScalarInit doesn't think
867  // we're referring to the variable in its own initializer.
868  ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
869  SourceLocation(), /*name*/ nullptr,
870  type);
871 
872  // We use one of these or the other depending on whether the
873  // reference is nested.
874  DeclRefExpr declRef(const_cast<VarDecl *>(variable),
875  /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
877 
879  &declRef, VK_RValue);
880  // FIXME: Pass a specific location for the expr init so that the store is
881  // attributed to a reasonable location - otherwise it may be attributed to
882  // locations of subexpressions in the initialization.
883  EmitExprAsInit(&l2r, &blockFieldPseudoVar,
884  MakeAddrLValue(blockField, type, AlignmentSource::Decl),
885  /*captured by init*/ false);
886  }
887 
888  // Activate the cleanup if layout pushed one.
889  if (!CI.isByRef()) {
891  if (cleanup.isValid())
892  ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
893  }
894  }
895 
896  // Cast to the converted block-pointer type, which happens (somewhat
897  // unfortunately) to be a pointer to function type.
898  llvm::Value *result =
899  Builder.CreateBitCast(blockAddr.getPointer(),
900  ConvertType(blockInfo.getBlockExpr()->getType()));
901 
902  return result;
903 }
904 
905 
907  if (BlockDescriptorType)
908  return BlockDescriptorType;
909 
910  llvm::Type *UnsignedLongTy =
911  getTypes().ConvertType(getContext().UnsignedLongTy);
912 
913  // struct __block_descriptor {
914  // unsigned long reserved;
915  // unsigned long block_size;
916  //
917  // // later, the following will be added
918  //
919  // struct {
920  // void (*copyHelper)();
921  // void (*copyHelper)();
922  // } helpers; // !!! optional
923  //
924  // const char *signature; // the block signature
925  // const char *layout; // reserved
926  // };
927  BlockDescriptorType =
928  llvm::StructType::create("struct.__block_descriptor",
929  UnsignedLongTy, UnsignedLongTy, nullptr);
930 
931  // Now form a pointer to that.
932  BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
933  return BlockDescriptorType;
934 }
935 
937  if (GenericBlockLiteralType)
938  return GenericBlockLiteralType;
939 
940  llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
941 
942  // struct __block_literal_generic {
943  // void *__isa;
944  // int __flags;
945  // int __reserved;
946  // void (*__invoke)(void *);
947  // struct __block_descriptor *__descriptor;
948  // };
949  GenericBlockLiteralType =
950  llvm::StructType::create("struct.__block_literal_generic",
951  VoidPtrTy, IntTy, IntTy, VoidPtrTy,
952  BlockDescPtrTy, nullptr);
953 
954  return GenericBlockLiteralType;
955 }
956 
958  ReturnValueSlot ReturnValue) {
959  const BlockPointerType *BPT =
961 
962  llvm::Value *Callee = EmitScalarExpr(E->getCallee());
963 
964  // Get a pointer to the generic block literal.
965  llvm::Type *BlockLiteralTy =
966  llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
967 
968  // Bitcast the callee to a block literal.
969  llvm::Value *BlockLiteral =
970  Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
971 
972  // Get the function pointer from the literal.
973  llvm::Value *FuncPtr =
974  Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
975 
976  BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
977 
978  // Add the block literal.
979  CallArgList Args;
980  Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
981 
982  QualType FnType = BPT->getPointeeType();
983 
984  // And the rest of the arguments.
985  EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
986 
987  // Load the function.
988  llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
989 
990  const FunctionType *FuncTy = FnType->castAs<FunctionType>();
991  const CGFunctionInfo &FnInfo =
992  CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
993 
994  // Cast the function pointer to the right type.
995  llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
996 
997  llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
998  Func = Builder.CreateBitCast(Func, BlockFTyPtr);
999 
1000  // And call the block.
1001  return EmitCall(FnInfo, Func, ReturnValue, Args);
1002 }
1003 
1005  bool isByRef) {
1006  assert(BlockInfo && "evaluating block ref without block information?");
1007  const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1008 
1009  // Handle constant captures.
1010  if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1011 
1012  Address addr =
1013  Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1014  capture.getOffset(), "block.capture.addr");
1015 
1016  if (isByRef) {
1017  // addr should be a void** right now. Load, then cast the result
1018  // to byref*.
1019 
1020  auto &byrefInfo = getBlockByrefInfo(variable);
1021  addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1022 
1023  auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1024  addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1025 
1026  addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1027  variable->getName());
1028  }
1029 
1030  if (auto refType = variable->getType()->getAs<ReferenceType>()) {
1031  addr = EmitLoadOfReference(addr, refType);
1032  }
1033 
1034  return addr;
1035 }
1036 
1037 llvm::Constant *
1039  const char *name) {
1040  CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1041  blockInfo.BlockExpression = blockExpr;
1042 
1043  // Compute information about the layout, etc., of this block.
1044  computeBlockInfo(*this, nullptr, blockInfo);
1045 
1046  // Using that metadata, generate the actual block function.
1047  llvm::Constant *blockFn;
1048  {
1049  CodeGenFunction::DeclMapTy LocalDeclMap;
1051  blockInfo,
1052  LocalDeclMap,
1053  false);
1054  }
1055  blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1056 
1057  return buildGlobalBlock(*this, blockInfo, blockFn);
1058 }
1059 
1060 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1061  const CGBlockInfo &blockInfo,
1062  llvm::Constant *blockFn) {
1063  assert(blockInfo.CanBeGlobal);
1064 
1065  // Generate the constants for the block literal initializer.
1066  llvm::Constant *fields[BlockHeaderSize];
1067 
1068  // isa
1069  fields[0] = CGM.getNSConcreteGlobalBlock();
1070 
1071  // __flags
1073  if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1074 
1075  fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1076 
1077  // Reserved
1078  fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1079 
1080  // Function
1081  fields[3] = blockFn;
1082 
1083  // Descriptor
1084  fields[4] = buildBlockDescriptor(CGM, blockInfo);
1085 
1086  llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1087 
1088  llvm::GlobalVariable *literal =
1089  new llvm::GlobalVariable(CGM.getModule(),
1090  init->getType(),
1091  /*constant*/ true,
1093  init,
1094  "__block_literal_global");
1095  literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1096 
1097  // Return a constant of the appropriately-casted type.
1098  llvm::Type *requiredType =
1099  CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1100  return llvm::ConstantExpr::getBitCast(literal, requiredType);
1101 }
1102 
1104  unsigned argNum,
1105  llvm::Value *arg) {
1106  assert(BlockInfo && "not emitting prologue of block invocation function?!");
1107 
1108  llvm::Value *localAddr = nullptr;
1109  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1110  // Allocate a stack slot to let the debug info survive the RA.
1111  Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1112  Builder.CreateStore(arg, alloc);
1113  localAddr = Builder.CreateLoad(alloc);
1114  }
1115 
1116  if (CGDebugInfo *DI = getDebugInfo()) {
1117  if (CGM.getCodeGenOpts().getDebugInfo() >=
1119  DI->setLocation(D->getLocation());
1120  DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1121  localAddr, Builder);
1122  }
1123  }
1124 
1125  SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1126  ApplyDebugLocation Scope(*this, StartLoc);
1127 
1128  // Instead of messing around with LocalDeclMap, just set the value
1129  // directly as BlockPointer.
1130  BlockPointer = Builder.CreateBitCast(arg,
1131  BlockInfo->StructureType->getPointerTo(),
1132  "block");
1133 }
1134 
1136  assert(BlockInfo && "not in a block invocation function!");
1137  assert(BlockPointer && "no block pointer set!");
1138  return Address(BlockPointer, BlockInfo->BlockAlign);
1139 }
1140 
1141 llvm::Function *
1143  const CGBlockInfo &blockInfo,
1144  const DeclMapTy &ldm,
1145  bool IsLambdaConversionToBlock) {
1146  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1147 
1148  CurGD = GD;
1149 
1150  CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
1151 
1152  BlockInfo = &blockInfo;
1153 
1154  // Arrange for local static and local extern declarations to appear
1155  // to be local to this function as well, in case they're directly
1156  // referenced in a block.
1157  for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1158  const auto *var = dyn_cast<VarDecl>(i->first);
1159  if (var && !var->hasLocalStorage())
1160  setAddrOfLocalVar(var, i->second);
1161  }
1162 
1163  // Begin building the function declaration.
1164 
1165  // Build the argument list.
1166  FunctionArgList args;
1167 
1168  // The first argument is the block pointer. Just take it as a void*
1169  // and cast it later.
1170  QualType selfTy = getContext().VoidPtrTy;
1171  IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1172 
1173  ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1174  SourceLocation(), II, selfTy);
1175  args.push_back(&selfDecl);
1176 
1177  // Now add the rest of the parameters.
1178  args.append(blockDecl->param_begin(), blockDecl->param_end());
1179 
1180  // Create the function declaration.
1181  const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1182  const CGFunctionInfo &fnInfo =
1183  CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1184  if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1185  blockInfo.UsesStret = true;
1186 
1187  llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1188 
1189  StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1190  llvm::Function *fn = llvm::Function::Create(
1191  fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1192  CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1193 
1194  // Begin generating the function.
1195  StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1196  blockDecl->getLocation(),
1197  blockInfo.getBlockExpr()->getBody()->getLocStart());
1198 
1199  // Okay. Undo some of what StartFunction did.
1200 
1201  // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1202  // won't delete the dbg.declare intrinsics for captured variables.
1203  llvm::Value *BlockPointerDbgLoc = BlockPointer;
1204  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1205  // Allocate a stack slot for it, so we can point the debugger to it
1206  Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1207  getPointerAlign(),
1208  "block.addr");
1209  // Set the DebugLocation to empty, so the store is recognized as a
1210  // frame setup instruction by llvm::DwarfDebug::beginFunction().
1211  auto NL = ApplyDebugLocation::CreateEmpty(*this);
1212  Builder.CreateStore(BlockPointer, Alloca);
1213  BlockPointerDbgLoc = Alloca.getPointer();
1214  }
1215 
1216  // If we have a C++ 'this' reference, go ahead and force it into
1217  // existence now.
1218  if (blockDecl->capturesCXXThis()) {
1219  Address addr =
1220  Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1221  blockInfo.CXXThisOffset, "block.captured-this");
1222  CXXThisValue = Builder.CreateLoad(addr, "this");
1223  }
1224 
1225  // Also force all the constant captures.
1226  for (const auto &CI : blockDecl->captures()) {
1227  const VarDecl *variable = CI.getVariable();
1228  const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1229  if (!capture.isConstant()) continue;
1230 
1231  CharUnits align = getContext().getDeclAlign(variable);
1232  Address alloca =
1233  CreateMemTemp(variable->getType(), align, "block.captured-const");
1234 
1235  Builder.CreateStore(capture.getConstant(), alloca);
1236 
1237  setAddrOfLocalVar(variable, alloca);
1238  }
1239 
1240  // Save a spot to insert the debug information for all the DeclRefExprs.
1241  llvm::BasicBlock *entry = Builder.GetInsertBlock();
1242  llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1243  --entry_ptr;
1244 
1245  if (IsLambdaConversionToBlock)
1246  EmitLambdaBlockInvokeBody();
1247  else {
1248  PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1249  incrementProfileCounter(blockDecl->getBody());
1250  EmitStmt(blockDecl->getBody());
1251  }
1252 
1253  // Remember where we were...
1254  llvm::BasicBlock *resume = Builder.GetInsertBlock();
1255 
1256  // Go back to the entry.
1257  ++entry_ptr;
1258  Builder.SetInsertPoint(entry, entry_ptr);
1259 
1260  // Emit debug information for all the DeclRefExprs.
1261  // FIXME: also for 'this'
1262  if (CGDebugInfo *DI = getDebugInfo()) {
1263  for (const auto &CI : blockDecl->captures()) {
1264  const VarDecl *variable = CI.getVariable();
1265  DI->EmitLocation(Builder, variable->getLocation());
1266 
1267  if (CGM.getCodeGenOpts().getDebugInfo() >=
1269  const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1270  if (capture.isConstant()) {
1271  auto addr = LocalDeclMap.find(variable)->second;
1272  DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1273  Builder);
1274  continue;
1275  }
1276 
1277  DI->EmitDeclareOfBlockDeclRefVariable(
1278  variable, BlockPointerDbgLoc, Builder, blockInfo,
1279  entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1280  }
1281  }
1282  // Recover location if it was changed in the above loop.
1283  DI->EmitLocation(Builder,
1284  cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1285  }
1286 
1287  // And resume where we left off.
1288  if (resume == nullptr)
1289  Builder.ClearInsertionPoint();
1290  else
1291  Builder.SetInsertPoint(resume);
1292 
1293  FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1294 
1295  return fn;
1296 }
1297 
1298 /*
1299  notes.push_back(HelperInfo());
1300  HelperInfo &note = notes.back();
1301  note.index = capture.getIndex();
1302  note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1303  note.cxxbar_import = ci->getCopyExpr();
1304 
1305  if (ci->isByRef()) {
1306  note.flag = BLOCK_FIELD_IS_BYREF;
1307  if (type.isObjCGCWeak())
1308  note.flag |= BLOCK_FIELD_IS_WEAK;
1309  } else if (type->isBlockPointerType()) {
1310  note.flag = BLOCK_FIELD_IS_BLOCK;
1311  } else {
1312  note.flag = BLOCK_FIELD_IS_OBJECT;
1313  }
1314  */
1315 
1316 /// Generate the copy-helper function for a block closure object:
1317 /// static void block_copy_helper(block_t *dst, block_t *src);
1318 /// The runtime will have previously initialized 'dst' by doing a
1319 /// bit-copy of 'src'.
1320 ///
1321 /// Note that this copies an entire block closure object to the heap;
1322 /// it should not be confused with a 'byref copy helper', which moves
1323 /// the contents of an individual __block variable to the heap.
1324 llvm::Constant *
1326  ASTContext &C = getContext();
1327 
1328  FunctionArgList args;
1329  ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1330  C.VoidPtrTy);
1331  args.push_back(&dstDecl);
1332  ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1333  C.VoidPtrTy);
1334  args.push_back(&srcDecl);
1335 
1336  const CGFunctionInfo &FI =
1338 
1339  // FIXME: it would be nice if these were mergeable with things with
1340  // identical semantics.
1341  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1342 
1343  llvm::Function *Fn =
1345  "__copy_helper_block_", &CGM.getModule());
1346 
1347  IdentifierInfo *II
1348  = &CGM.getContext().Idents.get("__copy_helper_block_");
1349 
1352  SourceLocation(),
1353  SourceLocation(), II, C.VoidTy,
1354  nullptr, SC_Static,
1355  false,
1356  false);
1357 
1358  CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1359 
1360  auto NL = ApplyDebugLocation::CreateEmpty(*this);
1361  StartFunction(FD, C.VoidTy, Fn, FI, args);
1362  // Create a scope with an artificial location for the body of this function.
1363  auto AL = ApplyDebugLocation::CreateArtificial(*this);
1364  llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1365 
1366  Address src = GetAddrOfLocalVar(&srcDecl);
1367  src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1368  src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1369 
1370  Address dst = GetAddrOfLocalVar(&dstDecl);
1371  dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
1372  dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1373 
1374  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1375 
1376  for (const auto &CI : blockDecl->captures()) {
1377  const VarDecl *variable = CI.getVariable();
1378  QualType type = variable->getType();
1379 
1380  const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1381  if (capture.isConstant()) continue;
1382 
1383  const Expr *copyExpr = CI.getCopyExpr();
1384  BlockFieldFlags flags;
1385 
1386  bool useARCWeakCopy = false;
1387  bool useARCStrongCopy = false;
1388 
1389  if (copyExpr) {
1390  assert(!CI.isByRef());
1391  // don't bother computing flags
1392 
1393  } else if (CI.isByRef()) {
1394  flags = BLOCK_FIELD_IS_BYREF;
1395  if (type.isObjCGCWeak())
1396  flags |= BLOCK_FIELD_IS_WEAK;
1397 
1398  } else if (type->isObjCRetainableType()) {
1399  flags = BLOCK_FIELD_IS_OBJECT;
1400  bool isBlockPointer = type->isBlockPointerType();
1401  if (isBlockPointer)
1402  flags = BLOCK_FIELD_IS_BLOCK;
1403 
1404  // Special rules for ARC captures:
1405  Qualifiers qs = type.getQualifiers();
1406 
1407  // We need to register __weak direct captures with the runtime.
1408  if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1409  useARCWeakCopy = true;
1410 
1411  // We need to retain the copied value for __strong direct captures.
1412  } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1413  // If it's a block pointer, we have to copy the block and
1414  // assign that to the destination pointer, so we might as
1415  // well use _Block_object_assign. Otherwise we can avoid that.
1416  if (!isBlockPointer)
1417  useARCStrongCopy = true;
1418 
1419  // Non-ARC captures of retainable pointers are strong and
1420  // therefore require a call to _Block_object_assign.
1421  } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1422  // fall through
1423 
1424  // Otherwise the memcpy is fine.
1425  } else {
1426  continue;
1427  }
1428 
1429  // For all other types, the memcpy is fine.
1430  } else {
1431  continue;
1432  }
1433 
1434  unsigned index = capture.getIndex();
1435  Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1436  Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
1437 
1438  // If there's an explicit copy expression, we do that.
1439  if (copyExpr) {
1440  EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1441  } else if (useARCWeakCopy) {
1442  EmitARCCopyWeak(dstField, srcField);
1443  } else {
1444  llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1445  if (useARCStrongCopy) {
1446  // At -O0, store null into the destination field (so that the
1447  // storeStrong doesn't over-release) and then call storeStrong.
1448  // This is a workaround to not having an initStrong call.
1449  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1450  auto *ty = cast<llvm::PointerType>(srcValue->getType());
1451  llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1452  Builder.CreateStore(null, dstField);
1453  EmitARCStoreStrongCall(dstField, srcValue, true);
1454 
1455  // With optimization enabled, take advantage of the fact that
1456  // the blocks runtime guarantees a memcpy of the block data, and
1457  // just emit a retain of the src field.
1458  } else {
1459  EmitARCRetainNonBlock(srcValue);
1460 
1461  // We don't need this anymore, so kill it. It's not quite
1462  // worth the annoyance to avoid creating it in the first place.
1463  cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
1464  }
1465  } else {
1466  srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1467  llvm::Value *dstAddr =
1468  Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
1469  llvm::Value *args[] = {
1470  dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1471  };
1472 
1473  bool copyCanThrow = false;
1474  if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1475  const Expr *copyExpr =
1476  CGM.getContext().getBlockVarCopyInits(variable);
1477  if (copyExpr) {
1478  copyCanThrow = true; // FIXME: reuse the noexcept logic
1479  }
1480  }
1481 
1482  if (copyCanThrow) {
1483  EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1484  } else {
1485  EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1486  }
1487  }
1488  }
1489  }
1490 
1491  FinishFunction();
1492 
1493  return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1494 }
1495 
1496 /// Generate the destroy-helper function for a block closure object:
1497 /// static void block_destroy_helper(block_t *theBlock);
1498 ///
1499 /// Note that this destroys a heap-allocated block closure object;
1500 /// it should not be confused with a 'byref destroy helper', which
1501 /// destroys the heap-allocated contents of an individual __block
1502 /// variable.
1503 llvm::Constant *
1505  ASTContext &C = getContext();
1506 
1507  FunctionArgList args;
1508  ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1509  C.VoidPtrTy);
1510  args.push_back(&srcDecl);
1511 
1512  const CGFunctionInfo &FI =
1514 
1515  // FIXME: We'd like to put these into a mergable by content, with
1516  // internal linkage.
1517  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1518 
1519  llvm::Function *Fn =
1521  "__destroy_helper_block_", &CGM.getModule());
1522 
1523  IdentifierInfo *II
1524  = &CGM.getContext().Idents.get("__destroy_helper_block_");
1525 
1527  SourceLocation(),
1528  SourceLocation(), II, C.VoidTy,
1529  nullptr, SC_Static,
1530  false, false);
1531 
1532  CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1533 
1534  // Create a scope with an artificial location for the body of this function.
1535  auto NL = ApplyDebugLocation::CreateEmpty(*this);
1536  StartFunction(FD, C.VoidTy, Fn, FI, args);
1537  auto AL = ApplyDebugLocation::CreateArtificial(*this);
1538 
1539  llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1540 
1541  Address src = GetAddrOfLocalVar(&srcDecl);
1542  src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1543  src = Builder.CreateBitCast(src, structPtrTy, "block");
1544 
1545  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1546 
1547  CodeGenFunction::RunCleanupsScope cleanups(*this);
1548 
1549  for (const auto &CI : blockDecl->captures()) {
1550  const VarDecl *variable = CI.getVariable();
1551  QualType type = variable->getType();
1552 
1553  const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1554  if (capture.isConstant()) continue;
1555 
1556  BlockFieldFlags flags;
1557  const CXXDestructorDecl *dtor = nullptr;
1558 
1559  bool useARCWeakDestroy = false;
1560  bool useARCStrongDestroy = false;
1561 
1562  if (CI.isByRef()) {
1563  flags = BLOCK_FIELD_IS_BYREF;
1564  if (type.isObjCGCWeak())
1565  flags |= BLOCK_FIELD_IS_WEAK;
1566  } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1567  if (record->hasTrivialDestructor())
1568  continue;
1569  dtor = record->getDestructor();
1570  } else if (type->isObjCRetainableType()) {
1571  flags = BLOCK_FIELD_IS_OBJECT;
1572  if (type->isBlockPointerType())
1573  flags = BLOCK_FIELD_IS_BLOCK;
1574 
1575  // Special rules for ARC captures.
1576  Qualifiers qs = type.getQualifiers();
1577 
1578  // Use objc_storeStrong for __strong direct captures; the
1579  // dynamic tools really like it when we do this.
1581  useARCStrongDestroy = true;
1582 
1583  // Support __weak direct captures.
1584  } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1585  useARCWeakDestroy = true;
1586 
1587  // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1588  } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1589  // fall through
1590 
1591  // Otherwise, we have nothing to do.
1592  } else {
1593  continue;
1594  }
1595  } else {
1596  continue;
1597  }
1598 
1599  Address srcField =
1600  Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
1601 
1602  // If there's an explicit copy expression, we do that.
1603  if (dtor) {
1604  PushDestructorCleanup(dtor, srcField);
1605 
1606  // If this is a __weak capture, emit the release directly.
1607  } else if (useARCWeakDestroy) {
1608  EmitARCDestroyWeak(srcField);
1609 
1610  // Destroy strong objects with a call if requested.
1611  } else if (useARCStrongDestroy) {
1612  EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1613 
1614  // Otherwise we call _Block_object_dispose. It wouldn't be too
1615  // hard to just emit this as a cleanup if we wanted to make sure
1616  // that things were done in reverse.
1617  } else {
1618  llvm::Value *value = Builder.CreateLoad(srcField);
1619  value = Builder.CreateBitCast(value, VoidPtrTy);
1620  BuildBlockRelease(value, flags);
1621  }
1622  }
1623 
1624  cleanups.ForceCleanup();
1625 
1626  FinishFunction();
1627 
1628  return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1629 }
1630 
1631 namespace {
1632 
1633 /// Emits the copy/dispose helper functions for a __block object of id type.
1634 class ObjectByrefHelpers final : public BlockByrefHelpers {
1635  BlockFieldFlags Flags;
1636 
1637 public:
1638  ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1639  : BlockByrefHelpers(alignment), Flags(flags) {}
1640 
1641  void emitCopy(CodeGenFunction &CGF, Address destField,
1642  Address srcField) override {
1643  destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1644 
1645  srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1646  llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1647 
1648  unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1649 
1650  llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1651  llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1652 
1653  llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
1654  CGF.EmitNounwindRuntimeCall(fn, args);
1655  }
1656 
1657  void emitDispose(CodeGenFunction &CGF, Address field) override {
1658  field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1659  llvm::Value *value = CGF.Builder.CreateLoad(field);
1660 
1661  CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1662  }
1663 
1664  void profileImpl(llvm::FoldingSetNodeID &id) const override {
1665  id.AddInteger(Flags.getBitMask());
1666  }
1667 };
1668 
1669 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1670 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
1671 public:
1672  ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1673 
1674  void emitCopy(CodeGenFunction &CGF, Address destField,
1675  Address srcField) override {
1676  CGF.EmitARCMoveWeak(destField, srcField);
1677  }
1678 
1679  void emitDispose(CodeGenFunction &CGF, Address field) override {
1680  CGF.EmitARCDestroyWeak(field);
1681  }
1682 
1683  void profileImpl(llvm::FoldingSetNodeID &id) const override {
1684  // 0 is distinguishable from all pointers and byref flags
1685  id.AddInteger(0);
1686  }
1687 };
1688 
1689 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1690 /// that's not of block-pointer type.
1691 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
1692 public:
1693  ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1694 
1695  void emitCopy(CodeGenFunction &CGF, Address destField,
1696  Address srcField) override {
1697  // Do a "move" by copying the value and then zeroing out the old
1698  // variable.
1699 
1700  llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1701 
1702  llvm::Value *null =
1703  llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1704 
1705  if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1706  CGF.Builder.CreateStore(null, destField);
1707  CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1708  CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1709  return;
1710  }
1711  CGF.Builder.CreateStore(value, destField);
1712  CGF.Builder.CreateStore(null, srcField);
1713  }
1714 
1715  void emitDispose(CodeGenFunction &CGF, Address field) override {
1717  }
1718 
1719  void profileImpl(llvm::FoldingSetNodeID &id) const override {
1720  // 1 is distinguishable from all pointers and byref flags
1721  id.AddInteger(1);
1722  }
1723 };
1724 
1725 /// Emits the copy/dispose helpers for an ARC __block __strong
1726 /// variable that's of block-pointer type.
1727 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
1728 public:
1729  ARCStrongBlockByrefHelpers(CharUnits alignment)
1730  : BlockByrefHelpers(alignment) {}
1731 
1732  void emitCopy(CodeGenFunction &CGF, Address destField,
1733  Address srcField) override {
1734  // Do the copy with objc_retainBlock; that's all that
1735  // _Block_object_assign would do anyway, and we'd have to pass the
1736  // right arguments to make sure it doesn't get no-op'ed.
1737  llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
1738  llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1739  CGF.Builder.CreateStore(copy, destField);
1740  }
1741 
1742  void emitDispose(CodeGenFunction &CGF, Address field) override {
1744  }
1745 
1746  void profileImpl(llvm::FoldingSetNodeID &id) const override {
1747  // 2 is distinguishable from all pointers and byref flags
1748  id.AddInteger(2);
1749  }
1750 };
1751 
1752 /// Emits the copy/dispose helpers for a __block variable with a
1753 /// nontrivial copy constructor or destructor.
1754 class CXXByrefHelpers final : public BlockByrefHelpers {
1755  QualType VarType;
1756  const Expr *CopyExpr;
1757 
1758 public:
1759  CXXByrefHelpers(CharUnits alignment, QualType type,
1760  const Expr *copyExpr)
1761  : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1762 
1763  bool needsCopy() const override { return CopyExpr != nullptr; }
1764  void emitCopy(CodeGenFunction &CGF, Address destField,
1765  Address srcField) override {
1766  if (!CopyExpr) return;
1767  CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1768  }
1769 
1770  void emitDispose(CodeGenFunction &CGF, Address field) override {
1771  EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1772  CGF.PushDestructorCleanup(VarType, field);
1773  CGF.PopCleanupBlocks(cleanupDepth);
1774  }
1775 
1776  void profileImpl(llvm::FoldingSetNodeID &id) const override {
1777  id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1778  }
1779 };
1780 } // end anonymous namespace
1781 
1782 static llvm::Constant *
1784  BlockByrefHelpers &generator) {
1785  ASTContext &Context = CGF.getContext();
1786 
1787  QualType R = Context.VoidTy;
1788 
1789  FunctionArgList args;
1790  ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1791  Context.VoidPtrTy);
1792  args.push_back(&dst);
1793 
1794  ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1795  Context.VoidPtrTy);
1796  args.push_back(&src);
1797 
1798  const CGFunctionInfo &FI =
1800 
1801  llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1802 
1803  // FIXME: We'd like to put these into a mergable by content, with
1804  // internal linkage.
1805  llvm::Function *Fn =
1807  "__Block_byref_object_copy_", &CGF.CGM.getModule());
1808 
1809  IdentifierInfo *II
1810  = &Context.Idents.get("__Block_byref_object_copy_");
1811 
1812  FunctionDecl *FD = FunctionDecl::Create(Context,
1813  Context.getTranslationUnitDecl(),
1814  SourceLocation(),
1815  SourceLocation(), II, R, nullptr,
1816  SC_Static,
1817  false, false);
1818 
1819  CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1820 
1821  CGF.StartFunction(FD, R, Fn, FI, args);
1822 
1823  if (generator.needsCopy()) {
1824  llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
1825 
1826  // dst->x
1827  Address destField = CGF.GetAddrOfLocalVar(&dst);
1828  destField = Address(CGF.Builder.CreateLoad(destField),
1829  byrefInfo.ByrefAlignment);
1830  destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1831  destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1832  "dest-object");
1833 
1834  // src->x
1835  Address srcField = CGF.GetAddrOfLocalVar(&src);
1836  srcField = Address(CGF.Builder.CreateLoad(srcField),
1837  byrefInfo.ByrefAlignment);
1838  srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1839  srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1840  "src-object");
1841 
1842  generator.emitCopy(CGF, destField, srcField);
1843  }
1844 
1845  CGF.FinishFunction();
1846 
1847  return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1848 }
1849 
1850 /// Build the copy helper for a __block variable.
1851 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1852  const BlockByrefInfo &byrefInfo,
1853  BlockByrefHelpers &generator) {
1854  CodeGenFunction CGF(CGM);
1855  return generateByrefCopyHelper(CGF, byrefInfo, generator);
1856 }
1857 
1858 /// Generate code for a __block variable's dispose helper.
1859 static llvm::Constant *
1861  const BlockByrefInfo &byrefInfo,
1862  BlockByrefHelpers &generator) {
1863  ASTContext &Context = CGF.getContext();
1864  QualType R = Context.VoidTy;
1865 
1866  FunctionArgList args;
1867  ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1868  Context.VoidPtrTy);
1869  args.push_back(&src);
1870 
1871  const CGFunctionInfo &FI =
1873 
1874  llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1875 
1876  // FIXME: We'd like to put these into a mergable by content, with
1877  // internal linkage.
1878  llvm::Function *Fn =
1880  "__Block_byref_object_dispose_",
1881  &CGF.CGM.getModule());
1882 
1883  IdentifierInfo *II
1884  = &Context.Idents.get("__Block_byref_object_dispose_");
1885 
1886  FunctionDecl *FD = FunctionDecl::Create(Context,
1887  Context.getTranslationUnitDecl(),
1888  SourceLocation(),
1889  SourceLocation(), II, R, nullptr,
1890  SC_Static,
1891  false, false);
1892 
1893  CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1894 
1895  CGF.StartFunction(FD, R, Fn, FI, args);
1896 
1897  if (generator.needsDispose()) {
1898  Address addr = CGF.GetAddrOfLocalVar(&src);
1899  addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1900  auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1901  addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1902  addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
1903 
1904  generator.emitDispose(CGF, addr);
1905  }
1906 
1907  CGF.FinishFunction();
1908 
1909  return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1910 }
1911 
1912 /// Build the dispose helper for a __block variable.
1913 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1914  const BlockByrefInfo &byrefInfo,
1915  BlockByrefHelpers &generator) {
1916  CodeGenFunction CGF(CGM);
1917  return generateByrefDisposeHelper(CGF, byrefInfo, generator);
1918 }
1919 
1920 /// Lazily build the copy and dispose helpers for a __block variable
1921 /// with the given information.
1922 template <class T>
1923 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1924  T &&generator) {
1925  llvm::FoldingSetNodeID id;
1926  generator.Profile(id);
1927 
1928  void *insertPos;
1929  BlockByrefHelpers *node
1930  = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1931  if (node) return static_cast<T*>(node);
1932 
1933  generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1934  generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
1935 
1936  T *copy = new (CGM.getContext()) T(std::move(generator));
1937  CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1938  return copy;
1939 }
1940 
1941 /// Build the copy and dispose helpers for the given __block variable
1942 /// emission. Places the helpers in the global cache. Returns null
1943 /// if no helpers are required.
1945 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1946  const AutoVarEmission &emission) {
1947  const VarDecl &var = *emission.Variable;
1948  QualType type = var.getType();
1949 
1950  auto &byrefInfo = getBlockByrefInfo(&var);
1951 
1952  // The alignment we care about for the purposes of uniquing byref
1953  // helpers is the alignment of the actual byref value field.
1954  CharUnits valueAlignment =
1955  byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
1956 
1957  if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1958  const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1959  if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1960 
1962  CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
1963  }
1964 
1965  // Otherwise, if we don't have a retainable type, there's nothing to do.
1966  // that the runtime does extra copies.
1967  if (!type->isObjCRetainableType()) return nullptr;
1968 
1969  Qualifiers qs = type.getQualifiers();
1970 
1971  // If we have lifetime, that dominates.
1972  if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1973  switch (lifetime) {
1974  case Qualifiers::OCL_None: llvm_unreachable("impossible");
1975 
1976  // These are just bits as far as the runtime is concerned.
1979  return nullptr;
1980 
1981  // Tell the runtime that this is ARC __weak, called by the
1982  // byref routines.
1983  case Qualifiers::OCL_Weak:
1984  return ::buildByrefHelpers(CGM, byrefInfo,
1985  ARCWeakByrefHelpers(valueAlignment));
1986 
1987  // ARC __strong __block variables need to be retained.
1989  // Block pointers need to be copied, and there's no direct
1990  // transfer possible.
1991  if (type->isBlockPointerType()) {
1992  return ::buildByrefHelpers(CGM, byrefInfo,
1993  ARCStrongBlockByrefHelpers(valueAlignment));
1994 
1995  // Otherwise, we transfer ownership of the retain from the stack
1996  // to the heap.
1997  } else {
1998  return ::buildByrefHelpers(CGM, byrefInfo,
1999  ARCStrongByrefHelpers(valueAlignment));
2000  }
2001  }
2002  llvm_unreachable("fell out of lifetime switch!");
2003  }
2004 
2005  BlockFieldFlags flags;
2006  if (type->isBlockPointerType()) {
2007  flags |= BLOCK_FIELD_IS_BLOCK;
2008  } else if (CGM.getContext().isObjCNSObjectType(type) ||
2009  type->isObjCObjectPointerType()) {
2010  flags |= BLOCK_FIELD_IS_OBJECT;
2011  } else {
2012  return nullptr;
2013  }
2014 
2015  if (type.isObjCGCWeak())
2016  flags |= BLOCK_FIELD_IS_WEAK;
2017 
2018  return ::buildByrefHelpers(CGM, byrefInfo,
2019  ObjectByrefHelpers(valueAlignment, flags));
2020 }
2021 
2023  const VarDecl *var,
2024  bool followForward) {
2025  auto &info = getBlockByrefInfo(var);
2026  return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2027 }
2028 
2030  const BlockByrefInfo &info,
2031  bool followForward,
2032  const llvm::Twine &name) {
2033  // Chase the forwarding address if requested.
2034  if (followForward) {
2035  Address forwardingAddr =
2036  Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2037  baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2038  }
2039 
2040  return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2041  info.FieldOffset, name);
2042 }
2043 
2044 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2045 /// into:
2046 ///
2047 /// struct {
2048 /// void *__isa;
2049 /// void *__forwarding;
2050 /// int32_t __flags;
2051 /// int32_t __size;
2052 /// void *__copy_helper; // only if needed
2053 /// void *__destroy_helper; // only if needed
2054 /// void *__byref_variable_layout;// only if needed
2055 /// char padding[X]; // only if needed
2056 /// T x;
2057 /// } x
2058 ///
2060  auto it = BlockByrefInfos.find(D);
2061  if (it != BlockByrefInfos.end())
2062  return it->second;
2063 
2064  llvm::StructType *byrefType =
2065  llvm::StructType::create(getLLVMContext(),
2066  "struct.__block_byref_" + D->getNameAsString());
2067 
2068  QualType Ty = D->getType();
2069 
2070  CharUnits size;
2072 
2073  // void *__isa;
2074  types.push_back(Int8PtrTy);
2075  size += getPointerSize();
2076 
2077  // void *__forwarding;
2078  types.push_back(llvm::PointerType::getUnqual(byrefType));
2079  size += getPointerSize();
2080 
2081  // int32_t __flags;
2082  types.push_back(Int32Ty);
2083  size += CharUnits::fromQuantity(4);
2084 
2085  // int32_t __size;
2086  types.push_back(Int32Ty);
2087  size += CharUnits::fromQuantity(4);
2088 
2089  // Note that this must match *exactly* the logic in buildByrefHelpers.
2090  bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2091  if (hasCopyAndDispose) {
2092  /// void *__copy_helper;
2093  types.push_back(Int8PtrTy);
2094  size += getPointerSize();
2095 
2096  /// void *__destroy_helper;
2097  types.push_back(Int8PtrTy);
2098  size += getPointerSize();
2099  }
2100 
2101  bool HasByrefExtendedLayout = false;
2102  Qualifiers::ObjCLifetime Lifetime;
2103  if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2104  HasByrefExtendedLayout) {
2105  /// void *__byref_variable_layout;
2106  types.push_back(Int8PtrTy);
2107  size += CharUnits::fromQuantity(PointerSizeInBytes);
2108  }
2109 
2110  // T x;
2111  llvm::Type *varTy = ConvertTypeForMem(Ty);
2112 
2113  bool packed = false;
2114  CharUnits varAlign = getContext().getDeclAlign(D);
2115  CharUnits varOffset = size.alignTo(varAlign);
2116 
2117  // We may have to insert padding.
2118  if (varOffset != size) {
2119  llvm::Type *paddingTy =
2120  llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2121 
2122  types.push_back(paddingTy);
2123  size = varOffset;
2124 
2125  // Conversely, we might have to prevent LLVM from inserting padding.
2126  } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2127  > varAlign.getQuantity()) {
2128  packed = true;
2129  }
2130  types.push_back(varTy);
2131 
2132  byrefType->setBody(types, packed);
2133 
2134  BlockByrefInfo info;
2135  info.Type = byrefType;
2136  info.FieldIndex = types.size() - 1;
2137  info.FieldOffset = varOffset;
2138  info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2139 
2140  auto pair = BlockByrefInfos.insert({D, info});
2141  assert(pair.second && "info was inserted recursively?");
2142  return pair.first->second;
2143 }
2144 
2145 /// Initialize the structural components of a __block variable, i.e.
2146 /// everything but the actual object.
2148  // Find the address of the local.
2149  Address addr = emission.Addr;
2150 
2151  // That's an alloca of the byref structure type.
2152  llvm::StructType *byrefType = cast<llvm::StructType>(
2153  cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2154 
2155  unsigned nextHeaderIndex = 0;
2156  CharUnits nextHeaderOffset;
2157  auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2158  const Twine &name) {
2159  auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2160  nextHeaderOffset, name);
2161  Builder.CreateStore(value, fieldAddr);
2162 
2163  nextHeaderIndex++;
2164  nextHeaderOffset += fieldSize;
2165  };
2166 
2167  // Build the byref helpers if necessary. This is null if we don't need any.
2168  BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2169 
2170  const VarDecl &D = *emission.Variable;
2171  QualType type = D.getType();
2172 
2173  bool HasByrefExtendedLayout;
2174  Qualifiers::ObjCLifetime ByrefLifetime;
2175  bool ByRefHasLifetime =
2176  getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2177 
2178  llvm::Value *V;
2179 
2180  // Initialize the 'isa', which is just 0 or 1.
2181  int isa = 0;
2182  if (type.isObjCGCWeak())
2183  isa = 1;
2184  V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2185  storeHeaderField(V, getPointerSize(), "byref.isa");
2186 
2187  // Store the address of the variable into its own forwarding pointer.
2188  storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2189 
2190  // Blocks ABI:
2191  // c) the flags field is set to either 0 if no helper functions are
2192  // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2193  BlockFlags flags;
2194  if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2195  if (ByRefHasLifetime) {
2196  if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2197  else switch (ByrefLifetime) {
2199  flags |= BLOCK_BYREF_LAYOUT_STRONG;
2200  break;
2201  case Qualifiers::OCL_Weak:
2202  flags |= BLOCK_BYREF_LAYOUT_WEAK;
2203  break;
2206  break;
2207  case Qualifiers::OCL_None:
2208  if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2210  break;
2211  default:
2212  break;
2213  }
2214  if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2215  printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2216  if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2217  printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2218  if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2219  BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2220  if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2221  printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2222  if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2223  printf(" BLOCK_BYREF_LAYOUT_STRONG");
2224  if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2225  printf(" BLOCK_BYREF_LAYOUT_WEAK");
2226  if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2227  printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2228  if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2229  printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2230  }
2231  printf("\n");
2232  }
2233  }
2234  storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2235  getIntSize(), "byref.flags");
2236 
2237  CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2238  V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2239  storeHeaderField(V, getIntSize(), "byref.size");
2240 
2241  if (helpers) {
2242  storeHeaderField(helpers->CopyHelper, getPointerSize(),
2243  "byref.copyHelper");
2244  storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2245  "byref.disposeHelper");
2246  }
2247 
2248  if (ByRefHasLifetime && HasByrefExtendedLayout) {
2249  auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2250  storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2251  }
2252 }
2253 
2256  llvm::Value *args[] = {
2257  Builder.CreateBitCast(V, Int8PtrTy),
2258  llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2259  };
2260  EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2261 }
2262 
2263 namespace {
2264  /// Release a __block variable.
2265  struct CallBlockRelease final : EHScopeStack::Cleanup {
2266  llvm::Value *Addr;
2267  CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2268 
2269  void Emit(CodeGenFunction &CGF, Flags flags) override {
2270  // Should we be passing FIELD_IS_WEAK here?
2272  }
2273  };
2274 } // end anonymous namespace
2275 
2276 /// Enter a cleanup to destroy a __block variable. Note that this
2277 /// cleanup should be a no-op if the variable hasn't left the stack
2278 /// yet; if a cleanup is required for the variable itself, that needs
2279 /// to be done externally.
2281  // We don't enter this cleanup if we're in pure-GC mode.
2282  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2283  return;
2284 
2285  EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2286  emission.Addr.getPointer());
2287 }
2288 
2289 /// Adjust the declaration of something from the blocks API.
2291  llvm::Constant *C) {
2292  if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
2293 
2294  auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2295  if (GV->isDeclaration() && GV->hasExternalLinkage())
2296  GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2297 }
2298 
2300  if (BlockObjectDispose)
2301  return BlockObjectDispose;
2302 
2303  llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2304  llvm::FunctionType *fty
2305  = llvm::FunctionType::get(VoidTy, args, false);
2306  BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2307  configureBlocksRuntimeObject(*this, BlockObjectDispose);
2308  return BlockObjectDispose;
2309 }
2310 
2312  if (BlockObjectAssign)
2313  return BlockObjectAssign;
2314 
2315  llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2316  llvm::FunctionType *fty
2317  = llvm::FunctionType::get(VoidTy, args, false);
2318  BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2319  configureBlocksRuntimeObject(*this, BlockObjectAssign);
2320  return BlockObjectAssign;
2321 }
2322 
2324  if (NSConcreteGlobalBlock)
2325  return NSConcreteGlobalBlock;
2326 
2327  NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2328  Int8PtrTy->getPointerTo(),
2329  nullptr);
2330  configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2331  return NSConcreteGlobalBlock;
2332 }
2333 
2335  if (NSConcreteStackBlock)
2336  return NSConcreteStackBlock;
2337 
2338  NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2339  Int8PtrTy->getPointerTo(),
2340  nullptr);
2341  configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2342  return NSConcreteStackBlock;
2343 }
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:578
void enterNonTrivialFullExpression(const ExprWithCleanups *E)
Enter a full-expression with a non-trivial number of objects to clean up.
Definition: CGBlocks.cpp:637
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:151
Information about the layout of a __block variable.
Definition: CGBlocks.h:144
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:1325
static llvm::Constant * generateByrefDisposeHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo, BlockByrefHelpers &generator)
Generate code for a __block variable&#39;s dispose helper.
Definition: CGBlocks.cpp:1860
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1539
CK_LValueToRValue - A conversion which causes the extraction of an r-value from the operand gl-value...
llvm::IntegerType * IntTy
int
llvm::Type * getGenericBlockLiteralType()
The type of a generic block literal.
Definition: CGBlocks.cpp:936
const CGFunctionInfo & arrangeBlockFunctionDeclaration(const FunctionProtoType *type, const FunctionArgList &args)
Block invocation functions are C functions with an implicit parameter.
Definition: CGCall.cpp:553
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:237
CharUnits BlockHeaderForcedGapOffset
Definition: CGBlocks.h:239
tooling::Replacements cleanup(const FormatStyle &Style, SourceManager &SourceMgr, FileID ID, ArrayRef< CharSourceRange > Ranges)
Clean up any erroneous/redundant code in the given Ranges in the file ID.
Definition: Format.cpp:2193
static llvm::Constant * buildByrefDisposeHelper(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo, BlockByrefHelpers &generator)
Build the dispose helper for a __block variable.
Definition: CGBlocks.cpp:1913
A class which contains all the information about a particular captured value.
Definition: Decl.h:3435
CanQualType VoidPtrTy
Definition: ASTContext.h:899
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition: CGDecl.cpp:1426
A (possibly-)qualified type.
Definition: Type.h:575
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1009
llvm::Module & getModule() const
llvm::LLVMContext & getLLVMContext()
void EmitARCDestroyWeak(Address addr)
void @objc_destroyWeak(i8** addr) Essentially objc_storeWeak(addr, nil).
Definition: CGObjC.cpp:2248
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2848
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:1923
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateTempAlloca - This creates a alloca and inserts it into the entry block.
Definition: CGExpr.cpp:67
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
param_iterator param_end()
Definition: Decl.h:3533
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
static llvm::Constant * buildBlockDescriptor(CodeGenModule &CGM, const CGBlockInfo &blockInfo)
buildBlockDescriptor - Build the block descriptor meta-data for a block.
Definition: CGBlocks.cpp:76
const llvm::DataLayout & getDataLayout() const
const Expr * getInit() const
Definition: Decl.h:1135
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
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
bool isBlockPointerType() const
Definition: Type.h:5448
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
uint32_t getBitMask() const
Definition: CGBlocks.h:121
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:767
CGBlockInfo(const BlockDecl *blockDecl, StringRef Name)
Definition: CGBlocks.cpp:30
bool capturesCXXThis() const
Definition: Decl.h:3583
const Expr * getCallee() const
Definition: Expr.h:2184
ObjCLifetime getObjCLifetime() const
Definition: Type.h:290
bool hasCaptures() const
hasCaptures - True if this block (or its nested blocks) captures anything of local storage from its e...
Definition: Decl.h:3560
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2025
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:52
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
virtual llvm::Constant * BuildRCBlockLayout(CodeGen::CodeGenModule &CGM, const CodeGen::CGBlockInfo &blockInfo)=0
capture_range captures()
Definition: Decl.h:3571
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
capture_iterator capture_begin()
Definition: Decl.h:3578
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:2854
bool isObjCRetainableType() const
Definition: Type.cpp:3692
static void destroyBlockInfos(CGBlockInfo *info)
Destroy a chain of block layouts.
Definition: CGBlocks.cpp:664
The collection of all-type qualifiers we support.
Definition: Type.h:116
llvm::Constant * getPointer() const
Definition: Address.h:84
One of these records is kept for each identifier that is lexed.
void emitByrefStructureInit(const AutoVarEmission &emission)
Initialize the structural components of a __block variable, i.e.
Definition: CGBlocks.cpp:2147
CGBlockInfo * FirstBlockInfo
FirstBlockInfo - The head of a singly-linked-list of block layouts.
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:92
bool HasCapturedVariableLayout
HasCapturedVariableLayout : True if block has captured variables and their layout meta-data has been ...
Definition: CGBlocks.h:223
bool isReferenceType() const
Definition: Type.h:5451
const Stmt * getBody() const
Definition: Expr.cpp:2034
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:1783
static bool isSafeForCXXConstantCapture(QualType type)
Determines if the given type is safe for constant capture in C++.
Definition: CGBlocks.cpp:238
IdentifierTable & Idents
Definition: ASTContext.h:455
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:104
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:565
const Capture & getCapture(const VarDecl *var) const
Definition: CGBlocks.h:254
llvm::Value * EmitARCStoreStrongCall(Address addr, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition: CGObjC.cpp:2086
Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef)
Definition: CGBlocks.cpp:1004
const LangOptions & getLangOpts() const
Definition: ASTContext.h:600
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:3511
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:2072
static Capture makeIndex(unsigned index, CharUnits offset)
Definition: CGBlocks.h:192
QualType getReturnType() const
Definition: Type.h:2978
bool HasCXXObject
HasCXXObject - True if the block&#39;s custom copy/dispose functions need to be run even in GC mode...
Definition: CGBlocks.h:215
llvm::Value * EmitBlockLiteral(const BlockExpr *)
Emit a block literal expression in the current function.
Definition: CGBlocks.cpp:674
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind...
RecordDecl * getDecl() const
Definition: Type.h:3685
std::string getNameAsString() const
getNameAsString - Get a human-readable name for the declaration, even if it is one of the special kin...
Definition: Decl.h:252
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
static Capture makeConstant(llvm::Value *value)
Definition: CGBlocks.h:199
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
bool isValid() const
Definition: Address.h:36
llvm::Constant * getNSConcreteStackBlock()
Definition: CGBlocks.cpp:2334
std::pair< CharUnits, CharUnits > getTypeInfoInChars(const Type *T) const
QualType getType() const
Definition: Decl.h:598
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:1698
This object can be modified without requiring retains or releases.
Definition: Type.h:137
bool NeedsCopyDispose
True if the block needs a custom copy or dispose function.
Definition: CGBlocks.h:211
const BlockExpr * BlockExpression
Definition: CGBlocks.h:231
static llvm::Constant * buildCopyHelper(CodeGenModule &CGM, const CGBlockInfo &blockInfo)
Build the helper function to copy a block.
Definition: CGBlocks.cpp:51
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3042
bool isConversionFromLambda() const
Definition: Decl.h:3587
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
llvm::Function * GenerateBlockFunction(GlobalDecl GD, const CGBlockInfo &Info, const DeclMapTy &ldm, bool IsLambdaConversionToBlock)
Definition: CGBlocks.cpp:1142
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:986
CGBlockInfo - Information to generate a block literal.
Definition: CGBlocks.h:153
virtual void emitCopy(CodeGenFunction &CGF, Address dest, Address src)=0
unsigned getNumObjects() const
Definition: ExprCXX.h:2885
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:38
bool CanBeGlobal
CanBeGlobal - True if the block can be global, i.e.
Definition: CGBlocks.h:208
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Expr.h:4618
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
capture_iterator capture_end()
Definition: Decl.h:3579
bool isObjCInertUnsafeUnretainedType() const
Was this type written with the special inert-in-MRC __unsafe_unretained qualifier?
Definition: Type.cpp:519
CGBlockInfo * NextBlockInfo
The next block in the block-info chain.
Definition: CGBlocks.h:252
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
llvm::Value * getPointer() const
Definition: Address.h:38
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
Definition: Decl.h:3431
QualType getPointeeType() const
Definition: Type.h:2269
Expr - This represents one expression.
Definition: Expr.h:105
virtual bool needsCopy() const
void EmitARCMoveWeak(Address dst, Address src)
void @objc_moveWeak(i8** dest, i8** src) Disregards the current value in dest.
Definition: CGObjC.cpp:2265
Emit only debug info necessary for generating line number tables (-gline-tables-only).
static Address invalid()
Definition: Address.h:35
VarDecl * getVariable() const
The variable being captured.
Definition: Decl.h:3456
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
void SetInternalFunctionAttributes(const Decl *D, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:4594
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2376
static llvm::Constant * buildGlobalBlock(CodeGenModule &CGM, const CGBlockInfo &blockInfo, llvm::Constant *blockFn)
Build the given block as a global block.
Definition: CGBlocks.cpp:1060
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:1504
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:879
bool isObjCGCWeak() const
true when Type is objc&#39;s weak.
Definition: Type.h:976
ASTContext & getContext() const
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:115
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:81
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:376
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:1406
bool isa(CodeGen::Address addr)
Definition: Address.h:112
static CharUnits getLowBit(CharUnits v)
Get the low bit of a nonzero character count.
Definition: CGBlocks.cpp:294
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, IsZeroed_t isZeroed=IsNotZeroed)
forAddr - Make a slot for an aggregate value.
Definition: CGValue.h:502
do v
Definition: arm_acle.h:78
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:29
EHScopeStack::stable_iterator getCleanup() const
Definition: CGBlocks.h:178
virtual llvm::Constant * BuildByrefLayout(CodeGen::CodeGenModule &CGM, QualType T)=0
Returns an i8* which points to the byref layout information.
bool hasObjCLifetime() const
Definition: Type.h:289
param_iterator param_begin()
Definition: Decl.h:3532
The l-value was considered opaque, so the alignment was determined from a type.
void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum, llvm::Value *ptr)
Definition: CGBlocks.cpp:1103
bool UsesStret
UsesStret : True if the block uses an stret return.
Definition: CGBlocks.h:219
void enterByrefCleanup(const AutoVarEmission &emission)
Enter a cleanup to destroy a __block variable.
Definition: CGBlocks.cpp:2280
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
There is no lifetime qualification on this type.
Definition: Type.h:133
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:160
ArrayRef< CleanupObject > getObjects() const
Definition: ExprCXX.h:2880
#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:144
Expr * getBlockVarCopyInits(const VarDecl *VD)
Get the copy initialization expression of the VarDecl VD, or NULL if none exists. ...
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:2297
ASTContext & getContext() const
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:1451
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
A saved depth on the scope stack.
Definition: EHScopeStack.h:104
llvm::StructType * StructureType
Definition: CGBlocks.h:229
static void configureBlocksRuntimeObject(CodeGenModule &CGM, llvm::Constant *C)
Adjust the declaration of something from the blocks API.
Definition: CGBlocks.cpp:2290
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.
An aggregate value slot.
Definition: CGValue.h:441
const BlockByrefInfo & getBlockByrefInfo(const VarDecl *var)
BuildByrefInfo - This routine changes a __block variable declared as T x into:
Definition: CGBlocks.cpp:2059
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:534
CanQualType VoidTy
Definition: ASTContext.h:885
llvm::DenseMap< const VarDecl *, Capture > Captures
The mapping of allocated indexes within the block.
Definition: CGBlocks.h:226
const CodeGenOptions & getCodeGenOpts() const
arg_range arguments()
Definition: Expr.h:2238
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:5734
llvm::Constant * getBlockObjectDispose()
Definition: CGBlocks.cpp:2299
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.
const LangOptions & getLangOpts() const
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2726
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5800
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
virtual bool needsDispose() const
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:150
const BlockDecl * getBlockDecl() const
Definition: Expr.h:4608
static Destroyer destroyARCStrongImprecise
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
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:546
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...
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:146
static llvm::Constant * tryCaptureAsConstant(CodeGenModule &CGM, CodeGenFunction *CGF, const VarDecl *var)
It is illegal to modify a const object after initialization.
Definition: CGBlocks.cpp:262
QualType getType() const
Definition: Expr.h:126
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
const unsigned BlockHeaderSize
The number of fields in a block header.
Definition: CGBlocks.cpp:187
static const Type * getElementType(const Expr *BaseExpr)
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:321
llvm::FoldingSet< BlockByrefHelpers > ByrefHelpersCache
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1888
Address CreateStructGEP(Address Addr, unsigned Index, CharUnits Offset, const llvm::Twine &Name="")
Definition: CGBuilder.h:183
llvm::Value * getConstant() const
Definition: CGBlocks.h:187
static llvm::Constant * buildDisposeHelper(CodeGenModule &CGM, const CGBlockInfo &blockInfo)
Build the helper function to dispose of a block.
Definition: CGBlocks.cpp:57
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
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:113
llvm::StructType * Type
Definition: CGBlocks.h:146
llvm::DenseMap< const Decl *, Address > DeclMapTy
static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block)
Enter the scope of a block.
Definition: CGBlocks.cpp:562
Pointer to a block type.
Definition: Type.h:2255
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3676
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:5769
CanQualType UnsignedLongTy
Definition: ASTContext.h:894
static llvm::Constant * buildByrefCopyHelper(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo, BlockByrefHelpers &generator)
Build the copy helper for a __block variable.
Definition: CGBlocks.cpp:1851
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2288
void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp)
Definition: CGExprCXX.cpp:508
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:647
llvm::Constant * GetAddrOfGlobalBlock(const BlockExpr *BE, const char *)
Gets the address of a block which requires no captures.
Definition: CGBlocks.cpp:1038
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1522
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:33
llvm::Constant * getBlockObjectAssign()
Definition: CGBlocks.cpp:2311
llvm::Constant * EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF=nullptr)
Try to emit the initializer for the given declaration as a constant; returns 0 if the expression cann...
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
A pair of helper functions for a __block variable.
Reading or writing from this object requires a barrier call.
Definition: Type.h:147
static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info, SmallVectorImpl< llvm::Type * > &elementTypes)
Definition: CGBlocks.cpp:298
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
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
bool isObjCObjectPointerType() const
Definition: Type.h:5514
uint32_t getBitMask() const
Definition: CGBlocks.h:77
void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize)
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
Definition: CGCleanup.cpp:418
const BlockDecl * getBlockDecl() const
Definition: CGBlocks.h:264
CharUnits BlockHeaderForcedGapSize
Definition: CGBlocks.h:242
llvm::Value * EmitARCRetainBlock(llvm::Value *value, bool mandatory)
Retain the given block, with _Block_copy semantics.
Definition: CGObjC.cpp:1945
void ForceCleanup()
Force the emission of cleanups now, instead of waiting until this object is destroyed.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2144
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2184
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:932
static RValue get(llvm::Value *V)
Definition: CGValue.h:85
RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue)
Definition: CGBlocks.cpp:957
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
Definition: CGDebugInfo.h:582
llvm::Constant * getNSConcreteGlobalBlock()
Definition: CGBlocks.cpp:2323
llvm::Type * getBlockDescriptorType()
Fetches the type of a generic block descriptor.
Definition: CGBlocks.cpp:906
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:108
const BlockExpr * getBlockExpr() const
Definition: CGBlocks.h:265
SourceLocation getLocation() const
Definition: DeclBase.h:388
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:144
llvm::Instruction * DominatingIP
An instruction which dominates the full-expression that the block is inside.
Definition: CGBlocks.h:246
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5285
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:1777
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:56
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:2022
void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags)
Definition: CGBlocks.cpp:2254
void setCleanup(EHScopeStack::stable_iterator cleanup)
Definition: CGBlocks.h:182
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5253
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1445