CGObjCRuntime.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. //==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This abstract class defines the interface for Objective-C runtime-specific
  10. // code generation. It provides some concrete helper methods for functionality
  11. // shared between all (or most) of the Objective-C runtimes supported by clang.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CGObjCRuntime.h"
  15. #include "CGCleanup.h"
  16. #include "CGCXXABI.h"
  17. #include "CGRecordLayout.h"
  18. #include "CodeGenFunction.h"
  19. #include "CodeGenModule.h"
  20. #include "clang/AST/RecordLayout.h"
  21. #include "clang/AST/StmtObjC.h"
  22. #include "clang/CodeGen/CGFunctionInfo.h"
  23. #include "llvm/Support/SaveAndRestore.h"
  24. using namespace clang;
  25. using namespace CodeGen;
  26. uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
  27. const ObjCInterfaceDecl *OID,
  28. const ObjCIvarDecl *Ivar) {
  29. return CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar) /
  30. CGM.getContext().getCharWidth();
  31. }
  32. uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
  33. const ObjCImplementationDecl *OID,
  34. const ObjCIvarDecl *Ivar) {
  35. return CGM.getContext().lookupFieldBitOffset(OID->getClassInterface(), OID,
  36. Ivar) /
  37. CGM.getContext().getCharWidth();
  38. }
  39. unsigned CGObjCRuntime::ComputeBitfieldBitOffset(
  40. CodeGen::CodeGenModule &CGM,
  41. const ObjCInterfaceDecl *ID,
  42. const ObjCIvarDecl *Ivar) {
  43. return CGM.getContext().lookupFieldBitOffset(ID, ID->getImplementation(),
  44. Ivar);
  45. }
  46. LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
  47. const ObjCInterfaceDecl *OID,
  48. llvm::Value *BaseValue,
  49. const ObjCIvarDecl *Ivar,
  50. unsigned CVRQualifiers,
  51. llvm::Value *Offset) {
  52. // Compute (type*) ( (char *) BaseValue + Offset)
  53. QualType InterfaceTy{OID->getTypeForDecl(), 0};
  54. QualType ObjectPtrTy =
  55. CGF.CGM.getContext().getObjCObjectPointerType(InterfaceTy);
  56. QualType IvarTy =
  57. Ivar->getUsageType(ObjectPtrTy).withCVRQualifiers(CVRQualifiers);
  58. llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
  59. llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy);
  60. V = CGF.Builder.CreateInBoundsGEP(V, Offset, "add.ptr");
  61. if (!Ivar->isBitField()) {
  62. V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
  63. LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
  64. return LV;
  65. }
  66. // We need to compute an access strategy for this bit-field. We are given the
  67. // offset to the first byte in the bit-field, the sub-byte offset is taken
  68. // from the original layout. We reuse the normal bit-field access strategy by
  69. // treating this as an access to a struct where the bit-field is in byte 0,
  70. // and adjust the containing type size as appropriate.
  71. //
  72. // FIXME: Note that currently we make a very conservative estimate of the
  73. // alignment of the bit-field, because (a) it is not clear what guarantees the
  74. // runtime makes us, and (b) we don't have a way to specify that the struct is
  75. // at an alignment plus offset.
  76. //
  77. // Note, there is a subtle invariant here: we can only call this routine on
  78. // non-synthesized ivars but we may be called for synthesized ivars. However,
  79. // a synthesized ivar can never be a bit-field, so this is safe.
  80. uint64_t FieldBitOffset =
  81. CGF.CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar);
  82. uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
  83. uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign();
  84. uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
  85. CharUnits StorageSize = CGF.CGM.getContext().toCharUnitsFromBits(
  86. llvm::alignTo(BitOffset + BitFieldSize, AlignmentBits));
  87. CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits);
  88. // Allocate a new CGBitFieldInfo object to describe this access.
  89. //
  90. // FIXME: This is incredibly wasteful, these should be uniqued or part of some
  91. // layout object. However, this is blocked on other cleanups to the
  92. // Objective-C code, so for now we just live with allocating a bunch of these
  93. // objects.
  94. CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
  95. CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
  96. CGF.CGM.getContext().toBits(StorageSize),
  97. CharUnits::fromQuantity(0)));
  98. Address Addr(V, Alignment);
  99. Addr = CGF.Builder.CreateElementBitCast(Addr,
  100. llvm::Type::getIntNTy(CGF.getLLVMContext(),
  101. Info->StorageSize));
  102. return LValue::MakeBitfield(Addr, *Info, IvarTy,
  103. LValueBaseInfo(AlignmentSource::Decl),
  104. TBAAAccessInfo());
  105. }
  106. namespace {
  107. struct CatchHandler {
  108. const VarDecl *Variable;
  109. const Stmt *Body;
  110. llvm::BasicBlock *Block;
  111. llvm::Constant *TypeInfo;
  112. /// Flags used to differentiate cleanups and catchalls in Windows SEH
  113. unsigned Flags;
  114. };
  115. struct CallObjCEndCatch final : EHScopeStack::Cleanup {
  116. CallObjCEndCatch(bool MightThrow, llvm::FunctionCallee Fn)
  117. : MightThrow(MightThrow), Fn(Fn) {}
  118. bool MightThrow;
  119. llvm::FunctionCallee Fn;
  120. void Emit(CodeGenFunction &CGF, Flags flags) override {
  121. if (MightThrow)
  122. CGF.EmitRuntimeCallOrInvoke(Fn);
  123. else
  124. CGF.EmitNounwindRuntimeCall(Fn);
  125. }
  126. };
  127. }
  128. void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
  129. const ObjCAtTryStmt &S,
  130. llvm::FunctionCallee beginCatchFn,
  131. llvm::FunctionCallee endCatchFn,
  132. llvm::FunctionCallee exceptionRethrowFn) {
  133. // Jump destination for falling out of catch bodies.
  134. CodeGenFunction::JumpDest Cont;
  135. if (S.getNumCatchStmts())
  136. Cont = CGF.getJumpDestInCurrentScope("eh.cont");
  137. bool useFunclets = EHPersonality::get(CGF).usesFuncletPads();
  138. CodeGenFunction::FinallyInfo FinallyInfo;
  139. if (!useFunclets)
  140. if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
  141. FinallyInfo.enter(CGF, Finally->getFinallyBody(),
  142. beginCatchFn, endCatchFn, exceptionRethrowFn);
  143. SmallVector<CatchHandler, 8> Handlers;
  144. // Enter the catch, if there is one.
  145. if (S.getNumCatchStmts()) {
  146. for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {
  147. const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);
  148. const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
  149. Handlers.push_back(CatchHandler());
  150. CatchHandler &Handler = Handlers.back();
  151. Handler.Variable = CatchDecl;
  152. Handler.Body = CatchStmt->getCatchBody();
  153. Handler.Block = CGF.createBasicBlock("catch");
  154. Handler.Flags = 0;
  155. // @catch(...) always matches.
  156. if (!CatchDecl) {
  157. auto catchAll = getCatchAllTypeInfo();
  158. Handler.TypeInfo = catchAll.RTTI;
  159. Handler.Flags = catchAll.Flags;
  160. // Don't consider any other catches.
  161. break;
  162. }
  163. Handler.TypeInfo = GetEHType(CatchDecl->getType());
  164. }
  165. EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
  166. for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
  167. Catch->setHandler(I, { Handlers[I].TypeInfo, Handlers[I].Flags }, Handlers[I].Block);
  168. }
  169. if (useFunclets)
  170. if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
  171. CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
  172. if (!CGF.CurSEHParent)
  173. CGF.CurSEHParent = cast<NamedDecl>(CGF.CurFuncDecl);
  174. // Outline the finally block.
  175. const Stmt *FinallyBlock = Finally->getFinallyBody();
  176. HelperCGF.startOutlinedSEHHelper(CGF, /*isFilter*/false, FinallyBlock);
  177. // Emit the original filter expression, convert to i32, and return.
  178. HelperCGF.EmitStmt(FinallyBlock);
  179. HelperCGF.FinishFunction(FinallyBlock->getEndLoc());
  180. llvm::Function *FinallyFunc = HelperCGF.CurFn;
  181. // Push a cleanup for __finally blocks.
  182. CGF.pushSEHCleanup(NormalAndEHCleanup, FinallyFunc);
  183. }
  184. // Emit the try body.
  185. CGF.EmitStmt(S.getTryBody());
  186. // Leave the try.
  187. if (S.getNumCatchStmts())
  188. CGF.popCatchScope();
  189. // Remember where we were.
  190. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
  191. // Emit the handlers.
  192. for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
  193. CatchHandler &Handler = Handlers[I];
  194. CGF.EmitBlock(Handler.Block);
  195. llvm::CatchPadInst *CPI = nullptr;
  196. SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(CGF.CurrentFuncletPad);
  197. if (useFunclets)
  198. if ((CPI = dyn_cast_or_null<llvm::CatchPadInst>(Handler.Block->getFirstNonPHI()))) {
  199. CGF.CurrentFuncletPad = CPI;
  200. CPI->setOperand(2, CGF.getExceptionSlot().getPointer());
  201. }
  202. llvm::Value *RawExn = CGF.getExceptionFromSlot();
  203. // Enter the catch.
  204. llvm::Value *Exn = RawExn;
  205. if (beginCatchFn)
  206. Exn = CGF.EmitNounwindRuntimeCall(beginCatchFn, RawExn, "exn.adjusted");
  207. CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());
  208. if (endCatchFn) {
  209. // Add a cleanup to leave the catch.
  210. bool EndCatchMightThrow = (Handler.Variable == nullptr);
  211. CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
  212. EndCatchMightThrow,
  213. endCatchFn);
  214. }
  215. // Bind the catch parameter if it exists.
  216. if (const VarDecl *CatchParam = Handler.Variable) {
  217. llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
  218. llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
  219. CGF.EmitAutoVarDecl(*CatchParam);
  220. EmitInitOfCatchParam(CGF, CastExn, CatchParam);
  221. }
  222. if (CPI)
  223. CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
  224. CGF.ObjCEHValueStack.push_back(Exn);
  225. CGF.EmitStmt(Handler.Body);
  226. CGF.ObjCEHValueStack.pop_back();
  227. // Leave any cleanups associated with the catch.
  228. cleanups.ForceCleanup();
  229. CGF.EmitBranchThroughCleanup(Cont);
  230. }
  231. // Go back to the try-statement fallthrough.
  232. CGF.Builder.restoreIP(SavedIP);
  233. // Pop out of the finally.
  234. if (!useFunclets && S.getFinallyStmt())
  235. FinallyInfo.exit(CGF);
  236. if (Cont.isValid())
  237. CGF.EmitBlock(Cont.getBlock());
  238. }
  239. void CGObjCRuntime::EmitInitOfCatchParam(CodeGenFunction &CGF,
  240. llvm::Value *exn,
  241. const VarDecl *paramDecl) {
  242. Address paramAddr = CGF.GetAddrOfLocalVar(paramDecl);
  243. switch (paramDecl->getType().getQualifiers().getObjCLifetime()) {
  244. case Qualifiers::OCL_Strong:
  245. exn = CGF.EmitARCRetainNonBlock(exn);
  246. LLVM_FALLTHROUGH;
  247. case Qualifiers::OCL_None:
  248. case Qualifiers::OCL_ExplicitNone:
  249. case Qualifiers::OCL_Autoreleasing:
  250. CGF.Builder.CreateStore(exn, paramAddr);
  251. return;
  252. case Qualifiers::OCL_Weak:
  253. CGF.EmitARCInitWeak(paramAddr, exn);
  254. return;
  255. }
  256. llvm_unreachable("invalid ownership qualifier");
  257. }
  258. namespace {
  259. struct CallSyncExit final : EHScopeStack::Cleanup {
  260. llvm::FunctionCallee SyncExitFn;
  261. llvm::Value *SyncArg;
  262. CallSyncExit(llvm::FunctionCallee SyncExitFn, llvm::Value *SyncArg)
  263. : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
  264. void Emit(CodeGenFunction &CGF, Flags flags) override {
  265. CGF.EmitNounwindRuntimeCall(SyncExitFn, SyncArg);
  266. }
  267. };
  268. }
  269. void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
  270. const ObjCAtSynchronizedStmt &S,
  271. llvm::FunctionCallee syncEnterFn,
  272. llvm::FunctionCallee syncExitFn) {
  273. CodeGenFunction::RunCleanupsScope cleanups(CGF);
  274. // Evaluate the lock operand. This is guaranteed to dominate the
  275. // ARC release and lock-release cleanups.
  276. const Expr *lockExpr = S.getSynchExpr();
  277. llvm::Value *lock;
  278. if (CGF.getLangOpts().ObjCAutoRefCount) {
  279. lock = CGF.EmitARCRetainScalarExpr(lockExpr);
  280. lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
  281. } else {
  282. lock = CGF.EmitScalarExpr(lockExpr);
  283. }
  284. lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
  285. // Acquire the lock.
  286. CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
  287. // Register an all-paths cleanup to release the lock.
  288. CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
  289. // Emit the body of the statement.
  290. CGF.EmitStmt(S.getSynchBody());
  291. }
  292. /// Compute the pointer-to-function type to which a message send
  293. /// should be casted in order to correctly call the given method
  294. /// with the given arguments.
  295. ///
  296. /// \param method - may be null
  297. /// \param resultType - the result type to use if there's no method
  298. /// \param callArgs - the actual arguments, including implicit ones
  299. CGObjCRuntime::MessageSendInfo
  300. CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
  301. QualType resultType,
  302. CallArgList &callArgs) {
  303. // If there's a method, use information from that.
  304. if (method) {
  305. const CGFunctionInfo &signature =
  306. CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
  307. llvm::PointerType *signatureType =
  308. CGM.getTypes().GetFunctionType(signature)->getPointerTo();
  309. const CGFunctionInfo &signatureForCall =
  310. CGM.getTypes().arrangeCall(signature, callArgs);
  311. return MessageSendInfo(signatureForCall, signatureType);
  312. }
  313. // There's no method; just use a default CC.
  314. const CGFunctionInfo &argsInfo =
  315. CGM.getTypes().arrangeUnprototypedObjCMessageSend(resultType, callArgs);
  316. // Derive the signature to call from that.
  317. llvm::PointerType *signatureType =
  318. CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();
  319. return MessageSendInfo(argsInfo, signatureType);
  320. }