objc-object.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. /*
  2. * Copyright (c) 2010-2012 Apple Inc. All rights reserved.
  3. *
  4. * @APPLE_LICENSE_HEADER_START@
  5. *
  6. * This file contains Original Code and/or Modifications of Original Code
  7. * as defined in and that are subject to the Apple Public Source License
  8. * Version 2.0 (the 'License'). You may not use this file except in
  9. * compliance with the License. Please obtain a copy of the License at
  10. * http://www.opensource.apple.com/apsl/ and read it before using this
  11. * file.
  12. *
  13. * The Original Code and all software distributed under the License are
  14. * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  15. * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  16. * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  18. * Please see the License for the specific language governing rights and
  19. * limitations under the License.
  20. *
  21. * @APPLE_LICENSE_HEADER_END@
  22. */
  23. /***********************************************************************
  24. * Inlineable parts of NSObject / objc_object implementation
  25. **********************************************************************/
  26. #ifndef _OBJC_OBJCOBJECT_H_
  27. #define _OBJC_OBJCOBJECT_H_
  28. #include "objc-private.h"
  29. enum ReturnDisposition : bool {
  30. ReturnAtPlus0 = false, ReturnAtPlus1 = true
  31. };
  32. static ALWAYS_INLINE
  33. bool prepareOptimizedReturn(ReturnDisposition disposition);
  34. #if SUPPORT_TAGGED_POINTERS
  35. extern "C" {
  36. extern Class objc_debug_taggedpointer_classes[_OBJC_TAG_SLOT_COUNT*2];
  37. extern Class objc_debug_taggedpointer_ext_classes[_OBJC_TAG_EXT_SLOT_COUNT];
  38. }
  39. #define objc_tag_classes objc_debug_taggedpointer_classes
  40. #define objc_tag_ext_classes objc_debug_taggedpointer_ext_classes
  41. #endif
  42. #if SUPPORT_INDEXED_ISA
  43. ALWAYS_INLINE Class &
  44. classForIndex(uintptr_t index) {
  45. assert(index > 0);
  46. assert(index < (uintptr_t)objc_indexed_classes_count);
  47. return objc_indexed_classes[index];
  48. }
  49. #endif
  50. inline bool
  51. objc_object::isClass()
  52. {
  53. if (isTaggedPointer()) return false;
  54. return ISA()->isMetaClass();
  55. }
  56. #if SUPPORT_TAGGED_POINTERS
  57. inline Class
  58. objc_object::getIsa()
  59. {
  60. if (!isTaggedPointer()) return ISA();
  61. uintptr_t ptr = (uintptr_t)this;
  62. if (isExtTaggedPointer()) {
  63. uintptr_t slot =
  64. (ptr >> _OBJC_TAG_EXT_SLOT_SHIFT) & _OBJC_TAG_EXT_SLOT_MASK;
  65. return objc_tag_ext_classes[slot];
  66. } else {
  67. uintptr_t slot =
  68. (ptr >> _OBJC_TAG_SLOT_SHIFT) & _OBJC_TAG_SLOT_MASK;
  69. return objc_tag_classes[slot];
  70. }
  71. }
  72. inline bool
  73. objc_object::isTaggedPointer()
  74. {
  75. return _objc_isTaggedPointer(this);
  76. }
  77. inline bool
  78. objc_object::isBasicTaggedPointer()
  79. {
  80. return isTaggedPointer() && !isExtTaggedPointer();
  81. }
  82. inline bool
  83. objc_object::isExtTaggedPointer()
  84. {
  85. uintptr_t ptr = _objc_decodeTaggedPointer(this);
  86. return (ptr & _OBJC_TAG_EXT_MASK) == _OBJC_TAG_EXT_MASK;
  87. }
  88. // SUPPORT_TAGGED_POINTERS
  89. #else
  90. // not SUPPORT_TAGGED_POINTERS
  91. inline Class
  92. objc_object::getIsa()
  93. {
  94. return ISA();
  95. }
  96. inline bool
  97. objc_object::isTaggedPointer()
  98. {
  99. return false;
  100. }
  101. inline bool
  102. objc_object::isBasicTaggedPointer()
  103. {
  104. return false;
  105. }
  106. inline bool
  107. objc_object::isExtTaggedPointer()
  108. {
  109. return false;
  110. }
  111. // not SUPPORT_TAGGED_POINTERS
  112. #endif
  113. #if SUPPORT_NONPOINTER_ISA
  114. inline Class
  115. objc_object::ISA()
  116. {
  117. assert(!isTaggedPointer());
  118. #if SUPPORT_INDEXED_ISA
  119. if (isa.nonpointer) {
  120. uintptr_t slot = isa.indexcls;
  121. return classForIndex((unsigned)slot);
  122. }
  123. return (Class)isa.bits;
  124. #else
  125. return (Class)(isa.bits & ISA_MASK);
  126. #endif
  127. }
  128. inline bool
  129. objc_object::hasNonpointerIsa()
  130. {
  131. return isa.nonpointer;
  132. }
  133. inline void
  134. objc_object::initIsa(Class cls)
  135. {
  136. initIsa(cls, false, false);
  137. }
  138. inline void
  139. objc_object::initClassIsa(Class cls)
  140. {
  141. if (DisableNonpointerIsa || cls->instancesRequireRawIsa()) {
  142. initIsa(cls, false/*not nonpointer*/, false);
  143. } else {
  144. initIsa(cls, true/*nonpointer*/, false);
  145. }
  146. }
  147. inline void
  148. objc_object::initProtocolIsa(Class cls)
  149. {
  150. return initClassIsa(cls);
  151. }
  152. inline void
  153. objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
  154. {
  155. assert(!cls->instancesRequireRawIsa());
  156. assert(hasCxxDtor == cls->hasCxxDtor());
  157. initIsa(cls, true, hasCxxDtor);
  158. }
  159. inline void
  160. objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor)
  161. {
  162. assert(!isTaggedPointer());
  163. if (!nonpointer) {
  164. isa.cls = cls;
  165. } else {
  166. assert(!DisableNonpointerIsa);
  167. assert(!cls->instancesRequireRawIsa());
  168. isa_t newisa(0);
  169. #if SUPPORT_INDEXED_ISA
  170. assert(cls->classArrayIndex() > 0);
  171. newisa.bits = ISA_INDEX_MAGIC_VALUE;
  172. // isa.magic is part of ISA_MAGIC_VALUE
  173. // isa.nonpointer is part of ISA_MAGIC_VALUE
  174. newisa.has_cxx_dtor = hasCxxDtor;
  175. newisa.indexcls = (uintptr_t)cls->classArrayIndex();
  176. #else
  177. newisa.bits = ISA_MAGIC_VALUE;
  178. // isa.magic is part of ISA_MAGIC_VALUE
  179. // isa.nonpointer is part of ISA_MAGIC_VALUE
  180. newisa.has_cxx_dtor = hasCxxDtor;
  181. newisa.shiftcls = (uintptr_t)cls >> 3;
  182. #endif
  183. // This write must be performed in a single store in some cases
  184. // (for example when realizing a class because other threads
  185. // may simultaneously try to use the class).
  186. // fixme use atomics here to guarantee single-store and to
  187. // guarantee memory order w.r.t. the class index table
  188. // ...but not too atomic because we don't want to hurt instantiation
  189. isa = newisa;
  190. }
  191. }
  192. inline Class
  193. objc_object::changeIsa(Class newCls)
  194. {
  195. // This is almost always true but there are
  196. // enough edge cases that we can't assert it.
  197. // assert(newCls->isFuture() ||
  198. // newCls->isInitializing() || newCls->isInitialized());
  199. assert(!isTaggedPointer());
  200. isa_t oldisa;
  201. isa_t newisa;
  202. bool sideTableLocked = false;
  203. bool transcribeToSideTable = false;
  204. do {
  205. transcribeToSideTable = false;
  206. oldisa = LoadExclusive(&isa.bits);
  207. if ((oldisa.bits == 0 || oldisa.nonpointer) &&
  208. !newCls->isFuture() && newCls->canAllocNonpointer())
  209. {
  210. // 0 -> nonpointer
  211. // nonpointer -> nonpointer
  212. #if SUPPORT_INDEXED_ISA
  213. if (oldisa.bits == 0) newisa.bits = ISA_INDEX_MAGIC_VALUE;
  214. else newisa = oldisa;
  215. // isa.magic is part of ISA_MAGIC_VALUE
  216. // isa.nonpointer is part of ISA_MAGIC_VALUE
  217. newisa.has_cxx_dtor = newCls->hasCxxDtor();
  218. assert(newCls->classArrayIndex() > 0);
  219. newisa.indexcls = (uintptr_t)newCls->classArrayIndex();
  220. #else
  221. if (oldisa.bits == 0) newisa.bits = ISA_MAGIC_VALUE;
  222. else newisa = oldisa;
  223. // isa.magic is part of ISA_MAGIC_VALUE
  224. // isa.nonpointer is part of ISA_MAGIC_VALUE
  225. newisa.has_cxx_dtor = newCls->hasCxxDtor();
  226. newisa.shiftcls = (uintptr_t)newCls >> 3;
  227. #endif
  228. }
  229. else if (oldisa.nonpointer) {
  230. // nonpointer -> raw pointer
  231. // Need to copy retain count et al to side table.
  232. // Acquire side table lock before setting isa to
  233. // prevent races such as concurrent -release.
  234. if (!sideTableLocked) sidetable_lock();
  235. sideTableLocked = true;
  236. transcribeToSideTable = true;
  237. newisa.cls = newCls;
  238. }
  239. else {
  240. // raw pointer -> raw pointer
  241. newisa.cls = newCls;
  242. }
  243. } while (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits));
  244. if (transcribeToSideTable) {
  245. // Copy oldisa's retain count et al to side table.
  246. // oldisa.has_assoc: nothing to do
  247. // oldisa.has_cxx_dtor: nothing to do
  248. sidetable_moveExtraRC_nolock(oldisa.extra_rc,
  249. oldisa.deallocating,
  250. oldisa.weakly_referenced);
  251. }
  252. if (sideTableLocked) sidetable_unlock();
  253. if (oldisa.nonpointer) {
  254. #if SUPPORT_INDEXED_ISA
  255. return classForIndex(oldisa.indexcls);
  256. #else
  257. return (Class)((uintptr_t)oldisa.shiftcls << 3);
  258. #endif
  259. }
  260. else {
  261. return oldisa.cls;
  262. }
  263. }
  264. inline bool
  265. objc_object::hasAssociatedObjects()
  266. {
  267. if (isTaggedPointer()) return true;
  268. if (isa.nonpointer) return isa.has_assoc;
  269. return true;
  270. }
  271. inline void
  272. objc_object::setHasAssociatedObjects()
  273. {
  274. if (isTaggedPointer()) return;
  275. retry:
  276. isa_t oldisa = LoadExclusive(&isa.bits);
  277. isa_t newisa = oldisa;
  278. if (!newisa.nonpointer || newisa.has_assoc) {
  279. ClearExclusive(&isa.bits);
  280. return;
  281. }
  282. newisa.has_assoc = true;
  283. if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
  284. }
  285. inline bool
  286. objc_object::isWeaklyReferenced()
  287. {
  288. assert(!isTaggedPointer());
  289. if (isa.nonpointer) return isa.weakly_referenced;
  290. else return sidetable_isWeaklyReferenced();
  291. }
  292. inline void
  293. objc_object::setWeaklyReferenced_nolock()
  294. {
  295. retry:
  296. isa_t oldisa = LoadExclusive(&isa.bits);
  297. isa_t newisa = oldisa;
  298. if (slowpath(!newisa.nonpointer)) {
  299. ClearExclusive(&isa.bits);
  300. sidetable_setWeaklyReferenced_nolock();
  301. return;
  302. }
  303. if (newisa.weakly_referenced) {
  304. ClearExclusive(&isa.bits);
  305. return;
  306. }
  307. newisa.weakly_referenced = true;
  308. if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
  309. }
  310. inline bool
  311. objc_object::hasCxxDtor()
  312. {
  313. assert(!isTaggedPointer());
  314. if (isa.nonpointer) return isa.has_cxx_dtor;
  315. else return isa.cls->hasCxxDtor();
  316. }
  317. inline bool
  318. objc_object::rootIsDeallocating()
  319. {
  320. if (isTaggedPointer()) return false;
  321. if (isa.nonpointer) return isa.deallocating;
  322. return sidetable_isDeallocating();
  323. }
  324. inline void
  325. objc_object::clearDeallocating()
  326. {
  327. if (slowpath(!isa.nonpointer)) {
  328. // Slow path for raw pointer isa.
  329. sidetable_clearDeallocating();
  330. }
  331. else if (slowpath(isa.weakly_referenced || isa.has_sidetable_rc)) {
  332. // Slow path for non-pointer isa with weak refs and/or side table data.
  333. clearDeallocating_slow();
  334. }
  335. assert(!sidetable_present());
  336. }
  337. inline void
  338. objc_object::rootDealloc()
  339. {
  340. if (isTaggedPointer()) return; // fixme necessary?
  341. if (fastpath(isa.nonpointer &&
  342. !isa.weakly_referenced &&
  343. !isa.has_assoc &&
  344. !isa.has_cxx_dtor &&
  345. !isa.has_sidetable_rc))
  346. {
  347. assert(!sidetable_present());
  348. free(this);
  349. }
  350. else {
  351. object_dispose((id)this);
  352. }
  353. }
  354. // Equivalent to calling [this retain], with shortcuts if there is no override
  355. inline id
  356. objc_object::retain()
  357. {
  358. assert(!isTaggedPointer());
  359. if (fastpath(!ISA()->hasCustomRR())) {
  360. return rootRetain();
  361. }
  362. return ((id(*)(objc_object *, SEL))objc_msgSend)(this, SEL_retain);
  363. }
  364. // Base retain implementation, ignoring overrides.
  365. // This does not check isa.fast_rr; if there is an RR override then
  366. // it was already called and it chose to call [super retain].
  367. //
  368. // tryRetain=true is the -_tryRetain path.
  369. // handleOverflow=false is the frameless fast path.
  370. // handleOverflow=true is the framed slow path including overflow to side table
  371. // The code is structured this way to prevent duplication.
  372. ALWAYS_INLINE id
  373. objc_object::rootRetain()
  374. {
  375. return rootRetain(false, false);
  376. }
  377. ALWAYS_INLINE bool
  378. objc_object::rootTryRetain()
  379. {
  380. return rootRetain(true, false) ? true : false;
  381. }
  382. ALWAYS_INLINE id
  383. objc_object::rootRetain(bool tryRetain, bool handleOverflow)
  384. {
  385. if (isTaggedPointer()) return (id)this;
  386. bool sideTableLocked = false;
  387. bool transcribeToSideTable = false;
  388. isa_t oldisa;
  389. isa_t newisa;
  390. do {
  391. transcribeToSideTable = false;
  392. oldisa = LoadExclusive(&isa.bits);
  393. newisa = oldisa;
  394. if (slowpath(!newisa.nonpointer)) {
  395. ClearExclusive(&isa.bits);
  396. if (!tryRetain && sideTableLocked) sidetable_unlock();
  397. if (tryRetain) return sidetable_tryRetain() ? (id)this : nil;
  398. else return sidetable_retain();
  399. }
  400. // don't check newisa.fast_rr; we already called any RR overrides
  401. if (slowpath(tryRetain && newisa.deallocating)) {
  402. ClearExclusive(&isa.bits);
  403. if (!tryRetain && sideTableLocked) sidetable_unlock();
  404. return nil;
  405. }
  406. uintptr_t carry;
  407. newisa.bits = addc(newisa.bits, RC_ONE, 0, &carry); // extra_rc++
  408. if (slowpath(carry)) {
  409. // newisa.extra_rc++ overflowed
  410. if (!handleOverflow) {
  411. ClearExclusive(&isa.bits);
  412. return rootRetain_overflow(tryRetain);
  413. }
  414. // Leave half of the retain counts inline and
  415. // prepare to copy the other half to the side table.
  416. if (!tryRetain && !sideTableLocked) sidetable_lock();
  417. sideTableLocked = true;
  418. transcribeToSideTable = true;
  419. newisa.extra_rc = RC_HALF;
  420. newisa.has_sidetable_rc = true;
  421. }
  422. } while (slowpath(!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)));
  423. if (slowpath(transcribeToSideTable)) {
  424. // Copy the other half of the retain counts to the side table.
  425. sidetable_addExtraRC_nolock(RC_HALF);
  426. }
  427. if (slowpath(!tryRetain && sideTableLocked)) sidetable_unlock();
  428. return (id)this;
  429. }
  430. // Equivalent to calling [this release], with shortcuts if there is no override
  431. inline void
  432. objc_object::release()
  433. {
  434. assert(!isTaggedPointer());
  435. if (fastpath(!ISA()->hasCustomRR())) {
  436. rootRelease();
  437. return;
  438. }
  439. ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_release);
  440. }
  441. // Base release implementation, ignoring overrides.
  442. // Does not call -dealloc.
  443. // Returns true if the object should now be deallocated.
  444. // This does not check isa.fast_rr; if there is an RR override then
  445. // it was already called and it chose to call [super release].
  446. //
  447. // handleUnderflow=false is the frameless fast path.
  448. // handleUnderflow=true is the framed slow path including side table borrow
  449. // The code is structured this way to prevent duplication.
  450. ALWAYS_INLINE bool
  451. objc_object::rootRelease()
  452. {
  453. return rootRelease(true, false);
  454. }
  455. ALWAYS_INLINE bool
  456. objc_object::rootReleaseShouldDealloc()
  457. {
  458. return rootRelease(false, false);
  459. }
  460. ALWAYS_INLINE bool
  461. objc_object::rootRelease(bool performDealloc, bool handleUnderflow)
  462. {
  463. if (isTaggedPointer()) return false;
  464. bool sideTableLocked = false;
  465. isa_t oldisa;
  466. isa_t newisa;
  467. retry:
  468. do {
  469. oldisa = LoadExclusive(&isa.bits);
  470. newisa = oldisa;
  471. if (slowpath(!newisa.nonpointer)) {
  472. ClearExclusive(&isa.bits);
  473. if (sideTableLocked) sidetable_unlock();
  474. return sidetable_release(performDealloc);
  475. }
  476. // don't check newisa.fast_rr; we already called any RR overrides
  477. uintptr_t carry;
  478. newisa.bits = subc(newisa.bits, RC_ONE, 0, &carry); // extra_rc--
  479. if (slowpath(carry)) {
  480. // don't ClearExclusive()
  481. goto underflow;
  482. }
  483. } while (slowpath(!StoreReleaseExclusive(&isa.bits,
  484. oldisa.bits, newisa.bits)));
  485. if (slowpath(sideTableLocked)) sidetable_unlock();
  486. return false;
  487. underflow:
  488. // newisa.extra_rc-- underflowed: borrow from side table or deallocate
  489. // abandon newisa to undo the decrement
  490. newisa = oldisa;
  491. if (slowpath(newisa.has_sidetable_rc)) {
  492. if (!handleUnderflow) {
  493. ClearExclusive(&isa.bits);
  494. return rootRelease_underflow(performDealloc);
  495. }
  496. // Transfer retain count from side table to inline storage.
  497. if (!sideTableLocked) {
  498. ClearExclusive(&isa.bits);
  499. sidetable_lock();
  500. sideTableLocked = true;
  501. // Need to start over to avoid a race against
  502. // the nonpointer -> raw pointer transition.
  503. goto retry;
  504. }
  505. // Try to remove some retain counts from the side table.
  506. size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF);
  507. // To avoid races, has_sidetable_rc must remain set
  508. // even if the side table count is now zero.
  509. if (borrowed > 0) {
  510. // Side table retain count decreased.
  511. // Try to add them to the inline count.
  512. newisa.extra_rc = borrowed - 1; // redo the original decrement too
  513. bool stored = StoreReleaseExclusive(&isa.bits,
  514. oldisa.bits, newisa.bits);
  515. if (!stored) {
  516. // Inline update failed.
  517. // Try it again right now. This prevents livelock on LL/SC
  518. // architectures where the side table access itself may have
  519. // dropped the reservation.
  520. isa_t oldisa2 = LoadExclusive(&isa.bits);
  521. isa_t newisa2 = oldisa2;
  522. if (newisa2.nonpointer) {
  523. uintptr_t overflow;
  524. newisa2.bits =
  525. addc(newisa2.bits, RC_ONE * (borrowed-1), 0, &overflow);
  526. if (!overflow) {
  527. stored = StoreReleaseExclusive(&isa.bits, oldisa2.bits,
  528. newisa2.bits);
  529. }
  530. }
  531. }
  532. if (!stored) {
  533. // Inline update failed.
  534. // Put the retains back in the side table.
  535. sidetable_addExtraRC_nolock(borrowed);
  536. goto retry;
  537. }
  538. // Decrement successful after borrowing from side table.
  539. // This decrement cannot be the deallocating decrement - the side
  540. // table lock and has_sidetable_rc bit ensure that if everyone
  541. // else tried to -release while we worked, the last one would block.
  542. sidetable_unlock();
  543. return false;
  544. }
  545. else {
  546. // Side table is empty after all. Fall-through to the dealloc path.
  547. }
  548. }
  549. // Really deallocate.
  550. if (slowpath(newisa.deallocating)) {
  551. ClearExclusive(&isa.bits);
  552. if (sideTableLocked) sidetable_unlock();
  553. return overrelease_error();
  554. // does not actually return
  555. }
  556. newisa.deallocating = true;
  557. if (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits)) goto retry;
  558. if (slowpath(sideTableLocked)) sidetable_unlock();
  559. __sync_synchronize();
  560. if (performDealloc) {
  561. ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);
  562. }
  563. return true;
  564. }
  565. // Equivalent to [this autorelease], with shortcuts if there is no override
  566. inline id
  567. objc_object::autorelease()
  568. {
  569. if (isTaggedPointer()) return (id)this;
  570. if (fastpath(!ISA()->hasCustomRR())) return rootAutorelease();
  571. return ((id(*)(objc_object *, SEL))objc_msgSend)(this, SEL_autorelease);
  572. }
  573. // Base autorelease implementation, ignoring overrides.
  574. inline id
  575. objc_object::rootAutorelease()
  576. {
  577. if (isTaggedPointer()) return (id)this;
  578. if (prepareOptimizedReturn(ReturnAtPlus1)) return (id)this;
  579. return rootAutorelease2();
  580. }
  581. inline uintptr_t
  582. objc_object::rootRetainCount()
  583. {
  584. if (isTaggedPointer()) return (uintptr_t)this;
  585. sidetable_lock();
  586. isa_t bits = LoadExclusive(&isa.bits);
  587. ClearExclusive(&isa.bits);
  588. if (bits.nonpointer) {
  589. uintptr_t rc = 1 + bits.extra_rc;
  590. if (bits.has_sidetable_rc) {
  591. rc += sidetable_getExtraRC_nolock();
  592. }
  593. sidetable_unlock();
  594. return rc;
  595. }
  596. sidetable_unlock();
  597. return sidetable_retainCount();
  598. }
  599. // SUPPORT_NONPOINTER_ISA
  600. #else
  601. // not SUPPORT_NONPOINTER_ISA
  602. inline Class
  603. objc_object::ISA()
  604. {
  605. assert(!isTaggedPointer());
  606. return isa.cls;
  607. }
  608. inline bool
  609. objc_object::hasNonpointerIsa()
  610. {
  611. return false;
  612. }
  613. inline void
  614. objc_object::initIsa(Class cls)
  615. {
  616. assert(!isTaggedPointer());
  617. isa = (uintptr_t)cls;
  618. }
  619. inline void
  620. objc_object::initClassIsa(Class cls)
  621. {
  622. initIsa(cls);
  623. }
  624. inline void
  625. objc_object::initProtocolIsa(Class cls)
  626. {
  627. initIsa(cls);
  628. }
  629. inline void
  630. objc_object::initInstanceIsa(Class cls, bool)
  631. {
  632. initIsa(cls);
  633. }
  634. inline void
  635. objc_object::initIsa(Class cls, bool, bool)
  636. {
  637. initIsa(cls);
  638. }
  639. inline Class
  640. objc_object::changeIsa(Class cls)
  641. {
  642. // This is almost always rue but there are
  643. // enough edge cases that we can't assert it.
  644. // assert(cls->isFuture() ||
  645. // cls->isInitializing() || cls->isInitialized());
  646. assert(!isTaggedPointer());
  647. isa_t oldisa, newisa;
  648. newisa.cls = cls;
  649. do {
  650. oldisa = LoadExclusive(&isa.bits);
  651. } while (!StoreExclusive(&isa.bits, oldisa.bits, newisa.bits));
  652. if (oldisa.cls && oldisa.cls->instancesHaveAssociatedObjects()) {
  653. cls->setInstancesHaveAssociatedObjects();
  654. }
  655. return oldisa.cls;
  656. }
  657. inline bool
  658. objc_object::hasAssociatedObjects()
  659. {
  660. return getIsa()->instancesHaveAssociatedObjects();
  661. }
  662. inline void
  663. objc_object::setHasAssociatedObjects()
  664. {
  665. getIsa()->setInstancesHaveAssociatedObjects();
  666. }
  667. inline bool
  668. objc_object::isWeaklyReferenced()
  669. {
  670. assert(!isTaggedPointer());
  671. return sidetable_isWeaklyReferenced();
  672. }
  673. inline void
  674. objc_object::setWeaklyReferenced_nolock()
  675. {
  676. assert(!isTaggedPointer());
  677. sidetable_setWeaklyReferenced_nolock();
  678. }
  679. inline bool
  680. objc_object::hasCxxDtor()
  681. {
  682. assert(!isTaggedPointer());
  683. return isa.cls->hasCxxDtor();
  684. }
  685. inline bool
  686. objc_object::rootIsDeallocating()
  687. {
  688. if (isTaggedPointer()) return false;
  689. return sidetable_isDeallocating();
  690. }
  691. inline void
  692. objc_object::clearDeallocating()
  693. {
  694. sidetable_clearDeallocating();
  695. }
  696. inline void
  697. objc_object::rootDealloc()
  698. {
  699. if (isTaggedPointer()) return;
  700. object_dispose((id)this);
  701. }
  702. // Equivalent to calling [this retain], with shortcuts if there is no override
  703. inline id
  704. objc_object::retain()
  705. {
  706. assert(!isTaggedPointer());
  707. if (fastpath(!ISA()->hasCustomRR())) {
  708. return sidetable_retain();
  709. }
  710. return ((id(*)(objc_object *, SEL))objc_msgSend)(this, SEL_retain);
  711. }
  712. // Base retain implementation, ignoring overrides.
  713. // This does not check isa.fast_rr; if there is an RR override then
  714. // it was already called and it chose to call [super retain].
  715. inline id
  716. objc_object::rootRetain()
  717. {
  718. if (isTaggedPointer()) return (id)this;
  719. return sidetable_retain();
  720. }
  721. // Equivalent to calling [this release], with shortcuts if there is no override
  722. inline void
  723. objc_object::release()
  724. {
  725. assert(!isTaggedPointer());
  726. if (fastpath(!ISA()->hasCustomRR())) {
  727. sidetable_release();
  728. return;
  729. }
  730. ((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_release);
  731. }
  732. // Base release implementation, ignoring overrides.
  733. // Does not call -dealloc.
  734. // Returns true if the object should now be deallocated.
  735. // This does not check isa.fast_rr; if there is an RR override then
  736. // it was already called and it chose to call [super release].
  737. inline bool
  738. objc_object::rootRelease()
  739. {
  740. if (isTaggedPointer()) return false;
  741. return sidetable_release(true);
  742. }
  743. inline bool
  744. objc_object::rootReleaseShouldDealloc()
  745. {
  746. if (isTaggedPointer()) return false;
  747. return sidetable_release(false);
  748. }
  749. // Equivalent to [this autorelease], with shortcuts if there is no override
  750. inline id
  751. objc_object::autorelease()
  752. {
  753. if (isTaggedPointer()) return (id)this;
  754. if (fastpath(!ISA()->hasCustomRR())) return rootAutorelease();
  755. return ((id(*)(objc_object *, SEL))objc_msgSend)(this, SEL_autorelease);
  756. }
  757. // Base autorelease implementation, ignoring overrides.
  758. inline id
  759. objc_object::rootAutorelease()
  760. {
  761. if (isTaggedPointer()) return (id)this;
  762. if (prepareOptimizedReturn(ReturnAtPlus1)) return (id)this;
  763. return rootAutorelease2();
  764. }
  765. // Base tryRetain implementation, ignoring overrides.
  766. // This does not check isa.fast_rr; if there is an RR override then
  767. // it was already called and it chose to call [super _tryRetain].
  768. inline bool
  769. objc_object::rootTryRetain()
  770. {
  771. if (isTaggedPointer()) return true;
  772. return sidetable_tryRetain();
  773. }
  774. inline uintptr_t
  775. objc_object::rootRetainCount()
  776. {
  777. if (isTaggedPointer()) return (uintptr_t)this;
  778. return sidetable_retainCount();
  779. }
  780. // not SUPPORT_NONPOINTER_ISA
  781. #endif
  782. #if SUPPORT_RETURN_AUTORELEASE
  783. /***********************************************************************
  784. Fast handling of return through Cocoa's +0 autoreleasing convention.
  785. The caller and callee cooperate to keep the returned object
  786. out of the autorelease pool and eliminate redundant retain/release pairs.
  787. An optimized callee looks at the caller's instructions following the
  788. return. If the caller's instructions are also optimized then the callee
  789. skips all retain count operations: no autorelease, no retain/autorelease.
  790. Instead it saves the result's current retain count (+0 or +1) in
  791. thread-local storage. If the caller does not look optimized then
  792. the callee performs autorelease or retain/autorelease as usual.
  793. An optimized caller looks at the thread-local storage. If the result
  794. is set then it performs any retain or release needed to change the
  795. result from the retain count left by the callee to the retain count
  796. desired by the caller. Otherwise the caller assumes the result is
  797. currently at +0 from an unoptimized callee and performs any retain
  798. needed for that case.
  799. There are two optimized callees:
  800. objc_autoreleaseReturnValue
  801. result is currently +1. The unoptimized path autoreleases it.
  802. objc_retainAutoreleaseReturnValue
  803. result is currently +0. The unoptimized path retains and autoreleases it.
  804. There are two optimized callers:
  805. objc_retainAutoreleasedReturnValue
  806. caller wants the value at +1. The unoptimized path retains it.
  807. objc_unsafeClaimAutoreleasedReturnValue
  808. caller wants the value at +0 unsafely. The unoptimized path does nothing.
  809. Example:
  810. Callee:
  811. // compute ret at +1
  812. return objc_autoreleaseReturnValue(ret);
  813. Caller:
  814. ret = callee();
  815. ret = objc_retainAutoreleasedReturnValue(ret);
  816. // use ret at +1 here
  817. Callee sees the optimized caller, sets TLS, and leaves the result at +1.
  818. Caller sees the TLS, clears it, and accepts the result at +1 as-is.
  819. The callee's recognition of the optimized caller is architecture-dependent.
  820. x86_64: Callee looks for `mov rax, rdi` followed by a call or
  821. jump instruction to objc_retainAutoreleasedReturnValue or
  822. objc_unsafeClaimAutoreleasedReturnValue.
  823. i386: Callee looks for a magic nop `movl %ebp, %ebp` (frame pointer register)
  824. armv7: Callee looks for a magic nop `mov r7, r7` (frame pointer register).
  825. arm64: Callee looks for a magic nop `mov x29, x29` (frame pointer register).
  826. Tagged pointer objects do participate in the optimized return scheme,
  827. because it saves message sends. They are not entered in the autorelease
  828. pool in the unoptimized case.
  829. **********************************************************************/
  830. # if __x86_64__
  831. static ALWAYS_INLINE bool
  832. callerAcceptsOptimizedReturn(const void * const ra0)
  833. {
  834. const uint8_t *ra1 = (const uint8_t *)ra0;
  835. const unaligned_uint16_t *ra2;
  836. const unaligned_uint32_t *ra4 = (const unaligned_uint32_t *)ra1;
  837. const void **sym;
  838. #define PREFER_GOTPCREL 0
  839. #if PREFER_GOTPCREL
  840. // 48 89 c7 movq %rax,%rdi
  841. // ff 15 callq *symbol@GOTPCREL(%rip)
  842. if (*ra4 != 0xffc78948) {
  843. return false;
  844. }
  845. if (ra1[4] != 0x15) {
  846. return false;
  847. }
  848. ra1 += 3;
  849. #else
  850. // 48 89 c7 movq %rax,%rdi
  851. // e8 callq symbol
  852. if (*ra4 != 0xe8c78948) {
  853. return false;
  854. }
  855. ra1 += (long)*(const unaligned_int32_t *)(ra1 + 4) + 8l;
  856. ra2 = (const unaligned_uint16_t *)ra1;
  857. // ff 25 jmpq *symbol@DYLDMAGIC(%rip)
  858. if (*ra2 != 0x25ff) {
  859. return false;
  860. }
  861. #endif
  862. ra1 += 6l + (long)*(const unaligned_int32_t *)(ra1 + 2);
  863. sym = (const void **)ra1;
  864. if (*sym != objc_retainAutoreleasedReturnValue &&
  865. *sym != objc_unsafeClaimAutoreleasedReturnValue)
  866. {
  867. return false;
  868. }
  869. return true;
  870. }
  871. // __x86_64__
  872. # elif __arm__
  873. static ALWAYS_INLINE bool
  874. callerAcceptsOptimizedReturn(const void *ra)
  875. {
  876. // if the low bit is set, we're returning to thumb mode
  877. if ((uintptr_t)ra & 1) {
  878. // 3f 46 mov r7, r7
  879. // we mask off the low bit via subtraction
  880. // 16-bit instructions are well-aligned
  881. if (*(uint16_t *)((uint8_t *)ra - 1) == 0x463f) {
  882. return true;
  883. }
  884. } else {
  885. // 07 70 a0 e1 mov r7, r7
  886. // 32-bit instructions may be only 16-bit aligned
  887. if (*(unaligned_uint32_t *)ra == 0xe1a07007) {
  888. return true;
  889. }
  890. }
  891. return false;
  892. }
  893. // __arm__
  894. # elif __arm64__
  895. static ALWAYS_INLINE bool
  896. callerAcceptsOptimizedReturn(const void *ra)
  897. {
  898. // fd 03 1d aa mov fp, fp
  899. // arm64 instructions are well-aligned
  900. if (*(uint32_t *)ra == 0xaa1d03fd) {
  901. return true;
  902. }
  903. return false;
  904. }
  905. // __arm64__
  906. # elif __i386__
  907. static ALWAYS_INLINE bool
  908. callerAcceptsOptimizedReturn(const void *ra)
  909. {
  910. // 89 ed movl %ebp, %ebp
  911. if (*(unaligned_uint16_t *)ra == 0xed89) {
  912. return true;
  913. }
  914. return false;
  915. }
  916. // __i386__
  917. # else
  918. #warning unknown architecture
  919. static ALWAYS_INLINE bool
  920. callerAcceptsOptimizedReturn(const void *ra)
  921. {
  922. return false;
  923. }
  924. // unknown architecture
  925. # endif
  926. static ALWAYS_INLINE ReturnDisposition
  927. getReturnDisposition()
  928. {
  929. return (ReturnDisposition)(uintptr_t)tls_get_direct(RETURN_DISPOSITION_KEY);
  930. }
  931. static ALWAYS_INLINE void
  932. setReturnDisposition(ReturnDisposition disposition)
  933. {
  934. tls_set_direct(RETURN_DISPOSITION_KEY, (void*)(uintptr_t)disposition);
  935. }
  936. // Try to prepare for optimized return with the given disposition (+0 or +1).
  937. // Returns true if the optimized path is successful.
  938. // Otherwise the return value must be retained and/or autoreleased as usual.
  939. static ALWAYS_INLINE bool
  940. prepareOptimizedReturn(ReturnDisposition disposition)
  941. {
  942. assert(getReturnDisposition() == ReturnAtPlus0);
  943. if (callerAcceptsOptimizedReturn(__builtin_return_address(0))) {
  944. if (disposition) setReturnDisposition(disposition);
  945. return true;
  946. }
  947. return false;
  948. }
  949. // Try to accept an optimized return.
  950. // Returns the disposition of the returned object (+0 or +1).
  951. // An un-optimized return is +0.
  952. static ALWAYS_INLINE ReturnDisposition
  953. acceptOptimizedReturn()
  954. {
  955. ReturnDisposition disposition = getReturnDisposition();
  956. setReturnDisposition(ReturnAtPlus0); // reset to the unoptimized state
  957. return disposition;
  958. }
  959. // SUPPORT_RETURN_AUTORELEASE
  960. #else
  961. // not SUPPORT_RETURN_AUTORELEASE
  962. static ALWAYS_INLINE bool
  963. prepareOptimizedReturn(ReturnDisposition disposition __unused)
  964. {
  965. return false;
  966. }
  967. static ALWAYS_INLINE ReturnDisposition
  968. acceptOptimizedReturn()
  969. {
  970. return ReturnAtPlus0;
  971. }
  972. // not SUPPORT_RETURN_AUTORELEASE
  973. #endif
  974. // _OBJC_OBJECT_H_
  975. #endif