1 //==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "CGObjCRuntime.h"
18 #include "CGRecordLayout.h"
19 #include "CodeGenModule.h"
20 #include "CodeGenFunction.h"
21 #include "CGCleanup.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtObjC.h"
26 #include "llvm/Support/CallSite.h"
28 using namespace clang;
29 using namespace CodeGen;
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();
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.
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);
47 RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
49 // Compute field index.
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
55 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
56 CGM.getContext().ShallowCollectObjCIvars(Container, Ivars);
57 for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
62 assert(Index != Ivars.size() && "Ivar is not inside container!");
63 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
65 return RL->getFieldOffset(Index);
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();
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();
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));
96 if (!Ivar->isBitField()) {
97 LValue LV = CGF.MakeAddrLValue(V, IvarTy);
98 LV.getQuals().addCVRQualifiers(CVRQualifiers);
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.
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.
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();
126 // Allocate a new CGBitFieldInfo object to describe this access.
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
132 CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
133 CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
134 ContainingTypeSize, ContainingTypeAlign));
136 return LValue::MakeBitfield(V, *Info,
137 IvarTy.getCVRQualifiers() | CVRQualifiers);
141 struct CatchHandler {
142 const VarDecl *Variable;
144 llvm::BasicBlock *Block;
145 llvm::Value *TypeInfo;
148 struct CallObjCEndCatch : EHScopeStack::Cleanup {
149 CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :
150 MightThrow(MightThrow), Fn(Fn) {}
154 void Emit(CodeGenFunction &CGF, bool IsForEH) {
156 CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
160 CGF.EmitCallOrInvoke(Fn, 0, 0);
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");
176 CodeGenFunction::FinallyInfo FinallyInfo;
177 if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
178 FinallyInfo = CGF.EnterFinallyBlock(Finally->getFinallyBody(),
183 llvm::SmallVector<CatchHandler, 8> Handlers;
185 // Enter the catch, if there is one.
186 if (S.getNumCatchStmts()) {
187 for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
188 const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
189 const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
191 Handlers.push_back(CatchHandler());
192 CatchHandler &Handler = Handlers.back();
193 Handler.Variable = CatchDecl;
194 Handler.Body = CatchStmt->getCatchBody();
195 Handler.Block = CGF.createBasicBlock("catch");
197 // @catch(...) always matches.
199 Handler.TypeInfo = 0; // catch-all
200 // Don't consider any other catches.
204 Handler.TypeInfo = GetEHType(CatchDecl->getType());
207 EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
208 for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
209 Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
212 // Emit the try body.
213 CGF.EmitStmt(S.getTryBody());
216 if (S.getNumCatchStmts())
217 CGF.EHStack.popCatch();
219 // Remember where we were.
220 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
222 // Emit the handlers.
223 for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
224 CatchHandler &Handler = Handlers[I];
226 CGF.EmitBlock(Handler.Block);
227 llvm::Value *RawExn = CGF.Builder.CreateLoad(CGF.getExceptionSlot());
230 llvm::Value *Exn = RawExn;
232 Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted");
233 cast<llvm::CallInst>(Exn)->setDoesNotThrow();
236 CodeGenFunction::RunCleanupsScope cleanups(CGF);
239 // Add a cleanup to leave the catch.
240 bool EndCatchMightThrow = (Handler.Variable == 0);
242 CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
247 // Bind the catch parameter if it exists.
248 if (const VarDecl *CatchParam = Handler.Variable) {
249 const llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
250 llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
252 CGF.EmitAutoVarDecl(*CatchParam);
253 CGF.Builder.CreateStore(CastExn, CGF.GetAddrOfLocalVar(CatchParam));
256 CGF.ObjCEHValueStack.push_back(Exn);
257 CGF.EmitStmt(Handler.Body);
258 CGF.ObjCEHValueStack.pop_back();
260 // Leave any cleanups associated with the catch.
261 cleanups.ForceCleanup();
263 CGF.EmitBranchThroughCleanup(Cont);
266 // Go back to the try-statement fallthrough.
267 CGF.Builder.restoreIP(SavedIP);
269 // Pop out of the normal cleanup on the finally.
270 if (S.getFinallyStmt())
271 CGF.ExitFinallyBlock(FinallyInfo);
274 CGF.EmitBlock(Cont.getBlock());
278 struct CallSyncExit : EHScopeStack::Cleanup {
279 llvm::Value *SyncExitFn;
280 llvm::Value *SyncArg;
281 CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
282 : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
284 void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) {
285 CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
290 void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
291 const ObjCAtSynchronizedStmt &S,
292 llvm::Function *syncEnterFn,
293 llvm::Function *syncExitFn) {
294 // Evaluate the lock operand. This should dominate the cleanup.
295 llvm::Value *SyncArg =
296 CGF.EmitScalarExpr(S.getSynchExpr());
299 SyncArg = CGF.Builder.CreateBitCast(SyncArg, syncEnterFn->getFunctionType()->getParamType(0));
300 CGF.Builder.CreateCall(syncEnterFn, SyncArg);
302 // Register an all-paths cleanup to release the lock.
303 CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn,
306 // Emit the body of the statement.
307 CGF.EmitStmt(S.getSynchBody());
309 // Pop the lock-release cleanup.
310 CGF.PopCleanupBlock();