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"
16989908fbSFariborz Jahanian #include "CGObjCRuntime.h"
172437cbfaSAnders Carlsson #include "CodeGenModule.h"
18692c6e37SMike Stump #include "clang/AST/DeclObjC.h"
192437cbfaSAnders Carlsson #include "llvm/Module.h"
206a60fa24SAnders Carlsson #include "llvm/Target/TargetData.h"
212437cbfaSAnders Carlsson #include <algorithm>
22db714924STorok Edwin 
232437cbfaSAnders Carlsson using namespace clang;
242437cbfaSAnders Carlsson using namespace CodeGen;
252437cbfaSAnders Carlsson 
26d6ef62f0SMike Stump llvm::Constant *CodeGenFunction::
27fc83aa04SBlaine Garst BuildDescriptorBlockDecl(const BlockExpr *BE, bool BlockHasCopyDispose, CharUnits Size,
28d2142cffSMike Stump                          const llvm::StructType* Ty,
29aeb0ffd5SMike Stump                          std::vector<HelperInfo> *NoteForHelper) {
30c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
31c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
3285284bacSMike Stump   llvm::Constant *C;
3385284bacSMike Stump   std::vector<llvm::Constant*> Elts;
3485284bacSMike Stump 
3585284bacSMike Stump   // reserved
36b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
3785284bacSMike Stump   Elts.push_back(C);
3885284bacSMike Stump 
3985284bacSMike Stump   // Size
402ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
412ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
422ac40a9fSMike Stump   // API to size_t.
4340775003SKen Dyck   C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
4485284bacSMike Stump   Elts.push_back(C);
4585284bacSMike Stump 
46fc83aa04SBlaine Garst   // optional copy/dispose helpers
4785284bacSMike Stump   if (BlockHasCopyDispose) {
4885284bacSMike Stump     // copy_func_helper_decl
4967645930SMike Stump     Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
5085284bacSMike Stump 
5185284bacSMike Stump     // destroy_func_decl
5267645930SMike Stump     Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
5385284bacSMike Stump   }
5485284bacSMike Stump 
55fc83aa04SBlaine Garst   // Signature.  non-optional ObjC-style method descriptor @encode sequence
56fc83aa04SBlaine Garst   std::string BlockTypeEncoding;
57fc83aa04SBlaine Garst   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
58fc83aa04SBlaine Garst 
59fc83aa04SBlaine Garst   Elts.push_back(llvm::ConstantExpr::getBitCast(
60fc83aa04SBlaine Garst           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty));
61fc83aa04SBlaine Garst 
62fc83aa04SBlaine Garst   // Layout.
63fc83aa04SBlaine Garst   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
64fc83aa04SBlaine Garst   Elts.push_back(C);
65fc83aa04SBlaine Garst 
6641eaf0acSNick Lewycky   C = llvm::ConstantStruct::get(VMContext, Elts, false);
6785284bacSMike Stump 
68c10c8d3eSOwen Anderson   C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
6985284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
70c10c8d3eSOwen Anderson                                C, "__block_descriptor_tmp");
7185284bacSMike Stump   return C;
7285284bacSMike Stump }
7385284bacSMike Stump 
7495435674SMike Stump llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
7546813bbfSChris Lattner   if (NSConcreteGlobalBlock == 0)
7646813bbfSChris Lattner     NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
7746813bbfSChris Lattner                                                       "_NSConcreteGlobalBlock");
78971f9b66SMike Stump   return NSConcreteGlobalBlock;
79971f9b66SMike Stump }
80971f9b66SMike Stump 
8195435674SMike Stump llvm::Constant *BlockModule::getNSConcreteStackBlock() {
8246813bbfSChris Lattner   if (NSConcreteStackBlock == 0)
8346813bbfSChris Lattner     NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
8446813bbfSChris Lattner                                                      "_NSConcreteStackBlock");
857ab278dbSMike Stump   return NSConcreteStackBlock;
867ab278dbSMike Stump }
877ab278dbSMike Stump 
88066b6166SMike Stump static void CollectBlockDeclRefInfo(
89066b6166SMike Stump   const Stmt *S, CodeGenFunction::BlockInfo &Info,
90066b6166SMike Stump   llvm::SmallSet<const DeclContext *, 16> &InnerContexts) {
91ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
92ed5e69feSAnders Carlsson        I != E; ++I)
93dd942713SDaniel Dunbar     if (*I)
94066b6166SMike Stump       CollectBlockDeclRefInfo(*I, Info, InnerContexts);
95ed5e69feSAnders Carlsson 
967fe9cc1dSMike Stump   // We want to ensure we walk down into block literals so we can find
977fe9cc1dSMike Stump   // all nested BlockDeclRefExprs.
98066b6166SMike Stump   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
99066b6166SMike Stump     InnerContexts.insert(cast<DeclContext>(BE->getBlockDecl()));
100066b6166SMike Stump     CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
101066b6166SMike Stump   }
1027fe9cc1dSMike Stump 
103066b6166SMike Stump   if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
104ed5e69feSAnders Carlsson     // FIXME: Handle enums.
105066b6166SMike Stump     if (isa<FunctionDecl>(BDRE->getDecl()))
106ed5e69feSAnders Carlsson       return;
107ed5e69feSAnders Carlsson 
108066b6166SMike Stump     // Only Decls that escape are added.
109066b6166SMike Stump     if (!InnerContexts.count(BDRE->getDecl()->getDeclContext()))
110066b6166SMike Stump       Info.DeclRefs.push_back(BDRE);
111ed5e69feSAnders Carlsson   }
112ed5e69feSAnders Carlsson }
113ed5e69feSAnders Carlsson 
1142d33d630SMike Stump /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
1152d33d630SMike Stump /// declared as a global variable instead of on the stack.
11646813bbfSChris Lattner static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info) {
1177fe9cc1dSMike Stump   return Info.DeclRefs.empty();
1187fe9cc1dSMike Stump }
1197fe9cc1dSMike Stump 
1207fe9cc1dSMike Stump /// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
1217fe9cc1dSMike Stump /// ensure we can generate the debug information for the parameter for the block
1227fe9cc1dSMike Stump /// invoke function.
1237fe9cc1dSMike Stump static void AllocateAllBlockDeclRefs(const CodeGenFunction::BlockInfo &Info,
1247fe9cc1dSMike Stump                                      CodeGenFunction *CGF) {
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   std::vector<llvm::Constant*> Elts(BlockFields);
151950a9518SDavid Chisnall 
15285284bacSMike Stump   llvm::Constant *C;
153b750d928SMike Stump   llvm::Value *V;
15485284bacSMike Stump 
15585284bacSMike Stump   {
15685284bacSMike Stump     // C = BuildBlockStructInitlist();
157f27ab71dSBlaine Garst     unsigned int flags = BLOCK_HAS_SIGNATURE;
158950a9518SDavid Chisnall 
1594446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
1604446dcf0SMike Stump     // block literal.
1614446dcf0SMike Stump     // __invoke
16240775003SKen Dyck     CharUnits subBlockSize;
1635262b119SKen Dyck     CharUnits subBlockAlign;
1644446dcf0SMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
165d2142cffSMike Stump     bool subBlockHasCopyDispose = false;
1664446dcf0SMike Stump     llvm::Function *Fn
167d2a3e617SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
168d2a3e617SMike Stump                                                    LocalDeclMap,
1695469f29aSMike Stump                                                    subBlockSize,
1704446dcf0SMike Stump                                                    subBlockAlign,
1714446dcf0SMike Stump                                                    subBlockDeclRefDecls,
172d2142cffSMike Stump                                                    subBlockHasCopyDispose);
173d2142cffSMike Stump     BlockHasCopyDispose |= subBlockHasCopyDispose;
1744446dcf0SMike Stump     Elts[3] = Fn;
1754446dcf0SMike Stump 
17618bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
17718bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
178d2142cffSMike Stump     if (subBlockHasCopyDispose)
17985284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
18085284bacSMike Stump 
181499ae7ecSMike Stump     // __isa
1827ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
183ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1844446dcf0SMike Stump     Elts[0] = C;
18585284bacSMike Stump 
18685284bacSMike Stump     // __flags
187f27ab71dSBlaine Garst     {
188f27ab71dSBlaine Garst       QualType BPT = BE->getType();
189f27ab71dSBlaine Garst       const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
190f27ab71dSBlaine Garst       QualType ResultType = ftype->getResultType();
191f27ab71dSBlaine Garst 
192f27ab71dSBlaine Garst       CallArgList Args;
193f27ab71dSBlaine Garst       CodeGenTypes &Types = CGM.getTypes();
194f27ab71dSBlaine Garst       const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
195*c50c27ccSRafael Espindola                                                        FunctionType::ExtInfo());
196f27ab71dSBlaine Garst       if (CGM.ReturnTypeUsesSret(FnInfo))
197f27ab71dSBlaine Garst         flags |= BLOCK_USE_STRET;
198f27ab71dSBlaine Garst     }
19985284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
20085284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
201b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
2024446dcf0SMike Stump     Elts[1] = C;
20385284bacSMike Stump 
20485284bacSMike Stump     // __reserved
205b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
2064446dcf0SMike Stump     Elts[2] = C;
20785284bacSMike Stump 
208b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
209d6ef62f0SMike Stump       // __descriptor
210fc83aa04SBlaine Garst       Elts[4] = BuildDescriptorBlockDecl(BE, subBlockHasCopyDispose, subBlockSize,
2117fe9cc1dSMike Stump                                          0, 0);
212d6ef62f0SMike Stump 
2133a139f37SMike Stump       // Optimize to being a global block.
2143a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
215f27ab71dSBlaine Garst 
216b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2173a139f37SMike Stump 
21841eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
21985284bacSMike Stump 
220c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
221d6b28fc6SBenjamin Kramer                                    llvm::GlobalValue::InternalLinkage, C,
222d6b28fc6SBenjamin Kramer                                    "__block_holder_tmp_" +
223d6b28fc6SBenjamin Kramer                                    llvm::Twine(CGM.getGlobalUniqueCount()));
2245d2534adSMike Stump       QualType BPT = BE->getType();
225ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
22685284bacSMike Stump       return C;
22785284bacSMike Stump     }
22885284bacSMike Stump 
229950a9518SDavid Chisnall     std::vector<const llvm::Type *> Types(BlockFields+subBlockDeclRefDecls.size());
230aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
231b750d928SMike Stump       Types[i] = Elts[i]->getType();
232aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
23385284bacSMike Stump 
2341db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
2351db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
2361db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2371db7d04bSMike Stump       QualType Ty = E->getType();
23897d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
239950a9518SDavid Chisnall         Types[i+BlockFields] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
24097d01d50SMike Stump       } else
241950a9518SDavid Chisnall         Types[i+BlockFields] = ConvertType(Ty);
2421db7d04bSMike Stump     }
243b750d928SMike Stump 
244758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
245b750d928SMike Stump 
246b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
2475262b119SKen Dyck     A->setAlignment(subBlockAlign.getQuantity());
248b750d928SMike Stump     V = A;
249b750d928SMike Stump 
250aeb0ffd5SMike Stump     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
251aeb0ffd5SMike Stump     int helpersize = 0;
252aeb0ffd5SMike Stump 
253aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
254b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
255b750d928SMike Stump 
256b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
257b750d928SMike Stump       {
2581db7d04bSMike Stump         // FIXME: Push const down.
2591db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2601db7d04bSMike Stump         DeclRefExpr *DR;
2611db7d04bSMike Stump         ValueDecl *VD;
262b750d928SMike Stump 
2631db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2641db7d04bSMike Stump         // Skip padding.
2651db7d04bSMike Stump         if (DR) continue;
2661db7d04bSMike Stump 
2671db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2681db7d04bSMike Stump         VD = BDRE->getDecl();
2691db7d04bSMike Stump 
270950a9518SDavid Chisnall         llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
271aeb0ffd5SMike Stump         NoteForHelper[helpersize].index = i+5;
2722114d7c2SMike Stump         NoteForHelper[helpersize].RequiresCopying
2732114d7c2SMike Stump           = BlockRequiresCopying(VD->getType());
274aeb0ffd5SMike Stump         NoteForHelper[helpersize].flag
2752114d7c2SMike Stump           = (VD->getType()->isBlockPointerType()
2762114d7c2SMike Stump              ? BLOCK_FIELD_IS_BLOCK
2772114d7c2SMike Stump              : BLOCK_FIELD_IS_OBJECT);
278aeb0ffd5SMike Stump 
2791db7d04bSMike Stump         if (LocalDeclMap[VD]) {
28097d01d50SMike Stump           if (BDRE->isByRef()) {
281aeb0ffd5SMike Stump             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
28290d8daf5SMike Stump               // FIXME: Someone double check this.
28390d8daf5SMike Stump               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
28497d01d50SMike Stump             llvm::Value *Loc = LocalDeclMap[VD];
28597d01d50SMike Stump             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
286c76493a6SDaniel Dunbar             Loc = Builder.CreateLoad(Loc);
28797d01d50SMike Stump             Builder.CreateStore(Loc, Addr);
288aeb0ffd5SMike Stump             ++helpersize;
28997d01d50SMike Stump             continue;
29097d01d50SMike Stump           } else
291ce54657eSJohn McCall             E = new (getContext()) DeclRefExpr (VD,
292ed6c7440SDouglas Gregor                                                 VD->getType(),
293ed6c7440SDouglas Gregor                                                 SourceLocation());
2941db7d04bSMike Stump         }
29597d01d50SMike Stump         if (BDRE->isByRef()) {
296efd7caa8SMike Stump           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
297efd7caa8SMike Stump             // FIXME: Someone double check this.
298efd7caa8SMike Stump             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
2991db7d04bSMike Stump           E = new (getContext())
3001db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
3011db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
3021db7d04bSMike Stump                           SourceLocation());
30397d01d50SMike Stump         }
304aeb0ffd5SMike Stump         ++helpersize;
3051db7d04bSMike Stump 
3061db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
30797d01d50SMike Stump         if (r.isScalar()) {
30897d01d50SMike Stump           llvm::Value *Loc = r.getScalarVal();
309950a9518SDavid Chisnall           const llvm::Type *Ty = Types[i+BlockFields];
31097d01d50SMike Stump           if  (BDRE->isByRef()) {
3112d33d630SMike Stump             // E is now the address of the value field, instead, we want the
3122d33d630SMike Stump             // address of the actual ByRef struct.  We optimize this slightly
3132d33d630SMike Stump             // compared to gcc by not grabbing the forwarding slot as this must
3142d33d630SMike Stump             // be done during Block_copy for us, and we can postpone the work
3152d33d630SMike Stump             // until then.
31640775003SKen Dyck             CharUnits offset = BlockDecls[BDRE->getDecl()];
3172d33d630SMike Stump 
3182d33d630SMike Stump             llvm::Value *BlockLiteral = LoadBlockStruct();
3192d33d630SMike Stump 
3202d33d630SMike Stump             Loc = Builder.CreateGEP(BlockLiteral,
32141a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
32240775003SKen Dyck                                                            offset.getQuantity()),
3232d33d630SMike Stump                                     "block.literal");
3249793f0e4SOwen Anderson             Ty = llvm::PointerType::get(Ty, 0);
32597d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
326c76493a6SDaniel Dunbar             Loc = Builder.CreateLoad(Loc);
3272d33d630SMike Stump             // Loc = Builder.CreateBitCast(Loc, Ty);
32897d01d50SMike Stump           }
32997d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
33097d01d50SMike Stump         } else if (r.isComplex())
331b750d928SMike Stump           // FIXME: implement
332b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
333b750d928SMike Stump         else if (r.isAggregate())
334b750d928SMike Stump           ; // Already created into the destination
335b750d928SMike Stump         else
336b750d928SMike Stump           assert (0 && "bad block variable");
337b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
338b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
339b750d928SMike Stump       }
340aeb0ffd5SMike Stump     NoteForHelper.resize(helpersize);
341d6ef62f0SMike Stump 
342d6ef62f0SMike Stump     // __descriptor
343fc83aa04SBlaine Garst     llvm::Value *Descriptor = BuildDescriptorBlockDecl(BE,
344fc83aa04SBlaine Garst                                                        subBlockHasCopyDispose,
345d2142cffSMike Stump                                                        subBlockSize, Ty,
346aeb0ffd5SMike Stump                                                        &NoteForHelper);
347aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
348aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
349b750d928SMike Stump   }
350b750d928SMike Stump 
351b750d928SMike Stump   QualType BPT = BE->getType();
352989908fbSFariborz Jahanian   V = Builder.CreateBitCast(V, ConvertType(BPT));
353989908fbSFariborz Jahanian   // See if this is a __weak block variable and the must call objc_read_weak
354989908fbSFariborz Jahanian   // on it.
355989908fbSFariborz Jahanian   const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
356989908fbSFariborz Jahanian   QualType RES = ftype->getResultType();
357989908fbSFariborz Jahanian   if (RES.isObjCGCWeak()) {
358989908fbSFariborz Jahanian     // Must cast argument to id*
359989908fbSFariborz Jahanian     const llvm::Type *ObjectPtrTy =
360989908fbSFariborz Jahanian       ConvertType(CGM.getContext().getObjCIdType());
361989908fbSFariborz Jahanian     const llvm::Type *PtrObjectPtrTy =
362989908fbSFariborz Jahanian       llvm::PointerType::getUnqual(ObjectPtrTy);
363989908fbSFariborz Jahanian     V = Builder.CreateBitCast(V, PtrObjectPtrTy);
364989908fbSFariborz Jahanian     V =  CGM.getObjCRuntime().EmitObjCWeakRead(*this, V);
365989908fbSFariborz Jahanian   }
366989908fbSFariborz Jahanian   return V;
367b750d928SMike Stump }
36885284bacSMike Stump 
36985284bacSMike Stump 
37095435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
371650c932dSMike Stump   if (BlockDescriptorType)
372650c932dSMike Stump     return BlockDescriptorType;
3732437cbfaSAnders Carlsson 
3742437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
375650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3762437cbfaSAnders Carlsson 
3772437cbfaSAnders Carlsson   // struct __block_descriptor {
3782437cbfaSAnders Carlsson   //   unsigned long reserved;
3792437cbfaSAnders Carlsson   //   unsigned long block_size;
380fc83aa04SBlaine Garst   //
381fc83aa04SBlaine Garst   //   // later, the following will be added
382fc83aa04SBlaine Garst   //
383fc83aa04SBlaine Garst   //   struct {
384fc83aa04SBlaine Garst   //     void (*copyHelper)();
385fc83aa04SBlaine Garst   //     void (*copyHelper)();
386fc83aa04SBlaine Garst   //   } helpers;                // !!! optional
387fc83aa04SBlaine Garst   //
388fc83aa04SBlaine Garst   //   const char *signature;   // the block signature
389fc83aa04SBlaine Garst   //   const char *layout;      // reserved
3902437cbfaSAnders Carlsson   // };
391758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
392758428f4SOwen Anderson                                               UnsignedLongTy,
3932437cbfaSAnders Carlsson                                               UnsignedLongTy,
3942437cbfaSAnders Carlsson                                               NULL);
3952437cbfaSAnders Carlsson 
396650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
397650c932dSMike Stump                           BlockDescriptorType);
3982437cbfaSAnders Carlsson 
399650c932dSMike Stump   return BlockDescriptorType;
4002437cbfaSAnders Carlsson }
4012437cbfaSAnders Carlsson 
40295435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
403005c9a62SMike Stump   if (GenericBlockLiteralType)
404005c9a62SMike Stump     return GenericBlockLiteralType;
4052437cbfaSAnders Carlsson 
4062437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
4079793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
4082437cbfaSAnders Carlsson 
40992bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
41092bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
41192bbd6d4SMike Stump 
4122437cbfaSAnders Carlsson   // struct __block_literal_generic {
4135d2534adSMike Stump   //   void *__isa;
4145d2534adSMike Stump   //   int __flags;
4155d2534adSMike Stump   //   int __reserved;
4165d2534adSMike Stump   //   void (*__invoke)(void *);
4175d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
4182437cbfaSAnders Carlsson   // };
419758428f4SOwen Anderson   GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
420758428f4SOwen Anderson                                                   PtrToInt8Ty,
42192bbd6d4SMike Stump                                                   IntTy,
42292bbd6d4SMike Stump                                                   IntTy,
423626aecc4SMike Stump                                                   PtrToInt8Ty,
4242437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
4252437cbfaSAnders Carlsson                                                   NULL);
4262437cbfaSAnders Carlsson 
427005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
428005c9a62SMike Stump                           GenericBlockLiteralType);
4292437cbfaSAnders Carlsson 
430005c9a62SMike Stump   return GenericBlockLiteralType;
4312437cbfaSAnders Carlsson }
4322437cbfaSAnders Carlsson 
4335d2534adSMike Stump 
434bfb3671bSAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
435bfb3671bSAnders Carlsson                                           ReturnValueSlot ReturnValue) {
4362437cbfaSAnders Carlsson   const BlockPointerType *BPT =
437c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
4382437cbfaSAnders Carlsson 
4392437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
4402437cbfaSAnders Carlsson 
4412437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
4422437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
4439793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
4442437cbfaSAnders Carlsson 
4452437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
4462437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
4472437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4482437cbfaSAnders Carlsson 
4492437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4502437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
4512437cbfaSAnders Carlsson 
4522437cbfaSAnders Carlsson   BlockLiteral =
4532437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
454abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
4552437cbfaSAnders Carlsson                           "tmp");
4562437cbfaSAnders Carlsson 
4572437cbfaSAnders Carlsson   // Add the block literal.
4582437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4592437cbfaSAnders Carlsson   CallArgList Args;
4602437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4612437cbfaSAnders Carlsson 
462479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
463479e6fc7SAnders Carlsson 
4642437cbfaSAnders Carlsson   // And the rest of the arguments.
4659dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
466479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
4672437cbfaSAnders Carlsson 
4685f50c651SAnders Carlsson   // Load the function.
469c76493a6SDaniel Dunbar   llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
4705f50c651SAnders Carlsson 
471ab26cfa5SJohn McCall   const FunctionType *FuncTy = FnType->getAs<FunctionType>();
472ab26cfa5SJohn McCall   QualType ResultType = FuncTy->getResultType();
473a60cbcdfSAnders Carlsson 
474a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
475*c50c27ccSRafael Espindola     CGM.getTypes().getFunctionInfo(ResultType, Args,
476*c50c27ccSRafael Espindola                                    FuncTy->getExtInfo());
4775f50c651SAnders Carlsson 
4785f50c651SAnders Carlsson   // Cast the function pointer to the right type.
4795f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
480a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
4815f50c651SAnders Carlsson 
4829793f0e4SOwen Anderson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
4835f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
4845f50c651SAnders Carlsson 
4852437cbfaSAnders Carlsson   // And call the block.
486bfb3671bSAnders Carlsson   return EmitCall(FnInfo, Func, ReturnValue, Args);
4872437cbfaSAnders Carlsson }
4886a60fa24SAnders Carlsson 
48940775003SKen Dyck CharUnits CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
4900168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
49140775003SKen Dyck   CharUnits &offset = BlockDecls[VD];
4920168f4b2SAnders Carlsson 
49397d01d50SMike Stump   // See if we have already allocated an offset for this variable.
49440775003SKen Dyck   if (offset.isPositive())
4957fe9cc1dSMike Stump     return offset;
4967fe9cc1dSMike Stump 
4974446dcf0SMike Stump   // Don't run the expensive check, unless we have to.
498e1b19ba0SMike Stump   if (!BlockHasCopyDispose)
499e1b19ba0SMike Stump     if (E->isByRef()
500e1b19ba0SMike Stump         || BlockRequiresCopying(E->getType()))
5014446dcf0SMike Stump       BlockHasCopyDispose = true;
5027fe9cc1dSMike Stump 
50397d01d50SMike Stump   // if not, allocate one now.
50497d01d50SMike Stump   offset = getBlockOffset(E);
5057fe9cc1dSMike Stump 
5067fe9cc1dSMike Stump   return offset;
50797d01d50SMike Stump }
50897d01d50SMike Stump 
5097fe9cc1dSMike Stump llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
5107fe9cc1dSMike Stump   const ValueDecl *VD = E->getDecl();
51140775003SKen Dyck   CharUnits offset = AllocateBlockDecl(E);
5127fe9cc1dSMike Stump 
5137fe9cc1dSMike Stump 
51497d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
51597d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
51641a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
51740775003SKen Dyck                                                          offset.getQuantity()),
5182d33d630SMike Stump                                      "block.literal");
51997d01d50SMike Stump   if (E->isByRef()) {
52097d01d50SMike Stump     const llvm::Type *PtrStructTy
5210168f4b2SAnders Carlsson       = llvm::PointerType::get(BuildByRefType(VD), 0);
522efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
523efd7caa8SMike Stump     BlockHasCopyDispose = true;
5240168f4b2SAnders Carlsson 
5250168f4b2SAnders Carlsson     const llvm::Type *Ty = PtrStructTy;
5269793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
52797d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
528c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
52997d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
530c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
53197d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
5320168f4b2SAnders Carlsson     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
5330168f4b2SAnders Carlsson                                 VD->getNameAsString());
53497d01d50SMike Stump   } else {
5350168f4b2SAnders Carlsson     const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
5360168f4b2SAnders Carlsson 
5379793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
53897d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
53997d01d50SMike Stump   }
54097d01d50SMike Stump   return V;
54197d01d50SMike Stump }
54297d01d50SMike Stump 
543692c6e37SMike Stump void CodeGenFunction::BlockForwardSelf() {
544692c6e37SMike Stump   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
545692c6e37SMike Stump   ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
546692c6e37SMike Stump   llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
547692c6e37SMike Stump   if (DMEntry)
548692c6e37SMike Stump     return;
549692c6e37SMike Stump   // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
550692c6e37SMike Stump   BlockDeclRefExpr *BDRE = new (getContext())
551692c6e37SMike Stump     BlockDeclRefExpr(SelfDecl,
552692c6e37SMike Stump                      SelfDecl->getType(), SourceLocation(), false);
553692c6e37SMike Stump   DMEntry = GetAddrOfBlockDecl(BDRE);
554692c6e37SMike Stump }
555692c6e37SMike Stump 
5562d5a2878SMike Stump llvm::Constant *
5576c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
5586a60fa24SAnders Carlsson   // Generate the block descriptor.
5596a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
56092bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
56192bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
5626a60fa24SAnders Carlsson 
563fc83aa04SBlaine Garst   llvm::Constant *DescriptorFields[4];
5646a60fa24SAnders Carlsson 
5656a60fa24SAnders Carlsson   // Reserved
5660b75f23bSOwen Anderson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
5676a60fa24SAnders Carlsson 
5686a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
5696a60fa24SAnders Carlsson   // block literal struct.
57098ca7943SKen Dyck   CharUnits BlockLiteralSize =
57198ca7943SKen Dyck     CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
572170229f6SOwen Anderson   DescriptorFields[1] =
57340775003SKen Dyck     llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
5746a60fa24SAnders Carlsson 
575fc83aa04SBlaine Garst   // signature.  non-optional ObjC-style method descriptor @encode sequence
576fc83aa04SBlaine Garst   std::string BlockTypeEncoding;
577fc83aa04SBlaine Garst   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
578fc83aa04SBlaine Garst 
579fc83aa04SBlaine Garst   DescriptorFields[2] = llvm::ConstantExpr::getBitCast(
580fc83aa04SBlaine Garst           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
581fc83aa04SBlaine Garst 
582fc83aa04SBlaine Garst   // layout
583fc83aa04SBlaine Garst   DescriptorFields[3] =
584fc83aa04SBlaine Garst     llvm::ConstantInt::get(UnsignedLongTy,0);
585fc83aa04SBlaine Garst 
586fc83aa04SBlaine Garst   // build the structure from the 4 elements
5876a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
588fc83aa04SBlaine Garst     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false);
5896a60fa24SAnders Carlsson 
5906a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
591c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
5926a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
593c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
5946a60fa24SAnders Carlsson 
595950a9518SDavid Chisnall   int FieldCount = 5;
5966a60fa24SAnders Carlsson   // Generate the constants for the block literal.
597950a9518SDavid Chisnall 
598950a9518SDavid Chisnall   std::vector<llvm::Constant*> LiteralFields(FieldCount);
5996a60fa24SAnders Carlsson 
6002d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
60140775003SKen Dyck   CharUnits subBlockSize;
6025262b119SKen Dyck   CharUnits subBlockAlign;
6031db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
604a61bb4d1SDaniel Dunbar   bool subBlockHasCopyDispose = false;
6055469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
606cb2fbcb0SMike Stump   llvm::Function *Fn
607692c6e37SMike Stump     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
6085469f29aSMike Stump                                                  subBlockSize,
609b750d928SMike Stump                                                  subBlockAlign,
6104446dcf0SMike Stump                                                  subBlockDeclRefDecls,
6114446dcf0SMike Stump                                                  subBlockHasCopyDispose);
612cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
613cb2fbcb0SMike Stump          && "no imports allowed for global block");
6146a60fa24SAnders Carlsson 
6156a60fa24SAnders Carlsson   // isa
616971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
6176a60fa24SAnders Carlsson 
6186a60fa24SAnders Carlsson   // Flags
619fc83aa04SBlaine Garst   LiteralFields[1] =
620f27ab71dSBlaine Garst     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
6216a60fa24SAnders Carlsson 
6226a60fa24SAnders Carlsson   // Reserved
6230b75f23bSOwen Anderson   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
6246a60fa24SAnders Carlsson 
6256a60fa24SAnders Carlsson   // Function
6266a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
6276a60fa24SAnders Carlsson 
6286a60fa24SAnders Carlsson   // Descriptor
6296a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
6306a60fa24SAnders Carlsson 
6316a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
632950a9518SDavid Chisnall     llvm::ConstantStruct::get(VMContext, LiteralFields, false);
6336a60fa24SAnders Carlsson 
6346a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
635c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
6366a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
637c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
6386a60fa24SAnders Carlsson 
6396a60fa24SAnders Carlsson   return BlockLiteral;
6406a60fa24SAnders Carlsson }
6416a60fa24SAnders Carlsson 
642cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
64338382028SMike Stump   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
64438382028SMike Stump                                       "self");
64538382028SMike Stump   // For now, we codegen based upon byte offsets.
64638382028SMike Stump   return Builder.CreateBitCast(V, PtrToInt8Ty);
647cb2fbcb0SMike Stump }
648cb2fbcb0SMike Stump 
6494446dcf0SMike Stump llvm::Function *
6504446dcf0SMike Stump CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
651cb2fbcb0SMike Stump                                        const BlockInfo& Info,
652692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
6535469f29aSMike Stump                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm,
65440775003SKen Dyck                                        CharUnits &Size,
6555262b119SKen Dyck                                        CharUnits &Align,
6564446dcf0SMike Stump                        llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
6574446dcf0SMike Stump                                        bool &subBlockHasCopyDispose) {
6589074ed8cSDevang Patel 
6599074ed8cSDevang Patel   // Check if we should generate debug info for this block.
6609074ed8cSDevang Patel   if (CGM.getDebugInfo())
6619074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
6629074ed8cSDevang Patel 
6635469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
6645469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
6655469f29aSMike Stump   // in a block.
6665469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
6675469f29aSMike Stump        i != ldm.end();
6685469f29aSMike Stump        ++i) {
6695469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
6705469f29aSMike Stump 
6710ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
6725469f29aSMike Stump       LocalDeclMap[VD] = i->second;
6735469f29aSMike Stump   }
6745469f29aSMike Stump 
67598ca7943SKen Dyck   BlockOffset =
67698ca7943SKen Dyck       CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
6775262b119SKen Dyck   BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
67809a9b6e3SEli Friedman 
679aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
680aae4349dSFariborz Jahanian   QualType ResultType;
681*c50c27ccSRafael Espindola   FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType);
682aae4349dSFariborz Jahanian   bool IsVariadic;
683a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
684a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
685aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
686aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
687658fe02dSMike Stump   } else {
688aae4349dSFariborz Jahanian     // K&R style block.
689aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
690aae4349dSFariborz Jahanian     IsVariadic = false;
691aae4349dSFariborz Jahanian   }
6926a60fa24SAnders Carlsson 
6936a60fa24SAnders Carlsson   FunctionArgList Args;
6946a60fa24SAnders Carlsson 
6957fe9cc1dSMike Stump   CurFuncDecl = OuterFuncDecl;
6967fe9cc1dSMike Stump 
6973385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
6986a60fa24SAnders Carlsson 
6997fe9cc1dSMike Stump   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
700d015328fSMike Stump 
701945fec05SMike Stump   // Allocate all BlockDeclRefDecls, so we can calculate the right ParmTy below.
7027fe9cc1dSMike Stump   AllocateAllBlockDeclRefs(Info, this);
7037fe9cc1dSMike Stump 
704e1b19ba0SMike Stump   QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
705e1b19ba0SMike Stump                                                   BlockDeclRefDecls);
7066a60fa24SAnders Carlsson   // FIXME: This leaks
7076a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
7086a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
709d015328fSMike Stump                               SourceLocation(), II,
710d015328fSMike Stump                               ParmTy);
7116a60fa24SAnders Carlsson 
7126a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
713cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
7146a60fa24SAnders Carlsson 
715c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
7166a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
717eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
7186a60fa24SAnders Carlsson 
7196a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
720*c50c27ccSRafael Espindola     CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo);
7216a60fa24SAnders Carlsson 
7226a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
723aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
7246a60fa24SAnders Carlsson 
7256a60fa24SAnders Carlsson   llvm::Function *Fn =
7266a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
727d6b28fc6SBenjamin Kramer                            llvm::Twine("__") + Info.Name + "_block_invoke_",
7286a60fa24SAnders Carlsson                            &CGM.getModule());
7296a60fa24SAnders Carlsson 
730c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
731c3e7cff6SDaniel Dunbar 
732324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
7333385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
7342e722b91SMike Stump 
735324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
73628ec0cf8SChris Lattner   CurCodeDecl = BD;
737017460abSMike Stump 
738017460abSMike Stump   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
739017460abSMike Stump   llvm::BasicBlock *entry = Builder.GetInsertBlock();
740017460abSMike Stump   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
741017460abSMike Stump   --entry_ptr;
742017460abSMike Stump 
7433385fe12SChris Lattner   EmitStmt(BExpr->getBody());
744017460abSMike Stump 
7457d69911aSMike Stump   // Remember where we were...
7467d69911aSMike Stump   llvm::BasicBlock *resume = Builder.GetInsertBlock();
747017460abSMike Stump 
7487d69911aSMike Stump   // Go back to the entry.
749017460abSMike Stump   ++entry_ptr;
750017460abSMike Stump   Builder.SetInsertPoint(entry, entry_ptr);
751017460abSMike Stump 
7522e722b91SMike Stump   if (CGDebugInfo *DI = getDebugInfo()) {
7532e722b91SMike Stump     // Emit debug information for all the BlockDeclRefDecls.
754bf78478dSChris Lattner     for (unsigned i = 0, e = BlockDeclRefDecls.size(); i != e; ++i) {
755bf78478dSChris Lattner       if (const BlockDeclRefExpr *BDRE =
756bf78478dSChris Lattner             dyn_cast<BlockDeclRefExpr>(BlockDeclRefDecls[i])) {
7572e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
7582e722b91SMike Stump         DI->setLocation(D->getLocation());
7592e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
7602e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
7612e722b91SMike Stump                                               Builder, this);
7622e722b91SMike Stump       }
7632e722b91SMike Stump     }
7642e722b91SMike Stump   }
7657d69911aSMike Stump   // And resume where we left off.
7667d69911aSMike Stump   if (resume == 0)
7677d69911aSMike Stump     Builder.ClearInsertionPoint();
7687d69911aSMike Stump   else
7697d69911aSMike Stump     Builder.SetInsertPoint(resume);
7702e722b91SMike Stump 
7713385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
7726a60fa24SAnders Carlsson 
773b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
7745262b119SKen Dyck   CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
77540775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
7765262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
7775262b119SKen Dyck                                MinAlign.getQuantity()));
778b750d928SMike Stump 
779cb2fbcb0SMike Stump   Size = BlockOffset;
780b750d928SMike Stump   Align = BlockAlign;
781b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
7824446dcf0SMike Stump   subBlockHasCopyDispose |= BlockHasCopyDispose;
7836a60fa24SAnders Carlsson   return Fn;
7846a60fa24SAnders Carlsson }
7851db7d04bSMike Stump 
78640775003SKen Dyck CharUnits BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
7871db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
7881db7d04bSMike Stump 
78940775003SKen Dyck   CharUnits Size = getContext().getTypeSizeInChars(D->getType());
790160146ebSKen Dyck   CharUnits Align = getContext().getDeclAlign(D);
7911db7d04bSMike Stump 
7921db7d04bSMike Stump   if (BDRE->isByRef()) {
79340775003SKen Dyck     Size = getContext().getTypeSizeInChars(getContext().VoidPtrTy);
7945262b119SKen Dyck     Align = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
7951db7d04bSMike Stump   }
7961db7d04bSMike Stump 
7975262b119SKen Dyck   assert ((Align.isPositive()) && "alignment must be 1 byte or more");
7981db7d04bSMike Stump 
79940775003SKen Dyck   CharUnits OldOffset = BlockOffset;
8001db7d04bSMike Stump 
8011db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
80240775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
8035262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
8041db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
8051db7d04bSMike Stump 
80640775003SKen Dyck   CharUnits Pad = BlockOffset - OldOffset;
80740775003SKen Dyck   if (Pad.isPositive()) {
80840775003SKen Dyck     llvm::ArrayType::get(llvm::Type::getInt8Ty(VMContext), Pad.getQuantity());
8091db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
81040775003SKen Dyck                                                        llvm::APInt(32,
81140775003SKen Dyck                                                          Pad.getQuantity()),
8121db7d04bSMike Stump                                                        ArrayType::Normal, 0);
8131db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
8146032ef1aSArgyrios Kyrtzidis                                          0, QualType(PadTy), 0, VarDecl::None);
8151db7d04bSMike Stump     Expr *E;
8161db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
817ed6c7440SDouglas Gregor                                        SourceLocation());
8181db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
8191db7d04bSMike Stump   }
8201db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
8211db7d04bSMike Stump 
8221db7d04bSMike Stump   BlockOffset += Size;
8231db7d04bSMike Stump   return BlockOffset-Size;
8241db7d04bSMike Stump }
82597d01d50SMike Stump 
826aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
827aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
82867645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
8290c743277SMike Stump   QualType R = getContext().VoidTy;
8300c743277SMike Stump 
8310c743277SMike Stump   FunctionArgList Args;
8320c743277SMike Stump   // FIXME: This leaks
833aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
8347fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8357fe9cc1dSMike Stump                               SourceLocation(), 0,
836aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
837aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
8380c743277SMike Stump   ImplicitParamDecl *Src =
8397fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8407fe9cc1dSMike Stump                               SourceLocation(), 0,
8410c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
8420c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
8430c743277SMike Stump 
8440c743277SMike Stump   const CGFunctionInfo &FI =
845*c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
8460c743277SMike Stump 
847cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
848cbc2bcafSMike Stump   // internal linkage.
8490c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
8500c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8510c743277SMike Stump 
8520c743277SMike Stump   llvm::Function *Fn =
8530c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
854d6b28fc6SBenjamin Kramer                            "__copy_helper_block_", &CGM.getModule());
8550c743277SMike Stump 
8560c743277SMike Stump   IdentifierInfo *II
8570c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
8580c743277SMike Stump 
8590c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8600c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
86160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
8620c743277SMike Stump                                           FunctionDecl::Static, false,
8630c743277SMike Stump                                           true);
8640c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
865aeb0ffd5SMike Stump 
866aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
867aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
86867645930SMike Stump 
86967645930SMike Stump   if (NoteForHelperp) {
87067645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
87167645930SMike Stump 
8729793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
873aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
874aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
875aeb0ffd5SMike Stump 
876aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
8773b65ac26SMike Stump     llvm::Type *PtrPtrT;
8789793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
8793b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
8803b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
881aeb0ffd5SMike Stump 
882aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
883aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
884aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
885aeb0ffd5SMike Stump 
886aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
887aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
888aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
889aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
890aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
8919793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
892aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
893aeb0ffd5SMike Stump 
894aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
895aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
896aeb0ffd5SMike Stump 
89741a75027SOwen Anderson         llvm::Value *N = llvm::ConstantInt::get(
89841a75027SOwen Anderson               llvm::Type::getInt32Ty(T->getContext()), flag);
899aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
900aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
901aeb0ffd5SMike Stump       }
902aeb0ffd5SMike Stump     }
90367645930SMike Stump   }
904aeb0ffd5SMike Stump 
9050c743277SMike Stump   CGF.FinishFunction();
9060c743277SMike Stump 
907ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
90897d01d50SMike Stump }
90997d01d50SMike Stump 
910d6ef62f0SMike Stump llvm::Constant *BlockFunction::
911aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
912aeb0ffd5SMike Stump                               const llvm::StructType* T,
91367645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
9140c743277SMike Stump   QualType R = getContext().VoidTy;
9150c743277SMike Stump 
9160c743277SMike Stump   FunctionArgList Args;
9170c743277SMike Stump   // FIXME: This leaks
9180c743277SMike Stump   ImplicitParamDecl *Src =
9197fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9207fe9cc1dSMike Stump                               SourceLocation(), 0,
9210c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
9220c743277SMike Stump 
9230c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
9240c743277SMike Stump 
9250c743277SMike Stump   const CGFunctionInfo &FI =
926*c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
9270c743277SMike Stump 
928cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
929cbc2bcafSMike Stump   // internal linkage.
9300c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
9310c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
9320c743277SMike Stump 
9330c743277SMike Stump   llvm::Function *Fn =
9340c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
935d6b28fc6SBenjamin Kramer                            "__destroy_helper_block_", &CGM.getModule());
9360c743277SMike Stump 
9370c743277SMike Stump   IdentifierInfo *II
9380c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
9390c743277SMike Stump 
9400c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
9410c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
94260ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
9430c743277SMike Stump                                           FunctionDecl::Static, false,
9440c743277SMike Stump                                           true);
9450c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
9466f7d9f87SMike Stump 
94767645930SMike Stump   if (NoteForHelperp) {
94867645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
94967645930SMike Stump 
9506f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
9516f7d9f87SMike Stump     llvm::Type *PtrPtrT;
9529793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9536f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
9546f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
9556f7d9f87SMike Stump 
9566f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
9576f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
9586f7d9f87SMike Stump       int index = NoteForHelper[i].index;
9596f7d9f87SMike Stump 
9606f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
9616f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
9626f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
9636f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
9646f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9659793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
9666f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
9676f7d9f87SMike Stump 
9686f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
9696f7d9f87SMike Stump       }
9706f7d9f87SMike Stump     }
97167645930SMike Stump   }
9726f7d9f87SMike Stump 
9730c743277SMike Stump   CGF.FinishFunction();
9740c743277SMike Stump 
975ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
9760c743277SMike Stump }
9770c743277SMike Stump 
978aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
97967645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
980aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
981aeb0ffd5SMike Stump                                                          T, NoteForHelper);
9820c743277SMike Stump }
9830c743277SMike Stump 
984aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
98567645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
986aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
98767645930SMike Stump                                                             T, NoteForHelperp);
98897d01d50SMike Stump }
989626aecc4SMike Stump 
990f89230d9SMike Stump llvm::Constant *BlockFunction::
991f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
992ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
993ee2a5ee5SMike Stump 
994ee2a5ee5SMike Stump   FunctionArgList Args;
995ee2a5ee5SMike Stump   // FIXME: This leaks
996f89230d9SMike Stump   ImplicitParamDecl *Dst =
9977fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9987fe9cc1dSMike Stump                               SourceLocation(), 0,
999f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1000f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
1001f89230d9SMike Stump 
1002f89230d9SMike Stump   // FIXME: This leaks
1003ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10047fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10057fe9cc1dSMike Stump                               SourceLocation(), 0,
1006ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1007ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1008ee2a5ee5SMike Stump 
1009ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1010*c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1011ee2a5ee5SMike Stump 
1012ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1013ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1014ee2a5ee5SMike Stump 
1015cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1016cbc2bcafSMike Stump   // internal linkage.
1017ee2a5ee5SMike Stump   llvm::Function *Fn =
1018ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1019d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_copy_", &CGM.getModule());
1020ee2a5ee5SMike Stump 
1021ee2a5ee5SMike Stump   IdentifierInfo *II
1022ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1023ee2a5ee5SMike Stump 
1024ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1025ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
102660ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1027ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1028ee2a5ee5SMike Stump                                           true);
1029ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1030f89230d9SMike Stump 
1031f89230d9SMike Stump   // dst->x
1032f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
10339793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10343b65ac26SMike Stump   V = Builder.CreateLoad(V);
1035f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
1036f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1037f89230d9SMike Stump 
1038f89230d9SMike Stump   // src->x
1039f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
1040f89230d9SMike Stump   V = Builder.CreateLoad(V);
1041f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
1042f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10439793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1044f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
1045f89230d9SMike Stump 
1046f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
1047f89230d9SMike Stump 
104841a75027SOwen Anderson   llvm::Value *N = llvm::ConstantInt::get(
104941a75027SOwen Anderson           llvm::Type::getInt32Ty(T->getContext()), flag);
1050f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
1051f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1052f89230d9SMike Stump 
1053ee2a5ee5SMike Stump   CGF.FinishFunction();
1054ee2a5ee5SMike Stump 
1055ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1056ee2a5ee5SMike Stump }
1057ee2a5ee5SMike Stump 
1058fbe25dd1SMike Stump llvm::Constant *
1059fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1060fbe25dd1SMike Stump                                                   int flag) {
1061ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1062ee2a5ee5SMike Stump 
1063ee2a5ee5SMike Stump   FunctionArgList Args;
1064ee2a5ee5SMike Stump   // FIXME: This leaks
1065ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10667fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10677fe9cc1dSMike Stump                               SourceLocation(), 0,
1068ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1069ee2a5ee5SMike Stump 
1070ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1071ee2a5ee5SMike Stump 
1072ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1073*c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1074ee2a5ee5SMike Stump 
1075ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1076ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1077ee2a5ee5SMike Stump 
1078cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1079cbc2bcafSMike Stump   // internal linkage.
1080ee2a5ee5SMike Stump   llvm::Function *Fn =
1081ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1082d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_dispose_",
1083ee2a5ee5SMike Stump                            &CGM.getModule());
1084ee2a5ee5SMike Stump 
1085ee2a5ee5SMike Stump   IdentifierInfo *II
1086ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1087ee2a5ee5SMike Stump 
1088ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1089ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
109060ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1091ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1092ee2a5ee5SMike Stump                                           true);
1093ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1094fbe25dd1SMike Stump 
1095fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
10969793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10973b65ac26SMike Stump   V = Builder.CreateLoad(V);
1098fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10999793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
11003b65ac26SMike Stump   V = Builder.CreateLoad(V);
1101fbe25dd1SMike Stump 
1102fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1103fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1104ee2a5ee5SMike Stump   CGF.FinishFunction();
1105ee2a5ee5SMike Stump 
1106ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1107ee2a5ee5SMike Stump }
1108ee2a5ee5SMike Stump 
1109f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1110e08ea787SChris Lattner                                                     int Flag, unsigned Align) {
1111e08ea787SChris Lattner   // All alignments below that of pointer alignment collapse down to just
1112cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1113cbc2bcafSMike Stump   // with.
1114cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1115e08ea787SChris Lattner 
1116cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1117cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1118cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1119e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1120e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.AssignCache[Kind];
1121cbc2bcafSMike Stump   if (Entry)
1122cbc2bcafSMike Stump     return Entry;
1123e08ea787SChris Lattner   return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
1124ee2a5ee5SMike Stump }
1125ee2a5ee5SMike Stump 
1126fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1127e08ea787SChris Lattner                                                        int Flag,
1128cbc2bcafSMike Stump                                                        unsigned Align) {
1129cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1130cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1131cbc2bcafSMike Stump   // with.
1132cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1133e08ea787SChris Lattner 
1134cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1135cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1136cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1137e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1138e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.DestroyCache[Kind];
1139cbc2bcafSMike Stump   if (Entry)
1140cbc2bcafSMike Stump     return Entry;
1141e08ea787SChris Lattner   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
1142ee2a5ee5SMike Stump }
1143ee2a5ee5SMike Stump 
1144626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1145626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1146626aecc4SMike Stump     const llvm::FunctionType *FTy;
1147626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
114841a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1149626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
115041a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11519793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1152626aecc4SMike Stump     CGM.BlockObjectDispose
1153626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1154626aecc4SMike Stump   }
1155626aecc4SMike Stump   return CGM.BlockObjectDispose;
1156626aecc4SMike Stump }
1157626aecc4SMike Stump 
1158f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1159f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1160f89230d9SMike Stump     const llvm::FunctionType *FTy;
1161f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
116241a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1163f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1164f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
116541a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11669793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1167f89230d9SMike Stump     CGM.BlockObjectAssign
1168f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1169f89230d9SMike Stump   }
1170f89230d9SMike Stump   return CGM.BlockObjectAssign;
1171f89230d9SMike Stump }
1172f89230d9SMike Stump 
1173fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1174626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1175fbe25dd1SMike Stump   llvm::Value *N;
1176626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
117741a75027SOwen Anderson   N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1178626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1179626aecc4SMike Stump }
11804446dcf0SMike Stump 
11814446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1182aeb0ffd5SMike Stump 
1183aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1184aeb0ffd5SMike Stump                              CGBuilderTy &B)
1185170229f6SOwen Anderson   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
118641a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
118741a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1188aeb0ffd5SMike Stump 
1189aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1190aeb0ffd5SMike Stump }
1191