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 
142e722b91SMike Stump #include "CGDebugInfo.h"
152437cbfaSAnders Carlsson #include "CodeGenFunction.h"
162437cbfaSAnders Carlsson #include "CodeGenModule.h"
17692c6e37SMike Stump #include "clang/AST/DeclObjC.h"
182437cbfaSAnders Carlsson #include "llvm/Module.h"
196a60fa24SAnders Carlsson #include "llvm/Target/TargetData.h"
202437cbfaSAnders Carlsson #include <algorithm>
21db714924STorok Edwin #include <cstdio>
22db714924STorok Edwin 
232437cbfaSAnders Carlsson using namespace clang;
242437cbfaSAnders Carlsson using namespace CodeGen;
252437cbfaSAnders Carlsson 
26d6ef62f0SMike Stump llvm::Constant *CodeGenFunction::
27*40775003SKen Dyck BuildDescriptorBlockDecl(bool BlockHasCopyDispose, CharUnits Size,
28d2142cffSMike Stump                          const llvm::StructType* Ty,
29aeb0ffd5SMike Stump                          std::vector<HelperInfo> *NoteForHelper) {
30c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
31c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
3285284bacSMike Stump   llvm::Constant *C;
3385284bacSMike Stump   std::vector<llvm::Constant*> Elts;
3485284bacSMike Stump 
3585284bacSMike Stump   // reserved
36b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
3785284bacSMike Stump   Elts.push_back(C);
3885284bacSMike Stump 
3985284bacSMike Stump   // Size
402ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
412ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
422ac40a9fSMike Stump   // API to size_t.
43*40775003SKen Dyck   C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
4485284bacSMike Stump   Elts.push_back(C);
4585284bacSMike Stump 
4685284bacSMike Stump   if (BlockHasCopyDispose) {
4785284bacSMike Stump     // copy_func_helper_decl
4867645930SMike Stump     Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
4985284bacSMike Stump 
5085284bacSMike Stump     // destroy_func_decl
5167645930SMike Stump     Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
5285284bacSMike Stump   }
5385284bacSMike Stump 
5441eaf0acSNick Lewycky   C = llvm::ConstantStruct::get(VMContext, Elts, false);
5585284bacSMike Stump 
56c10c8d3eSOwen Anderson   C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
5785284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
58c10c8d3eSOwen Anderson                                C, "__block_descriptor_tmp");
5985284bacSMike Stump   return C;
6085284bacSMike Stump }
6185284bacSMike Stump 
6295435674SMike Stump llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
6346813bbfSChris Lattner   if (NSConcreteGlobalBlock == 0)
6446813bbfSChris Lattner     NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
6546813bbfSChris Lattner                                                       "_NSConcreteGlobalBlock");
66971f9b66SMike Stump   return NSConcreteGlobalBlock;
67971f9b66SMike Stump }
68971f9b66SMike Stump 
6995435674SMike Stump llvm::Constant *BlockModule::getNSConcreteStackBlock() {
7046813bbfSChris Lattner   if (NSConcreteStackBlock == 0)
7146813bbfSChris Lattner     NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
7246813bbfSChris Lattner                                                      "_NSConcreteStackBlock");
737ab278dbSMike Stump   return NSConcreteStackBlock;
747ab278dbSMike Stump }
757ab278dbSMike Stump 
76066b6166SMike Stump static void CollectBlockDeclRefInfo(
77066b6166SMike Stump   const Stmt *S, CodeGenFunction::BlockInfo &Info,
78066b6166SMike Stump   llvm::SmallSet<const DeclContext *, 16> &InnerContexts) {
79ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
80ed5e69feSAnders Carlsson        I != E; ++I)
81dd942713SDaniel Dunbar     if (*I)
82066b6166SMike Stump       CollectBlockDeclRefInfo(*I, Info, InnerContexts);
83ed5e69feSAnders Carlsson 
847fe9cc1dSMike Stump   // We want to ensure we walk down into block literals so we can find
857fe9cc1dSMike Stump   // all nested BlockDeclRefExprs.
86066b6166SMike Stump   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
87066b6166SMike Stump     InnerContexts.insert(cast<DeclContext>(BE->getBlockDecl()));
88066b6166SMike Stump     CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
89066b6166SMike Stump   }
907fe9cc1dSMike Stump 
91066b6166SMike Stump   if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
92ed5e69feSAnders Carlsson     // FIXME: Handle enums.
93066b6166SMike Stump     if (isa<FunctionDecl>(BDRE->getDecl()))
94ed5e69feSAnders Carlsson       return;
95ed5e69feSAnders Carlsson 
96066b6166SMike Stump     // Only Decls that escape are added.
97066b6166SMike Stump     if (!InnerContexts.count(BDRE->getDecl()->getDeclContext()))
98066b6166SMike Stump       Info.DeclRefs.push_back(BDRE);
99ed5e69feSAnders Carlsson   }
100ed5e69feSAnders Carlsson }
101ed5e69feSAnders Carlsson 
1022d33d630SMike Stump /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
1032d33d630SMike Stump /// declared as a global variable instead of on the stack.
10446813bbfSChris Lattner static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info) {
1057fe9cc1dSMike Stump   return Info.DeclRefs.empty();
1067fe9cc1dSMike Stump }
1077fe9cc1dSMike Stump 
1087fe9cc1dSMike Stump /// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
1097fe9cc1dSMike Stump /// ensure we can generate the debug information for the parameter for the block
1107fe9cc1dSMike Stump /// invoke function.
1117fe9cc1dSMike Stump static void AllocateAllBlockDeclRefs(const CodeGenFunction::BlockInfo &Info,
1127fe9cc1dSMike Stump                                      CodeGenFunction *CGF) {
1137fe9cc1dSMike Stump   // Always allocate self, as it is often handy in the debugger, even if there
1147fe9cc1dSMike Stump   // is no codegen in the block that uses it.  This is also useful to always do
1157fe9cc1dSMike Stump   // this as if we didn't, we'd have to figure out all code that uses a self
1167fe9cc1dSMike Stump   // pointer, including implicit uses.
1177fe9cc1dSMike Stump   if (const ObjCMethodDecl *OMD
1187fe9cc1dSMike Stump       = dyn_cast_or_null<ObjCMethodDecl>(CGF->CurFuncDecl)) {
1197fe9cc1dSMike Stump     ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
1207fe9cc1dSMike Stump     BlockDeclRefExpr *BDRE = new (CGF->getContext())
1217fe9cc1dSMike Stump       BlockDeclRefExpr(SelfDecl,
1227fe9cc1dSMike Stump                        SelfDecl->getType(), SourceLocation(), false);
1237fe9cc1dSMike Stump     CGF->AllocateBlockDecl(BDRE);
1247fe9cc1dSMike Stump   }
1257fe9cc1dSMike Stump 
1267fe9cc1dSMike Stump   // FIXME: Also always forward the this pointer in C++ as well.
1277fe9cc1dSMike Stump 
1287fe9cc1dSMike Stump   for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
1297fe9cc1dSMike Stump     CGF->AllocateBlockDecl(Info.DeclRefs[i]);
130ed5e69feSAnders Carlsson }
131ed5e69feSAnders Carlsson 
1322d33d630SMike Stump // FIXME: Push most into CGM, passing down a few bits, like current function
1332d33d630SMike Stump // name.
134b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
135ed5e69feSAnders Carlsson 
136ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
137ed5e69feSAnders Carlsson   CodeGenFunction::BlockInfo Info(0, Name.c_str());
138066b6166SMike Stump   llvm::SmallSet<const DeclContext *, 16> InnerContexts;
139066b6166SMike Stump   InnerContexts.insert(BE->getBlockDecl());
140066b6166SMike Stump   CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
141ed5e69feSAnders Carlsson 
142ed5e69feSAnders Carlsson   // Check if the block can be global.
1432d33d630SMike Stump   // FIXME: This test doesn't work for nested blocks yet.  Longer term, I'd like
1442d33d630SMike Stump   // to just have one code path.  We should move this function into CGM and pass
1452d33d630SMike Stump   // CGF, then we can just check to see if CGF is 0.
14697d01d50SMike Stump   if (0 && CanBlockBeGlobal(Info))
147ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
14885284bacSMike Stump 
149950a9518SDavid Chisnall   size_t BlockFields = 5;
150950a9518SDavid Chisnall 
151950a9518SDavid Chisnall   bool hasIntrospection  = CGM.getContext().getLangOptions().BlockIntrospection;
152950a9518SDavid Chisnall 
153950a9518SDavid Chisnall   if (hasIntrospection) {
154950a9518SDavid Chisnall     BlockFields++;
155950a9518SDavid Chisnall   }
156950a9518SDavid Chisnall   std::vector<llvm::Constant*> Elts(BlockFields);
157950a9518SDavid Chisnall 
158950a9518SDavid Chisnall   if (hasIntrospection) {
159950a9518SDavid Chisnall     std::string BlockTypeEncoding;
160950a9518SDavid Chisnall     CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
161950a9518SDavid Chisnall 
162950a9518SDavid Chisnall     Elts[5] = llvm::ConstantExpr::getBitCast(
163950a9518SDavid Chisnall             CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
164950a9518SDavid Chisnall   }
165950a9518SDavid Chisnall 
16685284bacSMike Stump   llvm::Constant *C;
167b750d928SMike Stump   llvm::Value *V;
16885284bacSMike Stump 
16985284bacSMike Stump   {
17085284bacSMike Stump     // C = BuildBlockStructInitlist();
17185284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
17285284bacSMike Stump 
173950a9518SDavid Chisnall     if (hasIntrospection)
174950a9518SDavid Chisnall       flags |= BLOCK_HAS_OBJC_TYPE;
175950a9518SDavid Chisnall 
1764446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
1774446dcf0SMike Stump     // block literal.
1784446dcf0SMike Stump     // __invoke
179*40775003SKen Dyck     CharUnits subBlockSize;
180*40775003SKen Dyck     uint64_t subBlockAlign;
1814446dcf0SMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
182d2142cffSMike Stump     bool subBlockHasCopyDispose = false;
1834446dcf0SMike Stump     llvm::Function *Fn
184d2a3e617SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
185d2a3e617SMike Stump                                                    LocalDeclMap,
1865469f29aSMike Stump                                                    subBlockSize,
1874446dcf0SMike Stump                                                    subBlockAlign,
1884446dcf0SMike Stump                                                    subBlockDeclRefDecls,
189d2142cffSMike Stump                                                    subBlockHasCopyDispose);
190d2142cffSMike Stump     BlockHasCopyDispose |= subBlockHasCopyDispose;
1914446dcf0SMike Stump     Elts[3] = Fn;
1924446dcf0SMike Stump 
19318bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
19418bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
195d2142cffSMike Stump     if (subBlockHasCopyDispose)
19685284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
19785284bacSMike Stump 
198499ae7ecSMike Stump     // __isa
1997ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
200ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
2014446dcf0SMike Stump     Elts[0] = C;
20285284bacSMike Stump 
20385284bacSMike Stump     // __flags
20485284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
20585284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
206b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
2074446dcf0SMike Stump     Elts[1] = C;
20885284bacSMike Stump 
20985284bacSMike Stump     // __reserved
210b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
2114446dcf0SMike Stump     Elts[2] = C;
21285284bacSMike Stump 
213b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
214d6ef62f0SMike Stump       // __descriptor
2157fe9cc1dSMike Stump       Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize,
2167fe9cc1dSMike Stump                                          0, 0);
217d6ef62f0SMike Stump 
2183a139f37SMike Stump       // Optimize to being a global block.
2193a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
220b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2213a139f37SMike Stump 
22241eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
22385284bacSMike Stump 
22485284bacSMike Stump       char Name[32];
2259319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
226c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
22785284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
228c10c8d3eSOwen Anderson                                    C, Name);
2295d2534adSMike Stump       QualType BPT = BE->getType();
230ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
23185284bacSMike Stump       return C;
23285284bacSMike Stump     }
23385284bacSMike Stump 
234950a9518SDavid Chisnall     std::vector<const llvm::Type *> Types(BlockFields+subBlockDeclRefDecls.size());
235aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
236b750d928SMike Stump       Types[i] = Elts[i]->getType();
237aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
238950a9518SDavid Chisnall     if (hasIntrospection)
239950a9518SDavid Chisnall       Types[5] = PtrToInt8Ty;
24085284bacSMike Stump 
2411db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
2421db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
2431db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2441db7d04bSMike Stump       QualType Ty = E->getType();
24597d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
246950a9518SDavid Chisnall         Types[i+BlockFields] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
24797d01d50SMike Stump       } else
248950a9518SDavid Chisnall         Types[i+BlockFields] = ConvertType(Ty);
2491db7d04bSMike Stump     }
250b750d928SMike Stump 
251758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
252b750d928SMike Stump 
253b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
254b750d928SMike Stump     A->setAlignment(subBlockAlign);
255b750d928SMike Stump     V = A;
256b750d928SMike Stump 
257aeb0ffd5SMike Stump     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
258aeb0ffd5SMike Stump     int helpersize = 0;
259aeb0ffd5SMike Stump 
260aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
261b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
262950a9518SDavid Chisnall     if (hasIntrospection)
263950a9518SDavid Chisnall       Builder.CreateStore(Elts[5], Builder.CreateStructGEP(V, 5, "block.tmp"));
264b750d928SMike Stump 
265b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
266b750d928SMike Stump       {
2671db7d04bSMike Stump         // FIXME: Push const down.
2681db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2691db7d04bSMike Stump         DeclRefExpr *DR;
2701db7d04bSMike Stump         ValueDecl *VD;
271b750d928SMike Stump 
2721db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2731db7d04bSMike Stump         // Skip padding.
2741db7d04bSMike Stump         if (DR) continue;
2751db7d04bSMike Stump 
2761db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2771db7d04bSMike Stump         VD = BDRE->getDecl();
2781db7d04bSMike Stump 
279950a9518SDavid Chisnall         llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
280aeb0ffd5SMike Stump         NoteForHelper[helpersize].index = i+5;
2812114d7c2SMike Stump         NoteForHelper[helpersize].RequiresCopying
2822114d7c2SMike Stump           = BlockRequiresCopying(VD->getType());
283aeb0ffd5SMike Stump         NoteForHelper[helpersize].flag
2842114d7c2SMike Stump           = (VD->getType()->isBlockPointerType()
2852114d7c2SMike Stump              ? BLOCK_FIELD_IS_BLOCK
2862114d7c2SMike Stump              : BLOCK_FIELD_IS_OBJECT);
287aeb0ffd5SMike Stump 
2881db7d04bSMike Stump         if (LocalDeclMap[VD]) {
28997d01d50SMike Stump           if (BDRE->isByRef()) {
290aeb0ffd5SMike Stump             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
29190d8daf5SMike Stump               // FIXME: Someone double check this.
29290d8daf5SMike Stump               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
29397d01d50SMike Stump             llvm::Value *Loc = LocalDeclMap[VD];
29497d01d50SMike Stump             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
295c76493a6SDaniel Dunbar             Loc = Builder.CreateLoad(Loc);
29697d01d50SMike Stump             Builder.CreateStore(Loc, Addr);
297aeb0ffd5SMike Stump             ++helpersize;
29897d01d50SMike Stump             continue;
29997d01d50SMike Stump           } else
300ce54657eSJohn McCall             E = new (getContext()) DeclRefExpr (VD,
301ed6c7440SDouglas Gregor                                                 VD->getType(),
302ed6c7440SDouglas Gregor                                                 SourceLocation());
3031db7d04bSMike Stump         }
30497d01d50SMike Stump         if (BDRE->isByRef()) {
305efd7caa8SMike Stump           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
306efd7caa8SMike Stump             // FIXME: Someone double check this.
307efd7caa8SMike Stump             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
3081db7d04bSMike Stump           E = new (getContext())
3091db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
3101db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
3111db7d04bSMike Stump                           SourceLocation());
31297d01d50SMike Stump         }
313aeb0ffd5SMike Stump         ++helpersize;
3141db7d04bSMike Stump 
3151db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
31697d01d50SMike Stump         if (r.isScalar()) {
31797d01d50SMike Stump           llvm::Value *Loc = r.getScalarVal();
318950a9518SDavid Chisnall           const llvm::Type *Ty = Types[i+BlockFields];
31997d01d50SMike Stump           if  (BDRE->isByRef()) {
3202d33d630SMike Stump             // E is now the address of the value field, instead, we want the
3212d33d630SMike Stump             // address of the actual ByRef struct.  We optimize this slightly
3222d33d630SMike Stump             // compared to gcc by not grabbing the forwarding slot as this must
3232d33d630SMike Stump             // be done during Block_copy for us, and we can postpone the work
3242d33d630SMike Stump             // until then.
325*40775003SKen Dyck             CharUnits offset = BlockDecls[BDRE->getDecl()];
3262d33d630SMike Stump 
3272d33d630SMike Stump             llvm::Value *BlockLiteral = LoadBlockStruct();
3282d33d630SMike Stump 
3292d33d630SMike Stump             Loc = Builder.CreateGEP(BlockLiteral,
33041a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
331*40775003SKen Dyck                                                            offset.getQuantity()),
3322d33d630SMike Stump                                     "block.literal");
3339793f0e4SOwen Anderson             Ty = llvm::PointerType::get(Ty, 0);
33497d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
335c76493a6SDaniel Dunbar             Loc = Builder.CreateLoad(Loc);
3362d33d630SMike Stump             // Loc = Builder.CreateBitCast(Loc, Ty);
33797d01d50SMike Stump           }
33897d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
33997d01d50SMike Stump         } else if (r.isComplex())
340b750d928SMike Stump           // FIXME: implement
341b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
342b750d928SMike Stump         else if (r.isAggregate())
343b750d928SMike Stump           ; // Already created into the destination
344b750d928SMike Stump         else
345b750d928SMike Stump           assert (0 && "bad block variable");
346b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
347b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
348b750d928SMike Stump       }
349aeb0ffd5SMike Stump     NoteForHelper.resize(helpersize);
350d6ef62f0SMike Stump 
351d6ef62f0SMike Stump     // __descriptor
352d2142cffSMike Stump     llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
353d2142cffSMike Stump                                                        subBlockSize, Ty,
354aeb0ffd5SMike Stump                                                        &NoteForHelper);
355aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
356aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
357b750d928SMike Stump   }
358b750d928SMike Stump 
359b750d928SMike Stump   QualType BPT = BE->getType();
360b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
361b750d928SMike Stump }
36285284bacSMike Stump 
36385284bacSMike Stump 
36495435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
365650c932dSMike Stump   if (BlockDescriptorType)
366650c932dSMike Stump     return BlockDescriptorType;
3672437cbfaSAnders Carlsson 
3682437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
369650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3702437cbfaSAnders Carlsson 
3712437cbfaSAnders Carlsson   // struct __block_descriptor {
3722437cbfaSAnders Carlsson   //   unsigned long reserved;
3732437cbfaSAnders Carlsson   //   unsigned long block_size;
3742437cbfaSAnders Carlsson   // };
375758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
376758428f4SOwen Anderson                                               UnsignedLongTy,
3772437cbfaSAnders Carlsson                                               UnsignedLongTy,
3782437cbfaSAnders Carlsson                                               NULL);
3792437cbfaSAnders Carlsson 
380650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
381650c932dSMike Stump                           BlockDescriptorType);
3822437cbfaSAnders Carlsson 
383650c932dSMike Stump   return BlockDescriptorType;
3842437cbfaSAnders Carlsson }
3852437cbfaSAnders Carlsson 
38695435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
387005c9a62SMike Stump   if (GenericBlockLiteralType)
388005c9a62SMike Stump     return GenericBlockLiteralType;
3892437cbfaSAnders Carlsson 
3902437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
3919793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
3922437cbfaSAnders Carlsson 
39392bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
39492bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
39592bbd6d4SMike Stump 
3962437cbfaSAnders Carlsson   // struct __block_literal_generic {
3975d2534adSMike Stump   //   void *__isa;
3985d2534adSMike Stump   //   int __flags;
3995d2534adSMike Stump   //   int __reserved;
4005d2534adSMike Stump   //   void (*__invoke)(void *);
4015d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
402950a9518SDavid Chisnall   //   // GNU runtime only:
403950a9518SDavid Chisnall   //   const char *types;
4042437cbfaSAnders Carlsson   // };
405950a9518SDavid Chisnall   if (CGM.getContext().getLangOptions().BlockIntrospection)
406950a9518SDavid Chisnall     GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
407950a9518SDavid Chisnall                                                   PtrToInt8Ty,
408950a9518SDavid Chisnall                                                   IntTy,
409950a9518SDavid Chisnall                                                   IntTy,
410950a9518SDavid Chisnall                                                   PtrToInt8Ty,
411950a9518SDavid Chisnall                                                   BlockDescPtrTy,
412950a9518SDavid Chisnall                                                   PtrToInt8Ty,
413950a9518SDavid Chisnall                                                   NULL);
414950a9518SDavid Chisnall   else
415758428f4SOwen Anderson     GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
416758428f4SOwen Anderson                                                   PtrToInt8Ty,
41792bbd6d4SMike Stump                                                   IntTy,
41892bbd6d4SMike Stump                                                   IntTy,
419626aecc4SMike Stump                                                   PtrToInt8Ty,
4202437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
4212437cbfaSAnders Carlsson                                                   NULL);
4222437cbfaSAnders Carlsson 
423005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
424005c9a62SMike Stump                           GenericBlockLiteralType);
4252437cbfaSAnders Carlsson 
426005c9a62SMike Stump   return GenericBlockLiteralType;
4272437cbfaSAnders Carlsson }
4282437cbfaSAnders Carlsson 
42995435674SMike Stump const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
4305d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
4315d2534adSMike Stump     return GenericExtendedBlockLiteralType;
4325d2534adSMike Stump 
4335d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
4349793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
4355d2534adSMike Stump 
4365d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
4375d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
4385d2534adSMike Stump 
4395d2534adSMike Stump   // struct __block_literal_generic {
4405d2534adSMike Stump   //   void *__isa;
4415d2534adSMike Stump   //   int __flags;
4425d2534adSMike Stump   //   int __reserved;
4435d2534adSMike Stump   //   void (*__invoke)(void *);
4445d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
4455d2534adSMike Stump   //   void *__copy_func_helper_decl;
4465d2534adSMike Stump   //   void *__destroy_func_decl;
4475d2534adSMike Stump   // };
448758428f4SOwen Anderson   GenericExtendedBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
449758428f4SOwen Anderson                                                           PtrToInt8Ty,
4505d2534adSMike Stump                                                           IntTy,
4515d2534adSMike Stump                                                           IntTy,
452626aecc4SMike Stump                                                           PtrToInt8Ty,
4535d2534adSMike Stump                                                           BlockDescPtrTy,
454626aecc4SMike Stump                                                           PtrToInt8Ty,
455626aecc4SMike Stump                                                           PtrToInt8Ty,
4565d2534adSMike Stump                                                           NULL);
4575d2534adSMike Stump 
4585d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
4595d2534adSMike Stump                           GenericExtendedBlockLiteralType);
4605d2534adSMike Stump 
4615d2534adSMike Stump   return GenericExtendedBlockLiteralType;
4625d2534adSMike Stump }
4635d2534adSMike Stump 
464bfb3671bSAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
465bfb3671bSAnders Carlsson                                           ReturnValueSlot ReturnValue) {
4662437cbfaSAnders Carlsson   const BlockPointerType *BPT =
467c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
4682437cbfaSAnders Carlsson 
4692437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
4702437cbfaSAnders Carlsson 
4712437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
4722437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
4739793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
4742437cbfaSAnders Carlsson 
4752437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
4762437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
4772437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4782437cbfaSAnders Carlsson 
4792437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4802437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
4812437cbfaSAnders Carlsson 
4822437cbfaSAnders Carlsson   BlockLiteral =
4832437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
484abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
4852437cbfaSAnders Carlsson                           "tmp");
4862437cbfaSAnders Carlsson 
4872437cbfaSAnders Carlsson   // Add the block literal.
4882437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4892437cbfaSAnders Carlsson   CallArgList Args;
4902437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4912437cbfaSAnders Carlsson 
492479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
493479e6fc7SAnders Carlsson 
4942437cbfaSAnders Carlsson   // And the rest of the arguments.
4959dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
496479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
4972437cbfaSAnders Carlsson 
4985f50c651SAnders Carlsson   // Load the function.
499c76493a6SDaniel Dunbar   llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
5005f50c651SAnders Carlsson 
5019dd450bbSJohn McCall   QualType ResultType = FnType->getAs<FunctionType>()->getResultType();
502a60cbcdfSAnders Carlsson 
503a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
504a60cbcdfSAnders Carlsson     CGM.getTypes().getFunctionInfo(ResultType, Args);
5055f50c651SAnders Carlsson 
5065f50c651SAnders Carlsson   // Cast the function pointer to the right type.
5075f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
508a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
5095f50c651SAnders Carlsson 
5109793f0e4SOwen Anderson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
5115f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
5125f50c651SAnders Carlsson 
5132437cbfaSAnders Carlsson   // And call the block.
514bfb3671bSAnders Carlsson   return EmitCall(FnInfo, Func, ReturnValue, Args);
5152437cbfaSAnders Carlsson }
5166a60fa24SAnders Carlsson 
517*40775003SKen Dyck CharUnits CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
5180168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
519*40775003SKen Dyck   CharUnits &offset = BlockDecls[VD];
5200168f4b2SAnders Carlsson 
52197d01d50SMike Stump   // See if we have already allocated an offset for this variable.
522*40775003SKen Dyck   if (offset.isPositive())
5237fe9cc1dSMike Stump     return offset;
5247fe9cc1dSMike Stump 
5254446dcf0SMike Stump   // Don't run the expensive check, unless we have to.
526e1b19ba0SMike Stump   if (!BlockHasCopyDispose)
527e1b19ba0SMike Stump     if (E->isByRef()
528e1b19ba0SMike Stump         || BlockRequiresCopying(E->getType()))
5294446dcf0SMike Stump       BlockHasCopyDispose = true;
5307fe9cc1dSMike Stump 
53197d01d50SMike Stump   // if not, allocate one now.
53297d01d50SMike Stump   offset = getBlockOffset(E);
5337fe9cc1dSMike Stump 
5347fe9cc1dSMike Stump   return offset;
53597d01d50SMike Stump }
53697d01d50SMike Stump 
5377fe9cc1dSMike Stump llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
5387fe9cc1dSMike Stump   const ValueDecl *VD = E->getDecl();
539*40775003SKen Dyck   CharUnits offset = AllocateBlockDecl(E);
5407fe9cc1dSMike Stump 
5417fe9cc1dSMike Stump 
54297d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
54397d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
54441a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
545*40775003SKen Dyck                                                          offset.getQuantity()),
5462d33d630SMike Stump                                      "block.literal");
54797d01d50SMike Stump   if (E->isByRef()) {
54897d01d50SMike Stump     const llvm::Type *PtrStructTy
5490168f4b2SAnders Carlsson       = llvm::PointerType::get(BuildByRefType(VD), 0);
550efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
551efd7caa8SMike Stump     BlockHasCopyDispose = true;
5520168f4b2SAnders Carlsson 
5530168f4b2SAnders Carlsson     const llvm::Type *Ty = PtrStructTy;
5549793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
55597d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
556c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
55797d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
558c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
55997d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
5600168f4b2SAnders Carlsson     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
5610168f4b2SAnders Carlsson                                 VD->getNameAsString());
56297d01d50SMike Stump   } else {
5630168f4b2SAnders Carlsson     const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
5640168f4b2SAnders Carlsson 
5659793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
56697d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
56797d01d50SMike Stump   }
56897d01d50SMike Stump   return V;
56997d01d50SMike Stump }
57097d01d50SMike Stump 
571692c6e37SMike Stump void CodeGenFunction::BlockForwardSelf() {
572692c6e37SMike Stump   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
573692c6e37SMike Stump   ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
574692c6e37SMike Stump   llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
575692c6e37SMike Stump   if (DMEntry)
576692c6e37SMike Stump     return;
577692c6e37SMike Stump   // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
578692c6e37SMike Stump   BlockDeclRefExpr *BDRE = new (getContext())
579692c6e37SMike Stump     BlockDeclRefExpr(SelfDecl,
580692c6e37SMike Stump                      SelfDecl->getType(), SourceLocation(), false);
581692c6e37SMike Stump   DMEntry = GetAddrOfBlockDecl(BDRE);
582692c6e37SMike Stump }
583692c6e37SMike Stump 
5842d5a2878SMike Stump llvm::Constant *
5856c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
5866a60fa24SAnders Carlsson   // Generate the block descriptor.
5876a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
58892bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
58992bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
5906a60fa24SAnders Carlsson 
5916a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
5926a60fa24SAnders Carlsson 
5936a60fa24SAnders Carlsson   // Reserved
5940b75f23bSOwen Anderson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
5956a60fa24SAnders Carlsson 
5966a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
5976a60fa24SAnders Carlsson   // block literal struct.
598*40775003SKen Dyck   CharUnits BlockLiteralSize = CharUnits::fromQuantity(
599*40775003SKen Dyck     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8);
600170229f6SOwen Anderson   DescriptorFields[1] =
601*40775003SKen Dyck     llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
6026a60fa24SAnders Carlsson 
6036a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
60441eaf0acSNick Lewycky     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 2, false);
6056a60fa24SAnders Carlsson 
6066a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
607c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
6086a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
609c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
6106a60fa24SAnders Carlsson 
611950a9518SDavid Chisnall   int FieldCount = 5;
6126a60fa24SAnders Carlsson   // Generate the constants for the block literal.
613950a9518SDavid Chisnall   if (CGM.getContext().getLangOptions().BlockIntrospection)
614950a9518SDavid Chisnall     FieldCount = 6;
615950a9518SDavid Chisnall 
616950a9518SDavid Chisnall   std::vector<llvm::Constant*> LiteralFields(FieldCount);
6176a60fa24SAnders Carlsson 
6182d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
619*40775003SKen Dyck   CharUnits subBlockSize;
620*40775003SKen Dyck   uint64_t subBlockAlign;
6211db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
622a61bb4d1SDaniel Dunbar   bool subBlockHasCopyDispose = false;
6235469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
624cb2fbcb0SMike Stump   llvm::Function *Fn
625692c6e37SMike Stump     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
6265469f29aSMike Stump                                                  subBlockSize,
627b750d928SMike Stump                                                  subBlockAlign,
6284446dcf0SMike Stump                                                  subBlockDeclRefDecls,
6294446dcf0SMike Stump                                                  subBlockHasCopyDispose);
630cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
631cb2fbcb0SMike Stump          && "no imports allowed for global block");
6326a60fa24SAnders Carlsson 
6336a60fa24SAnders Carlsson   // isa
634971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
6356a60fa24SAnders Carlsson 
6366a60fa24SAnders Carlsson   // Flags
637950a9518SDavid Chisnall   LiteralFields[1] = CGM.getContext().getLangOptions().BlockIntrospection ?
638950a9518SDavid Chisnall     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR |
639950a9518SDavid Chisnall             BLOCK_HAS_OBJC_TYPE) :
640b7a2fe6fSOwen Anderson     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
6416a60fa24SAnders Carlsson 
6426a60fa24SAnders Carlsson   // Reserved
6430b75f23bSOwen Anderson   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
6446a60fa24SAnders Carlsson 
6456a60fa24SAnders Carlsson   // Function
6466a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
6476a60fa24SAnders Carlsson 
6486a60fa24SAnders Carlsson   // Descriptor
6496a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
6506a60fa24SAnders Carlsson 
651950a9518SDavid Chisnall   // Type encoding
652950a9518SDavid Chisnall   if (CGM.getContext().getLangOptions().BlockIntrospection) {
653950a9518SDavid Chisnall     std::string BlockTypeEncoding;
654950a9518SDavid Chisnall     CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
655950a9518SDavid Chisnall 
656950a9518SDavid Chisnall     LiteralFields[5] = CGM.GetAddrOfConstantCString(BlockTypeEncoding);
657950a9518SDavid Chisnall   }
658950a9518SDavid Chisnall 
6596a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
660950a9518SDavid Chisnall     llvm::ConstantStruct::get(VMContext, LiteralFields, false);
6616a60fa24SAnders Carlsson 
6626a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
663c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
6646a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
665c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
6666a60fa24SAnders Carlsson 
6676a60fa24SAnders Carlsson   return BlockLiteral;
6686a60fa24SAnders Carlsson }
6696a60fa24SAnders Carlsson 
670cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
67138382028SMike Stump   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
67238382028SMike Stump                                       "self");
67338382028SMike Stump   // For now, we codegen based upon byte offsets.
67438382028SMike Stump   return Builder.CreateBitCast(V, PtrToInt8Ty);
675cb2fbcb0SMike Stump }
676cb2fbcb0SMike Stump 
6774446dcf0SMike Stump llvm::Function *
6784446dcf0SMike Stump CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
679cb2fbcb0SMike Stump                                        const BlockInfo& Info,
680692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
6815469f29aSMike Stump                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm,
682*40775003SKen Dyck                                        CharUnits &Size,
683b750d928SMike Stump                                        uint64_t &Align,
6844446dcf0SMike Stump                        llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
6854446dcf0SMike Stump                                        bool &subBlockHasCopyDispose) {
6869074ed8cSDevang Patel 
6879074ed8cSDevang Patel   // Check if we should generate debug info for this block.
6889074ed8cSDevang Patel   if (CGM.getDebugInfo())
6899074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
6909074ed8cSDevang Patel 
6915469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
6925469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
6935469f29aSMike Stump   // in a block.
6945469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
6955469f29aSMike Stump        i != ldm.end();
6965469f29aSMike Stump        ++i) {
6975469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
6985469f29aSMike Stump 
6990ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
7005469f29aSMike Stump       LocalDeclMap[VD] = i->second;
7015469f29aSMike Stump   }
7025469f29aSMike Stump 
703*40775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
704*40775003SKen Dyck       CGM.getTargetData()
705*40775003SKen Dyck         .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8);
70609a9b6e3SEli Friedman   BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
70709a9b6e3SEli Friedman 
708aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
709aae4349dSFariborz Jahanian   QualType ResultType;
710aae4349dSFariborz Jahanian   bool IsVariadic;
711a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
712a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
713aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
714aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
715658fe02dSMike Stump   } else {
716aae4349dSFariborz Jahanian     // K&R style block.
717aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
718aae4349dSFariborz Jahanian     IsVariadic = false;
719aae4349dSFariborz Jahanian   }
7206a60fa24SAnders Carlsson 
7216a60fa24SAnders Carlsson   FunctionArgList Args;
7226a60fa24SAnders Carlsson 
7237fe9cc1dSMike Stump   CurFuncDecl = OuterFuncDecl;
7247fe9cc1dSMike Stump 
7253385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
7266a60fa24SAnders Carlsson 
7277fe9cc1dSMike Stump   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
728d015328fSMike Stump 
729945fec05SMike Stump   // Allocate all BlockDeclRefDecls, so we can calculate the right ParmTy below.
7307fe9cc1dSMike Stump   AllocateAllBlockDeclRefs(Info, this);
7317fe9cc1dSMike Stump 
732e1b19ba0SMike Stump   QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
733e1b19ba0SMike Stump                                                   BlockDeclRefDecls);
7346a60fa24SAnders Carlsson   // FIXME: This leaks
7356a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
7366a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
737d015328fSMike Stump                               SourceLocation(), II,
738d015328fSMike Stump                               ParmTy);
7396a60fa24SAnders Carlsson 
7406a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
741cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
7426a60fa24SAnders Carlsson 
743c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
7446a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
745eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
7466a60fa24SAnders Carlsson 
7476a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
748aae4349dSFariborz Jahanian     CGM.getTypes().getFunctionInfo(ResultType, Args);
7496a60fa24SAnders Carlsson 
7502d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
7516a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
752aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
7536a60fa24SAnders Carlsson 
7546a60fa24SAnders Carlsson   llvm::Function *Fn =
7556a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
7566a60fa24SAnders Carlsson                            Name,
7576a60fa24SAnders Carlsson                            &CGM.getModule());
7586a60fa24SAnders Carlsson 
759c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
760c3e7cff6SDaniel Dunbar 
761324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
7623385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
7632e722b91SMike Stump 
764324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
76528ec0cf8SChris Lattner   CurCodeDecl = BD;
766017460abSMike Stump 
767017460abSMike Stump   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
768017460abSMike Stump   llvm::BasicBlock *entry = Builder.GetInsertBlock();
769017460abSMike Stump   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
770017460abSMike Stump   --entry_ptr;
771017460abSMike Stump 
7723385fe12SChris Lattner   EmitStmt(BExpr->getBody());
773017460abSMike Stump 
7747d69911aSMike Stump   // Remember where we were...
7757d69911aSMike Stump   llvm::BasicBlock *resume = Builder.GetInsertBlock();
776017460abSMike Stump 
7777d69911aSMike Stump   // Go back to the entry.
778017460abSMike Stump   ++entry_ptr;
779017460abSMike Stump   Builder.SetInsertPoint(entry, entry_ptr);
780017460abSMike Stump 
7812e722b91SMike Stump   if (CGDebugInfo *DI = getDebugInfo()) {
7822e722b91SMike Stump     // Emit debug information for all the BlockDeclRefDecls.
7832e722b91SMike Stump     for (unsigned i=0; i < BlockDeclRefDecls.size(); ++i) {
7842e722b91SMike Stump       const Expr *E = BlockDeclRefDecls[i];
7852e722b91SMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
7862e722b91SMike Stump       if (BDRE) {
7872e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
7882e722b91SMike Stump         DI->setLocation(D->getLocation());
7892e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
7902e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
7912e722b91SMike Stump                                               Builder, this);
7922e722b91SMike Stump       }
7932e722b91SMike Stump     }
7942e722b91SMike Stump   }
7957d69911aSMike Stump   // And resume where we left off.
7967d69911aSMike Stump   if (resume == 0)
7977d69911aSMike Stump     Builder.ClearInsertionPoint();
7987d69911aSMike Stump   else
7997d69911aSMike Stump     Builder.SetInsertPoint(resume);
8002e722b91SMike Stump 
8013385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
8026a60fa24SAnders Carlsson 
803b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
804b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
805*40775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
806*40775003SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(), MinAlign));
807b750d928SMike Stump 
808cb2fbcb0SMike Stump   Size = BlockOffset;
809b750d928SMike Stump   Align = BlockAlign;
810b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
8114446dcf0SMike Stump   subBlockHasCopyDispose |= BlockHasCopyDispose;
8126a60fa24SAnders Carlsson   return Fn;
8136a60fa24SAnders Carlsson }
8141db7d04bSMike Stump 
815*40775003SKen Dyck CharUnits BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
8161db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
8171db7d04bSMike Stump 
818*40775003SKen Dyck   CharUnits Size = getContext().getTypeSizeInChars(D->getType());
8191db7d04bSMike Stump   uint64_t Align = getContext().getDeclAlignInBytes(D);
8201db7d04bSMike Stump 
8211db7d04bSMike Stump   if (BDRE->isByRef()) {
822*40775003SKen Dyck     Size = getContext().getTypeSizeInChars(getContext().VoidPtrTy);
8231db7d04bSMike Stump     Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
8241db7d04bSMike Stump   }
8251db7d04bSMike Stump 
8261db7d04bSMike Stump   assert ((Align > 0) && "alignment must be 1 byte or more");
8271db7d04bSMike Stump 
828*40775003SKen Dyck   CharUnits OldOffset = BlockOffset;
8291db7d04bSMike Stump 
8301db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
831*40775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
832*40775003SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align));
8331db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
8341db7d04bSMike Stump 
835*40775003SKen Dyck   CharUnits Pad = BlockOffset - OldOffset;
836*40775003SKen Dyck   if (Pad.isPositive()) {
837*40775003SKen Dyck     llvm::ArrayType::get(llvm::Type::getInt8Ty(VMContext), Pad.getQuantity());
8381db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
839*40775003SKen Dyck                                                        llvm::APInt(32,
840*40775003SKen Dyck                                                          Pad.getQuantity()),
8411db7d04bSMike Stump                                                        ArrayType::Normal, 0);
8421db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
8436032ef1aSArgyrios Kyrtzidis                                          0, QualType(PadTy), 0, VarDecl::None);
8441db7d04bSMike Stump     Expr *E;
8451db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
846ed6c7440SDouglas Gregor                                        SourceLocation());
8471db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
8481db7d04bSMike Stump   }
8491db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
8501db7d04bSMike Stump 
8511db7d04bSMike Stump   BlockOffset += Size;
8521db7d04bSMike Stump   return BlockOffset-Size;
8531db7d04bSMike Stump }
85497d01d50SMike Stump 
855aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
856aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
85767645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
8580c743277SMike Stump   QualType R = getContext().VoidTy;
8590c743277SMike Stump 
8600c743277SMike Stump   FunctionArgList Args;
8610c743277SMike Stump   // FIXME: This leaks
862aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
8637fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8647fe9cc1dSMike Stump                               SourceLocation(), 0,
865aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
866aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
8670c743277SMike Stump   ImplicitParamDecl *Src =
8687fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8697fe9cc1dSMike Stump                               SourceLocation(), 0,
8700c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
8710c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
8720c743277SMike Stump 
8730c743277SMike Stump   const CGFunctionInfo &FI =
8740c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
8750c743277SMike Stump 
876cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
877cbc2bcafSMike Stump   // internal linkage.
8780c743277SMike Stump   std::string Name = std::string("__copy_helper_block_");
8790c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
8800c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8810c743277SMike Stump 
8820c743277SMike Stump   llvm::Function *Fn =
8830c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
8840c743277SMike Stump                            Name,
8850c743277SMike Stump                            &CGM.getModule());
8860c743277SMike Stump 
8870c743277SMike Stump   IdentifierInfo *II
8880c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
8890c743277SMike Stump 
8900c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8910c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
89260ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
8930c743277SMike Stump                                           FunctionDecl::Static, false,
8940c743277SMike Stump                                           true);
8950c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
896aeb0ffd5SMike Stump 
897aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
898aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
89967645930SMike Stump 
90067645930SMike Stump   if (NoteForHelperp) {
90167645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
90267645930SMike Stump 
9039793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
904aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
905aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
906aeb0ffd5SMike Stump 
907aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
9083b65ac26SMike Stump     llvm::Type *PtrPtrT;
9099793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9103b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
9113b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
912aeb0ffd5SMike Stump 
913aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
914aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
915aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
916aeb0ffd5SMike Stump 
917aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
918aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
919aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
920aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
921aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9229793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
923aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
924aeb0ffd5SMike Stump 
925aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
926aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
927aeb0ffd5SMike Stump 
92841a75027SOwen Anderson         llvm::Value *N = llvm::ConstantInt::get(
92941a75027SOwen Anderson               llvm::Type::getInt32Ty(T->getContext()), flag);
930aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
931aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
932aeb0ffd5SMike Stump       }
933aeb0ffd5SMike Stump     }
93467645930SMike Stump   }
935aeb0ffd5SMike Stump 
9360c743277SMike Stump   CGF.FinishFunction();
9370c743277SMike Stump 
938ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
93997d01d50SMike Stump }
94097d01d50SMike Stump 
941d6ef62f0SMike Stump llvm::Constant *BlockFunction::
942aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
943aeb0ffd5SMike Stump                               const llvm::StructType* T,
94467645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
9450c743277SMike Stump   QualType R = getContext().VoidTy;
9460c743277SMike Stump 
9470c743277SMike Stump   FunctionArgList Args;
9480c743277SMike Stump   // FIXME: This leaks
9490c743277SMike Stump   ImplicitParamDecl *Src =
9507fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9517fe9cc1dSMike Stump                               SourceLocation(), 0,
9520c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
9530c743277SMike Stump 
9540c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
9550c743277SMike Stump 
9560c743277SMike Stump   const CGFunctionInfo &FI =
9570c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
9580c743277SMike Stump 
959cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
960cbc2bcafSMike Stump   // internal linkage.
9610c743277SMike Stump   std::string Name = std::string("__destroy_helper_block_");
9620c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
9630c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
9640c743277SMike Stump 
9650c743277SMike Stump   llvm::Function *Fn =
9660c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
9670c743277SMike Stump                            Name,
9680c743277SMike Stump                            &CGM.getModule());
9690c743277SMike Stump 
9700c743277SMike Stump   IdentifierInfo *II
9710c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
9720c743277SMike Stump 
9730c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
9740c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
97560ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
9760c743277SMike Stump                                           FunctionDecl::Static, false,
9770c743277SMike Stump                                           true);
9780c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
9796f7d9f87SMike Stump 
98067645930SMike Stump   if (NoteForHelperp) {
98167645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
98267645930SMike Stump 
9836f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
9846f7d9f87SMike Stump     llvm::Type *PtrPtrT;
9859793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9866f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
9876f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
9886f7d9f87SMike Stump 
9896f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
9906f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
9916f7d9f87SMike Stump       int index = NoteForHelper[i].index;
9926f7d9f87SMike Stump 
9936f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
9946f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
9956f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
9966f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
9976f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9989793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
9996f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
10006f7d9f87SMike Stump 
10016f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
10026f7d9f87SMike Stump       }
10036f7d9f87SMike Stump     }
100467645930SMike Stump   }
10056f7d9f87SMike Stump 
10060c743277SMike Stump   CGF.FinishFunction();
10070c743277SMike Stump 
1008ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
10090c743277SMike Stump }
10100c743277SMike Stump 
1011aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
101267645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
1013aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1014aeb0ffd5SMike Stump                                                          T, NoteForHelper);
10150c743277SMike Stump }
10160c743277SMike Stump 
1017aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
101867645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
1019aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
102067645930SMike Stump                                                             T, NoteForHelperp);
102197d01d50SMike Stump }
1022626aecc4SMike Stump 
1023f89230d9SMike Stump llvm::Constant *BlockFunction::
1024f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
1025ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1026ee2a5ee5SMike Stump 
1027ee2a5ee5SMike Stump   FunctionArgList Args;
1028ee2a5ee5SMike Stump   // FIXME: This leaks
1029f89230d9SMike Stump   ImplicitParamDecl *Dst =
10307fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10317fe9cc1dSMike Stump                               SourceLocation(), 0,
1032f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1033f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
1034f89230d9SMike Stump 
1035f89230d9SMike Stump   // FIXME: This leaks
1036ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10377fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10387fe9cc1dSMike Stump                               SourceLocation(), 0,
1039ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1040ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1041ee2a5ee5SMike Stump 
1042ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1043ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
1044ee2a5ee5SMike Stump 
1045ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_copy_");
1046ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1047ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1048ee2a5ee5SMike Stump 
1049cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1050cbc2bcafSMike Stump   // internal linkage.
1051ee2a5ee5SMike Stump   llvm::Function *Fn =
1052ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1053ee2a5ee5SMike Stump                            Name,
1054ee2a5ee5SMike Stump                            &CGM.getModule());
1055ee2a5ee5SMike Stump 
1056ee2a5ee5SMike Stump   IdentifierInfo *II
1057ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1058ee2a5ee5SMike Stump 
1059ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1060ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
106160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1062ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1063ee2a5ee5SMike Stump                                           true);
1064ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1065f89230d9SMike Stump 
1066f89230d9SMike Stump   // dst->x
1067f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
10689793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10693b65ac26SMike Stump   V = Builder.CreateLoad(V);
1070f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
1071f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1072f89230d9SMike Stump 
1073f89230d9SMike Stump   // src->x
1074f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
1075f89230d9SMike Stump   V = Builder.CreateLoad(V);
1076f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
1077f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10789793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1079f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
1080f89230d9SMike Stump 
1081f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
1082f89230d9SMike Stump 
108341a75027SOwen Anderson   llvm::Value *N = llvm::ConstantInt::get(
108441a75027SOwen Anderson           llvm::Type::getInt32Ty(T->getContext()), flag);
1085f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
1086f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1087f89230d9SMike Stump 
1088ee2a5ee5SMike Stump   CGF.FinishFunction();
1089ee2a5ee5SMike Stump 
1090ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1091ee2a5ee5SMike Stump }
1092ee2a5ee5SMike Stump 
1093fbe25dd1SMike Stump llvm::Constant *
1094fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1095fbe25dd1SMike Stump                                                   int flag) {
1096ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1097ee2a5ee5SMike Stump 
1098ee2a5ee5SMike Stump   FunctionArgList Args;
1099ee2a5ee5SMike Stump   // FIXME: This leaks
1100ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
11017fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
11027fe9cc1dSMike Stump                               SourceLocation(), 0,
1103ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1104ee2a5ee5SMike Stump 
1105ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1106ee2a5ee5SMike Stump 
1107ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1108ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
1109ee2a5ee5SMike Stump 
1110ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_dispose_");
1111ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1112ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1113ee2a5ee5SMike Stump 
1114cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1115cbc2bcafSMike Stump   // internal linkage.
1116ee2a5ee5SMike Stump   llvm::Function *Fn =
1117ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1118ee2a5ee5SMike Stump                            Name,
1119ee2a5ee5SMike Stump                            &CGM.getModule());
1120ee2a5ee5SMike Stump 
1121ee2a5ee5SMike Stump   IdentifierInfo *II
1122ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1123ee2a5ee5SMike Stump 
1124ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1125ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
112660ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1127ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1128ee2a5ee5SMike Stump                                           true);
1129ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1130fbe25dd1SMike Stump 
1131fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
11329793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
11333b65ac26SMike Stump   V = Builder.CreateLoad(V);
1134fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
11359793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
11363b65ac26SMike Stump   V = Builder.CreateLoad(V);
1137fbe25dd1SMike Stump 
1138fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1139fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1140ee2a5ee5SMike Stump   CGF.FinishFunction();
1141ee2a5ee5SMike Stump 
1142ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1143ee2a5ee5SMike Stump }
1144ee2a5ee5SMike Stump 
1145f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1146e08ea787SChris Lattner                                                     int Flag, unsigned Align) {
1147e08ea787SChris Lattner   // All alignments below that of pointer alignment collapse down to just
1148cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1149cbc2bcafSMike Stump   // with.
1150cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1151e08ea787SChris Lattner 
1152cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1153cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1154cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1155e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1156e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.AssignCache[Kind];
1157cbc2bcafSMike Stump   if (Entry)
1158cbc2bcafSMike Stump     return Entry;
1159e08ea787SChris Lattner   return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
1160ee2a5ee5SMike Stump }
1161ee2a5ee5SMike Stump 
1162fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1163e08ea787SChris Lattner                                                        int Flag,
1164cbc2bcafSMike Stump                                                        unsigned Align) {
1165cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1166cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1167cbc2bcafSMike Stump   // with.
1168cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1169e08ea787SChris Lattner 
1170cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1171cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1172cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1173e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1174e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.DestroyCache[Kind];
1175cbc2bcafSMike Stump   if (Entry)
1176cbc2bcafSMike Stump     return Entry;
1177e08ea787SChris Lattner   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
1178ee2a5ee5SMike Stump }
1179ee2a5ee5SMike Stump 
1180626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1181626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1182626aecc4SMike Stump     const llvm::FunctionType *FTy;
1183626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
118441a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1185626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
118641a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11879793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1188626aecc4SMike Stump     CGM.BlockObjectDispose
1189626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1190626aecc4SMike Stump   }
1191626aecc4SMike Stump   return CGM.BlockObjectDispose;
1192626aecc4SMike Stump }
1193626aecc4SMike Stump 
1194f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1195f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1196f89230d9SMike Stump     const llvm::FunctionType *FTy;
1197f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
119841a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1199f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1200f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
120141a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
12029793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1203f89230d9SMike Stump     CGM.BlockObjectAssign
1204f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1205f89230d9SMike Stump   }
1206f89230d9SMike Stump   return CGM.BlockObjectAssign;
1207f89230d9SMike Stump }
1208f89230d9SMike Stump 
1209fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1210626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1211fbe25dd1SMike Stump   llvm::Value *N;
1212626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
121341a75027SOwen Anderson   N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1214626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1215626aecc4SMike Stump }
12164446dcf0SMike Stump 
12174446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1218aeb0ffd5SMike Stump 
1219aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1220aeb0ffd5SMike Stump                              CGBuilderTy &B)
1221170229f6SOwen Anderson   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
122241a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
122341a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1224aeb0ffd5SMike Stump 
1225aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1226aeb0ffd5SMike Stump }
1227