CGObjCRuntime.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 "CGCXXABI.h"
  16. #include "CGCleanup.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 "clang/CodeGen/CodeGenABITypes.h"
  24. #include "llvm/Support/SaveAndRestore.h"
  25. using namespace clang;
  26. using namespace CodeGen;
  27. uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
  28. const ObjCInterfaceDecl *OID,
  29. const ObjCIvarDecl *Ivar) {
  30. return CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar) /
  31. CGM.getContext().getCharWidth();
  32. }
  33. uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
  34. const ObjCImplementationDecl *OID,
  35. const ObjCIvarDecl *Ivar) {
  36. return CGM.getContext().lookupFieldBitOffset(OID->getClassInterface(), OID,
  37. Ivar) /
  38. CGM.getContext().getCharWidth();
  39. }
  40. unsigned CGObjCRuntime::ComputeBitfieldBitOffset(
  41. CodeGen::CodeGenModule &CGM,
  42. const ObjCInterfaceDecl *ID,
  43. const ObjCIvarDecl *Ivar) {
  44. return CGM.getContext().lookupFieldBitOffset(ID, ID->getImplementation(),
  45. Ivar);
  46. }
  47. LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
  48. const ObjCInterfaceDecl *OID,
  49. llvm::Value *BaseValue,
  50. const ObjCIvarDecl *Ivar,
  51. unsigned CVRQualifiers,
  52. llvm::Value *Offset) {
  53. // Compute (type*) ( (char *) BaseValue + Offset)
  54. QualType InterfaceTy{OID->getTypeForDecl(), 0};
  55. QualType ObjectPtrTy =
  56. CGF.CGM.getContext().getObjCObjectPointerType(InterfaceTy);
  57. QualType IvarTy =
  58. Ivar->getUsageType(ObjectPtrTy).withCVRQualifiers(CVRQualifiers);
  59. llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
  60. llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy);
  61. V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, V, Offset, "add.ptr");
  62. if (!Ivar->isBitField()) {
  63. V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
  64. LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
  65. return LV;
  66. }
  67. // We need to compute an access strategy for this bit-field. We are given the
  68. // offset to the first byte in the bit-field, the sub-byte offset is taken
  69. // from the original layout. We reuse the normal bit-field access strategy by
  70. // treating this as an access to a struct where the bit-field is in byte 0,
  71. // and adjust the containing type size as appropriate.
  72. //
  73. // FIXME: Note that currently we make a very conservative estimate of the
  74. // alignment of the bit-field, because (a) it is not clear what guarantees the
  75. // runtime makes us, and (b) we don't have a way to specify that the struct is
  76. // at an alignment plus offset.
  77. //
  78. // Note, there is a subtle invariant here: we can only call this routine on
  79. // non-synthesized ivars but we may be called for synthesized ivars. However,
  80. // a synthesized ivar can never be a bit-field, so this is safe.
  81. uint64_t FieldBitOffset =
  82. CGF.CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar);
  83. uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
  84. uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign();
  85. uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
  86. CharUnits StorageSize = CGF.CGM.getContext().toCharUnitsFromBits(
  87. llvm::alignTo(BitOffset + BitFieldSize, AlignmentBits));
  88. CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits);
  89. // Allocate a new CGBitFieldInfo object to describe this access.
  90. //
  91. // FIXME: This is incredibly wasteful, these should be uniqued or part of some
  92. // layout object. However, this is blocked on other cleanups to the
  93. // Objective-C code, so for now we just live with allocating a bunch of these
  94. // objects.
  95. CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
  96. CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
  97. CGF.CGM.getContext().toBits(StorageSize),
  98. CharUnits::fromQuantity(0)));
  99. Address Addr(V, Alignment);
  100. Addr = CGF.Builder.CreateElementBitCast(Addr,
  101. llvm::Type::getIntNTy(CGF.getLLVMContext(),
  102. Info->StorageSize));
  103. return LValue::MakeBitfield(Addr, *Info, IvarTy,
  104. LValueBaseInfo(AlignmentSource::Decl),
  105. TBAAAccessInfo());
  106. }
  107. namespace {
  108. struct CatchHandler {
  109. const VarDecl *Variable;
  110. const Stmt *Body;
  111. llvm::BasicBlock *Block;
  112. llvm::Constant *TypeInfo;
  113. /// Flags used to differentiate cleanups and catchalls in Windows SEH
  114. unsigned Flags;
  115. };
  116. struct CallObjCEndCatch final : EHScopeStack::Cleanup {
  117. CallObjCEndCatch(bool MightThrow, llvm::FunctionCallee Fn)
  118. : MightThrow(MightThrow), Fn(Fn) {}
  119. bool MightThrow;
  120. llvm::FunctionCallee Fn;
  121. void Emit(CodeGenFunction &CGF, Flags flags) override {
  122. if (MightThrow)
  123. CGF.EmitRuntimeCallOrInvoke(Fn);
  124. else
  125. CGF.EmitNounwindRuntimeCall(Fn);
  126. }
  127. };
  128. }
  129. void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
  130. const ObjCAtTryStmt &S,
  131. llvm::FunctionCallee beginCatchFn,
  132. llvm::FunctionCallee endCatchFn,
  133. llvm::FunctionCallee exceptionRethrowFn) {
  134. // Jump destination for falling out of catch bodies.
  135. CodeGenFunction::JumpDest Cont;
  136. if (S.getNumCatchStmts())
  137. Cont = CGF.getJumpDestInCurrentScope("eh.cont");
  138. bool useFunclets = EHPersonality::get(CGF).usesFuncletPads();
  139. CodeGenFunction::FinallyInfo FinallyInfo;
  140. if (!useFunclets)
  141. if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
  142. FinallyInfo.enter(CGF, Finally->getFinallyBody(),
  143. beginCatchFn, endCatchFn, exceptionRethrowFn);
  144. SmallVector<CatchHandler, 8> Handlers;
  145. // Enter the catch, if there is one.
  146. if (S.getNumCatchStmts()) {
  147. for (const ObjCAtCatchStmt *CatchStmt : S.catch_stmts()) {
  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. }
  321. bool CGObjCRuntime::canMessageReceiverBeNull(CodeGenFunction &CGF,
  322. const ObjCMethodDecl *method,
  323. bool isSuper,
  324. const ObjCInterfaceDecl *classReceiver,
  325. llvm::Value *receiver) {
  326. // Super dispatch assumes that self is non-null; even the messenger
  327. // doesn't have a null check internally.
  328. if (isSuper)
  329. return false;
  330. // If this is a direct dispatch of a class method, check whether the class,
  331. // or anything in its hierarchy, was weak-linked.
  332. if (classReceiver && method && method->isClassMethod())
  333. return isWeakLinkedClass(classReceiver);
  334. // If we're emitting a method, and self is const (meaning just ARC, for now),
  335. // and the receiver is a load of self, then self is a valid object.
  336. if (auto curMethod =
  337. dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) {
  338. auto self = curMethod->getSelfDecl();
  339. if (self->getType().isConstQualified()) {
  340. if (auto LI = dyn_cast<llvm::LoadInst>(receiver->stripPointerCasts())) {
  341. llvm::Value *selfAddr = CGF.GetAddrOfLocalVar(self).getPointer();
  342. if (selfAddr == LI->getPointerOperand()) {
  343. return false;
  344. }
  345. }
  346. }
  347. }
  348. // Otherwise, assume it can be null.
  349. return true;
  350. }
  351. bool CGObjCRuntime::isWeakLinkedClass(const ObjCInterfaceDecl *ID) {
  352. do {
  353. if (ID->isWeakImported())
  354. return true;
  355. } while ((ID = ID->getSuperClass()));
  356. return false;
  357. }
  358. void CGObjCRuntime::destroyCalleeDestroyedArguments(CodeGenFunction &CGF,
  359. const ObjCMethodDecl *method,
  360. const CallArgList &callArgs) {
  361. CallArgList::const_iterator I = callArgs.begin();
  362. for (auto i = method->param_begin(), e = method->param_end();
  363. i != e; ++i, ++I) {
  364. const ParmVarDecl *param = (*i);
  365. if (param->hasAttr<NSConsumedAttr>()) {
  366. RValue RV = I->getRValue(CGF);
  367. assert(RV.isScalar() &&
  368. "NullReturnState::complete - arg not on object");
  369. CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
  370. } else {
  371. QualType QT = param->getType();
  372. auto *RT = QT->getAs<RecordType>();
  373. if (RT && RT->getDecl()->isParamDestroyedInCallee()) {
  374. RValue RV = I->getRValue(CGF);
  375. QualType::DestructionKind DtorKind = QT.isDestructedType();
  376. switch (DtorKind) {
  377. case QualType::DK_cxx_destructor:
  378. CGF.destroyCXXObject(CGF, RV.getAggregateAddress(), QT);
  379. break;
  380. case QualType::DK_nontrivial_c_struct:
  381. CGF.destroyNonTrivialCStruct(CGF, RV.getAggregateAddress(), QT);
  382. break;
  383. default:
  384. llvm_unreachable("unexpected dtor kind");
  385. break;
  386. }
  387. }
  388. }
  389. }
  390. }
  391. llvm::Constant *
  392. clang::CodeGen::emitObjCProtocolObject(CodeGenModule &CGM,
  393. const ObjCProtocolDecl *protocol) {
  394. return CGM.getObjCRuntime().GetOrEmitProtocol(protocol);
  395. }
  396. std::string CGObjCRuntime::getSymbolNameForMethod(const ObjCMethodDecl *OMD,
  397. bool includeCategoryName) {
  398. std::string buffer;
  399. llvm::raw_string_ostream out(buffer);
  400. CGM.getCXXABI().getMangleContext().mangleObjCMethodName(OMD, out,
  401. /*includePrefixByte=*/true,
  402. includeCategoryName);
  403. return buffer;
  404. }