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 && declaresSameEntity(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 = CGF.Int8PtrTy;
     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.MakeNaturalAlignAddrLValue(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 
    250       llvm::Value *CatchParamAddr = CGF.GetAddrOfLocalVar(CatchParam);
    251 
    252       switch (CatchParam->getType().getQualifiers().getObjCLifetime()) {
    253       case Qualifiers::OCL_Strong:
    254         CastExn = CGF.EmitARCRetainNonBlock(CastExn);
    255         // fallthrough
    256 
    257       case Qualifiers::OCL_None:
    258       case Qualifiers::OCL_ExplicitNone:
    259       case Qualifiers::OCL_Autoreleasing:
    260         CGF.Builder.CreateStore(CastExn, CatchParamAddr);
    261         break;
    262 
    263       case Qualifiers::OCL_Weak:
    264         CGF.EmitARCInitWeak(CatchParamAddr, CastExn);
    265         break;
    266       }
    267     }
    268 
    269     CGF.ObjCEHValueStack.push_back(Exn);
    270     CGF.EmitStmt(Handler.Body);
    271     CGF.ObjCEHValueStack.pop_back();
    272 
    273     // Leave any cleanups associated with the catch.
    274     cleanups.ForceCleanup();
    275 
    276     CGF.EmitBranchThroughCleanup(Cont);
    277   }
    278 
    279   // Go back to the try-statement fallthrough.
    280   CGF.Builder.restoreIP(SavedIP);
    281 
    282   // Pop out of the finally.
    283   if (S.getFinallyStmt())
    284     FinallyInfo.exit(CGF);
    285 
    286   if (Cont.isValid())
    287     CGF.EmitBlock(Cont.getBlock());
    288 }
    289 
    290 namespace {
    291   struct CallSyncExit : EHScopeStack::Cleanup {
    292     llvm::Value *SyncExitFn;
    293     llvm::Value *SyncArg;
    294     CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)
    295       : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
    296 
    297     void Emit(CodeGenFunction &CGF, Flags flags) {
    298       CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();
    299     }
    300   };
    301 }
    302 
    303 void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
    304                                            const ObjCAtSynchronizedStmt &S,
    305                                            llvm::Function *syncEnterFn,
    306                                            llvm::Function *syncExitFn) {
    307   CodeGenFunction::RunCleanupsScope cleanups(CGF);
    308 
    309   // Evaluate the lock operand.  This is guaranteed to dominate the
    310   // ARC release and lock-release cleanups.
    311   const Expr *lockExpr = S.getSynchExpr();
    312   llvm::Value *lock;
    313   if (CGF.getLangOpts().ObjCAutoRefCount) {
    314     lock = CGF.EmitARCRetainScalarExpr(lockExpr);
    315     lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
    316   } else {
    317     lock = CGF.EmitScalarExpr(lockExpr);
    318   }
    319   lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
    320 
    321   // Acquire the lock.
    322   CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
    323 
    324   // Register an all-paths cleanup to release the lock.
    325   CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
    326 
    327   // Emit the body of the statement.
    328   CGF.EmitStmt(S.getSynchBody());
    329 }
    330 
    331 /// Compute the pointer-to-function type to which a message send
    332 /// should be casted in order to correctly call the given method
    333 /// with the given arguments.
    334 ///
    335 /// \param method - may be null
    336 /// \param resultType - the result type to use if there's no method
    337 /// \param argInfo - the actual arguments, including implicit ones
    338 CGObjCRuntime::MessageSendInfo
    339 CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
    340                                   QualType resultType,
    341                                   CallArgList &callArgs) {
    342   // If there's a method, use information from that.
    343   if (method) {
    344     const CGFunctionInfo &signature =
    345       CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
    346 
    347     llvm::PointerType *signatureType =
    348       CGM.getTypes().GetFunctionType(signature)->getPointerTo();
    349 
    350     // If that's not variadic, there's no need to recompute the ABI
    351     // arrangement.
    352     if (!signature.isVariadic())
    353       return MessageSendInfo(signature, signatureType);
    354 
    355     // Otherwise, there is.
    356     FunctionType::ExtInfo einfo = signature.getExtInfo();
    357     const CGFunctionInfo &argsInfo =
    358       CGM.getTypes().arrangeFunctionCall(resultType, callArgs, einfo,
    359                                          signature.getRequiredArgs());
    360 
    361     return MessageSendInfo(argsInfo, signatureType);
    362   }
    363 
    364   // There's no method;  just use a default CC.
    365   const CGFunctionInfo &argsInfo =
    366     CGM.getTypes().arrangeFunctionCall(resultType, callArgs,
    367                                        FunctionType::ExtInfo(),
    368                                        RequiredArgs::All);
    369 
    370   // Derive the signature to call from that.
    371   llvm::PointerType *signatureType =
    372     CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();
    373   return MessageSendInfo(argsInfo, signatureType);
    374 }
    375