blob: 05d138b2a2b24d2c09b5070c3613d68a60889dbd [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/DeclObjC.h"
18#include "llvm/Module.h"
19#include "llvm/Target/TargetData.h"
20#include <algorithm>
21
22using namespace clang;
23using namespace CodeGen;
24
25llvm::Constant *CodeGenFunction::
26BuildDescriptorBlockDecl(bool BlockHasCopyDispose, CharUnits Size,
27 const llvm::StructType* Ty,
28 std::vector<HelperInfo> *NoteForHelper) {
29 const llvm::Type *UnsignedLongTy
30 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
31 llvm::Constant *C;
32 std::vector<llvm::Constant*> Elts;
33
34 // reserved
35 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
36 Elts.push_back(C);
37
38 // Size
39 // FIXME: What is the right way to say this doesn't fit? We should give
40 // a user diagnostic in that case. Better fix would be to change the
41 // API to size_t.
42 C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
43 Elts.push_back(C);
44
45 if (BlockHasCopyDispose) {
46 // copy_func_helper_decl
47 Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
48
49 // destroy_func_decl
50 Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
51 }
52
53 C = llvm::ConstantStruct::get(VMContext, Elts, false);
54
55 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
56 llvm::GlobalValue::InternalLinkage,
57 C, "__block_descriptor_tmp");
58 return C;
59}
60
61llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
62 if (NSConcreteGlobalBlock == 0)
63 NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
64 "_NSConcreteGlobalBlock");
65 return NSConcreteGlobalBlock;
66}
67
68llvm::Constant *BlockModule::getNSConcreteStackBlock() {
69 if (NSConcreteStackBlock == 0)
70 NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
71 "_NSConcreteStackBlock");
72 return NSConcreteStackBlock;
73}
74
75static void CollectBlockDeclRefInfo(
76 const Stmt *S, CodeGenFunction::BlockInfo &Info,
77 llvm::SmallSet<const DeclContext *, 16> &InnerContexts) {
78 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
79 I != E; ++I)
80 if (*I)
81 CollectBlockDeclRefInfo(*I, Info, InnerContexts);
82
83 // We want to ensure we walk down into block literals so we can find
84 // all nested BlockDeclRefExprs.
85 if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
86 InnerContexts.insert(cast<DeclContext>(BE->getBlockDecl()));
87 CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
88 }
89
90 if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
91 // FIXME: Handle enums.
92 if (isa<FunctionDecl>(BDRE->getDecl()))
93 return;
94
95 // Only Decls that escape are added.
96 if (!InnerContexts.count(BDRE->getDecl()->getDeclContext()))
97 Info.DeclRefs.push_back(BDRE);
98 }
99}
100
101/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
102/// declared as a global variable instead of on the stack.
103static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info) {
104 return Info.DeclRefs.empty();
105}
106
107/// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
108/// ensure we can generate the debug information for the parameter for the block
109/// invoke function.
110static void AllocateAllBlockDeclRefs(const CodeGenFunction::BlockInfo &Info,
111 CodeGenFunction *CGF) {
112 // Always allocate self, as it is often handy in the debugger, even if there
113 // is no codegen in the block that uses it. This is also useful to always do
114 // this as if we didn't, we'd have to figure out all code that uses a self
115 // pointer, including implicit uses.
116 if (const ObjCMethodDecl *OMD
117 = dyn_cast_or_null<ObjCMethodDecl>(CGF->CurFuncDecl)) {
118 ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
119 BlockDeclRefExpr *BDRE = new (CGF->getContext())
120 BlockDeclRefExpr(SelfDecl,
121 SelfDecl->getType(), SourceLocation(), false);
122 CGF->AllocateBlockDecl(BDRE);
123 }
124
125 // FIXME: Also always forward the this pointer in C++ as well.
126
127 for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
128 CGF->AllocateBlockDecl(Info.DeclRefs[i]);
129}
130
131// FIXME: Push most into CGM, passing down a few bits, like current function
132// name.
133llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
134
135 std::string Name = CurFn->getName();
136 CodeGenFunction::BlockInfo Info(0, Name.c_str());
137 llvm::SmallSet<const DeclContext *, 16> InnerContexts;
138 InnerContexts.insert(BE->getBlockDecl());
139 CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
140
141 // Check if the block can be global.
142 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
143 // to just have one code path. We should move this function into CGM and pass
144 // CGF, then we can just check to see if CGF is 0.
145 if (0 && CanBlockBeGlobal(Info))
146 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
147
148 size_t BlockFields = 5;
149
150 bool hasIntrospection = CGM.getContext().getLangOptions().BlockIntrospection;
151
152 if (hasIntrospection) {
153 BlockFields++;
154 }
155 std::vector<llvm::Constant*> Elts(BlockFields);
156
157 if (hasIntrospection) {
158 std::string BlockTypeEncoding;
159 CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
160
161 Elts[5] = llvm::ConstantExpr::getBitCast(
162 CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
163 }
164
165 llvm::Constant *C;
166 llvm::Value *V;
167
168 {
169 // C = BuildBlockStructInitlist();
170 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
171
172 if (hasIntrospection)
173 flags |= BLOCK_HAS_OBJC_TYPE;
174
175 // We run this first so that we set BlockHasCopyDispose from the entire
176 // block literal.
177 // __invoke
178 CharUnits subBlockSize;
179 CharUnits subBlockAlign;
180 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
181 bool subBlockHasCopyDispose = false;
182 llvm::Function *Fn
183 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
184 LocalDeclMap,
185 subBlockSize,
186 subBlockAlign,
187 subBlockDeclRefDecls,
188 subBlockHasCopyDispose);
189 BlockHasCopyDispose |= subBlockHasCopyDispose;
190 Elts[3] = Fn;
191
192 // FIXME: Don't use BlockHasCopyDispose, it is set more often then
193 // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
194 if (subBlockHasCopyDispose)
195 flags |= BLOCK_HAS_COPY_DISPOSE;
196
197 // __isa
198 C = CGM.getNSConcreteStackBlock();
199 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
200 Elts[0] = C;
201
202 // __flags
203 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
204 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
205 C = llvm::ConstantInt::get(IntTy, flags);
206 Elts[1] = C;
207
208 // __reserved
209 C = llvm::ConstantInt::get(IntTy, 0);
210 Elts[2] = C;
211
212 if (subBlockDeclRefDecls.size() == 0) {
213 // __descriptor
214 Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize,
215 0, 0);
216
217 // Optimize to being a global block.
218 Elts[0] = CGM.getNSConcreteGlobalBlock();
219 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
220
221 C = llvm::ConstantStruct::get(VMContext, Elts, false);
222
223 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
224 llvm::GlobalValue::InternalLinkage, C,
225 "__block_holder_tmp_" +
226 llvm::Twine(CGM.getGlobalUniqueCount()));
227 QualType BPT = BE->getType();
228 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
229 return C;
230 }
231
232 std::vector<const llvm::Type *> Types(BlockFields+subBlockDeclRefDecls.size());
233 for (int i=0; i<4; ++i)
234 Types[i] = Elts[i]->getType();
235 Types[4] = PtrToInt8Ty;
236 if (hasIntrospection)
237 Types[5] = PtrToInt8Ty;
238
239 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
240 const Expr *E = subBlockDeclRefDecls[i];
241 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
242 QualType Ty = E->getType();
243 if (BDRE && BDRE->isByRef()) {
244 Types[i+BlockFields] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
245 } else
246 Types[i+BlockFields] = ConvertType(Ty);
247 }
248
249 llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
250
251 llvm::AllocaInst *A = CreateTempAlloca(Ty);
252 A->setAlignment(subBlockAlign.getQuantity());
253 V = A;
254
255 std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
256 int helpersize = 0;
257
258 for (unsigned i=0; i<4; ++i)
259 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
260 if (hasIntrospection)
261 Builder.CreateStore(Elts[5], Builder.CreateStructGEP(V, 5, "block.tmp"));
262
263 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
264 {
265 // FIXME: Push const down.
266 Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
267 DeclRefExpr *DR;
268 ValueDecl *VD;
269
270 DR = dyn_cast<DeclRefExpr>(E);
271 // Skip padding.
272 if (DR) continue;
273
274 BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
275 VD = BDRE->getDecl();
276
277 llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
278 NoteForHelper[helpersize].index = i+5;
279 NoteForHelper[helpersize].RequiresCopying
280 = BlockRequiresCopying(VD->getType());
281 NoteForHelper[helpersize].flag
282 = (VD->getType()->isBlockPointerType()
283 ? BLOCK_FIELD_IS_BLOCK
284 : BLOCK_FIELD_IS_OBJECT);
285
286 if (LocalDeclMap[VD]) {
287 if (BDRE->isByRef()) {
288 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
289 // FIXME: Someone double check this.
290 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
291 llvm::Value *Loc = LocalDeclMap[VD];
292 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
293 Loc = Builder.CreateLoad(Loc);
294 Builder.CreateStore(Loc, Addr);
295 ++helpersize;
296 continue;
297 } else
298 E = new (getContext()) DeclRefExpr (VD,
299 VD->getType(),
300 SourceLocation());
301 }
302 if (BDRE->isByRef()) {
303 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
304 // FIXME: Someone double check this.
305 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
306 E = new (getContext())
307 UnaryOperator(E, UnaryOperator::AddrOf,
308 getContext().getPointerType(E->getType()),
309 SourceLocation());
310 }
311 ++helpersize;
312
313 RValue r = EmitAnyExpr(E, Addr, false);
314 if (r.isScalar()) {
315 llvm::Value *Loc = r.getScalarVal();
316 const llvm::Type *Ty = Types[i+BlockFields];
317 if (BDRE->isByRef()) {
318 // E is now the address of the value field, instead, we want the
319 // address of the actual ByRef struct. We optimize this slightly
320 // compared to gcc by not grabbing the forwarding slot as this must
321 // be done during Block_copy for us, and we can postpone the work
322 // until then.
323 CharUnits offset = BlockDecls[BDRE->getDecl()];
324
325 llvm::Value *BlockLiteral = LoadBlockStruct();
326
327 Loc = Builder.CreateGEP(BlockLiteral,
328 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
329 offset.getQuantity()),
330 "block.literal");
331 Ty = llvm::PointerType::get(Ty, 0);
332 Loc = Builder.CreateBitCast(Loc, Ty);
333 Loc = Builder.CreateLoad(Loc);
334 // Loc = Builder.CreateBitCast(Loc, Ty);
335 }
336 Builder.CreateStore(Loc, Addr);
337 } else if (r.isComplex())
338 // FIXME: implement
339 ErrorUnsupported(BE, "complex in block literal");
340 else if (r.isAggregate())
341 ; // Already created into the destination
342 else
343 assert (0 && "bad block variable");
344 // FIXME: Ensure that the offset created by the backend for
345 // the struct matches the previously computed offset in BlockDecls.
346 }
347 NoteForHelper.resize(helpersize);
348
349 // __descriptor
350 llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
351 subBlockSize, Ty,
352 &NoteForHelper);
353 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
354 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
355 }
356
357 QualType BPT = BE->getType();
358 return Builder.CreateBitCast(V, ConvertType(BPT));
359}
360
361
362const llvm::Type *BlockModule::getBlockDescriptorType() {
363 if (BlockDescriptorType)
364 return BlockDescriptorType;
365
366 const llvm::Type *UnsignedLongTy =
367 getTypes().ConvertType(getContext().UnsignedLongTy);
368
369 // struct __block_descriptor {
370 // unsigned long reserved;
371 // unsigned long block_size;
372 // };
373 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
374 UnsignedLongTy,
375 UnsignedLongTy,
376 NULL);
377
378 getModule().addTypeName("struct.__block_descriptor",
379 BlockDescriptorType);
380
381 return BlockDescriptorType;
382}
383
384const llvm::Type *BlockModule::getGenericBlockLiteralType() {
385 if (GenericBlockLiteralType)
386 return GenericBlockLiteralType;
387
388 const llvm::Type *BlockDescPtrTy =
389 llvm::PointerType::getUnqual(getBlockDescriptorType());
390
391 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
392 getTypes().ConvertType(getContext().IntTy));
393
394 // struct __block_literal_generic {
395 // void *__isa;
396 // int __flags;
397 // int __reserved;
398 // void (*__invoke)(void *);
399 // struct __block_descriptor *__descriptor;
400 // // GNU runtime only:
401 // const char *types;
402 // };
403 if (CGM.getContext().getLangOptions().BlockIntrospection)
404 GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
405 PtrToInt8Ty,
406 IntTy,
407 IntTy,
408 PtrToInt8Ty,
409 BlockDescPtrTy,
410 PtrToInt8Ty,
411 NULL);
412 else
413 GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
414 PtrToInt8Ty,
415 IntTy,
416 IntTy,
417 PtrToInt8Ty,
418 BlockDescPtrTy,
419 NULL);
420
421 getModule().addTypeName("struct.__block_literal_generic",
422 GenericBlockLiteralType);
423
424 return GenericBlockLiteralType;
425}
426
427const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
428 if (GenericExtendedBlockLiteralType)
429 return GenericExtendedBlockLiteralType;
430
431 const llvm::Type *BlockDescPtrTy =
432 llvm::PointerType::getUnqual(getBlockDescriptorType());
433
434 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
435 getTypes().ConvertType(getContext().IntTy));
436
437 // struct __block_literal_generic {
438 // void *__isa;
439 // int __flags;
440 // int __reserved;
441 // void (*__invoke)(void *);
442 // struct __block_descriptor *__descriptor;
443 // void *__copy_func_helper_decl;
444 // void *__destroy_func_decl;
445 // };
446 GenericExtendedBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
447 PtrToInt8Ty,
448 IntTy,
449 IntTy,
450 PtrToInt8Ty,
451 BlockDescPtrTy,
452 PtrToInt8Ty,
453 PtrToInt8Ty,
454 NULL);
455
456 getModule().addTypeName("struct.__block_literal_extended_generic",
457 GenericExtendedBlockLiteralType);
458
459 return GenericExtendedBlockLiteralType;
460}
461
462RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
463 ReturnValueSlot ReturnValue) {
464 const BlockPointerType *BPT =
465 E->getCallee()->getType()->getAs<BlockPointerType>();
466
467 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
468
469 // Get a pointer to the generic block literal.
470 const llvm::Type *BlockLiteralTy =
471 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
472
473 // Bitcast the callee to a block literal.
474 llvm::Value *BlockLiteral =
475 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
476
477 // Get the function pointer from the literal.
478 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
479
480 BlockLiteral =
481 Builder.CreateBitCast(BlockLiteral,
482 llvm::Type::getInt8PtrTy(VMContext),
483 "tmp");
484
485 // Add the block literal.
486 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
487 CallArgList Args;
488 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
489
490 QualType FnType = BPT->getPointeeType();
491
492 // And the rest of the arguments.
493 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
494 E->arg_begin(), E->arg_end());
495
496 // Load the function.
497 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
498
499 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
500 QualType ResultType = FuncTy->getResultType();
501
502 const CGFunctionInfo &FnInfo =
503 CGM.getTypes().getFunctionInfo(ResultType, Args, FuncTy->getCallConv(),
504 FuncTy->getNoReturnAttr());
505
506 // Cast the function pointer to the right type.
507 const llvm::Type *BlockFTy =
508 CGM.getTypes().GetFunctionType(FnInfo, false);
509
510 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
511 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
512
513 // And call the block.
514 return EmitCall(FnInfo, Func, ReturnValue, Args);
515}
516
517CharUnits CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
518 const ValueDecl *VD = E->getDecl();
519 CharUnits &offset = BlockDecls[VD];
520
521 // See if we have already allocated an offset for this variable.
522 if (offset.isPositive())
523 return offset;
524
525 // Don't run the expensive check, unless we have to.
526 if (!BlockHasCopyDispose)
527 if (E->isByRef()
528 || BlockRequiresCopying(E->getType()))
529 BlockHasCopyDispose = true;
530
531 // if not, allocate one now.
532 offset = getBlockOffset(E);
533
534 return offset;
535}
536
537llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
538 const ValueDecl *VD = E->getDecl();
539 CharUnits offset = AllocateBlockDecl(E);
540
541
542 llvm::Value *BlockLiteral = LoadBlockStruct();
543 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
544 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
545 offset.getQuantity()),
546 "block.literal");
547 if (E->isByRef()) {
548 const llvm::Type *PtrStructTy
549 = llvm::PointerType::get(BuildByRefType(VD), 0);
550 // The block literal will need a copy/destroy helper.
551 BlockHasCopyDispose = true;
552
553 const llvm::Type *Ty = PtrStructTy;
554 Ty = llvm::PointerType::get(Ty, 0);
555 V = Builder.CreateBitCast(V, Ty);
556 V = Builder.CreateLoad(V);
557 V = Builder.CreateStructGEP(V, 1, "forwarding");
558 V = Builder.CreateLoad(V);
559 V = Builder.CreateBitCast(V, PtrStructTy);
560 V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
561 VD->getNameAsString());
562 } else {
563 const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
564
565 Ty = llvm::PointerType::get(Ty, 0);
566 V = Builder.CreateBitCast(V, Ty);
567 }
568 return V;
569}
570
571void CodeGenFunction::BlockForwardSelf() {
572 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
573 ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
574 llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
575 if (DMEntry)
576 return;
577 // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
578 BlockDeclRefExpr *BDRE = new (getContext())
579 BlockDeclRefExpr(SelfDecl,
580 SelfDecl->getType(), SourceLocation(), false);
581 DMEntry = GetAddrOfBlockDecl(BDRE);
582}
583
584llvm::Constant *
585BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
586 // Generate the block descriptor.
587 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
588 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
589 getTypes().ConvertType(getContext().IntTy));
590
591 llvm::Constant *DescriptorFields[2];
592
593 // Reserved
594 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
595
596 // Block literal size. For global blocks we just use the size of the generic
597 // block literal struct.
598 CharUnits BlockLiteralSize =
599 CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
600 DescriptorFields[1] =
601 llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
602
603 llvm::Constant *DescriptorStruct =
604 llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 2, false);
605
606 llvm::GlobalVariable *Descriptor =
607 new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
608 llvm::GlobalVariable::InternalLinkage,
609 DescriptorStruct, "__block_descriptor_global");
610
611 int FieldCount = 5;
612 // Generate the constants for the block literal.
613 if (CGM.getContext().getLangOptions().BlockIntrospection)
614 FieldCount = 6;
615
616 std::vector<llvm::Constant*> LiteralFields(FieldCount);
617
618 CodeGenFunction::BlockInfo Info(0, n);
619 CharUnits subBlockSize;
620 CharUnits subBlockAlign;
621 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
622 bool subBlockHasCopyDispose = false;
623 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
624 llvm::Function *Fn
625 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
626 subBlockSize,
627 subBlockAlign,
628 subBlockDeclRefDecls,
629 subBlockHasCopyDispose);
630 assert(subBlockSize == BlockLiteralSize
631 && "no imports allowed for global block");
632
633 // isa
634 LiteralFields[0] = getNSConcreteGlobalBlock();
635
636 // Flags
637 LiteralFields[1] = CGM.getContext().getLangOptions().BlockIntrospection ?
638 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR |
639 BLOCK_HAS_OBJC_TYPE) :
640 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
641
642 // Reserved
643 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
644
645 // Function
646 LiteralFields[3] = Fn;
647
648 // Descriptor
649 LiteralFields[4] = Descriptor;
650
651 // Type encoding
652 if (CGM.getContext().getLangOptions().BlockIntrospection) {
653 std::string BlockTypeEncoding;
654 CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
655
656 LiteralFields[5] = CGM.GetAddrOfConstantCString(BlockTypeEncoding);
657 }
658
659 llvm::Constant *BlockLiteralStruct =
660 llvm::ConstantStruct::get(VMContext, LiteralFields, false);
661
662 llvm::GlobalVariable *BlockLiteral =
663 new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
664 llvm::GlobalVariable::InternalLinkage,
665 BlockLiteralStruct, "__block_literal_global");
666
667 return BlockLiteral;
668}
669
670llvm::Value *CodeGenFunction::LoadBlockStruct() {
671 llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
672 "self");
673 // For now, we codegen based upon byte offsets.
674 return Builder.CreateBitCast(V, PtrToInt8Ty);
675}
676
677llvm::Function *
678CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
679 const BlockInfo& Info,
680 const Decl *OuterFuncDecl,
681 llvm::DenseMap<const Decl*, llvm::Value*> ldm,
682 CharUnits &Size,
683 CharUnits &Align,
684 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
685 bool &subBlockHasCopyDispose) {
686
687 // Check if we should generate debug info for this block.
688 if (CGM.getDebugInfo())
689 DebugInfo = CGM.getDebugInfo();
690
691 // Arrange for local static and local extern declarations to appear
692 // to be local to this function as well, as they are directly referenced
693 // in a block.
694 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
695 i != ldm.end();
696 ++i) {
697 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
698
699 if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
700 LocalDeclMap[VD] = i->second;
701 }
702
703 BlockOffset =
704 CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
705 BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
706
707 const FunctionType *BlockFunctionType = BExpr->getFunctionType();
708 QualType ResultType;
709 CallingConv CC = BlockFunctionType->getCallConv();
710 bool NoReturn = BlockFunctionType->getNoReturnAttr();
711 bool IsVariadic;
712 if (const FunctionProtoType *FTy =
713 dyn_cast<FunctionProtoType>(BlockFunctionType)) {
714 ResultType = FTy->getResultType();
715 IsVariadic = FTy->isVariadic();
716 } else {
717 // K&R style block.
718 ResultType = BlockFunctionType->getResultType();
719 IsVariadic = false;
720 }
721
722 FunctionArgList Args;
723
724 CurFuncDecl = OuterFuncDecl;
725
726 const BlockDecl *BD = BExpr->getBlockDecl();
727
728 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
729
730 // Allocate all BlockDeclRefDecls, so we can calculate the right ParmTy below.
731 AllocateAllBlockDeclRefs(Info, this);
732
733 QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
734 BlockDeclRefDecls);
735 // FIXME: This leaks
736 ImplicitParamDecl *SelfDecl =
737 ImplicitParamDecl::Create(getContext(), 0,
738 SourceLocation(), II,
739 ParmTy);
740
741 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
742 BlockStructDecl = SelfDecl;
743
744 for (BlockDecl::param_const_iterator i = BD->param_begin(),
745 e = BD->param_end(); i != e; ++i)
746 Args.push_back(std::make_pair(*i, (*i)->getType()));
747
748 const CGFunctionInfo &FI =
749 CGM.getTypes().getFunctionInfo(ResultType, Args, CC, NoReturn);
750
751 CodeGenTypes &Types = CGM.getTypes();
752 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
753
754 llvm::Function *Fn =
755 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
756 llvm::Twine("__") + Info.Name + "_block_invoke_",
757 &CGM.getModule());
758
759 CGM.SetInternalFunctionAttributes(BD, Fn, FI);
760
761 StartFunction(BD, ResultType, Fn, Args,
762 BExpr->getBody()->getLocEnd());
763
764 CurFuncDecl = OuterFuncDecl;
765 CurCodeDecl = BD;
766
767 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
768 llvm::BasicBlock *entry = Builder.GetInsertBlock();
769 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
770 --entry_ptr;
771
772 EmitStmt(BExpr->getBody());
773
774 // Remember where we were...
775 llvm::BasicBlock *resume = Builder.GetInsertBlock();
776
777 // Go back to the entry.
778 ++entry_ptr;
779 Builder.SetInsertPoint(entry, entry_ptr);
780
781 if (CGDebugInfo *DI = getDebugInfo()) {
782 // Emit debug information for all the BlockDeclRefDecls.
783 for (unsigned i = 0, e = BlockDeclRefDecls.size(); i != e; ++i) {
784 if (const BlockDeclRefExpr *BDRE =
785 dyn_cast<BlockDeclRefExpr>(BlockDeclRefDecls[i])) {
786 const ValueDecl *D = BDRE->getDecl();
787 DI->setLocation(D->getLocation());
788 DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
789 LocalDeclMap[getBlockStructDecl()],
790 Builder, this);
791 }
792 }
793 }
794 // And resume where we left off.
795 if (resume == 0)
796 Builder.ClearInsertionPoint();
797 else
798 Builder.SetInsertPoint(resume);
799
800 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
801
802 // The runtime needs a minimum alignment of a void *.
803 CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
804 BlockOffset = CharUnits::fromQuantity(
805 llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
806 MinAlign.getQuantity()));
807
808 Size = BlockOffset;
809 Align = BlockAlign;
810 subBlockDeclRefDecls = BlockDeclRefDecls;
811 subBlockHasCopyDispose |= BlockHasCopyDispose;
812 return Fn;
813}
814
815CharUnits BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
816 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
817
818 CharUnits Size = getContext().getTypeSizeInChars(D->getType());
819 CharUnits Align = getContext().getDeclAlign(D);
820
821 if (BDRE->isByRef()) {
822 Size = getContext().getTypeSizeInChars(getContext().VoidPtrTy);
823 Align = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
824 }
825
826 assert ((Align.isPositive()) && "alignment must be 1 byte or more");
827
828 CharUnits OldOffset = BlockOffset;
829
830 // Ensure proper alignment, even if it means we have to have a gap
831 BlockOffset = CharUnits::fromQuantity(
832 llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
833 BlockAlign = std::max(Align, BlockAlign);
834
835 CharUnits Pad = BlockOffset - OldOffset;
836 if (Pad.isPositive()) {
837 llvm::ArrayType::get(llvm::Type::getInt8Ty(VMContext), Pad.getQuantity());
838 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
839 llvm::APInt(32,
840 Pad.getQuantity()),
841 ArrayType::Normal, 0);
842 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
843 0, QualType(PadTy), 0, VarDecl::None);
844 Expr *E;
845 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
846 SourceLocation());
847 BlockDeclRefDecls.push_back(E);
848 }
849 BlockDeclRefDecls.push_back(BDRE);
850
851 BlockOffset += Size;
852 return BlockOffset-Size;
853}
854
855llvm::Constant *BlockFunction::
856GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
857 std::vector<HelperInfo> *NoteForHelperp) {
858 QualType R = getContext().VoidTy;
859
860 FunctionArgList Args;
861 // FIXME: This leaks
862 ImplicitParamDecl *Dst =
863 ImplicitParamDecl::Create(getContext(), 0,
864 SourceLocation(), 0,
865 getContext().getPointerType(getContext().VoidTy));
866 Args.push_back(std::make_pair(Dst, Dst->getType()));
867 ImplicitParamDecl *Src =
868 ImplicitParamDecl::Create(getContext(), 0,
869 SourceLocation(), 0,
870 getContext().getPointerType(getContext().VoidTy));
871 Args.push_back(std::make_pair(Src, Src->getType()));
872
873 const CGFunctionInfo &FI =
874 CGM.getTypes().getFunctionInfo(R, Args, CC_Default, false);
875
876 // FIXME: We'd like to put these into a mergable by content, with
877 // internal linkage.
878 CodeGenTypes &Types = CGM.getTypes();
879 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
880
881 llvm::Function *Fn =
882 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
883 "__copy_helper_block_", &CGM.getModule());
884
885 IdentifierInfo *II
886 = &CGM.getContext().Idents.get("__copy_helper_block_");
887
888 FunctionDecl *FD = FunctionDecl::Create(getContext(),
889 getContext().getTranslationUnitDecl(),
890 SourceLocation(), II, R, 0,
891 FunctionDecl::Static, false,
892 true);
893 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
894
895 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
896 llvm::Type *PtrPtrT;
897
898 if (NoteForHelperp) {
899 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
900
901 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
902 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
903 SrcObj = Builder.CreateLoad(SrcObj);
904
905 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
906 llvm::Type *PtrPtrT;
907 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
908 DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
909 DstObj = Builder.CreateLoad(DstObj);
910
911 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
912 int flag = NoteForHelper[i].flag;
913 int index = NoteForHelper[i].index;
914
915 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
916 || NoteForHelper[i].RequiresCopying) {
917 llvm::Value *Srcv = SrcObj;
918 Srcv = Builder.CreateStructGEP(Srcv, index);
919 Srcv = Builder.CreateBitCast(Srcv,
920 llvm::PointerType::get(PtrToInt8Ty, 0));
921 Srcv = Builder.CreateLoad(Srcv);
922
923 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
924 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
925
926 llvm::Value *N = llvm::ConstantInt::get(
927 llvm::Type::getInt32Ty(T->getContext()), flag);
928 llvm::Value *F = getBlockObjectAssign();
929 Builder.CreateCall3(F, Dstv, Srcv, N);
930 }
931 }
932 }
933
934 CGF.FinishFunction();
935
936 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
937}
938
939llvm::Constant *BlockFunction::
940GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
941 const llvm::StructType* T,
942 std::vector<HelperInfo> *NoteForHelperp) {
943 QualType R = getContext().VoidTy;
944
945 FunctionArgList Args;
946 // FIXME: This leaks
947 ImplicitParamDecl *Src =
948 ImplicitParamDecl::Create(getContext(), 0,
949 SourceLocation(), 0,
950 getContext().getPointerType(getContext().VoidTy));
951
952 Args.push_back(std::make_pair(Src, Src->getType()));
953
954 const CGFunctionInfo &FI =
955 CGM.getTypes().getFunctionInfo(R, Args, CC_Default, false);
956
957 // FIXME: We'd like to put these into a mergable by content, with
958 // internal linkage.
959 CodeGenTypes &Types = CGM.getTypes();
960 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
961
962 llvm::Function *Fn =
963 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
964 "__destroy_helper_block_", &CGM.getModule());
965
966 IdentifierInfo *II
967 = &CGM.getContext().Idents.get("__destroy_helper_block_");
968
969 FunctionDecl *FD = FunctionDecl::Create(getContext(),
970 getContext().getTranslationUnitDecl(),
971 SourceLocation(), II, R, 0,
972 FunctionDecl::Static, false,
973 true);
974 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
975
976 if (NoteForHelperp) {
977 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
978
979 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
980 llvm::Type *PtrPtrT;
981 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
982 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
983 SrcObj = Builder.CreateLoad(SrcObj);
984
985 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
986 int flag = NoteForHelper[i].flag;
987 int index = NoteForHelper[i].index;
988
989 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
990 || NoteForHelper[i].RequiresCopying) {
991 llvm::Value *Srcv = SrcObj;
992 Srcv = Builder.CreateStructGEP(Srcv, index);
993 Srcv = Builder.CreateBitCast(Srcv,
994 llvm::PointerType::get(PtrToInt8Ty, 0));
995 Srcv = Builder.CreateLoad(Srcv);
996
997 BuildBlockRelease(Srcv, flag);
998 }
999 }
1000 }
1001
1002 CGF.FinishFunction();
1003
1004 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1005}
1006
1007llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
1008 std::vector<HelperInfo> *NoteForHelper) {
1009 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1010 T, NoteForHelper);
1011}
1012
1013llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
1014 std::vector<HelperInfo> *NoteForHelperp) {
1015 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
1016 T, NoteForHelperp);
1017}
1018
1019llvm::Constant *BlockFunction::
1020GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
1021 QualType R = getContext().VoidTy;
1022
1023 FunctionArgList Args;
1024 // FIXME: This leaks
1025 ImplicitParamDecl *Dst =
1026 ImplicitParamDecl::Create(getContext(), 0,
1027 SourceLocation(), 0,
1028 getContext().getPointerType(getContext().VoidTy));
1029 Args.push_back(std::make_pair(Dst, Dst->getType()));
1030
1031 // FIXME: This leaks
1032 ImplicitParamDecl *Src =
1033 ImplicitParamDecl::Create(getContext(), 0,
1034 SourceLocation(), 0,
1035 getContext().getPointerType(getContext().VoidTy));
1036 Args.push_back(std::make_pair(Src, Src->getType()));
1037
1038 const CGFunctionInfo &FI =
1039 CGM.getTypes().getFunctionInfo(R, Args, CC_Default, false);
1040
1041 CodeGenTypes &Types = CGM.getTypes();
1042 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1043
1044 // FIXME: We'd like to put these into a mergable by content, with
1045 // internal linkage.
1046 llvm::Function *Fn =
1047 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1048 "__Block_byref_id_object_copy_", &CGM.getModule());
1049
1050 IdentifierInfo *II
1051 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1052
1053 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1054 getContext().getTranslationUnitDecl(),
1055 SourceLocation(), II, R, 0,
1056 FunctionDecl::Static, false,
1057 true);
1058 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1059
1060 // dst->x
1061 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
1062 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
1063 V = Builder.CreateLoad(V);
1064 V = Builder.CreateStructGEP(V, 6, "x");
1065 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1066
1067 // src->x
1068 V = CGF.GetAddrOfLocalVar(Src);
1069 V = Builder.CreateLoad(V);
1070 V = Builder.CreateBitCast(V, T);
1071 V = Builder.CreateStructGEP(V, 6, "x");
1072 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1073 llvm::Value *SrcObj = Builder.CreateLoad(V);
1074
1075 flag |= BLOCK_BYREF_CALLER;
1076
1077 llvm::Value *N = llvm::ConstantInt::get(
1078 llvm::Type::getInt32Ty(T->getContext()), flag);
1079 llvm::Value *F = getBlockObjectAssign();
1080 Builder.CreateCall3(F, DstObj, SrcObj, N);
1081
1082 CGF.FinishFunction();
1083
1084 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1085}
1086
1087llvm::Constant *
1088BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1089 int flag) {
1090 QualType R = getContext().VoidTy;
1091
1092 FunctionArgList Args;
1093 // FIXME: This leaks
1094 ImplicitParamDecl *Src =
1095 ImplicitParamDecl::Create(getContext(), 0,
1096 SourceLocation(), 0,
1097 getContext().getPointerType(getContext().VoidTy));
1098
1099 Args.push_back(std::make_pair(Src, Src->getType()));
1100
1101 const CGFunctionInfo &FI =
1102 CGM.getTypes().getFunctionInfo(R, Args, CC_Default, false);
1103
1104 CodeGenTypes &Types = CGM.getTypes();
1105 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1106
1107 // FIXME: We'd like to put these into a mergable by content, with
1108 // internal linkage.
1109 llvm::Function *Fn =
1110 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1111 "__Block_byref_id_object_dispose_",
1112 &CGM.getModule());
1113
1114 IdentifierInfo *II
1115 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1116
1117 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1118 getContext().getTranslationUnitDecl(),
1119 SourceLocation(), II, R, 0,
1120 FunctionDecl::Static, false,
1121 true);
1122 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1123
1124 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
1125 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
1126 V = Builder.CreateLoad(V);
1127 V = Builder.CreateStructGEP(V, 6, "x");
1128 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1129 V = Builder.CreateLoad(V);
1130
1131 flag |= BLOCK_BYREF_CALLER;
1132 BuildBlockRelease(V, flag);
1133 CGF.FinishFunction();
1134
1135 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1136}
1137
1138llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1139 int Flag, unsigned Align) {
1140 // All alignments below that of pointer alignment collapse down to just
1141 // pointer alignment, as we always have at least that much alignment to begin
1142 // with.
1143 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1144
1145 // As an optimization, we only generate a single function of each kind we
1146 // might need. We need a different one for each alignment and for each
1147 // setting of flags. We mix Align and flag to get the kind.
1148 uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1149 llvm::Constant *&Entry = CGM.AssignCache[Kind];
1150 if (Entry)
1151 return Entry;
1152 return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
1153}
1154
1155llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1156 int Flag,
1157 unsigned Align) {
1158 // All alignments below that of pointer alignment collpase down to just
1159 // pointer alignment, as we always have at least that much alignment to begin
1160 // with.
1161 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1162
1163 // As an optimization, we only generate a single function of each kind we
1164 // might need. We need a different one for each alignment and for each
1165 // setting of flags. We mix Align and flag to get the kind.
1166 uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1167 llvm::Constant *&Entry = CGM.DestroyCache[Kind];
1168 if (Entry)
1169 return Entry;
1170 return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
1171}
1172
1173llvm::Value *BlockFunction::getBlockObjectDispose() {
1174 if (CGM.BlockObjectDispose == 0) {
1175 const llvm::FunctionType *FTy;
1176 std::vector<const llvm::Type*> ArgTys;
1177 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1178 ArgTys.push_back(PtrToInt8Ty);
1179 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
1180 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1181 CGM.BlockObjectDispose
1182 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1183 }
1184 return CGM.BlockObjectDispose;
1185}
1186
1187llvm::Value *BlockFunction::getBlockObjectAssign() {
1188 if (CGM.BlockObjectAssign == 0) {
1189 const llvm::FunctionType *FTy;
1190 std::vector<const llvm::Type*> ArgTys;
1191 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1192 ArgTys.push_back(PtrToInt8Ty);
1193 ArgTys.push_back(PtrToInt8Ty);
1194 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
1195 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1196 CGM.BlockObjectAssign
1197 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1198 }
1199 return CGM.BlockObjectAssign;
1200}
1201
1202void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1203 llvm::Value *F = getBlockObjectDispose();
1204 llvm::Value *N;
1205 V = Builder.CreateBitCast(V, PtrToInt8Ty);
1206 N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1207 Builder.CreateCall2(F, V, N);
1208}
1209
1210ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1211
1212BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1213 CGBuilderTy &B)
1214 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
1215 PtrToInt8Ty = llvm::PointerType::getUnqual(
1216 llvm::Type::getInt8Ty(VMContext));
1217
1218 BlockHasCopyDispose = false;
1219}