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)
114ed5e69feSAnders Carlsson     CollectBlockDeclRefInfo(*I, Info);
115ed5e69feSAnders Carlsson 
116ed5e69feSAnders Carlsson   if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
117ed5e69feSAnders Carlsson     // FIXME: Handle enums.
118ed5e69feSAnders Carlsson     if (isa<FunctionDecl>(DE->getDecl()))
119ed5e69feSAnders Carlsson       return;
120ed5e69feSAnders Carlsson 
121ed5e69feSAnders Carlsson     if (DE->isByRef())
122ed5e69feSAnders Carlsson       Info.ByRefDeclRefs.push_back(DE);
123ed5e69feSAnders Carlsson     else
124ed5e69feSAnders Carlsson       Info.ByCopyDeclRefs.push_back(DE);
125ed5e69feSAnders Carlsson   }
126ed5e69feSAnders Carlsson }
127ed5e69feSAnders Carlsson 
128ed5e69feSAnders Carlsson /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block
129ed5e69feSAnders Carlsson /// can be declared as a global variable instead of on the stack.
130ed5e69feSAnders Carlsson static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
131ed5e69feSAnders Carlsson {
132ed5e69feSAnders Carlsson   return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
133ed5e69feSAnders Carlsson }
134ed5e69feSAnders Carlsson 
135961763e3SAnders Carlsson /// CanGenerateCodeForBlockExpr - Returns whether CodeGen for the block expr
136961763e3SAnders Carlsson /// is supported. Will emit a diagnostic and return false if not.
137961763e3SAnders Carlsson /// FIXME: Once we support everything this should of course be removed.
138961763e3SAnders Carlsson static bool CanGenerateCodeForBlockExpr(CodeGenFunction &CGF,
139961763e3SAnders Carlsson                                         const BlockExpr* BE,
140961763e3SAnders Carlsson                                         const CodeGenFunction::BlockInfo &Info)
141961763e3SAnders Carlsson {
142961763e3SAnders Carlsson   if (!Info.ByRefDeclRefs.empty()) {
143961763e3SAnders Carlsson     CGF.ErrorUnsupported(BE, "block expression with __block variables");
144961763e3SAnders Carlsson     return false;
145961763e3SAnders Carlsson   }
146961763e3SAnders Carlsson 
147961763e3SAnders Carlsson   for (size_t I = 0, E = Info.ByCopyDeclRefs.size(); I != E; ++I) {
148961763e3SAnders Carlsson     const BlockDeclRefExpr *E = Info.ByCopyDeclRefs[I];
149961763e3SAnders Carlsson 
150961763e3SAnders Carlsson     if (E->getType()->isBlockPointerType()) {
151961763e3SAnders Carlsson       CGF.ErrorUnsupported(BE, "block expression with imported block");
152961763e3SAnders Carlsson       return false;
153961763e3SAnders Carlsson     }
154961763e3SAnders Carlsson 
155961763e3SAnders Carlsson     if (E->getDecl()->getAttr<ObjCNSObjectAttr>() ||
156961763e3SAnders Carlsson         CGF.getContext().isObjCNSObjectType(E->getType())) {
157961763e3SAnders Carlsson       CGF.ErrorUnsupported(BE, "block expression with __attribute__((NSObject))"
158961763e3SAnders Carlsson                            " variable");
159961763e3SAnders Carlsson       return false;
160961763e3SAnders Carlsson     }
161961763e3SAnders Carlsson 
162961763e3SAnders Carlsson     if (CGF.getContext().isObjCObjectPointerType(E->getType())) {
163961763e3SAnders Carlsson       CGF.ErrorUnsupported(BE, "block expression with Objective-C variable");
164961763e3SAnders Carlsson       return false;
165961763e3SAnders Carlsson     }
166961763e3SAnders Carlsson   }
167961763e3SAnders Carlsson 
168961763e3SAnders Carlsson   return true;
169961763e3SAnders Carlsson }
170961763e3SAnders Carlsson 
1715d2534adSMike Stump // FIXME: Push most into CGM, passing down a few bits, like current
1725d2534adSMike Stump // function name.
173b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
174ed5e69feSAnders Carlsson 
175ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
176ed5e69feSAnders Carlsson   CodeGenFunction::BlockInfo Info(0, Name.c_str());
177ed5e69feSAnders Carlsson   CollectBlockDeclRefInfo(BE->getBody(), Info);
178ed5e69feSAnders Carlsson 
179ed5e69feSAnders Carlsson   // Check if the block can be global.
180ed5e69feSAnders Carlsson   if (CanBlockBeGlobal(Info))
181ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
18285284bacSMike Stump 
183961763e3SAnders Carlsson   if (!CanGenerateCodeForBlockExpr(*this, BE, Info))
184961763e3SAnders Carlsson     return llvm::UndefValue::get(ConvertType(BE->getType()));
185961763e3SAnders Carlsson 
18685284bacSMike Stump   std::vector<llvm::Constant*> Elts;
18785284bacSMike Stump   llvm::Constant *C;
188b750d928SMike Stump   llvm::Value *V;
18985284bacSMike Stump 
19085284bacSMike Stump   {
19185284bacSMike Stump     // C = BuildBlockStructInitlist();
19285284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
19385284bacSMike Stump 
19485284bacSMike Stump     if (BlockHasCopyDispose)
19585284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
19685284bacSMike Stump 
197499ae7ecSMike Stump     // __isa
1987ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
1997ab278dbSMike Stump     const llvm::PointerType *PtrToInt8Ty
2007ab278dbSMike Stump       = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
20185284bacSMike Stump     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
20285284bacSMike Stump     Elts.push_back(C);
20385284bacSMike Stump 
20485284bacSMike Stump     // __flags
20585284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
20685284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
20785284bacSMike Stump     C = llvm::ConstantInt::get(IntTy, flags);
20885284bacSMike Stump     Elts.push_back(C);
20985284bacSMike Stump 
21085284bacSMike Stump     // __reserved
21185284bacSMike Stump     C = llvm::ConstantInt::get(IntTy, 0);
21285284bacSMike Stump     Elts.push_back(C);
21385284bacSMike Stump 
2145d2534adSMike Stump     // __invoke
215b750d928SMike Stump     uint64_t subBlockSize, subBlockAlign;
2161db7d04bSMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
217cb2fbcb0SMike Stump     llvm::Function *Fn
218b750d928SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
219b750d928SMike Stump                                                    subBlockAlign, subBlockDeclRefDecls);
2202d5a2878SMike Stump     Elts.push_back(Fn);
22185284bacSMike Stump 
22285284bacSMike Stump     // __descriptor
223cb2fbcb0SMike Stump     Elts.push_back(BuildDescriptorBlockDecl(subBlockSize));
22485284bacSMike Stump 
225b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
2263a139f37SMike Stump       // Optimize to being a global block.
2273a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
2283a139f37SMike Stump       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2293a139f37SMike Stump 
23085284bacSMike Stump       C = llvm::ConstantStruct::get(Elts);
23185284bacSMike Stump 
23285284bacSMike Stump       char Name[32];
2339319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
23485284bacSMike Stump       C = new llvm::GlobalVariable(C->getType(), true,
23585284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
23685284bacSMike Stump                                    C, Name, &CGM.getModule());
2375d2534adSMike Stump       QualType BPT = BE->getType();
2385d2534adSMike Stump       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
23985284bacSMike Stump       return C;
24085284bacSMike Stump     }
24185284bacSMike Stump 
242b750d928SMike Stump     std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
243b750d928SMike Stump     for (int i=0; i<5; ++i)
244b750d928SMike Stump       Types[i] = Elts[i]->getType();
24585284bacSMike Stump 
2461db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
2471db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
2481db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2491db7d04bSMike Stump       QualType Ty = E->getType();
2501db7d04bSMike Stump       if (BDRE && BDRE->isByRef())
2511db7d04bSMike Stump         Ty = getContext().getPointerType(Ty);
2521db7d04bSMike Stump       Types[i+5] = ConvertType(Ty);
2531db7d04bSMike Stump     }
254b750d928SMike Stump 
255b750d928SMike Stump     llvm::Type *Ty = llvm::StructType::get(Types, true);
256b750d928SMike Stump 
257b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
258b750d928SMike Stump     A->setAlignment(subBlockAlign);
259b750d928SMike Stump     V = A;
260b750d928SMike Stump 
261b750d928SMike Stump     for (unsigned i=0; i<5; ++i)
262b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
263b750d928SMike Stump 
264b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
265b750d928SMike Stump       {
2661db7d04bSMike Stump         // FIXME: Push const down.
2671db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2681db7d04bSMike Stump         DeclRefExpr *DR;
2691db7d04bSMike Stump         ValueDecl *VD;
270b750d928SMike Stump 
2711db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2721db7d04bSMike Stump         // Skip padding.
2731db7d04bSMike Stump         if (DR) continue;
2741db7d04bSMike Stump 
2751db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2761db7d04bSMike Stump         VD = BDRE->getDecl();
2771db7d04bSMike Stump 
2781db7d04bSMike Stump         // FIXME: I want a better way to do this.
2791db7d04bSMike Stump         if (LocalDeclMap[VD]) {
2801db7d04bSMike Stump           E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
2811db7d04bSMike Stump                                               VD->getType(), SourceLocation(),
2821db7d04bSMike Stump                                               false, false);
2831db7d04bSMike Stump         }
2841db7d04bSMike Stump         if (BDRE->isByRef())
2851db7d04bSMike Stump           E = new (getContext())
2861db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
2871db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
2881db7d04bSMike Stump                           SourceLocation());
2891db7d04bSMike Stump 
290b750d928SMike Stump         llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
2911db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
292b750d928SMike Stump         if (r.isScalar())
293b750d928SMike Stump           Builder.CreateStore(r.getScalarVal(), Addr);
294b750d928SMike Stump         else if (r.isComplex())
295b750d928SMike Stump           // FIXME: implement
296b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
297b750d928SMike Stump         else if (r.isAggregate())
298b750d928SMike Stump           ; // Already created into the destination
299b750d928SMike Stump         else
300b750d928SMike Stump           assert (0 && "bad block variable");
301b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
302b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
303b750d928SMike Stump       }
304b750d928SMike Stump   }
305b750d928SMike Stump 
306b750d928SMike Stump   QualType BPT = BE->getType();
307b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
308b750d928SMike Stump }
30985284bacSMike Stump 
31085284bacSMike Stump 
311650c932dSMike Stump const llvm::Type *CodeGenModule::getBlockDescriptorType() {
312650c932dSMike Stump   if (BlockDescriptorType)
313650c932dSMike Stump     return BlockDescriptorType;
3142437cbfaSAnders Carlsson 
3152437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
316650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3172437cbfaSAnders Carlsson 
3182437cbfaSAnders Carlsson   // struct __block_descriptor {
3192437cbfaSAnders Carlsson   //   unsigned long reserved;
3202437cbfaSAnders Carlsson   //   unsigned long block_size;
3212437cbfaSAnders Carlsson   // };
322650c932dSMike Stump   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
3232437cbfaSAnders Carlsson                                               UnsignedLongTy,
3242437cbfaSAnders Carlsson                                               NULL);
3252437cbfaSAnders Carlsson 
326650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
327650c932dSMike Stump                           BlockDescriptorType);
3282437cbfaSAnders Carlsson 
329650c932dSMike Stump   return BlockDescriptorType;
3302437cbfaSAnders Carlsson }
3312437cbfaSAnders Carlsson 
332005c9a62SMike Stump const llvm::Type *
333005c9a62SMike Stump CodeGenModule::getGenericBlockLiteralType() {
334005c9a62SMike Stump   if (GenericBlockLiteralType)
335005c9a62SMike Stump     return GenericBlockLiteralType;
3362437cbfaSAnders Carlsson 
3372437cbfaSAnders Carlsson   const llvm::Type *Int8PtrTy =
3382437cbfaSAnders Carlsson     llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3392437cbfaSAnders Carlsson 
3402437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
341005c9a62SMike Stump     llvm::PointerType::getUnqual(getBlockDescriptorType());
3422437cbfaSAnders Carlsson 
34392bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
34492bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
34592bbd6d4SMike Stump 
3462437cbfaSAnders Carlsson   // struct __block_literal_generic {
3475d2534adSMike Stump   //   void *__isa;
3485d2534adSMike Stump   //   int __flags;
3495d2534adSMike Stump   //   int __reserved;
3505d2534adSMike Stump   //   void (*__invoke)(void *);
3515d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3522437cbfaSAnders Carlsson   // };
353005c9a62SMike Stump   GenericBlockLiteralType = llvm::StructType::get(Int8PtrTy,
35492bbd6d4SMike Stump                                                   IntTy,
35592bbd6d4SMike Stump                                                   IntTy,
3562437cbfaSAnders Carlsson                                                   Int8PtrTy,
3572437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
3582437cbfaSAnders Carlsson                                                   NULL);
3592437cbfaSAnders Carlsson 
360005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
361005c9a62SMike Stump                           GenericBlockLiteralType);
3622437cbfaSAnders Carlsson 
363005c9a62SMike Stump   return GenericBlockLiteralType;
3642437cbfaSAnders Carlsson }
3652437cbfaSAnders Carlsson 
3665d2534adSMike Stump const llvm::Type *
3675d2534adSMike Stump CodeGenModule::getGenericExtendedBlockLiteralType() {
3685d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
3695d2534adSMike Stump     return GenericExtendedBlockLiteralType;
3705d2534adSMike Stump 
3715d2534adSMike Stump   const llvm::Type *Int8PtrTy =
3725d2534adSMike Stump     llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3735d2534adSMike Stump 
3745d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
3755d2534adSMike Stump     llvm::PointerType::getUnqual(getBlockDescriptorType());
3765d2534adSMike Stump 
3775d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
3785d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
3795d2534adSMike Stump 
3805d2534adSMike Stump   // struct __block_literal_generic {
3815d2534adSMike Stump   //   void *__isa;
3825d2534adSMike Stump   //   int __flags;
3835d2534adSMike Stump   //   int __reserved;
3845d2534adSMike Stump   //   void (*__invoke)(void *);
3855d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3865d2534adSMike Stump   //   void *__copy_func_helper_decl;
3875d2534adSMike Stump   //   void *__destroy_func_decl;
3885d2534adSMike Stump   // };
3895d2534adSMike Stump   GenericExtendedBlockLiteralType = llvm::StructType::get(Int8PtrTy,
3905d2534adSMike Stump                                                           IntTy,
3915d2534adSMike Stump                                                           IntTy,
3925d2534adSMike Stump                                                           Int8PtrTy,
3935d2534adSMike Stump                                                           BlockDescPtrTy,
3945d2534adSMike Stump                                                           Int8PtrTy,
3955d2534adSMike Stump                                                           Int8PtrTy,
3965d2534adSMike Stump                                                           NULL);
3975d2534adSMike Stump 
3985d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
3995d2534adSMike Stump                           GenericExtendedBlockLiteralType);
4005d2534adSMike Stump 
4015d2534adSMike Stump   return GenericExtendedBlockLiteralType;
4025d2534adSMike Stump }
4035d2534adSMike Stump 
4042437cbfaSAnders Carlsson /// getBlockFunctionType - Given a BlockPointerType, will return the
4052437cbfaSAnders Carlsson /// function type for the block, including the first block literal argument.
4062437cbfaSAnders Carlsson static QualType getBlockFunctionType(ASTContext &Ctx,
4076a60fa24SAnders Carlsson                                      const BlockPointerType *BPT) {
408deaad8ccSDouglas Gregor   const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
4092437cbfaSAnders Carlsson 
4102437cbfaSAnders Carlsson   llvm::SmallVector<QualType, 8> Types;
4112437cbfaSAnders Carlsson   Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
4122437cbfaSAnders Carlsson 
413deaad8ccSDouglas Gregor   for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
4142437cbfaSAnders Carlsson        e = FTy->arg_type_end(); i != e; ++i)
4152437cbfaSAnders Carlsson     Types.push_back(*i);
4162437cbfaSAnders Carlsson 
4172437cbfaSAnders Carlsson   return Ctx.getFunctionType(FTy->getResultType(),
4182437cbfaSAnders Carlsson                              &Types[0], Types.size(),
4192437cbfaSAnders Carlsson                              FTy->isVariadic(), 0);
4202437cbfaSAnders Carlsson }
4212437cbfaSAnders Carlsson 
4226a60fa24SAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
4232437cbfaSAnders Carlsson   const BlockPointerType *BPT =
4242437cbfaSAnders Carlsson     E->getCallee()->getType()->getAsBlockPointerType();
4252437cbfaSAnders Carlsson 
4262437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
4272437cbfaSAnders Carlsson 
4282437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
4292437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
430005c9a62SMike Stump     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
4312437cbfaSAnders Carlsson 
4322437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
4332437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
4342437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4352437cbfaSAnders Carlsson 
4362437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4372437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
438624497c2SMike Stump   llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
4392437cbfaSAnders Carlsson 
4402437cbfaSAnders Carlsson   // Cast the function pointer to the right type.
4412437cbfaSAnders Carlsson   const llvm::Type *BlockFTy =
4422437cbfaSAnders Carlsson     ConvertType(getBlockFunctionType(getContext(), BPT));
4432437cbfaSAnders Carlsson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
4442437cbfaSAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
4452437cbfaSAnders Carlsson 
4462437cbfaSAnders Carlsson   BlockLiteral =
4472437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
4482437cbfaSAnders Carlsson                           llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
4492437cbfaSAnders Carlsson                           "tmp");
4502437cbfaSAnders Carlsson 
4512437cbfaSAnders Carlsson   // Add the block literal.
4522437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4532437cbfaSAnders Carlsson   CallArgList Args;
4542437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4552437cbfaSAnders Carlsson 
4562437cbfaSAnders Carlsson   // And the rest of the arguments.
4572437cbfaSAnders Carlsson   for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
4582437cbfaSAnders Carlsson        i != e; ++i)
4592437cbfaSAnders Carlsson     Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
4602437cbfaSAnders Carlsson                                   i->getType()));
4612437cbfaSAnders Carlsson 
4622437cbfaSAnders Carlsson   // And call the block.
4632437cbfaSAnders Carlsson   return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
4642437cbfaSAnders Carlsson                   Func, Args);
4652437cbfaSAnders Carlsson }
4666a60fa24SAnders Carlsson 
4672d5a2878SMike Stump llvm::Constant *
4680e7d7b68SMike Stump CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
4696a60fa24SAnders Carlsson   // Generate the block descriptor.
4706a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
47192bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
47292bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
4736a60fa24SAnders Carlsson 
4746a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
4756a60fa24SAnders Carlsson 
4766a60fa24SAnders Carlsson   // Reserved
4776a60fa24SAnders Carlsson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
4786a60fa24SAnders Carlsson 
4796a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
4806a60fa24SAnders Carlsson   // block literal struct.
4816a60fa24SAnders Carlsson   uint64_t BlockLiteralSize =
482005c9a62SMike Stump     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
4836a60fa24SAnders Carlsson   DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
4846a60fa24SAnders Carlsson 
4856a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
4866a60fa24SAnders Carlsson     llvm::ConstantStruct::get(&DescriptorFields[0], 2);
4876a60fa24SAnders Carlsson 
4886a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
4896a60fa24SAnders Carlsson     new llvm::GlobalVariable(DescriptorStruct->getType(), true,
4906a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
4916a60fa24SAnders Carlsson                              DescriptorStruct, "__block_descriptor_global",
4926a60fa24SAnders Carlsson                              &getModule());
4936a60fa24SAnders Carlsson 
4946a60fa24SAnders Carlsson   // Generate the constants for the block literal.
4956a60fa24SAnders Carlsson   llvm::Constant *LiteralFields[5];
4966a60fa24SAnders Carlsson 
4972d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
498b750d928SMike Stump   uint64_t subBlockSize, subBlockAlign;
4991db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
500cb2fbcb0SMike Stump   llvm::Function *Fn
501b750d928SMike Stump     = CodeGenFunction(*this).GenerateBlockFunction(BE, Info, subBlockSize,
502b750d928SMike Stump                                                    subBlockAlign,
503b750d928SMike Stump                                                    subBlockDeclRefDecls);
504cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
505cb2fbcb0SMike Stump          && "no imports allowed for global block");
5066a60fa24SAnders Carlsson 
5076a60fa24SAnders Carlsson   // isa
508971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
5096a60fa24SAnders Carlsson 
5106a60fa24SAnders Carlsson   // Flags
511*5878c797SAnders Carlsson   LiteralFields[1] =
512*5878c797SAnders Carlsson     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
5136a60fa24SAnders Carlsson 
5146a60fa24SAnders Carlsson   // Reserved
51592bbd6d4SMike Stump   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
5166a60fa24SAnders Carlsson 
5176a60fa24SAnders Carlsson   // Function
5186a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
5196a60fa24SAnders Carlsson 
5206a60fa24SAnders Carlsson   // Descriptor
5216a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
5226a60fa24SAnders Carlsson 
5236a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
5246a60fa24SAnders Carlsson     llvm::ConstantStruct::get(&LiteralFields[0], 5);
5256a60fa24SAnders Carlsson 
5266a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
5276a60fa24SAnders Carlsson     new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
5286a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
5296a60fa24SAnders Carlsson                              BlockLiteralStruct, "__block_literal_global",
5306a60fa24SAnders Carlsson                              &getModule());
5316a60fa24SAnders Carlsson 
5326a60fa24SAnders Carlsson   return BlockLiteral;
5336a60fa24SAnders Carlsson }
5346a60fa24SAnders Carlsson 
535cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
536cb2fbcb0SMike Stump   return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
537cb2fbcb0SMike Stump }
538cb2fbcb0SMike Stump 
5393385fe12SChris Lattner llvm::Function *CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
540cb2fbcb0SMike Stump                                                        const BlockInfo& Info,
541b750d928SMike Stump                                                        uint64_t &Size,
542b750d928SMike Stump                                                        uint64_t &Align,
5431db7d04bSMike Stump                          llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls) {
544deaad8ccSDouglas Gregor   const FunctionProtoType *FTy =
5453385fe12SChris Lattner     cast<FunctionProtoType>(BExpr->getFunctionType());
5466a60fa24SAnders Carlsson 
5476a60fa24SAnders Carlsson   FunctionArgList Args;
5486a60fa24SAnders Carlsson 
5493385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
5506a60fa24SAnders Carlsson 
5516a60fa24SAnders Carlsson   // FIXME: This leaks
5526a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
5536a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
5546a60fa24SAnders Carlsson                               SourceLocation(), 0,
5556a60fa24SAnders Carlsson                               getContext().getPointerType(getContext().VoidTy));
5566a60fa24SAnders Carlsson 
5576a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
558cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
5596a60fa24SAnders Carlsson 
5606a60fa24SAnders Carlsson   for (BlockDecl::param_iterator i = BD->param_begin(),
5616a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
562eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
5636a60fa24SAnders Carlsson 
5646a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
5656a60fa24SAnders Carlsson     CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
5666a60fa24SAnders Carlsson 
5672d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
5686a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
5696a60fa24SAnders Carlsson   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
5706a60fa24SAnders Carlsson 
5716a60fa24SAnders Carlsson   llvm::Function *Fn =
5726a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
5736a60fa24SAnders Carlsson                            Name,
5746a60fa24SAnders Carlsson                            &CGM.getModule());
5756a60fa24SAnders Carlsson 
5766a60fa24SAnders Carlsson   StartFunction(BD, FTy->getResultType(), Fn, Args,
5773385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
5783385fe12SChris Lattner   EmitStmt(BExpr->getBody());
5793385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
5806a60fa24SAnders Carlsson 
581b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
582b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
583b750d928SMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
584b750d928SMike Stump 
585cb2fbcb0SMike Stump   Size = BlockOffset;
586b750d928SMike Stump   Align = BlockAlign;
587b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
588cb2fbcb0SMike Stump 
5896a60fa24SAnders Carlsson   return Fn;
5906a60fa24SAnders Carlsson }
5911db7d04bSMike Stump 
5921db7d04bSMike Stump uint64_t CodeGenFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
5931db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
5941db7d04bSMike Stump 
5951db7d04bSMike Stump   uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
5961db7d04bSMike Stump   uint64_t Align = getContext().getDeclAlignInBytes(D);
5971db7d04bSMike Stump 
5981db7d04bSMike Stump   if (BDRE->isByRef()) {
5991db7d04bSMike Stump     Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
6001db7d04bSMike Stump     Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
6011db7d04bSMike Stump   }
6021db7d04bSMike Stump 
6031db7d04bSMike Stump   assert ((Align > 0) && "alignment must be 1 byte or more");
6041db7d04bSMike Stump 
6051db7d04bSMike Stump   uint64_t OldOffset = BlockOffset;
6061db7d04bSMike Stump 
6071db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
6081db7d04bSMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
6091db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
6101db7d04bSMike Stump 
6111db7d04bSMike Stump   uint64_t Pad = BlockOffset - OldOffset;
6121db7d04bSMike Stump   if (Pad) {
6131db7d04bSMike Stump     llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
6141db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
6151db7d04bSMike Stump                                                        llvm::APInt(32, Pad),
6161db7d04bSMike Stump                                                        ArrayType::Normal, 0);
6171db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
6181db7d04bSMike Stump                                          0, QualType(PadTy), VarDecl::None,
6191db7d04bSMike Stump                                          SourceLocation());
6201db7d04bSMike Stump     Expr *E;
6211db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
6221db7d04bSMike Stump                                        SourceLocation(), false, false);
6231db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
6241db7d04bSMike Stump   }
6251db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
6261db7d04bSMike Stump 
6271db7d04bSMike Stump   BlockOffset += Size;
6281db7d04bSMike Stump   return BlockOffset-Size;
6291db7d04bSMike Stump }
630