]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.cpp
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / CodeGen / CGObjCRuntime.cpp
1 //==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This abstract class defines the interface for Objective-C runtime-specific
11 // code generation.  It provides some concrete helper methods for functionality
12 // shared between all (or most) of the Objective-C runtimes supported by clang.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "CGObjCRuntime.h"
17
18 #include "CGRecordLayout.h"
19 #include "CodeGenModule.h"
20 #include "CodeGenFunction.h"
21 #include "CGCleanup.h"
22
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtObjC.h"
25
26 #include "llvm/Support/CallSite.h"
27
28 using namespace clang;
29 using namespace CodeGen;
30
31 static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
32                                      const ObjCInterfaceDecl *OID,
33                                      const ObjCImplementationDecl *ID,
34                                      const ObjCIvarDecl *Ivar) {
35   const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
36
37   // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
38   // in here; it should never be necessary because that should be the lexical
39   // decl context for the ivar.
40
41   // If we know have an implementation (and the ivar is in it) then
42   // look up in the implementation layout.
43   const ASTRecordLayout *RL;
44   if (ID && ID->getClassInterface() == Container)
45     RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
46   else
47     RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
48
49   // Compute field index.
50   //
51   // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
52   // implemented. This should be fixed to get the information from the layout
53   // directly.
54   unsigned Index = 0;
55   ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl*>(Container);
56
57   for (ObjCIvarDecl *IVD = IDecl->all_declared_ivar_begin(); 
58        IVD; IVD = IVD->getNextIvar()) {
59     if (Ivar == IVD)
60       break;
61     ++Index;
62   }
63   assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
64
65   return RL->getFieldOffset(Index);
66 }
67
68 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
69                                               const ObjCInterfaceDecl *OID,
70                                               const ObjCIvarDecl *Ivar) {
71   return LookupFieldBitOffset(CGM, OID, 0, Ivar) / 
72     CGM.getContext().getCharWidth();
73 }
74
75 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
76                                               const ObjCImplementationDecl *OID,
77                                               const ObjCIvarDecl *Ivar) {
78   return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) / 
79     CGM.getContext().getCharWidth();
80 }
81
82 LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
83                                                const ObjCInterfaceDecl *OID,
84                                                llvm::Value *BaseValue,
85                                                const ObjCIvarDecl *Ivar,
86                                                unsigned CVRQualifiers,
87                                                llvm::Value *Offset) {
88   // Compute (type*) ( (char *) BaseValue + Offset)
89   const llvm::Type *I8Ptr = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
90   QualType IvarTy = Ivar->getType();
91   const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
92   llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
93   V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
94   V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
95
96   if (!Ivar->isBitField()) {
97     LValue LV = CGF.MakeAddrLValue(V, IvarTy);
98     LV.getQuals().addCVRQualifiers(CVRQualifiers);
99     return LV;
100   }
101
102   // We need to compute an access strategy for this bit-field. We are given the
103   // offset to the first byte in the bit-field, the sub-byte offset is taken
104   // from the original layout. We reuse the normal bit-field access strategy by
105   // treating this as an access to a struct where the bit-field is in byte 0,
106   // and adjust the containing type size as appropriate.
107   //
108   // FIXME: Note that currently we make a very conservative estimate of the
109   // alignment of the bit-field, because (a) it is not clear what guarantees the
110   // runtime makes us, and (b) we don't have a way to specify that the struct is
111   // at an alignment plus offset.
112   //
113   // Note, there is a subtle invariant here: we can only call this routine on
114   // non-synthesized ivars but we may be called for synthesized ivars.  However,
115   // a synthesized ivar can never be a bit-field, so this is safe.
116   const ASTRecordLayout &RL =
117     CGF.CGM.getContext().getASTObjCInterfaceLayout(OID);
118   uint64_t TypeSizeInBits = CGF.CGM.getContext().toBits(RL.getSize());
119   uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);
120   uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
121   uint64_t ContainingTypeAlign = CGF.CGM.getContext().Target.getCharAlign();
122   uint64_t ContainingTypeSize = TypeSizeInBits - (FieldBitOffset - BitOffset);
123   uint64_t BitFieldSize =
124     Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
125
126   // Allocate a new CGBitFieldInfo object to describe this access.
127   //
128   // FIXME: This is incredibly wasteful, these should be uniqued or part of some
129   // layout object. However, this is blocked on other cleanups to the
130   // Objective-C code, so for now we just live with allocating a bunch of these
131   // objects.
132   CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
133     CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
134                              ContainingTypeSize, ContainingTypeAlign));
135
136   return LValue::MakeBitfield(V, *Info,
137                               IvarTy.withCVRQualifiers(CVRQualifiers));
138 }
139
140 namespace {
141   struct CatchHandler {
142     const VarDecl *Variable;
143     const Stmt *Body;
144     llvm::BasicBlock *Block;
145     llvm::Value *TypeInfo;
146   };
147
148   struct CallObjCEndCatch : EHScopeStack::Cleanup {
149     CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :
150       MightThrow(MightThrow), Fn(Fn) {}
151     bool MightThrow;
152     llvm::Value *Fn;
153
154     void Emit(CodeGenFunction &CGF, Flags flags) {
155       if (!MightThrow) {
156         CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
157         return;
158       }
159
160       CGF.EmitCallOrInvoke(Fn);
161     }
162   };
163 }
164
165
166 void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
167                                      const ObjCAtTryStmt &S,
168                                      llvm::Constant *beginCatchFn,
169                                      llvm::Constant *endCatchFn,
170                                      llvm::Constant *exceptionRethrowFn) {
171   // Jump destination for falling out of catch bodies.
172   CodeGenFunction::JumpDest Cont;
173   if (S.getNumCatchStmts())
174     Cont = CGF.getJumpDestInCurrentScope("eh.cont");
175
176   CodeGenFunction::FinallyInfo FinallyInfo;
177   if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
178     FinallyInfo.enter(CGF, Finally->getFinallyBody(),
179                       beginCatchFn, endCatchFn, exceptionRethrowFn);
180
181   llvm::SmallVector<CatchHandler, 8> Handlers;
182
183   // Enter the catch, if there is one.
184   if (S.getNumCatchStmts()) {
185     for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
186       const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
187       const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
188
189       Handlers.push_back(CatchHandler());
190       CatchHandler &Handler = Handlers.back();
191       Handler.Variable = CatchDecl;
192       Handler.Body = CatchStmt->getCatchBody();
193       Handler.Block = CGF.createBasicBlock("catch");
194
195       // @catch(...) always matches.
196       if (!CatchDecl) {
197         Handler.TypeInfo = 0; // catch-all
198         // Don't consider any other catches.
199         break;
200       }
201
202       Handler.TypeInfo = GetEHType(CatchDecl->getType());
203     }
204
205     EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
206     for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
207       Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
208   }
209   
210   // Emit the try body.
211   CGF.EmitStmt(S.getTryBody());
212
213   // Leave the try.
214   if (S.getNumCatchStmts())
215     CGF.EHStack.popCatch();
216
217   // Remember where we were.
218   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
219
220   // Emit the handlers.
221   for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
222     CatchHandler &Handler = Handlers[I];
223
224     CGF.EmitBlock(Handler.Block);
225     llvm::Value *RawExn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
226
227     // Enter the catch.
228     llvm::Value *Exn = RawExn;
229     if (beginCatchFn) {
230       Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted");
231       cast<llvm::CallInst>(Exn)->setDoesNotThrow();
232     }
233
234     CodeGenFunction::RunCleanupsScope cleanups(CGF);
235
236     if (endCatchFn) {
237       // Add a cleanup to leave the catch.
238       bool EndCatchMightThrow = (Handler.Variable == 0);
239
240       CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
241                                                 EndCatchMightThrow,
242                                                 endCatchFn);
243     }
244
245     // Bind the catch parameter if it exists.
246     if (const VarDecl *CatchParam = Handler.Variable) {
247       const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
248       llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
249
250       CGF.EmitAutoVarDecl(*CatchParam);
251       CGF.Builder.CreateStore(CastExn, CGF.GetAddrOfLocalVar(CatchParam));
252     }
253
254     CGF.ObjCEHValueStack.push_back(Exn);
255     CGF.EmitStmt(Handler.Body);
256     CGF.ObjCEHValueStack.pop_back();
257
258     // Leave any cleanups associated with the catch.
259     cleanups.ForceCleanup();
260
261     CGF.EmitBranchThroughCleanup(Cont);
262   }  
263
264   // Go back to the try-statement fallthrough.
265   CGF.Builder.restoreIP(SavedIP);
266
267   // Pop out of the finally.
268   if (S.getFinallyStmt())
269     FinallyInfo.exit(CGF);
270
271   if (Cont.isValid())
272     CGF.EmitBlock(Cont.getBlock());
273 }
274
275 namespace {
276   struct CallSyncExit : EHScopeStack::Cleanup {
277     llvm::Value *SyncExitFn;
278     llvm::Value *SyncArg;
279     CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
280       : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
281
282     void Emit(CodeGenFunction &CGF, Flags flags) {
283       CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
284     }
285   };
286 }
287
288 void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
289                                            const ObjCAtSynchronizedStmt &S,
290                                            llvm::Function *syncEnterFn,
291                                            llvm::Function *syncExitFn) {
292   // Evaluate the lock operand.  This should dominate the cleanup.
293   llvm::Value *SyncArg =
294     CGF.EmitScalarExpr(S.getSynchExpr());
295
296   // Acquire the lock.
297   SyncArg = CGF.Builder.CreateBitCast(SyncArg, syncEnterFn->getFunctionType()->getParamType(0));
298   CGF.Builder.CreateCall(syncEnterFn, SyncArg);
299
300   // Register an all-paths cleanup to release the lock.
301   CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn,
302       SyncArg);
303
304   // Emit the body of the statement.
305   CGF.EmitStmt(S.getSynchBody());
306
307   // Pop the lock-release cleanup.
308   CGF.PopCleanupBlock();
309 }