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::
27d2142cffSMike Stump BuildDescriptorBlockDecl(bool BlockHasCopyDispose, uint64_t 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.
43b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, Size);
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 
1494446dcf0SMike Stump   std::vector<llvm::Constant*> Elts(5);
15085284bacSMike Stump   llvm::Constant *C;
151b750d928SMike Stump   llvm::Value *V;
15285284bacSMike Stump 
15385284bacSMike Stump   {
15485284bacSMike Stump     // C = BuildBlockStructInitlist();
15585284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
15685284bacSMike Stump 
1574446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
1584446dcf0SMike Stump     // block literal.
1594446dcf0SMike Stump     // __invoke
1604446dcf0SMike Stump     uint64_t subBlockSize, subBlockAlign;
1614446dcf0SMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
162d2142cffSMike Stump     bool subBlockHasCopyDispose = false;
1634446dcf0SMike Stump     llvm::Function *Fn
164d2a3e617SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
165d2a3e617SMike Stump                                                    LocalDeclMap,
1665469f29aSMike Stump                                                    subBlockSize,
1674446dcf0SMike Stump                                                    subBlockAlign,
1684446dcf0SMike Stump                                                    subBlockDeclRefDecls,
169d2142cffSMike Stump                                                    subBlockHasCopyDispose);
170d2142cffSMike Stump     BlockHasCopyDispose |= subBlockHasCopyDispose;
1714446dcf0SMike Stump     Elts[3] = Fn;
1724446dcf0SMike Stump 
17318bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
17418bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
175d2142cffSMike Stump     if (subBlockHasCopyDispose)
17685284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
17785284bacSMike Stump 
178499ae7ecSMike Stump     // __isa
1797ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
180ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1814446dcf0SMike Stump     Elts[0] = C;
18285284bacSMike Stump 
18385284bacSMike Stump     // __flags
18485284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
18585284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
186b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
1874446dcf0SMike Stump     Elts[1] = C;
18885284bacSMike Stump 
18985284bacSMike Stump     // __reserved
190b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
1914446dcf0SMike Stump     Elts[2] = C;
19285284bacSMike Stump 
193b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
194d6ef62f0SMike Stump       // __descriptor
1957fe9cc1dSMike Stump       Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize,
1967fe9cc1dSMike Stump                                          0, 0);
197d6ef62f0SMike Stump 
1983a139f37SMike Stump       // Optimize to being a global block.
1993a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
200b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2013a139f37SMike Stump 
20241eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
20385284bacSMike Stump 
20485284bacSMike Stump       char Name[32];
2059319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
206c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
20785284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
208c10c8d3eSOwen Anderson                                    C, Name);
2095d2534adSMike Stump       QualType BPT = BE->getType();
210ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
21185284bacSMike Stump       return C;
21285284bacSMike Stump     }
21385284bacSMike Stump 
214b750d928SMike Stump     std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
215aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
216b750d928SMike Stump       Types[i] = Elts[i]->getType();
217aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
21885284bacSMike Stump 
2191db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
2201db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
2211db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2221db7d04bSMike Stump       QualType Ty = E->getType();
22397d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
22471d1d92dSAnders Carlsson         Types[i+5] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
22597d01d50SMike Stump       } else
2261db7d04bSMike Stump         Types[i+5] = ConvertType(Ty);
2271db7d04bSMike Stump     }
228b750d928SMike Stump 
229758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
230b750d928SMike Stump 
231b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
232b750d928SMike Stump     A->setAlignment(subBlockAlign);
233b750d928SMike Stump     V = A;
234b750d928SMike Stump 
235aeb0ffd5SMike Stump     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
236aeb0ffd5SMike Stump     int helpersize = 0;
237aeb0ffd5SMike Stump 
238aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
239b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
240b750d928SMike Stump 
241b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
242b750d928SMike Stump       {
2431db7d04bSMike Stump         // FIXME: Push const down.
2441db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2451db7d04bSMike Stump         DeclRefExpr *DR;
2461db7d04bSMike Stump         ValueDecl *VD;
247b750d928SMike Stump 
2481db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2491db7d04bSMike Stump         // Skip padding.
2501db7d04bSMike Stump         if (DR) continue;
2511db7d04bSMike Stump 
2521db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2531db7d04bSMike Stump         VD = BDRE->getDecl();
2541db7d04bSMike Stump 
25597d01d50SMike Stump         llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
256aeb0ffd5SMike Stump         NoteForHelper[helpersize].index = i+5;
2572114d7c2SMike Stump         NoteForHelper[helpersize].RequiresCopying
2582114d7c2SMike Stump           = BlockRequiresCopying(VD->getType());
259aeb0ffd5SMike Stump         NoteForHelper[helpersize].flag
2602114d7c2SMike Stump           = (VD->getType()->isBlockPointerType()
2612114d7c2SMike Stump              ? BLOCK_FIELD_IS_BLOCK
2622114d7c2SMike Stump              : BLOCK_FIELD_IS_OBJECT);
263aeb0ffd5SMike Stump 
2641db7d04bSMike Stump         if (LocalDeclMap[VD]) {
26597d01d50SMike Stump           if (BDRE->isByRef()) {
266aeb0ffd5SMike Stump             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
26790d8daf5SMike Stump               // FIXME: Someone double check this.
26890d8daf5SMike Stump               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
26997d01d50SMike Stump             llvm::Value *Loc = LocalDeclMap[VD];
27097d01d50SMike Stump             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
27197d01d50SMike Stump             Loc = Builder.CreateLoad(Loc, false);
27297d01d50SMike Stump             Builder.CreateStore(Loc, Addr);
273aeb0ffd5SMike Stump             ++helpersize;
27497d01d50SMike Stump             continue;
27597d01d50SMike Stump           } else
2761db7d04bSMike Stump             E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
2771db7d04bSMike Stump                                                 VD->getType(), SourceLocation(),
2781db7d04bSMike Stump                                                 false, false);
2791db7d04bSMike Stump         }
28097d01d50SMike Stump         if (BDRE->isByRef()) {
281efd7caa8SMike Stump           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
282efd7caa8SMike Stump             // FIXME: Someone double check this.
283efd7caa8SMike Stump             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
2841db7d04bSMike Stump           E = new (getContext())
2851db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
2861db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
2871db7d04bSMike Stump                           SourceLocation());
28897d01d50SMike Stump         }
289aeb0ffd5SMike Stump         ++helpersize;
2901db7d04bSMike Stump 
2911db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
29297d01d50SMike Stump         if (r.isScalar()) {
29397d01d50SMike Stump           llvm::Value *Loc = r.getScalarVal();
29497d01d50SMike Stump           const llvm::Type *Ty = Types[i+5];
29597d01d50SMike Stump           if  (BDRE->isByRef()) {
2962d33d630SMike Stump             // E is now the address of the value field, instead, we want the
2972d33d630SMike Stump             // address of the actual ByRef struct.  We optimize this slightly
2982d33d630SMike Stump             // compared to gcc by not grabbing the forwarding slot as this must
2992d33d630SMike Stump             // be done during Block_copy for us, and we can postpone the work
3002d33d630SMike Stump             // until then.
3012d33d630SMike Stump             uint64_t offset = BlockDecls[BDRE->getDecl()];
3022d33d630SMike Stump 
3032d33d630SMike Stump             llvm::Value *BlockLiteral = LoadBlockStruct();
3042d33d630SMike Stump 
3052d33d630SMike Stump             Loc = Builder.CreateGEP(BlockLiteral,
30641a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
3072d33d630SMike Stump                                                            offset),
3082d33d630SMike Stump                                     "block.literal");
3099793f0e4SOwen Anderson             Ty = llvm::PointerType::get(Ty, 0);
31097d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
3112d33d630SMike Stump             Loc = Builder.CreateLoad(Loc, false);
3122d33d630SMike Stump             // Loc = Builder.CreateBitCast(Loc, Ty);
31397d01d50SMike Stump           }
31497d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
31597d01d50SMike Stump         } else if (r.isComplex())
316b750d928SMike Stump           // FIXME: implement
317b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
318b750d928SMike Stump         else if (r.isAggregate())
319b750d928SMike Stump           ; // Already created into the destination
320b750d928SMike Stump         else
321b750d928SMike Stump           assert (0 && "bad block variable");
322b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
323b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
324b750d928SMike Stump       }
325aeb0ffd5SMike Stump     NoteForHelper.resize(helpersize);
326d6ef62f0SMike Stump 
327d6ef62f0SMike Stump     // __descriptor
328d2142cffSMike Stump     llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
329d2142cffSMike Stump                                                        subBlockSize, Ty,
330aeb0ffd5SMike Stump                                                        &NoteForHelper);
331aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
332aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
333b750d928SMike Stump   }
334b750d928SMike Stump 
335b750d928SMike Stump   QualType BPT = BE->getType();
336b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
337b750d928SMike Stump }
33885284bacSMike Stump 
33985284bacSMike Stump 
34095435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
341650c932dSMike Stump   if (BlockDescriptorType)
342650c932dSMike Stump     return BlockDescriptorType;
3432437cbfaSAnders Carlsson 
3442437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
345650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3462437cbfaSAnders Carlsson 
3472437cbfaSAnders Carlsson   // struct __block_descriptor {
3482437cbfaSAnders Carlsson   //   unsigned long reserved;
3492437cbfaSAnders Carlsson   //   unsigned long block_size;
3502437cbfaSAnders Carlsson   // };
351758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
352758428f4SOwen Anderson                                               UnsignedLongTy,
3532437cbfaSAnders Carlsson                                               UnsignedLongTy,
3542437cbfaSAnders Carlsson                                               NULL);
3552437cbfaSAnders Carlsson 
356650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
357650c932dSMike Stump                           BlockDescriptorType);
3582437cbfaSAnders Carlsson 
359650c932dSMike Stump   return BlockDescriptorType;
3602437cbfaSAnders Carlsson }
3612437cbfaSAnders Carlsson 
36295435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
363005c9a62SMike Stump   if (GenericBlockLiteralType)
364005c9a62SMike Stump     return GenericBlockLiteralType;
3652437cbfaSAnders Carlsson 
3662437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
3679793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
3682437cbfaSAnders Carlsson 
36992bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
37092bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
37192bbd6d4SMike Stump 
3722437cbfaSAnders Carlsson   // struct __block_literal_generic {
3735d2534adSMike Stump   //   void *__isa;
3745d2534adSMike Stump   //   int __flags;
3755d2534adSMike Stump   //   int __reserved;
3765d2534adSMike Stump   //   void (*__invoke)(void *);
3775d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3782437cbfaSAnders Carlsson   // };
379758428f4SOwen Anderson   GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
380758428f4SOwen Anderson                                                   PtrToInt8Ty,
38192bbd6d4SMike Stump                                                   IntTy,
38292bbd6d4SMike Stump                                                   IntTy,
383626aecc4SMike Stump                                                   PtrToInt8Ty,
3842437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
3852437cbfaSAnders Carlsson                                                   NULL);
3862437cbfaSAnders Carlsson 
387005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
388005c9a62SMike Stump                           GenericBlockLiteralType);
3892437cbfaSAnders Carlsson 
390005c9a62SMike Stump   return GenericBlockLiteralType;
3912437cbfaSAnders Carlsson }
3922437cbfaSAnders Carlsson 
39395435674SMike Stump const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
3945d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
3955d2534adSMike Stump     return GenericExtendedBlockLiteralType;
3965d2534adSMike Stump 
3975d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
3989793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
3995d2534adSMike Stump 
4005d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
4015d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
4025d2534adSMike Stump 
4035d2534adSMike Stump   // struct __block_literal_generic {
4045d2534adSMike Stump   //   void *__isa;
4055d2534adSMike Stump   //   int __flags;
4065d2534adSMike Stump   //   int __reserved;
4075d2534adSMike Stump   //   void (*__invoke)(void *);
4085d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
4095d2534adSMike Stump   //   void *__copy_func_helper_decl;
4105d2534adSMike Stump   //   void *__destroy_func_decl;
4115d2534adSMike Stump   // };
412758428f4SOwen Anderson   GenericExtendedBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
413758428f4SOwen Anderson                                                           PtrToInt8Ty,
4145d2534adSMike Stump                                                           IntTy,
4155d2534adSMike Stump                                                           IntTy,
416626aecc4SMike Stump                                                           PtrToInt8Ty,
4175d2534adSMike Stump                                                           BlockDescPtrTy,
418626aecc4SMike Stump                                                           PtrToInt8Ty,
419626aecc4SMike Stump                                                           PtrToInt8Ty,
4205d2534adSMike Stump                                                           NULL);
4215d2534adSMike Stump 
4225d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
4235d2534adSMike Stump                           GenericExtendedBlockLiteralType);
4245d2534adSMike Stump 
4255d2534adSMike Stump   return GenericExtendedBlockLiteralType;
4265d2534adSMike Stump }
4275d2534adSMike Stump 
4286a60fa24SAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
4292437cbfaSAnders Carlsson   const BlockPointerType *BPT =
430c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
4312437cbfaSAnders Carlsson 
4322437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
4332437cbfaSAnders Carlsson 
4342437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
4352437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
4369793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
4372437cbfaSAnders Carlsson 
4382437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
4392437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
4402437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4412437cbfaSAnders Carlsson 
4422437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4432437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
4442437cbfaSAnders Carlsson 
4452437cbfaSAnders Carlsson   BlockLiteral =
4462437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
447abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
4482437cbfaSAnders Carlsson                           "tmp");
4492437cbfaSAnders Carlsson 
4502437cbfaSAnders Carlsson   // Add the block literal.
4512437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4522437cbfaSAnders Carlsson   CallArgList Args;
4532437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4542437cbfaSAnders Carlsson 
455479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
456479e6fc7SAnders Carlsson 
4572437cbfaSAnders Carlsson   // And the rest of the arguments.
4589dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
459479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
4602437cbfaSAnders Carlsson 
4615f50c651SAnders Carlsson   // Load the function.
4625f50c651SAnders Carlsson   llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
4635f50c651SAnders Carlsson 
4649dd450bbSJohn McCall   QualType ResultType = FnType->getAs<FunctionType>()->getResultType();
465a60cbcdfSAnders Carlsson 
466a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
467a60cbcdfSAnders Carlsson     CGM.getTypes().getFunctionInfo(ResultType, Args);
4685f50c651SAnders Carlsson 
4695f50c651SAnders Carlsson   // Cast the function pointer to the right type.
4705f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
471a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
4725f50c651SAnders Carlsson 
4739793f0e4SOwen Anderson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
4745f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
4755f50c651SAnders Carlsson 
4762437cbfaSAnders Carlsson   // And call the block.
477350da607SAnders Carlsson   return EmitCall(FnInfo, Func, Args);
4782437cbfaSAnders Carlsson }
4796a60fa24SAnders Carlsson 
4807fe9cc1dSMike Stump uint64_t CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
4810168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
4820168f4b2SAnders Carlsson   uint64_t &offset = BlockDecls[VD];
4830168f4b2SAnders Carlsson 
48497d01d50SMike Stump   // See if we have already allocated an offset for this variable.
4857fe9cc1dSMike Stump   if (offset)
4867fe9cc1dSMike Stump     return offset;
4877fe9cc1dSMike Stump 
4884446dcf0SMike Stump   // Don't run the expensive check, unless we have to.
489*e1b19ba0SMike Stump   if (!BlockHasCopyDispose)
490*e1b19ba0SMike Stump     if (E->isByRef()
491*e1b19ba0SMike Stump         || BlockRequiresCopying(E->getType()))
4924446dcf0SMike Stump       BlockHasCopyDispose = true;
4937fe9cc1dSMike Stump 
49497d01d50SMike Stump   // if not, allocate one now.
49597d01d50SMike Stump   offset = getBlockOffset(E);
4967fe9cc1dSMike Stump 
4977fe9cc1dSMike Stump   return offset;
49897d01d50SMike Stump }
49997d01d50SMike Stump 
5007fe9cc1dSMike Stump llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
5017fe9cc1dSMike Stump   const ValueDecl *VD = E->getDecl();
5027fe9cc1dSMike Stump   uint64_t offset = AllocateBlockDecl(E);
5037fe9cc1dSMike Stump 
5047fe9cc1dSMike Stump 
50597d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
50697d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
50741a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
50897d01d50SMike Stump                                                          offset),
5092d33d630SMike Stump                                      "block.literal");
51097d01d50SMike Stump   if (E->isByRef()) {
51197d01d50SMike Stump     const llvm::Type *PtrStructTy
5120168f4b2SAnders Carlsson       = llvm::PointerType::get(BuildByRefType(VD), 0);
513efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
514efd7caa8SMike Stump     BlockHasCopyDispose = true;
5150168f4b2SAnders Carlsson 
5160168f4b2SAnders Carlsson     const llvm::Type *Ty = PtrStructTy;
5179793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
51897d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
51997d01d50SMike Stump     V = Builder.CreateLoad(V, false);
52097d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
52197d01d50SMike Stump     V = Builder.CreateLoad(V, false);
52297d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
5230168f4b2SAnders Carlsson     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
5240168f4b2SAnders Carlsson                                 VD->getNameAsString());
52597d01d50SMike Stump   } else {
5260168f4b2SAnders Carlsson     const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
5270168f4b2SAnders Carlsson 
5289793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
52997d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
53097d01d50SMike Stump   }
53197d01d50SMike Stump   return V;
53297d01d50SMike Stump }
53397d01d50SMike Stump 
534692c6e37SMike Stump void CodeGenFunction::BlockForwardSelf() {
535692c6e37SMike Stump   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
536692c6e37SMike Stump   ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
537692c6e37SMike Stump   llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
538692c6e37SMike Stump   if (DMEntry)
539692c6e37SMike Stump     return;
540692c6e37SMike Stump   // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
541692c6e37SMike Stump   BlockDeclRefExpr *BDRE = new (getContext())
542692c6e37SMike Stump     BlockDeclRefExpr(SelfDecl,
543692c6e37SMike Stump                      SelfDecl->getType(), SourceLocation(), false);
544692c6e37SMike Stump   DMEntry = GetAddrOfBlockDecl(BDRE);
545692c6e37SMike Stump }
546692c6e37SMike Stump 
5472d5a2878SMike Stump llvm::Constant *
5486c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
5496a60fa24SAnders Carlsson   // Generate the block descriptor.
5506a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
55192bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
55292bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
5536a60fa24SAnders Carlsson 
5546a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
5556a60fa24SAnders Carlsson 
5566a60fa24SAnders Carlsson   // Reserved
5570b75f23bSOwen Anderson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
5586a60fa24SAnders Carlsson 
5596a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
5606a60fa24SAnders Carlsson   // block literal struct.
5616a60fa24SAnders Carlsson   uint64_t BlockLiteralSize =
562005c9a62SMike Stump     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
563170229f6SOwen Anderson   DescriptorFields[1] =
564b7a2fe6fSOwen Anderson                       llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
5656a60fa24SAnders Carlsson 
5666a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
56741eaf0acSNick Lewycky     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 2, false);
5686a60fa24SAnders Carlsson 
5696a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
570c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
5716a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
572c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
5736a60fa24SAnders Carlsson 
5746a60fa24SAnders Carlsson   // Generate the constants for the block literal.
5756a60fa24SAnders Carlsson   llvm::Constant *LiteralFields[5];
5766a60fa24SAnders Carlsson 
5772d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
578b750d928SMike Stump   uint64_t subBlockSize, subBlockAlign;
5791db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
580a61bb4d1SDaniel Dunbar   bool subBlockHasCopyDispose = false;
5815469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
582cb2fbcb0SMike Stump   llvm::Function *Fn
583692c6e37SMike Stump     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
5845469f29aSMike Stump                                                  subBlockSize,
585b750d928SMike Stump                                                  subBlockAlign,
5864446dcf0SMike Stump                                                  subBlockDeclRefDecls,
5874446dcf0SMike Stump                                                  subBlockHasCopyDispose);
588cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
589cb2fbcb0SMike Stump          && "no imports allowed for global block");
5906a60fa24SAnders Carlsson 
5916a60fa24SAnders Carlsson   // isa
592971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
5936a60fa24SAnders Carlsson 
5946a60fa24SAnders Carlsson   // Flags
5955878c797SAnders Carlsson   LiteralFields[1] =
596b7a2fe6fSOwen Anderson     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
5976a60fa24SAnders Carlsson 
5986a60fa24SAnders Carlsson   // Reserved
5990b75f23bSOwen Anderson   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
6006a60fa24SAnders Carlsson 
6016a60fa24SAnders Carlsson   // Function
6026a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
6036a60fa24SAnders Carlsson 
6046a60fa24SAnders Carlsson   // Descriptor
6056a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
6066a60fa24SAnders Carlsson 
6076a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
60841eaf0acSNick Lewycky     llvm::ConstantStruct::get(VMContext, &LiteralFields[0], 5, false);
6096a60fa24SAnders Carlsson 
6106a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
611c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
6126a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
613c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
6146a60fa24SAnders Carlsson 
6156a60fa24SAnders Carlsson   return BlockLiteral;
6166a60fa24SAnders Carlsson }
6176a60fa24SAnders Carlsson 
618cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
61938382028SMike Stump   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
62038382028SMike Stump                                       "self");
62138382028SMike Stump   // For now, we codegen based upon byte offsets.
62238382028SMike Stump   return Builder.CreateBitCast(V, PtrToInt8Ty);
623cb2fbcb0SMike Stump }
624cb2fbcb0SMike Stump 
6254446dcf0SMike Stump llvm::Function *
6264446dcf0SMike Stump CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
627cb2fbcb0SMike Stump                                        const BlockInfo& Info,
628692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
6295469f29aSMike Stump                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm,
630b750d928SMike Stump                                        uint64_t &Size,
631b750d928SMike Stump                                        uint64_t &Align,
6324446dcf0SMike Stump                        llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
6334446dcf0SMike Stump                                        bool &subBlockHasCopyDispose) {
6349074ed8cSDevang Patel 
6359074ed8cSDevang Patel   // Check if we should generate debug info for this block.
6369074ed8cSDevang Patel   if (CGM.getDebugInfo())
6379074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
6389074ed8cSDevang Patel 
6395469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
6405469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
6415469f29aSMike Stump   // in a block.
6425469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
6435469f29aSMike Stump        i != ldm.end();
6445469f29aSMike Stump        ++i) {
6455469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
6465469f29aSMike Stump 
6470ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
6485469f29aSMike Stump       LocalDeclMap[VD] = i->second;
6495469f29aSMike Stump   }
6505469f29aSMike Stump 
65109a9b6e3SEli Friedman   // FIXME: We need to rearrange the code for copy/dispose so we have this
65209a9b6e3SEli Friedman   // sooner, so we can calculate offsets correctly.
65309a9b6e3SEli Friedman   if (!BlockHasCopyDispose)
65409a9b6e3SEli Friedman     BlockOffset = CGM.getTargetData()
65509a9b6e3SEli Friedman       .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
65609a9b6e3SEli Friedman   else
65709a9b6e3SEli Friedman     BlockOffset = CGM.getTargetData()
65809a9b6e3SEli Friedman       .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
65909a9b6e3SEli Friedman   BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
66009a9b6e3SEli Friedman 
661aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
662aae4349dSFariborz Jahanian   QualType ResultType;
663aae4349dSFariborz Jahanian   bool IsVariadic;
664a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
665a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
666aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
667aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
668658fe02dSMike Stump   } else {
669aae4349dSFariborz Jahanian     // K&R style block.
670aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
671aae4349dSFariborz Jahanian     IsVariadic = false;
672aae4349dSFariborz Jahanian   }
6736a60fa24SAnders Carlsson 
6746a60fa24SAnders Carlsson   FunctionArgList Args;
6756a60fa24SAnders Carlsson 
6767fe9cc1dSMike Stump   CurFuncDecl = OuterFuncDecl;
6777fe9cc1dSMike Stump 
6783385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
6796a60fa24SAnders Carlsson 
6807fe9cc1dSMike Stump   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
681d015328fSMike Stump 
682945fec05SMike Stump   // Allocate all BlockDeclRefDecls, so we can calculate the right ParmTy below.
6837fe9cc1dSMike Stump   AllocateAllBlockDeclRefs(Info, this);
6847fe9cc1dSMike Stump 
685*e1b19ba0SMike Stump   QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
686*e1b19ba0SMike Stump                                                   BlockDeclRefDecls);
6876a60fa24SAnders Carlsson   // FIXME: This leaks
6886a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
6896a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
690d015328fSMike Stump                               SourceLocation(), II,
691d015328fSMike Stump                               ParmTy);
6926a60fa24SAnders Carlsson 
6936a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
694cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
6956a60fa24SAnders Carlsson 
696c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
6976a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
698eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
6996a60fa24SAnders Carlsson 
7006a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
701aae4349dSFariborz Jahanian     CGM.getTypes().getFunctionInfo(ResultType, Args);
7026a60fa24SAnders Carlsson 
7032d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
7046a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
705aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
7066a60fa24SAnders Carlsson 
7076a60fa24SAnders Carlsson   llvm::Function *Fn =
7086a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
7096a60fa24SAnders Carlsson                            Name,
7106a60fa24SAnders Carlsson                            &CGM.getModule());
7116a60fa24SAnders Carlsson 
712c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
713c3e7cff6SDaniel Dunbar 
714324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
7153385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
7162e722b91SMike Stump 
717324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
71828ec0cf8SChris Lattner   CurCodeDecl = BD;
719017460abSMike Stump 
720017460abSMike Stump   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
721017460abSMike Stump   llvm::BasicBlock *entry = Builder.GetInsertBlock();
722017460abSMike Stump   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
723017460abSMike Stump   --entry_ptr;
724017460abSMike Stump 
7253385fe12SChris Lattner   EmitStmt(BExpr->getBody());
726017460abSMike Stump 
7277d69911aSMike Stump   // Remember where we were...
7287d69911aSMike Stump   llvm::BasicBlock *resume = Builder.GetInsertBlock();
729017460abSMike Stump 
7307d69911aSMike Stump   // Go back to the entry.
731017460abSMike Stump   ++entry_ptr;
732017460abSMike Stump   Builder.SetInsertPoint(entry, entry_ptr);
733017460abSMike Stump 
7342e722b91SMike Stump   if (CGDebugInfo *DI = getDebugInfo()) {
7352e722b91SMike Stump     // Emit debug information for all the BlockDeclRefDecls.
7362e722b91SMike Stump     for (unsigned i=0; i < BlockDeclRefDecls.size(); ++i) {
7372e722b91SMike Stump       const Expr *E = BlockDeclRefDecls[i];
7382e722b91SMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
7392e722b91SMike Stump       if (BDRE) {
7402e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
7412e722b91SMike Stump         DI->setLocation(D->getLocation());
7422e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
7432e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
7442e722b91SMike Stump                                               Builder, this);
7452e722b91SMike Stump       }
7462e722b91SMike Stump     }
7472e722b91SMike Stump   }
7487d69911aSMike Stump   // And resume where we left off.
7497d69911aSMike Stump   if (resume == 0)
7507d69911aSMike Stump     Builder.ClearInsertionPoint();
7517d69911aSMike Stump   else
7527d69911aSMike Stump     Builder.SetInsertPoint(resume);
7532e722b91SMike Stump 
7543385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
7556a60fa24SAnders Carlsson 
756b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
757b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
758b750d928SMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
759b750d928SMike Stump 
760cb2fbcb0SMike Stump   Size = BlockOffset;
761b750d928SMike Stump   Align = BlockAlign;
762b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
7634446dcf0SMike Stump   subBlockHasCopyDispose |= BlockHasCopyDispose;
7646a60fa24SAnders Carlsson   return Fn;
7656a60fa24SAnders Carlsson }
7661db7d04bSMike Stump 
767aeb0ffd5SMike Stump uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
7681db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
7691db7d04bSMike Stump 
7701db7d04bSMike Stump   uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
7711db7d04bSMike Stump   uint64_t Align = getContext().getDeclAlignInBytes(D);
7721db7d04bSMike Stump 
7731db7d04bSMike Stump   if (BDRE->isByRef()) {
7741db7d04bSMike Stump     Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
7751db7d04bSMike Stump     Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
7761db7d04bSMike Stump   }
7771db7d04bSMike Stump 
7781db7d04bSMike Stump   assert ((Align > 0) && "alignment must be 1 byte or more");
7791db7d04bSMike Stump 
7801db7d04bSMike Stump   uint64_t OldOffset = BlockOffset;
7811db7d04bSMike Stump 
7821db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
7831db7d04bSMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
7841db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
7851db7d04bSMike Stump 
7861db7d04bSMike Stump   uint64_t Pad = BlockOffset - OldOffset;
7871db7d04bSMike Stump   if (Pad) {
78841a75027SOwen Anderson     llvm::ArrayType::get(llvm::Type::getInt8Ty(VMContext), Pad);
7891db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
7901db7d04bSMike Stump                                                        llvm::APInt(32, Pad),
7911db7d04bSMike Stump                                                        ArrayType::Normal, 0);
7921db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
7936032ef1aSArgyrios Kyrtzidis                                          0, QualType(PadTy), 0, VarDecl::None);
7941db7d04bSMike Stump     Expr *E;
7951db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
7961db7d04bSMike Stump                                        SourceLocation(), false, false);
7971db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
7981db7d04bSMike Stump   }
7991db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
8001db7d04bSMike Stump 
8011db7d04bSMike Stump   BlockOffset += Size;
8021db7d04bSMike Stump   return BlockOffset-Size;
8031db7d04bSMike Stump }
80497d01d50SMike Stump 
805aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
806aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
80767645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
8080c743277SMike Stump   QualType R = getContext().VoidTy;
8090c743277SMike Stump 
8100c743277SMike Stump   FunctionArgList Args;
8110c743277SMike Stump   // FIXME: This leaks
812aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
8137fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8147fe9cc1dSMike Stump                               SourceLocation(), 0,
815aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
816aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
8170c743277SMike Stump   ImplicitParamDecl *Src =
8187fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8197fe9cc1dSMike Stump                               SourceLocation(), 0,
8200c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
8210c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
8220c743277SMike Stump 
8230c743277SMike Stump   const CGFunctionInfo &FI =
8240c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
8250c743277SMike Stump 
826cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
827cbc2bcafSMike Stump   // internal linkage.
8280c743277SMike Stump   std::string Name = std::string("__copy_helper_block_");
8290c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
8300c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8310c743277SMike Stump 
8320c743277SMike Stump   llvm::Function *Fn =
8330c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
8340c743277SMike Stump                            Name,
8350c743277SMike Stump                            &CGM.getModule());
8360c743277SMike Stump 
8370c743277SMike Stump   IdentifierInfo *II
8380c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
8390c743277SMike Stump 
8400c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8410c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
84260ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
8430c743277SMike Stump                                           FunctionDecl::Static, false,
8440c743277SMike Stump                                           true);
8450c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
846aeb0ffd5SMike Stump 
847aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
848aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
84967645930SMike Stump 
85067645930SMike Stump   if (NoteForHelperp) {
85167645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
85267645930SMike Stump 
8539793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
854aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
855aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
856aeb0ffd5SMike Stump 
857aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
8583b65ac26SMike Stump     llvm::Type *PtrPtrT;
8599793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
8603b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
8613b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
862aeb0ffd5SMike Stump 
863aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
864aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
865aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
866aeb0ffd5SMike Stump 
867aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
868aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
869aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
870aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
871aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
8729793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
873aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
874aeb0ffd5SMike Stump 
875aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
876aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
877aeb0ffd5SMike Stump 
87841a75027SOwen Anderson         llvm::Value *N = llvm::ConstantInt::get(
87941a75027SOwen Anderson               llvm::Type::getInt32Ty(T->getContext()), flag);
880aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
881aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
882aeb0ffd5SMike Stump       }
883aeb0ffd5SMike Stump     }
88467645930SMike Stump   }
885aeb0ffd5SMike Stump 
8860c743277SMike Stump   CGF.FinishFunction();
8870c743277SMike Stump 
888ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
88997d01d50SMike Stump }
89097d01d50SMike Stump 
891d6ef62f0SMike Stump llvm::Constant *BlockFunction::
892aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
893aeb0ffd5SMike Stump                               const llvm::StructType* T,
89467645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
8950c743277SMike Stump   QualType R = getContext().VoidTy;
8960c743277SMike Stump 
8970c743277SMike Stump   FunctionArgList Args;
8980c743277SMike Stump   // FIXME: This leaks
8990c743277SMike Stump   ImplicitParamDecl *Src =
9007fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9017fe9cc1dSMike Stump                               SourceLocation(), 0,
9020c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
9030c743277SMike Stump 
9040c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
9050c743277SMike Stump 
9060c743277SMike Stump   const CGFunctionInfo &FI =
9070c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
9080c743277SMike Stump 
909cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
910cbc2bcafSMike Stump   // internal linkage.
9110c743277SMike Stump   std::string Name = std::string("__destroy_helper_block_");
9120c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
9130c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
9140c743277SMike Stump 
9150c743277SMike Stump   llvm::Function *Fn =
9160c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
9170c743277SMike Stump                            Name,
9180c743277SMike Stump                            &CGM.getModule());
9190c743277SMike Stump 
9200c743277SMike Stump   IdentifierInfo *II
9210c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
9220c743277SMike Stump 
9230c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
9240c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
92560ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
9260c743277SMike Stump                                           FunctionDecl::Static, false,
9270c743277SMike Stump                                           true);
9280c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
9296f7d9f87SMike Stump 
93067645930SMike Stump   if (NoteForHelperp) {
93167645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
93267645930SMike Stump 
9336f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
9346f7d9f87SMike Stump     llvm::Type *PtrPtrT;
9359793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9366f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
9376f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
9386f7d9f87SMike Stump 
9396f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
9406f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
9416f7d9f87SMike Stump       int index = NoteForHelper[i].index;
9426f7d9f87SMike Stump 
9436f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
9446f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
9456f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
9466f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
9476f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9489793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
9496f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
9506f7d9f87SMike Stump 
9516f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
9526f7d9f87SMike Stump       }
9536f7d9f87SMike Stump     }
95467645930SMike Stump   }
9556f7d9f87SMike Stump 
9560c743277SMike Stump   CGF.FinishFunction();
9570c743277SMike Stump 
958ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
9590c743277SMike Stump }
9600c743277SMike Stump 
961aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
96267645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
963aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
964aeb0ffd5SMike Stump                                                          T, NoteForHelper);
9650c743277SMike Stump }
9660c743277SMike Stump 
967aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
96867645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
969aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
97067645930SMike Stump                                                             T, NoteForHelperp);
97197d01d50SMike Stump }
972626aecc4SMike Stump 
973f89230d9SMike Stump llvm::Constant *BlockFunction::
974f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
975ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
976ee2a5ee5SMike Stump 
977ee2a5ee5SMike Stump   FunctionArgList Args;
978ee2a5ee5SMike Stump   // FIXME: This leaks
979f89230d9SMike Stump   ImplicitParamDecl *Dst =
9807fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9817fe9cc1dSMike Stump                               SourceLocation(), 0,
982f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
983f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
984f89230d9SMike Stump 
985f89230d9SMike Stump   // FIXME: This leaks
986ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
9877fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9887fe9cc1dSMike Stump                               SourceLocation(), 0,
989ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
990ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
991ee2a5ee5SMike Stump 
992ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
993ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
994ee2a5ee5SMike Stump 
995ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_copy_");
996ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
997ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
998ee2a5ee5SMike Stump 
999cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1000cbc2bcafSMike Stump   // internal linkage.
1001ee2a5ee5SMike Stump   llvm::Function *Fn =
1002ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1003ee2a5ee5SMike Stump                            Name,
1004ee2a5ee5SMike Stump                            &CGM.getModule());
1005ee2a5ee5SMike Stump 
1006ee2a5ee5SMike Stump   IdentifierInfo *II
1007ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1008ee2a5ee5SMike Stump 
1009ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1010ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
101160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1012ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1013ee2a5ee5SMike Stump                                           true);
1014ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1015f89230d9SMike Stump 
1016f89230d9SMike Stump   // dst->x
1017f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
10189793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10193b65ac26SMike Stump   V = Builder.CreateLoad(V);
1020f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
1021f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1022f89230d9SMike Stump 
1023f89230d9SMike Stump   // src->x
1024f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
1025f89230d9SMike Stump   V = Builder.CreateLoad(V);
1026f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
1027f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10289793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1029f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
1030f89230d9SMike Stump 
1031f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
1032f89230d9SMike Stump 
103341a75027SOwen Anderson   llvm::Value *N = llvm::ConstantInt::get(
103441a75027SOwen Anderson           llvm::Type::getInt32Ty(T->getContext()), flag);
1035f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
1036f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1037f89230d9SMike Stump 
1038ee2a5ee5SMike Stump   CGF.FinishFunction();
1039ee2a5ee5SMike Stump 
1040ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1041ee2a5ee5SMike Stump }
1042ee2a5ee5SMike Stump 
1043fbe25dd1SMike Stump llvm::Constant *
1044fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1045fbe25dd1SMike Stump                                                   int flag) {
1046ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1047ee2a5ee5SMike Stump 
1048ee2a5ee5SMike Stump   FunctionArgList Args;
1049ee2a5ee5SMike Stump   // FIXME: This leaks
1050ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10517fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10527fe9cc1dSMike Stump                               SourceLocation(), 0,
1053ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1054ee2a5ee5SMike Stump 
1055ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1056ee2a5ee5SMike Stump 
1057ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1058ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
1059ee2a5ee5SMike Stump 
1060ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_dispose_");
1061ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1062ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1063ee2a5ee5SMike Stump 
1064cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1065cbc2bcafSMike Stump   // internal linkage.
1066ee2a5ee5SMike Stump   llvm::Function *Fn =
1067ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1068ee2a5ee5SMike Stump                            Name,
1069ee2a5ee5SMike Stump                            &CGM.getModule());
1070ee2a5ee5SMike Stump 
1071ee2a5ee5SMike Stump   IdentifierInfo *II
1072ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1073ee2a5ee5SMike Stump 
1074ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1075ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
107660ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1077ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1078ee2a5ee5SMike Stump                                           true);
1079ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1080fbe25dd1SMike Stump 
1081fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
10829793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10833b65ac26SMike Stump   V = Builder.CreateLoad(V);
1084fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10859793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
10863b65ac26SMike Stump   V = Builder.CreateLoad(V);
1087fbe25dd1SMike Stump 
1088fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1089fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1090ee2a5ee5SMike Stump   CGF.FinishFunction();
1091ee2a5ee5SMike Stump 
1092ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1093ee2a5ee5SMike Stump }
1094ee2a5ee5SMike Stump 
1095f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1096cbc2bcafSMike Stump                                                     int flag, unsigned Align) {
1097cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1098cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1099cbc2bcafSMike Stump   // with.
1100cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1101cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1102cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1103cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1104cbc2bcafSMike Stump   uint64_t kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + flag;
1105cbc2bcafSMike Stump   llvm::Constant *& Entry = CGM.AssignCache[kind];
1106cbc2bcafSMike Stump   if (Entry)
1107cbc2bcafSMike Stump     return Entry;
1108cbc2bcafSMike Stump   return Entry=CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
1109ee2a5ee5SMike Stump }
1110ee2a5ee5SMike Stump 
1111fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1112cbc2bcafSMike Stump                                                        int flag,
1113cbc2bcafSMike Stump                                                        unsigned Align) {
1114cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1115cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1116cbc2bcafSMike Stump   // with.
1117cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1118cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1119cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1120cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1121cbc2bcafSMike Stump   uint64_t kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + flag;
1122cbc2bcafSMike Stump   llvm::Constant *& Entry = CGM.DestroyCache[kind];
1123cbc2bcafSMike Stump   if (Entry)
1124cbc2bcafSMike Stump     return Entry;
1125cbc2bcafSMike Stump   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
1126ee2a5ee5SMike Stump }
1127ee2a5ee5SMike Stump 
1128626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1129626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1130626aecc4SMike Stump     const llvm::FunctionType *FTy;
1131626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
113241a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1133626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
113441a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11359793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1136626aecc4SMike Stump     CGM.BlockObjectDispose
1137626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1138626aecc4SMike Stump   }
1139626aecc4SMike Stump   return CGM.BlockObjectDispose;
1140626aecc4SMike Stump }
1141626aecc4SMike Stump 
1142f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1143f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1144f89230d9SMike Stump     const llvm::FunctionType *FTy;
1145f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
114641a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1147f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1148f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
114941a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11509793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1151f89230d9SMike Stump     CGM.BlockObjectAssign
1152f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1153f89230d9SMike Stump   }
1154f89230d9SMike Stump   return CGM.BlockObjectAssign;
1155f89230d9SMike Stump }
1156f89230d9SMike Stump 
1157fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1158626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1159fbe25dd1SMike Stump   llvm::Value *N;
1160626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
116141a75027SOwen Anderson   N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1162626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1163626aecc4SMike Stump }
11644446dcf0SMike Stump 
11654446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1166aeb0ffd5SMike Stump 
1167aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1168aeb0ffd5SMike Stump                              CGBuilderTy &B)
1169170229f6SOwen Anderson   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
117041a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
117141a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1172aeb0ffd5SMike Stump 
1173aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1174aeb0ffd5SMike Stump }
1175