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#include "CGCleanup.h"
18#include "CGRecordLayout.h"
19#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
21#include "clang/AST/RecordLayout.h"
22#include "clang/AST/StmtObjC.h"
23#include "llvm/Support/CallSite.h"
24
25using namespace clang;
26using namespace CodeGen;
27
28static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
29                                     const ObjCInterfaceDecl *OID,
30                                     const ObjCImplementationDecl *ID,
31                                     const ObjCIvarDecl *Ivar) {
32  const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
33
34  // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
35  // in here; it should never be necessary because that should be the lexical
36  // decl context for the ivar.
37
38  // If we know have an implementation (and the ivar is in it) then
39  // look up in the implementation layout.
40  const ASTRecordLayout *RL;
41  if (ID && declaresSameEntity(ID->getClassInterface(), Container))
42    RL = &CGM.getContext().getASTObjCImplementationLayout(ID);
43  else
44    RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);
45
46  // Compute field index.
47  //
48  // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
49  // implemented. This should be fixed to get the information from the layout
50  // directly.
51  unsigned Index = 0;
52
53  for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin();
54       IVD; IVD = IVD->getNextIvar()) {
55    if (Ivar == IVD)
56      break;
57    ++Index;
58  }
59  assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
60
61  return RL->getFieldOffset(Index);
62}
63
64uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
65                                              const ObjCInterfaceDecl *OID,
66                                              const ObjCIvarDecl *Ivar) {
67  return LookupFieldBitOffset(CGM, OID, 0, Ivar) /
68    CGM.getContext().getCharWidth();
69}
70
71uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
72                                              const ObjCImplementationDecl *OID,
73                                              const ObjCIvarDecl *Ivar) {
74  return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) /
75    CGM.getContext().getCharWidth();
76}
77
78unsigned CGObjCRuntime::ComputeBitfieldBitOffset(
79    CodeGen::CodeGenModule &CGM,
80    const ObjCInterfaceDecl *ID,
81    const ObjCIvarDecl *Ivar) {
82  return LookupFieldBitOffset(CGM, ID, ID->getImplementation(), Ivar);
83}
84
85LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
86                                               const ObjCInterfaceDecl *OID,
87                                               llvm::Value *BaseValue,
88                                               const ObjCIvarDecl *Ivar,
89                                               unsigned CVRQualifiers,
90                                               llvm::Value *Offset) {
91  // Compute (type*) ( (char *) BaseValue + Offset)
92  QualType IvarTy = Ivar->getType();
93  llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
94  llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy);
95  V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
96
97  if (!Ivar->isBitField()) {
98    V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
99    LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
100    LV.getQuals().addCVRQualifiers(CVRQualifiers);
101    return LV;
102  }
103
104  // We need to compute an access strategy for this bit-field. We are given the
105  // offset to the first byte in the bit-field, the sub-byte offset is taken
106  // from the original layout. We reuse the normal bit-field access strategy by
107  // treating this as an access to a struct where the bit-field is in byte 0,
108  // and adjust the containing type size as appropriate.
109  //
110  // FIXME: Note that currently we make a very conservative estimate of the
111  // alignment of the bit-field, because (a) it is not clear what guarantees the
112  // runtime makes us, and (b) we don't have a way to specify that the struct is
113  // at an alignment plus offset.
114  //
115  // Note, there is a subtle invariant here: we can only call this routine on
116  // non-synthesized ivars but we may be called for synthesized ivars.  However,
117  // a synthesized ivar can never be a bit-field, so this is safe.
118  uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);
119  uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
120  uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign();
121  uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
122  CharUnits StorageSize =
123    CGF.CGM.getContext().toCharUnitsFromBits(
124      llvm::RoundUpToAlignment(BitOffset + BitFieldSize, AlignmentBits));
125  CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits);
126
127  // Allocate a new CGBitFieldInfo object to describe this access.
128  //
129  // FIXME: This is incredibly wasteful, these should be uniqued or part of some
130  // layout object. However, this is blocked on other cleanups to the
131  // Objective-C code, so for now we just live with allocating a bunch of these
132  // objects.
133  CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
134    CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
135                             CGF.CGM.getContext().toBits(StorageSize),
136                             Alignment.getQuantity()));
137
138  V = CGF.Builder.CreateBitCast(V,
139                                llvm::Type::getIntNPtrTy(CGF.getLLVMContext(),
140                                                         Info->StorageSize));
141  return LValue::MakeBitfield(V, *Info,
142                              IvarTy.withCVRQualifiers(CVRQualifiers),
143                              Alignment);
144}
145
146namespace {
147  struct CatchHandler {
148    const VarDecl *Variable;
149    const Stmt *Body;
150    llvm::BasicBlock *Block;
151    llvm::Value *TypeInfo;
152  };
153
154  struct CallObjCEndCatch : EHScopeStack::Cleanup {
155    CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :
156      MightThrow(MightThrow), Fn(Fn) {}
157    bool MightThrow;
158    llvm::Value *Fn;
159
160    void Emit(CodeGenFunction &CGF, Flags flags) {
161      if (!MightThrow) {
162        CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
163        return;
164      }
165
166      CGF.EmitRuntimeCallOrInvoke(Fn);
167    }
168  };
169}
170
171
172void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
173                                     const ObjCAtTryStmt &S,
174                                     llvm::Constant *beginCatchFn,
175                                     llvm::Constant *endCatchFn,
176                                     llvm::Constant *exceptionRethrowFn) {
177  // Jump destination for falling out of catch bodies.
178  CodeGenFunction::JumpDest Cont;
179  if (S.getNumCatchStmts())
180    Cont = CGF.getJumpDestInCurrentScope("eh.cont");
181
182  CodeGenFunction::FinallyInfo FinallyInfo;
183  if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
184    FinallyInfo.enter(CGF, Finally->getFinallyBody(),
185                      beginCatchFn, endCatchFn, exceptionRethrowFn);
186
187  SmallVector<CatchHandler, 8> Handlers;
188
189  // Enter the catch, if there is one.
190  if (S.getNumCatchStmts()) {
191    for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
192      const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
193      const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
194
195      Handlers.push_back(CatchHandler());
196      CatchHandler &Handler = Handlers.back();
197      Handler.Variable = CatchDecl;
198      Handler.Body = CatchStmt->getCatchBody();
199      Handler.Block = CGF.createBasicBlock("catch");
200
201      // @catch(...) always matches.
202      if (!CatchDecl) {
203        Handler.TypeInfo = 0; // catch-all
204        // Don't consider any other catches.
205        break;
206      }
207
208      Handler.TypeInfo = GetEHType(CatchDecl->getType());
209    }
210
211    EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
212    for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
213      Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
214  }
215
216  // Emit the try body.
217  CGF.EmitStmt(S.getTryBody());
218
219  // Leave the try.
220  if (S.getNumCatchStmts())
221    CGF.popCatchScope();
222
223  // Remember where we were.
224  CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
225
226  // Emit the handlers.
227  for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
228    CatchHandler &Handler = Handlers[I];
229
230    CGF.EmitBlock(Handler.Block);
231    llvm::Value *RawExn = CGF.getExceptionFromSlot();
232
233    // Enter the catch.
234    llvm::Value *Exn = RawExn;
235    if (beginCatchFn) {
236      Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted");
237      cast<llvm::CallInst>(Exn)->setDoesNotThrow();
238    }
239
240    CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());
241
242    if (endCatchFn) {
243      // Add a cleanup to leave the catch.
244      bool EndCatchMightThrow = (Handler.Variable == 0);
245
246      CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
247                                                EndCatchMightThrow,
248                                                endCatchFn);
249    }
250
251    // Bind the catch parameter if it exists.
252    if (const VarDecl *CatchParam = Handler.Variable) {
253      llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
254      llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
255
256      CGF.EmitAutoVarDecl(*CatchParam);
257
258      llvm::Value *CatchParamAddr = CGF.GetAddrOfLocalVar(CatchParam);
259
260      switch (CatchParam->getType().getQualifiers().getObjCLifetime()) {
261      case Qualifiers::OCL_Strong:
262        CastExn = CGF.EmitARCRetainNonBlock(CastExn);
263        // fallthrough
264
265      case Qualifiers::OCL_None:
266      case Qualifiers::OCL_ExplicitNone:
267      case Qualifiers::OCL_Autoreleasing:
268        CGF.Builder.CreateStore(CastExn, CatchParamAddr);
269        break;
270
271      case Qualifiers::OCL_Weak:
272        CGF.EmitARCInitWeak(CatchParamAddr, CastExn);
273        break;
274      }
275    }
276
277    CGF.ObjCEHValueStack.push_back(Exn);
278    CGF.EmitStmt(Handler.Body);
279    CGF.ObjCEHValueStack.pop_back();
280
281    // Leave any cleanups associated with the catch.
282    cleanups.ForceCleanup();
283
284    CGF.EmitBranchThroughCleanup(Cont);
285  }
286
287  // Go back to the try-statement fallthrough.
288  CGF.Builder.restoreIP(SavedIP);
289
290  // Pop out of the finally.
291  if (S.getFinallyStmt())
292    FinallyInfo.exit(CGF);
293
294  if (Cont.isValid())
295    CGF.EmitBlock(Cont.getBlock());
296}
297
298namespace {
299  struct CallSyncExit : EHScopeStack::Cleanup {
300    llvm::Value *SyncExitFn;
301    llvm::Value *SyncArg;
302    CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
303      : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
304
305    void Emit(CodeGenFunction &CGF, Flags flags) {
306      CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
307    }
308  };
309}
310
311void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
312                                           const ObjCAtSynchronizedStmt &S,
313                                           llvm::Function *syncEnterFn,
314                                           llvm::Function *syncExitFn) {
315  CodeGenFunction::RunCleanupsScope cleanups(CGF);
316
317  // Evaluate the lock operand.  This is guaranteed to dominate the
318  // ARC release and lock-release cleanups.
319  const Expr *lockExpr = S.getSynchExpr();
320  llvm::Value *lock;
321  if (CGF.getLangOpts().ObjCAutoRefCount) {
322    lock = CGF.EmitARCRetainScalarExpr(lockExpr);
323    lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
324  } else {
325    lock = CGF.EmitScalarExpr(lockExpr);
326  }
327  lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
328
329  // Acquire the lock.
330  CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
331
332  // Register an all-paths cleanup to release the lock.
333  CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
334
335  // Emit the body of the statement.
336  CGF.EmitStmt(S.getSynchBody());
337}
338
339/// Compute the pointer-to-function type to which a message send
340/// should be casted in order to correctly call the given method
341/// with the given arguments.
342///
343/// \param method - may be null
344/// \param resultType - the result type to use if there's no method
345/// \param callArgs - the actual arguments, including implicit ones
346CGObjCRuntime::MessageSendInfo
347CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
348                                  QualType resultType,
349                                  CallArgList &callArgs) {
350  // If there's a method, use information from that.
351  if (method) {
352    const CGFunctionInfo &signature =
353      CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
354
355    llvm::PointerType *signatureType =
356      CGM.getTypes().GetFunctionType(signature)->getPointerTo();
357
358    // If that's not variadic, there's no need to recompute the ABI
359    // arrangement.
360    if (!signature.isVariadic())
361      return MessageSendInfo(signature, signatureType);
362
363    // Otherwise, there is.
364    FunctionType::ExtInfo einfo = signature.getExtInfo();
365    const CGFunctionInfo &argsInfo =
366      CGM.getTypes().arrangeFreeFunctionCall(resultType, callArgs, einfo,
367                                             signature.getRequiredArgs());
368
369    return MessageSendInfo(argsInfo, signatureType);
370  }
371
372  // There's no method;  just use a default CC.
373  const CGFunctionInfo &argsInfo =
374    CGM.getTypes().arrangeFreeFunctionCall(resultType, callArgs,
375                                           FunctionType::ExtInfo(),
376                                           RequiredArgs::All);
377
378  // Derive the signature to call from that.
379  llvm::PointerType *signatureType =
380    CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();
381  return MessageSendInfo(argsInfo, signatureType);
382}
383