CGObjCRuntime.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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/IR/Instruction.h"
  25. #include "llvm/Support/SaveAndRestore.h"
  26. using namespace clang;
  27. using namespace CodeGen;
  28. uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
  29. const ObjCInterfaceDecl *OID,
  30. const ObjCIvarDecl *Ivar) {
  31. return CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar) /
  32. CGM.getContext().getCharWidth();
  33. }
  34. uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
  35. const ObjCImplementationDecl *OID,
  36. const ObjCIvarDecl *Ivar) {
  37. return CGM.getContext().lookupFieldBitOffset(OID->getClassInterface(), OID,
  38. Ivar) /
  39. CGM.getContext().getCharWidth();
  40. }
  41. unsigned CGObjCRuntime::ComputeBitfieldBitOffset(
  42. CodeGen::CodeGenModule &CGM,
  43. const ObjCInterfaceDecl *ID,
  44. const ObjCIvarDecl *Ivar) {
  45. return CGM.getContext().lookupFieldBitOffset(ID, ID->getImplementation(),
  46. Ivar);
  47. }
  48. LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
  49. const ObjCInterfaceDecl *OID,
  50. llvm::Value *BaseValue,
  51. const ObjCIvarDecl *Ivar,
  52. unsigned CVRQualifiers,
  53. llvm::Value *Offset) {
  54. // Compute (type*) ( (char *) BaseValue + Offset)
  55. QualType InterfaceTy{OID->getTypeForDecl(), 0};
  56. QualType ObjectPtrTy =
  57. CGF.CGM.getContext().getObjCObjectPointerType(InterfaceTy);
  58. QualType IvarTy =
  59. Ivar->getUsageType(ObjectPtrTy).withCVRQualifiers(CVRQualifiers);
  60. llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
  61. llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, CGF.Int8PtrTy);
  62. V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, V, Offset, "add.ptr");
  63. if (!Ivar->isBitField()) {
  64. V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
  65. LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
  66. return LV;
  67. }
  68. // We need to compute an access strategy for this bit-field. We are given the
  69. // offset to the first byte in the bit-field, the sub-byte offset is taken
  70. // from the original layout. We reuse the normal bit-field access strategy by
  71. // treating this as an access to a struct where the bit-field is in byte 0,
  72. // and adjust the containing type size as appropriate.
  73. //
  74. // FIXME: Note that currently we make a very conservative estimate of the
  75. // alignment of the bit-field, because (a) it is not clear what guarantees the
  76. // runtime makes us, and (b) we don't have a way to specify that the struct is
  77. // at an alignment plus offset.
  78. //
  79. // Note, there is a subtle invariant here: we can only call this routine on
  80. // non-synthesized ivars but we may be called for synthesized ivars. However,
  81. // a synthesized ivar can never be a bit-field, so this is safe.
  82. uint64_t FieldBitOffset =
  83. CGF.CGM.getContext().lookupFieldBitOffset(OID, nullptr, Ivar);
  84. uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
  85. uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign();
  86. uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
  87. CharUnits StorageSize = CGF.CGM.getContext().toCharUnitsFromBits(
  88. llvm::alignTo(BitOffset + BitFieldSize, AlignmentBits));
  89. CharUnits Alignment = CGF.CGM.getContext().toCharUnitsFromBits(AlignmentBits);
  90. // Allocate a new CGBitFieldInfo object to describe this access.
  91. //
  92. // FIXME: This is incredibly wasteful, these should be uniqued or part of some
  93. // layout object. However, this is blocked on other cleanups to the
  94. // Objective-C code, so for now we just live with allocating a bunch of these
  95. // objects.
  96. CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(
  97. CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,
  98. CGF.CGM.getContext().toBits(StorageSize),
  99. CharUnits::fromQuantity(0)));
  100. Address Addr = Address(V, CGF.Int8Ty, Alignment);
  101. Addr = CGF.Builder.CreateElementBitCast(Addr,
  102. llvm::Type::getIntNTy(CGF.getLLVMContext(),
  103. Info->StorageSize));
  104. return LValue::MakeBitfield(Addr, *Info, IvarTy,
  105. LValueBaseInfo(AlignmentSource::Decl),
  106. TBAAAccessInfo());
  107. }
  108. namespace {
  109. struct CatchHandler {
  110. const VarDecl *Variable;
  111. const Stmt *Body;
  112. llvm::BasicBlock *Block;
  113. llvm::Constant *TypeInfo;
  114. /// Flags used to differentiate cleanups and catchalls in Windows SEH
  115. unsigned Flags;
  116. };
  117. struct CallObjCEndCatch final : EHScopeStack::Cleanup {
  118. CallObjCEndCatch(bool MightThrow, llvm::FunctionCallee Fn)
  119. : MightThrow(MightThrow), Fn(Fn) {}
  120. bool MightThrow;
  121. llvm::FunctionCallee Fn;
  122. void Emit(CodeGenFunction &CGF, Flags flags) override {
  123. if (MightThrow)
  124. CGF.EmitRuntimeCallOrInvoke(Fn);
  125. else
  126. CGF.EmitNounwindRuntimeCall(Fn);
  127. }
  128. };
  129. }
  130. void CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,
  131. const ObjCAtTryStmt &S,
  132. llvm::FunctionCallee beginCatchFn,
  133. llvm::FunctionCallee endCatchFn,
  134. llvm::FunctionCallee exceptionRethrowFn) {
  135. // Jump destination for falling out of catch bodies.
  136. CodeGenFunction::JumpDest Cont;
  137. if (S.getNumCatchStmts())
  138. Cont = CGF.getJumpDestInCurrentScope("eh.cont");
  139. bool useFunclets = EHPersonality::get(CGF).usesFuncletPads();
  140. CodeGenFunction::FinallyInfo FinallyInfo;
  141. if (!useFunclets)
  142. if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())
  143. FinallyInfo.enter(CGF, Finally->getFinallyBody(),
  144. beginCatchFn, endCatchFn, exceptionRethrowFn);
  145. SmallVector<CatchHandler, 8> Handlers;
  146. // Enter the catch, if there is one.
  147. if (S.getNumCatchStmts()) {
  148. for (const ObjCAtCatchStmt *CatchStmt : S.catch_stmts()) {
  149. const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
  150. Handlers.push_back(CatchHandler());
  151. CatchHandler &Handler = Handlers.back();
  152. Handler.Variable = CatchDecl;
  153. Handler.Body = CatchStmt->getCatchBody();
  154. Handler.Block = CGF.createBasicBlock("catch");
  155. Handler.Flags = 0;
  156. // @catch(...) always matches.
  157. if (!CatchDecl) {
  158. auto catchAll = getCatchAllTypeInfo();
  159. Handler.TypeInfo = catchAll.RTTI;
  160. Handler.Flags = catchAll.Flags;
  161. // Don't consider any other catches.
  162. break;
  163. }
  164. Handler.TypeInfo = GetEHType(CatchDecl->getType());
  165. }
  166. EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());
  167. for (unsigned I = 0, E = Handlers.size(); I != E; ++I)
  168. Catch->setHandler(I, { Handlers[I].TypeInfo, Handlers[I].Flags }, Handlers[I].Block);
  169. }
  170. if (useFunclets)
  171. if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt()) {
  172. CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
  173. if (!CGF.CurSEHParent)
  174. CGF.CurSEHParent = cast<NamedDecl>(CGF.CurFuncDecl);
  175. // Outline the finally block.
  176. const Stmt *FinallyBlock = Finally->getFinallyBody();
  177. HelperCGF.startOutlinedSEHHelper(CGF, /*isFilter*/false, FinallyBlock);
  178. // Emit the original filter expression, convert to i32, and return.
  179. HelperCGF.EmitStmt(FinallyBlock);
  180. HelperCGF.FinishFunction(FinallyBlock->getEndLoc());
  181. llvm::Function *FinallyFunc = HelperCGF.CurFn;
  182. // Push a cleanup for __finally blocks.
  183. CGF.pushSEHCleanup(NormalAndEHCleanup, FinallyFunc);
  184. }
  185. // Emit the try body.
  186. CGF.EmitStmt(S.getTryBody());
  187. // Leave the try.
  188. if (S.getNumCatchStmts())
  189. CGF.popCatchScope();
  190. // Remember where we were.
  191. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
  192. // Emit the handlers.
  193. for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
  194. CatchHandler &Handler = Handlers[I];
  195. CGF.EmitBlock(Handler.Block);
  196. CodeGenFunction::LexicalScope Cleanups(CGF, Handler.Body->getSourceRange());
  197. SaveAndRestore RevertAfterScope(CGF.CurrentFuncletPad);
  198. if (useFunclets) {
  199. llvm::Instruction *CPICandidate = Handler.Block->getFirstNonPHI();
  200. if (auto *CPI = dyn_cast_or_null<llvm::CatchPadInst>(CPICandidate)) {
  201. CGF.CurrentFuncletPad = CPI;
  202. CPI->setOperand(2, CGF.getExceptionSlot().getPointer());
  203. CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
  204. }
  205. }
  206. llvm::Value *RawExn = CGF.getExceptionFromSlot();
  207. // Enter the catch.
  208. llvm::Value *Exn = RawExn;
  209. if (beginCatchFn)
  210. Exn = CGF.EmitNounwindRuntimeCall(beginCatchFn, RawExn, "exn.adjusted");
  211. if (endCatchFn) {
  212. // Add a cleanup to leave the catch.
  213. bool EndCatchMightThrow = (Handler.Variable == nullptr);
  214. CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,
  215. EndCatchMightThrow,
  216. endCatchFn);
  217. }
  218. // Bind the catch parameter if it exists.
  219. if (const VarDecl *CatchParam = Handler.Variable) {
  220. llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());
  221. llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);
  222. CGF.EmitAutoVarDecl(*CatchParam);
  223. EmitInitOfCatchParam(CGF, CastExn, CatchParam);
  224. }
  225. CGF.ObjCEHValueStack.push_back(Exn);
  226. CGF.EmitStmt(Handler.Body);
  227. CGF.ObjCEHValueStack.pop_back();
  228. // Leave any cleanups associated with the catch.
  229. Cleanups.ForceCleanup();
  230. CGF.EmitBranchThroughCleanup(Cont);
  231. }
  232. // Go back to the try-statement fallthrough.
  233. CGF.Builder.restoreIP(SavedIP);
  234. // Pop out of the finally.
  235. if (!useFunclets && S.getFinallyStmt())
  236. FinallyInfo.exit(CGF);
  237. if (Cont.isValid())
  238. CGF.EmitBlock(Cont.getBlock());
  239. }
  240. void CGObjCRuntime::EmitInitOfCatchParam(CodeGenFunction &CGF,
  241. llvm::Value *exn,
  242. const VarDecl *paramDecl) {
  243. Address paramAddr = CGF.GetAddrOfLocalVar(paramDecl);
  244. switch (paramDecl->getType().getQualifiers().getObjCLifetime()) {
  245. case Qualifiers::OCL_Strong:
  246. exn = CGF.EmitARCRetainNonBlock(exn);
  247. [[fallthrough]];
  248. case Qualifiers::OCL_None:
  249. case Qualifiers::OCL_ExplicitNone:
  250. case Qualifiers::OCL_Autoreleasing:
  251. CGF.Builder.CreateStore(exn, paramAddr);
  252. return;
  253. case Qualifiers::OCL_Weak:
  254. CGF.EmitARCInitWeak(paramAddr, exn);
  255. return;
  256. }
  257. llvm_unreachable("invalid ownership qualifier");
  258. }
  259. namespace {
  260. struct CallSyncExit final : EHScopeStack::Cleanup {
  261. llvm::FunctionCallee SyncExitFn;
  262. llvm::Value *SyncArg;
  263. CallSyncExit(llvm::FunctionCallee SyncExitFn, llvm::Value *SyncArg)
  264. : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}
  265. void Emit(CodeGenFunction &CGF, Flags flags) override {
  266. CGF.EmitNounwindRuntimeCall(SyncExitFn, SyncArg);
  267. }
  268. };
  269. }
  270. void CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,
  271. const ObjCAtSynchronizedStmt &S,
  272. llvm::FunctionCallee syncEnterFn,
  273. llvm::FunctionCallee syncExitFn) {
  274. CodeGenFunction::RunCleanupsScope cleanups(CGF);
  275. // Evaluate the lock operand. This is guaranteed to dominate the
  276. // ARC release and lock-release cleanups.
  277. const Expr *lockExpr = S.getSynchExpr();
  278. llvm::Value *lock;
  279. if (CGF.getLangOpts().ObjCAutoRefCount) {
  280. lock = CGF.EmitARCRetainScalarExpr(lockExpr);
  281. lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
  282. } else {
  283. lock = CGF.EmitScalarExpr(lockExpr);
  284. }
  285. lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);
  286. // Acquire the lock.
  287. CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();
  288. // Register an all-paths cleanup to release the lock.
  289. CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);
  290. // Emit the body of the statement.
  291. CGF.EmitStmt(S.getSynchBody());
  292. }
  293. /// Compute the pointer-to-function type to which a message send
  294. /// should be casted in order to correctly call the given method
  295. /// with the given arguments.
  296. ///
  297. /// \param method - may be null
  298. /// \param resultType - the result type to use if there's no method
  299. /// \param callArgs - the actual arguments, including implicit ones
  300. CGObjCRuntime::MessageSendInfo
  301. CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
  302. QualType resultType,
  303. CallArgList &callArgs) {
  304. unsigned ProgramAS = CGM.getDataLayout().getProgramAddressSpace();
  305. // If there's a method, use information from that.
  306. if (method) {
  307. const CGFunctionInfo &signature =
  308. CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);
  309. llvm::PointerType *signatureType =
  310. CGM.getTypes().GetFunctionType(signature)->getPointerTo(ProgramAS);
  311. const CGFunctionInfo &signatureForCall =
  312. CGM.getTypes().arrangeCall(signature, callArgs);
  313. return MessageSendInfo(signatureForCall, signatureType);
  314. }
  315. // There's no method; just use a default CC.
  316. const CGFunctionInfo &argsInfo =
  317. CGM.getTypes().arrangeUnprototypedObjCMessageSend(resultType, callArgs);
  318. // Derive the signature to call from that.
  319. llvm::PointerType *signatureType =
  320. CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo(ProgramAS);
  321. return MessageSendInfo(argsInfo, signatureType);
  322. }
  323. bool CGObjCRuntime::canMessageReceiverBeNull(CodeGenFunction &CGF,
  324. const ObjCMethodDecl *method,
  325. bool isSuper,
  326. const ObjCInterfaceDecl *classReceiver,
  327. llvm::Value *receiver) {
  328. // Super dispatch assumes that self is non-null; even the messenger
  329. // doesn't have a null check internally.
  330. if (isSuper)
  331. return false;
  332. // If this is a direct dispatch of a class method, check whether the class,
  333. // or anything in its hierarchy, was weak-linked.
  334. if (classReceiver && method && method->isClassMethod())
  335. return isWeakLinkedClass(classReceiver);
  336. // If we're emitting a method, and self is const (meaning just ARC, for now),
  337. // and the receiver is a load of self, then self is a valid object.
  338. if (auto curMethod =
  339. dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) {
  340. auto self = curMethod->getSelfDecl();
  341. if (self->getType().isConstQualified()) {
  342. if (auto LI = dyn_cast<llvm::LoadInst>(receiver->stripPointerCasts())) {
  343. llvm::Value *selfAddr = CGF.GetAddrOfLocalVar(self).getPointer();
  344. if (selfAddr == LI->getPointerOperand()) {
  345. return false;
  346. }
  347. }
  348. }
  349. }
  350. // Otherwise, assume it can be null.
  351. return true;
  352. }
  353. bool CGObjCRuntime::isWeakLinkedClass(const ObjCInterfaceDecl *ID) {
  354. do {
  355. if (ID->isWeakImported())
  356. return true;
  357. } while ((ID = ID->getSuperClass()));
  358. return false;
  359. }
  360. void CGObjCRuntime::destroyCalleeDestroyedArguments(CodeGenFunction &CGF,
  361. const ObjCMethodDecl *method,
  362. const CallArgList &callArgs) {
  363. CallArgList::const_iterator I = callArgs.begin();
  364. for (auto i = method->param_begin(), e = method->param_end();
  365. i != e; ++i, ++I) {
  366. const ParmVarDecl *param = (*i);
  367. if (param->hasAttr<NSConsumedAttr>()) {
  368. RValue RV = I->getRValue(CGF);
  369. assert(RV.isScalar() &&
  370. "NullReturnState::complete - arg not on object");
  371. CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
  372. } else {
  373. QualType QT = param->getType();
  374. auto *RT = QT->getAs<RecordType>();
  375. if (RT && RT->getDecl()->isParamDestroyedInCallee()) {
  376. RValue RV = I->getRValue(CGF);
  377. QualType::DestructionKind DtorKind = QT.isDestructedType();
  378. switch (DtorKind) {
  379. case QualType::DK_cxx_destructor:
  380. CGF.destroyCXXObject(CGF, RV.getAggregateAddress(), QT);
  381. break;
  382. case QualType::DK_nontrivial_c_struct:
  383. CGF.destroyNonTrivialCStruct(CGF, RV.getAggregateAddress(), QT);
  384. break;
  385. default:
  386. llvm_unreachable("unexpected dtor kind");
  387. break;
  388. }
  389. }
  390. }
  391. }
  392. }
  393. llvm::Constant *
  394. clang::CodeGen::emitObjCProtocolObject(CodeGenModule &CGM,
  395. const ObjCProtocolDecl *protocol) {
  396. return CGM.getObjCRuntime().GetOrEmitProtocol(protocol);
  397. }
  398. std::string CGObjCRuntime::getSymbolNameForMethod(const ObjCMethodDecl *OMD,
  399. bool includeCategoryName) {
  400. std::string buffer;
  401. llvm::raw_string_ostream out(buffer);
  402. CGM.getCXXABI().getMangleContext().mangleObjCMethodName(OMD, out,
  403. /*includePrefixByte=*/true,
  404. includeCategoryName);
  405. return buffer;
  406. }