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