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 
11495435674SMike Stump llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
11546813bbfSChris Lattner   if (NSConcreteGlobalBlock == 0)
11646813bbfSChris Lattner     NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
11746813bbfSChris Lattner                                                       "_NSConcreteGlobalBlock");
118971f9b66SMike Stump   return NSConcreteGlobalBlock;
119971f9b66SMike Stump }
120971f9b66SMike Stump 
12195435674SMike Stump llvm::Constant *BlockModule::getNSConcreteStackBlock() {
12246813bbfSChris Lattner   if (NSConcreteStackBlock == 0)
12346813bbfSChris Lattner     NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
12446813bbfSChris Lattner                                                      "_NSConcreteStackBlock");
1257ab278dbSMike Stump   return NSConcreteStackBlock;
1267ab278dbSMike Stump }
1277ab278dbSMike Stump 
1289d42f0f1SJohn McCall static void CollectBlockDeclRefInfo(const Stmt *S, CGBlockInfo &Info) {
129ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
130ed5e69feSAnders Carlsson        I != E; ++I)
131dd942713SDaniel Dunbar     if (*I)
1329d42f0f1SJohn McCall       CollectBlockDeclRefInfo(*I, Info);
133ed5e69feSAnders Carlsson 
1347fe9cc1dSMike Stump   // We want to ensure we walk down into block literals so we can find
1357fe9cc1dSMike Stump   // all nested BlockDeclRefExprs.
136066b6166SMike Stump   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
1379d42f0f1SJohn McCall     Info.InnerBlocks.insert(BE->getBlockDecl());
1389d42f0f1SJohn McCall     CollectBlockDeclRefInfo(BE->getBody(), Info);
139066b6166SMike Stump   }
1407fe9cc1dSMike Stump 
1419d42f0f1SJohn McCall   else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1429d42f0f1SJohn McCall     const ValueDecl *D = BDRE->getDecl();
143ed5e69feSAnders Carlsson     // FIXME: Handle enums.
1449d42f0f1SJohn McCall     if (isa<FunctionDecl>(D))
145ed5e69feSAnders Carlsson       return;
146ed5e69feSAnders Carlsson 
1479d42f0f1SJohn McCall     if (isa<ImplicitParamDecl>(D) &&
1489d42f0f1SJohn McCall         isa<ObjCMethodDecl>(D->getDeclContext()) &&
1499d42f0f1SJohn McCall         cast<ObjCMethodDecl>(D->getDeclContext())->getSelfDecl() == D) {
1509d42f0f1SJohn McCall       Info.NeedsObjCSelf = true;
1519d42f0f1SJohn McCall       return;
1529d42f0f1SJohn McCall     }
1539d42f0f1SJohn McCall 
154066b6166SMike Stump     // Only Decls that escape are added.
1559d42f0f1SJohn McCall     if (!Info.InnerBlocks.count(D->getDeclContext()))
156066b6166SMike Stump       Info.DeclRefs.push_back(BDRE);
157ed5e69feSAnders Carlsson   }
15887fe5d56SJohn McCall 
1599d42f0f1SJohn McCall   // Make sure to capture implicit 'self' references due to super calls.
1607ea01c3fSChandler Carruth   else if (const ObjCMessageExpr *E = dyn_cast<ObjCMessageExpr>(S)) {
1619d42f0f1SJohn McCall     if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
1629d42f0f1SJohn McCall         E->getReceiverKind() == ObjCMessageExpr::SuperInstance)
1639d42f0f1SJohn McCall       Info.NeedsObjCSelf = true;
1647ea01c3fSChandler Carruth   }
1659d42f0f1SJohn McCall 
1669d42f0f1SJohn McCall   // Getter/setter uses may also cause implicit super references,
1679d42f0f1SJohn McCall   // which we can check for with:
1689d42f0f1SJohn McCall   else if (isa<ObjCSuperExpr>(S))
1699d42f0f1SJohn McCall     Info.NeedsObjCSelf = true;
1709d42f0f1SJohn McCall 
1719d42f0f1SJohn McCall   else if (isa<CXXThisExpr>(S))
17287fe5d56SJohn McCall     Info.CXXThisRef = cast<CXXThisExpr>(S);
173ed5e69feSAnders Carlsson }
174ed5e69feSAnders Carlsson 
1759d42f0f1SJohn McCall /// CanBlockBeGlobal - Given a CGBlockInfo struct, determines if a block can be
1762d33d630SMike Stump /// declared as a global variable instead of on the stack.
1779d42f0f1SJohn McCall static bool CanBlockBeGlobal(const CGBlockInfo &Info) {
1787fe9cc1dSMike Stump   return Info.DeclRefs.empty();
1797fe9cc1dSMike Stump }
1807fe9cc1dSMike Stump 
1817fe9cc1dSMike Stump /// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
1827fe9cc1dSMike Stump /// ensure we can generate the debug information for the parameter for the block
1837fe9cc1dSMike Stump /// invoke function.
1849d42f0f1SJohn McCall static void AllocateAllBlockDeclRefs(CodeGenFunction &CGF, CGBlockInfo &Info) {
18587fe5d56SJohn McCall   if (Info.CXXThisRef)
1869d42f0f1SJohn McCall     CGF.AllocateBlockCXXThisPointer(Info.CXXThisRef);
1877fe9cc1dSMike Stump 
1887fe9cc1dSMike Stump   for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
1899d42f0f1SJohn McCall     CGF.AllocateBlockDecl(Info.DeclRefs[i]);
1909d42f0f1SJohn McCall 
1919d42f0f1SJohn McCall   if (Info.NeedsObjCSelf) {
1929d42f0f1SJohn McCall     ValueDecl *Self = cast<ObjCMethodDecl>(CGF.CurFuncDecl)->getSelfDecl();
1939d42f0f1SJohn McCall     BlockDeclRefExpr *BDRE =
1949d42f0f1SJohn McCall       new (CGF.getContext()) BlockDeclRefExpr(Self, Self->getType(),
1959d42f0f1SJohn McCall                                               SourceLocation(), false);
1969d42f0f1SJohn McCall     Info.DeclRefs.push_back(BDRE);
1979d42f0f1SJohn McCall     CGF.AllocateBlockDecl(BDRE);
1989d42f0f1SJohn McCall   }
199ed5e69feSAnders Carlsson }
200ed5e69feSAnders Carlsson 
2012d33d630SMike Stump // FIXME: Push most into CGM, passing down a few bits, like current function
2022d33d630SMike Stump // name.
203b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
204ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
2059d42f0f1SJohn McCall   CGBlockInfo Info(Name.c_str());
2069d42f0f1SJohn McCall   Info.InnerBlocks.insert(BE->getBlockDecl());
2079d42f0f1SJohn McCall   CollectBlockDeclRefInfo(BE->getBody(), Info);
208ed5e69feSAnders Carlsson 
209ed5e69feSAnders Carlsson   // Check if the block can be global.
2102d33d630SMike Stump   // FIXME: This test doesn't work for nested blocks yet.  Longer term, I'd like
2112d33d630SMike Stump   // to just have one code path.  We should move this function into CGM and pass
2122d33d630SMike Stump   // CGF, then we can just check to see if CGF is 0.
21397d01d50SMike Stump   if (0 && CanBlockBeGlobal(Info))
214ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
21585284bacSMike Stump 
216950a9518SDavid Chisnall   size_t BlockFields = 5;
217950a9518SDavid Chisnall 
218950a9518SDavid Chisnall   std::vector<llvm::Constant*> Elts(BlockFields);
219950a9518SDavid Chisnall 
22085284bacSMike Stump   llvm::Constant *C;
221b750d928SMike Stump   llvm::Value *V;
22285284bacSMike Stump 
22385284bacSMike Stump   {
22485284bacSMike Stump     // C = BuildBlockStructInitlist();
225f27ab71dSBlaine Garst     unsigned int flags = BLOCK_HAS_SIGNATURE;
226950a9518SDavid Chisnall 
2274446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
2284446dcf0SMike Stump     // block literal.
2294446dcf0SMike Stump     // __invoke
2304446dcf0SMike Stump     llvm::Function *Fn
231d2a3e617SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
2329d42f0f1SJohn McCall                                                    LocalDeclMap);
2339d42f0f1SJohn McCall     BlockHasCopyDispose |= Info.BlockHasCopyDispose;
2344446dcf0SMike Stump     Elts[3] = Fn;
2354446dcf0SMike Stump 
23618bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
23718bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
2389d42f0f1SJohn McCall     if (Info.BlockHasCopyDispose)
23985284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
24085284bacSMike Stump 
241499ae7ecSMike Stump     // __isa
2427ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
243ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
2444446dcf0SMike Stump     Elts[0] = C;
24585284bacSMike Stump 
24685284bacSMike Stump     // __flags
247f27ab71dSBlaine Garst     {
248f27ab71dSBlaine Garst       QualType BPT = BE->getType();
249f27ab71dSBlaine Garst       const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
250f27ab71dSBlaine Garst       QualType ResultType = ftype->getResultType();
251f27ab71dSBlaine Garst 
252f27ab71dSBlaine Garst       CallArgList Args;
253f27ab71dSBlaine Garst       CodeGenTypes &Types = CGM.getTypes();
254f27ab71dSBlaine Garst       const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
255c50c27ccSRafael Espindola                                                        FunctionType::ExtInfo());
256f27ab71dSBlaine Garst       if (CGM.ReturnTypeUsesSret(FnInfo))
257f27ab71dSBlaine Garst         flags |= BLOCK_USE_STRET;
258f27ab71dSBlaine Garst     }
25985284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
26085284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
261b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
2624446dcf0SMike Stump     Elts[1] = C;
26385284bacSMike Stump 
26485284bacSMike Stump     // __reserved
265b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
2664446dcf0SMike Stump     Elts[2] = C;
26785284bacSMike Stump 
2689d42f0f1SJohn McCall     if (Info.BlockLayout.empty()) {
269d6ef62f0SMike Stump       // __descriptor
2709d42f0f1SJohn McCall       Elts[4] = BuildDescriptorBlockDecl(BE, Info.BlockHasCopyDispose,
2719d42f0f1SJohn McCall                                          Info.BlockSize, 0, 0);
272d6ef62f0SMike Stump 
2733a139f37SMike Stump       // Optimize to being a global block.
2743a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
275f27ab71dSBlaine Garst 
276b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2773a139f37SMike Stump 
27841eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
27985284bacSMike Stump 
280c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
281d6b28fc6SBenjamin Kramer                                    llvm::GlobalValue::InternalLinkage, C,
282d6b28fc6SBenjamin Kramer                                    "__block_holder_tmp_" +
283d6b28fc6SBenjamin Kramer                                    llvm::Twine(CGM.getGlobalUniqueCount()));
2845d2534adSMike Stump       QualType BPT = BE->getType();
285ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
28685284bacSMike Stump       return C;
28785284bacSMike Stump     }
28885284bacSMike Stump 
2899d42f0f1SJohn McCall     std::vector<const llvm::Type *> Types(BlockFields+Info.BlockLayout.size());
290aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
291b750d928SMike Stump       Types[i] = Elts[i]->getType();
292aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
29385284bacSMike Stump 
2949d42f0f1SJohn McCall     for (unsigned i = 0, n = Info.BlockLayout.size(); i != n; ++i) {
2959d42f0f1SJohn McCall       const Expr *E = Info.BlockLayout[i];
2961db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2971db7d04bSMike Stump       QualType Ty = E->getType();
29897d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
299d1b378e0SFariborz Jahanian         Types[i+BlockFields] =
300d1b378e0SFariborz Jahanian           llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
301d1b378e0SFariborz Jahanian       } else if (BDRE && BDRE->getDecl()->getType()->isReferenceType()) {
302d1b378e0SFariborz Jahanian          Types[i+BlockFields] = llvm::PointerType::get(ConvertType(Ty), 0);
30397d01d50SMike Stump       } else
304950a9518SDavid Chisnall         Types[i+BlockFields] = ConvertType(Ty);
3051db7d04bSMike Stump     }
306b750d928SMike Stump 
307758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
308b750d928SMike Stump 
309b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
3109d42f0f1SJohn McCall     A->setAlignment(Info.BlockAlign.getQuantity());
311b750d928SMike Stump     V = A;
312b750d928SMike Stump 
31387fe5d56SJohn McCall     // Build layout / cleanup information for all the data entries in the
31487fe5d56SJohn McCall     // layout, and write the enclosing fields into the type.
3159d42f0f1SJohn McCall     std::vector<HelperInfo> NoteForHelper(Info.BlockLayout.size());
31687fe5d56SJohn McCall     unsigned NumHelpers = 0;
317aeb0ffd5SMike Stump 
318aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
319b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
320b750d928SMike Stump 
3219d42f0f1SJohn McCall     for (unsigned i=0; i < Info.BlockLayout.size(); ++i) {
3229d42f0f1SJohn McCall       const Expr *E = Info.BlockLayout[i];
323b750d928SMike Stump 
3241db7d04bSMike Stump       // Skip padding.
32587fe5d56SJohn McCall       if (isa<DeclRefExpr>(E)) continue;
3261db7d04bSMike Stump 
327950a9518SDavid Chisnall       llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
32887fe5d56SJohn McCall       HelperInfo &Note = NoteForHelper[NumHelpers++];
32987fe5d56SJohn McCall 
33087fe5d56SJohn McCall       Note.index = i+5;
33187fe5d56SJohn McCall 
33287fe5d56SJohn McCall       if (isa<CXXThisExpr>(E)) {
33387fe5d56SJohn McCall         Note.RequiresCopying = false;
33487fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_OBJECT;
33587fe5d56SJohn McCall 
33687fe5d56SJohn McCall         Builder.CreateStore(LoadCXXThis(), Addr);
33787fe5d56SJohn McCall         continue;
33887fe5d56SJohn McCall       }
33987fe5d56SJohn McCall 
34087fe5d56SJohn McCall       const BlockDeclRefExpr *BDRE = cast<BlockDeclRefExpr>(E);
34187fe5d56SJohn McCall       const ValueDecl *VD = BDRE->getDecl();
34287fe5d56SJohn McCall       QualType T = VD->getType();
34387fe5d56SJohn McCall 
34487fe5d56SJohn McCall       Note.RequiresCopying = BlockRequiresCopying(T);
34587fe5d56SJohn McCall 
34687fe5d56SJohn McCall       if (BDRE->isByRef()) {
34787fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_BYREF;
34887fe5d56SJohn McCall         if (T.isObjCGCWeak())
34987fe5d56SJohn McCall           Note.flag |= BLOCK_FIELD_IS_WEAK;
35087fe5d56SJohn McCall       } else if (T->isBlockPointerType()) {
35187fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_BLOCK;
35287fe5d56SJohn McCall       } else {
35387fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_OBJECT;
35487fe5d56SJohn McCall       }
355aeb0ffd5SMike Stump 
3561db7d04bSMike Stump       if (LocalDeclMap[VD]) {
35797d01d50SMike Stump         if (BDRE->isByRef()) {
35897d01d50SMike Stump           llvm::Value *Loc = LocalDeclMap[VD];
35997d01d50SMike Stump           Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
360c76493a6SDaniel Dunbar           Loc = Builder.CreateLoad(Loc);
36197d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
36297d01d50SMike Stump           continue;
36387fe5d56SJohn McCall         } else {
36487fe5d56SJohn McCall           E = new (getContext()) DeclRefExpr(const_cast<ValueDecl*>(VD),
365d1b378e0SFariborz Jahanian                                             VD->getType().getNonReferenceType(),
366d1b378e0SFariborz Jahanian                                             SourceLocation());
367*64176c2cSFariborz Jahanian           if (getContext().getLangOptions().CPlusPlus) {
368*64176c2cSFariborz Jahanian             if (VD->getType()->isReferenceType()) {
369d1b378e0SFariborz Jahanian               E = new (getContext())
370d1b378e0SFariborz Jahanian                 UnaryOperator(const_cast<Expr*>(E), UnaryOperator::AddrOf,
371d1b378e0SFariborz Jahanian                               getContext().getPointerType(E->getType()),
372ed6c7440SDouglas Gregor                               SourceLocation());
3731db7d04bSMike Stump             }
374*64176c2cSFariborz Jahanian             else {
375*64176c2cSFariborz Jahanian               QualType T = E->getType();
376*64176c2cSFariborz Jahanian               if (const RecordType *RT = T->getAs<RecordType>()) {
377*64176c2cSFariborz Jahanian                 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
378*64176c2cSFariborz Jahanian                 if (!Record->hasTrivialCopyConstructor()) {
379*64176c2cSFariborz Jahanian                   CXXConstructorDecl *D = Record->getCopyConstructor(getContext(),
380*64176c2cSFariborz Jahanian                                                                      0);
381*64176c2cSFariborz Jahanian                   Expr *Arg = const_cast<Expr*>(E);
382*64176c2cSFariborz Jahanian                   E = CXXConstructExpr::Create(getContext(), T, D->getLocation(),
383*64176c2cSFariborz Jahanian                                                D, false, &Arg, 1, false,
384*64176c2cSFariborz Jahanian                                                CXXConstructExpr::CK_Complete);
385*64176c2cSFariborz Jahanian                 }
386*64176c2cSFariborz Jahanian               }
387*64176c2cSFariborz Jahanian             }
388*64176c2cSFariborz Jahanian           }
389*64176c2cSFariborz Jahanian         }
39087fe5d56SJohn McCall       }
39187fe5d56SJohn McCall 
39297d01d50SMike Stump       if (BDRE->isByRef()) {
3931db7d04bSMike Stump         E = new (getContext())
39487fe5d56SJohn McCall           UnaryOperator(const_cast<Expr*>(E), UnaryOperator::AddrOf,
3951db7d04bSMike Stump                         getContext().getPointerType(E->getType()),
3961db7d04bSMike Stump                         SourceLocation());
39797d01d50SMike Stump       }
3981db7d04bSMike Stump 
3991db7d04bSMike Stump       RValue r = EmitAnyExpr(E, Addr, false);
40097d01d50SMike Stump       if (r.isScalar()) {
40197d01d50SMike Stump         llvm::Value *Loc = r.getScalarVal();
402950a9518SDavid Chisnall         const llvm::Type *Ty = Types[i+BlockFields];
40397d01d50SMike Stump         if  (BDRE->isByRef()) {
4042d33d630SMike Stump           // E is now the address of the value field, instead, we want the
4052d33d630SMike Stump           // address of the actual ByRef struct.  We optimize this slightly
4062d33d630SMike Stump           // compared to gcc by not grabbing the forwarding slot as this must
4072d33d630SMike Stump           // be done during Block_copy for us, and we can postpone the work
4082d33d630SMike Stump           // until then.
40940775003SKen Dyck           CharUnits offset = BlockDecls[BDRE->getDecl()];
4102d33d630SMike Stump 
4112d33d630SMike Stump           llvm::Value *BlockLiteral = LoadBlockStruct();
4122d33d630SMike Stump 
4132d33d630SMike Stump           Loc = Builder.CreateGEP(BlockLiteral,
41441a75027SOwen Anderson                      llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
41540775003SKen Dyck                                                          offset.getQuantity()),
4162d33d630SMike Stump                                   "block.literal");
4179793f0e4SOwen Anderson           Ty = llvm::PointerType::get(Ty, 0);
41897d01d50SMike Stump           Loc = Builder.CreateBitCast(Loc, Ty);
419c76493a6SDaniel Dunbar           Loc = Builder.CreateLoad(Loc);
4202d33d630SMike Stump           // Loc = Builder.CreateBitCast(Loc, Ty);
42197d01d50SMike Stump         }
42297d01d50SMike Stump         Builder.CreateStore(Loc, Addr);
42397d01d50SMike Stump       } else if (r.isComplex())
424b750d928SMike Stump         // FIXME: implement
425b750d928SMike Stump         ErrorUnsupported(BE, "complex in block literal");
426b750d928SMike Stump       else if (r.isAggregate())
427b750d928SMike Stump         ; // Already created into the destination
428b750d928SMike Stump       else
429b750d928SMike Stump         assert (0 && "bad block variable");
430b750d928SMike Stump       // FIXME: Ensure that the offset created by the backend for
431b750d928SMike Stump       // the struct matches the previously computed offset in BlockDecls.
432b750d928SMike Stump     }
43387fe5d56SJohn McCall     NoteForHelper.resize(NumHelpers);
434d6ef62f0SMike Stump 
435d6ef62f0SMike Stump     // __descriptor
436fc83aa04SBlaine Garst     llvm::Value *Descriptor = BuildDescriptorBlockDecl(BE,
4379d42f0f1SJohn McCall                                                        Info.BlockHasCopyDispose,
4389d42f0f1SJohn McCall                                                        Info.BlockSize, Ty,
439aeb0ffd5SMike Stump                                                        &NoteForHelper);
440aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
441aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
442b750d928SMike Stump   }
443b750d928SMike Stump 
444b750d928SMike Stump   QualType BPT = BE->getType();
445989908fbSFariborz Jahanian   V = Builder.CreateBitCast(V, ConvertType(BPT));
446989908fbSFariborz Jahanian   // See if this is a __weak block variable and the must call objc_read_weak
447989908fbSFariborz Jahanian   // on it.
448989908fbSFariborz Jahanian   const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
449989908fbSFariborz Jahanian   QualType RES = ftype->getResultType();
450989908fbSFariborz Jahanian   if (RES.isObjCGCWeak()) {
451989908fbSFariborz Jahanian     // Must cast argument to id*
452989908fbSFariborz Jahanian     const llvm::Type *ObjectPtrTy =
453989908fbSFariborz Jahanian       ConvertType(CGM.getContext().getObjCIdType());
454989908fbSFariborz Jahanian     const llvm::Type *PtrObjectPtrTy =
455989908fbSFariborz Jahanian       llvm::PointerType::getUnqual(ObjectPtrTy);
456989908fbSFariborz Jahanian     V = Builder.CreateBitCast(V, PtrObjectPtrTy);
457989908fbSFariborz Jahanian     V =  CGM.getObjCRuntime().EmitObjCWeakRead(*this, V);
458989908fbSFariborz Jahanian   }
459989908fbSFariborz Jahanian   return V;
460b750d928SMike Stump }
46185284bacSMike Stump 
46285284bacSMike Stump 
46395435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
464650c932dSMike Stump   if (BlockDescriptorType)
465650c932dSMike Stump     return BlockDescriptorType;
4662437cbfaSAnders Carlsson 
4672437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
468650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
4692437cbfaSAnders Carlsson 
4702437cbfaSAnders Carlsson   // struct __block_descriptor {
4712437cbfaSAnders Carlsson   //   unsigned long reserved;
4722437cbfaSAnders Carlsson   //   unsigned long block_size;
473fc83aa04SBlaine Garst   //
474fc83aa04SBlaine Garst   //   // later, the following will be added
475fc83aa04SBlaine Garst   //
476fc83aa04SBlaine Garst   //   struct {
477fc83aa04SBlaine Garst   //     void (*copyHelper)();
478fc83aa04SBlaine Garst   //     void (*copyHelper)();
479fc83aa04SBlaine Garst   //   } helpers;                // !!! optional
480fc83aa04SBlaine Garst   //
481fc83aa04SBlaine Garst   //   const char *signature;   // the block signature
482fc83aa04SBlaine Garst   //   const char *layout;      // reserved
4832437cbfaSAnders Carlsson   // };
484758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
485758428f4SOwen Anderson                                               UnsignedLongTy,
4862437cbfaSAnders Carlsson                                               UnsignedLongTy,
4872437cbfaSAnders Carlsson                                               NULL);
4882437cbfaSAnders Carlsson 
489650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
490650c932dSMike Stump                           BlockDescriptorType);
4912437cbfaSAnders Carlsson 
492650c932dSMike Stump   return BlockDescriptorType;
4932437cbfaSAnders Carlsson }
4942437cbfaSAnders Carlsson 
49595435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
496005c9a62SMike Stump   if (GenericBlockLiteralType)
497005c9a62SMike Stump     return GenericBlockLiteralType;
4982437cbfaSAnders Carlsson 
4992437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
5009793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
5012437cbfaSAnders Carlsson 
50292bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
50392bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
50492bbd6d4SMike Stump 
5052437cbfaSAnders Carlsson   // struct __block_literal_generic {
5065d2534adSMike Stump   //   void *__isa;
5075d2534adSMike Stump   //   int __flags;
5085d2534adSMike Stump   //   int __reserved;
5095d2534adSMike Stump   //   void (*__invoke)(void *);
5105d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
5112437cbfaSAnders Carlsson   // };
512758428f4SOwen Anderson   GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
513758428f4SOwen Anderson                                                   PtrToInt8Ty,
51492bbd6d4SMike Stump                                                   IntTy,
51592bbd6d4SMike Stump                                                   IntTy,
516626aecc4SMike Stump                                                   PtrToInt8Ty,
5172437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
5182437cbfaSAnders Carlsson                                                   NULL);
5192437cbfaSAnders Carlsson 
520005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
521005c9a62SMike Stump                           GenericBlockLiteralType);
5222437cbfaSAnders Carlsson 
523005c9a62SMike Stump   return GenericBlockLiteralType;
5242437cbfaSAnders Carlsson }
5252437cbfaSAnders Carlsson 
5265d2534adSMike Stump 
527bfb3671bSAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
528bfb3671bSAnders Carlsson                                           ReturnValueSlot ReturnValue) {
5292437cbfaSAnders Carlsson   const BlockPointerType *BPT =
530c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
5312437cbfaSAnders Carlsson 
5322437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
5332437cbfaSAnders Carlsson 
5342437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
5352437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
5369793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
5372437cbfaSAnders Carlsson 
5382437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
5392437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
5402437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
5412437cbfaSAnders Carlsson 
5422437cbfaSAnders Carlsson   // Get the function pointer from the literal.
5432437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
5442437cbfaSAnders Carlsson 
5452437cbfaSAnders Carlsson   BlockLiteral =
5462437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
547abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
5482437cbfaSAnders Carlsson                           "tmp");
5492437cbfaSAnders Carlsson 
5502437cbfaSAnders Carlsson   // Add the block literal.
5512437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
5522437cbfaSAnders Carlsson   CallArgList Args;
5532437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
5542437cbfaSAnders Carlsson 
555479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
556479e6fc7SAnders Carlsson 
5572437cbfaSAnders Carlsson   // And the rest of the arguments.
5589dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
559479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
5602437cbfaSAnders Carlsson 
5615f50c651SAnders Carlsson   // Load the function.
562c76493a6SDaniel Dunbar   llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
5635f50c651SAnders Carlsson 
564ab26cfa5SJohn McCall   const FunctionType *FuncTy = FnType->getAs<FunctionType>();
565ab26cfa5SJohn McCall   QualType ResultType = FuncTy->getResultType();
566a60cbcdfSAnders Carlsson 
567a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
568c50c27ccSRafael Espindola     CGM.getTypes().getFunctionInfo(ResultType, Args,
569c50c27ccSRafael Espindola                                    FuncTy->getExtInfo());
5705f50c651SAnders Carlsson 
5715f50c651SAnders Carlsson   // Cast the function pointer to the right type.
5725f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
573a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
5745f50c651SAnders Carlsson 
5759793f0e4SOwen Anderson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
5765f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
5775f50c651SAnders Carlsson 
5782437cbfaSAnders Carlsson   // And call the block.
579bfb3671bSAnders Carlsson   return EmitCall(FnInfo, Func, ReturnValue, Args);
5802437cbfaSAnders Carlsson }
5816a60fa24SAnders Carlsson 
58287fe5d56SJohn McCall void CodeGenFunction::AllocateBlockCXXThisPointer(const CXXThisExpr *E) {
58387fe5d56SJohn McCall   assert(BlockCXXThisOffset.isZero() && "already computed 'this' pointer");
58487fe5d56SJohn McCall 
58587fe5d56SJohn McCall   // Figure out what the offset is.
58687fe5d56SJohn McCall   QualType T = E->getType();
58787fe5d56SJohn McCall   std::pair<CharUnits,CharUnits> TypeInfo = getContext().getTypeInfoInChars(T);
58887fe5d56SJohn McCall   CharUnits Offset = getBlockOffset(TypeInfo.first, TypeInfo.second);
58987fe5d56SJohn McCall 
59087fe5d56SJohn McCall   BlockCXXThisOffset = Offset;
59187fe5d56SJohn McCall   BlockLayout.push_back(E);
59287fe5d56SJohn McCall }
59387fe5d56SJohn McCall 
59487fe5d56SJohn McCall void CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
5950168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
59687fe5d56SJohn McCall   CharUnits &Offset = BlockDecls[VD];
5970168f4b2SAnders Carlsson 
59897d01d50SMike Stump   // See if we have already allocated an offset for this variable.
59987fe5d56SJohn McCall   if (!Offset.isZero())
60087fe5d56SJohn McCall     return;
6017fe9cc1dSMike Stump 
6024446dcf0SMike Stump   // Don't run the expensive check, unless we have to.
603e1b19ba0SMike Stump   if (!BlockHasCopyDispose)
604e1b19ba0SMike Stump     if (E->isByRef()
605e1b19ba0SMike Stump         || BlockRequiresCopying(E->getType()))
6064446dcf0SMike Stump       BlockHasCopyDispose = true;
6077fe9cc1dSMike Stump 
60887fe5d56SJohn McCall   const ValueDecl *D = cast<ValueDecl>(E->getDecl());
6097fe9cc1dSMike Stump 
61087fe5d56SJohn McCall   CharUnits Size;
61187fe5d56SJohn McCall   CharUnits Align;
61287fe5d56SJohn McCall 
61387fe5d56SJohn McCall   if (E->isByRef()) {
61487fe5d56SJohn McCall     llvm::tie(Size,Align) =
61587fe5d56SJohn McCall       getContext().getTypeInfoInChars(getContext().VoidPtrTy);
61687fe5d56SJohn McCall   } else {
61787fe5d56SJohn McCall     Size = getContext().getTypeSizeInChars(D->getType());
61887fe5d56SJohn McCall     Align = getContext().getDeclAlign(D);
61987fe5d56SJohn McCall   }
62087fe5d56SJohn McCall 
62187fe5d56SJohn McCall   Offset = getBlockOffset(Size, Align);
62287fe5d56SJohn McCall   BlockLayout.push_back(E);
62397d01d50SMike Stump }
62497d01d50SMike Stump 
6259d42f0f1SJohn McCall llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const ValueDecl *VD,
6269d42f0f1SJohn McCall                                                  bool IsByRef) {
627*64176c2cSFariborz Jahanian   llvm::Value *&VE = BlockDeclsValue[VD];
628*64176c2cSFariborz Jahanian   if (VE)
629*64176c2cSFariborz Jahanian     return VE;
630*64176c2cSFariborz Jahanian 
63187fe5d56SJohn McCall   CharUnits offset = BlockDecls[VD];
63287fe5d56SJohn McCall   assert(!offset.isZero() && "getting address of unallocated decl");
6337fe9cc1dSMike Stump 
63497d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
63597d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
63641a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
63740775003SKen Dyck                                                          offset.getQuantity()),
6382d33d630SMike Stump                                      "block.literal");
6399d42f0f1SJohn McCall   if (IsByRef) {
64097d01d50SMike Stump     const llvm::Type *PtrStructTy
6410168f4b2SAnders Carlsson       = llvm::PointerType::get(BuildByRefType(VD), 0);
642efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
643efd7caa8SMike Stump     BlockHasCopyDispose = true;
6440168f4b2SAnders Carlsson 
6450168f4b2SAnders Carlsson     const llvm::Type *Ty = PtrStructTy;
6469793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
64797d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
648c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
64997d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
650c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
65197d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
6520168f4b2SAnders Carlsson     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
6530168f4b2SAnders Carlsson                                 VD->getNameAsString());
654eeb23379SFariborz Jahanian     if (VD->getType()->isReferenceType())
655eeb23379SFariborz Jahanian       V = Builder.CreateLoad(V);
65697d01d50SMike Stump   } else {
6570168f4b2SAnders Carlsson     const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
6589793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
65997d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
660d1b378e0SFariborz Jahanian     if (VD->getType()->isReferenceType())
661*64176c2cSFariborz Jahanian       V = Builder.CreateLoad(V, "ref.tmp");
66297d01d50SMike Stump   }
663*64176c2cSFariborz Jahanian   VE = V;
66497d01d50SMike Stump   return V;
66597d01d50SMike Stump }
66697d01d50SMike Stump 
6672d5a2878SMike Stump llvm::Constant *
6686c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
6696a60fa24SAnders Carlsson   // Generate the block descriptor.
6706a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
67192bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
67292bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
6736a60fa24SAnders Carlsson 
674fc83aa04SBlaine Garst   llvm::Constant *DescriptorFields[4];
6756a60fa24SAnders Carlsson 
6766a60fa24SAnders Carlsson   // Reserved
6770b75f23bSOwen Anderson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
6786a60fa24SAnders Carlsson 
6796a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
6806a60fa24SAnders Carlsson   // block literal struct.
68198ca7943SKen Dyck   CharUnits BlockLiteralSize =
68298ca7943SKen Dyck     CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
683170229f6SOwen Anderson   DescriptorFields[1] =
68440775003SKen Dyck     llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
6856a60fa24SAnders Carlsson 
686fc83aa04SBlaine Garst   // signature.  non-optional ObjC-style method descriptor @encode sequence
687fc83aa04SBlaine Garst   std::string BlockTypeEncoding;
688fc83aa04SBlaine Garst   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
689fc83aa04SBlaine Garst 
690fc83aa04SBlaine Garst   DescriptorFields[2] = llvm::ConstantExpr::getBitCast(
691fc83aa04SBlaine Garst           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
692fc83aa04SBlaine Garst 
693fc83aa04SBlaine Garst   // layout
694fc83aa04SBlaine Garst   DescriptorFields[3] =
695fc83aa04SBlaine Garst     llvm::ConstantInt::get(UnsignedLongTy,0);
696fc83aa04SBlaine Garst 
697fc83aa04SBlaine Garst   // build the structure from the 4 elements
6986a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
699fc83aa04SBlaine Garst     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false);
7006a60fa24SAnders Carlsson 
7016a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
702c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
7036a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
704c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
7056a60fa24SAnders Carlsson 
706950a9518SDavid Chisnall   int FieldCount = 5;
7076a60fa24SAnders Carlsson   // Generate the constants for the block literal.
708950a9518SDavid Chisnall 
709950a9518SDavid Chisnall   std::vector<llvm::Constant*> LiteralFields(FieldCount);
7106a60fa24SAnders Carlsson 
7119d42f0f1SJohn McCall   CGBlockInfo Info(n);
7125469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
713cb2fbcb0SMike Stump   llvm::Function *Fn
7149d42f0f1SJohn McCall     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap);
7159d42f0f1SJohn McCall   assert(Info.BlockSize == BlockLiteralSize
716cb2fbcb0SMike Stump          && "no imports allowed for global block");
7176a60fa24SAnders Carlsson 
7186a60fa24SAnders Carlsson   // isa
719971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
7206a60fa24SAnders Carlsson 
7216a60fa24SAnders Carlsson   // Flags
722fc83aa04SBlaine Garst   LiteralFields[1] =
723f27ab71dSBlaine Garst     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
7246a60fa24SAnders Carlsson 
7256a60fa24SAnders Carlsson   // Reserved
7260b75f23bSOwen Anderson   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
7276a60fa24SAnders Carlsson 
7286a60fa24SAnders Carlsson   // Function
7296a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
7306a60fa24SAnders Carlsson 
7316a60fa24SAnders Carlsson   // Descriptor
7326a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
7336a60fa24SAnders Carlsson 
7346a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
735950a9518SDavid Chisnall     llvm::ConstantStruct::get(VMContext, LiteralFields, false);
7366a60fa24SAnders Carlsson 
7376a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
738c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
7396a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
740c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
7416a60fa24SAnders Carlsson 
7426a60fa24SAnders Carlsson   return BlockLiteral;
7436a60fa24SAnders Carlsson }
7446a60fa24SAnders Carlsson 
745cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
74638382028SMike Stump   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
74738382028SMike Stump                                       "self");
74838382028SMike Stump   // For now, we codegen based upon byte offsets.
74938382028SMike Stump   return Builder.CreateBitCast(V, PtrToInt8Ty);
750cb2fbcb0SMike Stump }
751cb2fbcb0SMike Stump 
7524446dcf0SMike Stump llvm::Function *
7534446dcf0SMike Stump CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
7549d42f0f1SJohn McCall                                        CGBlockInfo &Info,
755692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
7569d42f0f1SJohn McCall                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm) {
7579074ed8cSDevang Patel 
7589074ed8cSDevang Patel   // Check if we should generate debug info for this block.
7599074ed8cSDevang Patel   if (CGM.getDebugInfo())
7609074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
7619074ed8cSDevang Patel 
7625469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
7635469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
7645469f29aSMike Stump   // in a block.
7655469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
7665469f29aSMike Stump        i != ldm.end();
7675469f29aSMike Stump        ++i) {
7685469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
7695469f29aSMike Stump 
7700ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
7715469f29aSMike Stump       LocalDeclMap[VD] = i->second;
7725469f29aSMike Stump   }
7735469f29aSMike Stump 
77498ca7943SKen Dyck   BlockOffset =
77598ca7943SKen Dyck       CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
7765262b119SKen Dyck   BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
77709a9b6e3SEli Friedman 
778aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
779aae4349dSFariborz Jahanian   QualType ResultType;
780c50c27ccSRafael Espindola   FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType);
781aae4349dSFariborz Jahanian   bool IsVariadic;
782a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
783a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
784aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
785aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
786658fe02dSMike Stump   } else {
787aae4349dSFariborz Jahanian     // K&R style block.
788aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
789aae4349dSFariborz Jahanian     IsVariadic = false;
790aae4349dSFariborz Jahanian   }
7916a60fa24SAnders Carlsson 
7926a60fa24SAnders Carlsson   FunctionArgList Args;
7936a60fa24SAnders Carlsson 
7947fe9cc1dSMike Stump   CurFuncDecl = OuterFuncDecl;
7957fe9cc1dSMike Stump 
7963385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
7976a60fa24SAnders Carlsson 
7987fe9cc1dSMike Stump   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
799d015328fSMike Stump 
80087fe5d56SJohn McCall   // Build the block struct now.
8019d42f0f1SJohn McCall   AllocateAllBlockDeclRefs(*this, Info);
8027fe9cc1dSMike Stump 
803e1b19ba0SMike Stump   QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
80487fe5d56SJohn McCall                                                   BlockLayout);
80587fe5d56SJohn McCall 
8066a60fa24SAnders Carlsson   // FIXME: This leaks
8076a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
8084d4dcc8eSJohn McCall     ImplicitParamDecl::Create(getContext(), const_cast<BlockDecl*>(BD),
809d015328fSMike Stump                               SourceLocation(), II,
810d015328fSMike Stump                               ParmTy);
8116a60fa24SAnders Carlsson 
8126a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
813cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
8146a60fa24SAnders Carlsson 
815c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
8166a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
817eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
8186a60fa24SAnders Carlsson 
8196a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
820c50c27ccSRafael Espindola     CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo);
8216a60fa24SAnders Carlsson 
8226a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
823aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
8246a60fa24SAnders Carlsson 
8257e10f369SDouglas Gregor   MangleBuffer Name;
8267e10f369SDouglas Gregor   CGM.getMangledName(Name, BD);
8276a60fa24SAnders Carlsson   llvm::Function *Fn =
82802df9da2SDouglas Gregor     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
82902df9da2SDouglas Gregor                            Name.getString(), &CGM.getModule());
8306a60fa24SAnders Carlsson 
831c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
832c3e7cff6SDaniel Dunbar 
833324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
8343385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
8352e722b91SMike Stump 
836324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
83728ec0cf8SChris Lattner   CurCodeDecl = BD;
838017460abSMike Stump 
83987fe5d56SJohn McCall   // If we have a C++ 'this' reference, go ahead and force it into
84087fe5d56SJohn McCall   // existence now.
84187fe5d56SJohn McCall   if (Info.CXXThisRef) {
84287fe5d56SJohn McCall     assert(!BlockCXXThisOffset.isZero() &&
84387fe5d56SJohn McCall            "haven't yet allocated 'this' reference");
84487fe5d56SJohn McCall 
84587fe5d56SJohn McCall     // TODO: I have a dream that one day this will be typed.
84687fe5d56SJohn McCall     llvm::Value *BlockLiteral = LoadBlockStruct();
84787fe5d56SJohn McCall     llvm::Value *ThisPtrRaw =
84887fe5d56SJohn McCall       Builder.CreateConstInBoundsGEP1_64(BlockLiteral,
84987fe5d56SJohn McCall                                          BlockCXXThisOffset.getQuantity(),
85087fe5d56SJohn McCall                                          "this.ptr.raw");
85187fe5d56SJohn McCall 
85287fe5d56SJohn McCall     const llvm::Type *Ty =
85387fe5d56SJohn McCall       CGM.getTypes().ConvertType(Info.CXXThisRef->getType());
85487fe5d56SJohn McCall     Ty = llvm::PointerType::get(Ty, 0);
85587fe5d56SJohn McCall     llvm::Value *ThisPtr = Builder.CreateBitCast(ThisPtrRaw, Ty, "this.ptr");
85687fe5d56SJohn McCall 
85787fe5d56SJohn McCall     CXXThisValue = Builder.CreateLoad(ThisPtr, "this");
85887fe5d56SJohn McCall   }
85987fe5d56SJohn McCall 
8609d42f0f1SJohn McCall   // If we have an Objective C 'self' reference, go ahead and force it
8619d42f0f1SJohn McCall   // into existence now.
8629d42f0f1SJohn McCall   if (Info.NeedsObjCSelf) {
8639d42f0f1SJohn McCall     ValueDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
8649d42f0f1SJohn McCall     LocalDeclMap[Self] = GetAddrOfBlockDecl(Self, false);
8659d42f0f1SJohn McCall   }
8669d42f0f1SJohn McCall 
867017460abSMike Stump   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
868017460abSMike Stump   llvm::BasicBlock *entry = Builder.GetInsertBlock();
869017460abSMike Stump   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
870017460abSMike Stump   --entry_ptr;
871017460abSMike Stump 
8723385fe12SChris Lattner   EmitStmt(BExpr->getBody());
873017460abSMike Stump 
8747d69911aSMike Stump   // Remember where we were...
8757d69911aSMike Stump   llvm::BasicBlock *resume = Builder.GetInsertBlock();
876017460abSMike Stump 
8777d69911aSMike Stump   // Go back to the entry.
878017460abSMike Stump   ++entry_ptr;
879017460abSMike Stump   Builder.SetInsertPoint(entry, entry_ptr);
880017460abSMike Stump 
8812e722b91SMike Stump   if (CGDebugInfo *DI = getDebugInfo()) {
8822e722b91SMike Stump     // Emit debug information for all the BlockDeclRefDecls.
88387fe5d56SJohn McCall     // FIXME: also for 'this'
88487fe5d56SJohn McCall     for (unsigned i = 0, e = BlockLayout.size(); i != e; ++i) {
885bf78478dSChris Lattner       if (const BlockDeclRefExpr *BDRE =
88687fe5d56SJohn McCall             dyn_cast<BlockDeclRefExpr>(BlockLayout[i])) {
8872e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
8882e722b91SMike Stump         DI->setLocation(D->getLocation());
8892e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
8902e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
8912e722b91SMike Stump                                               Builder, this);
8922e722b91SMike Stump       }
8932e722b91SMike Stump     }
8942e722b91SMike Stump   }
8957d69911aSMike Stump   // And resume where we left off.
8967d69911aSMike Stump   if (resume == 0)
8977d69911aSMike Stump     Builder.ClearInsertionPoint();
8987d69911aSMike Stump   else
8997d69911aSMike Stump     Builder.SetInsertPoint(resume);
9002e722b91SMike Stump 
9013385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
9026a60fa24SAnders Carlsson 
903b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
9045262b119SKen Dyck   CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
90540775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
9065262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
9075262b119SKen Dyck                                MinAlign.getQuantity()));
908b750d928SMike Stump 
9099d42f0f1SJohn McCall   Info.BlockSize = BlockOffset;
9109d42f0f1SJohn McCall   Info.BlockAlign = BlockAlign;
9119d42f0f1SJohn McCall   Info.BlockLayout = BlockLayout;
9129d42f0f1SJohn McCall   Info.BlockHasCopyDispose = BlockHasCopyDispose;
9136a60fa24SAnders Carlsson   return Fn;
9146a60fa24SAnders Carlsson }
9151db7d04bSMike Stump 
91687fe5d56SJohn McCall CharUnits BlockFunction::getBlockOffset(CharUnits Size, CharUnits Align) {
9175262b119SKen Dyck   assert((Align.isPositive()) && "alignment must be 1 byte or more");
9181db7d04bSMike Stump 
91940775003SKen Dyck   CharUnits OldOffset = BlockOffset;
9201db7d04bSMike Stump 
9211db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
92240775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
9235262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
9241db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
9251db7d04bSMike Stump 
92640775003SKen Dyck   CharUnits Pad = BlockOffset - OldOffset;
92740775003SKen Dyck   if (Pad.isPositive()) {
9281db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
92940775003SKen Dyck                                                        llvm::APInt(32,
93040775003SKen Dyck                                                          Pad.getQuantity()),
9311db7d04bSMike Stump                                                        ArrayType::Normal, 0);
9326a047c97SDouglas Gregor     ValueDecl *PadDecl = VarDecl::Create(getContext(),
9336a047c97SDouglas Gregor                                          getContext().getTranslationUnitDecl(),
9346a047c97SDouglas Gregor                                          SourceLocation(),
935c4df4076SDouglas Gregor                                          0, QualType(PadTy), 0,
936c4df4076SDouglas Gregor                                          VarDecl::None, VarDecl::None);
93787fe5d56SJohn McCall     Expr *E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
938ed6c7440SDouglas Gregor                                              SourceLocation());
93987fe5d56SJohn McCall     BlockLayout.push_back(E);
9401db7d04bSMike Stump   }
9411db7d04bSMike Stump 
9421db7d04bSMike Stump   BlockOffset += Size;
9431db7d04bSMike Stump   return BlockOffset - Size;
9441db7d04bSMike Stump }
94597d01d50SMike Stump 
946aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
947aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
94867645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
9490c743277SMike Stump   QualType R = getContext().VoidTy;
9500c743277SMike Stump 
9510c743277SMike Stump   FunctionArgList Args;
9520c743277SMike Stump   // FIXME: This leaks
953aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
9547fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9557fe9cc1dSMike Stump                               SourceLocation(), 0,
956aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
957aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
9580c743277SMike Stump   ImplicitParamDecl *Src =
9597fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9607fe9cc1dSMike Stump                               SourceLocation(), 0,
9610c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
9620c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
9630c743277SMike Stump 
9640c743277SMike Stump   const CGFunctionInfo &FI =
965c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
9660c743277SMike Stump 
967cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
968cbc2bcafSMike Stump   // internal linkage.
9690c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
9700c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
9710c743277SMike Stump 
9720c743277SMike Stump   llvm::Function *Fn =
9730c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
974d6b28fc6SBenjamin Kramer                            "__copy_helper_block_", &CGM.getModule());
9750c743277SMike Stump 
9760c743277SMike Stump   IdentifierInfo *II
9770c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
9780c743277SMike Stump 
9790c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
9800c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
98160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
982c4df4076SDouglas Gregor                                           FunctionDecl::Static,
983c4df4076SDouglas Gregor                                           FunctionDecl::None,
984c4df4076SDouglas Gregor                                           false,
9850c743277SMike Stump                                           true);
9860c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
987aeb0ffd5SMike Stump 
988aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
989aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
99067645930SMike Stump 
99167645930SMike Stump   if (NoteForHelperp) {
99267645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
99367645930SMike Stump 
9949793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
995aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
996aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
997aeb0ffd5SMike Stump 
998aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
9993b65ac26SMike Stump     llvm::Type *PtrPtrT;
10009793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
10013b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
10023b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
1003aeb0ffd5SMike Stump 
1004aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
1005aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
1006aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
1007aeb0ffd5SMike Stump 
1008aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
1009aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
1010aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
1011aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
1012aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
10139793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
1014aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
1015aeb0ffd5SMike Stump 
1016aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
1017aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
1018aeb0ffd5SMike Stump 
101941a75027SOwen Anderson         llvm::Value *N = llvm::ConstantInt::get(
102041a75027SOwen Anderson               llvm::Type::getInt32Ty(T->getContext()), flag);
1021aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
1022aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
1023aeb0ffd5SMike Stump       }
1024aeb0ffd5SMike Stump     }
102567645930SMike Stump   }
1026aeb0ffd5SMike Stump 
10270c743277SMike Stump   CGF.FinishFunction();
10280c743277SMike Stump 
1029ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
103097d01d50SMike Stump }
103197d01d50SMike Stump 
1032d6ef62f0SMike Stump llvm::Constant *BlockFunction::
1033aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
1034aeb0ffd5SMike Stump                               const llvm::StructType* T,
103567645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
10360c743277SMike Stump   QualType R = getContext().VoidTy;
10370c743277SMike Stump 
10380c743277SMike Stump   FunctionArgList Args;
10390c743277SMike Stump   // FIXME: This leaks
10400c743277SMike Stump   ImplicitParamDecl *Src =
10417fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10427fe9cc1dSMike Stump                               SourceLocation(), 0,
10430c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
10440c743277SMike Stump 
10450c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
10460c743277SMike Stump 
10470c743277SMike Stump   const CGFunctionInfo &FI =
1048c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
10490c743277SMike Stump 
1050cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1051cbc2bcafSMike Stump   // internal linkage.
10520c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
10530c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
10540c743277SMike Stump 
10550c743277SMike Stump   llvm::Function *Fn =
10560c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1057d6b28fc6SBenjamin Kramer                            "__destroy_helper_block_", &CGM.getModule());
10580c743277SMike Stump 
10590c743277SMike Stump   IdentifierInfo *II
10600c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
10610c743277SMike Stump 
10620c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
10630c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
106460ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1065c4df4076SDouglas Gregor                                           FunctionDecl::Static,
1066c4df4076SDouglas Gregor                                           FunctionDecl::None,
1067c4df4076SDouglas Gregor                                           false, true);
10680c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
10696f7d9f87SMike Stump 
107067645930SMike Stump   if (NoteForHelperp) {
107167645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
107267645930SMike Stump 
10736f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
10746f7d9f87SMike Stump     llvm::Type *PtrPtrT;
10759793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
10766f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
10776f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
10786f7d9f87SMike Stump 
10796f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
10806f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
10816f7d9f87SMike Stump       int index = NoteForHelper[i].index;
10826f7d9f87SMike Stump 
10836f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
10846f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
10856f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
10866f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
10876f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
10889793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
10896f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
10906f7d9f87SMike Stump 
10916f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
10926f7d9f87SMike Stump       }
10936f7d9f87SMike Stump     }
109467645930SMike Stump   }
10956f7d9f87SMike Stump 
10960c743277SMike Stump   CGF.FinishFunction();
10970c743277SMike Stump 
1098ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
10990c743277SMike Stump }
11000c743277SMike Stump 
1101aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
110267645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
1103aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1104aeb0ffd5SMike Stump                                                          T, NoteForHelper);
11050c743277SMike Stump }
11060c743277SMike Stump 
1107aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
110867645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
1109aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
111067645930SMike Stump                                                             T, NoteForHelperp);
111197d01d50SMike Stump }
1112626aecc4SMike Stump 
1113f89230d9SMike Stump llvm::Constant *BlockFunction::
1114f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
1115ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1116ee2a5ee5SMike Stump 
1117ee2a5ee5SMike Stump   FunctionArgList Args;
1118ee2a5ee5SMike Stump   // FIXME: This leaks
1119f89230d9SMike Stump   ImplicitParamDecl *Dst =
11207fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
11217fe9cc1dSMike Stump                               SourceLocation(), 0,
1122f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1123f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
1124f89230d9SMike Stump 
1125f89230d9SMike Stump   // FIXME: This leaks
1126ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
11277fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
11287fe9cc1dSMike Stump                               SourceLocation(), 0,
1129ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1130ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1131ee2a5ee5SMike Stump 
1132ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1133c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1134ee2a5ee5SMike Stump 
1135ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1136ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1137ee2a5ee5SMike Stump 
1138cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1139cbc2bcafSMike Stump   // internal linkage.
1140ee2a5ee5SMike Stump   llvm::Function *Fn =
1141ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1142d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_copy_", &CGM.getModule());
1143ee2a5ee5SMike Stump 
1144ee2a5ee5SMike Stump   IdentifierInfo *II
1145ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1146ee2a5ee5SMike Stump 
1147ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1148ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
114960ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1150c4df4076SDouglas Gregor                                           FunctionDecl::Static,
1151c4df4076SDouglas Gregor                                           FunctionDecl::None,
1152c4df4076SDouglas Gregor                                           false, true);
1153ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1154f89230d9SMike Stump 
1155f89230d9SMike Stump   // dst->x
1156f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
11579793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
11583b65ac26SMike Stump   V = Builder.CreateLoad(V);
1159f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
1160f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1161f89230d9SMike Stump 
1162f89230d9SMike Stump   // src->x
1163f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
1164f89230d9SMike Stump   V = Builder.CreateLoad(V);
1165f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
1166f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
11679793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1168f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
1169f89230d9SMike Stump 
1170f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
1171f89230d9SMike Stump 
117241a75027SOwen Anderson   llvm::Value *N = llvm::ConstantInt::get(
117341a75027SOwen Anderson           llvm::Type::getInt32Ty(T->getContext()), flag);
1174f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
1175f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1176f89230d9SMike Stump 
1177ee2a5ee5SMike Stump   CGF.FinishFunction();
1178ee2a5ee5SMike Stump 
1179ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1180ee2a5ee5SMike Stump }
1181ee2a5ee5SMike Stump 
1182fbe25dd1SMike Stump llvm::Constant *
1183fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1184fbe25dd1SMike Stump                                                   int flag) {
1185ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1186ee2a5ee5SMike Stump 
1187ee2a5ee5SMike Stump   FunctionArgList Args;
1188ee2a5ee5SMike Stump   // FIXME: This leaks
1189ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
11907fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
11917fe9cc1dSMike Stump                               SourceLocation(), 0,
1192ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1193ee2a5ee5SMike Stump 
1194ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1195ee2a5ee5SMike Stump 
1196ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1197c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1198ee2a5ee5SMike Stump 
1199ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1200ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1201ee2a5ee5SMike Stump 
1202cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1203cbc2bcafSMike Stump   // internal linkage.
1204ee2a5ee5SMike Stump   llvm::Function *Fn =
1205ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1206d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_dispose_",
1207ee2a5ee5SMike Stump                            &CGM.getModule());
1208ee2a5ee5SMike Stump 
1209ee2a5ee5SMike Stump   IdentifierInfo *II
1210ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1211ee2a5ee5SMike Stump 
1212ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1213ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
121460ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1215c4df4076SDouglas Gregor                                           FunctionDecl::Static,
1216c4df4076SDouglas Gregor                                           FunctionDecl::None,
1217c4df4076SDouglas Gregor                                           false, true);
1218ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1219fbe25dd1SMike Stump 
1220fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
12219793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
12223b65ac26SMike Stump   V = Builder.CreateLoad(V);
1223fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
12249793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
12253b65ac26SMike Stump   V = Builder.CreateLoad(V);
1226fbe25dd1SMike Stump 
1227fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1228fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1229ee2a5ee5SMike Stump   CGF.FinishFunction();
1230ee2a5ee5SMike Stump 
1231ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1232ee2a5ee5SMike Stump }
1233ee2a5ee5SMike Stump 
1234f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1235e08ea787SChris Lattner                                                     int Flag, unsigned Align) {
1236e08ea787SChris Lattner   // All alignments below that of pointer alignment collapse down to just
1237cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1238cbc2bcafSMike Stump   // with.
1239cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1240e08ea787SChris Lattner 
1241cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1242cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1243cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1244e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1245e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.AssignCache[Kind];
1246cbc2bcafSMike Stump   if (Entry)
1247cbc2bcafSMike Stump     return Entry;
1248e08ea787SChris Lattner   return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
1249ee2a5ee5SMike Stump }
1250ee2a5ee5SMike Stump 
1251fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1252e08ea787SChris Lattner                                                        int Flag,
1253cbc2bcafSMike Stump                                                        unsigned Align) {
1254cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1255cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1256cbc2bcafSMike Stump   // with.
1257cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1258e08ea787SChris Lattner 
1259cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1260cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1261cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1262e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1263e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.DestroyCache[Kind];
1264cbc2bcafSMike Stump   if (Entry)
1265cbc2bcafSMike Stump     return Entry;
1266e08ea787SChris Lattner   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
1267ee2a5ee5SMike Stump }
1268ee2a5ee5SMike Stump 
1269626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1270626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1271626aecc4SMike Stump     const llvm::FunctionType *FTy;
1272626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
127341a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1274626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
127541a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
12769793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1277626aecc4SMike Stump     CGM.BlockObjectDispose
1278626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1279626aecc4SMike Stump   }
1280626aecc4SMike Stump   return CGM.BlockObjectDispose;
1281626aecc4SMike Stump }
1282626aecc4SMike Stump 
1283f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1284f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1285f89230d9SMike Stump     const llvm::FunctionType *FTy;
1286f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
128741a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1288f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1289f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
129041a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
12919793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1292f89230d9SMike Stump     CGM.BlockObjectAssign
1293f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1294f89230d9SMike Stump   }
1295f89230d9SMike Stump   return CGM.BlockObjectAssign;
1296f89230d9SMike Stump }
1297f89230d9SMike Stump 
1298fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1299626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1300fbe25dd1SMike Stump   llvm::Value *N;
1301626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
130241a75027SOwen Anderson   N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1303626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1304626aecc4SMike Stump }
13054446dcf0SMike Stump 
13064446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1307aeb0ffd5SMike Stump 
1308aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1309aeb0ffd5SMike Stump                              CGBuilderTy &B)
1310170229f6SOwen Anderson   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
131141a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
131241a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1313aeb0ffd5SMike Stump 
1314aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1315aeb0ffd5SMike Stump }
1316