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"
209e2e1c90SBenjamin Kramer #include "llvm/ADT/SmallSet.h"
216a60fa24SAnders Carlsson #include "llvm/Target/TargetData.h"
222437cbfaSAnders Carlsson #include <algorithm>
23db714924STorok Edwin 
242437cbfaSAnders Carlsson using namespace clang;
252437cbfaSAnders Carlsson using namespace CodeGen;
262437cbfaSAnders Carlsson 
279d42f0f1SJohn McCall /// CGBlockInfo - Information to generate a block literal.
289d42f0f1SJohn McCall class clang::CodeGen::CGBlockInfo {
299d42f0f1SJohn McCall public:
309d42f0f1SJohn McCall   /// Name - The name of the block, kindof.
319d42f0f1SJohn McCall   const char *Name;
329d42f0f1SJohn McCall 
339d42f0f1SJohn McCall   /// DeclRefs - Variables from parent scopes that have been
349d42f0f1SJohn McCall   /// imported into this block.
359d42f0f1SJohn McCall   llvm::SmallVector<const BlockDeclRefExpr *, 8> DeclRefs;
369d42f0f1SJohn McCall 
379d42f0f1SJohn McCall   /// InnerBlocks - This block and the blocks it encloses.
389d42f0f1SJohn McCall   llvm::SmallPtrSet<const DeclContext *, 4> InnerBlocks;
399d42f0f1SJohn McCall 
409d42f0f1SJohn McCall   /// CXXThisRef - Non-null if 'this' was required somewhere, in
419d42f0f1SJohn McCall   /// which case this is that expression.
429d42f0f1SJohn McCall   const CXXThisExpr *CXXThisRef;
439d42f0f1SJohn McCall 
449d42f0f1SJohn McCall   /// NeedsObjCSelf - True if something in this block has an implicit
459d42f0f1SJohn McCall   /// reference to 'self'.
469d42f0f1SJohn McCall   bool NeedsObjCSelf;
479d42f0f1SJohn McCall 
489d42f0f1SJohn McCall   /// These are initialized by GenerateBlockFunction.
499d42f0f1SJohn McCall   bool BlockHasCopyDispose;
509d42f0f1SJohn McCall   CharUnits BlockSize;
519d42f0f1SJohn McCall   CharUnits BlockAlign;
529d42f0f1SJohn McCall   llvm::SmallVector<const Expr*, 8> BlockLayout;
539d42f0f1SJohn McCall 
549d42f0f1SJohn McCall   CGBlockInfo(const char *Name);
559d42f0f1SJohn McCall };
569d42f0f1SJohn McCall 
579d42f0f1SJohn McCall CGBlockInfo::CGBlockInfo(const char *N)
589d42f0f1SJohn McCall   : Name(N), CXXThisRef(0), NeedsObjCSelf(false) {
599d42f0f1SJohn McCall 
609d42f0f1SJohn McCall   // Skip asm prefix, if any.
619d42f0f1SJohn McCall   if (Name && Name[0] == '\01')
629d42f0f1SJohn McCall     ++Name;
639d42f0f1SJohn McCall }
649d42f0f1SJohn McCall 
659d42f0f1SJohn McCall 
66d6ef62f0SMike Stump llvm::Constant *CodeGenFunction::
67fc83aa04SBlaine Garst BuildDescriptorBlockDecl(const BlockExpr *BE, bool BlockHasCopyDispose, CharUnits Size,
68d2142cffSMike Stump                          const llvm::StructType* Ty,
69aeb0ffd5SMike Stump                          std::vector<HelperInfo> *NoteForHelper) {
70c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
71c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
7285284bacSMike Stump   llvm::Constant *C;
7385284bacSMike Stump   std::vector<llvm::Constant*> Elts;
7485284bacSMike Stump 
7585284bacSMike Stump   // reserved
76b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
7785284bacSMike Stump   Elts.push_back(C);
7885284bacSMike Stump 
7985284bacSMike Stump   // Size
802ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
812ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
822ac40a9fSMike Stump   // API to size_t.
8340775003SKen Dyck   C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
8485284bacSMike Stump   Elts.push_back(C);
8585284bacSMike Stump 
86fc83aa04SBlaine Garst   // optional copy/dispose helpers
8785284bacSMike Stump   if (BlockHasCopyDispose) {
8885284bacSMike Stump     // copy_func_helper_decl
8967645930SMike Stump     Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
9085284bacSMike Stump 
9185284bacSMike Stump     // destroy_func_decl
9267645930SMike Stump     Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
9385284bacSMike Stump   }
9485284bacSMike Stump 
95fc83aa04SBlaine Garst   // Signature.  non-optional ObjC-style method descriptor @encode sequence
96fc83aa04SBlaine Garst   std::string BlockTypeEncoding;
97fc83aa04SBlaine Garst   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
98fc83aa04SBlaine Garst 
99fc83aa04SBlaine Garst   Elts.push_back(llvm::ConstantExpr::getBitCast(
100fc83aa04SBlaine Garst           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty));
101fc83aa04SBlaine Garst 
102fc83aa04SBlaine Garst   // Layout.
103fc83aa04SBlaine Garst   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
104fc83aa04SBlaine Garst   Elts.push_back(C);
105fc83aa04SBlaine Garst 
10641eaf0acSNick Lewycky   C = llvm::ConstantStruct::get(VMContext, Elts, false);
10785284bacSMike Stump 
108c10c8d3eSOwen Anderson   C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
10985284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
110c10c8d3eSOwen Anderson                                C, "__block_descriptor_tmp");
11185284bacSMike Stump   return C;
11285284bacSMike Stump }
11385284bacSMike Stump 
1149d42f0f1SJohn McCall static void CollectBlockDeclRefInfo(const Stmt *S, CGBlockInfo &Info) {
115ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
116ed5e69feSAnders Carlsson        I != E; ++I)
117dd942713SDaniel Dunbar     if (*I)
1189d42f0f1SJohn McCall       CollectBlockDeclRefInfo(*I, Info);
119ed5e69feSAnders Carlsson 
1207fe9cc1dSMike Stump   // We want to ensure we walk down into block literals so we can find
1217fe9cc1dSMike Stump   // all nested BlockDeclRefExprs.
122066b6166SMike Stump   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
1239d42f0f1SJohn McCall     Info.InnerBlocks.insert(BE->getBlockDecl());
1249d42f0f1SJohn McCall     CollectBlockDeclRefInfo(BE->getBody(), Info);
125066b6166SMike Stump   }
1267fe9cc1dSMike Stump 
1279d42f0f1SJohn McCall   else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1289d42f0f1SJohn McCall     const ValueDecl *D = BDRE->getDecl();
129ed5e69feSAnders Carlsson     // FIXME: Handle enums.
1309d42f0f1SJohn McCall     if (isa<FunctionDecl>(D))
131ed5e69feSAnders Carlsson       return;
132ed5e69feSAnders Carlsson 
1339d42f0f1SJohn McCall     if (isa<ImplicitParamDecl>(D) &&
1349d42f0f1SJohn McCall         isa<ObjCMethodDecl>(D->getDeclContext()) &&
1359d42f0f1SJohn McCall         cast<ObjCMethodDecl>(D->getDeclContext())->getSelfDecl() == D) {
1369d42f0f1SJohn McCall       Info.NeedsObjCSelf = true;
1379d42f0f1SJohn McCall       return;
1389d42f0f1SJohn McCall     }
1399d42f0f1SJohn McCall 
140066b6166SMike Stump     // Only Decls that escape are added.
1419d42f0f1SJohn McCall     if (!Info.InnerBlocks.count(D->getDeclContext()))
142066b6166SMike Stump       Info.DeclRefs.push_back(BDRE);
143ed5e69feSAnders Carlsson   }
14487fe5d56SJohn McCall 
1459d42f0f1SJohn McCall   // Make sure to capture implicit 'self' references due to super calls.
1467ea01c3fSChandler Carruth   else if (const ObjCMessageExpr *E = dyn_cast<ObjCMessageExpr>(S)) {
1479d42f0f1SJohn McCall     if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
1489d42f0f1SJohn McCall         E->getReceiverKind() == ObjCMessageExpr::SuperInstance)
1499d42f0f1SJohn McCall       Info.NeedsObjCSelf = true;
1507ea01c3fSChandler Carruth   }
1519d42f0f1SJohn McCall 
1529d42f0f1SJohn McCall   // Getter/setter uses may also cause implicit super references,
1539d42f0f1SJohn McCall   // which we can check for with:
1549d42f0f1SJohn McCall   else if (isa<ObjCSuperExpr>(S))
1559d42f0f1SJohn McCall     Info.NeedsObjCSelf = true;
1569d42f0f1SJohn McCall 
1579d42f0f1SJohn McCall   else if (isa<CXXThisExpr>(S))
15887fe5d56SJohn McCall     Info.CXXThisRef = cast<CXXThisExpr>(S);
159ed5e69feSAnders Carlsson }
160ed5e69feSAnders Carlsson 
1619d42f0f1SJohn McCall /// CanBlockBeGlobal - Given a CGBlockInfo struct, determines if a block can be
1622d33d630SMike Stump /// declared as a global variable instead of on the stack.
1639d42f0f1SJohn McCall static bool CanBlockBeGlobal(const CGBlockInfo &Info) {
1647fe9cc1dSMike Stump   return Info.DeclRefs.empty();
1657fe9cc1dSMike Stump }
1667fe9cc1dSMike Stump 
1677fe9cc1dSMike Stump /// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
1687fe9cc1dSMike Stump /// ensure we can generate the debug information for the parameter for the block
1697fe9cc1dSMike Stump /// invoke function.
1709d42f0f1SJohn McCall static void AllocateAllBlockDeclRefs(CodeGenFunction &CGF, CGBlockInfo &Info) {
17187fe5d56SJohn McCall   if (Info.CXXThisRef)
1729d42f0f1SJohn McCall     CGF.AllocateBlockCXXThisPointer(Info.CXXThisRef);
1737fe9cc1dSMike Stump 
1747fe9cc1dSMike Stump   for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
1759d42f0f1SJohn McCall     CGF.AllocateBlockDecl(Info.DeclRefs[i]);
1769d42f0f1SJohn McCall 
1779d42f0f1SJohn McCall   if (Info.NeedsObjCSelf) {
1789d42f0f1SJohn McCall     ValueDecl *Self = cast<ObjCMethodDecl>(CGF.CurFuncDecl)->getSelfDecl();
1799d42f0f1SJohn McCall     BlockDeclRefExpr *BDRE =
1809d42f0f1SJohn McCall       new (CGF.getContext()) BlockDeclRefExpr(Self, Self->getType(),
1819d42f0f1SJohn McCall                                               SourceLocation(), false);
1829d42f0f1SJohn McCall     Info.DeclRefs.push_back(BDRE);
1839d42f0f1SJohn McCall     CGF.AllocateBlockDecl(BDRE);
1849d42f0f1SJohn McCall   }
185ed5e69feSAnders Carlsson }
186ed5e69feSAnders Carlsson 
187*d5010898SFariborz Jahanian static unsigned computeBlockFlag(CodeGenModule &CGM,
188*d5010898SFariborz Jahanian                                  const BlockExpr *BE, unsigned flags) {
189*d5010898SFariborz Jahanian   QualType BPT = BE->getType();
190*d5010898SFariborz Jahanian   const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
191*d5010898SFariborz Jahanian   QualType ResultType = ftype->getResultType();
192*d5010898SFariborz Jahanian 
193*d5010898SFariborz Jahanian   CallArgList Args;
194*d5010898SFariborz Jahanian   CodeGenTypes &Types = CGM.getTypes();
195*d5010898SFariborz Jahanian   const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
196*d5010898SFariborz Jahanian                                                        FunctionType::ExtInfo());
197*d5010898SFariborz Jahanian   if (CGM.ReturnTypeUsesSRet(FnInfo))
198*d5010898SFariborz Jahanian     flags |= CodeGenFunction::BLOCK_USE_STRET;
199*d5010898SFariborz Jahanian   return flags;
200*d5010898SFariborz Jahanian }
201*d5010898SFariborz Jahanian 
2022d33d630SMike Stump // FIXME: Push most into CGM, passing down a few bits, like current function
2032d33d630SMike Stump // name.
204b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
205ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
2069d42f0f1SJohn McCall   CGBlockInfo Info(Name.c_str());
2079d42f0f1SJohn McCall   Info.InnerBlocks.insert(BE->getBlockDecl());
2089d42f0f1SJohn McCall   CollectBlockDeclRefInfo(BE->getBody(), Info);
209ed5e69feSAnders Carlsson 
210ed5e69feSAnders Carlsson   // Check if the block can be global.
2112d33d630SMike Stump   // FIXME: This test doesn't work for nested blocks yet.  Longer term, I'd like
2122d33d630SMike Stump   // to just have one code path.  We should move this function into CGM and pass
2132d33d630SMike Stump   // CGF, then we can just check to see if CGF is 0.
21497d01d50SMike Stump   if (0 && CanBlockBeGlobal(Info))
215ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
21685284bacSMike Stump 
217950a9518SDavid Chisnall   size_t BlockFields = 5;
218950a9518SDavid Chisnall 
219950a9518SDavid Chisnall   std::vector<llvm::Constant*> Elts(BlockFields);
220950a9518SDavid Chisnall 
22185284bacSMike Stump   llvm::Constant *C;
222b750d928SMike Stump   llvm::Value *V;
22385284bacSMike Stump 
22485284bacSMike Stump   {
22585284bacSMike Stump     // C = BuildBlockStructInitlist();
226f27ab71dSBlaine Garst     unsigned int flags = BLOCK_HAS_SIGNATURE;
227950a9518SDavid Chisnall 
2284446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
2294446dcf0SMike Stump     // block literal.
2304446dcf0SMike Stump     // __invoke
2314446dcf0SMike Stump     llvm::Function *Fn
2329b5528d2SFariborz Jahanian       = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, BE, Info, CurFuncDecl,
2339d42f0f1SJohn McCall                                                    LocalDeclMap);
2349d42f0f1SJohn McCall     BlockHasCopyDispose |= Info.BlockHasCopyDispose;
2354446dcf0SMike Stump     Elts[3] = Fn;
2364446dcf0SMike Stump 
23718bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
23818bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
2399d42f0f1SJohn McCall     if (Info.BlockHasCopyDispose)
24085284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
24185284bacSMike Stump 
242499ae7ecSMike Stump     // __isa
2437ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
244ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
2454446dcf0SMike Stump     Elts[0] = C;
24685284bacSMike Stump 
24785284bacSMike Stump     // __flags
248*d5010898SFariborz Jahanian     flags = computeBlockFlag(CGM, BE, flags);
24985284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
25085284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
251b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
2524446dcf0SMike Stump     Elts[1] = C;
25385284bacSMike Stump 
25485284bacSMike Stump     // __reserved
255b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
2564446dcf0SMike Stump     Elts[2] = C;
25785284bacSMike Stump 
2589d42f0f1SJohn McCall     if (Info.BlockLayout.empty()) {
259d6ef62f0SMike Stump       // __descriptor
2609d42f0f1SJohn McCall       Elts[4] = BuildDescriptorBlockDecl(BE, Info.BlockHasCopyDispose,
2619d42f0f1SJohn McCall                                          Info.BlockSize, 0, 0);
262d6ef62f0SMike Stump 
2633a139f37SMike Stump       // Optimize to being a global block.
2643a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
265f27ab71dSBlaine Garst 
266b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2673a139f37SMike Stump 
26841eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
26985284bacSMike Stump 
270c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
271d6b28fc6SBenjamin Kramer                                    llvm::GlobalValue::InternalLinkage, C,
272d6b28fc6SBenjamin Kramer                                    "__block_holder_tmp_" +
273d6b28fc6SBenjamin Kramer                                    llvm::Twine(CGM.getGlobalUniqueCount()));
2745d2534adSMike Stump       QualType BPT = BE->getType();
275ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
27685284bacSMike Stump       return C;
27785284bacSMike Stump     }
27885284bacSMike Stump 
2799d42f0f1SJohn McCall     std::vector<const llvm::Type *> Types(BlockFields+Info.BlockLayout.size());
280aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
281b750d928SMike Stump       Types[i] = Elts[i]->getType();
282aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
28385284bacSMike Stump 
2849d42f0f1SJohn McCall     for (unsigned i = 0, n = Info.BlockLayout.size(); i != n; ++i) {
2859d42f0f1SJohn McCall       const Expr *E = Info.BlockLayout[i];
2861db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2871db7d04bSMike Stump       QualType Ty = E->getType();
28897d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
289d1b378e0SFariborz Jahanian         Types[i+BlockFields] =
290d1b378e0SFariborz Jahanian           llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
291d1b378e0SFariborz Jahanian       } else if (BDRE && BDRE->getDecl()->getType()->isReferenceType()) {
292d1b378e0SFariborz Jahanian          Types[i+BlockFields] = llvm::PointerType::get(ConvertType(Ty), 0);
29397d01d50SMike Stump       } else
294950a9518SDavid Chisnall         Types[i+BlockFields] = ConvertType(Ty);
2951db7d04bSMike Stump     }
296b750d928SMike Stump 
297758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
298b750d928SMike Stump 
299b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
3009d42f0f1SJohn McCall     A->setAlignment(Info.BlockAlign.getQuantity());
301b750d928SMike Stump     V = A;
302b750d928SMike Stump 
30387fe5d56SJohn McCall     // Build layout / cleanup information for all the data entries in the
30487fe5d56SJohn McCall     // layout, and write the enclosing fields into the type.
3059d42f0f1SJohn McCall     std::vector<HelperInfo> NoteForHelper(Info.BlockLayout.size());
30687fe5d56SJohn McCall     unsigned NumHelpers = 0;
307aeb0ffd5SMike Stump 
308aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
309b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
310b750d928SMike Stump 
3119d42f0f1SJohn McCall     for (unsigned i=0; i < Info.BlockLayout.size(); ++i) {
3129d42f0f1SJohn McCall       const Expr *E = Info.BlockLayout[i];
313b750d928SMike Stump 
3141db7d04bSMike Stump       // Skip padding.
31587fe5d56SJohn McCall       if (isa<DeclRefExpr>(E)) continue;
3161db7d04bSMike Stump 
317950a9518SDavid Chisnall       llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
31887fe5d56SJohn McCall       HelperInfo &Note = NoteForHelper[NumHelpers++];
31987fe5d56SJohn McCall 
32087fe5d56SJohn McCall       Note.index = i+5;
32187fe5d56SJohn McCall 
32287fe5d56SJohn McCall       if (isa<CXXThisExpr>(E)) {
32387fe5d56SJohn McCall         Note.RequiresCopying = false;
32487fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_OBJECT;
32587fe5d56SJohn McCall 
32687fe5d56SJohn McCall         Builder.CreateStore(LoadCXXThis(), Addr);
32787fe5d56SJohn McCall         continue;
32887fe5d56SJohn McCall       }
32987fe5d56SJohn McCall 
33087fe5d56SJohn McCall       const BlockDeclRefExpr *BDRE = cast<BlockDeclRefExpr>(E);
33187fe5d56SJohn McCall       const ValueDecl *VD = BDRE->getDecl();
33287fe5d56SJohn McCall       QualType T = VD->getType();
33387fe5d56SJohn McCall 
33487fe5d56SJohn McCall       Note.RequiresCopying = BlockRequiresCopying(T);
33587fe5d56SJohn McCall 
33687fe5d56SJohn McCall       if (BDRE->isByRef()) {
33787fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_BYREF;
33887fe5d56SJohn McCall         if (T.isObjCGCWeak())
33987fe5d56SJohn McCall           Note.flag |= BLOCK_FIELD_IS_WEAK;
34087fe5d56SJohn McCall       } else if (T->isBlockPointerType()) {
34187fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_BLOCK;
34287fe5d56SJohn McCall       } else {
34387fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_OBJECT;
34487fe5d56SJohn McCall       }
345aeb0ffd5SMike Stump 
3461db7d04bSMike Stump       if (LocalDeclMap[VD]) {
34797d01d50SMike Stump         if (BDRE->isByRef()) {
34897d01d50SMike Stump           llvm::Value *Loc = LocalDeclMap[VD];
34997d01d50SMike Stump           Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
350c76493a6SDaniel Dunbar           Loc = Builder.CreateLoad(Loc);
35197d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
35297d01d50SMike Stump           continue;
35387fe5d56SJohn McCall         } else {
3543b836180SFariborz Jahanian           if (BDRE->getCopyConstructorExpr()) {
355ea882cd9SFariborz Jahanian             E = BDRE->getCopyConstructorExpr();
356bd30929eSJohn McCall             PushDestructorCleanup(E->getType(), Addr);
3573b836180SFariborz Jahanian           }
358ea882cd9SFariborz Jahanian             else {
35987fe5d56SJohn McCall               E = new (getContext()) DeclRefExpr(const_cast<ValueDecl*>(VD),
360d1b378e0SFariborz Jahanian                                             VD->getType().getNonReferenceType(),
361d1b378e0SFariborz Jahanian                                             SourceLocation());
36264176c2cSFariborz Jahanian               if (VD->getType()->isReferenceType()) {
363d1b378e0SFariborz Jahanian                 E = new (getContext())
364d1b378e0SFariborz Jahanian                     UnaryOperator(const_cast<Expr*>(E), UnaryOperator::AddrOf,
365d1b378e0SFariborz Jahanian                                 getContext().getPointerType(E->getType()),
366ed6c7440SDouglas Gregor                                 SourceLocation());
3671db7d04bSMike Stump               }
36864176c2cSFariborz Jahanian             }
36964176c2cSFariborz Jahanian           }
37087fe5d56SJohn McCall         }
37187fe5d56SJohn McCall 
37297d01d50SMike Stump       if (BDRE->isByRef()) {
3731db7d04bSMike Stump         E = new (getContext())
37487fe5d56SJohn McCall           UnaryOperator(const_cast<Expr*>(E), UnaryOperator::AddrOf,
3751db7d04bSMike Stump                         getContext().getPointerType(E->getType()),
3761db7d04bSMike Stump                         SourceLocation());
37797d01d50SMike Stump       }
3781db7d04bSMike Stump 
3791db7d04bSMike Stump       RValue r = EmitAnyExpr(E, Addr, false);
38097d01d50SMike Stump       if (r.isScalar()) {
38197d01d50SMike Stump         llvm::Value *Loc = r.getScalarVal();
382950a9518SDavid Chisnall         const llvm::Type *Ty = Types[i+BlockFields];
38397d01d50SMike Stump         if  (BDRE->isByRef()) {
3842d33d630SMike Stump           // E is now the address of the value field, instead, we want the
3852d33d630SMike Stump           // address of the actual ByRef struct.  We optimize this slightly
3862d33d630SMike Stump           // compared to gcc by not grabbing the forwarding slot as this must
3872d33d630SMike Stump           // be done during Block_copy for us, and we can postpone the work
3882d33d630SMike Stump           // until then.
38940775003SKen Dyck           CharUnits offset = BlockDecls[BDRE->getDecl()];
3902d33d630SMike Stump 
3912d33d630SMike Stump           llvm::Value *BlockLiteral = LoadBlockStruct();
3922d33d630SMike Stump 
3932d33d630SMike Stump           Loc = Builder.CreateGEP(BlockLiteral,
3945e016ae9SChris Lattner                      llvm::ConstantInt::get(Int64Ty, offset.getQuantity()),
3952d33d630SMike Stump                                   "block.literal");
3969793f0e4SOwen Anderson           Ty = llvm::PointerType::get(Ty, 0);
39797d01d50SMike Stump           Loc = Builder.CreateBitCast(Loc, Ty);
398c76493a6SDaniel Dunbar           Loc = Builder.CreateLoad(Loc);
3992d33d630SMike Stump           // Loc = Builder.CreateBitCast(Loc, Ty);
40097d01d50SMike Stump         }
40197d01d50SMike Stump         Builder.CreateStore(Loc, Addr);
40297d01d50SMike Stump       } else if (r.isComplex())
403b750d928SMike Stump         // FIXME: implement
404b750d928SMike Stump         ErrorUnsupported(BE, "complex in block literal");
405b750d928SMike Stump       else if (r.isAggregate())
406b750d928SMike Stump         ; // Already created into the destination
407b750d928SMike Stump       else
408b750d928SMike Stump         assert (0 && "bad block variable");
409b750d928SMike Stump       // FIXME: Ensure that the offset created by the backend for
410b750d928SMike Stump       // the struct matches the previously computed offset in BlockDecls.
411b750d928SMike Stump     }
41287fe5d56SJohn McCall     NoteForHelper.resize(NumHelpers);
413d6ef62f0SMike Stump 
414d6ef62f0SMike Stump     // __descriptor
415fc83aa04SBlaine Garst     llvm::Value *Descriptor = BuildDescriptorBlockDecl(BE,
4169d42f0f1SJohn McCall                                                        Info.BlockHasCopyDispose,
4179d42f0f1SJohn McCall                                                        Info.BlockSize, Ty,
418aeb0ffd5SMike Stump                                                        &NoteForHelper);
419aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
420aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
421b750d928SMike Stump   }
422b750d928SMike Stump 
423b750d928SMike Stump   QualType BPT = BE->getType();
424989908fbSFariborz Jahanian   V = Builder.CreateBitCast(V, ConvertType(BPT));
425989908fbSFariborz Jahanian   // See if this is a __weak block variable and the must call objc_read_weak
426989908fbSFariborz Jahanian   // on it.
427989908fbSFariborz Jahanian   const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
428989908fbSFariborz Jahanian   QualType RES = ftype->getResultType();
429989908fbSFariborz Jahanian   if (RES.isObjCGCWeak()) {
430989908fbSFariborz Jahanian     // Must cast argument to id*
431989908fbSFariborz Jahanian     const llvm::Type *ObjectPtrTy =
432989908fbSFariborz Jahanian       ConvertType(CGM.getContext().getObjCIdType());
433989908fbSFariborz Jahanian     const llvm::Type *PtrObjectPtrTy =
434989908fbSFariborz Jahanian       llvm::PointerType::getUnqual(ObjectPtrTy);
435989908fbSFariborz Jahanian     V = Builder.CreateBitCast(V, PtrObjectPtrTy);
436989908fbSFariborz Jahanian     V =  CGM.getObjCRuntime().EmitObjCWeakRead(*this, V);
437989908fbSFariborz Jahanian   }
438989908fbSFariborz Jahanian   return V;
439b750d928SMike Stump }
44085284bacSMike Stump 
44185284bacSMike Stump 
44295435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
443650c932dSMike Stump   if (BlockDescriptorType)
444650c932dSMike Stump     return BlockDescriptorType;
4452437cbfaSAnders Carlsson 
4462437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
447650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
4482437cbfaSAnders Carlsson 
4492437cbfaSAnders Carlsson   // struct __block_descriptor {
4502437cbfaSAnders Carlsson   //   unsigned long reserved;
4512437cbfaSAnders Carlsson   //   unsigned long block_size;
452fc83aa04SBlaine Garst   //
453fc83aa04SBlaine Garst   //   // later, the following will be added
454fc83aa04SBlaine Garst   //
455fc83aa04SBlaine Garst   //   struct {
456fc83aa04SBlaine Garst   //     void (*copyHelper)();
457fc83aa04SBlaine Garst   //     void (*copyHelper)();
458fc83aa04SBlaine Garst   //   } helpers;                // !!! optional
459fc83aa04SBlaine Garst   //
460fc83aa04SBlaine Garst   //   const char *signature;   // the block signature
461fc83aa04SBlaine Garst   //   const char *layout;      // reserved
4622437cbfaSAnders Carlsson   // };
463758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
464758428f4SOwen Anderson                                               UnsignedLongTy,
4652437cbfaSAnders Carlsson                                               UnsignedLongTy,
4662437cbfaSAnders Carlsson                                               NULL);
4672437cbfaSAnders Carlsson 
468650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
469650c932dSMike Stump                           BlockDescriptorType);
4702437cbfaSAnders Carlsson 
471650c932dSMike Stump   return BlockDescriptorType;
4722437cbfaSAnders Carlsson }
4732437cbfaSAnders Carlsson 
47495435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
475005c9a62SMike Stump   if (GenericBlockLiteralType)
476005c9a62SMike Stump     return GenericBlockLiteralType;
4772437cbfaSAnders Carlsson 
4782437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
4799793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
4802437cbfaSAnders Carlsson 
48192bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
48292bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
48392bbd6d4SMike Stump 
4842437cbfaSAnders Carlsson   // struct __block_literal_generic {
4855d2534adSMike Stump   //   void *__isa;
4865d2534adSMike Stump   //   int __flags;
4875d2534adSMike Stump   //   int __reserved;
4885d2534adSMike Stump   //   void (*__invoke)(void *);
4895d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
4902437cbfaSAnders Carlsson   // };
491758428f4SOwen Anderson   GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
492758428f4SOwen Anderson                                                   PtrToInt8Ty,
49392bbd6d4SMike Stump                                                   IntTy,
49492bbd6d4SMike Stump                                                   IntTy,
495626aecc4SMike Stump                                                   PtrToInt8Ty,
4962437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
4972437cbfaSAnders Carlsson                                                   NULL);
4982437cbfaSAnders Carlsson 
499005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
500005c9a62SMike Stump                           GenericBlockLiteralType);
5012437cbfaSAnders Carlsson 
502005c9a62SMike Stump   return GenericBlockLiteralType;
5032437cbfaSAnders Carlsson }
5042437cbfaSAnders Carlsson 
5055d2534adSMike Stump 
506bfb3671bSAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
507bfb3671bSAnders Carlsson                                           ReturnValueSlot ReturnValue) {
5082437cbfaSAnders Carlsson   const BlockPointerType *BPT =
509c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
5102437cbfaSAnders Carlsson 
5112437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
5122437cbfaSAnders Carlsson 
5132437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
5142437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
5159793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
5162437cbfaSAnders Carlsson 
5172437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
5182437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
5192437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
5202437cbfaSAnders Carlsson 
5212437cbfaSAnders Carlsson   // Get the function pointer from the literal.
5222437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
5232437cbfaSAnders Carlsson 
5242437cbfaSAnders Carlsson   BlockLiteral =
5252437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
526abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
5272437cbfaSAnders Carlsson                           "tmp");
5282437cbfaSAnders Carlsson 
5292437cbfaSAnders Carlsson   // Add the block literal.
5302437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
5312437cbfaSAnders Carlsson   CallArgList Args;
5322437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
5332437cbfaSAnders Carlsson 
534479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
535479e6fc7SAnders Carlsson 
5362437cbfaSAnders Carlsson   // And the rest of the arguments.
5379dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
538479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
5392437cbfaSAnders Carlsson 
5405f50c651SAnders Carlsson   // Load the function.
541c76493a6SDaniel Dunbar   llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
5425f50c651SAnders Carlsson 
543ab26cfa5SJohn McCall   const FunctionType *FuncTy = FnType->getAs<FunctionType>();
544ab26cfa5SJohn McCall   QualType ResultType = FuncTy->getResultType();
545a60cbcdfSAnders Carlsson 
546a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
547c50c27ccSRafael Espindola     CGM.getTypes().getFunctionInfo(ResultType, Args,
548c50c27ccSRafael Espindola                                    FuncTy->getExtInfo());
5495f50c651SAnders Carlsson 
5505f50c651SAnders Carlsson   // Cast the function pointer to the right type.
5515f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
552a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
5535f50c651SAnders Carlsson 
5549793f0e4SOwen Anderson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
5555f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
5565f50c651SAnders Carlsson 
5572437cbfaSAnders Carlsson   // And call the block.
558bfb3671bSAnders Carlsson   return EmitCall(FnInfo, Func, ReturnValue, Args);
5592437cbfaSAnders Carlsson }
5606a60fa24SAnders Carlsson 
56187fe5d56SJohn McCall void CodeGenFunction::AllocateBlockCXXThisPointer(const CXXThisExpr *E) {
56287fe5d56SJohn McCall   assert(BlockCXXThisOffset.isZero() && "already computed 'this' pointer");
56387fe5d56SJohn McCall 
56487fe5d56SJohn McCall   // Figure out what the offset is.
56587fe5d56SJohn McCall   QualType T = E->getType();
56687fe5d56SJohn McCall   std::pair<CharUnits,CharUnits> TypeInfo = getContext().getTypeInfoInChars(T);
56787fe5d56SJohn McCall   CharUnits Offset = getBlockOffset(TypeInfo.first, TypeInfo.second);
56887fe5d56SJohn McCall 
56987fe5d56SJohn McCall   BlockCXXThisOffset = Offset;
57087fe5d56SJohn McCall   BlockLayout.push_back(E);
57187fe5d56SJohn McCall }
57287fe5d56SJohn McCall 
57387fe5d56SJohn McCall void CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
5740168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
57587fe5d56SJohn McCall   CharUnits &Offset = BlockDecls[VD];
5760168f4b2SAnders Carlsson 
57797d01d50SMike Stump   // See if we have already allocated an offset for this variable.
57887fe5d56SJohn McCall   if (!Offset.isZero())
57987fe5d56SJohn McCall     return;
5807fe9cc1dSMike Stump 
5814446dcf0SMike Stump   // Don't run the expensive check, unless we have to.
582e1b19ba0SMike Stump   if (!BlockHasCopyDispose)
583e1b19ba0SMike Stump     if (E->isByRef()
584e1b19ba0SMike Stump         || BlockRequiresCopying(E->getType()))
5854446dcf0SMike Stump       BlockHasCopyDispose = true;
5867fe9cc1dSMike Stump 
58787fe5d56SJohn McCall   const ValueDecl *D = cast<ValueDecl>(E->getDecl());
5887fe9cc1dSMike Stump 
58987fe5d56SJohn McCall   CharUnits Size;
59087fe5d56SJohn McCall   CharUnits Align;
59187fe5d56SJohn McCall 
59287fe5d56SJohn McCall   if (E->isByRef()) {
59387fe5d56SJohn McCall     llvm::tie(Size,Align) =
59487fe5d56SJohn McCall       getContext().getTypeInfoInChars(getContext().VoidPtrTy);
59587fe5d56SJohn McCall   } else {
59687fe5d56SJohn McCall     Size = getContext().getTypeSizeInChars(D->getType());
59787fe5d56SJohn McCall     Align = getContext().getDeclAlign(D);
59887fe5d56SJohn McCall   }
59987fe5d56SJohn McCall 
60087fe5d56SJohn McCall   Offset = getBlockOffset(Size, Align);
60187fe5d56SJohn McCall   BlockLayout.push_back(E);
60297d01d50SMike Stump }
60397d01d50SMike Stump 
6049d42f0f1SJohn McCall llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const ValueDecl *VD,
6059d42f0f1SJohn McCall                                                  bool IsByRef) {
60664176c2cSFariborz Jahanian 
60787fe5d56SJohn McCall   CharUnits offset = BlockDecls[VD];
60887fe5d56SJohn McCall   assert(!offset.isZero() && "getting address of unallocated decl");
6097fe9cc1dSMike Stump 
61097d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
61197d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
6125e016ae9SChris Lattner                        llvm::ConstantInt::get(Int64Ty, offset.getQuantity()),
6132d33d630SMike Stump                                      "block.literal");
6149d42f0f1SJohn McCall   if (IsByRef) {
61597d01d50SMike Stump     const llvm::Type *PtrStructTy
6160168f4b2SAnders Carlsson       = llvm::PointerType::get(BuildByRefType(VD), 0);
617efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
618efd7caa8SMike Stump     BlockHasCopyDispose = true;
6190168f4b2SAnders Carlsson 
6200168f4b2SAnders Carlsson     const llvm::Type *Ty = PtrStructTy;
6219793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
62297d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
623c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
62497d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
625c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
62697d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
6270168f4b2SAnders Carlsson     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
6280168f4b2SAnders Carlsson                                 VD->getNameAsString());
629eeb23379SFariborz Jahanian     if (VD->getType()->isReferenceType())
630eeb23379SFariborz Jahanian       V = Builder.CreateLoad(V);
63197d01d50SMike Stump   } else {
6320168f4b2SAnders Carlsson     const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
6339793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
63497d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
635d1b378e0SFariborz Jahanian     if (VD->getType()->isReferenceType())
63664176c2cSFariborz Jahanian       V = Builder.CreateLoad(V, "ref.tmp");
63797d01d50SMike Stump   }
63897d01d50SMike Stump   return V;
63997d01d50SMike Stump }
64097d01d50SMike Stump 
6412d5a2878SMike Stump llvm::Constant *
6426c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
6436a60fa24SAnders Carlsson   // Generate the block descriptor.
6446a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
64592bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
64692bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
6476a60fa24SAnders Carlsson 
648fc83aa04SBlaine Garst   llvm::Constant *DescriptorFields[4];
6496a60fa24SAnders Carlsson 
6506a60fa24SAnders Carlsson   // Reserved
6510b75f23bSOwen Anderson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
6526a60fa24SAnders Carlsson 
6536a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
6546a60fa24SAnders Carlsson   // block literal struct.
65598ca7943SKen Dyck   CharUnits BlockLiteralSize =
65698ca7943SKen Dyck     CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
657170229f6SOwen Anderson   DescriptorFields[1] =
65840775003SKen Dyck     llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
6596a60fa24SAnders Carlsson 
660fc83aa04SBlaine Garst   // signature.  non-optional ObjC-style method descriptor @encode sequence
661fc83aa04SBlaine Garst   std::string BlockTypeEncoding;
662fc83aa04SBlaine Garst   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
663fc83aa04SBlaine Garst 
664fc83aa04SBlaine Garst   DescriptorFields[2] = llvm::ConstantExpr::getBitCast(
665fc83aa04SBlaine Garst           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
666fc83aa04SBlaine Garst 
667fc83aa04SBlaine Garst   // layout
668fc83aa04SBlaine Garst   DescriptorFields[3] =
669fc83aa04SBlaine Garst     llvm::ConstantInt::get(UnsignedLongTy,0);
670fc83aa04SBlaine Garst 
671fc83aa04SBlaine Garst   // build the structure from the 4 elements
6726a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
673fc83aa04SBlaine Garst     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false);
6746a60fa24SAnders Carlsson 
6756a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
676c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
6776a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
678c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
6796a60fa24SAnders Carlsson 
680950a9518SDavid Chisnall   int FieldCount = 5;
6816a60fa24SAnders Carlsson   // Generate the constants for the block literal.
682950a9518SDavid Chisnall 
683950a9518SDavid Chisnall   std::vector<llvm::Constant*> LiteralFields(FieldCount);
6846a60fa24SAnders Carlsson 
6859d42f0f1SJohn McCall   CGBlockInfo Info(n);
6865469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
687cb2fbcb0SMike Stump   llvm::Function *Fn
688*d5010898SFariborz Jahanian     = CodeGenFunction(CGM).GenerateBlockFunction(GlobalDecl(), BE,
689*d5010898SFariborz Jahanian                                                  Info, 0, LocalDeclMap);
6909d42f0f1SJohn McCall   assert(Info.BlockSize == BlockLiteralSize
691cb2fbcb0SMike Stump          && "no imports allowed for global block");
6926a60fa24SAnders Carlsson 
6936a60fa24SAnders Carlsson   // isa
694900546d2SDaniel Dunbar   LiteralFields[0] = CGM.getNSConcreteGlobalBlock();
6956a60fa24SAnders Carlsson 
696*d5010898SFariborz Jahanian   // __flags
697*d5010898SFariborz Jahanian   unsigned flags = computeBlockFlag(CGM, BE,
698*d5010898SFariborz Jahanian                                     (BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE));
699fc83aa04SBlaine Garst   LiteralFields[1] =
700*d5010898SFariborz Jahanian     llvm::ConstantInt::get(IntTy, flags);
7016a60fa24SAnders Carlsson 
7026a60fa24SAnders Carlsson   // Reserved
7030b75f23bSOwen Anderson   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
7046a60fa24SAnders Carlsson 
7056a60fa24SAnders Carlsson   // Function
7066a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
7076a60fa24SAnders Carlsson 
7086a60fa24SAnders Carlsson   // Descriptor
7096a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
7106a60fa24SAnders Carlsson 
7116a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
712950a9518SDavid Chisnall     llvm::ConstantStruct::get(VMContext, LiteralFields, false);
7136a60fa24SAnders Carlsson 
7146a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
715c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
7166a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
717c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
7186a60fa24SAnders Carlsson 
7196a60fa24SAnders Carlsson   return BlockLiteral;
7206a60fa24SAnders Carlsson }
7216a60fa24SAnders Carlsson 
722cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
72338382028SMike Stump   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
72438382028SMike Stump                                       "self");
72538382028SMike Stump   // For now, we codegen based upon byte offsets.
72638382028SMike Stump   return Builder.CreateBitCast(V, PtrToInt8Ty);
727cb2fbcb0SMike Stump }
728cb2fbcb0SMike Stump 
7294446dcf0SMike Stump llvm::Function *
7309b5528d2SFariborz Jahanian CodeGenFunction::GenerateBlockFunction(GlobalDecl GD, const BlockExpr *BExpr,
7319d42f0f1SJohn McCall                                        CGBlockInfo &Info,
732692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
7339d42f0f1SJohn McCall                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm) {
7349074ed8cSDevang Patel 
7359074ed8cSDevang Patel   // Check if we should generate debug info for this block.
7369074ed8cSDevang Patel   if (CGM.getDebugInfo())
7379074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
7389074ed8cSDevang Patel 
7395469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
7405469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
7415469f29aSMike Stump   // in a block.
7425469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
7435469f29aSMike Stump        i != ldm.end();
7445469f29aSMike Stump        ++i) {
7455469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
7465469f29aSMike Stump 
7470ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
7485469f29aSMike Stump       LocalDeclMap[VD] = i->second;
7495469f29aSMike Stump   }
7505469f29aSMike Stump 
75198ca7943SKen Dyck   BlockOffset =
75298ca7943SKen Dyck       CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
7535262b119SKen Dyck   BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
75409a9b6e3SEli Friedman 
755aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
756aae4349dSFariborz Jahanian   QualType ResultType;
757c50c27ccSRafael Espindola   FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType);
758aae4349dSFariborz Jahanian   bool IsVariadic;
759a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
760a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
761aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
762aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
763658fe02dSMike Stump   } else {
764aae4349dSFariborz Jahanian     // K&R style block.
765aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
766aae4349dSFariborz Jahanian     IsVariadic = false;
767aae4349dSFariborz Jahanian   }
7686a60fa24SAnders Carlsson 
7696a60fa24SAnders Carlsson   FunctionArgList Args;
7706a60fa24SAnders Carlsson 
7717fe9cc1dSMike Stump   CurFuncDecl = OuterFuncDecl;
7727fe9cc1dSMike Stump 
7733385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
7746a60fa24SAnders Carlsson 
7757fe9cc1dSMike Stump   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
776d015328fSMike Stump 
77787fe5d56SJohn McCall   // Build the block struct now.
7789d42f0f1SJohn McCall   AllocateAllBlockDeclRefs(*this, Info);
7797fe9cc1dSMike Stump 
780e1b19ba0SMike Stump   QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
78187fe5d56SJohn McCall                                                   BlockLayout);
78287fe5d56SJohn McCall 
7836a60fa24SAnders Carlsson   // FIXME: This leaks
7846a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
7854d4dcc8eSJohn McCall     ImplicitParamDecl::Create(getContext(), const_cast<BlockDecl*>(BD),
786d015328fSMike Stump                               SourceLocation(), II,
787d015328fSMike Stump                               ParmTy);
7886a60fa24SAnders Carlsson 
7896a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
790cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
7916a60fa24SAnders Carlsson 
792c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
7936a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
794eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
7956a60fa24SAnders Carlsson 
7966a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
797c50c27ccSRafael Espindola     CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo);
7986a60fa24SAnders Carlsson 
7996a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
800aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
8016a60fa24SAnders Carlsson 
8027e10f369SDouglas Gregor   MangleBuffer Name;
8039b5528d2SFariborz Jahanian   CGM.getMangledName(GD, Name, BD);
8046a60fa24SAnders Carlsson   llvm::Function *Fn =
80502df9da2SDouglas Gregor     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
80602df9da2SDouglas Gregor                            Name.getString(), &CGM.getModule());
8076a60fa24SAnders Carlsson 
808c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
809c3e7cff6SDaniel Dunbar 
81036ad0e99SFariborz Jahanian   QualType FnType(BlockFunctionType, 0);
811c42461e1SFariborz Jahanian   bool HasPrototype = isa<FunctionProtoType>(BlockFunctionType);
81236ad0e99SFariborz Jahanian 
81336ad0e99SFariborz Jahanian   IdentifierInfo *ID = &getContext().Idents.get(Name.getString());
81436ad0e99SFariborz Jahanian   CurCodeDecl = FunctionDecl::Create(getContext(),
81536ad0e99SFariborz Jahanian                                      getContext().getTranslationUnitDecl(),
81636ad0e99SFariborz Jahanian                                      SourceLocation(), ID, FnType,
81736ad0e99SFariborz Jahanian                                      0,
81836ad0e99SFariborz Jahanian                                      FunctionDecl::Static,
81936ad0e99SFariborz Jahanian                                      FunctionDecl::None,
82036ad0e99SFariborz Jahanian                                      false, HasPrototype);
82136ad0e99SFariborz Jahanian 
822324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
8233385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
8242e722b91SMike Stump 
825324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
826017460abSMike Stump 
82787fe5d56SJohn McCall   // If we have a C++ 'this' reference, go ahead and force it into
82887fe5d56SJohn McCall   // existence now.
82987fe5d56SJohn McCall   if (Info.CXXThisRef) {
83087fe5d56SJohn McCall     assert(!BlockCXXThisOffset.isZero() &&
83187fe5d56SJohn McCall            "haven't yet allocated 'this' reference");
83287fe5d56SJohn McCall 
83387fe5d56SJohn McCall     // TODO: I have a dream that one day this will be typed.
83487fe5d56SJohn McCall     llvm::Value *BlockLiteral = LoadBlockStruct();
83587fe5d56SJohn McCall     llvm::Value *ThisPtrRaw =
83687fe5d56SJohn McCall       Builder.CreateConstInBoundsGEP1_64(BlockLiteral,
83787fe5d56SJohn McCall                                          BlockCXXThisOffset.getQuantity(),
83887fe5d56SJohn McCall                                          "this.ptr.raw");
83987fe5d56SJohn McCall 
84087fe5d56SJohn McCall     const llvm::Type *Ty =
84187fe5d56SJohn McCall       CGM.getTypes().ConvertType(Info.CXXThisRef->getType());
84287fe5d56SJohn McCall     Ty = llvm::PointerType::get(Ty, 0);
84387fe5d56SJohn McCall     llvm::Value *ThisPtr = Builder.CreateBitCast(ThisPtrRaw, Ty, "this.ptr");
84487fe5d56SJohn McCall 
84587fe5d56SJohn McCall     CXXThisValue = Builder.CreateLoad(ThisPtr, "this");
84687fe5d56SJohn McCall   }
84787fe5d56SJohn McCall 
8489d42f0f1SJohn McCall   // If we have an Objective C 'self' reference, go ahead and force it
8499d42f0f1SJohn McCall   // into existence now.
8509d42f0f1SJohn McCall   if (Info.NeedsObjCSelf) {
8519d42f0f1SJohn McCall     ValueDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
8529d42f0f1SJohn McCall     LocalDeclMap[Self] = GetAddrOfBlockDecl(Self, false);
8539d42f0f1SJohn McCall   }
8549d42f0f1SJohn McCall 
855017460abSMike Stump   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
856017460abSMike Stump   llvm::BasicBlock *entry = Builder.GetInsertBlock();
857017460abSMike Stump   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
858017460abSMike Stump   --entry_ptr;
859017460abSMike Stump 
8603385fe12SChris Lattner   EmitStmt(BExpr->getBody());
861017460abSMike Stump 
8627d69911aSMike Stump   // Remember where we were...
8637d69911aSMike Stump   llvm::BasicBlock *resume = Builder.GetInsertBlock();
864017460abSMike Stump 
8657d69911aSMike Stump   // Go back to the entry.
866017460abSMike Stump   ++entry_ptr;
867017460abSMike Stump   Builder.SetInsertPoint(entry, entry_ptr);
868017460abSMike Stump 
8692e722b91SMike Stump   if (CGDebugInfo *DI = getDebugInfo()) {
8702e722b91SMike Stump     // Emit debug information for all the BlockDeclRefDecls.
87187fe5d56SJohn McCall     // FIXME: also for 'this'
87287fe5d56SJohn McCall     for (unsigned i = 0, e = BlockLayout.size(); i != e; ++i) {
873bf78478dSChris Lattner       if (const BlockDeclRefExpr *BDRE =
87487fe5d56SJohn McCall             dyn_cast<BlockDeclRefExpr>(BlockLayout[i])) {
8752e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
8762e722b91SMike Stump         DI->setLocation(D->getLocation());
8772e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
8782e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
8792e722b91SMike Stump                                               Builder, this);
8802e722b91SMike Stump       }
8812e722b91SMike Stump     }
8822e722b91SMike Stump   }
8837d69911aSMike Stump   // And resume where we left off.
8847d69911aSMike Stump   if (resume == 0)
8857d69911aSMike Stump     Builder.ClearInsertionPoint();
8867d69911aSMike Stump   else
8877d69911aSMike Stump     Builder.SetInsertPoint(resume);
8882e722b91SMike Stump 
8893385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
8906a60fa24SAnders Carlsson 
891b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
8925262b119SKen Dyck   CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
89340775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
8945262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
8955262b119SKen Dyck                                MinAlign.getQuantity()));
896b750d928SMike Stump 
8979d42f0f1SJohn McCall   Info.BlockSize = BlockOffset;
8989d42f0f1SJohn McCall   Info.BlockAlign = BlockAlign;
8999d42f0f1SJohn McCall   Info.BlockLayout = BlockLayout;
9009d42f0f1SJohn McCall   Info.BlockHasCopyDispose = BlockHasCopyDispose;
9016a60fa24SAnders Carlsson   return Fn;
9026a60fa24SAnders Carlsson }
9031db7d04bSMike Stump 
90487fe5d56SJohn McCall CharUnits BlockFunction::getBlockOffset(CharUnits Size, CharUnits Align) {
9055262b119SKen Dyck   assert((Align.isPositive()) && "alignment must be 1 byte or more");
9061db7d04bSMike Stump 
90740775003SKen Dyck   CharUnits OldOffset = BlockOffset;
9081db7d04bSMike Stump 
9091db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
91040775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
9115262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
9121db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
9131db7d04bSMike Stump 
91440775003SKen Dyck   CharUnits Pad = BlockOffset - OldOffset;
91540775003SKen Dyck   if (Pad.isPositive()) {
9161db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
91740775003SKen Dyck                                                        llvm::APInt(32,
91840775003SKen Dyck                                                          Pad.getQuantity()),
9191db7d04bSMike Stump                                                        ArrayType::Normal, 0);
9206a047c97SDouglas Gregor     ValueDecl *PadDecl = VarDecl::Create(getContext(),
9216a047c97SDouglas Gregor                                          getContext().getTranslationUnitDecl(),
9226a047c97SDouglas Gregor                                          SourceLocation(),
923c4df4076SDouglas Gregor                                          0, QualType(PadTy), 0,
924c4df4076SDouglas Gregor                                          VarDecl::None, VarDecl::None);
92587fe5d56SJohn McCall     Expr *E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
926ed6c7440SDouglas Gregor                                              SourceLocation());
92787fe5d56SJohn McCall     BlockLayout.push_back(E);
9281db7d04bSMike Stump   }
9291db7d04bSMike Stump 
9301db7d04bSMike Stump   BlockOffset += Size;
9311db7d04bSMike Stump   return BlockOffset - Size;
9321db7d04bSMike Stump }
93397d01d50SMike Stump 
934aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
935aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
93667645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
9370c743277SMike Stump   QualType R = getContext().VoidTy;
9380c743277SMike Stump 
9390c743277SMike Stump   FunctionArgList Args;
9400c743277SMike Stump   // FIXME: This leaks
941aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
9427fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9437fe9cc1dSMike Stump                               SourceLocation(), 0,
944aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
945aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
9460c743277SMike Stump   ImplicitParamDecl *Src =
9477fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9487fe9cc1dSMike Stump                               SourceLocation(), 0,
9490c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
9500c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
9510c743277SMike Stump 
9520c743277SMike Stump   const CGFunctionInfo &FI =
953c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
9540c743277SMike Stump 
955cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
956cbc2bcafSMike Stump   // internal linkage.
9570c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
9580c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
9590c743277SMike Stump 
9600c743277SMike Stump   llvm::Function *Fn =
9610c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
962d6b28fc6SBenjamin Kramer                            "__copy_helper_block_", &CGM.getModule());
9630c743277SMike Stump 
9640c743277SMike Stump   IdentifierInfo *II
9650c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
9660c743277SMike Stump 
9670c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
9680c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
96960ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
970c4df4076SDouglas Gregor                                           FunctionDecl::Static,
971c4df4076SDouglas Gregor                                           FunctionDecl::None,
972c4df4076SDouglas Gregor                                           false,
9730c743277SMike Stump                                           true);
9740c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
975aeb0ffd5SMike Stump 
976aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
977aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
97867645930SMike Stump 
97967645930SMike Stump   if (NoteForHelperp) {
98067645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
98167645930SMike Stump 
9829793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
983aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
984aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
985aeb0ffd5SMike Stump 
986aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
9873b65ac26SMike Stump     llvm::Type *PtrPtrT;
9889793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9893b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
9903b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
991aeb0ffd5SMike Stump 
992aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
993aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
994aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
995aeb0ffd5SMike Stump 
996aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
997aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
998aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
999aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
1000aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
10019793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
1002aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
1003aeb0ffd5SMike Stump 
1004aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
1005aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
1006aeb0ffd5SMike Stump 
10075e016ae9SChris Lattner         llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
1008900546d2SDaniel Dunbar         llvm::Value *F = CGM.getBlockObjectAssign();
1009aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
1010aeb0ffd5SMike Stump       }
1011aeb0ffd5SMike Stump     }
101267645930SMike Stump   }
1013aeb0ffd5SMike Stump 
10140c743277SMike Stump   CGF.FinishFunction();
10150c743277SMike Stump 
1016ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
101797d01d50SMike Stump }
101897d01d50SMike Stump 
1019d6ef62f0SMike Stump llvm::Constant *BlockFunction::
1020aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
1021aeb0ffd5SMike Stump                               const llvm::StructType* T,
102267645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
10230c743277SMike Stump   QualType R = getContext().VoidTy;
10240c743277SMike Stump 
10250c743277SMike Stump   FunctionArgList Args;
10260c743277SMike Stump   // FIXME: This leaks
10270c743277SMike Stump   ImplicitParamDecl *Src =
10287fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10297fe9cc1dSMike Stump                               SourceLocation(), 0,
10300c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
10310c743277SMike Stump 
10320c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
10330c743277SMike Stump 
10340c743277SMike Stump   const CGFunctionInfo &FI =
1035c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
10360c743277SMike Stump 
1037cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1038cbc2bcafSMike Stump   // internal linkage.
10390c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
10400c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
10410c743277SMike Stump 
10420c743277SMike Stump   llvm::Function *Fn =
10430c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1044d6b28fc6SBenjamin Kramer                            "__destroy_helper_block_", &CGM.getModule());
10450c743277SMike Stump 
10460c743277SMike Stump   IdentifierInfo *II
10470c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
10480c743277SMike Stump 
10490c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
10500c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
105160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1052c4df4076SDouglas Gregor                                           FunctionDecl::Static,
1053c4df4076SDouglas Gregor                                           FunctionDecl::None,
1054c4df4076SDouglas Gregor                                           false, true);
10550c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
10566f7d9f87SMike Stump 
105767645930SMike Stump   if (NoteForHelperp) {
105867645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
105967645930SMike Stump 
10606f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
10616f7d9f87SMike Stump     llvm::Type *PtrPtrT;
10629793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
10636f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
10646f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
10656f7d9f87SMike Stump 
10666f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
10676f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
10686f7d9f87SMike Stump       int index = NoteForHelper[i].index;
10696f7d9f87SMike Stump 
10706f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
10716f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
10726f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
10736f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
10746f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
10759793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
10766f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
10776f7d9f87SMike Stump 
10786f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
10796f7d9f87SMike Stump       }
10806f7d9f87SMike Stump     }
108167645930SMike Stump   }
10826f7d9f87SMike Stump 
10830c743277SMike Stump   CGF.FinishFunction();
10840c743277SMike Stump 
1085ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
10860c743277SMike Stump }
10870c743277SMike Stump 
1088aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
108967645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
1090aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1091aeb0ffd5SMike Stump                                                          T, NoteForHelper);
10920c743277SMike Stump }
10930c743277SMike Stump 
1094aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
109567645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
1096aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
109767645930SMike Stump                                                             T, NoteForHelperp);
109897d01d50SMike Stump }
1099626aecc4SMike Stump 
1100f89230d9SMike Stump llvm::Constant *BlockFunction::
1101f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
1102ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1103ee2a5ee5SMike Stump 
1104ee2a5ee5SMike Stump   FunctionArgList Args;
1105ee2a5ee5SMike Stump   // FIXME: This leaks
1106f89230d9SMike Stump   ImplicitParamDecl *Dst =
11077fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
11087fe9cc1dSMike Stump                               SourceLocation(), 0,
1109f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1110f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
1111f89230d9SMike Stump 
1112f89230d9SMike Stump   // FIXME: This leaks
1113ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
11147fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
11157fe9cc1dSMike Stump                               SourceLocation(), 0,
1116ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1117ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1118ee2a5ee5SMike Stump 
1119ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1120c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1121ee2a5ee5SMike Stump 
1122ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1123ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1124ee2a5ee5SMike Stump 
1125cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1126cbc2bcafSMike Stump   // internal linkage.
1127ee2a5ee5SMike Stump   llvm::Function *Fn =
1128ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1129d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_copy_", &CGM.getModule());
1130ee2a5ee5SMike Stump 
1131ee2a5ee5SMike Stump   IdentifierInfo *II
1132ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1133ee2a5ee5SMike Stump 
1134ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1135ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
113660ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1137c4df4076SDouglas Gregor                                           FunctionDecl::Static,
1138c4df4076SDouglas Gregor                                           FunctionDecl::None,
1139c4df4076SDouglas Gregor                                           false, true);
1140ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1141f89230d9SMike Stump 
1142f89230d9SMike Stump   // dst->x
1143f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
11449793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
11453b65ac26SMike Stump   V = Builder.CreateLoad(V);
1146f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
1147f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1148f89230d9SMike Stump 
1149f89230d9SMike Stump   // src->x
1150f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
1151f89230d9SMike Stump   V = Builder.CreateLoad(V);
1152f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
1153f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
11549793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1155f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
1156f89230d9SMike Stump 
1157f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
1158f89230d9SMike Stump 
11595e016ae9SChris Lattner   llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
1160900546d2SDaniel Dunbar   llvm::Value *F = CGM.getBlockObjectAssign();
1161f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1162f89230d9SMike Stump 
1163ee2a5ee5SMike Stump   CGF.FinishFunction();
1164ee2a5ee5SMike Stump 
1165ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1166ee2a5ee5SMike Stump }
1167ee2a5ee5SMike Stump 
1168fbe25dd1SMike Stump llvm::Constant *
1169fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1170fbe25dd1SMike Stump                                                   int flag) {
1171ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1172ee2a5ee5SMike Stump 
1173ee2a5ee5SMike Stump   FunctionArgList Args;
1174ee2a5ee5SMike Stump   // FIXME: This leaks
1175ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
11767fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
11777fe9cc1dSMike Stump                               SourceLocation(), 0,
1178ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1179ee2a5ee5SMike Stump 
1180ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1181ee2a5ee5SMike Stump 
1182ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1183c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1184ee2a5ee5SMike Stump 
1185ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1186ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1187ee2a5ee5SMike Stump 
1188cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1189cbc2bcafSMike Stump   // internal linkage.
1190ee2a5ee5SMike Stump   llvm::Function *Fn =
1191ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1192d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_dispose_",
1193ee2a5ee5SMike Stump                            &CGM.getModule());
1194ee2a5ee5SMike Stump 
1195ee2a5ee5SMike Stump   IdentifierInfo *II
1196ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1197ee2a5ee5SMike Stump 
1198ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1199ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
120060ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1201c4df4076SDouglas Gregor                                           FunctionDecl::Static,
1202c4df4076SDouglas Gregor                                           FunctionDecl::None,
1203c4df4076SDouglas Gregor                                           false, true);
1204ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1205fbe25dd1SMike Stump 
1206fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
12079793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
12083b65ac26SMike Stump   V = Builder.CreateLoad(V);
1209fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
12109793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
12113b65ac26SMike Stump   V = Builder.CreateLoad(V);
1212fbe25dd1SMike Stump 
1213fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1214fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1215ee2a5ee5SMike Stump   CGF.FinishFunction();
1216ee2a5ee5SMike Stump 
1217ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1218ee2a5ee5SMike Stump }
1219ee2a5ee5SMike Stump 
1220f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1221e08ea787SChris Lattner                                                     int Flag, unsigned Align) {
1222e08ea787SChris Lattner   // All alignments below that of pointer alignment collapse down to just
1223cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1224cbc2bcafSMike Stump   // with.
1225cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1226e08ea787SChris Lattner 
1227cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1228cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1229cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1230e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1231e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.AssignCache[Kind];
1232cbc2bcafSMike Stump   if (Entry)
1233cbc2bcafSMike Stump     return Entry;
1234e08ea787SChris Lattner   return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
1235ee2a5ee5SMike Stump }
1236ee2a5ee5SMike Stump 
1237fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1238e08ea787SChris Lattner                                                        int Flag,
1239cbc2bcafSMike Stump                                                        unsigned Align) {
1240cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1241cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1242cbc2bcafSMike Stump   // with.
1243cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1244e08ea787SChris Lattner 
1245cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1246cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1247cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1248e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1249e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.DestroyCache[Kind];
1250cbc2bcafSMike Stump   if (Entry)
1251cbc2bcafSMike Stump     return Entry;
1252e08ea787SChris Lattner   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
1253ee2a5ee5SMike Stump }
1254ee2a5ee5SMike Stump 
1255fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1256900546d2SDaniel Dunbar   llvm::Value *F = CGM.getBlockObjectDispose();
1257fbe25dd1SMike Stump   llvm::Value *N;
1258626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
12595e016ae9SChris Lattner   N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
1260626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1261626aecc4SMike Stump }
12624446dcf0SMike Stump 
12634446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1264aeb0ffd5SMike Stump 
1265aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1266aeb0ffd5SMike Stump                              CGBuilderTy &B)
12675e016ae9SChris Lattner   : CGM(cgm), VMContext(cgm.getLLVMContext()), CGF(cgf), Builder(B) {
126841a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
126941a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1270aeb0ffd5SMike Stump 
1271aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1272aeb0ffd5SMike Stump }
1273