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 
222437cbfaSAnders Carlsson using namespace clang;
232437cbfaSAnders Carlsson using namespace CodeGen;
242437cbfaSAnders Carlsson 
25d6ef62f0SMike Stump llvm::Constant *CodeGenFunction::
2640775003SKen Dyck BuildDescriptorBlockDecl(bool BlockHasCopyDispose, CharUnits Size,
27d2142cffSMike Stump                          const llvm::StructType* Ty,
28aeb0ffd5SMike Stump                          std::vector<HelperInfo> *NoteForHelper) {
29c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
30c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
3185284bacSMike Stump   llvm::Constant *C;
3285284bacSMike Stump   std::vector<llvm::Constant*> Elts;
3385284bacSMike Stump 
3485284bacSMike Stump   // reserved
35b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
3685284bacSMike Stump   Elts.push_back(C);
3785284bacSMike Stump 
3885284bacSMike Stump   // Size
392ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
402ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
412ac40a9fSMike Stump   // API to size_t.
4240775003SKen Dyck   C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
4385284bacSMike Stump   Elts.push_back(C);
4485284bacSMike Stump 
4585284bacSMike Stump   if (BlockHasCopyDispose) {
4685284bacSMike Stump     // copy_func_helper_decl
4767645930SMike Stump     Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
4885284bacSMike Stump 
4985284bacSMike Stump     // destroy_func_decl
5067645930SMike Stump     Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
5185284bacSMike Stump   }
5285284bacSMike Stump 
5341eaf0acSNick Lewycky   C = llvm::ConstantStruct::get(VMContext, Elts, false);
5485284bacSMike Stump 
55c10c8d3eSOwen Anderson   C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
5685284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
57c10c8d3eSOwen Anderson                                C, "__block_descriptor_tmp");
5885284bacSMike Stump   return C;
5985284bacSMike Stump }
6085284bacSMike Stump 
6195435674SMike Stump llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
6246813bbfSChris Lattner   if (NSConcreteGlobalBlock == 0)
6346813bbfSChris Lattner     NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
6446813bbfSChris Lattner                                                       "_NSConcreteGlobalBlock");
65971f9b66SMike Stump   return NSConcreteGlobalBlock;
66971f9b66SMike Stump }
67971f9b66SMike Stump 
6895435674SMike Stump llvm::Constant *BlockModule::getNSConcreteStackBlock() {
6946813bbfSChris Lattner   if (NSConcreteStackBlock == 0)
7046813bbfSChris Lattner     NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
7146813bbfSChris Lattner                                                      "_NSConcreteStackBlock");
727ab278dbSMike Stump   return NSConcreteStackBlock;
737ab278dbSMike Stump }
747ab278dbSMike Stump 
75066b6166SMike Stump static void CollectBlockDeclRefInfo(
76066b6166SMike Stump   const Stmt *S, CodeGenFunction::BlockInfo &Info,
77066b6166SMike Stump   llvm::SmallSet<const DeclContext *, 16> &InnerContexts) {
78ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
79ed5e69feSAnders Carlsson        I != E; ++I)
80dd942713SDaniel Dunbar     if (*I)
81066b6166SMike Stump       CollectBlockDeclRefInfo(*I, Info, InnerContexts);
82ed5e69feSAnders Carlsson 
837fe9cc1dSMike Stump   // We want to ensure we walk down into block literals so we can find
847fe9cc1dSMike Stump   // all nested BlockDeclRefExprs.
85066b6166SMike Stump   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
86066b6166SMike Stump     InnerContexts.insert(cast<DeclContext>(BE->getBlockDecl()));
87066b6166SMike Stump     CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
88066b6166SMike Stump   }
897fe9cc1dSMike Stump 
90066b6166SMike Stump   if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
91ed5e69feSAnders Carlsson     // FIXME: Handle enums.
92066b6166SMike Stump     if (isa<FunctionDecl>(BDRE->getDecl()))
93ed5e69feSAnders Carlsson       return;
94ed5e69feSAnders Carlsson 
95066b6166SMike Stump     // Only Decls that escape are added.
96066b6166SMike Stump     if (!InnerContexts.count(BDRE->getDecl()->getDeclContext()))
97066b6166SMike Stump       Info.DeclRefs.push_back(BDRE);
98ed5e69feSAnders Carlsson   }
99ed5e69feSAnders Carlsson }
100ed5e69feSAnders Carlsson 
1012d33d630SMike Stump /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
1022d33d630SMike Stump /// declared as a global variable instead of on the stack.
10346813bbfSChris Lattner static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info) {
1047fe9cc1dSMike Stump   return Info.DeclRefs.empty();
1057fe9cc1dSMike Stump }
1067fe9cc1dSMike Stump 
1077fe9cc1dSMike Stump /// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
1087fe9cc1dSMike Stump /// ensure we can generate the debug information for the parameter for the block
1097fe9cc1dSMike Stump /// invoke function.
1107fe9cc1dSMike Stump static void AllocateAllBlockDeclRefs(const CodeGenFunction::BlockInfo &Info,
1117fe9cc1dSMike Stump                                      CodeGenFunction *CGF) {
1127fe9cc1dSMike Stump   // Always allocate self, as it is often handy in the debugger, even if there
1137fe9cc1dSMike Stump   // is no codegen in the block that uses it.  This is also useful to always do
1147fe9cc1dSMike Stump   // this as if we didn't, we'd have to figure out all code that uses a self
1157fe9cc1dSMike Stump   // pointer, including implicit uses.
1167fe9cc1dSMike Stump   if (const ObjCMethodDecl *OMD
1177fe9cc1dSMike Stump       = dyn_cast_or_null<ObjCMethodDecl>(CGF->CurFuncDecl)) {
1187fe9cc1dSMike Stump     ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
1197fe9cc1dSMike Stump     BlockDeclRefExpr *BDRE = new (CGF->getContext())
1207fe9cc1dSMike Stump       BlockDeclRefExpr(SelfDecl,
1217fe9cc1dSMike Stump                        SelfDecl->getType(), SourceLocation(), false);
1227fe9cc1dSMike Stump     CGF->AllocateBlockDecl(BDRE);
1237fe9cc1dSMike Stump   }
1247fe9cc1dSMike Stump 
1257fe9cc1dSMike Stump   // FIXME: Also always forward the this pointer in C++ as well.
1267fe9cc1dSMike Stump 
1277fe9cc1dSMike Stump   for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
1287fe9cc1dSMike Stump     CGF->AllocateBlockDecl(Info.DeclRefs[i]);
129ed5e69feSAnders Carlsson }
130ed5e69feSAnders Carlsson 
1312d33d630SMike Stump // FIXME: Push most into CGM, passing down a few bits, like current function
1322d33d630SMike Stump // name.
133b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
134ed5e69feSAnders Carlsson 
135ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
136ed5e69feSAnders Carlsson   CodeGenFunction::BlockInfo Info(0, Name.c_str());
137066b6166SMike Stump   llvm::SmallSet<const DeclContext *, 16> InnerContexts;
138066b6166SMike Stump   InnerContexts.insert(BE->getBlockDecl());
139066b6166SMike Stump   CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
140ed5e69feSAnders Carlsson 
141ed5e69feSAnders Carlsson   // Check if the block can be global.
1422d33d630SMike Stump   // FIXME: This test doesn't work for nested blocks yet.  Longer term, I'd like
1432d33d630SMike Stump   // to just have one code path.  We should move this function into CGM and pass
1442d33d630SMike Stump   // CGF, then we can just check to see if CGF is 0.
14597d01d50SMike Stump   if (0 && CanBlockBeGlobal(Info))
146ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
14785284bacSMike Stump 
148950a9518SDavid Chisnall   size_t BlockFields = 5;
149950a9518SDavid Chisnall 
150950a9518SDavid Chisnall   bool hasIntrospection  = CGM.getContext().getLangOptions().BlockIntrospection;
151950a9518SDavid Chisnall 
152950a9518SDavid Chisnall   if (hasIntrospection) {
153950a9518SDavid Chisnall     BlockFields++;
154950a9518SDavid Chisnall   }
155950a9518SDavid Chisnall   std::vector<llvm::Constant*> Elts(BlockFields);
156950a9518SDavid Chisnall 
157950a9518SDavid Chisnall   if (hasIntrospection) {
158950a9518SDavid Chisnall     std::string BlockTypeEncoding;
159950a9518SDavid Chisnall     CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
160950a9518SDavid Chisnall 
161950a9518SDavid Chisnall     Elts[5] = llvm::ConstantExpr::getBitCast(
162950a9518SDavid Chisnall             CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
163950a9518SDavid Chisnall   }
164950a9518SDavid Chisnall 
16585284bacSMike Stump   llvm::Constant *C;
166b750d928SMike Stump   llvm::Value *V;
16785284bacSMike Stump 
16885284bacSMike Stump   {
16985284bacSMike Stump     // C = BuildBlockStructInitlist();
17085284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
17185284bacSMike Stump 
172950a9518SDavid Chisnall     if (hasIntrospection)
173950a9518SDavid Chisnall       flags |= BLOCK_HAS_OBJC_TYPE;
174950a9518SDavid Chisnall 
1754446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
1764446dcf0SMike Stump     // block literal.
1774446dcf0SMike Stump     // __invoke
17840775003SKen Dyck     CharUnits subBlockSize;
1795262b119SKen Dyck     CharUnits subBlockAlign;
1804446dcf0SMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
181d2142cffSMike Stump     bool subBlockHasCopyDispose = false;
1824446dcf0SMike Stump     llvm::Function *Fn
183d2a3e617SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
184d2a3e617SMike Stump                                                    LocalDeclMap,
1855469f29aSMike Stump                                                    subBlockSize,
1864446dcf0SMike Stump                                                    subBlockAlign,
1874446dcf0SMike Stump                                                    subBlockDeclRefDecls,
188d2142cffSMike Stump                                                    subBlockHasCopyDispose);
189d2142cffSMike Stump     BlockHasCopyDispose |= subBlockHasCopyDispose;
1904446dcf0SMike Stump     Elts[3] = Fn;
1914446dcf0SMike Stump 
19218bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
19318bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
194d2142cffSMike Stump     if (subBlockHasCopyDispose)
19585284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
19685284bacSMike Stump 
197499ae7ecSMike Stump     // __isa
1987ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
199ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
2004446dcf0SMike Stump     Elts[0] = C;
20185284bacSMike Stump 
20285284bacSMike Stump     // __flags
20385284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
20485284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
205b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
2064446dcf0SMike Stump     Elts[1] = C;
20785284bacSMike Stump 
20885284bacSMike Stump     // __reserved
209b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
2104446dcf0SMike Stump     Elts[2] = C;
21185284bacSMike Stump 
212b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
213d6ef62f0SMike Stump       // __descriptor
2147fe9cc1dSMike Stump       Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize,
2157fe9cc1dSMike Stump                                          0, 0);
216d6ef62f0SMike Stump 
2173a139f37SMike Stump       // Optimize to being a global block.
2183a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
219b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2203a139f37SMike Stump 
22141eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
22285284bacSMike Stump 
223c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
224d6b28fc6SBenjamin Kramer                                    llvm::GlobalValue::InternalLinkage, C,
225d6b28fc6SBenjamin Kramer                                    "__block_holder_tmp_" +
226d6b28fc6SBenjamin Kramer                                    llvm::Twine(CGM.getGlobalUniqueCount()));
2275d2534adSMike Stump       QualType BPT = BE->getType();
228ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
22985284bacSMike Stump       return C;
23085284bacSMike Stump     }
23185284bacSMike Stump 
232950a9518SDavid Chisnall     std::vector<const llvm::Type *> Types(BlockFields+subBlockDeclRefDecls.size());
233aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
234b750d928SMike Stump       Types[i] = Elts[i]->getType();
235aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
236950a9518SDavid Chisnall     if (hasIntrospection)
237950a9518SDavid Chisnall       Types[5] = PtrToInt8Ty;
23885284bacSMike Stump 
2391db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
2401db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
2411db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2421db7d04bSMike Stump       QualType Ty = E->getType();
24397d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
244950a9518SDavid Chisnall         Types[i+BlockFields] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
24597d01d50SMike Stump       } else
246950a9518SDavid Chisnall         Types[i+BlockFields] = ConvertType(Ty);
2471db7d04bSMike Stump     }
248b750d928SMike Stump 
249758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
250b750d928SMike Stump 
251b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
2525262b119SKen Dyck     A->setAlignment(subBlockAlign.getQuantity());
253b750d928SMike Stump     V = A;
254b750d928SMike Stump 
255aeb0ffd5SMike Stump     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
256aeb0ffd5SMike Stump     int helpersize = 0;
257aeb0ffd5SMike Stump 
258aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
259b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
260950a9518SDavid Chisnall     if (hasIntrospection)
261950a9518SDavid Chisnall       Builder.CreateStore(Elts[5], Builder.CreateStructGEP(V, 5, "block.tmp"));
262b750d928SMike Stump 
263b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
264b750d928SMike Stump       {
2651db7d04bSMike Stump         // FIXME: Push const down.
2661db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2671db7d04bSMike Stump         DeclRefExpr *DR;
2681db7d04bSMike Stump         ValueDecl *VD;
269b750d928SMike Stump 
2701db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2711db7d04bSMike Stump         // Skip padding.
2721db7d04bSMike Stump         if (DR) continue;
2731db7d04bSMike Stump 
2741db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2751db7d04bSMike Stump         VD = BDRE->getDecl();
2761db7d04bSMike Stump 
277950a9518SDavid Chisnall         llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
278aeb0ffd5SMike Stump         NoteForHelper[helpersize].index = i+5;
2792114d7c2SMike Stump         NoteForHelper[helpersize].RequiresCopying
2802114d7c2SMike Stump           = BlockRequiresCopying(VD->getType());
281aeb0ffd5SMike Stump         NoteForHelper[helpersize].flag
2822114d7c2SMike Stump           = (VD->getType()->isBlockPointerType()
2832114d7c2SMike Stump              ? BLOCK_FIELD_IS_BLOCK
2842114d7c2SMike Stump              : BLOCK_FIELD_IS_OBJECT);
285aeb0ffd5SMike Stump 
2861db7d04bSMike Stump         if (LocalDeclMap[VD]) {
28797d01d50SMike Stump           if (BDRE->isByRef()) {
288aeb0ffd5SMike Stump             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
28990d8daf5SMike Stump               // FIXME: Someone double check this.
29090d8daf5SMike Stump               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
29197d01d50SMike Stump             llvm::Value *Loc = LocalDeclMap[VD];
29297d01d50SMike Stump             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
293c76493a6SDaniel Dunbar             Loc = Builder.CreateLoad(Loc);
29497d01d50SMike Stump             Builder.CreateStore(Loc, Addr);
295aeb0ffd5SMike Stump             ++helpersize;
29697d01d50SMike Stump             continue;
29797d01d50SMike Stump           } else
298ce54657eSJohn McCall             E = new (getContext()) DeclRefExpr (VD,
299ed6c7440SDouglas Gregor                                                 VD->getType(),
300ed6c7440SDouglas Gregor                                                 SourceLocation());
3011db7d04bSMike Stump         }
30297d01d50SMike Stump         if (BDRE->isByRef()) {
303efd7caa8SMike Stump           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
304efd7caa8SMike Stump             // FIXME: Someone double check this.
305efd7caa8SMike Stump             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
3061db7d04bSMike Stump           E = new (getContext())
3071db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
3081db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
3091db7d04bSMike Stump                           SourceLocation());
31097d01d50SMike Stump         }
311aeb0ffd5SMike Stump         ++helpersize;
3121db7d04bSMike Stump 
3131db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
31497d01d50SMike Stump         if (r.isScalar()) {
31597d01d50SMike Stump           llvm::Value *Loc = r.getScalarVal();
316950a9518SDavid Chisnall           const llvm::Type *Ty = Types[i+BlockFields];
31797d01d50SMike Stump           if  (BDRE->isByRef()) {
3182d33d630SMike Stump             // E is now the address of the value field, instead, we want the
3192d33d630SMike Stump             // address of the actual ByRef struct.  We optimize this slightly
3202d33d630SMike Stump             // compared to gcc by not grabbing the forwarding slot as this must
3212d33d630SMike Stump             // be done during Block_copy for us, and we can postpone the work
3222d33d630SMike Stump             // until then.
32340775003SKen Dyck             CharUnits offset = BlockDecls[BDRE->getDecl()];
3242d33d630SMike Stump 
3252d33d630SMike Stump             llvm::Value *BlockLiteral = LoadBlockStruct();
3262d33d630SMike Stump 
3272d33d630SMike Stump             Loc = Builder.CreateGEP(BlockLiteral,
32841a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
32940775003SKen Dyck                                                            offset.getQuantity()),
3302d33d630SMike Stump                                     "block.literal");
3319793f0e4SOwen Anderson             Ty = llvm::PointerType::get(Ty, 0);
33297d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
333c76493a6SDaniel Dunbar             Loc = Builder.CreateLoad(Loc);
3342d33d630SMike Stump             // Loc = Builder.CreateBitCast(Loc, Ty);
33597d01d50SMike Stump           }
33697d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
33797d01d50SMike Stump         } else if (r.isComplex())
338b750d928SMike Stump           // FIXME: implement
339b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
340b750d928SMike Stump         else if (r.isAggregate())
341b750d928SMike Stump           ; // Already created into the destination
342b750d928SMike Stump         else
343b750d928SMike Stump           assert (0 && "bad block variable");
344b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
345b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
346b750d928SMike Stump       }
347aeb0ffd5SMike Stump     NoteForHelper.resize(helpersize);
348d6ef62f0SMike Stump 
349d6ef62f0SMike Stump     // __descriptor
350d2142cffSMike Stump     llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
351d2142cffSMike Stump                                                        subBlockSize, Ty,
352aeb0ffd5SMike Stump                                                        &NoteForHelper);
353aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
354aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
355b750d928SMike Stump   }
356b750d928SMike Stump 
357b750d928SMike Stump   QualType BPT = BE->getType();
358b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
359b750d928SMike Stump }
36085284bacSMike Stump 
36185284bacSMike Stump 
36295435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
363650c932dSMike Stump   if (BlockDescriptorType)
364650c932dSMike Stump     return BlockDescriptorType;
3652437cbfaSAnders Carlsson 
3662437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
367650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3682437cbfaSAnders Carlsson 
3692437cbfaSAnders Carlsson   // struct __block_descriptor {
3702437cbfaSAnders Carlsson   //   unsigned long reserved;
3712437cbfaSAnders Carlsson   //   unsigned long block_size;
3722437cbfaSAnders Carlsson   // };
373758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
374758428f4SOwen Anderson                                               UnsignedLongTy,
3752437cbfaSAnders Carlsson                                               UnsignedLongTy,
3762437cbfaSAnders Carlsson                                               NULL);
3772437cbfaSAnders Carlsson 
378650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
379650c932dSMike Stump                           BlockDescriptorType);
3802437cbfaSAnders Carlsson 
381650c932dSMike Stump   return BlockDescriptorType;
3822437cbfaSAnders Carlsson }
3832437cbfaSAnders Carlsson 
38495435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
385005c9a62SMike Stump   if (GenericBlockLiteralType)
386005c9a62SMike Stump     return GenericBlockLiteralType;
3872437cbfaSAnders Carlsson 
3882437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
3899793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
3902437cbfaSAnders Carlsson 
39192bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
39292bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
39392bbd6d4SMike Stump 
3942437cbfaSAnders Carlsson   // struct __block_literal_generic {
3955d2534adSMike Stump   //   void *__isa;
3965d2534adSMike Stump   //   int __flags;
3975d2534adSMike Stump   //   int __reserved;
3985d2534adSMike Stump   //   void (*__invoke)(void *);
3995d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
400950a9518SDavid Chisnall   //   // GNU runtime only:
401950a9518SDavid Chisnall   //   const char *types;
4022437cbfaSAnders Carlsson   // };
403950a9518SDavid Chisnall   if (CGM.getContext().getLangOptions().BlockIntrospection)
404950a9518SDavid Chisnall     GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
405950a9518SDavid Chisnall                                                   PtrToInt8Ty,
406950a9518SDavid Chisnall                                                   IntTy,
407950a9518SDavid Chisnall                                                   IntTy,
408950a9518SDavid Chisnall                                                   PtrToInt8Ty,
409950a9518SDavid Chisnall                                                   BlockDescPtrTy,
410950a9518SDavid Chisnall                                                   PtrToInt8Ty,
411950a9518SDavid Chisnall                                                   NULL);
412950a9518SDavid Chisnall   else
413758428f4SOwen Anderson     GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
414758428f4SOwen Anderson                                                   PtrToInt8Ty,
41592bbd6d4SMike Stump                                                   IntTy,
41692bbd6d4SMike Stump                                                   IntTy,
417626aecc4SMike Stump                                                   PtrToInt8Ty,
4182437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
4192437cbfaSAnders Carlsson                                                   NULL);
4202437cbfaSAnders Carlsson 
421005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
422005c9a62SMike Stump                           GenericBlockLiteralType);
4232437cbfaSAnders Carlsson 
424005c9a62SMike Stump   return GenericBlockLiteralType;
4252437cbfaSAnders Carlsson }
4262437cbfaSAnders Carlsson 
42795435674SMike Stump const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
4285d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
4295d2534adSMike Stump     return GenericExtendedBlockLiteralType;
4305d2534adSMike Stump 
4315d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
4329793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
4335d2534adSMike Stump 
4345d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
4355d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
4365d2534adSMike Stump 
4375d2534adSMike Stump   // struct __block_literal_generic {
4385d2534adSMike Stump   //   void *__isa;
4395d2534adSMike Stump   //   int __flags;
4405d2534adSMike Stump   //   int __reserved;
4415d2534adSMike Stump   //   void (*__invoke)(void *);
4425d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
4435d2534adSMike Stump   //   void *__copy_func_helper_decl;
4445d2534adSMike Stump   //   void *__destroy_func_decl;
4455d2534adSMike Stump   // };
446758428f4SOwen Anderson   GenericExtendedBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
447758428f4SOwen Anderson                                                           PtrToInt8Ty,
4485d2534adSMike Stump                                                           IntTy,
4495d2534adSMike Stump                                                           IntTy,
450626aecc4SMike Stump                                                           PtrToInt8Ty,
4515d2534adSMike Stump                                                           BlockDescPtrTy,
452626aecc4SMike Stump                                                           PtrToInt8Ty,
453626aecc4SMike Stump                                                           PtrToInt8Ty,
4545d2534adSMike Stump                                                           NULL);
4555d2534adSMike Stump 
4565d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
4575d2534adSMike Stump                           GenericExtendedBlockLiteralType);
4585d2534adSMike Stump 
4595d2534adSMike Stump   return GenericExtendedBlockLiteralType;
4605d2534adSMike Stump }
4615d2534adSMike Stump 
462bfb3671bSAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
463bfb3671bSAnders Carlsson                                           ReturnValueSlot ReturnValue) {
4642437cbfaSAnders Carlsson   const BlockPointerType *BPT =
465c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
4662437cbfaSAnders Carlsson 
4672437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
4682437cbfaSAnders Carlsson 
4692437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
4702437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
4719793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
4722437cbfaSAnders Carlsson 
4732437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
4742437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
4752437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4762437cbfaSAnders Carlsson 
4772437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4782437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
4792437cbfaSAnders Carlsson 
4802437cbfaSAnders Carlsson   BlockLiteral =
4812437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
482abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
4832437cbfaSAnders Carlsson                           "tmp");
4842437cbfaSAnders Carlsson 
4852437cbfaSAnders Carlsson   // Add the block literal.
4862437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4872437cbfaSAnders Carlsson   CallArgList Args;
4882437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4892437cbfaSAnders Carlsson 
490479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
491479e6fc7SAnders Carlsson 
4922437cbfaSAnders Carlsson   // And the rest of the arguments.
4939dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
494479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
4952437cbfaSAnders Carlsson 
4965f50c651SAnders Carlsson   // Load the function.
497c76493a6SDaniel Dunbar   llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
4985f50c651SAnders Carlsson 
499*ab26cfa5SJohn McCall   const FunctionType *FuncTy = FnType->getAs<FunctionType>();
500*ab26cfa5SJohn McCall   QualType ResultType = FuncTy->getResultType();
501a60cbcdfSAnders Carlsson 
502a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
503*ab26cfa5SJohn McCall     CGM.getTypes().getFunctionInfo(ResultType, Args, FuncTy->getCallConv(),
504*ab26cfa5SJohn McCall                                    FuncTy->getNoReturnAttr());
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 
51740775003SKen Dyck CharUnits CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
5180168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
51940775003SKen Dyck   CharUnits &offset = BlockDecls[VD];
5200168f4b2SAnders Carlsson 
52197d01d50SMike Stump   // See if we have already allocated an offset for this variable.
52240775003SKen 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();
53940775003SKen 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),
54540775003SKen 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.
59898ca7943SKen Dyck   CharUnits BlockLiteralSize =
59998ca7943SKen Dyck     CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
600170229f6SOwen Anderson   DescriptorFields[1] =
60140775003SKen 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);
61940775003SKen Dyck   CharUnits subBlockSize;
6205262b119SKen Dyck   CharUnits 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,
68240775003SKen Dyck                                        CharUnits &Size,
6835262b119SKen Dyck                                        CharUnits &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 
70398ca7943SKen Dyck   BlockOffset =
70498ca7943SKen Dyck       CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
7055262b119SKen Dyck   BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
70609a9b6e3SEli Friedman 
707aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
708aae4349dSFariborz Jahanian   QualType ResultType;
709*ab26cfa5SJohn McCall   CallingConv CC = BlockFunctionType->getCallConv();
710*ab26cfa5SJohn McCall   bool NoReturn = BlockFunctionType->getNoReturnAttr();
711aae4349dSFariborz Jahanian   bool IsVariadic;
712a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
713a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
714aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
715aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
716658fe02dSMike Stump   } else {
717aae4349dSFariborz Jahanian     // K&R style block.
718aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
719aae4349dSFariborz Jahanian     IsVariadic = false;
720aae4349dSFariborz Jahanian   }
7216a60fa24SAnders Carlsson 
7226a60fa24SAnders Carlsson   FunctionArgList Args;
7236a60fa24SAnders Carlsson 
7247fe9cc1dSMike Stump   CurFuncDecl = OuterFuncDecl;
7257fe9cc1dSMike Stump 
7263385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
7276a60fa24SAnders Carlsson 
7287fe9cc1dSMike Stump   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
729d015328fSMike Stump 
730945fec05SMike Stump   // Allocate all BlockDeclRefDecls, so we can calculate the right ParmTy below.
7317fe9cc1dSMike Stump   AllocateAllBlockDeclRefs(Info, this);
7327fe9cc1dSMike Stump 
733e1b19ba0SMike Stump   QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
734e1b19ba0SMike Stump                                                   BlockDeclRefDecls);
7356a60fa24SAnders Carlsson   // FIXME: This leaks
7366a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
7376a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
738d015328fSMike Stump                               SourceLocation(), II,
739d015328fSMike Stump                               ParmTy);
7406a60fa24SAnders Carlsson 
7416a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
742cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
7436a60fa24SAnders Carlsson 
744c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
7456a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
746eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
7476a60fa24SAnders Carlsson 
7486a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
749*ab26cfa5SJohn McCall     CGM.getTypes().getFunctionInfo(ResultType, Args, CC, NoReturn);
7506a60fa24SAnders Carlsson 
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,
756d6b28fc6SBenjamin Kramer                            llvm::Twine("__") + Info.Name + "_block_invoke_",
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.
783bf78478dSChris Lattner     for (unsigned i = 0, e = BlockDeclRefDecls.size(); i != e; ++i) {
784bf78478dSChris Lattner       if (const BlockDeclRefExpr *BDRE =
785bf78478dSChris Lattner             dyn_cast<BlockDeclRefExpr>(BlockDeclRefDecls[i])) {
7862e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
7872e722b91SMike Stump         DI->setLocation(D->getLocation());
7882e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
7892e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
7902e722b91SMike Stump                                               Builder, this);
7912e722b91SMike Stump       }
7922e722b91SMike Stump     }
7932e722b91SMike Stump   }
7947d69911aSMike Stump   // And resume where we left off.
7957d69911aSMike Stump   if (resume == 0)
7967d69911aSMike Stump     Builder.ClearInsertionPoint();
7977d69911aSMike Stump   else
7987d69911aSMike Stump     Builder.SetInsertPoint(resume);
7992e722b91SMike Stump 
8003385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
8016a60fa24SAnders Carlsson 
802b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
8035262b119SKen Dyck   CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
80440775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
8055262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
8065262b119SKen Dyck                                MinAlign.getQuantity()));
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 
81540775003SKen Dyck CharUnits BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
8161db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
8171db7d04bSMike Stump 
81840775003SKen Dyck   CharUnits Size = getContext().getTypeSizeInChars(D->getType());
819160146ebSKen Dyck   CharUnits Align = getContext().getDeclAlign(D);
8201db7d04bSMike Stump 
8211db7d04bSMike Stump   if (BDRE->isByRef()) {
82240775003SKen Dyck     Size = getContext().getTypeSizeInChars(getContext().VoidPtrTy);
8235262b119SKen Dyck     Align = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
8241db7d04bSMike Stump   }
8251db7d04bSMike Stump 
8265262b119SKen Dyck   assert ((Align.isPositive()) && "alignment must be 1 byte or more");
8271db7d04bSMike Stump 
82840775003SKen Dyck   CharUnits OldOffset = BlockOffset;
8291db7d04bSMike Stump 
8301db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
83140775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
8325262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
8331db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
8341db7d04bSMike Stump 
83540775003SKen Dyck   CharUnits Pad = BlockOffset - OldOffset;
83640775003SKen Dyck   if (Pad.isPositive()) {
83740775003SKen Dyck     llvm::ArrayType::get(llvm::Type::getInt8Ty(VMContext), Pad.getQuantity());
8381db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
83940775003SKen Dyck                                                        llvm::APInt(32,
84040775003SKen 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 =
874*ab26cfa5SJohn McCall     CGM.getTypes().getFunctionInfo(R, Args, CC_Default, false);
8750c743277SMike Stump 
876cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
877cbc2bcafSMike Stump   // internal linkage.
8780c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
8790c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8800c743277SMike Stump 
8810c743277SMike Stump   llvm::Function *Fn =
8820c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
883d6b28fc6SBenjamin Kramer                            "__copy_helper_block_", &CGM.getModule());
8840c743277SMike Stump 
8850c743277SMike Stump   IdentifierInfo *II
8860c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
8870c743277SMike Stump 
8880c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8890c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
89060ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
8910c743277SMike Stump                                           FunctionDecl::Static, false,
8920c743277SMike Stump                                           true);
8930c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
894aeb0ffd5SMike Stump 
895aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
896aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
89767645930SMike Stump 
89867645930SMike Stump   if (NoteForHelperp) {
89967645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
90067645930SMike Stump 
9019793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
902aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
903aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
904aeb0ffd5SMike Stump 
905aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
9063b65ac26SMike Stump     llvm::Type *PtrPtrT;
9079793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9083b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
9093b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
910aeb0ffd5SMike Stump 
911aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
912aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
913aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
914aeb0ffd5SMike Stump 
915aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
916aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
917aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
918aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
919aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9209793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
921aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
922aeb0ffd5SMike Stump 
923aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
924aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
925aeb0ffd5SMike Stump 
92641a75027SOwen Anderson         llvm::Value *N = llvm::ConstantInt::get(
92741a75027SOwen Anderson               llvm::Type::getInt32Ty(T->getContext()), flag);
928aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
929aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
930aeb0ffd5SMike Stump       }
931aeb0ffd5SMike Stump     }
93267645930SMike Stump   }
933aeb0ffd5SMike Stump 
9340c743277SMike Stump   CGF.FinishFunction();
9350c743277SMike Stump 
936ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
93797d01d50SMike Stump }
93897d01d50SMike Stump 
939d6ef62f0SMike Stump llvm::Constant *BlockFunction::
940aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
941aeb0ffd5SMike Stump                               const llvm::StructType* T,
94267645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
9430c743277SMike Stump   QualType R = getContext().VoidTy;
9440c743277SMike Stump 
9450c743277SMike Stump   FunctionArgList Args;
9460c743277SMike Stump   // FIXME: This leaks
9470c743277SMike Stump   ImplicitParamDecl *Src =
9487fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9497fe9cc1dSMike Stump                               SourceLocation(), 0,
9500c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
9510c743277SMike Stump 
9520c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
9530c743277SMike Stump 
9540c743277SMike Stump   const CGFunctionInfo &FI =
955*ab26cfa5SJohn McCall     CGM.getTypes().getFunctionInfo(R, Args, CC_Default, false);
9560c743277SMike Stump 
957cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
958cbc2bcafSMike Stump   // internal linkage.
9590c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
9600c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
9610c743277SMike Stump 
9620c743277SMike Stump   llvm::Function *Fn =
9630c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
964d6b28fc6SBenjamin Kramer                            "__destroy_helper_block_", &CGM.getModule());
9650c743277SMike Stump 
9660c743277SMike Stump   IdentifierInfo *II
9670c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
9680c743277SMike Stump 
9690c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
9700c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
97160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
9720c743277SMike Stump                                           FunctionDecl::Static, false,
9730c743277SMike Stump                                           true);
9740c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
9756f7d9f87SMike Stump 
97667645930SMike Stump   if (NoteForHelperp) {
97767645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
97867645930SMike Stump 
9796f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
9806f7d9f87SMike Stump     llvm::Type *PtrPtrT;
9819793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9826f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
9836f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
9846f7d9f87SMike Stump 
9856f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
9866f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
9876f7d9f87SMike Stump       int index = NoteForHelper[i].index;
9886f7d9f87SMike Stump 
9896f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
9906f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
9916f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
9926f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
9936f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9949793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
9956f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
9966f7d9f87SMike Stump 
9976f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
9986f7d9f87SMike Stump       }
9996f7d9f87SMike Stump     }
100067645930SMike Stump   }
10016f7d9f87SMike Stump 
10020c743277SMike Stump   CGF.FinishFunction();
10030c743277SMike Stump 
1004ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
10050c743277SMike Stump }
10060c743277SMike Stump 
1007aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
100867645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
1009aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1010aeb0ffd5SMike Stump                                                          T, NoteForHelper);
10110c743277SMike Stump }
10120c743277SMike Stump 
1013aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
101467645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
1015aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
101667645930SMike Stump                                                             T, NoteForHelperp);
101797d01d50SMike Stump }
1018626aecc4SMike Stump 
1019f89230d9SMike Stump llvm::Constant *BlockFunction::
1020f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
1021ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1022ee2a5ee5SMike Stump 
1023ee2a5ee5SMike Stump   FunctionArgList Args;
1024ee2a5ee5SMike Stump   // FIXME: This leaks
1025f89230d9SMike Stump   ImplicitParamDecl *Dst =
10267fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10277fe9cc1dSMike Stump                               SourceLocation(), 0,
1028f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1029f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
1030f89230d9SMike Stump 
1031f89230d9SMike Stump   // FIXME: This leaks
1032ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10337fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10347fe9cc1dSMike Stump                               SourceLocation(), 0,
1035ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1036ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1037ee2a5ee5SMike Stump 
1038ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1039*ab26cfa5SJohn McCall     CGM.getTypes().getFunctionInfo(R, Args, CC_Default, false);
1040ee2a5ee5SMike Stump 
1041ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1042ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1043ee2a5ee5SMike Stump 
1044cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1045cbc2bcafSMike Stump   // internal linkage.
1046ee2a5ee5SMike Stump   llvm::Function *Fn =
1047ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1048d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_copy_", &CGM.getModule());
1049ee2a5ee5SMike Stump 
1050ee2a5ee5SMike Stump   IdentifierInfo *II
1051ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1052ee2a5ee5SMike Stump 
1053ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1054ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
105560ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1056ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1057ee2a5ee5SMike Stump                                           true);
1058ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1059f89230d9SMike Stump 
1060f89230d9SMike Stump   // dst->x
1061f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
10629793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10633b65ac26SMike Stump   V = Builder.CreateLoad(V);
1064f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
1065f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1066f89230d9SMike Stump 
1067f89230d9SMike Stump   // src->x
1068f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
1069f89230d9SMike Stump   V = Builder.CreateLoad(V);
1070f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
1071f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10729793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1073f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
1074f89230d9SMike Stump 
1075f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
1076f89230d9SMike Stump 
107741a75027SOwen Anderson   llvm::Value *N = llvm::ConstantInt::get(
107841a75027SOwen Anderson           llvm::Type::getInt32Ty(T->getContext()), flag);
1079f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
1080f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1081f89230d9SMike Stump 
1082ee2a5ee5SMike Stump   CGF.FinishFunction();
1083ee2a5ee5SMike Stump 
1084ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1085ee2a5ee5SMike Stump }
1086ee2a5ee5SMike Stump 
1087fbe25dd1SMike Stump llvm::Constant *
1088fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1089fbe25dd1SMike Stump                                                   int flag) {
1090ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1091ee2a5ee5SMike Stump 
1092ee2a5ee5SMike Stump   FunctionArgList Args;
1093ee2a5ee5SMike Stump   // FIXME: This leaks
1094ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10957fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10967fe9cc1dSMike Stump                               SourceLocation(), 0,
1097ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1098ee2a5ee5SMike Stump 
1099ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1100ee2a5ee5SMike Stump 
1101ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1102*ab26cfa5SJohn McCall     CGM.getTypes().getFunctionInfo(R, Args, CC_Default, false);
1103ee2a5ee5SMike Stump 
1104ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1105ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1106ee2a5ee5SMike Stump 
1107cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1108cbc2bcafSMike Stump   // internal linkage.
1109ee2a5ee5SMike Stump   llvm::Function *Fn =
1110ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1111d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_dispose_",
1112ee2a5ee5SMike Stump                            &CGM.getModule());
1113ee2a5ee5SMike Stump 
1114ee2a5ee5SMike Stump   IdentifierInfo *II
1115ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1116ee2a5ee5SMike Stump 
1117ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1118ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
111960ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1120ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1121ee2a5ee5SMike Stump                                           true);
1122ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1123fbe25dd1SMike Stump 
1124fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
11259793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
11263b65ac26SMike Stump   V = Builder.CreateLoad(V);
1127fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
11289793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
11293b65ac26SMike Stump   V = Builder.CreateLoad(V);
1130fbe25dd1SMike Stump 
1131fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1132fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1133ee2a5ee5SMike Stump   CGF.FinishFunction();
1134ee2a5ee5SMike Stump 
1135ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1136ee2a5ee5SMike Stump }
1137ee2a5ee5SMike Stump 
1138f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1139e08ea787SChris Lattner                                                     int Flag, unsigned Align) {
1140e08ea787SChris Lattner   // All alignments below that of pointer alignment collapse down to just
1141cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1142cbc2bcafSMike Stump   // with.
1143cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1144e08ea787SChris Lattner 
1145cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1146cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1147cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1148e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1149e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.AssignCache[Kind];
1150cbc2bcafSMike Stump   if (Entry)
1151cbc2bcafSMike Stump     return Entry;
1152e08ea787SChris Lattner   return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
1153ee2a5ee5SMike Stump }
1154ee2a5ee5SMike Stump 
1155fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1156e08ea787SChris Lattner                                                        int Flag,
1157cbc2bcafSMike Stump                                                        unsigned Align) {
1158cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1159cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1160cbc2bcafSMike Stump   // with.
1161cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1162e08ea787SChris Lattner 
1163cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1164cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1165cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1166e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1167e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.DestroyCache[Kind];
1168cbc2bcafSMike Stump   if (Entry)
1169cbc2bcafSMike Stump     return Entry;
1170e08ea787SChris Lattner   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
1171ee2a5ee5SMike Stump }
1172ee2a5ee5SMike Stump 
1173626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1174626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1175626aecc4SMike Stump     const llvm::FunctionType *FTy;
1176626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
117741a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1178626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
117941a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11809793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1181626aecc4SMike Stump     CGM.BlockObjectDispose
1182626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1183626aecc4SMike Stump   }
1184626aecc4SMike Stump   return CGM.BlockObjectDispose;
1185626aecc4SMike Stump }
1186626aecc4SMike Stump 
1187f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1188f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1189f89230d9SMike Stump     const llvm::FunctionType *FTy;
1190f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
119141a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1192f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1193f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
119441a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11959793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1196f89230d9SMike Stump     CGM.BlockObjectAssign
1197f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1198f89230d9SMike Stump   }
1199f89230d9SMike Stump   return CGM.BlockObjectAssign;
1200f89230d9SMike Stump }
1201f89230d9SMike Stump 
1202fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1203626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1204fbe25dd1SMike Stump   llvm::Value *N;
1205626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
120641a75027SOwen Anderson   N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1207626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1208626aecc4SMike Stump }
12094446dcf0SMike Stump 
12104446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1211aeb0ffd5SMike Stump 
1212aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1213aeb0ffd5SMike Stump                              CGBuilderTy &B)
1214170229f6SOwen Anderson   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
121541a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
121641a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1217aeb0ffd5SMike Stump 
1218aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1219aeb0ffd5SMike Stump }
1220