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 
110ed5e69feSAnders Carlsson static void CollectBlockDeclRefInfo(const Stmt *S,
111ed5e69feSAnders Carlsson                                     CodeGenFunction::BlockInfo &Info) {
112ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
113ed5e69feSAnders Carlsson        I != E; ++I)
114*dd942713SDaniel Dunbar     if (*I)
115ed5e69feSAnders Carlsson       CollectBlockDeclRefInfo(*I, Info);
116ed5e69feSAnders Carlsson 
117ed5e69feSAnders Carlsson   if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
118ed5e69feSAnders Carlsson     // FIXME: Handle enums.
119ed5e69feSAnders Carlsson     if (isa<FunctionDecl>(DE->getDecl()))
120ed5e69feSAnders Carlsson       return;
121ed5e69feSAnders Carlsson 
122ed5e69feSAnders Carlsson     if (DE->isByRef())
123ed5e69feSAnders Carlsson       Info.ByRefDeclRefs.push_back(DE);
124ed5e69feSAnders Carlsson     else
125ed5e69feSAnders Carlsson       Info.ByCopyDeclRefs.push_back(DE);
126ed5e69feSAnders Carlsson   }
127ed5e69feSAnders Carlsson }
128ed5e69feSAnders Carlsson 
129ed5e69feSAnders Carlsson /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block
130ed5e69feSAnders Carlsson /// can be declared as a global variable instead of on the stack.
131ed5e69feSAnders Carlsson static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
132ed5e69feSAnders Carlsson {
133ed5e69feSAnders Carlsson   return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
134ed5e69feSAnders Carlsson }
135ed5e69feSAnders Carlsson 
1365d2534adSMike Stump // FIXME: Push most into CGM, passing down a few bits, like current
1375d2534adSMike Stump // function name.
138b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
139ed5e69feSAnders Carlsson 
140ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
141ed5e69feSAnders Carlsson   CodeGenFunction::BlockInfo Info(0, Name.c_str());
142ed5e69feSAnders Carlsson   CollectBlockDeclRefInfo(BE->getBody(), Info);
143ed5e69feSAnders Carlsson 
144ed5e69feSAnders Carlsson   // Check if the block can be global.
145ed5e69feSAnders Carlsson   if (CanBlockBeGlobal(Info))
146ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
14785284bacSMike Stump 
14885284bacSMike Stump   std::vector<llvm::Constant*> Elts;
14985284bacSMike Stump   llvm::Constant *C;
150b750d928SMike Stump   llvm::Value *V;
15185284bacSMike Stump 
15285284bacSMike Stump   {
15385284bacSMike Stump     // C = BuildBlockStructInitlist();
15485284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
15585284bacSMike Stump 
15685284bacSMike Stump     if (BlockHasCopyDispose)
15785284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
15885284bacSMike Stump 
159499ae7ecSMike Stump     // __isa
1607ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
1617ab278dbSMike Stump     const llvm::PointerType *PtrToInt8Ty
1627ab278dbSMike Stump       = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
16385284bacSMike Stump     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
16485284bacSMike Stump     Elts.push_back(C);
16585284bacSMike Stump 
16685284bacSMike Stump     // __flags
16785284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
16885284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
16985284bacSMike Stump     C = llvm::ConstantInt::get(IntTy, flags);
17085284bacSMike Stump     Elts.push_back(C);
17185284bacSMike Stump 
17285284bacSMike Stump     // __reserved
17385284bacSMike Stump     C = llvm::ConstantInt::get(IntTy, 0);
17485284bacSMike Stump     Elts.push_back(C);
17585284bacSMike Stump 
1765d2534adSMike Stump     // __invoke
177b750d928SMike Stump     uint64_t subBlockSize, subBlockAlign;
1781db7d04bSMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
179cb2fbcb0SMike Stump     llvm::Function *Fn
180b750d928SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
181b750d928SMike Stump                                                    subBlockAlign, subBlockDeclRefDecls);
1822d5a2878SMike Stump     Elts.push_back(Fn);
18385284bacSMike Stump 
18485284bacSMike Stump     // __descriptor
185cb2fbcb0SMike Stump     Elts.push_back(BuildDescriptorBlockDecl(subBlockSize));
18685284bacSMike Stump 
187b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
1883a139f37SMike Stump       // Optimize to being a global block.
1893a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
1903a139f37SMike Stump       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
1913a139f37SMike Stump 
19285284bacSMike Stump       C = llvm::ConstantStruct::get(Elts);
19385284bacSMike Stump 
19485284bacSMike Stump       char Name[32];
1959319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
19685284bacSMike Stump       C = new llvm::GlobalVariable(C->getType(), true,
19785284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
19885284bacSMike Stump                                    C, Name, &CGM.getModule());
1995d2534adSMike Stump       QualType BPT = BE->getType();
2005d2534adSMike Stump       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
20185284bacSMike Stump       return C;
20285284bacSMike Stump     }
20385284bacSMike Stump 
204b750d928SMike Stump     std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
205b750d928SMike Stump     for (int i=0; i<5; ++i)
206b750d928SMike Stump       Types[i] = Elts[i]->getType();
20785284bacSMike Stump 
2081db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
2091db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
2101db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2111db7d04bSMike Stump       QualType Ty = E->getType();
2121db7d04bSMike Stump       if (BDRE && BDRE->isByRef())
2131db7d04bSMike Stump         Ty = getContext().getPointerType(Ty);
2141db7d04bSMike Stump       Types[i+5] = ConvertType(Ty);
2151db7d04bSMike Stump     }
216b750d928SMike Stump 
217b750d928SMike Stump     llvm::Type *Ty = llvm::StructType::get(Types, true);
218b750d928SMike Stump 
219b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
220b750d928SMike Stump     A->setAlignment(subBlockAlign);
221b750d928SMike Stump     V = A;
222b750d928SMike Stump 
223b750d928SMike Stump     for (unsigned i=0; i<5; ++i)
224b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
225b750d928SMike Stump 
226b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
227b750d928SMike Stump       {
2281db7d04bSMike Stump         // FIXME: Push const down.
2291db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2301db7d04bSMike Stump         DeclRefExpr *DR;
2311db7d04bSMike Stump         ValueDecl *VD;
232b750d928SMike Stump 
2331db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2341db7d04bSMike Stump         // Skip padding.
2351db7d04bSMike Stump         if (DR) continue;
2361db7d04bSMike Stump 
2371db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2381db7d04bSMike Stump         VD = BDRE->getDecl();
2391db7d04bSMike Stump 
2401db7d04bSMike Stump         // FIXME: I want a better way to do this.
2411db7d04bSMike Stump         if (LocalDeclMap[VD]) {
2421db7d04bSMike Stump           E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
2431db7d04bSMike Stump                                               VD->getType(), SourceLocation(),
2441db7d04bSMike Stump                                               false, false);
2451db7d04bSMike Stump         }
2461db7d04bSMike Stump         if (BDRE->isByRef())
2471db7d04bSMike Stump           E = new (getContext())
2481db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
2491db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
2501db7d04bSMike Stump                           SourceLocation());
2511db7d04bSMike Stump 
252b750d928SMike Stump         llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
2531db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
254b750d928SMike Stump         if (r.isScalar())
255b750d928SMike Stump           Builder.CreateStore(r.getScalarVal(), Addr);
256b750d928SMike Stump         else if (r.isComplex())
257b750d928SMike Stump           // FIXME: implement
258b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
259b750d928SMike Stump         else if (r.isAggregate())
260b750d928SMike Stump           ; // Already created into the destination
261b750d928SMike Stump         else
262b750d928SMike Stump           assert (0 && "bad block variable");
263b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
264b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
265b750d928SMike Stump       }
266b750d928SMike Stump   }
267b750d928SMike Stump 
268b750d928SMike Stump   QualType BPT = BE->getType();
269b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
270b750d928SMike Stump }
27185284bacSMike Stump 
27285284bacSMike Stump 
273650c932dSMike Stump const llvm::Type *CodeGenModule::getBlockDescriptorType() {
274650c932dSMike Stump   if (BlockDescriptorType)
275650c932dSMike Stump     return BlockDescriptorType;
2762437cbfaSAnders Carlsson 
2772437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
278650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
2792437cbfaSAnders Carlsson 
2802437cbfaSAnders Carlsson   // struct __block_descriptor {
2812437cbfaSAnders Carlsson   //   unsigned long reserved;
2822437cbfaSAnders Carlsson   //   unsigned long block_size;
2832437cbfaSAnders Carlsson   // };
284650c932dSMike Stump   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
2852437cbfaSAnders Carlsson                                               UnsignedLongTy,
2862437cbfaSAnders Carlsson                                               NULL);
2872437cbfaSAnders Carlsson 
288650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
289650c932dSMike Stump                           BlockDescriptorType);
2902437cbfaSAnders Carlsson 
291650c932dSMike Stump   return BlockDescriptorType;
2922437cbfaSAnders Carlsson }
2932437cbfaSAnders Carlsson 
294005c9a62SMike Stump const llvm::Type *
295005c9a62SMike Stump CodeGenModule::getGenericBlockLiteralType() {
296005c9a62SMike Stump   if (GenericBlockLiteralType)
297005c9a62SMike Stump     return GenericBlockLiteralType;
2982437cbfaSAnders Carlsson 
2992437cbfaSAnders Carlsson   const llvm::Type *Int8PtrTy =
3002437cbfaSAnders Carlsson     llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3012437cbfaSAnders Carlsson 
3022437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
303005c9a62SMike Stump     llvm::PointerType::getUnqual(getBlockDescriptorType());
3042437cbfaSAnders Carlsson 
30592bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
30692bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
30792bbd6d4SMike Stump 
3082437cbfaSAnders Carlsson   // struct __block_literal_generic {
3095d2534adSMike Stump   //   void *__isa;
3105d2534adSMike Stump   //   int __flags;
3115d2534adSMike Stump   //   int __reserved;
3125d2534adSMike Stump   //   void (*__invoke)(void *);
3135d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3142437cbfaSAnders Carlsson   // };
315005c9a62SMike Stump   GenericBlockLiteralType = llvm::StructType::get(Int8PtrTy,
31692bbd6d4SMike Stump                                                   IntTy,
31792bbd6d4SMike Stump                                                   IntTy,
3182437cbfaSAnders Carlsson                                                   Int8PtrTy,
3192437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
3202437cbfaSAnders Carlsson                                                   NULL);
3212437cbfaSAnders Carlsson 
322005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
323005c9a62SMike Stump                           GenericBlockLiteralType);
3242437cbfaSAnders Carlsson 
325005c9a62SMike Stump   return GenericBlockLiteralType;
3262437cbfaSAnders Carlsson }
3272437cbfaSAnders Carlsson 
3285d2534adSMike Stump const llvm::Type *
3295d2534adSMike Stump CodeGenModule::getGenericExtendedBlockLiteralType() {
3305d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
3315d2534adSMike Stump     return GenericExtendedBlockLiteralType;
3325d2534adSMike Stump 
3335d2534adSMike Stump   const llvm::Type *Int8PtrTy =
3345d2534adSMike Stump     llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3355d2534adSMike Stump 
3365d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
3375d2534adSMike Stump     llvm::PointerType::getUnqual(getBlockDescriptorType());
3385d2534adSMike Stump 
3395d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
3405d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
3415d2534adSMike Stump 
3425d2534adSMike Stump   // struct __block_literal_generic {
3435d2534adSMike Stump   //   void *__isa;
3445d2534adSMike Stump   //   int __flags;
3455d2534adSMike Stump   //   int __reserved;
3465d2534adSMike Stump   //   void (*__invoke)(void *);
3475d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3485d2534adSMike Stump   //   void *__copy_func_helper_decl;
3495d2534adSMike Stump   //   void *__destroy_func_decl;
3505d2534adSMike Stump   // };
3515d2534adSMike Stump   GenericExtendedBlockLiteralType = llvm::StructType::get(Int8PtrTy,
3525d2534adSMike Stump                                                           IntTy,
3535d2534adSMike Stump                                                           IntTy,
3545d2534adSMike Stump                                                           Int8PtrTy,
3555d2534adSMike Stump                                                           BlockDescPtrTy,
3565d2534adSMike Stump                                                           Int8PtrTy,
3575d2534adSMike Stump                                                           Int8PtrTy,
3585d2534adSMike Stump                                                           NULL);
3595d2534adSMike Stump 
3605d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
3615d2534adSMike Stump                           GenericExtendedBlockLiteralType);
3625d2534adSMike Stump 
3635d2534adSMike Stump   return GenericExtendedBlockLiteralType;
3645d2534adSMike Stump }
3655d2534adSMike Stump 
3662437cbfaSAnders Carlsson /// getBlockFunctionType - Given a BlockPointerType, will return the
3672437cbfaSAnders Carlsson /// function type for the block, including the first block literal argument.
3682437cbfaSAnders Carlsson static QualType getBlockFunctionType(ASTContext &Ctx,
3696a60fa24SAnders Carlsson                                      const BlockPointerType *BPT) {
370deaad8ccSDouglas Gregor   const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
3712437cbfaSAnders Carlsson 
3722437cbfaSAnders Carlsson   llvm::SmallVector<QualType, 8> Types;
3732437cbfaSAnders Carlsson   Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
3742437cbfaSAnders Carlsson 
375deaad8ccSDouglas Gregor   for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
3762437cbfaSAnders Carlsson        e = FTy->arg_type_end(); i != e; ++i)
3772437cbfaSAnders Carlsson     Types.push_back(*i);
3782437cbfaSAnders Carlsson 
3792437cbfaSAnders Carlsson   return Ctx.getFunctionType(FTy->getResultType(),
3802437cbfaSAnders Carlsson                              &Types[0], Types.size(),
3812437cbfaSAnders Carlsson                              FTy->isVariadic(), 0);
3822437cbfaSAnders Carlsson }
3832437cbfaSAnders Carlsson 
3846a60fa24SAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
3852437cbfaSAnders Carlsson   const BlockPointerType *BPT =
3862437cbfaSAnders Carlsson     E->getCallee()->getType()->getAsBlockPointerType();
3872437cbfaSAnders Carlsson 
3882437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
3892437cbfaSAnders Carlsson 
3902437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
3912437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
392005c9a62SMike Stump     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
3932437cbfaSAnders Carlsson 
3942437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
3952437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
3962437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
3972437cbfaSAnders Carlsson 
3982437cbfaSAnders Carlsson   // Get the function pointer from the literal.
3992437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
400624497c2SMike Stump   llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
4012437cbfaSAnders Carlsson 
4022437cbfaSAnders Carlsson   // Cast the function pointer to the right type.
4032437cbfaSAnders Carlsson   const llvm::Type *BlockFTy =
4042437cbfaSAnders Carlsson     ConvertType(getBlockFunctionType(getContext(), BPT));
4052437cbfaSAnders Carlsson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
4062437cbfaSAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
4072437cbfaSAnders Carlsson 
4082437cbfaSAnders Carlsson   BlockLiteral =
4092437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
4102437cbfaSAnders Carlsson                           llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
4112437cbfaSAnders Carlsson                           "tmp");
4122437cbfaSAnders Carlsson 
4132437cbfaSAnders Carlsson   // Add the block literal.
4142437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4152437cbfaSAnders Carlsson   CallArgList Args;
4162437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4172437cbfaSAnders Carlsson 
4182437cbfaSAnders Carlsson   // And the rest of the arguments.
4192437cbfaSAnders Carlsson   for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
4202437cbfaSAnders Carlsson        i != e; ++i)
4212437cbfaSAnders Carlsson     Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
4222437cbfaSAnders Carlsson                                   i->getType()));
4232437cbfaSAnders Carlsson 
4242437cbfaSAnders Carlsson   // And call the block.
4252437cbfaSAnders Carlsson   return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
4262437cbfaSAnders Carlsson                   Func, Args);
4272437cbfaSAnders Carlsson }
4286a60fa24SAnders Carlsson 
4292d5a2878SMike Stump llvm::Constant *
4300e7d7b68SMike Stump CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
4316a60fa24SAnders Carlsson   // Generate the block descriptor.
4326a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
43392bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
43492bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
4356a60fa24SAnders Carlsson 
4366a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
4376a60fa24SAnders Carlsson 
4386a60fa24SAnders Carlsson   // Reserved
4396a60fa24SAnders Carlsson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
4406a60fa24SAnders Carlsson 
4416a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
4426a60fa24SAnders Carlsson   // block literal struct.
4436a60fa24SAnders Carlsson   uint64_t BlockLiteralSize =
444005c9a62SMike Stump     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
4456a60fa24SAnders Carlsson   DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
4466a60fa24SAnders Carlsson 
4476a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
4486a60fa24SAnders Carlsson     llvm::ConstantStruct::get(&DescriptorFields[0], 2);
4496a60fa24SAnders Carlsson 
4506a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
4516a60fa24SAnders Carlsson     new llvm::GlobalVariable(DescriptorStruct->getType(), true,
4526a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
4536a60fa24SAnders Carlsson                              DescriptorStruct, "__block_descriptor_global",
4546a60fa24SAnders Carlsson                              &getModule());
4556a60fa24SAnders Carlsson 
4566a60fa24SAnders Carlsson   // Generate the constants for the block literal.
4576a60fa24SAnders Carlsson   llvm::Constant *LiteralFields[5];
4586a60fa24SAnders Carlsson 
4592d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
460b750d928SMike Stump   uint64_t subBlockSize, subBlockAlign;
4611db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
462cb2fbcb0SMike Stump   llvm::Function *Fn
463b750d928SMike Stump     = CodeGenFunction(*this).GenerateBlockFunction(BE, Info, subBlockSize,
464b750d928SMike Stump                                                    subBlockAlign,
465b750d928SMike Stump                                                    subBlockDeclRefDecls);
466cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
467cb2fbcb0SMike Stump          && "no imports allowed for global block");
4686a60fa24SAnders Carlsson 
4696a60fa24SAnders Carlsson   // isa
470971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
4716a60fa24SAnders Carlsson 
4726a60fa24SAnders Carlsson   // Flags
4735878c797SAnders Carlsson   LiteralFields[1] =
4745878c797SAnders Carlsson     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
4756a60fa24SAnders Carlsson 
4766a60fa24SAnders Carlsson   // Reserved
47792bbd6d4SMike Stump   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
4786a60fa24SAnders Carlsson 
4796a60fa24SAnders Carlsson   // Function
4806a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
4816a60fa24SAnders Carlsson 
4826a60fa24SAnders Carlsson   // Descriptor
4836a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
4846a60fa24SAnders Carlsson 
4856a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
4866a60fa24SAnders Carlsson     llvm::ConstantStruct::get(&LiteralFields[0], 5);
4876a60fa24SAnders Carlsson 
4886a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
4896a60fa24SAnders Carlsson     new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
4906a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
4916a60fa24SAnders Carlsson                              BlockLiteralStruct, "__block_literal_global",
4926a60fa24SAnders Carlsson                              &getModule());
4936a60fa24SAnders Carlsson 
4946a60fa24SAnders Carlsson   return BlockLiteral;
4956a60fa24SAnders Carlsson }
4966a60fa24SAnders Carlsson 
497cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
498cb2fbcb0SMike Stump   return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
499cb2fbcb0SMike Stump }
500cb2fbcb0SMike Stump 
5013385fe12SChris Lattner llvm::Function *CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
502cb2fbcb0SMike Stump                                                        const BlockInfo& Info,
503b750d928SMike Stump                                                        uint64_t &Size,
504b750d928SMike Stump                                                        uint64_t &Align,
5051db7d04bSMike Stump                          llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls) {
506deaad8ccSDouglas Gregor   const FunctionProtoType *FTy =
5073385fe12SChris Lattner     cast<FunctionProtoType>(BExpr->getFunctionType());
5086a60fa24SAnders Carlsson 
5096a60fa24SAnders Carlsson   FunctionArgList Args;
5106a60fa24SAnders Carlsson 
5113385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
5126a60fa24SAnders Carlsson 
5136a60fa24SAnders Carlsson   // FIXME: This leaks
5146a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
5156a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
5166a60fa24SAnders Carlsson                               SourceLocation(), 0,
5176a60fa24SAnders Carlsson                               getContext().getPointerType(getContext().VoidTy));
5186a60fa24SAnders Carlsson 
5196a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
520cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
5216a60fa24SAnders Carlsson 
5226a60fa24SAnders Carlsson   for (BlockDecl::param_iterator i = BD->param_begin(),
5236a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
524eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
5256a60fa24SAnders Carlsson 
5266a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
5276a60fa24SAnders Carlsson     CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
5286a60fa24SAnders Carlsson 
5292d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
5306a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
5316a60fa24SAnders Carlsson   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
5326a60fa24SAnders Carlsson 
5336a60fa24SAnders Carlsson   llvm::Function *Fn =
5346a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
5356a60fa24SAnders Carlsson                            Name,
5366a60fa24SAnders Carlsson                            &CGM.getModule());
5376a60fa24SAnders Carlsson 
5386a60fa24SAnders Carlsson   StartFunction(BD, FTy->getResultType(), Fn, Args,
5393385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
5403385fe12SChris Lattner   EmitStmt(BExpr->getBody());
5413385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
5426a60fa24SAnders Carlsson 
543b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
544b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
545b750d928SMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
546b750d928SMike Stump 
547cb2fbcb0SMike Stump   Size = BlockOffset;
548b750d928SMike Stump   Align = BlockAlign;
549b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
550cb2fbcb0SMike Stump 
5516a60fa24SAnders Carlsson   return Fn;
5526a60fa24SAnders Carlsson }
5531db7d04bSMike Stump 
5541db7d04bSMike Stump uint64_t CodeGenFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
5551db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
5561db7d04bSMike Stump 
5571db7d04bSMike Stump   uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
5581db7d04bSMike Stump   uint64_t Align = getContext().getDeclAlignInBytes(D);
5591db7d04bSMike Stump 
5601db7d04bSMike Stump   if (BDRE->isByRef()) {
5611db7d04bSMike Stump     Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
5621db7d04bSMike Stump     Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
5631db7d04bSMike Stump   }
5641db7d04bSMike Stump 
5651db7d04bSMike Stump   assert ((Align > 0) && "alignment must be 1 byte or more");
5661db7d04bSMike Stump 
5671db7d04bSMike Stump   uint64_t OldOffset = BlockOffset;
5681db7d04bSMike Stump 
5691db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
5701db7d04bSMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
5711db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
5721db7d04bSMike Stump 
5731db7d04bSMike Stump   uint64_t Pad = BlockOffset - OldOffset;
5741db7d04bSMike Stump   if (Pad) {
5751db7d04bSMike Stump     llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
5761db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
5771db7d04bSMike Stump                                                        llvm::APInt(32, Pad),
5781db7d04bSMike Stump                                                        ArrayType::Normal, 0);
5791db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
5801db7d04bSMike Stump                                          0, QualType(PadTy), VarDecl::None,
5811db7d04bSMike Stump                                          SourceLocation());
5821db7d04bSMike Stump     Expr *E;
5831db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
5841db7d04bSMike Stump                                        SourceLocation(), false, false);
5851db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
5861db7d04bSMike Stump   }
5871db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
5881db7d04bSMike Stump 
5891db7d04bSMike Stump   BlockOffset += Size;
5901db7d04bSMike Stump   return BlockOffset-Size;
5911db7d04bSMike Stump }
592