12437cbfaSAnders Carlsson //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
22437cbfaSAnders Carlsson //
32437cbfaSAnders Carlsson //                     The LLVM Compiler Infrastructure
42437cbfaSAnders Carlsson //
52437cbfaSAnders Carlsson // This file is distributed under the University of Illinois Open Source
62437cbfaSAnders Carlsson // License. See LICENSE.TXT for details.
72437cbfaSAnders Carlsson //
82437cbfaSAnders Carlsson //===----------------------------------------------------------------------===//
92437cbfaSAnders Carlsson //
102437cbfaSAnders Carlsson // This contains code to emit blocks.
112437cbfaSAnders Carlsson //
122437cbfaSAnders Carlsson //===----------------------------------------------------------------------===//
132437cbfaSAnders Carlsson 
142437cbfaSAnders Carlsson #include "CodeGenFunction.h"
152437cbfaSAnders Carlsson #include "CodeGenModule.h"
16692c6e37SMike Stump #include "clang/AST/DeclObjC.h"
172437cbfaSAnders Carlsson #include "llvm/Module.h"
186a60fa24SAnders Carlsson #include "llvm/Target/TargetData.h"
192437cbfaSAnders Carlsson #include <algorithm>
202437cbfaSAnders Carlsson using namespace clang;
212437cbfaSAnders Carlsson using namespace CodeGen;
222437cbfaSAnders Carlsson 
23d6ef62f0SMike Stump llvm::Constant *CodeGenFunction::
24d2142cffSMike Stump BuildDescriptorBlockDecl(bool BlockHasCopyDispose, uint64_t Size,
25d2142cffSMike Stump                          const llvm::StructType* Ty,
26aeb0ffd5SMike Stump                          std::vector<HelperInfo> *NoteForHelper) {
27c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
28c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
2985284bacSMike Stump   llvm::Constant *C;
3085284bacSMike Stump   std::vector<llvm::Constant*> Elts;
3185284bacSMike Stump 
3285284bacSMike Stump   // reserved
33b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
3485284bacSMike Stump   Elts.push_back(C);
3585284bacSMike Stump 
3685284bacSMike Stump   // Size
372ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
382ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
392ac40a9fSMike Stump   // API to size_t.
40b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, Size);
4185284bacSMike Stump   Elts.push_back(C);
4285284bacSMike Stump 
4385284bacSMike Stump   if (BlockHasCopyDispose) {
4485284bacSMike Stump     // copy_func_helper_decl
4567645930SMike Stump     Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
4685284bacSMike Stump 
4785284bacSMike Stump     // destroy_func_decl
4867645930SMike Stump     Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
4985284bacSMike Stump   }
5085284bacSMike Stump 
510e0189d6SOwen Anderson   C = llvm::ConstantStruct::get(Elts);
5285284bacSMike Stump 
53c10c8d3eSOwen Anderson   C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
5485284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
55c10c8d3eSOwen Anderson                                C, "__block_descriptor_tmp");
5685284bacSMike Stump   return C;
5785284bacSMike Stump }
5885284bacSMike Stump 
5995435674SMike Stump llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
6046813bbfSChris Lattner   if (NSConcreteGlobalBlock == 0)
6146813bbfSChris Lattner     NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
6246813bbfSChris Lattner                                                       "_NSConcreteGlobalBlock");
63971f9b66SMike Stump   return NSConcreteGlobalBlock;
64971f9b66SMike Stump }
65971f9b66SMike Stump 
6695435674SMike Stump llvm::Constant *BlockModule::getNSConcreteStackBlock() {
6746813bbfSChris Lattner   if (NSConcreteStackBlock == 0)
6846813bbfSChris Lattner     NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
6946813bbfSChris Lattner                                                      "_NSConcreteStackBlock");
707ab278dbSMike Stump   return NSConcreteStackBlock;
717ab278dbSMike Stump }
727ab278dbSMike Stump 
73ed5e69feSAnders Carlsson static void CollectBlockDeclRefInfo(const Stmt *S,
74ed5e69feSAnders Carlsson                                     CodeGenFunction::BlockInfo &Info) {
75ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
76ed5e69feSAnders Carlsson        I != E; ++I)
77dd942713SDaniel Dunbar     if (*I)
78ed5e69feSAnders Carlsson       CollectBlockDeclRefInfo(*I, Info);
79ed5e69feSAnders Carlsson 
80ed5e69feSAnders Carlsson   if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
81ed5e69feSAnders Carlsson     // FIXME: Handle enums.
82ed5e69feSAnders Carlsson     if (isa<FunctionDecl>(DE->getDecl()))
83ed5e69feSAnders Carlsson       return;
84ed5e69feSAnders Carlsson 
85ed5e69feSAnders Carlsson     if (DE->isByRef())
86ed5e69feSAnders Carlsson       Info.ByRefDeclRefs.push_back(DE);
87ed5e69feSAnders Carlsson     else
88ed5e69feSAnders Carlsson       Info.ByCopyDeclRefs.push_back(DE);
89ed5e69feSAnders Carlsson   }
90ed5e69feSAnders Carlsson }
91ed5e69feSAnders Carlsson 
922d33d630SMike Stump /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
932d33d630SMike Stump /// declared as a global variable instead of on the stack.
9446813bbfSChris Lattner static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info) {
95ed5e69feSAnders Carlsson   return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
96ed5e69feSAnders Carlsson }
97ed5e69feSAnders Carlsson 
982d33d630SMike Stump // FIXME: Push most into CGM, passing down a few bits, like current function
992d33d630SMike Stump // name.
100b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
101ed5e69feSAnders Carlsson 
102ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
103ed5e69feSAnders Carlsson   CodeGenFunction::BlockInfo Info(0, Name.c_str());
104ed5e69feSAnders Carlsson   CollectBlockDeclRefInfo(BE->getBody(), Info);
105ed5e69feSAnders Carlsson 
106ed5e69feSAnders Carlsson   // Check if the block can be global.
1072d33d630SMike Stump   // FIXME: This test doesn't work for nested blocks yet.  Longer term, I'd like
1082d33d630SMike Stump   // to just have one code path.  We should move this function into CGM and pass
1092d33d630SMike Stump   // CGF, then we can just check to see if CGF is 0.
11097d01d50SMike Stump   if (0 && CanBlockBeGlobal(Info))
111ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
11285284bacSMike Stump 
1134446dcf0SMike Stump   std::vector<llvm::Constant*> Elts(5);
11485284bacSMike Stump   llvm::Constant *C;
115b750d928SMike Stump   llvm::Value *V;
11685284bacSMike Stump 
11785284bacSMike Stump   {
11885284bacSMike Stump     // C = BuildBlockStructInitlist();
11985284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
12085284bacSMike Stump 
1214446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
1224446dcf0SMike Stump     // block literal.
1234446dcf0SMike Stump     // __invoke
1244446dcf0SMike Stump     uint64_t subBlockSize, subBlockAlign;
1254446dcf0SMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
126d2142cffSMike Stump     bool subBlockHasCopyDispose = false;
1274446dcf0SMike Stump     llvm::Function *Fn
128692c6e37SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl, LocalDeclMap,
1295469f29aSMike Stump                                                    subBlockSize,
1304446dcf0SMike Stump                                                    subBlockAlign,
1314446dcf0SMike Stump                                                    subBlockDeclRefDecls,
132d2142cffSMike Stump                                                    subBlockHasCopyDispose);
133d2142cffSMike Stump     BlockHasCopyDispose |= subBlockHasCopyDispose;
1344446dcf0SMike Stump     Elts[3] = Fn;
1354446dcf0SMike Stump 
13618bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
13718bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
138d2142cffSMike Stump     if (subBlockHasCopyDispose)
13985284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
14085284bacSMike Stump 
141499ae7ecSMike Stump     // __isa
1427ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
143*ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1444446dcf0SMike Stump     Elts[0] = C;
14585284bacSMike Stump 
14685284bacSMike Stump     // __flags
14785284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
14885284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
149b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
1504446dcf0SMike Stump     Elts[1] = C;
15185284bacSMike Stump 
15285284bacSMike Stump     // __reserved
153b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
1544446dcf0SMike Stump     Elts[2] = C;
15585284bacSMike Stump 
156b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
157d6ef62f0SMike Stump       // __descriptor
158d2142cffSMike Stump       Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize, 0, 0);
159d6ef62f0SMike Stump 
1603a139f37SMike Stump       // Optimize to being a global block.
1613a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
162b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
1633a139f37SMike Stump 
1640e0189d6SOwen Anderson       C = llvm::ConstantStruct::get(Elts);
16585284bacSMike Stump 
16685284bacSMike Stump       char Name[32];
1679319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
168c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
16985284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
170c10c8d3eSOwen Anderson                                    C, Name);
1715d2534adSMike Stump       QualType BPT = BE->getType();
172*ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
17385284bacSMike Stump       return C;
17485284bacSMike Stump     }
17585284bacSMike Stump 
176b750d928SMike Stump     std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
177aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
178b750d928SMike Stump       Types[i] = Elts[i]->getType();
179aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
18085284bacSMike Stump 
1811db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
1821db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
1831db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
1841db7d04bSMike Stump       QualType Ty = E->getType();
18597d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
18697d01d50SMike Stump         uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
187170229f6SOwen Anderson         Types[i+5] = VMContext.getPointerType(BuildByRefType(Ty, Align), 0);
18897d01d50SMike Stump       } else
1891db7d04bSMike Stump         Types[i+5] = ConvertType(Ty);
1901db7d04bSMike Stump     }
191b750d928SMike Stump 
192170229f6SOwen Anderson     llvm::StructType *Ty = VMContext.getStructType(Types, true);
193b750d928SMike Stump 
194b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
195b750d928SMike Stump     A->setAlignment(subBlockAlign);
196b750d928SMike Stump     V = A;
197b750d928SMike Stump 
198aeb0ffd5SMike Stump     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
199aeb0ffd5SMike Stump     int helpersize = 0;
200aeb0ffd5SMike Stump 
201aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
202b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
203b750d928SMike Stump 
204b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
205b750d928SMike Stump       {
2061db7d04bSMike Stump         // FIXME: Push const down.
2071db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2081db7d04bSMike Stump         DeclRefExpr *DR;
2091db7d04bSMike Stump         ValueDecl *VD;
210b750d928SMike Stump 
2111db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2121db7d04bSMike Stump         // Skip padding.
2131db7d04bSMike Stump         if (DR) continue;
2141db7d04bSMike Stump 
2151db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2161db7d04bSMike Stump         VD = BDRE->getDecl();
2171db7d04bSMike Stump 
21897d01d50SMike Stump         llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
219aeb0ffd5SMike Stump         NoteForHelper[helpersize].index = i+5;
220aeb0ffd5SMike Stump         NoteForHelper[helpersize].RequiresCopying = BlockRequiresCopying(VD->getType());
221aeb0ffd5SMike Stump         NoteForHelper[helpersize].flag
222aeb0ffd5SMike Stump           = VD->getType()->isBlockPointerType() ? BLOCK_FIELD_IS_BLOCK : BLOCK_FIELD_IS_OBJECT;
223aeb0ffd5SMike Stump 
2241db7d04bSMike Stump         if (LocalDeclMap[VD]) {
22597d01d50SMike Stump           if (BDRE->isByRef()) {
226aeb0ffd5SMike Stump             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
22790d8daf5SMike Stump               // FIXME: Someone double check this.
22890d8daf5SMike Stump               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
22997d01d50SMike Stump             const llvm::Type *Ty = Types[i+5];
23097d01d50SMike Stump             llvm::Value *Loc = LocalDeclMap[VD];
23197d01d50SMike Stump             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
23297d01d50SMike Stump             Loc = Builder.CreateLoad(Loc, false);
23397d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
23497d01d50SMike Stump             Builder.CreateStore(Loc, Addr);
235aeb0ffd5SMike Stump             ++helpersize;
23697d01d50SMike Stump             continue;
23797d01d50SMike Stump           } else
2381db7d04bSMike Stump             E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
2391db7d04bSMike Stump                                                 VD->getType(), SourceLocation(),
2401db7d04bSMike Stump                                                 false, false);
2411db7d04bSMike Stump         }
24297d01d50SMike Stump         if (BDRE->isByRef()) {
243efd7caa8SMike Stump           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
244efd7caa8SMike Stump             // FIXME: Someone double check this.
245efd7caa8SMike Stump             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
2461db7d04bSMike Stump           E = new (getContext())
2471db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
2481db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
2491db7d04bSMike Stump                           SourceLocation());
25097d01d50SMike Stump         }
251aeb0ffd5SMike Stump         ++helpersize;
2521db7d04bSMike Stump 
2531db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
25497d01d50SMike Stump         if (r.isScalar()) {
25597d01d50SMike Stump           llvm::Value *Loc = r.getScalarVal();
25697d01d50SMike Stump           const llvm::Type *Ty = Types[i+5];
25797d01d50SMike Stump           if  (BDRE->isByRef()) {
2582d33d630SMike Stump             // E is now the address of the value field, instead, we want the
2592d33d630SMike Stump             // address of the actual ByRef struct.  We optimize this slightly
2602d33d630SMike Stump             // compared to gcc by not grabbing the forwarding slot as this must
2612d33d630SMike Stump             // be done during Block_copy for us, and we can postpone the work
2622d33d630SMike Stump             // until then.
2632d33d630SMike Stump             uint64_t offset = BlockDecls[BDRE->getDecl()];
2642d33d630SMike Stump 
2652d33d630SMike Stump             llvm::Value *BlockLiteral = LoadBlockStruct();
2662d33d630SMike Stump 
2672d33d630SMike Stump             Loc = Builder.CreateGEP(BlockLiteral,
268b7a2fe6fSOwen Anderson                                   llvm::ConstantInt::get(llvm::Type::Int64Ty,
2692d33d630SMike Stump                                                            offset),
2702d33d630SMike Stump                                     "block.literal");
271170229f6SOwen Anderson             Ty = VMContext.getPointerType(Ty, 0);
27297d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
2732d33d630SMike Stump             Loc = Builder.CreateLoad(Loc, false);
2742d33d630SMike Stump             // Loc = Builder.CreateBitCast(Loc, Ty);
27597d01d50SMike Stump           }
27697d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
27797d01d50SMike Stump         } else if (r.isComplex())
278b750d928SMike Stump           // FIXME: implement
279b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
280b750d928SMike Stump         else if (r.isAggregate())
281b750d928SMike Stump           ; // Already created into the destination
282b750d928SMike Stump         else
283b750d928SMike Stump           assert (0 && "bad block variable");
284b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
285b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
286b750d928SMike Stump       }
287aeb0ffd5SMike Stump     NoteForHelper.resize(helpersize);
288d6ef62f0SMike Stump 
289d6ef62f0SMike Stump     // __descriptor
290d2142cffSMike Stump     llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
291d2142cffSMike Stump                                                        subBlockSize, Ty,
292aeb0ffd5SMike Stump                                                        &NoteForHelper);
293aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
294aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
295b750d928SMike Stump   }
296b750d928SMike Stump 
297b750d928SMike Stump   QualType BPT = BE->getType();
298b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
299b750d928SMike Stump }
30085284bacSMike Stump 
30185284bacSMike Stump 
30295435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
303650c932dSMike Stump   if (BlockDescriptorType)
304650c932dSMike Stump     return BlockDescriptorType;
3052437cbfaSAnders Carlsson 
3062437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
307650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3082437cbfaSAnders Carlsson 
3092437cbfaSAnders Carlsson   // struct __block_descriptor {
3102437cbfaSAnders Carlsson   //   unsigned long reserved;
3112437cbfaSAnders Carlsson   //   unsigned long block_size;
3122437cbfaSAnders Carlsson   // };
313170229f6SOwen Anderson   BlockDescriptorType = VMContext.getStructType(UnsignedLongTy,
3142437cbfaSAnders Carlsson                                               UnsignedLongTy,
3152437cbfaSAnders Carlsson                                               NULL);
3162437cbfaSAnders Carlsson 
317650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
318650c932dSMike Stump                           BlockDescriptorType);
3192437cbfaSAnders Carlsson 
320650c932dSMike Stump   return BlockDescriptorType;
3212437cbfaSAnders Carlsson }
3222437cbfaSAnders Carlsson 
32395435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
324005c9a62SMike Stump   if (GenericBlockLiteralType)
325005c9a62SMike Stump     return GenericBlockLiteralType;
3262437cbfaSAnders Carlsson 
3272437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
328170229f6SOwen Anderson     VMContext.getPointerTypeUnqual(getBlockDescriptorType());
3292437cbfaSAnders Carlsson 
33092bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
33192bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
33292bbd6d4SMike Stump 
3332437cbfaSAnders Carlsson   // struct __block_literal_generic {
3345d2534adSMike Stump   //   void *__isa;
3355d2534adSMike Stump   //   int __flags;
3365d2534adSMike Stump   //   int __reserved;
3375d2534adSMike Stump   //   void (*__invoke)(void *);
3385d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3392437cbfaSAnders Carlsson   // };
340170229f6SOwen Anderson   GenericBlockLiteralType = VMContext.getStructType(PtrToInt8Ty,
34192bbd6d4SMike Stump                                                   IntTy,
34292bbd6d4SMike Stump                                                   IntTy,
343626aecc4SMike Stump                                                   PtrToInt8Ty,
3442437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
3452437cbfaSAnders Carlsson                                                   NULL);
3462437cbfaSAnders Carlsson 
347005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
348005c9a62SMike Stump                           GenericBlockLiteralType);
3492437cbfaSAnders Carlsson 
350005c9a62SMike Stump   return GenericBlockLiteralType;
3512437cbfaSAnders Carlsson }
3522437cbfaSAnders Carlsson 
35395435674SMike Stump const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
3545d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
3555d2534adSMike Stump     return GenericExtendedBlockLiteralType;
3565d2534adSMike Stump 
3575d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
358170229f6SOwen Anderson     VMContext.getPointerTypeUnqual(getBlockDescriptorType());
3595d2534adSMike Stump 
3605d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
3615d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
3625d2534adSMike Stump 
3635d2534adSMike Stump   // struct __block_literal_generic {
3645d2534adSMike Stump   //   void *__isa;
3655d2534adSMike Stump   //   int __flags;
3665d2534adSMike Stump   //   int __reserved;
3675d2534adSMike Stump   //   void (*__invoke)(void *);
3685d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3695d2534adSMike Stump   //   void *__copy_func_helper_decl;
3705d2534adSMike Stump   //   void *__destroy_func_decl;
3715d2534adSMike Stump   // };
372170229f6SOwen Anderson   GenericExtendedBlockLiteralType = VMContext.getStructType(PtrToInt8Ty,
3735d2534adSMike Stump                                                           IntTy,
3745d2534adSMike Stump                                                           IntTy,
375626aecc4SMike Stump                                                           PtrToInt8Ty,
3765d2534adSMike Stump                                                           BlockDescPtrTy,
377626aecc4SMike Stump                                                           PtrToInt8Ty,
378626aecc4SMike Stump                                                           PtrToInt8Ty,
3795d2534adSMike Stump                                                           NULL);
3805d2534adSMike Stump 
3815d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
3825d2534adSMike Stump                           GenericExtendedBlockLiteralType);
3835d2534adSMike Stump 
3845d2534adSMike Stump   return GenericExtendedBlockLiteralType;
3855d2534adSMike Stump }
3865d2534adSMike Stump 
3876a60fa24SAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
3882437cbfaSAnders Carlsson   const BlockPointerType *BPT =
3898a286fbdSTed Kremenek     E->getCallee()->getType()->getAsBlockPointerType();
3902437cbfaSAnders Carlsson 
3912437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
3922437cbfaSAnders Carlsson 
3932437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
3942437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
395170229f6SOwen Anderson     VMContext.getPointerTypeUnqual(CGM.getGenericBlockLiteralType());
3962437cbfaSAnders Carlsson 
3972437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
3982437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
3992437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4002437cbfaSAnders Carlsson 
4012437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4022437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
4032437cbfaSAnders Carlsson 
4042437cbfaSAnders Carlsson   BlockLiteral =
4052437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
406170229f6SOwen Anderson                           VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty),
4072437cbfaSAnders Carlsson                           "tmp");
4082437cbfaSAnders Carlsson 
4092437cbfaSAnders Carlsson   // Add the block literal.
4102437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4112437cbfaSAnders Carlsson   CallArgList Args;
4122437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4132437cbfaSAnders Carlsson 
414479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
415479e6fc7SAnders Carlsson 
4162437cbfaSAnders Carlsson   // And the rest of the arguments.
417479e6fc7SAnders Carlsson   EmitCallArgs(Args, FnType->getAsFunctionProtoType(),
418479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
4192437cbfaSAnders Carlsson 
4205f50c651SAnders Carlsson   // Load the function.
4215f50c651SAnders Carlsson   llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
4225f50c651SAnders Carlsson 
423a60cbcdfSAnders Carlsson   QualType ResultType = FnType->getAsFunctionType()->getResultType();
424a60cbcdfSAnders Carlsson 
425a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
426a60cbcdfSAnders Carlsson     CGM.getTypes().getFunctionInfo(ResultType, Args);
4275f50c651SAnders Carlsson 
4285f50c651SAnders Carlsson   // Cast the function pointer to the right type.
4295f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
430a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
4315f50c651SAnders Carlsson 
432170229f6SOwen Anderson   const llvm::Type *BlockFTyPtr = VMContext.getPointerTypeUnqual(BlockFTy);
4335f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
4345f50c651SAnders Carlsson 
4352437cbfaSAnders Carlsson   // And call the block.
436350da607SAnders Carlsson   return EmitCall(FnInfo, Func, Args);
4372437cbfaSAnders Carlsson }
4386a60fa24SAnders Carlsson 
43997d01d50SMike Stump llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
44097d01d50SMike Stump   uint64_t &offset = BlockDecls[E->getDecl()];
44197d01d50SMike Stump 
44297d01d50SMike Stump   const llvm::Type *Ty;
44397d01d50SMike Stump   Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
44497d01d50SMike Stump 
44597d01d50SMike Stump   // See if we have already allocated an offset for this variable.
44697d01d50SMike Stump   if (offset == 0) {
4474446dcf0SMike Stump     // Don't run the expensive check, unless we have to.
4484446dcf0SMike Stump     if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
4494446dcf0SMike Stump       BlockHasCopyDispose = true;
45097d01d50SMike Stump     // if not, allocate one now.
45197d01d50SMike Stump     offset = getBlockOffset(E);
45297d01d50SMike Stump   }
45397d01d50SMike Stump 
45497d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
45597d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
456b7a2fe6fSOwen Anderson                                   llvm::ConstantInt::get(llvm::Type::Int64Ty,
45797d01d50SMike Stump                                                             offset),
4582d33d630SMike Stump                                      "block.literal");
45997d01d50SMike Stump   if (E->isByRef()) {
46097d01d50SMike Stump     bool needsCopyDispose = BlockRequiresCopying(E->getType());
46197d01d50SMike Stump     uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
46297d01d50SMike Stump     const llvm::Type *PtrStructTy
463170229f6SOwen Anderson       = VMContext.getPointerType(BuildByRefType(E->getType(), Align), 0);
464efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
465efd7caa8SMike Stump     BlockHasCopyDispose = true;
46697d01d50SMike Stump     Ty = PtrStructTy;
467170229f6SOwen Anderson     Ty = VMContext.getPointerType(Ty, 0);
46897d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
46997d01d50SMike Stump     V = Builder.CreateLoad(V, false);
47097d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
47197d01d50SMike Stump     V = Builder.CreateLoad(V, false);
47297d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
47397d01d50SMike Stump     V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
47497d01d50SMike Stump   } else {
475170229f6SOwen Anderson     Ty = VMContext.getPointerType(Ty, 0);
47697d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
47797d01d50SMike Stump   }
47897d01d50SMike Stump   return V;
47997d01d50SMike Stump }
48097d01d50SMike Stump 
481692c6e37SMike Stump void CodeGenFunction::BlockForwardSelf() {
482692c6e37SMike Stump   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
483692c6e37SMike Stump   ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
484692c6e37SMike Stump   llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
485692c6e37SMike Stump   if (DMEntry)
486692c6e37SMike Stump     return;
487692c6e37SMike Stump   // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
488692c6e37SMike Stump   BlockDeclRefExpr *BDRE = new (getContext())
489692c6e37SMike Stump     BlockDeclRefExpr(SelfDecl,
490692c6e37SMike Stump                      SelfDecl->getType(), SourceLocation(), false);
491692c6e37SMike Stump   DMEntry = GetAddrOfBlockDecl(BDRE);
492692c6e37SMike Stump }
493692c6e37SMike Stump 
4942d5a2878SMike Stump llvm::Constant *
4956c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
4966a60fa24SAnders Carlsson   // Generate the block descriptor.
4976a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
49892bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
49992bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
5006a60fa24SAnders Carlsson 
5016a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
5026a60fa24SAnders Carlsson 
5036a60fa24SAnders Carlsson   // Reserved
504ae86c19eSOwen Anderson   DescriptorFields[0] = getModule().getContext().getNullValue(UnsignedLongTy);
5056a60fa24SAnders Carlsson 
5066a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
5076a60fa24SAnders Carlsson   // block literal struct.
5086a60fa24SAnders Carlsson   uint64_t BlockLiteralSize =
509005c9a62SMike Stump     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
510170229f6SOwen Anderson   DescriptorFields[1] =
511b7a2fe6fSOwen Anderson                       llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
5126a60fa24SAnders Carlsson 
5136a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
5140e0189d6SOwen Anderson     llvm::ConstantStruct::get(&DescriptorFields[0], 2);
5156a60fa24SAnders Carlsson 
5166a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
517c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
5186a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
519c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
5206a60fa24SAnders Carlsson 
5216a60fa24SAnders Carlsson   // Generate the constants for the block literal.
5226a60fa24SAnders Carlsson   llvm::Constant *LiteralFields[5];
5236a60fa24SAnders Carlsson 
5242d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
525b750d928SMike Stump   uint64_t subBlockSize, subBlockAlign;
5261db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
527a61bb4d1SDaniel Dunbar   bool subBlockHasCopyDispose = false;
5285469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
529cb2fbcb0SMike Stump   llvm::Function *Fn
530692c6e37SMike Stump     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
5315469f29aSMike Stump                                                  subBlockSize,
532b750d928SMike Stump                                                  subBlockAlign,
5334446dcf0SMike Stump                                                  subBlockDeclRefDecls,
5344446dcf0SMike Stump                                                  subBlockHasCopyDispose);
535cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
536cb2fbcb0SMike Stump          && "no imports allowed for global block");
5376a60fa24SAnders Carlsson 
5386a60fa24SAnders Carlsson   // isa
539971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
5406a60fa24SAnders Carlsson 
5416a60fa24SAnders Carlsson   // Flags
5425878c797SAnders Carlsson   LiteralFields[1] =
543b7a2fe6fSOwen Anderson     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
5446a60fa24SAnders Carlsson 
5456a60fa24SAnders Carlsson   // Reserved
546ae86c19eSOwen Anderson   LiteralFields[2] = getModule().getContext().getNullValue(IntTy);
5476a60fa24SAnders Carlsson 
5486a60fa24SAnders Carlsson   // Function
5496a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
5506a60fa24SAnders Carlsson 
5516a60fa24SAnders Carlsson   // Descriptor
5526a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
5536a60fa24SAnders Carlsson 
5546a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
5550e0189d6SOwen Anderson     llvm::ConstantStruct::get(&LiteralFields[0], 5);
5566a60fa24SAnders Carlsson 
5576a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
558c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
5596a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
560c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
5616a60fa24SAnders Carlsson 
5626a60fa24SAnders Carlsson   return BlockLiteral;
5636a60fa24SAnders Carlsson }
5646a60fa24SAnders Carlsson 
565cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
566cb2fbcb0SMike Stump   return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
567cb2fbcb0SMike Stump }
568cb2fbcb0SMike Stump 
5694446dcf0SMike Stump llvm::Function *
5704446dcf0SMike Stump CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
571cb2fbcb0SMike Stump                                        const BlockInfo& Info,
572692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
5735469f29aSMike Stump                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm,
574b750d928SMike Stump                                        uint64_t &Size,
575b750d928SMike Stump                                        uint64_t &Align,
5764446dcf0SMike Stump                        llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
5774446dcf0SMike Stump                                        bool &subBlockHasCopyDispose) {
5789074ed8cSDevang Patel 
5799074ed8cSDevang Patel   // Check if we should generate debug info for this block.
5809074ed8cSDevang Patel   if (CGM.getDebugInfo())
5819074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
5829074ed8cSDevang Patel 
5835469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
5845469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
5855469f29aSMike Stump   // in a block.
5865469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
5875469f29aSMike Stump        i != ldm.end();
5885469f29aSMike Stump        ++i) {
5895469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
5905469f29aSMike Stump 
5910ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
5925469f29aSMike Stump       LocalDeclMap[VD] = i->second;
5935469f29aSMike Stump   }
5945469f29aSMike Stump 
59509a9b6e3SEli Friedman   // FIXME: We need to rearrange the code for copy/dispose so we have this
59609a9b6e3SEli Friedman   // sooner, so we can calculate offsets correctly.
59709a9b6e3SEli Friedman   if (!BlockHasCopyDispose)
59809a9b6e3SEli Friedman     BlockOffset = CGM.getTargetData()
59909a9b6e3SEli Friedman       .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
60009a9b6e3SEli Friedman   else
60109a9b6e3SEli Friedman     BlockOffset = CGM.getTargetData()
60209a9b6e3SEli Friedman       .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
60309a9b6e3SEli Friedman   BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
60409a9b6e3SEli Friedman 
605aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
606aae4349dSFariborz Jahanian   QualType ResultType;
607aae4349dSFariborz Jahanian   bool IsVariadic;
608a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
609a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
610aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
611aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
612aae4349dSFariborz Jahanian   }
613aae4349dSFariborz Jahanian   else {
614aae4349dSFariborz Jahanian     // K&R style block.
615aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
616aae4349dSFariborz Jahanian     IsVariadic = false;
617aae4349dSFariborz Jahanian   }
6186a60fa24SAnders Carlsson 
6196a60fa24SAnders Carlsson   FunctionArgList Args;
6206a60fa24SAnders Carlsson 
6213385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
6226a60fa24SAnders Carlsson 
6236a60fa24SAnders Carlsson   // FIXME: This leaks
6246a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
6256a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
6266a60fa24SAnders Carlsson                               SourceLocation(), 0,
6276a60fa24SAnders Carlsson                               getContext().getPointerType(getContext().VoidTy));
6286a60fa24SAnders Carlsson 
6296a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
630cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
6316a60fa24SAnders Carlsson 
632c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
6336a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
634eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
6356a60fa24SAnders Carlsson 
6366a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
637aae4349dSFariborz Jahanian     CGM.getTypes().getFunctionInfo(ResultType, Args);
6386a60fa24SAnders Carlsson 
6392d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
6406a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
641aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
6426a60fa24SAnders Carlsson 
6436a60fa24SAnders Carlsson   llvm::Function *Fn =
6446a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
6456a60fa24SAnders Carlsson                            Name,
6466a60fa24SAnders Carlsson                            &CGM.getModule());
6476a60fa24SAnders Carlsson 
648c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
649c3e7cff6SDaniel Dunbar 
650324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
6513385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
652324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
65328ec0cf8SChris Lattner   CurCodeDecl = BD;
6543385fe12SChris Lattner   EmitStmt(BExpr->getBody());
6553385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
6566a60fa24SAnders Carlsson 
657b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
658b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
659b750d928SMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
660b750d928SMike Stump 
661cb2fbcb0SMike Stump   Size = BlockOffset;
662b750d928SMike Stump   Align = BlockAlign;
663b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
6644446dcf0SMike Stump   subBlockHasCopyDispose |= BlockHasCopyDispose;
6656a60fa24SAnders Carlsson   return Fn;
6666a60fa24SAnders Carlsson }
6671db7d04bSMike Stump 
668aeb0ffd5SMike Stump uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
6691db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
6701db7d04bSMike Stump 
6711db7d04bSMike Stump   uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
6721db7d04bSMike Stump   uint64_t Align = getContext().getDeclAlignInBytes(D);
6731db7d04bSMike Stump 
6741db7d04bSMike Stump   if (BDRE->isByRef()) {
6751db7d04bSMike Stump     Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
6761db7d04bSMike Stump     Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
6771db7d04bSMike Stump   }
6781db7d04bSMike Stump 
6791db7d04bSMike Stump   assert ((Align > 0) && "alignment must be 1 byte or more");
6801db7d04bSMike Stump 
6811db7d04bSMike Stump   uint64_t OldOffset = BlockOffset;
6821db7d04bSMike Stump 
6831db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
6841db7d04bSMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
6851db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
6861db7d04bSMike Stump 
6871db7d04bSMike Stump   uint64_t Pad = BlockOffset - OldOffset;
6881db7d04bSMike Stump   if (Pad) {
689170229f6SOwen Anderson     VMContext.getArrayType(llvm::Type::Int8Ty, Pad);
6901db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
6911db7d04bSMike Stump                                                        llvm::APInt(32, Pad),
6921db7d04bSMike Stump                                                        ArrayType::Normal, 0);
6931db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
6941db7d04bSMike Stump                                          0, QualType(PadTy), VarDecl::None,
6951db7d04bSMike Stump                                          SourceLocation());
6961db7d04bSMike Stump     Expr *E;
6971db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
6981db7d04bSMike Stump                                        SourceLocation(), false, false);
6991db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
7001db7d04bSMike Stump   }
7011db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
7021db7d04bSMike Stump 
7031db7d04bSMike Stump   BlockOffset += Size;
7041db7d04bSMike Stump   return BlockOffset-Size;
7051db7d04bSMike Stump }
70697d01d50SMike Stump 
707aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
708aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
70967645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
7100c743277SMike Stump   QualType R = getContext().VoidTy;
7110c743277SMike Stump 
7120c743277SMike Stump   FunctionArgList Args;
7130c743277SMike Stump   // FIXME: This leaks
714aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
715aeb0ffd5SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
716aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
717aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
7180c743277SMike Stump   ImplicitParamDecl *Src =
7190c743277SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
7200c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
7210c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
7220c743277SMike Stump 
7230c743277SMike Stump   const CGFunctionInfo &FI =
7240c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
7250c743277SMike Stump 
726cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
727cbc2bcafSMike Stump   // internal linkage.
7280c743277SMike Stump   std::string Name = std::string("__copy_helper_block_");
7290c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
7300c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
7310c743277SMike Stump 
7320c743277SMike Stump   llvm::Function *Fn =
7330c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
7340c743277SMike Stump                            Name,
7350c743277SMike Stump                            &CGM.getModule());
7360c743277SMike Stump 
7370c743277SMike Stump   IdentifierInfo *II
7380c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
7390c743277SMike Stump 
7400c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
7410c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
7420c743277SMike Stump                                           SourceLocation(), II, R,
7430c743277SMike Stump                                           FunctionDecl::Static, false,
7440c743277SMike Stump                                           true);
7450c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
746aeb0ffd5SMike Stump 
747aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
748aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
74967645930SMike Stump 
75067645930SMike Stump   if (NoteForHelperp) {
75167645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
75267645930SMike Stump 
753170229f6SOwen Anderson     PtrPtrT = VMContext.getPointerType(VMContext.getPointerType(T, 0), 0);
754aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
755aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
756aeb0ffd5SMike Stump 
757aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
7583b65ac26SMike Stump     llvm::Type *PtrPtrT;
759170229f6SOwen Anderson     PtrPtrT = VMContext.getPointerType(VMContext.getPointerType(T, 0), 0);
7603b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
7613b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
762aeb0ffd5SMike Stump 
763aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
764aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
765aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
766aeb0ffd5SMike Stump 
767aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
768aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
769aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
770aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
771aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
772170229f6SOwen Anderson                                      VMContext.getPointerType(PtrToInt8Ty, 0));
773aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
774aeb0ffd5SMike Stump 
775aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
776aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
777aeb0ffd5SMike Stump 
778b7a2fe6fSOwen Anderson         llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
779aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
780aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
781aeb0ffd5SMike Stump       }
782aeb0ffd5SMike Stump     }
78367645930SMike Stump   }
784aeb0ffd5SMike Stump 
7850c743277SMike Stump   CGF.FinishFunction();
7860c743277SMike Stump 
787*ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
78897d01d50SMike Stump }
78997d01d50SMike Stump 
790d6ef62f0SMike Stump llvm::Constant *BlockFunction::
791aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
792aeb0ffd5SMike Stump                               const llvm::StructType* T,
79367645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
7940c743277SMike Stump   QualType R = getContext().VoidTy;
7950c743277SMike Stump 
7960c743277SMike Stump   FunctionArgList Args;
7970c743277SMike Stump   // FIXME: This leaks
7980c743277SMike Stump   ImplicitParamDecl *Src =
7990c743277SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
8000c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
8010c743277SMike Stump 
8020c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
8030c743277SMike Stump 
8040c743277SMike Stump   const CGFunctionInfo &FI =
8050c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
8060c743277SMike Stump 
807cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
808cbc2bcafSMike Stump   // internal linkage.
8090c743277SMike Stump   std::string Name = std::string("__destroy_helper_block_");
8100c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
8110c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8120c743277SMike Stump 
8130c743277SMike Stump   llvm::Function *Fn =
8140c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
8150c743277SMike Stump                            Name,
8160c743277SMike Stump                            &CGM.getModule());
8170c743277SMike Stump 
8180c743277SMike Stump   IdentifierInfo *II
8190c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
8200c743277SMike Stump 
8210c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8220c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
8230c743277SMike Stump                                           SourceLocation(), II, R,
8240c743277SMike Stump                                           FunctionDecl::Static, false,
8250c743277SMike Stump                                           true);
8260c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
8276f7d9f87SMike Stump 
82867645930SMike Stump   if (NoteForHelperp) {
82967645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
83067645930SMike Stump 
8316f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
8326f7d9f87SMike Stump     llvm::Type *PtrPtrT;
833170229f6SOwen Anderson     PtrPtrT = VMContext.getPointerType(VMContext.getPointerType(T, 0), 0);
8346f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
8356f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
8366f7d9f87SMike Stump 
8376f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
8386f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
8396f7d9f87SMike Stump       int index = NoteForHelper[i].index;
8406f7d9f87SMike Stump 
8416f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
8426f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
8436f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
8446f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
8456f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
846170229f6SOwen Anderson                                      VMContext.getPointerType(PtrToInt8Ty, 0));
8476f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
8486f7d9f87SMike Stump 
8496f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
8506f7d9f87SMike Stump       }
8516f7d9f87SMike Stump     }
85267645930SMike Stump   }
8536f7d9f87SMike Stump 
8540c743277SMike Stump   CGF.FinishFunction();
8550c743277SMike Stump 
856*ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
8570c743277SMike Stump }
8580c743277SMike Stump 
859aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
86067645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
861aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
862aeb0ffd5SMike Stump                                                          T, NoteForHelper);
8630c743277SMike Stump }
8640c743277SMike Stump 
865aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
86667645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
867aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
86867645930SMike Stump                                                             T, NoteForHelperp);
86997d01d50SMike Stump }
870626aecc4SMike Stump 
871f89230d9SMike Stump llvm::Constant *BlockFunction::
872f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
873ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
874ee2a5ee5SMike Stump 
875ee2a5ee5SMike Stump   FunctionArgList Args;
876ee2a5ee5SMike Stump   // FIXME: This leaks
877f89230d9SMike Stump   ImplicitParamDecl *Dst =
878f89230d9SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
879f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
880f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
881f89230d9SMike Stump 
882f89230d9SMike Stump   // FIXME: This leaks
883ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
884ee2a5ee5SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
885ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
886ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
887ee2a5ee5SMike Stump 
888ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
889ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
890ee2a5ee5SMike Stump 
891ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_copy_");
892ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
893ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
894ee2a5ee5SMike Stump 
895cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
896cbc2bcafSMike Stump   // internal linkage.
897ee2a5ee5SMike Stump   llvm::Function *Fn =
898ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
899ee2a5ee5SMike Stump                            Name,
900ee2a5ee5SMike Stump                            &CGM.getModule());
901ee2a5ee5SMike Stump 
902ee2a5ee5SMike Stump   IdentifierInfo *II
903ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
904ee2a5ee5SMike Stump 
905ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
906ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
907ee2a5ee5SMike Stump                                           SourceLocation(), II, R,
908ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
909ee2a5ee5SMike Stump                                           true);
910ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
911f89230d9SMike Stump 
912f89230d9SMike Stump   // dst->x
913f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
914170229f6SOwen Anderson   V = Builder.CreateBitCast(V, VMContext.getPointerType(T, 0));
9153b65ac26SMike Stump   V = Builder.CreateLoad(V);
916f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
917f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
918f89230d9SMike Stump 
919f89230d9SMike Stump   // src->x
920f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
921f89230d9SMike Stump   V = Builder.CreateLoad(V);
922f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
923f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
924170229f6SOwen Anderson   V = Builder.CreateBitCast(V, VMContext.getPointerType(PtrToInt8Ty, 0));
925f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
926f89230d9SMike Stump 
927f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
928f89230d9SMike Stump 
929b7a2fe6fSOwen Anderson   llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
930f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
931f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
932f89230d9SMike Stump 
933ee2a5ee5SMike Stump   CGF.FinishFunction();
934ee2a5ee5SMike Stump 
935*ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
936ee2a5ee5SMike Stump }
937ee2a5ee5SMike Stump 
938fbe25dd1SMike Stump llvm::Constant *
939fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
940fbe25dd1SMike Stump                                                   int flag) {
941ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
942ee2a5ee5SMike Stump 
943ee2a5ee5SMike Stump   FunctionArgList Args;
944ee2a5ee5SMike Stump   // FIXME: This leaks
945ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
946ee2a5ee5SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
947ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
948ee2a5ee5SMike Stump 
949ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
950ee2a5ee5SMike Stump 
951ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
952ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
953ee2a5ee5SMike Stump 
954ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_dispose_");
955ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
956ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
957ee2a5ee5SMike Stump 
958cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
959cbc2bcafSMike Stump   // internal linkage.
960ee2a5ee5SMike Stump   llvm::Function *Fn =
961ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
962ee2a5ee5SMike Stump                            Name,
963ee2a5ee5SMike Stump                            &CGM.getModule());
964ee2a5ee5SMike Stump 
965ee2a5ee5SMike Stump   IdentifierInfo *II
966ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
967ee2a5ee5SMike Stump 
968ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
969ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
970ee2a5ee5SMike Stump                                           SourceLocation(), II, R,
971ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
972ee2a5ee5SMike Stump                                           true);
973ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
974fbe25dd1SMike Stump 
975fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
976170229f6SOwen Anderson   V = Builder.CreateBitCast(V, VMContext.getPointerType(T, 0));
9773b65ac26SMike Stump   V = Builder.CreateLoad(V);
978fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
979170229f6SOwen Anderson   V = Builder.CreateBitCast(V, VMContext.getPointerType(PtrToInt8Ty, 0));
9803b65ac26SMike Stump   V = Builder.CreateLoad(V);
981fbe25dd1SMike Stump 
982fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
983fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
984ee2a5ee5SMike Stump   CGF.FinishFunction();
985ee2a5ee5SMike Stump 
986*ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
987ee2a5ee5SMike Stump }
988ee2a5ee5SMike Stump 
989f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
990cbc2bcafSMike Stump                                                     int flag, unsigned Align) {
991cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
992cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
993cbc2bcafSMike Stump   // with.
994cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
995cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
996cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
997cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
998cbc2bcafSMike Stump   uint64_t kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + flag;
999cbc2bcafSMike Stump   llvm::Constant *& Entry = CGM.AssignCache[kind];
1000cbc2bcafSMike Stump   if (Entry)
1001cbc2bcafSMike Stump     return Entry;
1002cbc2bcafSMike Stump   return Entry=CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
1003ee2a5ee5SMike Stump }
1004ee2a5ee5SMike Stump 
1005fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1006cbc2bcafSMike Stump                                                        int flag,
1007cbc2bcafSMike Stump                                                        unsigned Align) {
1008cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1009cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1010cbc2bcafSMike Stump   // with.
1011cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1012cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1013cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1014cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1015cbc2bcafSMike Stump   uint64_t kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + flag;
1016cbc2bcafSMike Stump   llvm::Constant *& Entry = CGM.DestroyCache[kind];
1017cbc2bcafSMike Stump   if (Entry)
1018cbc2bcafSMike Stump     return Entry;
1019cbc2bcafSMike Stump   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
1020ee2a5ee5SMike Stump }
1021ee2a5ee5SMike Stump 
1022626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1023626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1024626aecc4SMike Stump     const llvm::FunctionType *FTy;
1025626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
1026626aecc4SMike Stump     const llvm::Type *ResultType = llvm::Type::VoidTy;
1027626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1028626aecc4SMike Stump     ArgTys.push_back(llvm::Type::Int32Ty);
1029170229f6SOwen Anderson     FTy = VMContext.getFunctionType(ResultType, ArgTys, false);
1030626aecc4SMike Stump     CGM.BlockObjectDispose
1031626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1032626aecc4SMike Stump   }
1033626aecc4SMike Stump   return CGM.BlockObjectDispose;
1034626aecc4SMike Stump }
1035626aecc4SMike Stump 
1036f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1037f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1038f89230d9SMike Stump     const llvm::FunctionType *FTy;
1039f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
1040f89230d9SMike Stump     const llvm::Type *ResultType = llvm::Type::VoidTy;
1041f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1042f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1043f89230d9SMike Stump     ArgTys.push_back(llvm::Type::Int32Ty);
1044170229f6SOwen Anderson     FTy = VMContext.getFunctionType(ResultType, ArgTys, false);
1045f89230d9SMike Stump     CGM.BlockObjectAssign
1046f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1047f89230d9SMike Stump   }
1048f89230d9SMike Stump   return CGM.BlockObjectAssign;
1049f89230d9SMike Stump }
1050f89230d9SMike Stump 
1051fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1052626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1053fbe25dd1SMike Stump   llvm::Value *N;
1054626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
1055b7a2fe6fSOwen Anderson   N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
1056626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1057626aecc4SMike Stump }
10584446dcf0SMike Stump 
10594446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1060aeb0ffd5SMike Stump 
1061aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1062aeb0ffd5SMike Stump                              CGBuilderTy &B)
1063170229f6SOwen Anderson   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
1064170229f6SOwen Anderson   PtrToInt8Ty = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
1065aeb0ffd5SMike Stump 
1066aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1067aeb0ffd5SMike Stump }
1068