Home | History | Annotate | Download | only in CodeGen
      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 
     56   for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin();
     57        IVD; IVD = IVD->getNextIvar()) {
     58     if (Ivar == IVD)
     59       break;
     60     ++Index;
     61   }
     62   assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
     63 
     64   return RL->getFieldOffset(Index);
     65 }
     66 
     67 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
     68                                               const ObjCInterfaceDecl *OID,
     69                                               const ObjCIvarDecl *Ivar) {
     70   return LookupFieldBitOffset(CGM, OID, 0, Ivar) /
     71     CGM.getContext().getCharWidth();
     72 }
     73 
     74 uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
     75                                               const ObjCImplementationDecl *OID,
     76                                               const ObjCIvarDecl *Ivar) {
     77   return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) /
     78     CGM.getContext().getCharWidth();
     79 }
     80 
     81 LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
     82                                                const ObjCInterfaceDecl *OID,
     83                                                llvm::Value *BaseValue,
     84                                                const ObjCIvarDecl *Ivar,
     85                                                unsigned CVRQualifiers,
     86                                                llvm::Value *Offset) {
     87   // Compute (type*) ( (char *) BaseValue + Offset)
     88   llvm::Type *I8Ptr = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
     89   QualType IvarTy = Ivar->getType();
     90   llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
     91   llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
     92   V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
     93   V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
     94 
     95   if (!Ivar->isBitField()) {
     96     LValue LV = CGF.MakeAddrLValue(V, IvarTy);
     97     LV.getQuals().addCVRQualifiers(CVRQualifiers);
     98     return LV;
     99   }
    100 
    101   // We need to compute an access strategy for this bit-field. We are given the
    102   // offset to the first byte in the bit-field, the sub-byte offset is taken
    103   // from the original layout. We reuse the normal bit-field access strategy by
    104   // treating this as an access to a struct where the bit-field is in byte 0,
    105   // and adjust the containing type size as appropriate.
    106   //
    107   // FIXME: Note that currently we make a very conservative estimate of the
    108   // alignment of the bit-field, because (a) it is not clear what guarantees the
    109   // runtime makes us, and (b) we don't have a way to specify that the struct is
    110   // at an alignment plus offset.
    111   //
    112   // Note, there is a subtle invariant here: we can only call this routine on
    113   // non-synthesized ivars but we may be called for synthesized ivars.  However,
    114   // a synthesized ivar can never be a bit-field, so this is safe.
    115   const ASTRecordLayout &RL =
    116     CGF.CGM.getContext().getASTObjCInterfaceLayout(OID);
    117   uint64_t TypeSizeInBits = CGF.CGM.getContext().toBits(RL.getSize());
    118   uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);
    119   uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
    120   uint64_t ContainingTypeAlign = CGF.CGM.getContext().getTargetInfo().getCharAlign();
    121   uint64_t ContainingTypeSize = TypeSizeInBits - (FieldBitOffset - BitOffset);
    122   uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
    123 
    124   // Allocate a new CGBitFieldInfo object to describe this access.
    125   //
    126   // FIXME: This is incredibly wasteful, these should be uniqued or part of some
    127   // layout object. However, this is blocked on other cleanups to the
    128   // Objective-C code, so for now we just live with allocating a bunch of these
    129   // objects.
    130   CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
    131     CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
    132                              ContainingTypeSize, ContainingTypeAlign));
    133 
    134   return LValue::MakeBitfield(V, *Info,
    135                               IvarTy.withCVRQualifiers(CVRQualifiers));
    136 }
    137 
    138 namespace {
    139   struct CatchHandler {
    140     const VarDecl *Variable;
    141     const Stmt *Body;
    142     llvm::BasicBlock *Block;
    143     llvm::Value *TypeInfo;
    144   };
    145 
    146   struct CallObjCEndCatch : EHScopeStack::Cleanup {
    147     CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :
    148       MightThrow(MightThrow), Fn(Fn) {}
    149     bool MightThrow;
    150     llvm::Value *Fn;
    151 
    152     void Emit(CodeGenFunction &CGF, Flags flags) {
    153       if (!MightThrow) {
    154         CGF.Builder.CreateCall(Fn)->setDoesNotThrow();
    155         return;
    156       }
    157 
    158       CGF.EmitCallOrInvoke(Fn);
    159     }
    160   };
    161 }
    162 
    163 
    164 void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
    165                                      const ObjCAtTryStmt &S,
    166                                      llvm::Constant *beginCatchFn,
    167                                      llvm::Constant *endCatchFn,
    168                                      llvm::Constant *exceptionRethrowFn) {
    169   // Jump destination for falling out of catch bodies.
    170   CodeGenFunction::JumpDest Cont;
    171   if (S.getNumCatchStmts())
    172     Cont = CGF.getJumpDestInCurrentScope("eh.cont");
    173 
    174   CodeGenFunction::FinallyInfo FinallyInfo;
    175   if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
    176     FinallyInfo.enter(CGF, Finally->getFinallyBody(),
    177                       beginCatchFn, endCatchFn, exceptionRethrowFn);
    178 
    179   SmallVector<CatchHandler, 8> Handlers;
    180 
    181   // Enter the catch, if there is one.
    182   if (S.getNumCatchStmts()) {
    183     for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
    184       const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
    185       const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
    186 
    187       Handlers.push_back(CatchHandler());
    188       CatchHandler &Handler = Handlers.back();
    189       Handler.Variable = CatchDecl;
    190       Handler.Body = CatchStmt->getCatchBody();
    191       Handler.Block = CGF.createBasicBlock("catch");
    192 
    193       // @catch(...) always matches.
    194       if (!CatchDecl) {
    195         Handler.TypeInfo = 0; // catch-all
    196         // Don't consider any other catches.
    197         break;
    198       }
    199 
    200       Handler.TypeInfo = GetEHType(CatchDecl->getType());
    201     }
    202 
    203     EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
    204     for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
    205       Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);
    206   }
    207 
    208   // Emit the try body.
    209   CGF.EmitStmt(S.getTryBody());
    210 
    211   // Leave the try.
    212   if (S.getNumCatchStmts())
    213     CGF.popCatchScope();
    214 
    215   // Remember where we were.
    216   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
    217 
    218   // Emit the handlers.
    219   for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
    220     CatchHandler &Handler = Handlers[I];
    221 
    222     CGF.EmitBlock(Handler.Block);
    223     llvm::Value *RawExn = CGF.getExceptionFromSlot();
    224 
    225     // Enter the catch.
    226     llvm::Value *Exn = RawExn;
    227     if (beginCatchFn) {
    228       Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, "exn.adjusted");
    229       cast<llvm::CallInst>(Exn)->setDoesNotThrow();
    230     }
    231 
    232     CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());
    233 
    234     if (endCatchFn) {
    235       // Add a cleanup to leave the catch.
    236       bool EndCatchMightThrow = (Handler.Variable == 0);
    237 
    238       CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
    239                                                 EndCatchMightThrow,
    240                                                 endCatchFn);
    241     }
    242 
    243     // Bind the catch parameter if it exists.
    244     if (const VarDecl *CatchParam = Handler.Variable) {
    245       llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
    246       llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
    247 
    248       CGF.EmitAutoVarDecl(*CatchParam);
    249       CGF.Builder.CreateStore(CastExn, CGF.GetAddrOfLocalVar(CatchParam));
    250     }
    251 
    252     CGF.ObjCEHValueStack.push_back(Exn);
    253     CGF.EmitStmt(Handler.Body);
    254     CGF.ObjCEHValueStack.pop_back();
    255 
    256     // Leave any cleanups associated with the catch.
    257     cleanups.ForceCleanup();
    258 
    259     CGF.EmitBranchThroughCleanup(Cont);
    260   }
    261 
    262   // Go back to the try-statement fallthrough.
    263   CGF.Builder.restoreIP(SavedIP);
    264 
    265   // Pop out of the finally.
    266   if (S.getFinallyStmt())
    267     FinallyInfo.exit(CGF);
    268 
    269   if (Cont.isValid())
    270     CGF.EmitBlock(Cont.getBlock());
    271 }
    272 
    273 namespace {
    274   struct CallSyncExit : EHScopeStack::Cleanup {
    275     llvm::Value *SyncExitFn;
    276     llvm::Value *SyncArg;
    277     CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
    278       : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
    279 
    280     void Emit(CodeGenFunction &CGF, Flags flags) {
    281       CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
    282     }
    283   };
    284 }
    285 
    286 void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
    287                                            const ObjCAtSynchronizedStmt &S,
    288                                            llvm::Function *syncEnterFn,
    289                                            llvm::Function *syncExitFn) {
    290   CodeGenFunction::RunCleanupsScope cleanups(CGF);
    291 
    292   // Evaluate the lock operand.  This is guaranteed to dominate the
    293   // ARC release and lock-release cleanups.
    294   const Expr *lockExpr = S.getSynchExpr();
    295   llvm::Value *lock;
    296   if (CGF.getLangOptions().ObjCAutoRefCount) {
    297     lock = CGF.EmitARCRetainScalarExpr(lockExpr);
    298     lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
    299   } else {
    300     lock = CGF.EmitScalarExpr(lockExpr);
    301   }
    302   lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
    303 
    304   // Acquire the lock.
    305   CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
    306 
    307   // Register an all-paths cleanup to release the lock.
    308   CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
    309 
    310   // Emit the body of the statement.
    311   CGF.EmitStmt(S.getSynchBody());
    312 }
    313