CGObjCRuntime.cpp 14 KB

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