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 
142437cbfaSAnders Carlsson #include "CodeGenFunction.h"
152437cbfaSAnders Carlsson #include "CodeGenModule.h"
162437cbfaSAnders Carlsson #include "llvm/Module.h"
176a60fa24SAnders Carlsson #include "llvm/Target/TargetData.h"
182437cbfaSAnders Carlsson 
192437cbfaSAnders Carlsson #include <algorithm>
202437cbfaSAnders Carlsson 
212437cbfaSAnders Carlsson using namespace clang;
222437cbfaSAnders Carlsson using namespace CodeGen;
232437cbfaSAnders Carlsson 
246a60fa24SAnders Carlsson enum {
2585284bacSMike Stump   BLOCK_NEEDS_FREE =        (1 << 24),
2685284bacSMike Stump   BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
2785284bacSMike Stump   BLOCK_HAS_CXX_OBJ =       (1 << 26),
2885284bacSMike Stump   BLOCK_IS_GC =             (1 << 27),
2985284bacSMike Stump   BLOCK_IS_GLOBAL =         (1 << 28),
3085284bacSMike Stump   BLOCK_HAS_DESCRIPTOR =    (1 << 29)
316a60fa24SAnders Carlsson };
326a60fa24SAnders Carlsson 
33cb2fbcb0SMike Stump llvm::Constant *CodeGenFunction::BuildDescriptorBlockDecl(uint64_t Size) {
3485284bacSMike Stump   const llvm::PointerType *PtrToInt8Ty
3585284bacSMike Stump     = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
36c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
37c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
3885284bacSMike Stump   llvm::Constant *C;
3985284bacSMike Stump   std::vector<llvm::Constant*> Elts;
4085284bacSMike Stump 
4185284bacSMike Stump   // reserved
42c2c38331SMike Stump   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
4385284bacSMike Stump   Elts.push_back(C);
4485284bacSMike Stump 
4585284bacSMike Stump   // Size
462ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
472ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
482ac40a9fSMike Stump   // API to size_t.
49cb2fbcb0SMike Stump   C = llvm::ConstantInt::get(UnsignedLongTy, Size);
5085284bacSMike Stump   Elts.push_back(C);
5185284bacSMike Stump 
5285284bacSMike Stump   if (BlockHasCopyDispose) {
5385284bacSMike Stump     // copy_func_helper_decl
54cb2fbcb0SMike Stump     // FIXME: implement
55c2c38331SMike Stump     C = llvm::ConstantInt::get(UnsignedLongTy, 0);
5685284bacSMike Stump     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
5785284bacSMike Stump     Elts.push_back(C);
5885284bacSMike Stump 
5985284bacSMike Stump     // destroy_func_decl
60cb2fbcb0SMike Stump     // FIXME: implement
61c2c38331SMike Stump     C = llvm::ConstantInt::get(UnsignedLongTy, 0);
6285284bacSMike Stump     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
6385284bacSMike Stump     Elts.push_back(C);
6485284bacSMike Stump   }
6585284bacSMike Stump 
6685284bacSMike Stump   C = llvm::ConstantStruct::get(Elts);
6785284bacSMike Stump 
6885284bacSMike Stump   C = new llvm::GlobalVariable(C->getType(), true,
6985284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
70499ae7ecSMike Stump                                C, "__block_descriptor_tmp", &CGM.getModule());
7185284bacSMike Stump   return C;
7285284bacSMike Stump }
7385284bacSMike Stump 
74971f9b66SMike Stump llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
75971f9b66SMike Stump   if (NSConcreteGlobalBlock)
76971f9b66SMike Stump     return NSConcreteGlobalBlock;
77971f9b66SMike Stump 
78971f9b66SMike Stump   const llvm::PointerType *PtrToInt8Ty
79971f9b66SMike Stump     = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
8052d9c49dSMike Stump   // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
81971f9b66SMike Stump   // same thing as CreateRuntimeFunction if there's already a variable with
82971f9b66SMike Stump   // the same name.
83971f9b66SMike Stump   NSConcreteGlobalBlock
84971f9b66SMike Stump     = new llvm::GlobalVariable(PtrToInt8Ty, false,
85971f9b66SMike Stump                                llvm::GlobalValue::ExternalLinkage,
86971f9b66SMike Stump                                0, "_NSConcreteGlobalBlock",
87971f9b66SMike Stump                                &getModule());
88971f9b66SMike Stump 
89971f9b66SMike Stump   return NSConcreteGlobalBlock;
90971f9b66SMike Stump }
91971f9b66SMike Stump 
927ab278dbSMike Stump llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
937ab278dbSMike Stump   if (NSConcreteStackBlock)
947ab278dbSMike Stump     return NSConcreteStackBlock;
957ab278dbSMike Stump 
967ab278dbSMike Stump   const llvm::PointerType *PtrToInt8Ty
977ab278dbSMike Stump     = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
9852d9c49dSMike Stump   // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
997ab278dbSMike Stump   // same thing as CreateRuntimeFunction if there's already a variable with
1007ab278dbSMike Stump   // the same name.
1017ab278dbSMike Stump   NSConcreteStackBlock
1027ab278dbSMike Stump     = new llvm::GlobalVariable(PtrToInt8Ty, false,
1037ab278dbSMike Stump                                llvm::GlobalValue::ExternalLinkage,
1047ab278dbSMike Stump                                0, "_NSConcreteStackBlock",
1057ab278dbSMike Stump                                &getModule());
1067ab278dbSMike Stump 
1077ab278dbSMike Stump   return NSConcreteStackBlock;
1087ab278dbSMike Stump }
1097ab278dbSMike Stump 
1105d2534adSMike Stump // FIXME: Push most into CGM, passing down a few bits, like current
1115d2534adSMike Stump // function name.
112b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
11385284bacSMike Stump   bool insideFunction = false;
11485284bacSMike Stump   bool BlockRefDeclList = false;
11585284bacSMike Stump   bool BlockByrefDeclList = false;
11685284bacSMike Stump 
11785284bacSMike Stump   std::vector<llvm::Constant*> Elts;
11885284bacSMike Stump   llvm::Constant *C;
119b750d928SMike Stump   llvm::Value *V;
12085284bacSMike Stump 
12185284bacSMike Stump   {
12285284bacSMike Stump     // C = BuildBlockStructInitlist();
12385284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
12485284bacSMike Stump 
12585284bacSMike Stump     if (BlockHasCopyDispose)
12685284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
12785284bacSMike Stump 
128499ae7ecSMike Stump     // __isa
1297ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
13085284bacSMike Stump     if (!insideFunction ||
13185284bacSMike Stump         (!BlockRefDeclList && !BlockByrefDeclList)) {
132971f9b66SMike Stump       C = CGM.getNSConcreteGlobalBlock();
13385284bacSMike Stump       flags |= BLOCK_IS_GLOBAL;
13485284bacSMike Stump     }
1357ab278dbSMike Stump     const llvm::PointerType *PtrToInt8Ty
1367ab278dbSMike Stump       = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
13785284bacSMike Stump     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
13885284bacSMike Stump     Elts.push_back(C);
13985284bacSMike Stump 
14085284bacSMike Stump     // __flags
14185284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
14285284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
14385284bacSMike Stump     C = llvm::ConstantInt::get(IntTy, flags);
14485284bacSMike Stump     Elts.push_back(C);
14585284bacSMike Stump 
14685284bacSMike Stump     // __reserved
14785284bacSMike Stump     C = llvm::ConstantInt::get(IntTy, 0);
14885284bacSMike Stump     Elts.push_back(C);
14985284bacSMike Stump 
1505d2534adSMike Stump     // __invoke
15103868f4eSMike Stump     const char *Name = "";
1522d5a2878SMike Stump     if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurFuncDecl))
153eecd39f2SMike Stump       if (ND->getIdentifier())
1540e7d7b68SMike Stump         Name = ND->getNameAsCString();
1552d5a2878SMike Stump     BlockInfo Info(0, Name);
156b750d928SMike Stump     uint64_t subBlockSize, subBlockAlign;
1571db7d04bSMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
158cb2fbcb0SMike Stump     llvm::Function *Fn
159b750d928SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
160b750d928SMike Stump                                                    subBlockAlign, subBlockDeclRefDecls);
1612d5a2878SMike Stump     Elts.push_back(Fn);
16285284bacSMike Stump 
16385284bacSMike Stump     // __descriptor
164cb2fbcb0SMike Stump     Elts.push_back(BuildDescriptorBlockDecl(subBlockSize));
16585284bacSMike Stump 
166b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
16785284bacSMike Stump       C = llvm::ConstantStruct::get(Elts);
16885284bacSMike Stump 
16985284bacSMike Stump       char Name[32];
1709319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
17185284bacSMike Stump       C = new llvm::GlobalVariable(C->getType(), true,
17285284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
17385284bacSMike Stump                                    C, Name, &CGM.getModule());
1745d2534adSMike Stump       QualType BPT = BE->getType();
1755d2534adSMike Stump       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
17685284bacSMike Stump       return C;
17785284bacSMike Stump     }
17885284bacSMike Stump 
179b750d928SMike Stump     std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
180b750d928SMike Stump     for (int i=0; i<5; ++i)
181b750d928SMike Stump       Types[i] = Elts[i]->getType();
18285284bacSMike Stump 
1831db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
1841db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
1851db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
1861db7d04bSMike Stump       QualType Ty = E->getType();
1871db7d04bSMike Stump       if (BDRE && BDRE->isByRef())
1881db7d04bSMike Stump         Ty = getContext().getPointerType(Ty);
1891db7d04bSMike Stump       Types[i+5] = ConvertType(Ty);
1901db7d04bSMike Stump     }
191b750d928SMike Stump 
192b750d928SMike Stump     llvm::Type *Ty = llvm::StructType::get(Types, true);
193b750d928SMike Stump 
194b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
195b750d928SMike Stump     A->setAlignment(subBlockAlign);
196b750d928SMike Stump     V = A;
197b750d928SMike Stump 
198b750d928SMike Stump     for (unsigned i=0; i<5; ++i)
199b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
200b750d928SMike Stump 
201b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
202b750d928SMike Stump       {
2031db7d04bSMike Stump         // FIXME: Push const down.
2041db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2051db7d04bSMike Stump         DeclRefExpr *DR;
2061db7d04bSMike Stump         ValueDecl *VD;
207b750d928SMike Stump 
2081db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2091db7d04bSMike Stump         // Skip padding.
2101db7d04bSMike Stump         if (DR) continue;
2111db7d04bSMike Stump 
2121db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2131db7d04bSMike Stump         VD = BDRE->getDecl();
2141db7d04bSMike Stump 
2151db7d04bSMike Stump         // FIXME: I want a better way to do this.
2161db7d04bSMike Stump         if (LocalDeclMap[VD]) {
2171db7d04bSMike Stump           E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
2181db7d04bSMike Stump                                               VD->getType(), SourceLocation(),
2191db7d04bSMike Stump                                               false, false);
2201db7d04bSMike Stump         }
2211db7d04bSMike Stump         if (BDRE->isByRef())
2221db7d04bSMike Stump           E = new (getContext())
2231db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
2241db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
2251db7d04bSMike Stump                           SourceLocation());
2261db7d04bSMike Stump 
227b750d928SMike Stump         llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
2281db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
229b750d928SMike Stump         if (r.isScalar())
230b750d928SMike Stump           Builder.CreateStore(r.getScalarVal(), Addr);
231b750d928SMike Stump         else if (r.isComplex())
232b750d928SMike Stump           // FIXME: implement
233b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
234b750d928SMike Stump         else if (r.isAggregate())
235b750d928SMike Stump           ; // Already created into the destination
236b750d928SMike Stump         else
237b750d928SMike Stump           assert (0 && "bad block variable");
238b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
239b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
240b750d928SMike Stump       }
241b750d928SMike Stump   }
242b750d928SMike Stump 
243b750d928SMike Stump   QualType BPT = BE->getType();
244b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
245b750d928SMike Stump }
24685284bacSMike Stump 
24785284bacSMike Stump 
248650c932dSMike Stump const llvm::Type *CodeGenModule::getBlockDescriptorType() {
249650c932dSMike Stump   if (BlockDescriptorType)
250650c932dSMike Stump     return BlockDescriptorType;
2512437cbfaSAnders Carlsson 
2522437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
253650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
2542437cbfaSAnders Carlsson 
2552437cbfaSAnders Carlsson   // struct __block_descriptor {
2562437cbfaSAnders Carlsson   //   unsigned long reserved;
2572437cbfaSAnders Carlsson   //   unsigned long block_size;
2582437cbfaSAnders Carlsson   // };
259650c932dSMike Stump   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
2602437cbfaSAnders Carlsson                                               UnsignedLongTy,
2612437cbfaSAnders Carlsson                                               NULL);
2622437cbfaSAnders Carlsson 
263650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
264650c932dSMike Stump                           BlockDescriptorType);
2652437cbfaSAnders Carlsson 
266650c932dSMike Stump   return BlockDescriptorType;
2672437cbfaSAnders Carlsson }
2682437cbfaSAnders Carlsson 
269005c9a62SMike Stump const llvm::Type *
270005c9a62SMike Stump CodeGenModule::getGenericBlockLiteralType() {
271005c9a62SMike Stump   if (GenericBlockLiteralType)
272005c9a62SMike Stump     return GenericBlockLiteralType;
2732437cbfaSAnders Carlsson 
2742437cbfaSAnders Carlsson   const llvm::Type *Int8PtrTy =
2752437cbfaSAnders Carlsson     llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2762437cbfaSAnders Carlsson 
2772437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
278005c9a62SMike Stump     llvm::PointerType::getUnqual(getBlockDescriptorType());
2792437cbfaSAnders Carlsson 
28092bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
28192bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
28292bbd6d4SMike Stump 
2832437cbfaSAnders Carlsson   // struct __block_literal_generic {
2845d2534adSMike Stump   //   void *__isa;
2855d2534adSMike Stump   //   int __flags;
2865d2534adSMike Stump   //   int __reserved;
2875d2534adSMike Stump   //   void (*__invoke)(void *);
2885d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
2892437cbfaSAnders Carlsson   // };
290005c9a62SMike Stump   GenericBlockLiteralType = llvm::StructType::get(Int8PtrTy,
29192bbd6d4SMike Stump                                                   IntTy,
29292bbd6d4SMike Stump                                                   IntTy,
2932437cbfaSAnders Carlsson                                                   Int8PtrTy,
2942437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
2952437cbfaSAnders Carlsson                                                   NULL);
2962437cbfaSAnders Carlsson 
297005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
298005c9a62SMike Stump                           GenericBlockLiteralType);
2992437cbfaSAnders Carlsson 
300005c9a62SMike Stump   return GenericBlockLiteralType;
3012437cbfaSAnders Carlsson }
3022437cbfaSAnders Carlsson 
3035d2534adSMike Stump const llvm::Type *
3045d2534adSMike Stump CodeGenModule::getGenericExtendedBlockLiteralType() {
3055d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
3065d2534adSMike Stump     return GenericExtendedBlockLiteralType;
3075d2534adSMike Stump 
3085d2534adSMike Stump   const llvm::Type *Int8PtrTy =
3095d2534adSMike Stump     llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3105d2534adSMike Stump 
3115d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
3125d2534adSMike Stump     llvm::PointerType::getUnqual(getBlockDescriptorType());
3135d2534adSMike Stump 
3145d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
3155d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
3165d2534adSMike Stump 
3175d2534adSMike Stump   // struct __block_literal_generic {
3185d2534adSMike Stump   //   void *__isa;
3195d2534adSMike Stump   //   int __flags;
3205d2534adSMike Stump   //   int __reserved;
3215d2534adSMike Stump   //   void (*__invoke)(void *);
3225d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3235d2534adSMike Stump   //   void *__copy_func_helper_decl;
3245d2534adSMike Stump   //   void *__destroy_func_decl;
3255d2534adSMike Stump   // };
3265d2534adSMike Stump   GenericExtendedBlockLiteralType = llvm::StructType::get(Int8PtrTy,
3275d2534adSMike Stump                                                           IntTy,
3285d2534adSMike Stump                                                           IntTy,
3295d2534adSMike Stump                                                           Int8PtrTy,
3305d2534adSMike Stump                                                           BlockDescPtrTy,
3315d2534adSMike Stump                                                           Int8PtrTy,
3325d2534adSMike Stump                                                           Int8PtrTy,
3335d2534adSMike Stump                                                           NULL);
3345d2534adSMike Stump 
3355d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
3365d2534adSMike Stump                           GenericExtendedBlockLiteralType);
3375d2534adSMike Stump 
3385d2534adSMike Stump   return GenericExtendedBlockLiteralType;
3395d2534adSMike Stump }
3405d2534adSMike Stump 
3412437cbfaSAnders Carlsson /// getBlockFunctionType - Given a BlockPointerType, will return the
3422437cbfaSAnders Carlsson /// function type for the block, including the first block literal argument.
3432437cbfaSAnders Carlsson static QualType getBlockFunctionType(ASTContext &Ctx,
3446a60fa24SAnders Carlsson                                      const BlockPointerType *BPT) {
345deaad8ccSDouglas Gregor   const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
3462437cbfaSAnders Carlsson 
3472437cbfaSAnders Carlsson   llvm::SmallVector<QualType, 8> Types;
3482437cbfaSAnders Carlsson   Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
3492437cbfaSAnders Carlsson 
350deaad8ccSDouglas Gregor   for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
3512437cbfaSAnders Carlsson        e = FTy->arg_type_end(); i != e; ++i)
3522437cbfaSAnders Carlsson     Types.push_back(*i);
3532437cbfaSAnders Carlsson 
3542437cbfaSAnders Carlsson   return Ctx.getFunctionType(FTy->getResultType(),
3552437cbfaSAnders Carlsson                              &Types[0], Types.size(),
3562437cbfaSAnders Carlsson                              FTy->isVariadic(), 0);
3572437cbfaSAnders Carlsson }
3582437cbfaSAnders Carlsson 
3596a60fa24SAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
3602437cbfaSAnders Carlsson   const BlockPointerType *BPT =
3612437cbfaSAnders Carlsson     E->getCallee()->getType()->getAsBlockPointerType();
3622437cbfaSAnders Carlsson 
3632437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
3642437cbfaSAnders Carlsson 
3652437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
3662437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
367005c9a62SMike Stump     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
3682437cbfaSAnders Carlsson 
3692437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
3702437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
3712437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
3722437cbfaSAnders Carlsson 
3732437cbfaSAnders Carlsson   // Get the function pointer from the literal.
3742437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
375624497c2SMike Stump   llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
3762437cbfaSAnders Carlsson 
3772437cbfaSAnders Carlsson   // Cast the function pointer to the right type.
3782437cbfaSAnders Carlsson   const llvm::Type *BlockFTy =
3792437cbfaSAnders Carlsson     ConvertType(getBlockFunctionType(getContext(), BPT));
3802437cbfaSAnders Carlsson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
3812437cbfaSAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
3822437cbfaSAnders Carlsson 
3832437cbfaSAnders Carlsson   BlockLiteral =
3842437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
3852437cbfaSAnders Carlsson                           llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
3862437cbfaSAnders Carlsson                           "tmp");
3872437cbfaSAnders Carlsson 
3882437cbfaSAnders Carlsson   // Add the block literal.
3892437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
3902437cbfaSAnders Carlsson   CallArgList Args;
3912437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
3922437cbfaSAnders Carlsson 
3932437cbfaSAnders Carlsson   // And the rest of the arguments.
3942437cbfaSAnders Carlsson   for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
3952437cbfaSAnders Carlsson        i != e; ++i)
3962437cbfaSAnders Carlsson     Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
3972437cbfaSAnders Carlsson                                   i->getType()));
3982437cbfaSAnders Carlsson 
3992437cbfaSAnders Carlsson   // And call the block.
4002437cbfaSAnders Carlsson   return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
4012437cbfaSAnders Carlsson                   Func, Args);
4022437cbfaSAnders Carlsson }
4036a60fa24SAnders Carlsson 
4042d5a2878SMike Stump llvm::Constant *
4050e7d7b68SMike Stump CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
4066a60fa24SAnders Carlsson   // Generate the block descriptor.
4076a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
40892bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
40992bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
4106a60fa24SAnders Carlsson 
4116a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
4126a60fa24SAnders Carlsson 
4136a60fa24SAnders Carlsson   // Reserved
4146a60fa24SAnders Carlsson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
4156a60fa24SAnders Carlsson 
4166a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
4176a60fa24SAnders Carlsson   // block literal struct.
4186a60fa24SAnders Carlsson   uint64_t BlockLiteralSize =
419005c9a62SMike Stump     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
4206a60fa24SAnders Carlsson   DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
4216a60fa24SAnders Carlsson 
4226a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
4236a60fa24SAnders Carlsson     llvm::ConstantStruct::get(&DescriptorFields[0], 2);
4246a60fa24SAnders Carlsson 
4256a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
4266a60fa24SAnders Carlsson     new llvm::GlobalVariable(DescriptorStruct->getType(), true,
4276a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
4286a60fa24SAnders Carlsson                              DescriptorStruct, "__block_descriptor_global",
4296a60fa24SAnders Carlsson                              &getModule());
4306a60fa24SAnders Carlsson 
4316a60fa24SAnders Carlsson   // Generate the constants for the block literal.
4326a60fa24SAnders Carlsson   llvm::Constant *LiteralFields[5];
4336a60fa24SAnders Carlsson 
4342d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
435b750d928SMike Stump   uint64_t subBlockSize, subBlockAlign;
4361db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
437cb2fbcb0SMike Stump   llvm::Function *Fn
438b750d928SMike Stump     = CodeGenFunction(*this).GenerateBlockFunction(BE, Info, subBlockSize,
439b750d928SMike Stump                                                    subBlockAlign,
440b750d928SMike Stump                                                    subBlockDeclRefDecls);
441cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
442cb2fbcb0SMike Stump          && "no imports allowed for global block");
4436a60fa24SAnders Carlsson 
4446a60fa24SAnders Carlsson   // isa
445971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
4466a60fa24SAnders Carlsson 
4476a60fa24SAnders Carlsson   // Flags
44885284bacSMike Stump   LiteralFields[1] = llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL);
4496a60fa24SAnders Carlsson 
4506a60fa24SAnders Carlsson   // Reserved
45192bbd6d4SMike Stump   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
4526a60fa24SAnders Carlsson 
4536a60fa24SAnders Carlsson   // Function
4546a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
4556a60fa24SAnders Carlsson 
4566a60fa24SAnders Carlsson   // Descriptor
4576a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
4586a60fa24SAnders Carlsson 
4596a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
4606a60fa24SAnders Carlsson     llvm::ConstantStruct::get(&LiteralFields[0], 5);
4616a60fa24SAnders Carlsson 
4626a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
4636a60fa24SAnders Carlsson     new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
4646a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
4656a60fa24SAnders Carlsson                              BlockLiteralStruct, "__block_literal_global",
4666a60fa24SAnders Carlsson                              &getModule());
4676a60fa24SAnders Carlsson 
4686a60fa24SAnders Carlsson   return BlockLiteral;
4696a60fa24SAnders Carlsson }
4706a60fa24SAnders Carlsson 
471cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
472cb2fbcb0SMike Stump   return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
473cb2fbcb0SMike Stump }
474cb2fbcb0SMike Stump 
475*3385fe12SChris Lattner llvm::Function *CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
476cb2fbcb0SMike Stump                                                        const BlockInfo& Info,
477b750d928SMike Stump                                                        uint64_t &Size,
478b750d928SMike Stump                                                        uint64_t &Align,
4791db7d04bSMike Stump                          llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls) {
480deaad8ccSDouglas Gregor   const FunctionProtoType *FTy =
481*3385fe12SChris Lattner     cast<FunctionProtoType>(BExpr->getFunctionType());
4826a60fa24SAnders Carlsson 
4836a60fa24SAnders Carlsson   FunctionArgList Args;
4846a60fa24SAnders Carlsson 
485*3385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
4866a60fa24SAnders Carlsson 
4876a60fa24SAnders Carlsson   // FIXME: This leaks
4886a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
4896a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
4906a60fa24SAnders Carlsson                               SourceLocation(), 0,
4916a60fa24SAnders Carlsson                               getContext().getPointerType(getContext().VoidTy));
4926a60fa24SAnders Carlsson 
4936a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
494cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
4956a60fa24SAnders Carlsson 
4966a60fa24SAnders Carlsson   for (BlockDecl::param_iterator i = BD->param_begin(),
4976a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
498eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
4996a60fa24SAnders Carlsson 
5006a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
5016a60fa24SAnders Carlsson     CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
5026a60fa24SAnders Carlsson 
5032d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
5046a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
5056a60fa24SAnders Carlsson   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
5066a60fa24SAnders Carlsson 
5076a60fa24SAnders Carlsson   llvm::Function *Fn =
5086a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
5096a60fa24SAnders Carlsson                            Name,
5106a60fa24SAnders Carlsson                            &CGM.getModule());
5116a60fa24SAnders Carlsson 
5126a60fa24SAnders Carlsson   StartFunction(BD, FTy->getResultType(), Fn, Args,
513*3385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
514*3385fe12SChris Lattner   EmitStmt(BExpr->getBody());
515*3385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
5166a60fa24SAnders Carlsson 
517b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
518b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
519b750d928SMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
520b750d928SMike Stump 
521cb2fbcb0SMike Stump   Size = BlockOffset;
522b750d928SMike Stump   Align = BlockAlign;
523b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
524cb2fbcb0SMike Stump 
5256a60fa24SAnders Carlsson   return Fn;
5266a60fa24SAnders Carlsson }
5271db7d04bSMike Stump 
5281db7d04bSMike Stump uint64_t CodeGenFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
5291db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
5301db7d04bSMike Stump 
5311db7d04bSMike Stump   uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
5321db7d04bSMike Stump   uint64_t Align = getContext().getDeclAlignInBytes(D);
5331db7d04bSMike Stump 
5341db7d04bSMike Stump   if (BDRE->isByRef()) {
5351db7d04bSMike Stump     Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
5361db7d04bSMike Stump     Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
5371db7d04bSMike Stump   }
5381db7d04bSMike Stump 
5391db7d04bSMike Stump   assert ((Align > 0) && "alignment must be 1 byte or more");
5401db7d04bSMike Stump 
5411db7d04bSMike Stump   uint64_t OldOffset = BlockOffset;
5421db7d04bSMike Stump 
5431db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
5441db7d04bSMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
5451db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
5461db7d04bSMike Stump 
5471db7d04bSMike Stump   uint64_t Pad = BlockOffset - OldOffset;
5481db7d04bSMike Stump   if (Pad) {
5491db7d04bSMike Stump     llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
5501db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
5511db7d04bSMike Stump                                                        llvm::APInt(32, Pad),
5521db7d04bSMike Stump                                                        ArrayType::Normal, 0);
5531db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
5541db7d04bSMike Stump                                          0, QualType(PadTy), VarDecl::None,
5551db7d04bSMike Stump                                          SourceLocation());
5561db7d04bSMike Stump     Expr *E;
5571db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
5581db7d04bSMike Stump                                        SourceLocation(), false, false);
5591db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
5601db7d04bSMike Stump   }
5611db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
5621db7d04bSMike Stump 
5631db7d04bSMike Stump   BlockOffset += Size;
5641db7d04bSMike Stump   return BlockOffset-Size;
5651db7d04bSMike Stump }
566